Perform calculations on dataframe column based on index value

Question: I have to monthly normalize values of one dataframe column Allocation.
data=
                     Allocation  Temperature  Precipitation  Radiation
Date_From
2018-11-01 00:00:00    0.001905         9.55            0.0        0.0
2018-11-01 00:15:00    0.001794         9.55            0.0        0.0
2018-11-01 00:30:00    0.001700         9.55            0.0        0.0
2018-11-01 00:45:00    0.001607         9.55            0.0        0.0

This means, if we have 2018-11, divide Allocation by 11.116, while in 2018-12, divide Allocation by 2473.65, and so on... (These values come from a list Volume, where Volume[0] corresponds to 2018-11 untill Volume[7] corresponds to 2019-06).
Date_From is a index and a timestamp.
data_normalized=
                     Allocation  Temperature  Precipitation  Radiation
Date_From
2018-11-01 00:00:00    0.000171         9.55            0.0        0.0
2018-11-01 00:15:00    0.000097         9.55            0.0        0.0
...

My approach was the use of itertuples:
for row in data.itertuples(index=True,name='index'):
    if row.index =='2018-11':
        data['Allocation']/Volume[0]

Here, the if statement is never true...
Another approach was
if ((row.index >='2018-11-01 00:00:00') & (row.index<='2018-11-31 23:45:00')):

However, here I get the error TypeError: '>=' not supported between instances of 'builtin_function_or_method' and 'str'
Can I solve my problem with this approach or should I use a different approach? I am happy about any help
Cheers!
Comment: How can we guess whether the index is a string or a Timestamp? How can we guess what month correspond to what index in the Volume list? What cannot you understand in [mcve]?
Comment: Do you mind to share your expected output? It's not that clear to me what do you want to achieve. You might read about [mcve](/help/mcve) too.
Comment: In particular it's not clear what `Volume` is.
Comment: I edited the question. Volume is a list
Comment: do you know already that `Volume` as at least the same number of elements for the different months?
Comment: Yes, I consider 8 months and I have 8 elements in `Volume`
Answer: Maybe you can put your list Volume in a dataframe where the date (or index) is the first day of every month.
import pandas as pd
import numpy as np

N = 16
date = pd.date_range(start='2018-01-01', periods=N, freq="15d")
df = pd.DataFrame({"date":date, "Allocation":np.random.randn(N)})

# A dataframe where at every month associate a volume
df_vol = pd.DataFrame({"month":pd.date_range(start="2018-01-01", periods=8, freq="MS"),
                       "Volume": np.arange(8)+1})

# convert every date with the beginning of the month
df["month"] = df["date"].astype("datetime64[M]")

# merge
df1 = pd.merge(df,df_vol, on="month", how="left")

# divide allocation by Volume.
# Now it's vectorial as to every date we merged the right volume.
df1["norm"] = df1["Allocation"]/df1["Volume"]

Comment: @jonasa in your case you have to convert `Date_From` to `datatime` you can use `df["Date_From"]=df["Date_From"].astype("M8[us]")`


NASM/Yasm drops CALL after comment ending with backslash

Question: I am currently trying to built my own boot loader and noticed something peculiar.
When below code is assembled with NASM or Yasm without the marked NOP command the following CALL is missing from the binary. With the NOP included the CALL is correctly assembled but the op code 0x90 (NOP) is not present in the binary (later is understandable due to the nature of NOP).
to_hex_ascii:
        add al, '0'
        cmp al, 0x3a
        jl .end
;           add al, 0x07
            add al, 0x27
    .end:
        ret

print_word_hex:
        push bp
        mov bp, sp

        mov dx, [bp + 4]
        push dx
        mov al, dh
        push ax             ;\
        nop                 ; | <- NOP in question
        call print_lsb_hex  ; print_lsb_hex(ax);
        add sp, 2           ;/
        pop dx
        jmp print_lsb_hex.continue
print_lsb_hex:
        push bp
        mov bp, sp

        mov dl, [bp + 4]
    .continue:
        mov ah, 0x0e
        ; 0xf0
        mov al, dl
        and al, 0xf0
        shr al, 4
        call to_hex_ascii
        int 0x10  ; BIOS print call
        ; 0x0f
        mov al, dl
        and al, 0x0f
        call to_hex_ascii
        int 0x10  ; BIOS print call

        pop bp
        ret

Comment: The backslash character, '\', as the last thing on a line, is Nasm's "line continuation character". By putting it in a comment, the comment is continued to the next line - commenting out the `nop` or `call`. (it is not the nature of `nop` to just disappear like that!). Lose it, or put something after it.
Comment: Yes, so when you remove the `nop` line it is the `call` which becomes commented out.
Comment: Also; complying with C calling conventions (and passing parameters on the stack instead of in registers and diddling with "stack frame pointer") is the sign of an assembly language programmer that will never be able to fit everything they need into a "< 512 bytes" boot loader.. ;-)
Answer:
The backslash character, '\', as the last thing on a line, is Nasm's "line continuation character". By putting it in a comment, the comment is continued to the next line - commenting out the nop or call. (it is not the nature of nop to just disappear like that!). Lose it, or put something after it.

–  Frank Kotler

From the NASM manual, 3.1 Layout of a NASM Source Line:

NASM uses backslash (\) as the line continuation character; if a line ends with backslash, the next line is considered to be a part of the backslash-ended line.


Are child safety covers still required on modern outlets?

Question: I have a vague memory of either our electrician or home inspector telling us that the outlets in our recently renovated condo do not need those plastic child safety covers in order to be child-proofed because the circuit breakers are in some way better now than when I was a kid. Is there any truth to this?
Comment: I dont believe those silly plug-in child protection covers were ever required by code or law.  They are basically safety theater, so you might find them on receptacles near TSA checkpoints.  Any child with the industry to put something metallic in the hot pin would also have the industry to remove the cover.
Answer: Along with arc-fault breakers protecting some areas of the home, "tamper-resistant" outlets are also required. They don't allow insertion into just one slot--both slots must be pressed together as an actual plug would do.
I get the sense that you're asking about protecting little people. I'd either use plugs or install tamper-resistant outlets if I had toddlers, regardless of arc-fault protection.
Comment: +1. And tamper-resistant outlets have gotten better in recent years, as people had trouble inserting an actual plug into them before.
Comment: Actually, I'm not sure how much help AFCI is for the kid problem, though GFCI is definitely a huge improvement. But good tamper resistant outlets can slow the kids down a bit...
Comment: I hate the tamper resistant outlets , in Oregon all the outlets below 5'6" are now required to be tamper resistant even GFCI'S both inside and out.
Comment: Jiggleitalittleit'llgo.
Comment: @isherwood, lol .... that sounds like a great T-shirt slogan
Comment: yikes; it takes me forever to de-child-safety those things; remind me to stay away from oregon...


How to use styled component on a React application

Question: I have been trying to change the styling from bulma to Styled components on my react application but I am facing some issues while trying to implement it inside my function.
import React, {FC} from 'react';
import styled from 'styled-components';

const theme = styled.div`
text-align: center;
background-color: #535151;
font-style: bold;
`;

const H1 = styled.h1`
font-size: 60pt;
font-style: Verdana;
color: black;
`;

interface HeaderProps {
    title: string;
    subtitle: string;
}

const Header: FC<HeaderProps> = ({title, subtitle}) =>{
    return (
        <>
            <theme>

{title}

{subtitle}

            </theme>

        </>
    );
}

export default Header;

Answer: import React from 'react';
import styled from 'styled-components';

const Template = styled.a`
    background-color: red;
`;

export const Test = () => {
    return(
        <>
            <Template>Hello</Template>
        </>
    )
}

Try this.


Why is python giving me an UnboundLocalError when I run this program?

Question: Background
I am currently experimenting with computer learning, and I made a function where you enter "true" or "false" and the computer learns which boolean it is, after which the program prints the percent of correct guesses the computer made:
import math
import random
endgame = False
def oneround():
    Q1max = 1
    Q1min = -2
    guess = False
    answer = 0
    while guess == False:
        useranswer = input("True or False?")
        if useranswer == "True" or useranswer == "true":
            answer = True
            guess = True
        elif useranswer == "False" or useranswer == "false":
            answer = False
            guess = True

    corrects = 0
    incorrects = 0
    howmanytimes = int(input("how many times do you want the computer to guess? (If you want to end the game, type in letters instead of a number.) "))
    for x in range(0,howmanytimes):
        choice = random.randint(Q1min,Q1max)
        if choice >= 0:
            guess = True
        else:
            guess = False
        if guess == answer:
            corrects += 1
            if guess == True:
                Q1max += 1
            else:
                Q1min -= 1
        else:
            incorrects += 1
            if guess == False:
                Q1max += 1
            else:
                Q1min -= 1
    percent = (corrects/howmanytimes)*100
    print ("The computer learned to guess correctly",(str(math.floor(percent))+"%"),"of the time.")
while endgame == False:
    try:
        oneround()
    except ValueError:
        endgame = True

I then tried to improve my program by adding 2 global variables, percentavg and percentavgnum, that will average all the success percentages together at the end of the program:
import math
import random
endgame = False
global percentavg
global percentavgnum
percentavg = 0
percentavgnum = 0
def oneround():
    Q1max = 1
    Q1min = -2
    guess = False
    answer = 0
    while guess == False:
        useranswer = input("True or False?")
        if useranswer == "True" or useranswer == "true":
            answer = True
            guess = True
        elif useranswer == "False" or useranswer == "false":
            answer = False
            guess = True

    corrects = 0
    incorrects = 0
    howmanytimes = int(input("how many times do you want the computer to guess? (If you want to end the game, type in letters instead of a number.) "))
    for x in range(0,howmanytimes):
        choice = random.randint(Q1min,Q1max)
        if choice >= 0:
            guess = True
        else:
            guess = False
        if guess == answer:
            corrects += 1
            if guess == True:
                Q1max += 1
            else:
                Q1min -= 1
        else:
            incorrects += 1
            if guess == False:
                Q1max += 1
            else:
                Q1min -= 1
    percent = (corrects/howmanytimes)*100
    percentavg += percent
    percentavgnum += 1
    print ("The computer learned to guess correctly",(str(math.floor(percent))+"%"),"of the time.")
while endgame == False:
    try:
        oneround()
    except ValueError:
        endgame = True
print ("The computer guessed correctly",(str(math.floor(percentavg/percentavgnum))+"%"),"of the time")

Problem
But I keep getting this error whenever I run the program:
Traceback (most recent call last):
  File "main.py", line 49, in <module>
    oneround()
  File "main.py", line 44, in oneround
    percentavg += percent
UnboundLocalError: local variable 'percentavg' referenced before assignment

Does anyone know what I am doing wrong?
Comment: Instead of using a *global* variable, have your function return the calculated value(s); assign the return value(s) to the module level variables, pass the module level variables to the function.
Comment: @wwii Can you phrase that a bit more simply?
Comment: See my answer ...
Answer: Use global. Put it at the top of the function with the variable names after it. Like this: global percentavg, percentavgnum
NOTE: The names must be comma-separated.
Comment: This returns a syntax error for that line.
Comment: This is _somewhat_ correct, but doesn't explain _why_! `global` makes sure the referenced name is from the global scope (otherwise it can't be differentiated from a new name in the scope of the function). Put one per line
Comment: @ti7 Oh yeah, forgot about that. They can be all on one line if you separate them by commas.
Comment: So why was I getting an error? Please include that in your answer.
Comment: @jeffthechicken Done.
Comment: @Blue But WHY was I getting the error? I want to learn from this so I don't make the same mistake later.
Comment: @jeffthechicken Ah, I misunderstood you. Python doesn't like it when you don't put commas between the variable names. Not sure how I forgot to include that.
Comment: @Blue I understand that, but why does your solution fix the code, and what was wrong with my code before I added your global statement?
Comment: All of this is explained in the link i posted in my answer (https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value). When tou add `global my_variable` IN the function as @Blue said, it gives you access to the outer scope variable (declared outside the function), that's why it fixes the code.
Comment: @Rivers this is a simpler way to make it work, so I upvoted yours for helping with **why** I got an error, but selected this one for giving me the best answer.
Comment: @jeffthechicken I upvoted it. That was a good question, but generally we don't ask for upvotes. Best way to put it is that this is a forum, not a social media network.
Comment: @Blue my bad, sorry
Answer: This problem is related to how Python determines the scope of a variable.
You can notice that the error occurs when you try to increment percentavg via percentavg += percent.
So you are trying to assign a new value to percentavg.
The thing is that in Python, when you assign a value to a variable, the variable becomes a local variable. But percentavg has not been defined in this scope (the scope of oneround(), and so you get this UnboundLocalError.
All of this is explained in details here:
https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value
You have at least 3 options:

Define the variables in oneround():

def oneround():
    percentavg = 0
    percentavgnum = 0
    # ...

Pass your variables as arguments of  oneround():

percentavg = 0
percentavgnum = 0
oneround(percentavg,percentavgnum)

And you don't need to declare your variables as global at all.

Access your outer scope variables uing global inside your function:

(That's what @Blue proposed)
def oneround():
    global percentavg
    global percentavgnum

The keywork global is used to access the outer scope variables (the variables declared outside the scope of the function).
If you choose option 1, you can delete these lines at the begining of your code:
global percentavg
global percentavgnum
percentavg = 0
percentavgnum = 0

If you choose option 2, you can delete these lines at the begining of your code:
global percentavg
global percentavgnum

but you will have to keep these lines:
percentavg = 0
percentavgnum = 0

These lines could be at the beginin of your code, but it coul be in the while loop, or in the try statement, before calling oneround().
But, based on your piece of code, the option 1 is the best coding practice.
Comment: So I make it global by declaring it **IN** the function?
Comment: No, you don't have to make them global at all. I will edit my answer to explain this.
Comment: I'm confused, when do I need to use this function?
Answer: Instead of using a global variable and relying on a side affect of the function, write your function to accept the module level variables that need to be updated as arguments and to return the updated values.
>>> def f(one,two,three):
...     return one*1,two*2,three*3
...
>>> a,b,c = 'xyz'
>>> a,b,c = f(a,b,c)
>>> a
'x'
>>> b
'yy'
>>> c
'zzz'
>>>


Dead Space 3 won't detect Mass Effect 3 save

Question: So me and my friend want to replay DE3. In the game if you have a ME3 save on your pc it will unlock the N7 suit. Since i don't have ME3 i asked my buddy to send me one of his characters save folder. For some reason it wont detect the save. Any idea whats the problem? Do i have to do something else?
Comment: You want a reward for playing a game that you haven't actually played?
Comment: Obvious explaination is that the save file isn't located in the location that DS is looking for it.
Answer: Game save may be tied to one Origin account or Mass Effect 3 has to be in your Origin library - in that case you have no other option than purchase the game.


Normally distributed and uncorrelated and dependent

Question: I read that :
https://en.wikipedia.org/wiki/Normally_distributed_and_uncorrelated_does_not_imply_independent
And I can't understand how this is not in contradiction with that :
Jointly Gaussian uncorrelated random variables are independent
can anyone explain me why those are not contradictory ? What assumptions in the theorem are not respected in the examples of the first link?

For me, if one look at the joint distribution, it is normal and it can be splited into two normals. Why isn't it the case in the example given on wikipedia ?

The question has been asked plenty of times on mathstack. I am not
  searching for a counter example, neither for the proof. I am searching
  for the understanding between the two theorems.
Comment: At the first link the joint distribution is the product of two different distributions, where one is **not normally** distributed. There is no direct link to the joint distribution of two normal distributed random variables.
Answer: The first link concerns arbitrary joint distributions for which each variable's marginal distribution is univariate Gaussian. The second link concerns one such joint distribution, a multivariate generalization of the univariate case.
Comment: @MarineGalantin Note the second link's top answer unpacks the term "joint normally distributed" for two variables as meaning they have a *bivariate* (and hence multivariate) Gaussian distribution.
Comment: can you be more explicite please ? I still don't get it...
Comment: @MarineGalantin To take the first link's first example, $X,\,Y$ have joint probability density $\frac{1}{\sqrt{8\pi}}\exp-\frac{x^2}{2}[\delta(x-y)+\delta(x+y)]$, [which is clearly not multivariate Gaussian](https://en.wikipedia.org/wiki/Multivariate_normal_distribution#Density_function). (Before you ask, [this](https://en.wikipedia.org/wiki/Dirac_delta_function) is what $\delta$ is.)
Comment: Also, what is the difference between multivariate gaussian and joint gaussian ?
Comment: @MarineGalantin I never used the phrase "joint Gaussian". Whatever $X,\,Y$ are, they have *a joint distribution*. Given that joint distribution, you can obtain the respective *marginal distributions* of each variable. The first link is about what happens when, even though the same marginals are obtained as in the special case where the joint distribution is a mutlivariate Gaussian, *the joint distribution is not in fact a mutlivariate Gaussian*.
Comment: I still don't get it, the $X$ and $Y$ you mentionned comment nr $2$ are normal, uncorrelated, but dependant ? And that's not in contradiction with link nr $2$? sorry I can't understand it yet.
Comment: @MarineGalantin Link 2's "terms and conditions" include one condition the example in the first link violates, that the *joint distribution* takes a very specific form.
Comment: where? I don't see any "terms and conditions"
Answer: There's no contradiction because the random variables $X, Y$ in the first wikipedia link are not jointly normally distributed since $P(X+Y=0)=1/2$.
Comment: I don't get it. What s different from having two random normal variable, and them beeing jointly normal?


Proving that $\sup(S^2)=(\sup(S))^2$ for $S$ a subset of the reals with only nonnegative elements

Question: Let $S^2=\{x^2:x\in S,x\geq 0\}$. Prove that $\sup(S^2)=(\sup(S))^2$.
Attempt: let $s=\sup(S)$. Then for any $x\in S$ we have $s\geq x$. Hence $s^2\geq x^2$. Therefore $s^2$ is an upper bound for $S^2$. Hence $(\sup(S))^2\leq \sup(S^2)$.
I want to prove the reverse inequality but cannot seem to get anywhere with this - any hints would be great!
Answer: let $s = \text{sup}(S)$, as you have shown that $s^2$ is an upper bound for $S^2$,
we only need to show it is the smallest.
As the set contains only positive elements we can say $s \ge 0$ and $\sqrt{s}$ exists
Let $x$ be an upper bound then $\alpha^2 \le x \ \forall \alpha \in S $ and
$\alpha \le \sqrt{x}$ thus by definition of supremum we get $s \le \sqrt{x}$
or $s^2 \le x$ which proves the claim
Answer: I think this question has a mistake in it. Let me give a counterexample for which $\sup(S^2) > (\sup(S))^2$, which would be the following. Let $S = \{\frac{1}{2}\}$. Since $\frac{1}{2}$ is greater than or equal to zero, then $S^2 = \{\frac{1}{2}\}$ as well. Both of these sets contain just one element, so their supremums are equal and equate simply to $\frac{1}{2}$. Therefore we obtain
$$\frac{1}{2} = \sup(S^2) > (\sup(S))^2 = \frac{1}{4}$$
which is a not consistent with the claim made.
Comment: probably he meant $S^2$ as the set with elements squared, which is shown in his working
Comment: @Alidixon244 Ah, ok :) Thanks for the correction. Well, we can think along these lines. Since $sup(S^2)$ exists, then the set $S^2$ is not empty, which means that we have some non-negative elements in $S$. Thus, $sup(S)$ must necessarily be non-negative. By definition $sup(S^2)$ is also non-negative. Now let's assume that $(sup(S))^2 > sup(S^2)$. Both sides are non-negative, so I can take the square root, and we obtain $sup(S) > \sqrt{sup(S^2)} \geq 0$. Hence, there must exist some non-negative $x \in S$, such that $x > \sqrt{sup(S^2)}$. Therefore $x^2 > sup(S^2)$, which is a contradiction.
Comment: Hi yeah I meant the elements squared, just edited the question:)
Answer: Correction: you actually proved the reverse proposition, $(\sup(S))^2 \geq \sup(S^2).$
Hint: to prove $(\sup(S))^2\leq \sup(S^2),$ you could try rewriting it as $\sup(S)\leq \sqrt{\sup(S^2)},$ and using essentially the same argument again.
Answer:
I want to prove the reverse inequality but cannot seem to get anywhere with this - any hints would be great!

Just do it.
If $k <(\sup S)^2$ then if we assume $k\ge 0$ then $\sqrt{k} < \sup S$.  So $\sqrt{k}$ is not an upper bound of $S$.  So there exists a $w\in S$ so that $\sqrt k < w$. and $k < w^2 \in S^2$.   So $k$ is not an upper bound of $S$ if $k$ is positve.  And if $k$  is negative... well, it's obvious not an upper bound as it is smaller than all $y \in S^2$ which are all non-negative.
So no upper bound of $S^2$ is less than $(\sup S^2)$ so $\sup S^2 \le (\sup S^2)$.


Should I vertically flip the lines of an image loaded with stb_image to use in OpenGL?

Question: I'm working on an OpenGL-powered 2d engine.
I'm using stb_image to load image data so I can create OpenGL textures. I know that the UV origin for OpenGL is bottom-left and I also intend to work in that space for my screen-space 2d vertices i.e. I'm using glm::ortho( 0, width, 0, height, -1, 1 ), not inverting 0 and height.
You probably guessed it, my texturing is vertically flipped but I'm 100% sure that my UV are specified correctly.
So: is this caused by stbi_load's storage of pixel data? I'm currently loading PNG files only so I don't know if it would cause this problem if I was using another file format. Would it? (I can't test right now, I'm not at home).
I really want to keep the screen coords in the "standard" OpenGL space... I know I could just invert the orthogonal projection to fix it but I would really rather not.
I can see two sane options:
1- If this is caused by stbi_load storage of pixel data, I could invert it at loading time. I'm a little worried about that for performance reason and because I'm using texture arrays (glTexture3d) for sprite animations meaning I would need to invert texture tiles individually which seems painful and not a general solution.
2- I could use a texture coordinate transformation to vertically flip the UVs on the GPU (in my GLSL shaders).
A possible 3rd option would be to use glPixelStore to specify the input data... but I can't find a way to tell it that the incoming pixels are vertically flipped.
What are your recommendations for handling my problem? I figured I can't be the only one using stbi_load + OpenGL and having that problem.
Finally, my target platforms are PC, Android and iOS :)
EDIT: I answered my own question... see below.
Comment: Using normalized texture coordinates in OpenGL, (0,0) always refers to the bottom-left corner of a texture image. There is no way of changing this behavior short of as you said flipping your image before submitting it to GL or flipping your texture coordinates. Also, be aware that by using a non-standard projection matrix like the one you are using, if you were to ever cull polygon facet sides or perform per-side lighting or stenciling, your winding direction will be backwards. Polygon winding is determined post-projection, and assumes a standard right-handed projection.
Comment: To that end, there is no mechanism in OpenGL to flip an image during pixel transfer. You can reverse the order of components, change the format or data type (***not*** in OpenGL ES, mind you), but you cannot flip the image vertically or horizontally. With the introduction of programmable fragment shading, this is completely unnecessary. Reversing the order of the components is also somewhat unnecessary given the ability to swizzle textures, it may be removed from the API in 10-20 years if the current rate of deprecation holds ;)
Comment: Why are you saying that I'm using a non-standard projection matrix? AFAIK my problem comes from the fact that I want the matrix to be as standard as possible (origin at the bottom-left of the screen)... look at my call to glm::ortho above. I wanna keep it this way because I don't wanna have to worry about post-projection ops later down the road. Am I missing something here?
Comment: Just to be clear: I know that (0,0) is the bottom-left of the texture map. My problem is precisely that when I specify (0,0) I get the top-left corner texel. That's why I'm asking if stbi_load pixel storage and OpenGL pixel storage differ.
Comment: That (0,0) is bottom-left seems to be an assumption people have made that I can't see any evidence for in the actual spec, all the spec says is that `t` (the "y" coordinate) must lie in the range [0,1] and can be linearly interpolated. `lodepng` loads bottom-first, so top-left is (0,1), while `gdiplus` loads top-first, so top-left is (0, 0). Choosing your coordinates therefore depends on the image loader you use, not OpenGL.
Answer: I know this question's pretty old, but it's one of the first results on google when trying to solve this problem, so I thought I'd offer an updated solution.
Sometime after this question was originally asked stb_image.h added a function called "stbi_set_flip_vertically_on_load", simply passing true to this function will cause it to output images the way OpenGL expects - thus removing the need for manual flipping/texture-coordinate flipping.
Also, for those who don't know where to get the latest version, for whatever reason, you can find it at github being actively worked on:
https://github.com/nothings/stb
It's also worth noting that in stb_image's current implementation they flip the image pixel-by-pixel, which isn't exactly performant. This may change at a later date as they've already flagged it for optimsation. Edit: It appears that they've swapped to memcpy, which should be a good bit faster.
Comment: You could modify the loading logic to just respect the order set by stbi_set_flip_vertically_on_load, thus preventing the need for flipping at all. The next best thing would probably be using memcpy or memmove for entire rows.
Comment: How could it be done faster than doing it pixel by pixel? I can't think of any better way
Answer: Ok, I will answer my own question... I went thru the documentation for both libs (stb_image and OpenGL).
Here are the appropriate bits with reference:
glTexImage2D says the following about the data pointer parameter: "The first element corresponds to the lower left corner of the texture image. Subsequent elements progress left-to-right through the remaining texels in the lowest row of the texture image, and then in successively higher rows of the texture image. The final element corresponds to the upper right corner of the texture image." From http://www.opengl.org/sdk/docs/man/xhtml/glTexImage2D.xml
The stb_image lib says this about the loaded image pixel: "The return value from an image loader is an 'unsigned char *' which points to the pixel data. The pixel data consists of *y scanlines of *x pixels, with each pixel consisting of N interleaved 8-bit components; the first pixel pointed to is top-left-most in the image." From http://nothings.org/stb_image.c
So, the issue is related the pixel storage difference between the image loading lib and OpenGL. It wouldn't matter if I loaded other file formats than PNG because stb_image returns the same data pointer for all formats it loads.
So I decided I'll just swap in place the pixel data returned by stb_image in my OglTextureFactory. This way, I keep my approach platform-independent. If load time becomes an issue down the road, I'll remove the flipping at load time and do something on the GPU instead.
Hope this helps someone else in the future.
Comment: Gamedev.net forums version of this topic: http://www.gamedev.net/topic/649751-should-i-vertically-flip-the-lines-of-an-image-loaded-with-stb-image-to-use-in-opengl/
Answer: Yes, you should. This can be easily accomplished by simply calling this STBI function before loading the image:
<code>stbi_set_flip_vertically_on_load(true);
</code>
Answer: Since this is a matter of opposite assumptions between image libraries in general and OpenGL, Id say the best way is to manipulate the vertical UV-coord. This takes minimal effort and is always relevant when loading images using any image library and passing it to OpenGL.
Either feed tex-coords with 1.0f-uv.y in vertex-population OR reverse in shader.
<code> fcol = texture2D( tex, vec2(uv.x,1.-uv.y) );
</code>


Ubuntu 16.04 Bluetooth Can't find devices

Question: Good day fellow Ubuntu people, I have a similar bluetooth problem not detecting any devices
I installed ubuntu version 16.04 on hp 4520s laptop and want to connect a bluetooth keyboard i have tried finding device normally like i have done on other ubuntu laptops and can't see the device at all, I then tested to see if the laptop detects any other devices like my phone and stil no devices are visible i also checked if i can connect keyboard to a windows laptop and i am capable of finding the device and connect to it.fault so far i have determined lies with the either faulty hardware or firmware on ubuntu laptop
i have also tried installing other bluetooth managers like blueman appplet in ubuntu and stil cannot find any devices.THis is how far i have come.I am new to ubuntu forums and any advise help would be appreciated
Here, below lists of system information.
rfkill list:
0: hci0: Bluetooth
    Soft blocked: no
    Hard blocked: no
1: phy0: Wireless LAN
    Soft blocked: no
    Hard blocked: no
2: hp-wifi: Wireless LAN
    Soft blocked: no
    Hard blocked: no
3: hp-wwan: Wireless WAN
    Soft blocked: no
    Hard blocked: no
4: hp-bluetooth: Bluetooth
    Soft blocked: no
    Hard blocked: no

lspci -knn | grep Net -A2; lsusb:
Bus 002 Device 005: ID 148f:1000 Ralink Technology, Corp. Motorola
BC4 Bluetooth 3.0+HS Adapter

dmesg | grep -i blue:
[  177.053159] Bluetooth: Core ver 2.22
[  177.053185] Bluetooth: HCI device and connection manager initialized
[  177.053188] Bluetooth: HCI socket layer initialized
[  177.053190] Bluetooth: L2CAP socket layer initialized
[  177.053196] Bluetooth: SCO socket layer initialized
[  177.993897] Bluetooth: hci0 hardware error 0x37
[  189.515605] Bluetooth: BNEP (Ethernet Emulation) ver 1.3
[  189.515607] Bluetooth: BNEP filters: protocol multicast
[  189.515611] Bluetooth: BNEP socket layer initialized
[  220.258415] Bluetooth: RFCOMM TTY layer initialized
[  220.258425] Bluetooth: RFCOMM socket layer initialized
[  220.258433] Bluetooth: RFCOMM ver 1.11

Comment: Added broader description of problem hope it helps.
Answer: You can use this:
sudo bccmd psset -s 0x0000 0x028c 0x0001

And:
sudo service bluetooth restart

Answer: After reboot bluetooth adapter was not detected by bluez. Tried to restart the service, did not work. Reloading module helped
sudo rmmod btusb
sudo modprobe btusb
sudo service bluetooth restart


New Activity: Why Android Studio wants to create a Blank Activity for "Wear OS"?

Question: In Android Studio when I want to make a new (blank) activity via the context menu, it always makes one for "Wear OS". Is this normal? How can I prevent this?
I don't do anything with Wear OS.
My only solution is to do it by hand by creating the Java and Layout classes separately and update the Manifest file.
Answer: I think its Empty activity and not blank activity.I also had the same issue when i tried to create a blank activity it created a activity for wear os.
Hope this solves your problem.
Answer: I'm also facing the same problem, when creating a new blank activity, it wants to create a wearOS activity. I think this is a bug in Android studio 4.0.1
Select Empty Ativity instead of Blank Activity and it works as normal
Answer: cuz it show how google product works (Complexity out of control)


Android JQuery mobile cookies not stored

Question: I am using JQuery mobile library with jquery.cookie.js on Android. The header of index.html looks like this:
<link rel="stylesheet" href="css-js/jquery.mobile-1.0a2.min.css" />

Everything else works except storing and retrieving cookies.
The code to store them looks like
var tmp = 'abc'
$.cookie(COOKIE_NAME, tmp);

The code to retrieve looks like
var stored = $.cookie(COOKIE_NAME)

And i'm sure there are no empty or null values added. I have set
mWebView.getSettings().setDomStorageEnabled(true);

for the WebView.
What could be the problem, or what could be a good way to debug it?
Comment: What happens if you try to use document.cookies as described here: http://jquery-howto.blogspot.com/2010/09/jquery-cookies-getsetdelete-plugin.html
Comment: What android version was affected?
Comment: 2.3, but that was 3 years ago :)
Answer: The issue may be related to the fact that you are not setting a path:
$.cookie(COOKIE_NAME, tmp, { path: '/' });

Without the path, I believe the browser defaults to the current path (whatever page you are on), and as soon as you go to another page, the cookie is unaccessable.


adding child change the button bar tab from RTL to LTR

Question: am using https://github.com/xmartlabs/XLPagerTabStrip in my app .. and its work just fine as i need .. i had 5 children in the buttonbar .. and my app is in Arabic RTL language ... the tab will be like this:

which is the right way to be ..
i have just added the sixth child and it got messed up .. like this:

how to solve this and make it RTL as it was? also is there is a way to make the tabs scrollable so it will not be so crowded and messed up like this?
Comment: Hello, I'm facing the same issue, I'm currently looking at it and will let you know if I come up with something.
Comment: Hi, I am getting same issue now, do you have any solution for this BUG?
Answer: To get the needed behavior, one must the following:

Set the semantic property of your collection view to Force Left to Right
In the override func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController] method reverse the view controllers array before returning it
In ViewWillAppear go to the last element of the array but make sure to dispatch to the main queue
DispatchQueue.main.async {
    if(self.itemsList.value.count > 0){
        self.moveToViewController(at: self.itemsList.value.count-1, animated: false)
    }

}


Close all postman tabs before startup

Question: I really don't know if this is the right place to ask.
The last time I used postman, I had a tab open with a really really long response body, or maybe it was the request body, or perhaps the url?
Anyway, postman wasn't responding, so I killed it with task manager.
Today I open postman and it tries to load my open tabs - including the tab with a very long body. As a result, postman hangs and I have to kill it.
Is there a cache file I can delete somewhere to make postman open without the tabs? Or a command-line option?
Comment: In your %appData%/Postman you can find same cache and config file, really don't know but i think one of that store last tabs open. I suggest to copy files before delete them
Answer: Same thing just happened to me. I found a "window" file within Library/Application Support/Postman (Mac). Opened it using VI and removed all the entries, saved and started postman. All my tabs were closed and collections were retained.
Comment: On my windows 7, I found this file in C:\Users\\AppData\Roaming\Postman. Clearing it resolves the problem.
Comment: On linux the window file is in ~/.config/Postman directory
Comment: It's the Library directory under ~ and not under / in mac os
Answer: You can right-click on any tab and select Close all tabs.
Answer: Its best to delete the cache files or delete Postman folder itself, it can be found in Windows here:
 C:\Users\<user>\AppData\Roaming\Postman
 C:\Users\<user>\AppData\Local\Postman

Close all postman tabs before startup


Why does flexbox push my image to the side of the my logo?

Question: i have been trying to insert a image of a dog in my css with flexbox but every time i try it goes directly to the side of my logo(title) here is the code (thanks for the help):

Doggies

Learn

Images

Submit Photo

Creator

css=
.logo{
    display:flex;
    justify-content: center;
}
nav{
    display:flex;
    justify-content: center;

}
.list li{
    display:inline-flex;
    margin:10px 5vw;
}

body{
    display:flex;
}

Answer: Your header tag should be placed within your body tag. Don't confuse the header tag (should be in the body) with the head tag (should be outside the body). The body tag encompasses all of the content on the DOM. Even if you place the header tag outside of the body tag as you are doing now, the body still considers it as part of the body. To test this, if you add "background: red" to your body with your current code, you will see that the entire screen including behind the header content will have a background of red. That's why when you added "display: flex" to the body, it made all of the content (including the header) sit side-by-side.
Here, I just moved your header into the body and removed the "display: flex" on your body css. If you want to make the body content display flex, create a separate div inside the body just for the content and add display flex to that div.

.logo {
    display:flex;
    justify-content: center;
    background: red;
}
nav{
    display:flex;
    justify-content: center;
    background: blue;

}
.list li{
    display:inline-flex;
    margin:10px 5vw;
}

Doggies

Learn

Images

Submit Photo

Creator


Redshift - How to group by max() on an array field

Question: I am using redshift
I have a table like this :
metric is a super type, built with the array() function within redshift

user
metrics

red
array(2021, 120)

red
array(2020, 99)

blue
array(2021, 151)

I would like to do :
select user, max(metrics) from table group by user
and get this :

user
metrics

red
array(2021, 120)

blue
array(2021, 151)

Sadly using this query, I only get null values
Do you know how to handle that ?
Thanks
Comment: Please explain what `metrics` looks like.  Is it a string?  Redshift doesn't support arrays.
Comment: metric is a super type, built with the array() function within redshift
Comment: . . You need to explain that clearly *in the question*.
Answer: If you are familiar with Redshift Spectrum, the logic is very similar to unnest an array field when you query an external schema.
In your case, the query is pretty simple:
SELECT t.user, max(metric)
FROM my_schema.my_table as t, t.metrics as metric
GROUP BY 1

If the array contains types other than numerical ones, you can simply cast it to int or double like:
max(metric::int)

In this way, pure string such as "hello world" are considered as null, but string like "33333" is converted to int.
Comment: It seems here it would only send back the maximum value within the array for each user  :

| red  | 2021  |
 and
| blue | 2021  |

It may be dangerous if the second element of array would have been a string for exemple (which would be considered as the max value)
Comment: @alankar I updated the answer to handle that case


Daylight Saving Time start and end dates in Ruby/Rails

Question: I'm working on a Rails app where I need to find the Daylight Saving Time start and end dates given a specific offset or timezone.
I basically save in my database the timezone offset received from a user's browser( "+3", "-5") and I want to modify it when it changes because of daylight saving time.
I know Time instance variables have the dst? and isdst methods which return true or false if the date stored in them is in the daylight saving time or not.
 > Time.new.isdst
 => true

But using this to find the Daylight Saving Time beginning and end dates would take too many resources and I also have to do it for each timezone offset I have.
I would like to know a better way of doing this.
Comment: So looking back at what you are doing a question comes to mind. You are storing just their offset. But is the offset from YOUR time or from UTC? If the offset is UTC then DST doesn't come into play unless they happen to be in a zone that observes DST. Or is the offset the difference from yours, and again, will you know if they are observing DST or not? If your local time changes because of DST and theirs does too, then the offset remains the same.
Comment: I see some possible issues with the way you are doing this. Just because a person's offset puts them in the western time zone of the US, does not tell you if they observe DST. Most of Arizona does not observe DST. Notice I say most, not all. That's why you'd probably want to store the actual time zone as a string.
Comment: Let me give you further details on this. I'm working on a solar calculator that computes the solar elevation angles for each day in a given location on the globe. The app takes the geolocation coordinates, the date and the timezone offset only once. On the server I run a cron job that recomputes the elevation each day on midnight for each timezone( I can have users from New York, London, Moscow and so on).
Comment: Obviously I need to do this for each timezone so basically I my cron job actually runs every 15 minutes, finds the timezones for which the time became 00:00 AM and recomputes everything. Now I store my timezones using the offset I receive from users browser( currently I would get the summer offsets for most of Europe and America). But in the autumn this will change( and the date when it changes is different in various regions). This is the reason I need to find the DST period.
Comment: Comming back to your questions, yes, I currently store only the offset I get from `.getTimezoneOffset()`. I am aware that for certain states in the US and most of the countries in the World there is no DST. However I think that I can solve this problem using the geolocation coordinates I already have. I can get the user's Country/State using them and make the appropriate query.
Comment: OK, so you are getting UTC offset, and you plan on pulling timezone name from geolocation. Does my answer not work for you? As it stands you could use it to take their timezone name and get the start and end dates for their DST if they observe it. I would probably work it into some methods in the model that give your object those methods.
Answer: Ok, building on what you've said and @dhouty's answer:
You want to be able to feed in an offset and get a set of dates for knowing if there is a DST offset or not. I would recommend ending up with a range made of two DateTime objects, as that is easily used for many purposes in Rails...
require 'tzinfo'

def make_dst_range(offset)

  if dst_end = ActiveSupport::TimeZone[offset].tzinfo.current_period.local_end
     dst_start = ActiveSupport::TimeZone[offset].tzinfo.current_period.local_start
     dst_range = dst_start..dst_end
  else
     dst_range = nil
  end

end

Now you have a method that can do more than just take an offset thanks to the sugar that comes with ActiveSupport. You can do things like:
make_dst_range(-8)
#=> Sun, 08 Mar 2015 03:00:00 +0000..Sun, 01 Nov 2015 02:00:00 +0000

make_dst_range('America/Detroit')
#=> Sun, 08 Mar 2015 03:00:00 +0000..Sun, 01 Nov 2015 02:00:00 +0000

make_dst_range('America/Phoenix')
#=> nil     #returns nil because Phoenix does not observe DST

my_range = make_dst_range(-8)
#=> Sun, 08 Mar 2015 03:00:00 +0000..Sun, 01 Nov 2015 02:00:00 +0000

Today happens to be August 29th so:
my_range.cover?(Date.today)
  #=> true
my_range.cover?(Date.today + 70)
  #=> false
my_range.first
  #=> Sun, 08 Mar 2015 03:00:00 +0000
  #note that this is a DateTime object. If you want to print it use:
my_range.first.to_s
  #=> "2015-03-08T03:00:00+00:00"
my_range.last.to_s
  #=> "2015-11-01T02:00:00+00:00"

ActiveSupport gives you all sorts of goodies for display:
my_range.first.to_formatted_s(:short)
  #=> "08 Mar 03:00"
my_range.first.to_formatted_s(:long)
  #=> "March 08, 2015 03:00"
my_range.first.strftime('%B %d %Y')
   #=> "March 08 2015"

As you can see it's completely doable with just the offset, but as I said, offset doesn't tell you everything, so you might want to grab their actual time zone and store that as a string since the method will happily accept that string and still give you the date range. Even if you are just getting the time offset between your zone and theirs, you can easily figure correct that to the UTC offset:
my_offset = -8
their_offset = -3
utc_offset = my_offset + their_offset

Comment: Seems a good suggestion, I'll upvote it, However I will still keep the question open.
Answer: What you are probably looking for is TZInfo::TimezonePeriod. Specifically, the methods local_start/utc_start and local_end/utc_end.
Given a timezone offset, you can get a TZInfo::TimezonePeriod object with
ActiveSupport::TimeZone[-8].tzinfo.current_period

Or if you have a timezone name, you can also get a TZInfo::TimezonePeriod object with
ActiveSupport::TimeZone['America/Los_Angeles'].tzinfo.current_period

Comment: ah, you beat me to it, and with a simpler example.


Good books for WCF based SOA, Distributed and Server Side Programming?

Question: I am basically a .NET GUI programmer and have worked on a lot of WPF, Winforms and also have used WCF. I joined a new job in a bank and we are currently writing a new software to replace existing trading apps. This involves lot of work based on WCF services and we need to use/implement a lot of SOA related concepts like message broker, pub-sub patterns, message bus etc. So, basically means a lot of server side and distributed programming in my way ahead ! We now use simple WCF services that does our job for our service layer but aiming to make this more scalable, robust, secure and reliable.
I have a basic WCF book but wondering if there is a more specialized SOA, Distributed Architecture based book (based on .NET, WCF or may be not) that can quickly help me to get through the curve of server side programming. Possibly that talks about CEP, EDA etc..
Many Thanks,
Mani
Comment: possible duplicate of [WCF Book Recommendation](http://stackoverflow.com/questions/386801/wcf-book-recommendation)
Comment: and another http://stackoverflow.com/questions/3939302/which-book-for-soa-with-net
Comment: CEP, EDA, etc. are more about big SOA. WCF is API to build service. These terms are related to whole infrastructure and usually provided out-of-the box by ESBs etc.
Comment: I was wondering if these WCF based books cover CEP, EDA, CQRS related topics. But yes, those are useful links.
Answer: i highly recommend the following books by Lowy and Erl:

Juval Lowy, Programming WCF Services, 3rd Edition for .net 4
Thomas Erl, SOA Design Patterns
Thomas Erl, SOA Principles of Service Design

Lowy has a few WCF articles on the MSDN Mag site
Answer: Professional WCF 4: Windows Communication Foundation with .NET 4.
Pablo Cibraro; Kurt Claeys; Fabio Cozzolino; Johann Grabner
WCF 4.0 Multi-tier Services Development with LINQ to Entities.
Mike Liu
SOA Modeling Patterns for Service-Oriented Discovery and Analysis.
Michael Bell
Pro WCF: Practical Microsoft SOA Implementation.
Chris Peiris; Dennis Mulder
Thanks,
Sebastian


How do I use the Turret Override Program?

Question: There is a holodisk called the Turret Override Program, which you obtain by finding a specific Total Hack magazine.
Anytime you use a terminal that has turrets connected to it, you can "load" the override program to get additional options.
There is a short readme file that states that "scrambling" the targeting parameters will cause the turrets to shoot everyone, including the player. I cannot for the life of me get this to work the way I expect. There's also a menu option for remote targeting, that makes it seem like you should be able to tell the turrets to shoot at specific targets, but this has never worked for me either.
How do I use the override program, especially to make the turrets shoot enemies?
Comment: These programs just appear to be buggy. I have problems with the spotlight one (only one I've found so far).. Sometimes the override program just doesn't work at all. The spotlight continues to target me even after the override. I think it's just going to need to be patched.
Comment: I just noticed [this other question](http://gaming.stackexchange.com/q/243998/108003), that this might be a duplicate of. It's worded a bit differently. The answer is not at all helpful.
Answer: There are four options when using the override program:
Sabotage will cause turrets to explode the next time they fire.
Scramble will cause turrets to shoot everyone.
Override will cause the turrets to become friendly to the player and hostile to enemy NPCs.
Remote control doesn't seem to do anything. Every time it's used it seems to fail.
Note that some of the options aren't always available. Sabotage and override have both been observed to disappear when all turrets connected to the terminal have been destroyed, for example, but not every time.
Also note that if you hit the tab key on PC too quickly, the command might not process. Waiting 2-4 seconds is generally a safe bet. (kudos to aslum in the comments) There are also mods available on Nexus that speed up the terminal output and allow the turret commands to process faster.
Comment: It might be worth noting, sometimes when using a terminal if you press "back" (TAB on PC) too quickly whatever command you entered will not process... It generally takes about 2-4 seconds for a command to be "enabled" and if you hit back before then it will be canceled instead!
Comment: See, that's what I thought those options were supposed to do, but they don't. The only results I've had are the turrets shooting no one or the turrets shooting just me. Or exploding. The exploding one works.
Comment: @DCShannon what platform are you on? I have 100% success on PC, and my brother has the same on XBOne
Comment: I'm on Xbox One. I've tried this with at least half a dozen different turret terminals that still had working turrets, with multiple different characters.
Comment: Most of the time (always?), the Scramble option doesn't show up until after I hit the Override command. Have you found the need to do things in a specific order?
Comment: @aslum That might be it actually. I tend to hammer the A button to skip through the text typing out and immediately back out once it's done typing.
Comment: This seems to be working now. I think @aslum's comment was the key. Add that to the answer and I'll accept it.
Comment: Additionally, there is at least one mod out there for PC that increases "terminal speed" which might also alleviate this issue...
Comment: @DCShannon it took 2 months but I added it


Shared library and .h import in react native

Question: I have .so and .h files in a sdk built for android. I want to use it in react native. How can I do it? Is there a way to turn it into a module so I can import and use its functions?
Answer: You cannot use them directly but yes there is way. You need to Bridge that files to js.
Helping Material
Comment: With this, you need to create a whole module in java, add functions etc. But I have my functions in .h file as NativeString already. This material is probably not for my question


Build error building an example Flex mxml

Question: I'm using the Flex 3.3 SDK (not Flex builder, as I'm on 64-bit Linux), and it seems I can't even build simple example files.
The Pie Chart example on http://livedocs.adobe.com/flex/3/html/help.html?content=charts_types_09.html refuses to build, giving me:
The generated actionScript is as follows:
<code>package
{
import flash.accessibility.*;
import flash.debugger.*;
import flash.display.*;
import flash.errors.*;
import flash.events.*;
import flash.external.*;
import flash.filters.*;
import flash.geom.*;
import flash.media.*;
import flash.net.*;
import flash.printing.*;
import flash.profiler.*;
import flash.system.*;
import flash.text.*;
import flash.ui.*;
import flash.utils.*;
import flash.xml.*;
import mx.binding.*;
import mx.charts.PieChart;
import mx.core.Application;
import mx.core.ClassFactory;
import mx.core.DeferredInstanceFromClass;
import mx.core.DeferredInstanceFromFunction;
import mx.core.IDeferredInstance;
import mx.core.IFactory;
import mx.core.IPropertyChangeNotifier;
import mx.core.mx_internal;
import mx.styles.*;
import mx.containers.Panel;
import mx.charts.Legend;
import mx.core.Application;
import mx.charts.series.PieSeries;

public class piechartTest extends mx.core.Application
{
    public function piechartTest() {}

    [Bindable]
    public var myChart : mx.charts.PieChart;

    mx_internal var _bindings : Array;
    mx_internal var _watchers : Array;
    mx_internal var _bindingsByDestination : Object;
    mx_internal var _bindingsBeginWithWord : Object;

include "/home/mathias/Stage/hadoop_testing/flex_test/piechartTest.mxml:4,15";

}}
</code>
I would absolutely love a simple solution to this problem, and I'm sure one exists, I just can't seem to find it (partially because every explanation seems to have been written for Flex Builder).
Answer: Aha. The solution, apparently: http://pragmaticflex.wordpress.com/2008/02/20/charts-with-the-flex-sdk/
Answer: just make sure you have installed the datavisualization package to you 3.3 installation. The charts classes is in there and strangelly this package is separated of the rest of the sdk distribution.
google it to find  (but it is NOT listed on adobe confluence)
hope it helps


Regarding macros

Question: may i know what is the problem in using the below x-macro code
#define FILL_BUFF_1 (int *)(0x01, 0x02)
#define FILL_BUFF_2 (int *)(0x03, 0x04)

#define X(a,b)

#define LOOK_UP \
     X(0x13, FILL_BUFF_1), \
     X(0x14, FILL_BUFF_2)

#undef X

#define X(a,b) a
int pid_table[2] = {LOOK_UP};
#undef X

#define X(a,b) b

int *pid_buff_ptr[2] = {LOOK_UP};

void main(int argc, _TCHAR* argv[])
{
    printf("%d ", (pid_buff_ptr+0));  // displays 0x02

    printf("%d ", (pid_buff_ptr+1));  // displays 0x04

    printf("%d " ,*(pid_buff_ptr[0] + 1)); // doesnt work
}

How can I make the above code to access other elements in the buffer?
Comment: this has to be homework. Nobody would seriously want to write code as convoluted as that...
Comment: i've seen worse in the business world...
Comment: Perhaps you could explain what you are trying to do?
Comment: It may or it may not be homework, but I think inquisitive thinks that the first two lines define initialized arrays, which is the source of his/her problem.
Comment: gcc wont compile the line "int *pid_buff_ptr[2] = {LOOK_UP};" witch resolves to "int *pid_buff_ptr[2] = {(int *)(0x01, 0x02),(int *)(0x03, 0x04)"
Comment: Well guys this is not a homework as such.. i was trying to optimize the code by doing the above things..

@eaanon1: if the compilation fails, how come am getting some values dereferenced (in this case (pid_buff_ptr+0)) dereferences element 0x04
Answer: (Taking a wild stab at this just because it's been sitting here a while unanswered.)
In the last line, you appear to be dereferencing the value 0x03 as a pointer -- I suspect you are getting a SIGSEGV?
pid_buff_ptr[0] == 0x02

so
(pid_buff_ptr[0] + 1) == 0x03

so
*(pid_buff_ptr[0] + 1)

is dereferencing 0x03 as a pointer.
Comment: @william: Ya u r right.. my actual question is, how can i de-reference to get the value 0x03.. i dont understand why (pid_buff_ptr[0] + 1) is dereferencing 0x03, instead of memory location containing 0x03.. my understanding is, pid_buff_ptr[0] is the first element in the array, which is a pointer to the buffer (0x01, 0x03)
Answer: I am not sure what exactly you're trying to do, but if I guessed correctly, you want to have the pid_buff_ptr variable contain an array of int values, not an array of int * values.
If that is the case, you need to change
#define FILL_BUFF_1 (int *)(0x01, 0x02)
#define FILL_BUFF_2 (int *)(0x03, 0x04)

to
#define FILL_BUFF_1 {0x01, 0x02}
#define FILL_BUFF_2 {0x03, 0x04}

Change the following:
int *pid_buff_ptr[2] = {LOOK_UP};

to
int pid_buff_ptr[][2] = {LOOK_UP};

To print, you would use something like:
printf("%d ", pid_buff_ptr[0][1]);

Of course, I could be wrong.
Now, some other comments:

You need to #include <stdio.h> before using printf().
main() returns int.
Since main() returns int, you should return an int from it.  Traditionally, 0 means success.
I don't know what _TCHAR is, but if it is not an alias or #define for char, you might be in trouble.

Even with the above changes, I don't understand the need to do the trickery with the pre-processor.  What exactly are you trying to do?
Comment: Hey thanks a lot Alok!! i have tried your code and it works.. btw, when i try to have declaration like "int pid_buff_ptr[][] = {LOOK_UP}", i am not able to do so.. what is my understanding is, you need not mention the column subscript of a 2D array, when u try initializing it in declaration itself.. am i right.. i need the above because, FILL_BUFF_N may be dynamic and need not contain only 2 elements
Comment: That's correct.  You can have only one dimension "free".  If you need more than two FILL_BUFF_* macros, you can easily do this by changing int pid_table[2] = {LOOK_UP}; to int pid_table[] = {LOOK_UP};, adding the required FILL_BUFF_* macros, and changing LOOK_UP macro.

But I still don't know what you're trying to do.  There is almost certainly an easier way to do it.

Regarding macros


Small bathroom - feasible layout?

Question: With a tiny (5' by 6') bathroom we never have enough space. Current layout is like this:

Is the following feasible? Particularly in terms of drainage from the shower?

Currently the bath "waste" is directly by the window (where the waste for the toilet etc goes to outside) so there isn't any need to take it across/under the floor. I don't think there is any pipework "under" the floor currently.
Is it an option to have pipes above floor level but boxed in - would be happy with that.
I don't have a great deal of wall space as one wall is windows the whole width of the room (about 12" above the level of the sink/cistern).
Is there another layout (in general terms) you would recommend? My aim is really just to have a sense of more space and to have enough storage, (we're not concerned with keeping the bath) I realise it's a really small space.
Comment: Are you asking about vertical fall of the piping below the floor? Tell us about that space. This shouldn't be a problem otherwise.
Comment: Thanks for editing with the images- I'm not sure why they were broken. I was doing it on the mobile app..
Comment: @seventyeightist At the bottom of the post it keeps the links for the images. Like.. "[1]: http://imgur.com/06tYO8g.jpg"... your links were missing the ".jpg" to turn it into an image.
Comment: "where the waste for the toilet etc goes to outside" -- let me guess, this is in the UK
Comment: @amphibient - yes, UK, sorry if I haven't used quite the right terms - I'm a bit unfamiliar with all this..
Comment: no problem.  i remember the 4" pipe eye sore on many houses from my one trip to the otherwise beautiful country :)
Comment: ....What happens with the toilets elsewhere?? Naive question I know!
Comment: Maybe switch the door to open against the wall?
Answer:
Is it an option to have pipes above floor level but boxed in

Yes.
But if the hot and cold water supply pipes in and are metal (copper) and have supplementary equipotential bonding - I think you need to make sure the bonding clamps are easily accessible without tools. Ditto for isolating valves (for when you want to replace taps).
You don't need much slope on the horizontal runs of the waste pipe (and too much slope is bad) I read 1 in 40 to 1 in 110 somewhere.
I've boxed in pipework minimally but if I did it again I'd try to make more of a feature of it - cupboards with useful storage space as well as access to pipes.
Comment: Looking from above to outside (there's another floor above the bathroom), the toilet waste comes out exactly into the outflow pipe and the waste from the sink and bath comes out into the length of that pipe (a bit further down), so it seems like currently they are optimally placed in terms of distance to outside, although not optimally placed for anyone wanting to actually use the bathroom. If boxed in I'm happy to have a "hatch" or whatever to access the necessary parts. Are you saying there shouldn't be much of an issue with the shower waste (now mid room) to the outside?

Small bathroom - feasible layout?


How to fix Nested query HIVE SQL - syntax error

Question: SELECT
  COUNT(*),
  AVG(result) * 100
FROM
  (
    SELECT CASE WHEN (
      (m1.flag = 1)
      and (m1.Reason = 'reason_1')
    ) THEN 1 ELSE 0 END AS result
    FROM
      db1 m0
      INNER JOIN db2 m1 ON m0.id = m1.id
    WHERE
      col1 <= 3
      AND col2 = 0
  );

I'm getting an error on the WHEN CASE clause line, but I don't know what it is (https://www.eversql.com/sql-syntax-check-validator/). I can create a table with the nested SELECT clause, but I don't need it and since this is TB worth of data I though of combining both queries. Can I combine the two and would this save me time/space?
Comment: Sql seems to be wrong. Is it something working on some db or its hypothetical? Now you can create slq like this all you need is aliasing. Like this sql works `select c from (select d as c from ( select d from tab) innersql1) innersql2`
Comment: You are missing the select from your derived table. You are also missing the alias for that derived table.
Comment: Thank you, I just didn't know how to even search for this. Alias and derived table were the key terms I needed to know. Appreciate your help!
Answer: As per the comments on your post, the sub query needs to be "named" with an alias.
SELECT
  COUNT(*),
  AVG(result) * 100
FROM
  (
    SELECT CASE WHEN (
      (m1.flag = 1)
      and (m1.Reason = 'reason_1')
    ) THEN 1 ELSE 0 END AS result
    FROM
      db1 m0
      INNER JOIN db2 m1 ON m0.id = m1.id
    WHERE
      col1 <= 3
      AND col2 = 0
  )
    AS alias_name_goes_here

That said, you don't even need a sub-query...
SELECT
  COUNT(*),
  AVG(CASE WHEN (m1.flag = 1) and (m1.Reason = 'reason_1') THEN 100 ELSE 0 END)
FROM
  db1 m0
  INNER JOIN db2 m1 ON m0.id = m1.id
WHERE
  col1 <= 3
  AND col2 = 0

Comment: The query is simplified, I have quite a few case when cases. Is there any benefit to doing one way or the other? I find it easier to understand with the subquery


Ruby on Rails - Does the scope of SessionsHelper reach models?

Question: In my Organisations module, I try to assign a value to a field before creating the Organisation record.
I use a before_create filter in the model, which usually works fine.
But when I try to assign a value coming from an attribute of the current_user method defined in the session, I get an Undefined method 'current_user' error message.
As doing this works fine in a controller, I wonder why it does not work in the model?
Here is my code for the model:
# == Schema Information
#
# Table name: organisations
#
#  id                     :integer          not null, primary key
#  playground_id          :integer
#  code                   :string(255)
#  name                   :string(255)
#  description            :text
#  parent_organisation_id :integer
#  organisation_level     :integer
#  hierarchy              :string(255)
#  created_by             :string(255)
#  updated_by             :string(255)
#  created_at             :datetime         not null
#  updated_at             :datetime         not null
#

class Organisation < ActiveRecord::Base

### before filter
  before_create :set_code
  before_create :set_hierarchy

    validates :code, presence: true, uniqueness: true
    validates :name, presence: true, uniqueness: true
    validates :organisation_level, presence: true
    validates :created_by , presence: true
    validates :updated_by, presence: true
#   validates :owner_id, presence: true
#   validates :status_id, presence: true
    validates :playground_id, presence: true
#   belongs_to :owner, :class_name => "User", :foreign_key => "owner_id"        # helps retrieving the owner name
#   belongs_to :status, :class_name => "Parameter", :foreign_key => "status_id" # helps retrieving the status name
        belongs_to :organisation
        has_many :organisations

### private functions definitions
  private

  ### before filters
    def set_code
      if Organisation.count > 0
        self.code = self.organisation.code + '-' + code
      end
    end

    def set_hierarchy
      if Organisation.count == 0
        self.hierarchy = current_user.current_playground_id.to_s + '.001'
      else
        last_one = Organisation.maximum("hierarchy")
        self.hierarchy = last_one.next
      end
    end

end

Here is my code for the SessionsHelper (inspired from Rails Tutorial):
module SessionsHelper

  def sign_in(user)
    remember_token = User.new_remember_token
    cookies.permanent[:remember_token] = remember_token
    user.update_attribute(:remember_token, User.encrypt(remember_token))
    self.current_user = user
  end

  def current_user=(user)
    @current_user = user
  end

  def current_user
    remember_token = User.encrypt(cookies[:remember_token])
    @current_user ||= User.find_by(remember_token: remember_token)
  end

  def signed_in?
    !current_user.nil?
  end

  def sign_out
    self.current_user = nil
    cookies.delete(:remember_token)
  end

end

Here is an example from a controller where the assignment works:
@business_flow.playground_id = current_user.current_playground_id

I'd be glad to understand why it does not work in the model.
Comment: `current_user` method is accessible from controllers (provided `SessionsHelper` is included in `ApplicationController`) and views (by default).
Comment: You do not have access inside the model to current_user. Give it as a parameter to the methods inside the model if there is no better way. usually there are.
Answer: The SessionsHelper module gets included into your controller class, so you can use its methods from there.  It does not get included in the model class.
In fact it probably wouldn't work even if you included it by hand, because the model would need access to the cookies method for the current_user method to work.  cookies comes from an ActionController method.
To achieve what you want, try making the change in your Organisation object from the controller that's creating that object, passing in the user information that the controller has access to.


Uninstalling program

Question: I'm trying to uninstall a program with this code.. But it doesn't seem to work. I've tried the other answers but didn't seem to work either.. Can someone help me with this? I'm trying to uninstall the program by a given name(displayName)
For example I give the displayName = Appname then this code should uninstall the Appname program from my computer.
public static void UninstallApplictionInstalled(string p_name)
    {
        string displayName;
        string uninstlString;
        RegistryKey key;

        ProcessStartInfo info = new ProcessStartInfo();
        Process uninstallProcess = new Process();
        string temp;

        // search in: CurrentUser
        key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall");
        foreach (String keyName in key.GetSubKeyNames())
        {
            RegistryKey subkey = key.OpenSubKey(keyName);
            displayName = Convert.ToString(subkey.GetValue("DisplayName"));
            uninstlString = Convert.ToString(subkey.GetValue("UninstallString"));

            if (p_name.Equals(displayName, StringComparison.OrdinalIgnoreCase) == true)
            {

                uninstallProcess.StartInfo.FileName = "MsiExec.exe";
                uninstallProcess.StartInfo.Arguments = " /x " + uninstlString + " /quiet /norestart";
                uninstallProcess.Start();
                uninstallProcess.WaitForExit();
                break;

                //Console.WriteLine(subkey.GetValue("UninstallString"));
            }
        }

        // search in: LocalMachine_32
        key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall");
        foreach (String keyName in key.GetSubKeyNames())
        {
            RegistryKey subkey = key.OpenSubKey(keyName);
            displayName = Convert.ToString(subkey.GetValue("DisplayName"));
            uninstlString = Convert.ToString(subkey.GetValue("UninstallString"));

            if (p_name.Equals(displayName, StringComparison.OrdinalIgnoreCase) == true)
            {
                uninstallProcess.StartInfo.FileName = "MsiExec.exe";
                uninstallProcess.StartInfo.Arguments = " /x " + uninstlString + " /quiet /norestart";
                uninstallProcess.Start();
                uninstallProcess.WaitForExit();
                break;

                //Console.WriteLine(subkey.GetValue("UninstallString"));
            }
        }

        // search in: LocalMachine_64
        key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall");
        foreach (String keyName in key.GetSubKeyNames())
        {
            RegistryKey subkey = key.OpenSubKey(keyName);
            displayName = Convert.ToString(subkey.GetValue("DisplayName"));
            uninstlString = Convert.ToString(subkey.GetValue("UninstallString"));

            if (p_name.Equals(displayName, StringComparison.OrdinalIgnoreCase) == true)
            {
                //string prdctId = uninstlString.Substring((uninstlString.IndexOf("{")));

                uninstallProcess.StartInfo.FileName = "MsiExec.exe";
                uninstallProcess.StartInfo.Arguments = " /x " + uninstlString + " /quiet /norestart";
                uninstallProcess.Start();
                uninstallProcess.WaitForExit();
                break;
                //Console.WriteLine(subkey.GetValue("UninstallString"));
            }
        }
      }

Only this pops up..
Comment: Whatever is placed inside `UninstallString` is intended to be a *complete*, standalone command to uninstall the program. There's no guarantee that `msiexec /x` is the correct way to uninstall any given program, and even if it *is*, `UninstallString` will already *contain* that text.
Comment: Could you please tell us what `does not seem to be working` mean? It will be more helpful if you can give us some sort of "error message" you're getting while running this program.
Comment: The first thing that hits me when I read your code is `void IsApplicationInstalled`. Considering the name, I would have expected `bool` instead of `void`. The body of your function also does not match its name at all. It's like if you asked someone "*Hey, do you have some milk?*" and he answered "*mmh lemme check... yup, I just poured it in the toilets*" or even worse: he pours it in the toilet and doesn't tell you anything. (Just saying)
Comment: Are you sure your app has permission to uninstall? Are you running this as admin? Also, have you tried running it without the /quiet and with /L logging enabled
Comment: the Popup implies you got the syntax of the command wrong.  Did you provide the msi/product code to go with that /x or the display name? the display name isnt the same.
Comment: A general remark: don't do `if (p_name.Equals(value) == true)` - IMO it is bad style, it returns a boolean already, just do `if (p_name.Equals(value))`
Comment: @BugFinder as shown in the code i gave the Uninstallstring ... I think...not the display name
Comment: The uninstall string can be other uninstall methods, so for example ive got a couple which are c:\users\name\appdata\local\app\uninstall.exe or one thats c:\program files\...blah\something configuration - uninstallApp more blah...  You can assume they are all msi uninstall files
Comment: Possible duplicate of [MSI installer option- uninstalling an application](https://stackoverflow.com/questions/52267512/msi-installer-option-uninstalling-an-application)
Answer: Duplicates: Welcome to Stackoverflow. Just to mention to you that I see this question asked in at least 3 different flavors. We will have to close some of your questions since the duplication scatters replies and can waste a lot of time if people answer the (seemingly) unanswered duplicates.
In short: please don't post the same question several times. Here are the other questions:

MsiExec.exe product id uninstall
MSI installer option- uninstalling an application

C#: Using C# for this can be clunky - no matter how you do it. I would not push a command line to msiexec.exe, but go directly via the MSI API. This API can be accessed via Win32 functions or COM automation.

Uninstall Appraches for MSI: For your reference, there is a myriad of ways to kick of an MSI
uninstall:
Uninstalling an MSI file from the command line without using msiexec.
Section 14 from the link above shows how to uninstall using C++ - if that is an option. However:, there are changes in the Visual Studio 2017 templates again, so it might need a tune-up to work "out-of-the-box".

However, I would use the MSI API - as already stated - and I would recommend you go via the native Win32 functions and that you use DTF (Deployment Tools Foundation) which is part of the WiX toolkit. It is a .NET wrapper for the MSI API - which will save you a lot of boilerplate code, at the expense of having to deploy the DTF DLL: Microsoft.Deployment.WindowsInstaller.dll along with your product. I do not know if this is acceptable. I have code that does not depend on DTF if need be, but it is much longer.
Mock-up C# Sample. Project reference to Microsoft.Deployment.WindowsInstaller.dll needed. Then try the below code in a fresh C# .NET project. You can get that DLL by installing the WiX toolkit - the open source toolkit to create MSI files. After installation check in %ProgramFiles(x86)%\WiX Toolset v3.11\bin (adjust for WiX version - current as of September 2018).
Installer GUI: Important note first: the setup's UI level is set via the Installer.SetInternalUI function. If you run in silent mode, then you need to run the executable elevated for the uninstall to work properly, or an access exception occurs. When you run in Full GUI mode, you need to elevate the install yourself - provided you have the rights to do so.

Run Elevated: How to check for admin rights: Check if the current user is administrator.

using System;
using Microsoft.Deployment.WindowsInstaller;

namespace UninstallMsiViaDTF
{
    class Program
    {
        static void Main(string[] args)
        {
            // Update this name to search for your product. This sample searches for "Orca"
            var productcode = FindProductCode("orca");

            try
            {
                if (String.IsNullOrEmpty(productcode)) { throw new ArgumentNullException("productcode"); }

                // Note: Setting InstallUIOptions to silent will fail uninstall if uninstall requires elevation since UAC prompt then does not show up
                Installer.SetInternalUI(InstallUIOptions.Full); // Set MSI GUI level (run this function elevated for silent mode)
                Installer.ConfigureProduct(productcode, 0, InstallState.Absent, "REBOOT=\"ReallySuppress\"");

                // Check: Installer.RebootInitiated and Installer.RebootRequired;
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: " + e.Message);
            }

            Console.ReadLine(); // Keep console open
        }

        // Find product code for product name. First match found wins
        static string FindProductCode(string productname)
        {
            var productcode = String.Empty;
            var productname = productname.ToLower();
            foreach (ProductInstallation product in ProductInstallation.AllProducts)
            {
                if (product.ProductName.ToLower().Contains(productname))
                {
                    productcode = product.ProductCode;
                    break;
                }
            }

            return productcode;
        }
    }
}

Comment: You answer is informativ, but why `string.ToLower().Contains(string.Tolower())`? and that in a loop...
You are constructing 2 new strings per iteration, you don't need them. Is this in any way better performing than `string.IndexOf(string, StringComparison) > -1`?
Comment: @Steeve - Yes, you can lowercase the productname before the loop which is more efficient. But I don't think there is a significant performance difference between `string.IndexOf(myString, StringComparison) > -1` and `myString.Contains(StringComparison)`.

Uninstalling program


Server not mapping Ajax to Servlet correctly when switched to java 1.7 and eclipse

Question: TLDR: Do I have to use different syntax to access my servlet if I am using Tomcat instead of Glassfish or jkd 1.7 instead of jdk 1.8? I can't get my jquery ajax to communicate with my servlet (in eclipse 1.7 jdk tomcat instead of netbeans 1.8 jdk glassfish)
I am trying to convert my project from Netbeans 1.8 JDK to Eclipse 1.7 JKD.
It worked fine in Netbeans. I have spent over 5 hours trying to get it to function on Eclipse now.
I think the problem is that it is not mapping my ajax "search" to the servlet "/search" .
The servlet is annotated
@WebServlet(name = "SearchServlet", urlPatterns = {"/search"})

I have to assume this works with JDK 1.7.....?
I had trouble adding a glassfish server the same as my netbeans. I managed to add it but then it vanished and I had no server available whatsoever until I gave up and put in a tomcat one. However I don't know if you're supposed to configure this any further.
I try to add glassfish server tools by dragging it into my IDE but it says Nothing to update: nothing to update. So I'm just sticking with tomcat.
Here is the log when I run my jsp:
Apr 20, 2015 1:48:48 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:animelist1' did not find a matching property.
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version:        Apache Tomcat/8.0.21
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built:          Mar 23 2015 14:11:21 UTC
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server number:         220.127.116.11
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name:               Windows 7
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version:            6.1
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture:          amd64
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home:             C:\Program Files\Java\jdk1.7.0_79\jre
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version:           1.7.0_79-b15
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor:            Oracle Corporation
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE:         C:\Users\J\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME:         C:\Program Files\apache-tomcat-8.0.21
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=C:\Users\J\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=C:\Program Files\apache-tomcat-8.0.21
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=C:\Users\J\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=C:\Program Files\apache-tomcat-8.0.21\endorsed
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=Cp1252
Apr 20, 2015 1:48:48 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jdk1.7.0_79\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Skype\Phone\;C:\Program Files\Google\Cloud SDK\google-cloud-sdk\bin;C:\Program Files\Java\jdk1.7.0_79\jdk1.7.0_79\bin;.
Apr 20, 2015 1:48:48 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
Apr 20, 2015 1:48:48 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Apr 20, 2015 1:48:48 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-nio-8009"]
Apr 20, 2015 1:48:48 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Apr 20, 2015 1:48:48 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 772 ms
Apr 20, 2015 1:48:48 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Apr 20, 2015 1:48:48 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/8.0.21
Apr 20, 2015 1:48:49 PM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Apr 20, 2015 1:48:49 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
Apr 20, 2015 1:48:49 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
Apr 20, 2015 1:48:49 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 1162 ms

Here is the log when I try to make a search by clicking the button on the jsp:
Apr 20, 2015 1:50:11 PM org.apache.catalina.core.ApplicationContext log
INFO: Marking servlet SearchServlet as unavailable
Apr 20, 2015 1:50:11 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Allocate exception for servlet SearchServlet
javax.naming.NameNotFoundException: Name [main.SearchServlet/annj] is not bound in this Context. Unable to find [main.SearchServlet].
    at org.apache.naming.NamingContext.lookup(NamingContext.java:818)
    at org.apache.naming.NamingContext.lookup(NamingContext.java:166)
    at org.apache.catalina.core.DefaultInstanceManager.lookupFieldResource(DefaultInstanceManager.java:573)
    at org.apache.catalina.core.DefaultInstanceManager.processAnnotations(DefaultInstanceManager.java:461)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:144)
    at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:121)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1095)
    at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:817)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:135)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1517)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1474)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

Further searches after the first give this:
POST http://localhost:8080/animelist1/search 404 (Not Found)jQuery.ajaxTransport.send @ jquery-1.10.2.js:8706jQuery.extend.ajax @ jquery-1.10.2.js:8136(anonymous function) @ basic.js:8jQuery.event.dispatch @ jquery-1.10.2.js:5095jQuery.event.add.elemData.handle @ jquery-1.10.2.js:4766

I had to change my Environment variables to downgrade to JDK 1.7. I have put them below incase they are incorrect and are causing the issues (been messing around with them so much but I think they are right now):
(No added/changed User variables)
System variables:
Path
%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Skype\Phone\;C:\Program Files\Google\Cloud SDK\google-cloud-sdk\bin;C:\Program Files\Java\jdk1.7.0_79\jdk1.7.0_79\bin

JAVA_HOME
C:\Program Files\Java\jdk1.7.0_79

I am about to give up and revert to Netbeans 1.8 JDK and upload my web project to somewhere other than Google App Engine (which only works with 1.7). I will give it another hour incase anyone is able to help me but I have spent far too long wasting my time when there is another option.
Like I said I suspect the problem is something to do with my server configuration or some file related to that. Below I will paste my ajax and my servlet. They do both work in netbeans 1.8 jdk but perhaps they need changing for eclipse 1.7 jdk?
Thankyou for reading!
Jquery
$(document).ready(function () {
    $('#searchForm').submit(function () {

        $.ajax({
            url: 'search',
            type: 'POST',
            dataType: 'text',
            data: $('#searchForm').serialize(),
            success: function (data) {

                $('#displaySearchResults').html(data);
//                    $('#displaySearchResults').slideDown(500);
//
                $("#sortable1").empty();

                $.each(JSON.parse(data), function (listID, mapData) {

                    $("#sortable1").append(
                            "

"
                            + mapData.name+ "

");

//

//
Item 1

//                    var d1 = mapData.id;
//                    var d2 = d1.replace("'","");
//                    var div = document.createElement(d2);
//                    document.body.appendChild(div);

//                    $("#"+divName).text(mapData.id);
//                    $("#displaySearchResults2").text(mapData.name);
//                    $("#displaySearchResults3").text(mapData.url);

                });
            }
        });
        return false;
    });
});

Servlet
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package main;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import com.google.gson.Gson;
import entities.Anime;
import entities.Ann;
import entities.Info;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author J
 */
@WebServlet(name = "SearchServlet", urlPatterns = {"/search"})
public class SearchServlet extends HttpServlet {

        /**
     *
     */
    private static final long serialVersionUID = 1L;

        @EJB
    private AnnJAXB annj;

//    @EJB
//    private AnnJAXB annJAXB = new AnnJAXB();

    @EJB
    private Ann ann;

    /**
     * Processes requests for both HTTP GET and POST
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("");
            out.println("");
            out.println("<title>Servlet SearchServlet</title>");
            out.println("");
            out.println("");
            out.println("
Servlet SearchServlet at " + request.getContextPath() + "
");
            out.println("");
            out.println("");
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP GET method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP POST method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

//        processRequest(request, response);

//        Map <String, Object> map = new HashMap<String, Object>();

        String searchQuery = request.getParameter("searchQuery");
//         response.getWriter().write(searchQuery);

//        map.put("searchQuery", searchQuery);
//        returnResults(response, map);

        returnResults(response, searchQuery);

    }

    private void returnResults(HttpServletResponse response, String searchQuery) throws IOException {

        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");

        ArrayList<Map> arrayOfMap = new ArrayList<Map>();

        try {
            for (Anime anime : annj.Unmarshalling(searchQuery).getAnn()) {

                Map<String, String> map = new HashMap<String, String>();

                map.put("name", anime.getName());
                map.put("id", anime.getId());

                for (Info temp : anime.getAnime()) {
                    if (temp.getSrc() != null) {

                        map.put("url", temp.getSrc());
                    }
                }
                arrayOfMap.add(map);

            }

              response.getWriter().write(new Gson().toJson(arrayOfMap));

        } catch (Exception e) {}
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

TLDR: Do I have to use different syntax to access my servlet if I am using Tomcat instead of Glassfish or jkd 1.7 instead of jdk 1.8? I can't get my jquery ajax to communicate with my servlet (in eclipse 1.7 jdk tomcat instead of netbeans 1.8 jdk glassfish)
Comment: It has nothing to do with the version of Java. @WebServlet is a JEE annotation, not a standard JDK annotation. And since its a standard, it works the same in Tomcat and Glassfish. Likely the only problem you have is that the application deployment in your secondary Eclipse isn't working properly yet. As in: the servlet class file is not deployed to the server at all.
Comment: Thankyou for your answer. I've been working so long and I think we are close. I figured out what you said just now. I have a "feeling" it could be something to do with me needing to re-specify the main/base/root location... i say this because in netbeans version i access the jsp by going to http://localhost:8080/ or http://localhost:8080/index.jsp , whereas in eclipse version i need to go to http://localhost:8080/animelist1.index.jsp or http://localhost:8080/animelist1 . for eclipse, going to http://localhost:8080/ 404s . Why might this be? Thankyou!!!
Comment: I added / to my server.xml file and the page loads at localhost:8080 HOWEVER it now opens at http://localhost:8080/animelist1/ . This means something different needs to be configured to tell it where to "start looking" for things....
Answer: As I know , the notation

@WebServlet(name = "SearchServlet", urlPatterns = {"/search"})

only work in jdk 1.8
but if you still use jdk 1.7, forget the notation and fill web.xml with this map
<servlet>
    <servlet-name>search</servlet-name>
    <servlet-class>yourPackage.search</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>search</servlet-name>
    <url-pattern>/search</url-pattern>
</servlet-mapping>