Garage light switches don't always work

Question: I have a dual garage doors that operate on the 2 switches shown. The opening and closing of the doors works perfectly with the 2 large white switches. The light switches below the opening switches work sporadically and sometimes they won't switch off the garage light. They will ALWAYS switch ON the light but sometimes not switch off. Sometimes neither of them work and sometimes only one of them doesn't work. I find I have to leave them on and come back and try again later.
If I don't touch the light switches as part of the garage door open/close process where the switches are left to switch off on a timer then they always switch off and that is not an issue. The issue is when I come into the garage and need the light on without opening the garage doors.
How do I fix the light part of these switches? I'm happy to just replace them if that's what it takes. Just don't want to do that if the switch is not the problem. Also happy to replace with a different type or model of switch if that will resolve it. These switches are about 10 to 12 years old and the problem probably started happening about 2 years ago.
Comment: Those aren't switches. Those are wired (?) remotes.  They're encoding control signals on the normal 2-wire garage door button wiring.
Comment: One possibility is that the polarity of one of the switches is reversed. I installed a Genie a few years ago and they were adamant the polarity be correct... which they apparently reversed in labeling. The wall switch didn't function correctly without the polarity right, but it could still trigger the door to open.
Comment: I believe that Harper is correct. The "switches" or "devices" have the normal 2-wires running to each of the opening mechanisms.
Comment: Is it possible that once the timer has been started the lights cannot be switched off by the light button until the time runs out?
Answer: After 10-12 years, it's entirely possible that the switches behind the light buttons are failing. This would be especially true if you use the garage door opener lights on a regular basis. Consider that you probably hit the opener button (the big white one) once in the morning to open the door on your way out (then close it with the remote in your car), then once in the evening when you return home (after opening the door with the remote in the car). If you go to the garage twice in the evening, that's 4 presses of the light button (on/off for each trip), therefore more wear & tear on that particular switch.
If you're good with soldering, you could attempt to open up the wired remote, desolder the actual switch from the circuit board and replace it.
However, it's probably easier (and probably wouldn't cost significantly more) for most folk to simply replace the wired remote. You could get a Chamberlain, LiftMaster or Craftsman brand to replace it (since they're all made by Chamberlain), generally, though, these are pretty generic and almost any one will do.
I'd suggest replacing one, then testing for a few days to confirm that the light button works consistently. If that's solved the problem, then replace the other.
Replacing the wall-mount remote should be as simple as:

Pop the white plastic cover off
TAKE A PICTURE NOW
Disconnect red & white wires that are attached
No, really, you did take a picture with your phone back there, didn't you?
Unscrew 1 or 2 screws that hold the unit to the wall, and pull it off the wires.
Feed the wires through the hole in the back of the new unit
Screw it to the wall (existing screw holes if they happen to line up, otherwise, it's just drywall, screw it in wherever the new mounting holes are)
Attach the wires to the new opener (most likely exactly the way they were attached to the old one, but check the directions, just to be sure).
Pop the new white button onto the newly mounted remote.
Test!
No, really, you took a picture before you disconnected the wires back there, just to be sure, right?

Garage light switches don't always work


Are my calculations of a recursive prime-generating function based on logarithms correct?

Question:
I am trying to devise a recursive prime-generating function following an intuition of a possible analogy to Mills and Wright prime-representing functions, in the present case based on logarithms. The proposed prime generating function $f(n)$ will provide not a subset but the complete set of primes being $f(1)=2$, $f(2)=3$, $f(3)=5$... and the prime-generating constant will be called $L$. As in the standard results from Mills and Wright the decimal precision of the constant is important in order to recover the embedded primes and it is not known if
  $\lim_{n \to \infty} L_n$ is rational or not.

This is how it works and the questions are at the end:

Start with $n=1$, current prime $p_1=2$, previous accumulated value of the constant will be defined as $L_0=0$ (starting value). Calculate the value for the constant for $n=1$. It will be $$L_1=\frac{Ln(2+L_0)}{Ln(1+1)}$$

(Where $Ln$ is the natural logarithm).

Calculate the value for the constant for $n=2$, $p_2=3$, $$L_2=\frac{Ln(3+L_1)}{Ln(2+1)}$$

So if we apply recursively the formula, for $n$:
$$L_n=\frac{Ln(p_n+L_{n-1})}{Ln(n+1)}$$

For instance, the following PARI_GP code calculates $L_{500}$
\p2000;
testlimit=500;current_pr=2;L=0;for(n=1,testlimit,L=log(current_pr+L)/log(n+1);current_pr=nextprime(current_pr+1););print("n is ",testlimit," and L is ",L);

$$L_{500} = 1.3159864456...$$

Reviewing the results of the tests, it seems that $\lim_{n \to \infty} L_n$
oscillates (due to the gaps between primes applied in the formula) but in the long term it is stable and tends to decrease and goes down to a value closer to $1$ and lower than $2$.
For example:
\p3;
testlimit=500000;current_pr=2;L=0;for(n=2,testlimit,L=log(current_pr+L)/log(n);current_pr=nextprime(current_pr+1););print("n is ",testlimit," and L is ",L);

$L_{5000}$ is around $1.23...$ and the above code shows that $L_{500000}$ is around $1.21$. Other similar tests show that it tends to go down to some specific limit near the lower bound of $[1,2]$.
As the proccess of recovering the primes is recursive, the way of using the constant is as follows:
For instance, assuming that we have $L_{500}$, we need to start obtaining the last prime back:
$$f(500)=p_{500}=\lfloor (500+1)^{L_{500}} \rfloor - 1 = 3571$$
Then recover $L_{499}$ and recover $f(499)=p_{499}$
$$L_{499}=((500+1)^{L_{500}})-p_{500}=1.31586811...$$
$$f(499)=p_{499}=\lfloor (499+1)^{L_{499}} \rfloor - 1 = 3559$$
$$...$$

So in general the recursive process to recover $L_{n}$ and $f(n)=p_n$ from $L_{n+1}$ and $f(n+1)=p_{n+1}$ is:
$$L_{n}=((n+2)^{L_{n+1}})-p_{n+1}$$
$$f(n)=p_{n}=\lfloor (n+1)^{L_{n}} \rfloor - 1$$

The following code, having $L_{500}$ calculates backwards the complete set of primes $\{p_{500}..p_{1}\}$
curr_L=L;for(n=1,testlimit,curr_n=testlimit-n+2;curr_p=(floor(curr_n^curr_L))-1;print("n is ",testlimit-n+1," ; Current prime is ",curr_p," and is_prime check = ",isprime(curr_p));curr_L=(curr_n^curr_L)-curr_p;);

There is a little correction required for the calculation of $p_1$. Depending on the $L_n$ calculated, sometimes the recovered value $\lfloor (2)^{L_{1}} \rfloor = 2$ instead of $3$. And for that reason, when the value is $2$, $f(1)=p_{1}=\lfloor (2)^{L_{1}} \rfloor - 1 = 2-1 = 1$ instead of the expected $p_1=2$. To handle this special case, we can express the prime-generating function as:

$$f(n)=p_{n}=\lfloor (n+1)^{L_{n}} \rfloor - 1 + \delta_{f(n),2}$$

Where $\delta_{f(n),2}$ is the Kronecker delta function (kindly provided by @MitchellSpector in this question). Basically it is a little trick that will assure that always $f(1)=2$ independently of the value of $\lfloor (n+1)^{L_{n}} \rfloor$ ($2$ or $3$). It would be possible a definitions-by-case of $f(n)$ as well instead of using one single expression.
This is a graph of the evolution of $L_n$ (only four decimals of precision):

I would like to ask the following questions:

Are the calculations correct or is there a mistake in the assumptions?
How could I prove that $L_n$ is decreasing in the long term and
  there is indeed a limit? The tests show that but I am a little bit lost about
  how to demonstrate that it really is decreasing (because each step depends
  on the gaps between primes). A hint about the starting step would be great!
Initially I think this kind of recursive prime-generating function is a little bit different from the original results of Mills and towers of powers of Wright, but it might be possible that a similar idea had been explored before in recent literature. Initially I did not find such references. Are there similar solutions as the one I am devising? Any references to papers would be very appreciated. Thank you!
Comment: Well, in a nutshell (and simple words), if you look at prime distribution "from afar" (what you call "the big picture"), then it indeed looks smooth. This is a well known fact (hence the approximation that I have quoted in the previous comment). But as you zoom in, their distribution looks rather chaotic. I think that is where the prime-number "issue" lies - i.e., not in the macro level, but in the micro level.
Comment: A "concrete region" kinda makes the whole thing a little pointless IMO (i.e., this is by far not as "impressive" as Mills constant, for example). We all know that $\pi(n)\approx\frac{n}{\ln(n)}$, so we already have a rough idea (a "concrete region") of where the next prime is going to be...
Comment: Assuming that there are infinitely many pairs of twin primes, I believe that there are infinitely many values of $m$ such that $L_{m+1}>L_m>1$, hence $\lim_{n\to\infty}L_n\neq1$ (and in general does not exist).
Comment: @barakmanos that is very right indeed, thank you for making me think! Depending on the prime gaps makes this generating function not so cool as the canonicals, because it will not have a limit, so the $lim_{n\to\infty}L_n$ version of the constant will not exist. If you have time and you can wrap-up your points in an answer I would very gladly accept it as an answer!
Comment: @barakmanos thanks to your help I have been able to rethink the prime-representing function. The main point is forcing $L_n$ to be strictly decreasing. I have added an answer. If still you want to add your initial answer as I mentioned I will gladly accept it as the answer to the question. Regards!
Answer: So say that for some $C\in\Bbb{R}$, we have:
$$p_n\sim C^{(\log2)(n+3)}$$
Now:
$$L_n\sim\dfrac{\log(C^{(\log 2)(n+3)}+L_{n-1})}{\log 2^{n+3}}$$
We already know that $L_{n-1} < 1$, while $C^{(\log 2)(n+3)}$ tends to infinity:
$$L_n\sim \dfrac{\log(C^{(\log 2)(n+3)})}{\log 2^{n+3}} = \dfrac{1}{\log 2^{n+3}}\cdot \log(C^{(\log 2)(n+3)})=\\ \log(C^{\dfrac{(\log 2)(n+3)}{\log 2^{n+3}}})=\log(C^{\dfrac{(\log 2)(n+3)}{(\log 2)(n+3)}})= \log C$$
We can now say:
$$L_n \sim C \Longleftrightarrow p_n \sim e^{C^{(\log 2)(n+3)}}$$
So you'll still have some Mills-like constant involved.
Comment: very nice! thank you for that insight!
Answer: Thanks to @barakmanos I have been able to understand that due to the oscillating gaps between primes, the proposed constant $L_n$ will not be able to have a proper limit. To avoid that issue, I have restricted the conditions to force $L_n$ to be strictly decreasing, so a prime-generating function of this kind requires some more restrictions to have a constant with a limit when $n \to \infty$. Based on these two points:

The gap between the embedded primes will be strictly increasing. The first prime selected will be $11$ then $19$ (gap 8), then 29 (gap 10), then 41 (gap 12), etc.
The formula will be modified so each $n$ forces the value of $L$ to decrease on each iteration by using powers of $2$ associated to each $n$.

$$L_n=\frac{Ln(p_n+L_{n-1})}{Ln(2^{n+3})}$$

The initial status is $n=1$, $p_1=11$, $L_0=0$
So this looks like this ($16$ initial values):

Now $L_n$ is strictly decreasing, and a limit (rational or not) is assured.
The PARI/GP code to generate the constant:
\p20000;
testlimit=500;prev_gap=6;current_pr=11;L=0;for(n=1,testlimit,print("added prime p_",n,"=",current_pr,"; gap=",prev_gap);L=log(current_pr+L)/log(2^(n+3));prev_pr=current_pr;current_pr=nextprime(current_pr+prev_gap+1);prev_gap=current_pr-prev_pr;);print("n is ",testlimit," and L is ",L);

The constant now has this value for $n=500$:
$$L_{500}=0.0396890...$$

So in general the recursive process to recover $L_{n}$ and $f(n)=p_n$ from $L_{n+1}$ and $f(n+1)=p_{n+1}$ now will be:
$$L_{n}=(2^{n+1})^{L_{n+1}}-p_{n+1}$$
$$f(n)=p_{n}=\lfloor (2^{n})^{L_{n}} \rfloor$$

The following code, having $L_{500}$ calculates backwards the complete set of primes $\{p_{500}..p_{1}\}$
curr_L=L;for(n=1,testlimit,curr_n=testlimit-n+1;curr_p=floor((2^(curr_n+3))^curr_L);print("n = ",testlimit-n+1,"; current prime is ",curr_p," and is prime check = ",isprime(curr_p));curr_L=((2^(curr_n+3))^curr_L)-curr_p;);

Now it looks much more like a Mills-like constant but recursive!


How to track nested object in a MobX store

Question: Let's stay I have this myObject loaded via an API call:
myObject = {
  fieldA: { details: 'OK', message: 'HELLO' },
  fieldB: { details: 'NOT_OK', message: 'ERROR' },
}

Only details and message of each field can change. I want this object to be observable in a MobX store (which properties? to be defined below). I have a simple React component which reads the two fields from the store:
@observer
class App extends Component {
  store = new Store();

  componentWillMount() {
    this.store.load();
  }

  render() {
    return (

        {this.store.fieldA &&
{this.store.fieldA.details}
}
        {this.store.fieldB &&
{this.store.fieldB.details}
}

    );
  }
}

I read this page trying to understand what MobX reacts to, but still didn't get a clear idea. Specifically, which of the 4 stores below would work, and why?
1/
class Store1 = {
  @observable myObject = {};

  @action setMyObject = object => {
    this.myObject = object;
  }

  load = () => someAsyncStuff().then(this.setMyObject);
}

2/
class Store2 = {
  @observable myObject = {};

  @action setMyObject = object => {
    this.myObject.fieldA = object.fieldA;
    this.myObject.fieldB = object.fieldB;
  }

  load = () => someAsyncStuff().then(this.setMyObject);
}

3/
class Store3 = {
  @observable myObject = { fieldA: {}, fieldB: {} };

  @action setMyObject = object => {
    this.myObject = object;
  }

  load = () => someAsyncStuff().then(this.setMyObject);
}

4/
class Store4 = {
  @observable myObject = { fieldA: {}, fieldB: {} };

  @action setMyObject = object => {
    this.myObject.fieldA = object.fieldA;
    this.myObject.fieldB = object.fieldB;
  }

  load = () => someAsyncStuff().then(this.setMyObject);
}

Answer: All of the above will work, except for solution 2.
That because as described in Mobx docs about objects:

When passing objects through observable, only the properties that
  exist at the time of making the object observable will be observable.
  Properties that are added to the object at a later time won't become
  observable, unless extendObservable is used.

In the first solution you re-assign the object again with the properties already exist in the returned object.
In 3 and 4 you initialized the object with those 2 properties so it works.
Also I think in your component example you meant to use it like this (otherwise, it won't work in any way):
render() {
    const { myObject } = this.store;

    return (

        {myObject && myObject.fieldA &&
{myObject.fieldA.details}
}
        {myObject && myObject.fieldB &&
{myObject.fieldB.details}
}

    );
}


Why in multi-dimentional array in C/C++ a[0] is same as a?

Question: I have the following program
#include<stdio.h>

int main() {
    int a[3][3]={{1,2,3},
                {4,5,6},
                {7,8,9}};

    printf("%p\n",a);
    printf("%p\n",a[0]);
    printf("%p\n",*(a+0));
}

And it gives me the following output:
6356716
6356716
6356716

I was expecting that, given a base address such as 6356716 then *(6356716+0) would yield the value inside that location (i.e, 1).
So, if an array name is equivalent to a pointer to its first value like in above expression, printing 'a' should print the pointer to its first value i.e a[0](which itself decays to its 1st element at location 6356716). In that case, why does dereferencing not work here, and *(a+0) evaluates to
*(6356716+0)?
Comment: `C/C++ == UB` please pick one language
Comment: @pmg Nice analogy. It's just that `*(a+0)` is exactly same as `a[0]`.
Comment: Nothing in this code is actually referring to the *value* (i.e. 1). Second and third prints are equivalent.
Comment: Possible duplicate of [What is array decaying?](https://stackoverflow.com/questions/1461432/what-is-array-decaying)
Comment: it is not the same so your question is meaningless.
Comment: Imagine this: the first (`a`) points to a train... the second (`a[0]`) points to the first carriage of the train... the last (`*(a+0)`) points to the first seat in the first carriage. They all point to the "same place", but they point to different things.
Comment: Lol, yes @Eugenesh. But let that mistake go. Thanks anyway.
Comment: "... why dereferencing didn't work here ...." --> It did work.  What output were you expecting?
Comment: @chux! I was expecting 1 by evaluating *(6356716+0)!
Comment: `*(6356716+0)` attempts to add 2 integers and then de-reference the `sum` - this is not legal C and that is not what was done in the posted code.  What type of pointer was `6356716` to represent?  By answering that, the reason for the output should be clear.
Answer: a is an array of 3 arrays of 3 int. When used in an expression other than as an operand of sizeof, unary &, or _Alignof, it is automatically converted to a pointer to its first argument, which is an array of 3 int. If you correctly print this pointer, it will show the address of that array of 3 int.
a[0] is the first element in a, so it is an array of 3 int. When used in an expression, with the same exceptions as above, it is automatically converted to a pointer to its first element, which is an int. If you correctly print this pointer, it will show the address of that int.
Since an array is simply a sequence of objects stored contiguously, an array starts at the same place that its first element does. Therefore, the results of printing a and a[0] show the same address.
*(a+0) is the same as a[0], so printing it has the same result.
You should not use %u to print address. Printing pointers with %u has undefined behavior. It might appear to work in your implementation in some circumstances, but it will break in other circumstances. To print an address, use %p with a pointer converted to void * or const void *:
printf("%p\n", (const void *) a);
printf("%p\n", (const void *) a[0]);
printf("%p\n", (const void *) *(a+0));

Answer: When used in
printf("%u\n", a);
printf("%u\n", a[0]);

a decays to the pointer to the first element of a and a[0] decays to the pointer to the first element of a[0]. Equivalently, you could use:
printf("%u\n", &a[0]);
printf("%u\n", &a[0][0]);

From a object type point of view, &a, &a[], and&a[0][0] are completely different pointer types. However, if you look at the memory layout of a 2D array, you will realize that, from a purely numerical point of view, &a == &a[] == &a[0][0].
Also, "%u" is not the correct format for printing pointers. You should use "%p".
printf("%p\n", a);
printf("%p\n", a[0]);

Comment: UB:  wrong printf pointer format.  Sending the address is the same but the referenced objects are not (have different types).
Comment: @P__J__, you are right. I was addressing just the core question but I have updated the answer a bit.
Answer: First thing you need to understand is that a 2D array is treated as an array of arrays and all the elements of 2D array are stored in continuous memory locations,Now the second thing to understand is that an array name actually gives the address of first element in it.So your first printf statement printf("%u\n",a);actually gives you the address of a[0],as a[0] is the first element in this 2D array.Now your second printf statement printf("%u\n",a[0]); gives you the address of a[0][0] , because a[0] is actually the name of first array in the 2D array.Now your last printf statement is printf("%u\n",*(a+0)); is actually the way a compiler internally treats array ,it is exactly same as the second one.As from the explanation it is clear that the three statements are referring to the same address but this does not mean that they are same thing ,the first statement has a different meaning as compared to second and third as explained above.Though the three statements are giving you the address of 1,which is the first element of the 2D array.


Testing points on the closure of a union of increasing subsets

Question: Let $X$ be a topological space. Let $(S_\lambda)_{\lambda\in\Lambda}$ be a net of closed subspaces of $X$, and suppose that for all $\lambda\le\mu$, $S_\lambda\subseteq S_\mu$.
Let now
$$
x\in \mathrm{closure} \left( \bigcup_{\lambda\in\Lambda} S_\lambda \right) .
$$
Can we express $x$ as a limit of a net $(x_\lambda)_{\lambda\in\Lambda}$ where for each $\lambda$, $x_\lambda\in S_\lambda$?
Answer: No:
Consider $\beta \mathbb N$, the Stone-Cech compactification of $\mathbb N$.
Pick $ x \in \beta \mathbb N \setminus \mathbb N$.
For $n \in \mathbb N$ define
$S_n = \{1, ... n\}$, which is a closed subspace of
$\beta \mathbb N$.
$x \in \text{cl}(\mathbb N) =  \text{cl}(\cup_{n \in \mathbb N} S_n)$.
However, there is no sequence in $\mathbb N$, which converges to $x$.


Accessing to all the elements from the single member type from the struct in c++

Question: Lets say I have a following structures in c++
struct Fruit
  {
     std::string name, description;
  }

and
struct Fruit Fruits[]
  {
    {"orange"," Orange is a hybrid of ancient cultivated origin, possibly between pomelo and mandarin. "},
    {"apple", " Apple is the pomaceous fruit of the apple tree, species Malus domestica in the rose family. "},
  };

My question is, how can I access to all the elements of the single member type of the one struct in c++, or in this case how can I list all the elements of the member type name from the struct Fruit?
Any help would be appreciated. Thanks in advance.
Comment: That isn't real code. At all.
Comment: What other settings and suggestions would you introduce for this issue, @KerrekSB?
Comment: I think Kerrek is pointing out that your "Fruits" struct isn't really a struct. You are trying to represent a collection of fruits where the first is initialized as orange, and the second is initialized as apple. Your fruits would really be an array of Fruit, or a std::vector of Fruit, or a std::map of Fruit, etc. Where in that array/vector/map you start adding actual instances of a fruit -- similar to Kerrek's example below.
Comment: Oh, I forgot to add [] for the
`struct Fruit Fruits[]`
Comment: I was thinking to store them in a struct using two member types name and description, in which later on I will call that struct to form my way of lets say stacked fruits instances, by calling a Fruit struct in another struct, Fruits. So, each element of the struct Fruits holds two member types of the Fruit struct. My question was, can I somehow retrieve all the elements of the one membertype using this way of building an array or not.
Answer: Perhaps you need a dynamic array of pears:
#include <vector>
#include <string>
#include <utility>
#include <iostream>

std::vector<std::pair<std::string, std::string>> fruits {
   { "Apple", "Yum" },
   { "Tomato", "Yuck" }
};

You can iterate this:
for (auto it = fruits.cbegin(), end = fruits.cend(); it != end; ++it)
{
    std::cout << "Fruit: " << it->first << ", Description: " << it->second << "\n";
}

Or use the snazzy new range-for-loop:
for (auto const & p : fruits) { /* ... p.first etc ... */ }

Comment: It's an interesting proposal, but is it possible that I somehow access to all the elements of the member type in the way I posted.
Answer:
how can I list all the elements of the member type name from the struct Fruit?

#include <iostream>

struct Fruit
  {
     std::string name, description;
  };

struct Fruit Fruits[] =
  {
    {"orange"," Orange is a hybrid of ancient cultivated origin, possibly between pomelo and mandarin. "},
    {"apple", " Apple is the pomaceous fruit of the apple tree, species Malus domestica in the rose family. "},
  };

int main () {
  for(auto& fruit : Fruits ) {
    std::cout << fruit.name << "\n";
  }
}

Comment: This is exactly what I was searching for! :) Thank you.


NSDateFormatter dateFromString always returns (null)

Question: I am trying to use NSDateFormatter's dateFromString but it always returns (null)
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSLog(@"%@", [dateFormatter dateFromString:[[myArray objectAtIndex:x] objectForKey:@"finish"]]);

The date in question is this: 2017-05-15 5:00:00 PM
But it always returns (null)
I have tried adding these:
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
[dateFormatter setFormatterBehavior:NSDateFormatterBehaviorDefault];

But still returns null.
Please Help!
Comment: Please compare the date string with the date format. It clearly doesn't match. There is no equivalent of hours, minutes, seconds and AM/PM
Comment: Unrelated but use modern Objective-C syntax: `myArray[x][@"finish"]` instead of `[[myArray objectAtIndex:x] objectForKey:@"finish"]`
Answer: You dateFormat is wrong. You need to use:
[dateFormatter setDateFormat:@"yyyy-MM-dd h:mm:ss a"];

Comment: Actually it's `h:mm:ss`
Comment: It would be very rare to combine `H` (24-hour) and `a`
Comment: @vadian true xD my bad.


Fetching value from URL, Commentics

Question: I have a little problem with programming.
I'm trying to make a website in which people could leave their humble opinions about each other.
I was looking into one page, http://numeris.info and they seem to use very simple but also very good which would suit my needs. basically, you type in after / number and it gives info about it from database, for ex :myawesomepage.co.uk/1234567890
I'm using Commentics review system if that helps.
it fetches all data with identifier

$cmtx_identifier = 'x';

Is it possible somehow to fetch the digits from URL after slash and put them instead of x ?
and, if the digit doesnt exist in system, is it possible to 'create' a page?
Sorry if its to many questions, I'm just trying to learn programming, and many thanks
Comment: Use a rewrite rule on the server to change it to a URL parameter.
Answer: Your .htaccess
RewriteEngine On
RewriteRule ^([0-9]+)/?$ page.php?id=$1 [QSA,L]

Your page.php
<?php
$id = (int) $_GET["id"];
var_dump($id)

Comment: Well I got the part with ?id= , it loads a page. But how to make it to create a page if it doesnt exist?
for ex:
?id=1 exists, ok lets load it from mysql using id 1
?id=500 doesnt exist, ok lets load the comment system and create a new id
''
this is the script to load comment system.
Comment: You have to add a condition if the first of your page to check if it exists or not, if not redirect to 404 page

Fetching value from URL, Commentics


How do I find the sum of $\frac{\cos(n)}{n!}$?

Question: I am having a hard time to calculate the sum of $$\sum_{n\geq 0} \frac{\cos(n)}{n!}$$ I don't know how to approach this. Could you give any thints for this?
Comment: $\cos n = \operatorname{Re} ( \cos n + i\sin n)$
Comment: I'm surprised you're dealing with $ \cos n $ for integer $ n $ - usually arguments to cosine are either continuous or integer multiples of $ \pi $ - it's unusual, say, to run into $ \sin 1 $. Is this really the problem you meant to ask?
Comment: @QuantumFool, expressions such as $\sin n$ and $\cos n$ for $n \in \Bbb{Z}$ aren't that uncommon when dealing with infinite series in an academic setting.
Comment: @QuantumFool, expressions such as $\sin n$ and $\cos n$ for $n \in \Bbb{Z}$ aren't that uncommon when dealing with infinite series in an academic setting.
Answer: \begin{align}
\sum\frac{\cos n}{n!}& =\Re\sum\frac{e^{in}}{n!} \\
& = \Re e^{e^i}\\
& = e^{\cos 1} \cos(\sin 1)
\end{align}
Comment: nice solution! +1)
Comment: Short and clear! Perfect, thank you!


Due diligence preventing leaks between condos

Question: I wish to expand the size of my bathroom in my condo and will require the approval of my condo association.  Currently, all bathrooms in the building are stacked vertically - so if a leak occurs it will leak into another bathroom.  If I take a portion of the adjoining closet then any future leak could occur into the dry closet below.
Besides installing a floor drain and correctly pitching the floor. Are there techniques that can be used to direct a future leak towards the existing bathroom area?
Are there secondary barriers that can installed in between the units to direct leaks?
What due diligence can I present to the Condo Association to show I am doing everything possible to minimize any impact of future leaks?
Comment: I don't know if it will appease your condo association, but there's no guarantee that a leak will appear in the room directly below anyway. Water can run along beams, pipes, etc. and show up almost anywhere. The bathrooms were almost certainly built on top of each other to ease construction, not for leak control.
Answer: I am not sure how technical your board members are but I think an easy thing to do is waterproof the entire bathroom.  I feel like I am giving you some Holmes advice (totally overdoing something) but you can lay a Kerdi membrane over the entire floor and up 4-6 inches on the wall and of course your whole shower area.  You could virtually take a bath in your entire bathroom if this was installed correctly without a leak.
Now as Henry pointed out the plumbing can leak almost anywhere.  So maybe they want all of the plumbing along a wall or two.  If these are the things they want (I wouldn't bring it up) then you could configure your layout plus the waterproofing to hopefully meet their standards.  If your association is like most then it is probably more of how you get along with everyone vs. what you are looking to do.


A question of Cor2.14 on Hatcher's textbook

Question: Let  $\overset{\sim}{H}_{i} (X)$ be a reduced homology. I do not catch a precise reason why

$\overset{\sim}{H}_{i}(S^n)=0$ holds if $ i \neq n $.

holds.
According to the textbook, mathematical induction is used and using the prop2.6, prop2.8

Prop2.6 Corresponding to a decomposition of a space $X$ into its path component $X_{\alpha}$ there is an isomorphism of $H_n(X)$ with
the direct sum $\bigoplus _{\alpha} H_n(X_{\alpha}). $
prop2.8 If $X$ is a point, then $H_n(X)=0$ for $n>0$ and $H_0(X)=
> \mathbb{Z} $

Here is my sketch :
if $n=0$, it is true because $0= H_{i}(S^0)=\overset{\sim}{H}_{i} (S^0)$. And then suppose $H_{i}(S^{k})=0  $ holds when $n=k$. Then, it seems to finish when $n=k+1$ holds. But I cannot apply  prop2.6 to given proof.
According to my guess, $S^{k+1}$ seems to decompose some path components. Thus, $\overset{\sim}{H}_{i}(S^{k+1})=\overset{\sim}{H}_{i}(*) \oplus \overset{\sim}{H}_{i}(S^k) $ and, since both components expected to be $0$ (the first component is unknown but cleary should be $0$ and the second component is clearly $0$ from the previous assumption)
Furthermore, I have also a question about why Prop2.8 is used during the proof. This seems to be needed when I try to verify the case $n=0$, but I don't see why this proposition is used.
Even though my sketch seems to be thoroughly wrong, this is the trial that I do my best. Anyway, I want to know why $\overset{\sim}{H}_{i}(S^n)=0$ holds if $ i \neq n $ holds.
Comment: $\Bbb S^n$ is connected, hence consists of precisely one path component. You can however write it as the union of two hemispheres, which leads to an application of Mayer Vietoris…
Answer: In Hatcher's proof sketch, Propositions 2.6 and 2.8 are for proving the $n=0$ case. First, we need to recognize that $S^0$ is just a set of two points. Applying Prop 2.6 (splitting homology by path components) to it tells us that $H_i(S^0) = H_i(\mathrm{pt}) \oplus H_i(\mathrm{pt})$. Proposition 2.8 tells us the homology of a point, so $H_0(S^0) = \mathbb{Z}^2$ and $H_i(S^0) = 0$ when $i\neq 0$. Finally following Hatcher's comments after his definition of reduced homology groups, you can see that $\tilde{H}_0(S^0) = \mathbb{Z}$.
For the induction step, you apply Theorem 2.13 to the pair $(D^n, S^{n-1})$ as Hatcher specifies. The key ideas are that if you quotient out the boundary of a disc, you get a sphere, and that a disc is contractible. This is a common proof technique in algebraic topology. Constructing an LES involving some contractible spaces tells us that the corresponding terms in the LES are zero. Here the LES for the pair $(D^n, S^{n-1})$ looks like
$$
\cdots\to \tilde{H}_i(D^n)\to \tilde{H}_i(D^n/S^{n-1})\cong \tilde{H}_i(S^n) \to \tilde{H}_{i-1}(S^{n-1})\to \tilde{H}_{i-1}(D^n)\to\cdots
$$
Notice that since $\tilde{H}_i(D^n)=\tilde{H}_{i-1}(D^n)=0$, the LES just breaks up into isomorphisms $\tilde{H}_i(S^n)\to \tilde{H}_{i-1}(S^{n-1})$. This is the induction step.
Answer: Hint use Mayer Vietoris on the decomposition of $\Bbb S^n$ into the upper and lower hemispheres $\Bbb D^n_+$ and $\Bbb D^n_-$. Note that the hemispheres are contractible (homotopy equivalent to the point) and intersect in the equator, a $\Bbb S^{n-1}$. So apply induction and your theorem 2.8.
Edit Of cause there are several ways to deduce the desired result. According to Elliot Yu's answer Hatcher uses excission, because Mayer Vietoris is only introduced later. I did not check that, apologies for possible inconveniences.
Comment: Thanks for pointing this out to me! I find Mayer Vietoris easier to work with than excission and thought it would be introduced earlier, but failed to check this assumption…
Comment: Sorry I deleted my comment before you had a chance to post the response. I saw your edit as soon as I posted, so I removed the comment since it became clear that you realized what I was going to say.
Comment: No worries. Anyway thanks for the clarification :)


Where is Peach after I finished Super Mario Galaxy 1 or 2?

Question: I finished the story in Super Mario Galaxy 1 and 2 and rescued Peach. I often play with my 5 year old daughter, who is very happy that Peach is safe again. However, she is nowhere to be seen! Even stranger, we still get letters from Peach that say that she is far away but so happy that Mario is coming to rescue her. But we already did!
Am I missing something? Is Peach anywhere to be found in the Observatory/Starship Mario?
This probably sounds like a silly question but my daughter would really like to see Peach so I hope that she is hidden somewhere.
Answer: The letter text remains the same before and after the rescue. Peach is safe but far away again (in her castle). I don't think the letter speaks of "rescue" though.
Kudos to your daughter for appreciating the story line. I am huge Mario fan myself and also think in those terms. It makes the game more enjoyable.
Alas, I don't think there is a way to see Peach after rescuing her. I recommend you tell your daughter that Peach is safe in her castle since Bowser has been defeated (for a while). Mario is free to pursue a few remaining adventures after finishing his main task.
(I agree it would be great if Peach joined Mario as a character he could talk to after rescue. Nintendo really missed an opportunity here.)
Comment: Thank you! It's sad, but now at least we can stop looking.
Answer: As already answered, Peach is, alas, safely out of view.
However, your daughter may be interested in a storyline wherein Mario, Peach, Rosalina, and a whole bunch of other characters make it back to the Mushroom Kingdom to race against each other in Mario Kart Wii.


What is the Atlas's head?

Question: I keep hearing that the Atlas's head's hitbox is actually the left eye. Whose left is that though? Is it the attacker's left or the Atlas's left?
Comment: Typically, mech component locations are given from the Mech's perspective, so I'd assume it's the Atlas's left eye, but I haven't verified that. Related note: The damage display for your currently targeted enemy has right and left flipped for convenience.
Comment: I got rather close to an Atlas's head today and noticed that the left eye (i.e. the one on the right for somebody looking at it head-on) had some extra graphical detail - fairly sure that's it.
Answer: While playing yesterday I noticed that the Atlas cockpit's window isn't symmetrical:

As you can see, the right side is higher than the left.
This parallels looking at an Atlas from the outside:

As you can see, the eyes are both higher in the middle, so apparently the cockpit's in the Atlas's left eye, or the right from an onlooker's perspective, like the commenters said.

What is the Atlas's head?


$\exists x (P(x) \to \forall y P(y))$

Question: Prove $\exists x (P(x) \to \forall y P(y))$.
Let x = y. Suppose P(x) is true. Let y be arbitrary. Since P(x) is true, it must be that P(y) is true. Since y was arbitrary, we can conclude that $\forall y P(y)$. Therefore $P(x) \to \forall P(y)$. Since $P(x) \to \forall P(y)$, $\exists x (P(x) \to \forall y P(y))$.
Is my proof correct?
I'm not sure if I'm dealing with the $\forall y$ correctly. If the theorem were $\exists x (P(x) \to P(y))$, I think I would have a good handle on things.
Comment: @copper.hat I thought something similar at first, but this doesn't in fact disprove the implication statement. The statement "If $2$ is odd then every integer is odd" is in fact true.
Comment: Another case of the [drinker's principle](http://en.wikipedia.org/wiki/Drinker_paradox) - P is either always true, in which case x is arbitrary, or there is some x where P(x) is false, in which case pick one such x. However y cannot be "arbitrary" - it must be all values. The trick here is that  implies anything.
Comment: @GPerez: Thanks for catching another of my egregious mistakes. I should know better...
Comment: If you can't convince yourself that a proof is correct, then it is not correct, even if you got lucky and picked the correct words.  And in this case, phrases like "Let $x = y$ and "Suppose $P(x)$ is true" and "since $y$ was arbitrary" (even after you latched it to $x$ ... ?) seem pretty incoherent.  I think it would be better if you started with something more basic than the drinker's paradox, and come back to this problem after you are comfortable with the basics of implication and quantification.
Answer: Like you, we give a semantic  (model-theoretic) argument. There are also syntactic arguments, where the details depend  very much on the setup (axioms, rules of inference).
Let $L$ be our formal language.  We will show that the sentence $\exists x(P(x)\to \forall y P(y))$ is true in any $L$-structure $M$.
Suppose first that $\forall yP(y)$ is true in $M$. Then whatever $x$ we choose, the sentence $P(x)\to\forall y P(y)$ is true in $M$.  So $\exists x(P(x)\to\forall yP(y))$
Suppose on the other hand  that $\forall y P(y)$ is not true in $M$. Then there is an $x$ for which $P(x)$ is false. And then again, because of the truth table of implication, $\exists xP(x)\to\forall y P(y))$ is true in $M$.
Remark: The argument in the OP is no correct. You are letting $x=y$. What is $y$?  We want to show that there exists an $x$ such that for  $P(x)\to \forall y P(y)$. So the $x$
has to be universal, it has to work for all possible values of $y$.

$\exists x (P(x) \to \forall y P(y))$


Creating a QuickLook plug-in for text files in Xcode 4.1

Question: Background
I'm learning Objective-C and Cocoa, and I thought creating simple programs to answer my needs would be a nice thing. I already have a solid .NET C# background, some Python knowledge, and a little of C.
One of my "simple first app" I tried to do is a simple QuickLook plug-in for Arduino's sketch files. I thought it would be a simple task to accomplish since these files are plain text C-like scripts, the only "different" thing is they have a .pde extension.
I uploaded the project on GitHub at ArduinoQuickLook as a reference (the first commit contains a vanilla Xcode 4.1 QuickLook plugin-project).
What I found
Looking around the net I found these resources:

QLStephen
QLColorCode
Introduction to Quick Look Programming Guide

What are my problems

Both of them use GeneratePreviewForURL.m and GenerateThumbnailForURL.m files, but when I created the project in Xcode 4.1 it created GeneratePreviewForURL.c and GenerateThumbnailForURL.c (note .c instead of .m).
Both QLStephen and QLColorCode use #import <Foundation/Foundation.h> in their GeneratePreviewForURL.m and GenerateThumbnailForURL.m files, but if I try to #import it it yields to many errors. (Maybe because my files are .c instead of .m?)
It's not clear to me how I declare which files my plug-in will handle, I understood I need to change ArduinoQuickLook/ArduinoQuickLook-Info.plist (row 14) but what I have to write there? Something like cc.arduino.pde?
Answer: This tutorial on creating a Quicklook plugin explains things nicely, but to summarise:
Point 1 and 2 are related - for some strange reason the Quicklook plugin template only contains .c files - as such, importing the Obj-C Foundation.h header causes errors.
You should just be able to rename the files from .c to .m and it will work as expected.

It's not clear to me how I declare which files my plug-in will handle

You need to do two things - one is say which UTI (Uniform Type Identifier) your plugin handles (e.g cc.arduino.pde), by changing the line you mention:
<array>
    <dict>
        <key>CFBundleTypeRole</key>
        <string>QLGenerator</string>
        <key>LSItemContentTypes</key>
        <array>
            <string>cc.arduino.pde</string>
        </array>
    </dict>
</array>

...but you also have to describe that UTI (mostly so it can map the file-extension to that UTI)
There are two slightly different ways to declare UTI's, [as "Declaring New Uniform Type Identifiers"] describes:

Your UTI declarations must be either imported or exported:

An exported UTI declaration means that the type is available for use by all other parties. For example, an application that uses a proprietary document format should declare it as an exported UTI.
An imported UTI declaration is used to declare a type that the bundle does not own, but would like to see available on the system. For example, say a video-editing program creates files using a proprietary format whose UTI is declared in its application bundle. If you are writing an application or plugin that can read such files, you must make sure that the system knows about the proprietary UTI, even if the actual video-editing application is not available. To do so, your application should redeclare the UTI in its own bundle but mark it as an imported declaration.

For a Quicklook plugin, you probably want an "imported" UTI declaration, in which you would add something like this to your Info.plist:
<key>UTImportedTypeDeclarations</key>
<array>
    <dict>
        <key>UTTypeIdentifier</key>
        <string>cc.arduino.pde</string>
        <key>UTTypeReferenceURL</key>
        <string>http://www.example.com</string>
        <key>UTTypeDescription</key>
        <string>Arduino PDE file</string>
        <key>UTTypeConformsTo</key>
        <array>
            <string>public.c-source</string>
            <string>public.text</string>
        </array>
        <key>UTTypeTagSpecification</key>
        <dict>
            <key>public.filename-extension</key>
            <array>
                <string>pde</string>
            </array>
        </dict>
    </dict>
</array>

Answer: Here is the source for a project that provides QuickLook for Processing and Arduino .pde files: https://github.com/kroko/ProcessingQL  I know this question is a year old, but this project might be helpful for anyone else attempting this.


Web Service Unit Testing

Question: This is an interesting question I am sure a lot of people will benefit from knowing.
a typical web service will return a serialized complex data type for example:
<code><orgUnits>
 <orgUnit>
     <name>friendly name</orgUnit>
 </orgUnit>
 <orgUnit>
     <name>friendly name</orgUnit>
 </orgUnit>
</orgUnits>
</code>
The VS2008 unit testing seems to want to assert for an exact match of the return object, that is if the object (target and actual) are identical in terms of structure and content.
What I would like to do instead is assert only if the structure is fine, and no errors exist.
To perhaps simplify the matter, in the web service method, if any error occurs I throw a SOAPException.
1.Is there a way to test just based on the return status
2. Best case scenario would be to compare the doc trees for structural integrity of target and actual, and assert based on the structure being sound, and not the content.
Thanks in advance :)
Answer: I think that this is a duplicate of WSDL Testing
In that answer I suggested SoapUI as a good tool to use
Answer: An answer specific to your requirement would be to compare the serialized versions(to XML) of the object instead of the objects themselves.
Approach in your test case

Lets say you are expecting a return like expected.xml from your webservice .
Invoke service and get an actual Obj. Serialize that to an actual.xml.
Compare actual.xml and expected.xml by using a library like xmldiff(compares structural /value changes at XML level).
Based on the output of xmldiff determine whether the webservice passed the test.

Web Service Unit Testing


Become friendly after being discovered as a werewolf

Question: Recently, I was playing The Elder Scrolls V: Skyrim vanilla on xbox 360, and while I was playing, I turned into a werewolf in front of people in Riverwood and it caused them to become hostile.
I don't want to kill them. How can I make them friendly again without loading the last save? A lot of my precious items would disappear if I load the last save game.
Comment: If I remember correctly, all you get is a bounty for transforming into a werewolf. Try talking to the guards and see if you can pay off your bounty.
Answer: Transforming into a werewolf is a crime like any other; it has no lasting consequences and can be paid off in the same way: either by paying your bounty, or by serving jail time.
Comment: You need to leave the area though.  The bounty is high enough that you will not be able to yield to a hostile guard.  You can then pay the bounty somewhere else that isn't hostile to you on sight.


New condenser fan motor burned out

Question: AC technician replaced my condenser fan (through a home warranty service). The new fan worked for 5 min and stopped working after that. the fan motor was extremely hot (180F or more)
The old fan motor was 1.4 A 240 V and 1/4 hp. the new motor is also of the same configuration. the only thing i missed out is the RPM. i don't remember the RPM of the old motor and the new motor RPM is 1040. The AC technician took away the old motor and recycled it.
What can be the problem here?
I looked in some forums that the RPM mismatch can overheat the motor and damage it. i have no way of knowing the RPM of the original motor. I looked in manufacturer manual and there is no mention of it. is RPM matching that important?
http://www.nordyne.com/Literature/423a.pdf [ My unit is maytag DS3BD-036K ]
Very similar to question What could cause a replacement A/C condenser fan motor to only run for 3 minutes?
Comment: @David It doesn't matter if the system is out of warranty. If a) the tech used the wrong part, and b) it failed because he used the wrong part, and c) he reasonably should have known that the wrong part would cause failure, then the tech should be responsible for replacing the part.
Comment: Did the tech do any other work to the system, like trying to figure out why the original motor died?  If the problem that killed the old motor was not corrected, it's likely that the new motor was killed by the same thing.
Comment: He didn't did any other testing. I think the guys these house warranty companies hire are really lousy. what are the possible causes of such a problem? what can be those tests?
Comment: Faulty replacement out of the box? Was it spinning the correct way when they were done? What other problem could it be than a chattering contractor, which it really shouldn't mind?
Comment: @Mazura, Maybe the motor was faulty but it did ran for 5 min. So i believe there is some incompatibility in the new motor rather than its just faulty. Does RPM can constitute to this problem
Comment: Why are you not calling the warranty company first?
Comment: @Bryce out of warranty
Comment: RPM should only make a difference with the systems performance, i.e. how fast air moves through the condenser. There should be a label on the blade, stating the motor speed it's designed for.
Comment: "replaced my condenser fan "   Was the fan replaced, or just the motor on the existing set of fan blades?
Comment: @User58220 Just the motor was replaced and it have previous set of blades.
Comment: The warranty lasts more than 5 minutes, even on a repair.
Answer: Does RPM effect motor life? More than I thought it would.

"if you change an 825 motor and put in a 1075, your HP load will move from 1/6th to 1/2... with the same blade. and the noise level will go up dramatically in the unit."-vstech, HVAC Talk
"Plus you're probably going to eat a few motors in the process."-Six

Five minutes sounds about right when you ask a 1/4hp motor to give you 1/2hp.
Comment: What requires the HP and the RPM load to have to be exact? Is it the blades? The capacitor? If just looking purely from a electrical standpoint, changing to the correct cap is the only thing I can think of unless the control board is also part of the equation.
Answer: The tech wired the motor incorrectly. May have overpowered causing high heat; tripped thermal overload.
Seen this many times.

New condenser fan motor burned out


Embedding a media player in a website using HTML

Question: What I want to do is to embed music files within a website (Have something a'la little mp3 player on the site). I want the audience to be able to play, stop etc the songs by using custom made controllers.
How do I code those custom made buttons so that they all work fine?
Answer: You can use plenty of things.

If you're a standards junkie, you can use the HTML5 <audio> tag:

Here is the official W3C specification for the audio tag.
Usage:
<audio controls>
 <source src="http://media.w3.org/2010/07/bunny/04-Death_Becomes_Fur.mp4"
         type='audio/mp4'>

 <source src="http://media.w3.org/2010/07/bunny/04-Death_Becomes_Fur.oga"
         type='audio/ogg; codecs=vorbis'>

Your user agent does not support the HTML5 Audio element.

</audio>

jsFiddle here.

Or, if you want to support older browsers, you can use many of the free audio flash players available. Such as:

Dewplayer
MP3 Player (boring name... right? :) )
Website Music Player (even more boring... right?)
Zanorg Player

Note: I'm not sure which are the best ones, as I have never used one (yet).

UPDATE: As mentioned in another answer's comment, you are using XHTML 1.0 Transitional. You might be able to get <audio> to work with some hack.

UPDATE 2: I just remembered another way to do play audio. This will work in XHTML!!! This is fully standards-compliant.
You use this JavaScript:
var aud = document.createElement("iframe");
aud.setAttribute('src', "http://yoursite.com/youraudio.mp4"); // replace with actual file path
aud.setAttribute('width', '1px');
aud.setAttribute('height', '1px');
aud.setAttribute('scrolling', 'no');
aud.style.border = "0px";
document.body.appendChild(aud);

This is my answer to another question.

UPDATE 3: To customise the controls, you can use something like this.
Comment: @Vetaxili This question might help you: http://stackoverflow.com/questions/7638754/html-5-audio-tag-custom-controls
Comment: Do you know how I could customise the controller buttons?

P.S. I think 'MP3 Player' name is more boring than 'Website Music Player' :-P
Comment: I believe your answer is the one that I am looking for and will work. I have to go out now but I definitely will let you know whether it solved my problem. :-)
Comment: @Vetaxili Which method works?
Comment: Update 2 may be fully standards compliant, for whatever that's worth, but it doesn't play in Chrome.
Comment: @AnishGupta You don't know but you saved a lot of lifes.
Answer: Definitely the HTML5  element is the way to go. There's at least basic support for it in the most recent versions of almost all browsers:
http://caniuse.com/#feat=audio
And it allows to specify what to do when the element is not supported by the browser. For example you could add a link to a file by doing:
<audio controls src="intro.mp3">
   Introduction to HTML5 (10:12) - MP3 - 3.2MB
</audio>

You can find this examples and more information about the audio element in the following link:
http://hacks.mozilla.org/2012/04/enhanceyourhtml5appwithaudio/
Finally, the good news are that mozilla's April's dev Derby is about this element so that's probably going to provide loads of great examples of how to make the most out of this element:
http://hacks.mozilla.org/2012/04/april-dev-derby-show-us-what-you-can-do-with-html5-audio/
Comment: If you want to customize the controls of the player you could have a look at an explanation on how to do it [here](http://terrillthompson.com/blog/32)
Answer: Here is a solution to make an accessible audio player with valid xHTML and non-intrusive javascript thanks to W3C Web Audio API :
What to do :

If the browser is able to read, then we display controls
If the browser is not able to read, we just render a link to the file

First of all, we check if the browser implements Web Audio API:
if (typeof Audio === 'undefined') {
    // abort
}

Then we instanciate an Audio object:
var player = new Audio('mysong.ogg');

Then we can check if the browser is able to decode this type of file :
if(!player.canPlayType('audio/ogg')) {
    // abort
}

Or even if it can play the codec :
if(!player.canPlayType('audio/ogg; codecs="vorbis"')) {
    // abort
}

Then we can use player.play(), player.pause();
I have done a tiny JQuery plugin that I called nanodio to test this.
You can check how it works on my demo page (sorry, but text is in french :p )
Just click on a link to play, and click again to pause. If the browser can read it natively, it will. If it can't, it should download the file.
This is just a little example, but you can improve it to use any element of your page as a control button or generate ones on the fly with javascript... Whatever you want.
Answer: I found the that either IE or Chrome choked on most of these, or they required external libraries. I just wanted to play an MP3, and I found the page http://www.w3schools.com/html/html_sounds.asp very helpful.
<audio controls>
  <source src="horse.mp3" type="audio/mpeg">
  <embed height="50" width="100" src="horse.mp3">
</audio>

Worked for me in the browsers I tried, but I didn't have some of the old ones around at this time.
Answer:

      Automatically play music files on your website when a page loads

  <embed src="YourMusic.mp3" autostart="true" loop="true" width="2" height="0">
  </embed>

Answer: If you are using HTML 5, there is the <audio> element.
On MDN:

The audio element is used to embed sound content in an HTML or XHTML document.  The audio element was added as part of HTML5.

Update:
In order to play audio in the browser in HTML versions before 5 (including XHTML), you need to use one of the many flash audio players.
Comment: Sorry, I forgot to mention. I have to use XHTML 1.0 Transitional.

Do you know how I would have to code the controllers? So that the custom ones can be used rather that default ones?
Comment: @Vetaxili - small detail, eh? Please _edit_ your question and add this detail.


How to traverse a tree with only one line? (python, tree traversal)

Question: For a binary tree, we can traverse it in one line just like this (inorder, preorder, postorder is all ok):
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

# this is a preorder traversal with one line:

class Solution:
    def preorderTraversal(self, root) -> List[int]:
        return [] if root is None else [r.val] + self.preorderTraversal(r.left) + self.preorderTraversal(r.right)

For a tree that has multi-child in its node, how to complete the traversal work in one line?
I think list comprehension is a possible method, but I cannot complete the work in one line.
"""
# Definition for a Node.
class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children
"""
class Solution:
    def preorder(self, root: 'Node') -> List[int]:
        if root is None: return []
        ans = [root.val]
        [ans.extend(x) for x in [self.preorder(child) for child in root.children]]
        return ans

# This is a normal traversal:
# class Solution:
#     def preorder(self, root: 'Node') -> List[int]:
#         if root is None: return []
#         ans = [root.val]
#         for child in root.children:
#             ans += self.preorder(child)
#         return ans

Comment: Specifying the result a list is somewhat restricting.
Answer: Use a list comprehension to gather the traversal of all the root's children, regardless of how many children there are.
class Solution:
    def preorderTraversal(self, root) -> List[int]:
        # Original hard-coded approach for binary trees
        # return [] if root is None else [r.val] \
        #   + self.preorderTraversal(root.left) + self.preorderTraversal(root.right)

        # Generalized approach for binary trees
        # return [] if root is None else [r.val] \
        #   + [y for child in [root.left, root.right] for y in self.preorderTraversal(child)]

        # Generalized approach for a tree with arbitrary children per node
        return [] if root is None else ([root.val]
          + [y for child in root.children for y in self.preorderTraversal(child)])

Answer: It could work like this:
class Solution:
    def preorder(self, root):
        return [] if root is None else [root.val] + [value
            for child in (root.children or [])
                for value in self.preorder(child)]

The idea is that list comprehension replaces a repeated call to append, not to extend. The non-comprehension code, that maps to the above list comprehension version, is:
class Solution:
    def preorder(self, root):
        if root is None:
            return []
        res = [root.val]
        for child in (root.children or []):
            for value in self.preorder(child):
                res.append(value)
        return res


How does the hone angle of a glass cutter affect glass being cut?

Question: I need a glass cutter that can cut up to 1/2" inch plate glass. I heard the cutter's hone angle is very important, but I'm not sure what does that mean. Does 120 degrees better than 140 or the other way around.
I search through Amazon and eBay for this cutter but couldn't find any reputable ones. Can anyone recommend one from real word experience? I won't be doing a lot of projects with it but I definitely want to get a good one and use it for long long time.
My first use for this cutter will be to cut off 3 inches on a 70" x 42" x 1/2" table top along the short side.
Comment: You need to be certain it's not tempered glass which cannot be cut.
Comment: Yes, it's not tempered because one of the corners is broken and the edge is very sharp.
Answer: Glass Cutting
It's not uncommon for thicker glass be annealed, not tempered, for a table top.  This is due to the amount of force required to break it.
From what I've been told growing up around a glass shop and working in the industry for a number of years, the reason glass cutters work is that glass, stone, etc will always break at the greatest point of stress.
When you apply pressure to the surface of the glass with a glass cutter you are crushing the surface under the wheel which causes heat.  Oiling the wheel on your glass cutter will help maintain this heat evenly for a longer period of time.  You need to break the glass along your score before it cools in order to get the most reliable break.
Thick glass, 1/2" and greater is very difficult to cut even for the very experienced.  It also takes a much greater force to break after scored.  If this is your first attempt at cutting glass I would recommend getting a few scrap pieces of thinner material and practicing on those to get the feel for scoring and breaking the glass.  The thicker the glass the harder it becomes to cut off a small amount.  Even 3/8" can commonly break roughly and required a belt sander to polish the edge smooth.  Breaking 3" from a 1/2" thick piece of glass will be difficult and I would personally opt for a wet saw.
Also, any time you cut glass the edges will become sharp.  Be sure to use sandpaper to smooth the edges, called a seam, in order to help prevent cuts.
Glass Cutters
As far as cutter brands, I prefer Silberschnitt because the brass has a nice weight to it and I've grown accustomed to it.  Fletcher is probably the most common brand I've seen from shop to shop.  Someone that cuts glass daily is more likely to go with a cutter that is self oiling and is filled in the end.
The cheaper "hobby" cutters do the job just as well.  The most important thing is the wheel.  A carbide wheel will last you longer, but for limited usage a steel wheel will suffice.  If you opt for one of these types of cutters be sure to rub 3-in-1 oil on the wheel prior to scoring the glass.
A hone angle of 140° is the most common.  After enough experience 140° is easy enough to turn when needed, but broad enough to be effective for 1/4" or 3/8".  I've used it for glass with a thickness up to 3/8".  A hone angle of 154° is what is used more commonly for greater thicknesses.  This angle will give a broader score allowing for more surface stress distributed along the same line allowing for a more reliable break.  A 120° angle is more often used in artwork and difficult pattern cuts.  A more acute angle is easier to work with and what you want majority of the time.  The greater angle is more difficult to work with but necessary to control a break on thicker glass.
Comment: The score is a stress riser, glass breaks by fracture propagation from the bottom of the score and water dampening the score can cause the propagation rate to increase significantly due to a molecular debonding effect.
Comment: "glass fracture propagation" would be a good place to start. The best I read was an article "The Fracturing of Glass" in Scientific American Journal Volume 257, Issue 6. Unfortunately, I don't have access to their website to verify if this was the exact article.
Comment: @FiascoLabs I was always curious of the science behind it.  What is a general term I can search to research the physics of it?
Answer: I have a TOYO custom grip super cutter. I've had several different types and brands of cutter and this is by far the best fitting and cutting cutter I have ever used. They are around $38 but its worth it. Hope I could help :)


export SWT_GTK3=0 on terminal, does it effect your system?

Question: This question is related to my other question : Full dark theme for eclipse Luna in Ubuntu 14.04
So, i should run export SWT_GTK3=0 on a sh script for eclipse, but i mistakenly run it from my ubuntu's terminal.
I dont feel something changed for now, but i would like to make sure my system will be OK since i will need it in the near future.
Does running export SWT_GTK3=0 dangerous?
What does it do?
How to reset SWT_GTK3 to its default value?
Thanks  a lot for your time.
Answer: If the only thing you did was running export SWT_GTK3=0 then you did nothing permanent. What the command does is to set an environment variable SWT_GTK3 and set its value to 0 for that terminal session only. If you close the terminal window and open a new one it will be gone or reset.
If you want to unset it in the current terminal window you can also do: unset env SWT_GTK3.
If you want to see the current value of an env. variable: echo $SWT_GTK3 or for example to see your current PATH variable echo $PATH.
Comment: This, except that it sets its value to 0, not 3
Comment: Thanks a lot.@tigerjack89 Thanks, what do you mean? So if i run export SWT_GTK3=0, it will be permanent?
Comment: @BlazeTama no, I just pointed out that the value of the variables `SWT_GTK3` is actually 0, not 3 as suggested by Hami. Also, the export is not permanent: it marks a variable as "to be exported", so all the child programs of the parent program can see that environment variable. In your case, it is visible only to eclipse if you run it in the same shell. Indeed, if you run `echo $SWT_GTK` in the same shell where you execute the `export`, it returns 0; if you open another shell and type the same command, it returns an empty line.
Comment: @tigerjack89 oops, thanks for the correction. And Blaze_Tama no it will not be permanent, I just typed 3 instead of 0, the rest is correct (I hope :) ).
Comment: @tigerjack89 Just to clarify, so if i run export SWT_GTK3=0 in the terminal, it means the terminal is the shell, so if i exit the terminal, the export will be no more?
Comment: yes, the export will be deleted. Also, take a look at these links for a detailed difference between shell and terminal http://askubuntu.com/questions/111144/are-terminal-and-shell-the-same
http://unix.stackexchange.com/questions/4126/what-is-the-exact-difference-between-a-terminal-a-shell-a-tty-and-a-con


In git, what's the difference between A..B and A...B?

Question:
Possible Duplicate:
What's the difference between ".." and "…" in Git commit ranges?

I see on various tutorials two different syntaxes for commit ranges :
git log A..B
git log A...B

What's exactly the difference between both ?
Comment: Yup, added answer, as I couldn't delete question anymore...
Comment: In such cases just wait till the question is closed. The link to the duplicate will then be inserted at the top of the question and it will be left as a possible google signpost or deleted.
Comment: @pmr will do. At least, it did sparkle an executive summary :)
Answer: The first is: include all commits up to B, excluding all up to and including A. The second: include all commits up to be, excluding all up to and including common ancestor(s). See git help revisions, section SPECIFYING RANGES.
Comment: +1 for executive summary of the said linked duplicate
Answer: Ouch.
Is a duplicate of What are the differences between double-dot ".." and triple-dot "..." in Git commit ranges?.
Why didn't it show up in my various searchs remains mysterious.


32GB Micro SD shows only 32MB

Question: So, my phone has this error (it turns off randomly), and because of that, my 32GB microsd card got corrupted. Is there any way to fix de microsd card or recover the data on it?
I put the sd card on the pc through an USB adapter, and it only shows 32MB:

I tried CHKDSK command on windows but it didn't work.
Comment: @saikiranreddy that will **completely erase the disk**. Not what the OP is looking for.
Comment: What does it show for the SD card in GParted?
Comment: Please post the output of `sudo lsblk` and `sudo fdisk -l`.
Comment: try this answer
http://unix.stackexchange.com/a/31902 but be careful with dd command. if you enter /dev/sda instead of /dev/sdb of sdac, the hard disk is going to get erased.
Comment: @Zacharee1 but doesn't he want his data
Answer: First things first:
If you want your data. DON'T do any writing to the card as you try the rescue.
I just happened to have the same problem on a friends PC with an external HDD which got its volume entries corrupted and was also only showing a few MB instead of 60 GB. This happened because he did not safely remove the drive from his PC. If your card is really broken then nothing except a professional rescue service will be of any help to get your data.
Step 1: open a terminal window
Simply press ctrl+alt+t to open a terminal window.
Step 2: acquire testdisk
testdisk is available in the normal Ubuntu repositories so simply install it by:
sudo apt-get install testdisk

Step 3: rescuing your data via testdisk
Insert your SD-card into your card-reader or plug in the drive you want to rescue and fire up teskdisk with:
sudo testdisk

Then you will see the following in your terminal window:

Here you can choose to create a log file which I highly recommend for eventual troubleshooting. Simply press enter and you will see the next in your terminal, where you can choose the drive you want to rescue:

Of course you see my drives in the screen-shot so you have to navigate to the corresponding drive with the up and down arrow key and then select at the bottom proceed with the left and right arrow key and hit return.
Next you will see is the file-system selection like in the next screen-shot:

In most cases it tells you in the hint at the bottom which file-system type to select, do so or set it to the corresponding type of your drive. Then hit return again to proceed.
In the next menu (see screen-shot) select 'Advanced' and you should be able to see the full partitions (maybe a second partition on your card). Select it and select 'List' files and back them up.

You should then see the directory structure you had on your drive like in the next screen-shot:

See the red ones on the screen-shot; these are deleted files you can choose to hide by pressing h. Now navigate to the files/directories you want to rescue by pressing up and down arrow key (you can switch directories with enter or go upward by selecting the .. entries.
To make a selection of which files you want to copy/rescue press : which will mark the corresponding row green or press c to copy a single file. For copying the selection press shift+c. In both cases you will then be prompted with another directory view where you can navigate to a place to save your data/files. Navigate to where you want to have this data and press shift+c again to start copying.
Step 4: cleaning your SD-card
After you have all your data rescued its time to clean up the SD-card so you can use it again to full capacity. To do this just enter the following in your terminal (make sure you select the right volume for your card which was sdb in your screen-shot so I take that for my example here)
sudo dd bs=4m if=/dev/zero of=/dev/sdb

This may take a while to run but after that there is nothing on the SD-card at all so you should be able to use it with your reader and simply format it again.
Comment: dd: invalid number: '4m'
Comment: @RafayKhan: Try using `4M` instead, it can be that they changed this to uppercase for blocksize in Megabytes, sadly have no computer at hand right now to test.
Answer: When the SD card was formatted for file storage, a small portion was reserved for configuration files. That small portion is the 32 mb empty space that you can see there. I don't have enough info on your problem, but it sounds like you have a problem similar to this HowToGeek article. The Raspberry Pi in said article has the same issue as you. To quote from the article,

When I went to reformat the card only 64MB out of the original capacity was available and even when I went into Disk Management in Windows the best I could do is dump the contents of the inaccessible (and presumably Linux-filled) partition. This left me with a tiny Windows accessible partition and a big phantom partition I can't do anything with.
I should assume that you are using Windows to view your card's files on the SD reader. If so, then it is more than likely that your missing 32 GB of space is a Linux-formatted partition, which Windows cannot see. If that is case, you can get an Ubuntu LiveCD, boot it up on your computer, run the LiveCD without installing, and transfer the files to your Windows machine. Then, you can reformat the SD card, while still in the LiveCD.
Hope it helps!
~ P
Comment: but he is using Ubuntu, i thought
Answer: If the SD card claims that it's only 32 GB large then there's nothing you can do about that with software alone – Ubuntu/Linux or any other operating system.
If you need the data that might still be on the card contact a professional data rescue company who might be able to inspect the memory modules on the SD card without having to rely on the (apparently faulty) memory controller chip on the card.
If you don't care about the data and just want a working 32-GB SD cards, please edit your question to clarify that. There's also a comment to your question with a link dealing with that.

32GB Micro SD shows only 32MB


Numeric input, text fields, drop-downs : Is this too complex?

Question: I'm redesigning an interface to control an exercise game. The interface is going to be something like this (and exists on a PC, not mobile). Right now, we've gathered that our users want to be able to control these options, but I'm afraid our interface is too complex/cluttered.

download bmml source – Wireframes created with Balsamiq Mockups
The facilitator has the option to enable forced breaks (ie. the game stops for a period of  time) based on some criteria.  We decided on the numeric steppers so that we can have fixed increments.
My question is this, what is a good way to allow the user to set all these rules? This snippet is only a piece of a larger interface and I'm worried that overall it puts too much load on the user.
Comment: Have you looked into how your users vocalize these items - for example: "I want to workout for 150 repetitions with 2 minute breaks every 10 repetitions, with no bonuses". This can help you construct a flow that might be more straight forward. Also, can each section have different units (repetitions, attempt, minutes) set?
Comment: Each section can have different units, depending on the user's preferences. This falls into the category of our users want the ability to make all of these decisions without knowing exactly how they want to do that
Answer: I think that there are two directions that you may follow to make this setting less cluttered:

It seems like it's a good idea to treat settings like a meaningful phrases, but using desktop controls makes it unreadable. You may try to replace them by links (every user nowadays is familiar with links so it will not confuse). Doing this you will make your settings page much more clear and readable (avoid headers too — they are simply duplicates the text in the sentence).

You may try to use a predefined set (based on some statistics) of values for every option instead of flexible values, I mean something like this:

It will not only reduce the number of actions users should do but also will give them a meaningful set of predefined options (which are carefully selected with testing, etc).
Comment: I like the links idea, as our users tend to balk at any kind of predefined choices. In our previous iteration, we had most of this restricted to just a few options and our users expressed strongly that they felt like the tool had potential to replace them if they couldn't make decisions at this level of granularity.

The headers were included solely to provide a way to enable breaks clearly. Is there anything that says you shouldn't only have one checkbox on the page?
Comment: @Perchik Concerning the only checkbox: I wasn't sure there are another settings in your app but, yes, the only checkbox looks not so good so you may try something like this: http://glui.me/?i=k6jtw6cmj846n9h/2014-04-15_at_10.44_2x.png/
Comment: Oh that's a good idea too. Depending on how the rest of the interface is designed, I'll either use this method, or checkboxes if we have other ones in the page.
Answer: I like Alexey's idea, because the number and thing measured form a pair. So instead of showing controls for "50" and "repetitions" separately, the user instead edits "50 repetitions". My only concern is that links have a particular meaning and their use here is not standard. For example, I've been in situations where I had to wonder what the link would do, would it take me elsewhere and make me lose my form data or would it do a pop-up?
In your case, are there other areas/screens whether the link style behaves like a link? The style should beehave consistently, so user can learn how it works easily.
Also, another option is to put an edit action on the whole row, for example a row that many people will leave on default.
Comment: Good point about the links. In this case, there are no other links in the application, so I think we can get buy with it
Answer:
Hi! So you have the slider which will increase/decrease only at fixed values. Now, suppose I want to set my duration for Break as 2 minutes.

I set the slider at 2 and I click on the button "Duration for the Break is".
As I know that the label for this action is always going to be in "minutes", it can act as a fixed label for me. I wouldn't need to select any of the radio buttons.
I want to set the break after every 10 repetitions.What I do is increase the slider to 10, and then select "Repetition" as a radio button and click on "After Every".

Similarly, I select the value that I want for each of the "Action" and just hit the button for which I need to enter that value.
Constructive feedback is most welcome.
Thanks!


How can I remove the format part of the string?

Question: I have this table:
// image_path
+----+-----------------------------+
| id |           path              |
+----+-----------------------------+
| 1  | 3498uhrf34i098jf349jf43.png |
| 2  | mfij948t5498hj43h9f34p0.jpg |
| 3  | fcnh9348jmof9348i34f435.png |
| 4  | 3049jr430okf43p0ijfr43f.gif |
| 5  | oi3094jfo439ijf430f443r.jpg |
| 6  | 3f0irj03409iko4p3rfo04f.png |
+----+-----------------------------+

And here is my query:
SELECT * FROM image_path WHERE path = :token;
//                             ^^^^ removing everything from the right side until dot

So here is an example:
SELECT * FROM image_path WHERE path = 'fcnh9348jmof9348i34f435';
/* output:
+----+-----------------------------+
| 3  | fcnh9348jmof9348i34f435.png |
+----+-----------------------------+
*/

How can I do that?
Comment: An alternative is to modify the database schema, split into two columns; `path` and `extension`
Answer: How about using like:
where path like concat('fcnh9348jmof9348i34f435', '.%')

Here is a SQL Fiddle.
EDIT:
If you want to get the part before the first period, then use substring_index():
select substring_index(path, '.', 1)

Comment: @Shafizadeh . . . In your SQL Fiddle, you have a typo -- two `where`s in the query.
Comment: Oh .. you are right, thx .. +1. Noted that the fiddle in your question is also wrong `:-)` *(two `where` clause)*
Comment: @Shafizadeh . . . I fixed the link ;)
Comment: Good :) ..! Also as a consult, do you think which answer is more efficient? I mean which one has a better performance for index? *(because `path` column is unique)*
Comment: They are probably all pretty equivalent with respect to performance.
Comment: Look, I'm worried about this rule: *"You're not using the raw column value, so you couldn't use an index on the `path` column"*. So should I use either `like` or `substring_index` to keep safe against that rule?
Comment: I'm not familiar with such a rule.  I would use `like` because there is the hope that MySQL would use an index when the wildcard is at the end (although this is only true when the pattern is constant).
Answer: Something like this (substring_index):
SELECT * FROM image_path WHERE substring_index(path, '.', '1') = 'fcnh9348jmof9348i34f435';

Demo Here
Answer: You can use LEFT and LOCATE functions:
SELECT LEFT(path, LOCATE('.', path) - 1) FROM image_path;


Filling a cube (back-face culling algorithm)?

Question: I want to fill my cube. I found back-face culling algorithm. Can you explain me how it works? I have 8 points in vector:

Maybe you know another easier algorithm or explain me what I should do with back-face  culling?
(wallX[0] - point 0; wallX[1] - point 1; wallX[2] - point 2 from image)
Code for fist wall:
x1[0]=wallX[1]-wallX[0];
y1[0]=wallY[1]-wallY[0];
z1[0]=wallZ[1]-wallZ[0];

x2[0]=wallX[2]-wallX[0];
y2[0]=wallY[2]-wallY[0];
z2[0]=wallZ[2]-wallZ[0];

x3[0]=0;
y3[0]=0;
z3[0]=1000;

wall1={y2[0]*z1[0]-z2[0]*y1[0], z2[0]*x1[0]-x2[0]*z1[0], x2[0]*y1[0]-y2[0]*x1[0]};
wall1*={X3, Y3, Z3};
if(wall1[2]>0) cout<<"wall is watching"<<endl;

Comment: Have you tried researching back-face culling yourself before posting here??
Comment: What are you using to render the cube? Usually OpenGL or DirectX have already multiple culling algorithms included, you don't have to write it yourself.
Comment: I can't use OpenGL or DirectX, I must write algorithm to fill my cube. I must write it at myself.
Comment: Possible duplicate of [Algorithm to fill triangle](https://stackoverflow.com/questions/39038505/algorithm-to-fill-triangle)
Answer: Presumably, you want to render the cube as an opaque solid.
This is indeed done by painting the faces, in such a way that you see the faces closer to the viewer.
I assume that

you have a polygon painting algorithm,
you are able to compute the color/shading to assign to every face.

You can resort to two methods:

the painter's algorithm, i.e. painting all faces from back to front. You can achieve this by sorting the faces on the depth coordinate of the closest vertex of each face. This is easy to do but a little inefficient as you will paint six faces when three are enough.
backface culling, i.e. ignoring the faces that have the depth component of their normal vector pointing to the rear. just a little of vector calculus.


Error: User is not authorized while creating GCP project using service account

Question: I am trying to create GCP project programmatically using Google API. Here is the sample code:

const {JWT} = require('google-auth-library')

async function main (keyFile = {PATH_TO_CREDENTIAL_FILE}) {
  const keys = require(keyFile)
  const client = new JWT({
    email: keys.client_email,
    key: keys.private_key,
    scopes: ['https://www.googleapis.com/auth/cloud-platform']
  })
  const url = 'https://cloudresourcemanager.googleapis.com/v1beta1/projects/'
  const data = {
    projectId: 'my-first-project',
    name: 'My First Project',
    parent: {
      type: 'organization',
      id: {ORGANIZATION_ID}
    }
  }
  const res = await client.request({
    url,
    method: 'POST',
    data: JSON.stringify(data)
  })
  console.log('project Info:')
  console.log(res.data)

  const tokenInfo = await client.getTokenInfo(client.credentials.access_token)
  console.log('tokenInfo', tokenInfo)
}

const args = process.argv.slice(2)
main(...args).catch(console.error)

After running this code I am getting the following error:

UnhandledPromiseRejectionWarning: Error: User is not authorized.

Can anyone help me why I am getting this error? And how can I fix this?
P.S.

Google Resource Manager API is enabled.
Service account has the role=owner permission.
Comment: Is this user part of an organization and you are creating this project in the organization? If NO then you must create the project in the Google Cloud Console. IAM members that are not part of an organization cannot create projects using the CLI or API.
Comment: Yes the user is part of an organization and yes, I am creating the project in the organization.
Answer: You are creating a project within an organization. Does the user have the Project Creator role in the organization?
When the organization is created, all users in your domain are automatically granted Project Creator and Billing Account Creator IAM roles at the organization level. This enables users in your domain to continue creating projects with no disruption.
The Organization Administrator will decide when they want to start actively using the organization. They can then change the default permissions and enforce more restrictive policies as needed
Also if you are authenticating using a service account (SA) then the SA needs to have the role
Comment: Yes, the user have the Project Owner permission. Also, I have given SA role=owner under the project SA is created. Do I need to give SA role under the organization as well?
Comment: Granting the resource manage > project creator permission solved the problem. Thanks!


Haskell Get position from first digit in string

Question: What I got is
digitIndex :: String -> Int
digitIndex [] = 1
digitIndex (x:xs) =
    if
        isDigit x == True
    then
        -- Count list
    else
        -- Create list with x(x is not a digit)

What my idea is is to make a list with all the x that he is passing so when he passes a digit he only needs to count the list and that will be the position of the digit(when you count a +1).
Only thing is I don't know how to get the job more done. Can you guys help me out with tips?
Comment: Please don't vandalize your own posts. If it is necessary to remove them, flag for moderator attention and ask for removal.
Answer: You can use findIndex:
import Data.List

digitIndex :: String -> Int
digitIndex = maybe 0 id . findIndex isDigit

Answer: Just the normal recursion:
digitIndex :: String -> Int
digitIndex [] = 0
digitIndex (x:xs) = if isDigit x
                    then 1
                    else 1 + digitIndex xs

If the first character itself is a digit, then the function returns 1 else it just adds 1 and passes the remaining string (xs) to the function and the recursion goes on.
Also note that the above function doesn't work properly when the String doesn't have a number at all.
And also checking isDigit == True isn't necessary.
Comment: That wont make the good output because if I fill in: digitIndex "hel3lo" it will output 1 and not the 4 (the 3 is in the 4th place of the string)
Comment: @user3434886 I understood your question wrongly, have updated the solution.
Comment: Maybe I needed to be more clear in my explanation but you solved my problem. Thank you!


View linked server dependencies sql server 2008

Question: Does any know how / if it is possible to view all tables/views/stored procedures that depend on a linked server in Sql Server 2008. Basically as if the context menu "View dependencies" was accessible for linked servers?
Any help much appreciated.
Thanks
Answer: Search for it
SELECT OBJECT_NAME(object_id), *
FROM sys.sql_modules
WHERE definition LIKE '%myLinkedServer%'

Or use the free Red gate SQL Search to do the same with a GUI
There is no table or feature that tracks dependencies between the server-level linked server objects and database-level objects
Note: INFORMATION_SCHEMA views and the legacy syscomments truncate the definition so are unreliable for definition searches.
Comment: you would have to run that search for each database on the server...perhaps using sp_msforeachdb
Comment: This will work unless you have a query stored outside of SQL Server (e.g. in a report) that uses a linked server. In that case, yo'll have to resort to a trace or extended events.
Answer: Following @Mitch Wheat's suggestion, here's some sql to run @gbn's answer for all db's on the server. Maybe this will a bit of time for someone.
USE Master;
GO

IF OBJECT_ID('tempdb..#Deps') IS NOT NULL
  BEGIN
    DROP TABLE #Deps
  END

CREATE TABLE #Deps
  (
    [ServerName] [VARCHAR](500) NOT NULL,
    [DatabaseName] [VARCHAR](500) NOT NULL,
    [SchemaName] [VARCHAR](500) NOT NULL,
    [ObjectName] [VARCHAR](MAX) NULL,
    [ObjectId] [INT] NOT NULL,
    [ObjectType] [VARCHAR](500) NOT NULL,
    [DependsOnLinkedServer] [VARCHAR](500) NOT NULL,
    [definition] [VARCHAR](MAX) NULL
  )

IF OBJECT_ID('tempdb..#Queries') IS NOT NULL
  BEGIN
    DROP TABLE #Queries
  END

SELECT
  REPLACE('INSERT INTO #Deps
     (
       [ServerName]
       ,[DatabaseName]
       ,[SchemaName]
       ,[ObjectName]
       ,[ObjectType]
       ,[ObjectId]
       ,[DependsOnLinkedServer]
       ,[definition]
     )
     SELECT
       @@SERVERNAME,
       ''?'' AS DatabaseName,
       s.name AS SchemaName,
       o.name AS ObjectName,
       o.type_desc AS ObjectType,
       m.object_id AS ObjectId,
       ''' + srv.name + ''' AS DependsOnLinkedServer,
       m.definition
     FROM
       [?].sys.sql_modules m
       LEFT OUTER JOIN [?].sys.objects o
       ON m.object_id = o.object_id
       LEFT OUTER JOIN [?].sys.schemas s
       ON o.schema_id = s.schema_id
     WHERE
       definition LIKE ''%' + srv.name + '%''', CHAR(13) + CHAR(10), '') AS Query
INTO
  #Queries
FROM
  sys.servers srv;
GO

DECLARE @Query AS VARCHAR(MAX)
DECLARE LinkedServerCursor CURSOR FAST_FORWARD
FOR
  SELECT
    Query
  FROM
    #Queries

OPEN LinkedServerCursor
FETCH NEXT FROM LinkedServerCursor INTO @Query;

WHILE @@FETCH_STATUS = 0
  BEGIN
    EXECUTE master.sys.sp_MSforeachdb @Query

    FETCH NEXT FROM LinkedServerCursor INTO @Query;
  END

CLOSE LinkedServerCursor;
DEALLOCATE LinkedServerCursor;

GO

SELECT
  ServerName,
  DatabaseName,
  ObjectName,
  '[' + ServerName + '].[' + DatabaseName + '].[' + SchemaName + '].[' + ObjectName + ']' AS QualifiedObjectName,
  DependsOnLinkedServer,
  ObjectType
FROM
  #Deps
ORDER BY
  ServerName,
  DatabaseName,
  ObjectName

Comment: +1 Thanks for this, gives you all the information needed to track down usage of linked servers across all databases.
Answer: I would recommend changing the middle part of the query to be as below to ensure only when it is used in a query you get a hit.
If not you will get a lot of false positives whenever the servername is mentioned.
WHERE
definition LIKE ''%\[' + srv.name + '\].%''
or definition LIKE ''%' + srv.name + '.%''', CHAR(13) + CHAR(10), '') AS Query


Protect trim finish during installation

Question: When using a nail gun to install freshly stained and finished trim,  i want to make sure i don't damage the finish.  In concerned that pressing the  nail gun up against the surface will cause marks.
What's a good way to do that?
Answer: Most nail guns come with rubber bumpers or you can get them from the manufacturer. You can also use a piece of cardboard over the trim and move it along as you go.
Comment: Finish nailers, in particular should have a rubber protective piece. I was quite surprised to find that my _framing_ nailer also came with a protective plastic nose piece.
Comment: @FreeMan  Hey.... studs and rafters want to look nice too...
Comment: Yeah... sure... we'll go with that...  :)

Protect trim finish during installation


Migrate Large Table from one Azure SQL Server to Another without GenerateScripts

Question: At my organization, we have a table on one Azure SQL Server in which one of the columns contains a large JSON document.  This table also has over a thousand entries.  We need to migrate this table from one Azure SQL Server to another, but are running into issues with doing that.  We have generated scripts before to do similar processes however, the script generated for this migration is extremely large (due to the JSON document) and is unable to run properly.  Is there another tool/method for copying a large amount of data in a table between two Azure SQL Databases?  Thank you.
Comment: Thanks for the help, my supervisor figured it out, and I am not completely sure, but I think he used a method similar to this.
Comment: Is this [document](https://learn.microsoft.com/azure/azure-sql/database/database-copy?tabs=azure-powershell) helpful for you?
Comment: Hi @AppSupportGuru1995. Kindly let me know if you need more information.
Comment: Thanks a bunch.  I don't see your answer below, otherwise I can mark it for you.
Answer: There are several ways we can choose to copy to a new Azure SQL Server:

Copy using the Azure portal:

Use PowerShell to copy a database to a new server according to this documentation.

Copy using Transact-SQL according to this documentation.
Copy to a different server:

<code>-- Execute on the master database of the target server (server2) to start copying from Server1 to Server2
CREATE DATABASE Database2 AS COPY OF server1.Database1;
</code>


How can I disable the air conditioner beeper?

Question: I bought this model: MFL69782201 (User manual PDF http://gscs-b2c.lge.com/downloadFile?fileId=S45tMoOwlLqIpW2lkIGLfA)
It is a split dual inverter.
The problem is there is no way to disable the beep that happens every time we press a button in the remote control. I contacted the manufacturer and they say "it is how it works and is impossible to disable the beep".
The noise is very annoying, mostly in the morning, and mostly because I live in an apartment. I don't want that noise to cause trouble with my neighbors.
I know if I make a hole on it somewhere I will be able to reach the beeper and cut it out or block it enough to lower the beep volume in a hardware way.
But I can't find a maintenance manual for it, so I don't know where to cut. Yes I am aware about warranty, but... The beep is so horrible that I avoid using it as much I can. I feel like I bought the wrong product...

Has anyone done that kind of thing?
Did it work?
Where can I find such maintenance manual?
Cut or damage the utterly annoying beeper can cause other problems on the circuit board?
Comment: why would you cut a hole in the AC cabinet? ... how did that thought even enter your head? ... just take off the cover, find the beeper and cover it with tape
Comment: Your indoor unit will have two or more screws (often near the blower) that hold the cover. The cover in most split units can be removed easily without messing with the gas pipes or dismounting the whole unit from the wall. Watch some videos on how split ac units are serviced. [Take off the cover](https://youtu.be/texGW7Gi3fg?t=367) and maybe you can find the exact part that makes the beep and do something about it. If you are not able to remove the cover then call the service guys (they clean the coils) and when they arrive ask them to do something about the beep.
Comment: You could just set it and leave it set, too. No need to press a button = no beeps.
Comment: @Ecnerwal when I turn it on, it "sings" loudly for about 3s... If I need to change the temperature it makes a loud beep for every button press, I mean, I cant just set and leave it, I need to have access to these controls at anytime.
Comment: @jsotola mmm... I lift a movable panel but I couldnt see the control board. To take off the whole cover I would have to have access to the backside of it where are the screws, but it is on the wall. It is already installed (of course) and I am scared of messing with the gas tubes that connect to it. But I will look more to see if there is something safe that I could do, what a mess, I should have bought from some other manufacturer...
Comment: the link you posted requires a membership ... please post a picture of the front of the AC
Comment: is there a display board? ... that is where the beeper would be
Comment: @jsotola thx, I didnt see the pdf was not good... (only showed the initial pages), I changed the link to a pdf download (I cant find english version tho). I will lift the panel and take a photo tomorrow as right now it is 00:21am and I cant make much noise moving stairs around to reach it :)
Answer: [Attention, do not try this w/o a electronics technician that can give you warranties that your air conditioner will not be damaged! You have been warned!]
A few months later...
I talked to a friend that understand electronics.
He said that removing the buzzer completely could not cause any problems.
But before trying that drastic solution, first I tried just to remove the buzzer cover to try to put something inside the buzzer to lower the noise.
But then... to my surprise, the buzzer came out completely and cleanly w/o damaging the circuit board (probably it was weakly soldered), by luck I guess...
I've been using the air conditioner w/o noises since then.
So... for that model it is not causing any trouble that I can detect to the date.
This doesn't mean there is no problem there!!!
I am just sharing what happened and is apparently working w/o problems, but I do not understand electronics myself so I cannot explain if it is or is not causing problems!!!
Also, the buzzer is used to provide diagnostic data thru a cell phone call by making noises like a fax I guess, so that functionality became unavailable until I plug the buzzer back again.
If you want to try this, talk to some friend that understand electronics first, and better ask him to manipulate the buzzer so that you wont damage it, and if possible ask him to test if the circuit could be failing somehow so he can solder it (or something else less irritating, may be a led?) back if something looks wrong.
I risked myself damaging the air conditioner... totally out of real despair, because of the absurdly irritating noise, I should never have bought that model initially at all!!! (and will never buy again w/o being sure it is possible to disable the noises w/o risking damaging it).
I do not recommend doing it w/o someone that understand the electronics of the model of your specific air conditioner, ask a technician to help you tweak the hardware, and to give you warranty in case some problem happens, that would be the most safe way for sure.
If you think I could share this text in a way ppl will understand the risks better, say so or edit it please. I am just sharing that it is working but I cannot guarantee there is no problems...
If you understand electronics, you could explain us why it is apparently not causing any troubles? or even better, what problems may happen if I keep it w/o the buzzer?
Comment: It's like a light bulb. If it burns out, your toilets will continue to flush properly. The only purpose of the bulb is to turn on when provided with power. Similarly, the only purpose of the beeper is to beep when it receives an electrical impulse. If it doesn't beep, the compressor doesn't care, and neither does the blower motor or the filter.


How can I programmatically determine the size of my desktop?

Question: I'm trying to save / restore the window size, state and position of a System::Windows::Forms::Form and want to make sure that if the window was previously on another monitor and the app is started up when only a snogle monitor is available, that it puts itself somewhere on-screen.
So how can I determine the current desktop size and whether my application is out of bounds?
Comment: possible duplicate of [C#: Get complete desktop size?](http://stackoverflow.com/questions/1317235/c-get-complete-desktop-size)
Answer: Actually, the best solution would be to use the native methods GetWindowPlacement and SetWindowPlacement in user32.dll. These automatically handle all the edge cases.
A sample WPF implementation using them can be found at http://jake.ginnivan.net/2010/04/remembering-wpf-windows-position-2/ From that you could do the same for WinForms.
Comment: +1/Accepted ..although by the time I read this, I'd already rolled my own :-)
Answer: Have you looked at the Screen class?
The Screen.WorkingArea property will give you the desktop size of your display.