Understanding a Cosine Derivative

Question: Let $c$ be a constant. Why is it that

$$
D_x \left(- \frac{\cos(cx)}{c} \right) = \sin(cx)?
$$

I understand that $D_x \cos(x) = - \sin(x)$.  So what trigonometric identity is allowing us to infer the above?
Comment: The chain rule. $\qquad$
Comment: Often I post something just because I think a question can be answered more simply than it is in the other answers.  See my answer below. $\qquad$
Answer: You are just using the chain rule. Hence you get by using $D_x\cos(x) = -\sin(x)$ and $D_x(cx) = c$ that
$$
D_x \left(- \frac{\cos(cx)}{c} \right) = - c \frac{-\sin(cx)}{c} = \sin(cx)
$$
I hope that helps you :)
Answer: $$f(x) = {-\cos (cx) \over c}$$
$$\begin{align}  f^\prime(x) & = \lim_{h \to 0} {{{-\cos (c(x + h)) \over c} - {-\cos (cx) \over c}}\over h}\\
& = \lim_{h \to 0} {\cos (cx)-\cos (c(x + h)) \over hc}\\
& = \lim_{h \to 0} {-2 \sin ({cx + cx + ch \over 2})\times\sin ({cx - cx - ch \over 2}) \over hc}\\
& = \lim_{h \to 0} {2 \sin (cx + {ch \over 2})\times \sin ({ch \over 2}) \over hc}\\
& = \lim_{h \to 0} {\sin (cx + {ch \over 2})\times\sin ({ch \over 2}) \over {hc \over 2}}\\
& = \sin (cx)\times\lim_{h \to 0} {\sin ({ch \over 2}) \over {hc \over 2}}\\
& = \sin (cx)
 \end{align}$$
If you don't like chain rule :)
Answer: By De Moivre,
$$\cos(nx)+i\sin(nx)=(\cos(x)+i\sin(x))^n.$$
Then by the derivative of a power,
$$(\cos(nx)+i\sin(nx))'\\
=\left((\cos(x)+i\sin(x))^n\right)'\\
=n(\cos(x)+i\sin(x))^{n-1}\left(\cos(x)+i\sin(x)\right)'\\
=n\left((\cos((n-1)x)+i\sin((n-1)x))^{n-1}\right)\left(-\sin(x)+i\cos(x)\right)\\
=n\left((-\cos((n-1)x)\sin(x)-\sin((n-1)x)\cos(x)\\
-i\sin((n-1)x)\sin(x)+)^{n-1}+i\cos((n-1)x)\cos(x)+)^{n-1}\right)\\
=n(-\sin(nx)+i\cos(nx)),$$
which establishes the claim for all integer $n$.
But all of this is a stupid sledgehammer compared to the simple use of the chain rule.
Comment: Lmao, I love the overkill.
Answer: Let,$f\left( x \right) =\cos { x } ,g\left( x \right) =cx\quad $ then composition of $f$ and $g$ will be $f\circ g=f\left( g\left( x \right)  \right) \quad =\cos { \left( cx \right)  } $
we know from the chain rule that $$\\ f^{ \prime  }\left( g\left( x \right)  \right) =f^{ \prime  }\left( g\left( x \right)  \right) \quad g^{ \prime  }\left( x \right) $$ and consider the $D_{ x }\left( f\left( x \right)  \right) =-\sin { \left( cx \right)  } \\ { D }_{ x }\left( g\left( x \right)  \right) =c$
we get $$D_{ x }\left( -\frac { \cos  (cx) }{ c }  \right) =-\frac { 1 }{ c } { D }_{ x }\left( \cos { \left( cx \right)  }  \right) =-\frac { 1 }{ c } \cdot \left( -\sin { \left( cx \right)  }  \right) \cdot c=\sin { \left( cx \right)  } \\ $$
Answer: \begin{align}
y & = \cos(cx) \\[10pt]
y & = \cos u & u & = cx \\[10pt]
\frac{dy}{du} & = -\sin u & \frac{du}{dx} & = c
\end{align}
Now apply the chain rule:
$$
\frac{dy}{dx} = \frac{dy}{du} \cdot \frac{du}{dx} = \Big(-\sin u\Big) \cdot c = \Big(-\sin(cx)\Big) \cdot c.
$$
Comment: Possibly the lack of words?
Comment: @Daniel, Sometimes "words get in the way", as Miss Estefan has once said. ;)
Comment: Although i upvoted the answer, i don't get how this isn't a duplicate of the accepted answer. There are already 2 duplicates of the accepted answer. Anyway thanks for $\quad$.
Comment: And yet here it is being downvoted.
Comment: @DanielR.Collins : In some places in m.s.e. there is indeed insufficient use of words, and in some places there are far too many words, and often both problems occur in the same paragraph.  However, I have now added some words. $\qquad$
Comment: Divide the last equation by $c$ in order to get it in the same form as _OP_. I think this is why it didn't get voted much.
Answer: The easiest and most elegant way is to apply the chain rule literally:
$\def\lfrac#1#2{{\large\frac{#1}{#2}}}$

$\lfrac{d(\cos(cx))}{dx} \overset{\text{chain rule}}= \lfrac{d(\cos(cx))}{d(cx)} \times \lfrac{d(cx)}{dx} = -\sin(cx) \times c$ for any variable $x$ and constant $c$.

Of course this then gives $\lfrac{d(-\frac1c\cos(cx))}{dx} = -\lfrac1c ( -\sin(cx) \times c ) = \sin(cx)$.

Understanding a Cosine Derivative


calculate and return number of days in a week

Question: how to calculate number of days in a week? for example 1st week in January 2014 has 4 days, so the function will return 4.
googled this, no answers to my need.
Comment: They all have 7. Unless you mean something different than you are asking.
Comment: Make an effort and post your attempt and where you are stuck. Answers are not spoon fed.
Comment: This question is not well specified. Give concrete examples of input and expected output, so we can know what it is you're looking for.
Comment: thanks @EvanCarslake. i have no idea about it, is there any built in method for this or should i start writing the function from 0? if there is no built in method, then i am going to find a hint and write it myself.
Comment: yes there is no function that outright does this, you'll gonna have to write it yourself first. Consider using the `DateTime` class of PHP
Comment: @JakeParis : for example, in January 2014, there are 5 weeks, first week starting from January 1st 2014, which is wednesday, so for this week it will return 4 days.
Comment: So you want to start with the first day of the month, get the weekday of that date, and then calc how many days left until Saturday.
Comment: It's really not clear what you are asking here. Can you add more details to the question?
Answer: <code>$str = "January 1 2014 Sunday";
echo date("z", strtotime($str));
</code>
Output - 4
ps: works only for the first week of January of any year as follows from question.
pps: this is for 1st week of any month
<code>$str = "February 1 2014";
echo date("z", strtotime($str . " Sunday")) - date("z", strtotime($str));
</code>
and for the last week
<code>$str = "February 2014";
echo date("z", strtotime("last day of " . $str)) -
     date("z", strtotime("last monday of " . $str));
</code>
Comment: aw, it's close to my need..tried `February 1 2014 Sunday` and it return 32 LOL. thanks anyway
Comment: @DarielPratama do you want to know number of days in a first week of any month? show specific examples.
Comment: yes, exactly number of days in first week, and last week actually.
Comment: @DarielPratama added for the last week too.


How can I build more facilities?

Question: I have built quite a lot. Now I want to build even more...
There is a way to do it? or it is this all space that I have? If I need to do something, I need to demolish them create what I want?
Comment: Related. [What is the perfect base layout?](http://gaming.stackexchange.com/questions/89098/what-is-the-perfect-base-layout)
Answer: What you see is what there is - there's no way to expand your available space.
If you've excavated and built on every tile, that's it, that's all the space you have for building things.
Eventually you'll have researched everything and you can get by without the Laboratories, and some of the buildings can be upgraded (like the Power Generators and Satellite Uplinks) but you'll have to remove the existing buildings in order to do this.
At that point, you may want to have a look at an attempt at a "perfect" base layout.
Comment: @Michel,hey, I was like a full... what... 15 seconds faster? :P
Comment: I was planning to take Spartacus as the correct answer, but your "cheat" using the perfect layout question as a link gives you the title.
Comment: I make it 17 ^^
Answer: This is all the space you will ever have.  You can consider saving some space by removing the power generators and replacing some of them with elerium generators.  You can do the same with the satellite upliniks and nexus.  Finally, once you are done with all research, you can remove the labs for more workspaces.

How can I build more facilities?


What is the relationship, if any, between Active Directory groups and groups in Exchange?

Question: Tasked with creating a login page that would allow members of two specific groups access to some controllers and actions in an MVC project, I set about to create a role provider for AD. I managed to get it configured with forms authentication, and to enumerate the groups to which an authenticated user belongs in AD.
It turns out, however, that the groups I was asked to set this up for, are not AD groups. I see lots of groups, but not the ones in question.
The request was based on the fact that these groups show up in the global address book from Exchange, but there doesn't seem to be a 1:1 relationship.
Is there any relationship?
Comment: One thing that comes to my mind is the distribution list and security group.  When you create a group in AD, you can set whether it's a security group or distribution list.  Security group is used in the ACL while the distribution list is used mainly in the email list and other non-ACL related stuff.  How are you getting your groups your user belongs to?  Some API might just give you security group but not distribution list.
Comment: @Harvey Thanks, yes that is what I've found. In .NET, I was calling `UserPrincipal.GetAuthorizationGroups()`, when the groups in question were distribution groups. Calling `UserPrincipal.GetGroups()` returns them all. Post an answer and I'll accept.
Answer: There are two type of groups in Active Directory, distribution list and security group. Security group is used in the ACL while the distribution list is used mainly in the email list and other non-ACL related stuff.

UserPrincipal.GetAuthorizationGroups() returns security groups only.
UserPrincipal.GetGroups() returns security group as well as the distribution list.

Beware that unlike UserPrincipal.GetAuthorizationGroups(), UserPrincipal.GetGroups() returns only the immediate group that an user belongs to.  If GroupA contains GroupB and GroupB contains UserX, userX.GetGroups() returns GroupB only but not GroupA.
Just a side note, there are bugs in .NET 3.5 SP1.  UserPrincipal.GetGroups() may not work properly, you may like to check out this hotfix http://support.microsoft.com/kb/969166


What are all the elements of the group of symmetries of a regular tetrahedron?

Question: I can see that why the order of the group of symmetries of a regular tetrahedron is $12$ : Roughly speaking, each time one of ${\{1,2,3,4}\}$ is on 'top' and we do to the other $3$ as we did in a regular triangle. But I need to know the elements of the group and I don't have not only a physical regular tetrahedron but also my imagination is not strong. Videos like $1$ or $2$ didn't help, because I can't understand for example what happens to the other $2$ points when the top point and one of the surface points is exchanged.
I would appreciate any simple clear explanation.
Added - For next permutations (with order $3$) now simply we consider the 'surface' under the other three-points, i.e. each time $4$ on top is replaced by $1$ or $2$ or $3$. And, we perform rotations as we were doing when $4$ was on top. So we will get:
'$4$' on top : ${\{(123),(132)}\}$
'$1$' on top : ${\{(234),(243)}\}$
'$2$' on top : ${\{(134),(143)}\}$
'$3$' on top : ${\{(124),(142)}\}$.
But what about $(12)(34)$, $(13)(24)$ and $(14)(23)$? How to get them?
Comment: I find the best way to visualize it is to derive it [geometrically](https://math.stackexchange.com/questions/4862489/geometric-analysis-of-the-motions-of-a-tetrahedron), as explained [there](https://math.stackexchange.com/questions/4862489/geometric-analysis-of-the-motions-of-a-tetrahedron).
Answer: One of them

Use different axes (connecting the midpoints of two opposite edges of the tetrahedron) to get the other products of two disjoint 2-cycles as 180 degree rotations.
Here is the same animation with the cube surrounding the tetrahedron shown as a wireframe. The axis of rotation joins the centers of two opposite faces of the cube
Comment: Another way of thinking about this is to view it as a rotation of the cube surrounding the tetrahedron (the 4 vertices of the tetrahedron are also vertices of the cube)
Comment: It's brilliant! Thank you. Only thing that I struggle with is that "being a **rigid** shape is sufficient that after exchange of 1 and 2, and, 3 and 4 by **one rigid** axis the final configuration coincides with the original one"?
Comment: That depends on the definitions @Alearner. To reflect a regular $n$-gon you either need to use a third dimension to bring the back to the front, or break it into "atoms" (more like invididual points). A reflection (with respect to a codimension one hyperplane) reverses the handedness, be it 2D or 3D. I don't know if reflections are counted among the set of rigid motions?
Comment: A quick sampling of search results suggests that many people (targeting high schoolers and such) include reflections among *rigid motions* @Alearner. In that case you do get $D_n$ as the rigid motions preserving a regular $n$-gon. In this thread we only consider handedness preserving rigid motions. That is, rotations.
Comment: However, I am inclined to trust [Wikipedia](https://en.wikipedia.org/wiki/Rigid_transformation) that specifies *rigid motions* as handedness and distance preserving affine transformations. Caveat: I don't know how pre-college teachers use these concepts. Better to check.
Comment: Sorry I didn't get neither the picture nor the explanation. For example consider (12)(34). In order to change change 1 and 2 with each other, there must be a 180-degree rotation in some axis that pass through the midpoint of 1 and 2 as well. Why this axis of rotation is the axis of rotation which interchange 3 and 4?
Comment: The axis of rotation connects the midpoints of 12 and 34.
Comment: That's a good question. It should become clear that the said rotation is a symmetry, when I add the surrounding cube to the picture. Gimme 5-10 minutes.
Comment: in order to interchange 1 and 2, or, 3 and 4, the mentioned axis must be perpendicular to each of the lines joining 1 and 2, or, 3 and 4. I think that's enough. But I can't prove the perpendicularity.
Comment: @Liebe Those two lines are diagonals of two opposite faces of the surrounding cube. The axis is perpendicular to both of them, because the axis is perpendicular to both those faces.
Comment: Simply explained and perfect answer. Thank you very much indeed. :)
Comment: @ Jyrki Lahtonen nice explanations and animation. Which software do you use ?
Comment: @JeanMarie Mathematica. I only know a tiny fraction of its features, but I learned enough to do these animations when I was teaching courses on introductory abstract algebra and group theory.
Comment: @Jyrki Lahtonen nice explanation sir, thank you, sir, one question , is rigid motion of 3d diagram are equivalent to only symmetries of that diagram?
Comment: That mean rigid motion of $2$d diagram n-gon is clearly dihedral group?
Comment: @Jyrki Lahtonen thank you,sir, for the reply.
Answer: Consider the set of half edges of the tetrahedron. It is easy to convince yourself that the symmetry group of the solid allows you to move from one such half edge to any other in exactly one way. Since there are six edges, there are twelve half edges, and this implies that the group of symmetries has exactly 12 elements.
Now the group obviously permutes the four vertices. Since there is exactly one subgroup of order 12 in $S_4$, namely the alternating group, it must be our group.
Comment: The argument to count the elements of the group works for all regular solids. For example, as a dodecahedron has 30 edges, it has 60 half edges and, therefore, its group of symmetries has order 60.


Find multiple occurances in string

Question: If I have the below string, how can I search through it and return an object with a key represented by {{ key }} and the value set to the word tacked on to it, as in, not! a space in between.
I dont understand how I would look for each occurance in a string thats starts with {{ ...has some name... and ends with }}  as its not always going to be called one two three four as in the example below.
Example:
"The quick {{one}}onyx goblin {{two}}jumps over the {{three}}lazy {{four}} dwarf"

obj={
  one:"onyx",
  two:"jumps",
  three:"lazy",
  four:NULL
}

Note that {{four}} is NULL because its a space before the word dwarf. The word dward is not directly tacked on to {{four}}
grateful for any help,
thank you.
Comment: What if `{{one}}` occurs multiple times?
Comment: doesnt matter.... lets say, store the first occurance and ignore if it shows again.
Answer: You could use a regular expression to locate the braced properties in the input string and their value. Then use Object.fromEntries to turn those key,value pairs into an object. Note that this will take the last value if a property occurs more than once in the string.

const parse = (str) =>
    Object.fromEntries(Array.from(str.matchAll(/\{\{(\w+)}}(\S*)/g), arr =>
        [arr[1], arr[2] || null]));

// demo
let s = "The quick {{one}}onyx goblin {{two}}jumps over the {{three}}lazy {{four}} dwarf";
let result = parse(s);
console.log(result);

If you don't have support for matchAll, then:

const parse = (str) => {
    let regex = /\{\{(\w+)}}(\S*)/g;
    let match;
    let result = {};
    while (match = regex.exec(str)) {
        result[match[1]] = match[2] || null;
    }
    return result;
}
// demo
let s = "The quick {{one}}onyx goblin {{two}}jumps over the {{three}}lazy {{four}} dwarf";
let result = parse(s);
console.log(result);
Comment: Added a version that doesn't use `matchAll`.
Comment: thank you. but what if i dont know the name of the props, but first have to look for them in the string. anything within {{  ... }}
Comment: Added a solution for when you want any property in the string.
Comment: second solution is what im looking for, but im getting an error when testing it on jsbin, "str.matchAll is not a function" : https://jsbin.com/miyaliduwo/edit?js,console
Comment: It is part of current version of JavaScript, EcmaScript 2020. Which version do you support?
Comment: i wouldnt be able to aswer that exactly, but 202 is a bit too fresh for this. but say i would prefer ES5. edit: thanks for added version.
Comment: Using the last version, if the word after braces is a negative number, it does not get added to the object. exmple: {{two}}-1
Comment: What is your requirement for the character that may follow the closing braces? Should a comma be picked up? A slash, a plus, ...etc, ...etc. Can you explain the rule? I updated the answer so it will pick up anything that is not white space.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/227730/discussion-between-jason-and-trincot).
Answer: You can also proceed in the following way:
    let a = (x) =>{
    let obj = {};
    let z = x.split(' ');
     let m = z.filter(x1 => x1.charAt(0) == '{')
    m.forEach(x2=> obj[x2.substr(2,x2.indexOf('}')-2)] = x2.substr(x2.lastIndexOf('}')+1) == '' ? null : x2.substr(x2.lastIndexOf('}')+1))
    console.log(obj);

}

a("The quick {{one}}onyx goblin {{two}}jumps over the {{three}}lazy {{four}} dwarf")

This might solve your query.
Answer: This will work
const str = "The quick {{one}}onyx goblin {{two}}jumps over the {{three}}lazy {{four}} dwarf";
const result = {}

str.split("{{")
    .map(m => ({
        [m.split('}}')[0]]: m.includes("}}")
            && (m.split('}}')[1].split(' ')[0] || null)
    })).filter(e => e[Object.keys(e)[0]] != false).forEach(e => { result[Object.keys(e)[0]] = Object.values(e)[0] })
console.log("result", result)

Answer: This example is a bit verbose, but meets the need for variable names within the {{}}.
This code is a bit verbose, but allows one to read and understand:

const str = "The quick {{one}}onyx goblin {{two}}jumps over the {{three}}lazy {{four}} dwarf";

let output = str.match(/({{\w*}}\w*\b|{{\w*}} )/g).map(sub=>{
   const subArr = sub.replace('{{','').split('}}');
   const o = new Object();
   o[subArr[0]] = subArr[1];
   return o;
});

console.log(output);

Find multiple occurances in string


How do I pass input from a Blazor component to a Core MVC Controller?

Question: Given this Edit.cshtml:
@model User

<form asp-action="Edit">
    <component type="typeof(EditUser)" render-mode="ServerPrerendered" param-User="Model" />
    <input type="submit" value="Save" />
</form>

and this EditUser.razor:
<input class="form-control" type="text" @bind-value="User.Name" />

@code {
    [Parameter]
    public User User { get; set; }
}

with this User.cs model:
public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
}

and this UserController.cs:
// GET
public async Task<IActionResult> Edit(int id)
{
    var user = await _context.Users.FindAsync(id);
    if (user == null)
    {
        return NotFound();
    }

    return View(user);
}

[HttpPost]
public async Task<IActionResult> Edit(int id, [Bind("Id,Name")] User user)
{
    if (ModelState.IsValid)
    {
        _context.Update(user);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }

    return View(user);
}

But this doesn't seem to work, since the User passed into the Edit method is empty. How do I pass the User with the inputted values in the Blazor component to the UserController? Is there any way to get the input values from a Blazor component into the controller at all?
Answer: You should help yourself with a little JavaScript. Basically, it will use JSRuntime (proper way to communicate between Blazor and JS) to send changed data back to the view. It is maybe not exacly how it works under the hood, but you should get the idea :-)

Edit.cshtml:

a) Add a hidden item somewhere in the form section:
<input type="hidden" asp-for="Name" id="Name" />

b) Add some JS at the bottom of Edit.cshtml. This function will get the data from Blazor component and pass them to the input item.

In EditUser.razor:

a) Some changes in your input item - should looks like this:
<input class="form-control" @onchange="async (e) => { User.Name = e.Value.ToString(); await UpdateUserName(); }" value="@User.Name"  />

This enables invoking custom code to send changed data back to the view, using the method mentioned below.
b) In @code section:
public async Task UpdateUserName()
{
    await JSRuntime.InvokeVoidAsync("updateUserName", User.Name);
}

And thats all. I hope it helps.


c++ error: ??? does not name a type

Question: Okay upon running g++ main.cpp -o services
If i do all this in one class lets say .cpp it works fine, but whenever i divide it into another class i keep getting errors, and i really do not understand why, all i did was move the code to another file, and included it.
I am thrown:
<code>[Admin@shadowrealm ircservices]$ g++ main.cpp -o services
In file included from services.cpp:1:0,
                 from main.cpp:4:
services.h:23:2: error: âSOCKETâ does not name a type
services.h:24:2: error: âHOSTENTâ does not name a type
services.h:25:2: error: âSOCKADDR_INâ does not name a type
</code>
services.h:
<code>#ifndef SERVICES_H
#define SERVICES_H

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#include <stdarg.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

class services {

public:
    services(); //perhaps init something important here, dunno
    ~services();
    int connect();

private:
    SOCKET sock;
    HOSTENT* host;
    SOCKADDR_IN address;
};

#endif /* SERVICES_H */
</code>
services.cpp:
<code>#include "services.h"

services::services()
{
//do nothing
}

services::~services()
{
//TODO: incase crash, log why.
}

int services::connect()
{

    return 0;
}
</code>
Comment: Do you define structs called `SOCKET` etc. in main.cpp?
Comment: no, but its defined in services.h so would i need to?
Answer: C++ is case sensitive.
The right is
<code>sockaddr_in
hostent
</code>
If I am not mistaken SOCKET or socket does not name a type at all.
Comment: Oh I see what needs to be done, I just cant use 'socket' directly is all, but thank you!

c++ error: ??? does not name a type


How to access resources that are newly added while running? JAVA SPRING BOOT

Question: I got a spring boot application. Where I serve images from my front end. However, when I serve one it gets saved in the target directory?.
My springboot structure is the standard and I got my images in the src/main/resources/images folder. And I try to read them in using
File fileFolder = new File(new ClassPathResource("/images/").getURI());
However this gives me back the target/images that is build when I run my project. However, I want it to be dynamic so when a image is newly added in I want my app to read them in and give them to my front end. Can anybody help me with this?
Answer: When you build the project, Maven copies the content from src/main/resources to target/classes, hence the images would not have the new images. You should probably use an external directory for such purposes when you want to load the new images that you'll keep on adding on the server.


Expectation of a hitting time

Question: I'm trying to find the expectation of a stopping time. Specifically,

Let $T_1,...,T_n$ be i.i.d exponential random variables with mean $1$. Let $S_n = T_1 + ... + T_n$ denote their partial sum. Define the stopping time,
$$ T = \inf\{n \geq 1 : S_n \geq 1\}$$
which is the first time $S_n$ exceeds $1$. Calculate $E[T]$.

Here was my approach. Let $x = E[T]$. I want to condition on what happens at the first time $T_1$. If $T_1 \geq 1$, then the process, $\{S_n\}$ has stopped and $T \equiv 1$. Otherwise if $T_1 < 1$, then after one step, process, $\{S_n\}$ will renew again until it reaches $1$. So we have the following equation,
\begin{eqnarray} x &=& E[T]\\
&=& E[T | T_1 < 1]P(T_1 < 1) + E[T | T_1 \geq 1]P(T_1 \geq 1)\\
&=& (1+x)P(T_1 < 1) + P(T_1 \geq 1)\\
&=& (1+x)(1-e^{-1}) + e^{-1}
\end{eqnarray}
This results in $x = e$.
However, I was told that the answer is $2$. They gave a heuristic explanation that $S_T$ is distributed as $1 + S$ where $S$ is an exponential random variable with mean $1$. I can see the intuition behind this from the memoryless property, but I can't prove why it is so. I ran three simulations in $\textsf{R}$ and got $x \approx 2.001, 2.0161, 1.9785$, which seems to confirm that the answer is $2$. Can someone explain this result?
Also, why/where did my approach fail?
Comment: When you say $\mathbb{E}[T|T_1 < 1] = 1 + x,$ you're asserting that, in expectation, if the first step doesn't get all the way to $1,$ then the remaining steps have to get all the way to $1$. This is clearly false - if $T_1 = 1/2,$ then $T_2 + \dots T_T$ only have to get up to $1/2$. Since $T_1 > 0$ a.s., we should have $\mathbb{E}[T|T_1 < 1] < 1 + \mathbb{E}[T].$
Comment: A more high level argument is from queuing theory - suppose it takes you $\mathrm{Exp}(1)$ time to do a job. How many jobs will you finish in $1$ unit of time? It is a classical result that this number is $\mathrm{Poission}(1)$ distributed. However, intuitively, the mean is simpler to argue - your rate of doing jobs is $1$ per unit, so you, in expectation, should finish one job per unit (a Little's law type argument). You are interested in this number plus one - which job will you be doing when the time unit finishes.
Comment: I noticed that you wanted a non-heuristic proof - note that $\{T > n\} = \{S_n < 1\}$, since the $S_n$ are non-decreasing. It should be straightforward to figure out $\pi_n := P(S_n<1)$ by establishing a recurrence relation between $\pi_n$ and $\pi_{n-1}$ - you'll likely need the volume of a standard simplex in $n$ dimensions. This will directly give you $P(T = n),$ which you can then use to find the mean.
Comment: @stochasticboy321 Thank you! I was able to do a brute force calculation along these lines.
Comment: ^That's grand, you're welcome :). You should add an answer below, so that others trying the same problem can have a reference.
Comment: @stochasticboy321 I added an answer. If someone can confirm the value of that infinite sum, then I think the solution would be complete.
Answer: Following @stochasticboy321's approach, we want to find $P(T > n) = P(S_n < 1)$. Since $S_n = T_1 + ... + T_n \sim$ Gamma($n,1$), we have,
$$ P(S_n < 1) = \frac{1}{\Gamma(n)}\int_0^1x^{n-1}e^{-x}dx = 1 - \frac{\Gamma(n,1)}{\Gamma(n)}$$
where $\Gamma(n,1)$ is the incomplete Gamma function. To get this expression, I used the nice identity found here. Finally,
$$ E[T] = 1 + \sum\limits_{n=1}^\infty P(T > n) = 1 + \sum\limits_{n=1}^\infty P(S_n<1) = 1+ \sum\limits_{n=1}^\infty\left(1 - \frac{\Gamma(n,1)}{\Gamma(n)}\right)$$
I have no idea how to evaluate the sum in closed form, but a computation in Wolfram Alpha seems to suggest it converges to $1$. Thus, $E[T] = 2$ (at least by conjecture from this numerical computation).
Comment: If we set the integral above to $I_n,$ then by integration by parts, and using $\Gamma(n) = (n-1) \Gamma(n-1) = (n-1)!,$ we get for $n \ge 1,$

$$ P(T > n)  = \frac{I_n}{\Gamma(n)} =  \frac{(n-1) I_{n-1}}{(n-1) \Gamma(n-1)} - \frac{e^{-1}}{{(n-1)!}} = P(T > n-1) - \frac{e^{-1}}{(n-1)!} $$

But then $$P(T = n) = P(T> n-1) - P(T > n) = \frac{e^{-1}}{(n-1)!}.$$ We immediately have that $T \overset{\mathrm{law}}= 1 + Z,$ where $Z \sim \mathrm{Pois}(1),$ and so has mean $2$. Implicitly this also solves the series above (by summation by parts).
Comment: @stochasticboy321 Wow I would give a thousand upvotes if it were possible. Thank you!

Expectation of a hitting time


prevent keyup when input focus

Question: I intent to trigger something with spacebar key, but spacebar should be prevent trigger when input is focus.
I'm trying with this way, but it doesnt work well
is there any suggestion how to do it right.

$(document).ready(function(){
  $('input').on('blur', function(){
    $(document).on('keyup', function(e){
      if(e.keyCode == 32){
        alert("pressed!");
      }
    });
  });
});

<form>
   Name
  <input type="text" />

  Pass
  <input type="text" />
</form>
Comment: To clarify the question: do you want to disable the "triggering something with spacebar" while the input is focused, and when the input loses focus, "trigger something" again?
Comment: I mean, It can be trigger anytime, but when input setfocus trigger is disable
Answer: Detach the handler with .off() while input has focus:

$(function(){
    $(document).on('keyup', function(e) {
        if(e.keyCode == 32){
            alert("pressed!");
        }
    });
    $('input').on('focus', function() {
        $(document).off('keyup');
    });
    $('input').on('blur', function() {
        $(document).on('keyup', function(e) {
            if(e.keyCode == 32){
                alert("pressed!");
            }
        });
    });

});

<form>
   Name
  <input type="text" />

  Pass
  <input type="text" />
</form>
Comment: I see, I didnt notice that event can be stop with .off(), it work good, thank you for suggestion.

prevent keyup when input focus


no 12.04 login after locking user account setting on autologin

Question: I run 12.04 with gnome-classic. I wanted to get autologin since I am the only user.
I unlocked the user account GUI under settings, switched the slider to ON, then locked
the GIU.  Since then a reboot stops at stopping system V runlevel compatibility.
Pressing Ctrl+Alt+F1 then gives me a command-line login.  Typing startx starts
Unity instead of Gnome. In that, I cannot unlock the User Accounts GUI under
settings to set the autologin slider back to OFF.
Comment: @Eliah Kagan: Many thanks. I have unset the root password with your command. I am not sure but in all my mucking around before I might also have unlocked it. The [rootsudo link](https://help.ubuntu.com/community/RootSudo) is very informative. I wasn't aware of graphical sudo usage. I do understand the Ubuntu sudo philosophy (my earlier Mac did the same). I still wonder what I did wrong in the first place. Shifting the Automatic login slider
to ON in the User Accounts GUI seems to
Comment: I'm glad it's working now, and I don't blame you at all for not wanting to continue messing around with a production machine that you now have working properly.
Answer: You can log in on a virtual console (you must be doing that after pressing Ctrl+Alt+F1 but before running startx). So if the problem really is that you set a blank password for yourself (as MeM suggested), you can fix that easily by running:
passwd

Then change it to something that's not blank. You'll know it was changed successfully because the new password will work to log on at a virtual console. (You can type exit or logout to log off, then try logging back on.)
If that doesn't fix the problem, try disabling automatic login by editing /etc/lightdm/lightdm.conf with:
sudo nano -w /etc/lightdm/lightdm.conf

Remove the text that makes automatic login happen. That text looks like:

[SeatDefaults]
autologin-user=<YOUR USER>
autologin-user-timeout=0
user-session=ubuntu
greeter-session=unity-greeter

Source: htorque's answer to How do I enable auto-login in LightDM?
Comment: Thank you.  I now found the way to unlock the User Accounts GUI in the All Settings GUI.  Earlier, I had indeed tried editing /etc/lightdm/lightdm.conf and I had also changed my own user admin account password and added a root account password following the excellent
Comment: http://www.psychocats.net/ubuntu/resetpassword/  Sorry, am new to this forum and keep hitting return which upsets commenting and 5 min isnt enough.  I then used CNTRL+ALT+F1 to login as root, typed startx, get a fresh Unity screen, opened the All settings / Uer accountsGUI, clikced my own account open, slid the autologin slider to off, rebooted. OK.  Maybe the bug was trying to set the autologin sider to ON in Gnome-classic?  Should I know remove the root password again?  How?
Comment: @Rob If you really did set a password for the root account, you can  [re-disable](https://help.ubuntu.com/community/RootSudo#Re-disabling_your_root_account) it with `sudo passwd -dl root`. But you didn't have to do that; if you wanted to run X11 is root (generally *not* recommended), you could have used `sudo startx`. Once you have a GUI, you can run graphical programs in it with `gksu`/`gksudo`. [Here are the details.](https://help.ubuntu.com/community/RootSudo). BTW your psychocats.net link has broken images--[this is the correct link](http://www.psychocats.net/ubuntu/resetpassword).
Answer: If it happened because you didn't specify a password for the adm account or set it to not asking for a password on log in, I recomend resetting the password, here is how to do it (either one):

How to reset your password in Ubuntu
How do I reset a lost administrative password?

Then it should work. (Yes this is a lousy bug on Ubuntu, hope they fix it.) If that is not the case, then I don't have a clue either!
Comment: Do you know if this bug has been reported? If so, can you edit your answer to include a link to the bug report? If not, [it should be](https://help.ubuntu.com/community/ReportingBugs).
Comment: Thank you.  I now found the solution. Earlier, I had indeed tried editing /etc/lightdm/lightdm.conf and I had also changed my own user admin account password and added a root account password following [this excellent recipe](http://www.psychocats.net/ubuntu/resetpasswd). To no avail. I now logged in with CNTRL+ALT+F1 as root with this root passwd, typed startx, got a fresh Unity startup screen, went into the All Settings/User Accounts GUI, clicked my user account open under Other Accounts.  No lock/unlock clicker now.  Shifting autologin to off did the trick.  Maybe bug in Gnome-classic?


How are the regions connected?

Question: There are 6 regions in Pokemon, each one introduced in a new generation of games. In the second generation, I remember being able to travel to the first region, but other than that, that is the only connection I know between the regions.
Now, I know each of theses regions have representations in the real world (mostly based on Japan, though Gen VI is based on France, I believe), but what about in game? Is there any connections between the regions other than the first two? And is there any explanations given about the other regions? Or does each successive generation introduce new Pokemon, and a new region, and completely ignore that the previous region existed?
Answer: Beyond Gold, Silver, Crystal, and the modern remakes, HeartGold and SoulSilver, none of the flagship pokemon games have ever spanned more than one region (though several have included isolated islands or otherwise remote areas). So "as far as we know", only the Johto and Kanto regions are confirmed to be nearby (and are, in fact, adjacent).
As mentioned in Bulbapedia, however, the first four generations are all analogous to real-life parts of Japan, while the fifth generation maps to the New York Metropolitan area, and Kalos (6th and current gen) maps to real-world France.
I wouldn't go so far as to say that the previous regions are completely ignored (Oak, at least, has made it to Hoenn on more than one occasion), but beyond the previously mentioned exceptions (and monsterous residents, which feature previous generation pokemon in their "National Dex"), each region is pretty much distinct.
Comment: Several people mention that Proffesor Sycamore has worked with Professor Rowan from Sinnoh and the Gen V legendaries are oldish statues in Parfum Palace. And Unova is mentioned explicitly multiple times so we can assume it is nearby enough to Kalos for even ancient methods of travel.
Comment: @Reafexus in Pokemon world ancient methods of travel include subsonic flight.
Comment: The special arceus event in HGSS also established that in the pokemon world, Johto and Sinnoh are right next to each other. (Sinjoh Ruins)
Answer: There is an in-game myth that Unova is directly connected to Sinnoh through the deepest part of the Cave of Being in Unova. (I've tried. It doesn't work.)
Answer: Kalos and hoenn should be near because, the looker from X and Y's looker quest went to hoenn and if you go to the battle resort, on a certain spot of the island you can find an amnesiac looker washed up on the shore.
Comment: Welcome to Arqade. Could you add any more detail into your answer?

How are the regions connected?


xrandr settings changed. Display now won't run

Question: I was trying to use xrandr to have a script to adjust my monitor resolution. As a test I ran
xrandr -s 1360x768

This should be a valid setting. It  killed the xserver. I changed to tty6 tried running
xrandr -s 1600x900

And rebooting but the reboot freezes on the KDE splash screen (I am using Kubuntu 14.04)
I can change to a TTY terminal to run xrandr but if I try -s or (-q) settings I get "can't open display"
If I try with "xrandr -d :0" I can use -q but I am not sure which display I would need.
Trying
xrandr -d :0 --output LVDS1 --auto

Returns: Configure ctrc 0 failed
I am on my phone so I can't easily paste in the result of
xrandr -d :0 -q

But I notice there is no * by any option. Should there be?
Answer: It seems that xrandr permanently made a new settings file in
~/.kde/share/apps/kscreen

The old one was still available so I backed up the folder and deleted the newest settings file and everything works again.


KeyError: 'Value' when running slither on a contract

Question: Python version: 3.8.5
Solc version: 0.7.0+commit.9e61f92b.Linux.g++
Slither version: 0.6.13
When trying to run slither . on a solidity contract I get the following stack trace:
Traceback (most recent call last):
  File "/home/wirel/.local/lib/python3.8/site-packages/slither/__main__.py", line 692, in main_impl
    ) = process_all(filename, args, detector_classes, printer_classes)
  File "/home/wirel/.local/lib/python3.8/site-packages/slither/__main__.py", line 79, in process_all
    ) = process_single(compilation, args, detector_classes, printer_classes)
  File "/home/wirel/.local/lib/python3.8/site-packages/slither/__main__.py", line 62, in process_single
    slither = Slither(target, ast_format=ast, **vars(args))
  File "/home/wirel/.local/lib/python3.8/site-packages/slither/slither.py", line 100, in __init__
    self._parser.analyze_contracts()
  File "/home/wirel/.local/lib/python3.8/site-packages/slither/solc_parsing/slitherSolc.py", line 338, in analyze_contracts
    self._analyze_first_part(contracts_to_be_analyzed, libraries)
  File "/home/wirel/.local/lib/python3.8/site-packages/slither/solc_parsing/slitherSolc.py", line 395, in _analyze_first_part
    self._parse_struct_var_modifiers_functions(contract)
  File "/home/wirel/.local/lib/python3.8/site-packages/slither/solc_parsing/slitherSolc.py", line 461, in _parse_struct_var_modifiers_functions
    contract.parse_state_variables()
  File "/home/wirel/.local/lib/python3.8/site-packages/slither/solc_parsing/declarations/contract.py", line 303, in parse_state_variables
    var_parser = StateVariableSolc(var, varNotParsed)
  File "/home/wirel/.local/lib/python3.8/site-packages/slither/solc_parsing/variables/state_variable.py", line 9, in __init__
    super().__init__(variable, variable_data)
  File "/home/wirel/.local/lib/python3.8/site-packages/slither/solc_parsing/variables/variable_declaration.py", line 65, in __init__
    self._init_from_declaration(variable_data, variable_data["value"])
KeyError: 'value'
ERROR:root:None
ERROR:root:Error in .
ERROR:root:Traceback (most recent call last):
  File "/home/wirel/.local/lib/python3.8/site-packages/slither/__main__.py", line 692, in main_impl
    ) = process_all(filename, args, detector_classes, printer_classes)
  File "/home/wirel/.local/lib/python3.8/site-packages/slither/__main__.py", line 79, in process_all
    ) = process_single(compilation, args, detector_classes, printer_classes)
  File "/home/wirel/.local/lib/python3.8/site-packages/slither/__main__.py", line 62, in process_single
    slither = Slither(target, ast_format=ast, **vars(args))
  File "/home/wirel/.local/lib/python3.8/site-packages/slither/slither.py", line 100, in __init__
    self._parser.analyze_contracts()
  File "/home/wirel/.local/lib/python3.8/site-packages/slither/solc_parsing/slitherSolc.py", line 338, in analyze_contracts
    self._analyze_first_part(contracts_to_be_analyzed, libraries)
  File "/home/wirel/.local/lib/python3.8/site-packages/slither/solc_parsing/slitherSolc.py", line 395, in _analyze_first_part
    self._parse_struct_var_modifiers_functions(contract)
  File "/home/wirel/.local/lib/python3.8/site-packages/slither/solc_parsing/slitherSolc.py", line 461, in _parse_struct_var_modifiers_functions
    contract.parse_state_variables()
  File "/home/wirel/.local/lib/python3.8/site-packages/slither/solc_parsing/declarations/contract.py", line 303, in parse_state_variables
    var_parser = StateVariableSolc(var, varNotParsed)
  File "/home/wirel/.local/lib/python3.8/site-packages/slither/solc_parsing/variables/state_variable.py", line 9, in __init__
    super().__init__(variable, variable_data)
  File "/home/wirel/.local/lib/python3.8/site-packages/slither/solc_parsing/variables/variable_declaration.py", line 65, in __init__
    self._init_from_declaration(variable_data, variable_data["value"])
KeyError: 'value'

Here is the contract:
// SPDX-License-Identifier: UNLICENSED
//     _____          __         .____           __    __
//    /  _  \  __ ___/  |_  ____ |    |    _____/  |__/  |_  ___________ ___.__.
//   /  /_\  \|  |  \   __\/  _ \|    |   /  _ \   __\   __\/ __ \_  __ <   |  |
//  /    |    \  |  /|  | (  <_> )    |__(  <_> )  |  |  | \  ___/|  | \/\___  |
//  \____|__  /____/ |__|  \____/|_______ \____/|__|  |__|  \___  >__|   / ____|
//         \/                           \/                     \/       \/
// Automatically draws a winner once the payout threshold is met

pragma solidity ^0.7.0;

contract AutoLottery {
    address[] public players;
    uint256 public totalPayoutValue;
    uint256 public currentPrizePool;
    address public lastWinner;
    uint256 public lastPayout;
    address public owner;

    constructor() {
        totalPayoutValue = 0 ether;
        currentPrizePool = 0 ether;
        lastPayout = 0 ether;
        owner = msg.sender;
    }

    // Allow a player to enter, value entered must be 0.01 or greater
    function enter() public payable {
        require(msg.value >= 0.01 ether, "You must enter 0.01 or more Ether!");
        players.push(msg.sender);
        currentPrizePool += msg.value;
        if (address(this).balance >= 1.00 ether) {
            winner();
        }
    }

    // Choose a winner at random
    function winner() internal {
        require(address(this).balance >= 1.00 ether, "Not enough eth in prize pool!");

        uint index = random() % players.length;

        totalPayoutValue += address(this).balance;
        lastWinner = players[index];
        lastPayout = address(this).balance;

        payable(players[index]).transfer(address(this).balance);

        delete players;
    }

    // Creates a random number
    function random() private view returns (uint) {
        return uint(keccak256(abi.encode(block.difficulty, block.timestamp, players)));
    }

    // Returns a list of all currently entered players
    function getPlayers() public view returns (address[] memory) {
        return players;
    }

    // The owner of the contract can force a draw if its been too long since the last draw
    function emergencyDraw() public {
        require(msg.sender == owner, "Only the owner can call this method!");

        uint index = random() % players.length;

        totalPayoutValue += address(this).balance;
        lastWinner = players[index];
        lastPayout = address(this).balance;

        payable(players[index]).transfer(address(this).balance);

        delete players;
    }

}

Any ideas on how I could solve this issue? So far I have tried re-installing python, slither and solc and even tried installing slither from docker but get the same result.
Answer: It was an error within Slither itself, it should be fixed in new update.
Comment: Hi, how can I use Slither to test sample contract distributed by the docker image. Nearly all of them have compiler versions 0.4.15. This makes it possible to use them for demonstrations and using solc-select, I can not have that version. What do you suggest?


Should I use shipping estimate calculator on product page?

Question: It's almost like common sense (at least by observing many different online stores) to show a shipping estimate cost on the shopping cart page. With this, the user have the information of how much the full purchase will cost before entering the checkout process, where he will finally complete the transaction.
But... How about the product page. Does it make sense to show the same shipping calculator also on the product page?
If the user is only selecting one product, It seems fine. The final shipping cost will be the same in the cart page. However, if the user already has other products on the shopping cart, the shipping estimate on the product page would return a cheaper value than the full shopping cart.
Is there any other thing to consider to decide wether or not to put it on the product page.
Answer: When you mean shipping estimate there's 2 factors to consider. How soon and how much? (Also consider that free shipping is actually common among regional e-commerce stores)
Some websites show these as USPs e.g. Free shipping above 40$, shipping within 3 days. While these are generic rules, they give customers assurance early in their journey on the online store.
To answer your question, you can show the shipping estimate at different points your users journey. On the catalog(as a filter), product, cart or checkout. The sooner the user knows the shipping cost the easier it will be to make an informed decision? For this you might want to do some user testing on actual users to see what works on your online shop.
Also consider to be able to calculate shipping cost you will need your customer to give some input about where the delivery will be to. One example i've seen is where users can select their city or their postal code. of course this will give an estimate. Hope this helps.


Safety hook on double pole circuit breakers

Question: My home was built two years ago, so I would expect everything to have been done up to code. The problem is that I don't know what the metal ring in this photo is. It loops over the double pole circuit breakers, but only if in the off position. When hooked over the circuit breakers, the metal ring appears to prevent them from being pushed into the on position. The problem is, if the circuit breakers are turned on, and the metal ring were to flip over (it's fairly free to rotate), then the circuit breakers are prevented from flipping into the off position. Isn't this a valid safety concern? Yet I am confused because the hooks on these circuit breakers appear to be made to do this as seen by the hooks I have pointed out via green arrows (green speckles follow the loop I am talking about).
I am seeking to learn:

What is this gizmo named?
Is my safety concern valid?
Comment: you failed to notice another hardware component and you have not noticed the label .... look again
Comment: 'expect everything to have been done up to code' I've now several several cases where new buildings are not up to code. Never assume and have an expert check if required.
Answer: This is a breaker lockoff device
The gizmo on your water heater breaker is a lockoff that's designed to let you turn the breaker off, then attach a padlock with a 1/4" shackle (or a lockout tag with padlock(s) on it), so that you can then lock the padlock, stick the key in your pocket, and be sure that some bozo isn't going to flip the breaker back on while you are servicing the water heater.  Code often requires this when the breaker is the only disconnecting means for the load in question and the breaker box is not visible from where the load is located.
And no, it won't screw up the breaker's ability to trip
Modern circuit breakers are universally trip free (UL489 and related standards require this behavior, even), which means that they will trip properly, no matter what position the handle is held in.  As a result, it is possible (and even required, for breakers feeding fire alarm control panels in larger buildings) to safely lock a breaker on with the appropriate hardware, even, and you do not have to worry about mechanical blockages outside the breaker itself keeping the breaker from tripping.
Comment: @Criggie -- not really, I'm not sure what the range of motion on said loop is even (and you wouldn't want to break it, that'd make for a rather annoying repair callout, considering lockoffs are required by Code in several different sections)
Comment: Would it be useful to flip the loop hard to the right and tape it down to the grey-painted metal of the enclosure?  Or just as a sop to OP's conscience to know that nothing short of an earthquake could flip the loop to the left ?


Starcraft 2: What are "mechanics"?

Question: Every SC2 tutorial emphasizes that beginners are best served by focusing on two aspects of the game: (i) mechanics and (ii) macro.
I understand what is meant by "macro" (i.e., making sure you're constantly collecting resources, producing units/buildings, and expanding when appropriate).
My question: what do experienced SC2 players refer to when they say "mechanics"?  Is it simply fluency in the various keyboard hotkeys used when macro-ing / micro-ing?
Comment: Just going to leave this here: http://en.m.wikipedia.org/wiki/Game_mechanics
Answer: Mechanics refers to the game engine and all possible interactions with it. While you do not need to execute every action perfectly, you need to be aware that it is possible. Without time pressure you should know how to execute every command in the game and understand its result. This is not limited to the race you play.
To learn these start with the most obvious ones and work your way to the more hidden mechanics:

Learn and use all hotkeys
Learn all units their abilities, upgrades, strengths and weaknesses (e.g. EMP removes all energy and shields from all enemies in the area of effect additionally it reveals cloaked units)
Know the tech trees and requirements for each unit and building
Understand the basics of each races bonus: SCVs, scans, larva injects and chrono boost
Use the interface (e.g. minimap and resources display)
Understand the benefits and consequences of burrowed and stealth units
Understand how warp in and nydus worms work
Learn how HP and shield regeneration work
Animation canceling (aka stutter step)
...

Many of the mechanics are introduced in the campaign. For the more advanced mechanics you either need to look at forums or listen to professional matches with casters. From time to time they explain what just happened.
Comment: Most of the things you have listed would not be classified as "mechanics". To have good mechanics you don't need to know what an upgrade is but you should be able to research while doing everything else. Mechanics is simply the execution of everything.
Answer: Mechanics do not always refer to the game engine and all possible interactions with it, but rather, the proper thought process and execution. A player that has good mechanics is one that understands the game well enough to make split second decisions, and have a clear understanding of their long term and short term goals. Often you will see this in the form of choosing the better of multiple scenarios, or simply preparing ahead of time for the potential threats that could come their way.

Every SC2 tutorial emphasizes that beginners are best served by focusing on two aspects of the game: (i) mechanics and (ii) macro.

Macro is your base management, and Mechanics are your ability to react and adapt accordingly. To know when it is optimal to scout your opponent and how to react to what you do scout.

Starcraft 2: What are "mechanics"?


How to convert multiple tiff file to png files using gmmagick?

Question: I have to convert multipple tiff to separate png files.For isntance i have a tiff file which have a 3 pages and i'd like to convert it 3 separate png's.In below code i could only convert first page of tiff file into png.
gm(__dirname+'/Tiff/Recorded.tiff').write(__dirname+'/Png/cpng.png',(err)=>{
if(!err){
    console.log('Done');
}
else {
    console.log(err);
}

});
How could i convert for example a second page of this tiff file?
And second question regarding adding a tiff file into another tiff.For example i have tiff file with one page and have second tiff file with three pages? I investigate  i have found the append method but it was not working.The code below!
gm(__dirname+'/Tiff/Recorded.tiff')
.append(__dirname+'/Tiff/another.tiff').append(false);

could i add the tiff with one  page into the tiiff with three pages and get a one tiff file with four pages?
Comment: Your question is not very clear. Do you mean you have `file1.tif` and `file2.tif` and `file3.tif`? Or do you mean you have `file.tif` and it contains three pages?
Comment: Sorry if i didi not write clear.I mean that i have file1.tiff  which have 1 page, and have file2.tiff which have 3 pages.so in final result i would like  to have one  tiff file with 4 pages.But i do not want to create a new file, just add the single page tiff into tiff which have 3 pages. In other words i would like to append  file1.tiff with file2.tiff and as a result get one tiff file with 4 pages.
Answer: Your question is quite unclear, so I will show you some examples and you can extract the bits you need.
Let's say we start with a single TIFF file, called 6page.tif, that has 6 pages in it. Let's see how many pages there are:
gm identify 6page.tif
6page.tif[0] TIFF 595x842+0+0 DirectClass 16-bit 17.2Mi 0.000u 0m:0.000000s
6page.tif[1] TIFF 595x842+0+0 DirectClass 16-bit 17.2Mi 0.000u 0m:0.000000s
6page.tif[2] TIFF 595x842+0+0 DirectClass 16-bit 17.2Mi 0.000u 0m:0.000000s
6page.tif[3] TIFF 595x842+0+0 DirectClass 16-bit 17.2Mi 0.000u 0m:0.000000s
6page.tif[4] TIFF 595x842+0+0 DirectClass 16-bit 17.2Mi 0.000u 0m:0.000000s
6page.tif[5] TIFF 595x842+0+0 DirectClass 16-bit 17.2Mi 0.000u 0m:0.000000s

Ok, 6 pages, numbered 0-5.
Let's extract page 3 to a PNG:
gm convert 6page.tif[3] JustPage3.png

Let's append the extracted page 3 to the end of the original tif:
gm convert 6page.tif JustPage3.png BigBoy.tif

Now check what we have got - yes, 7 pages:
gm identify BigBoy.tif
BigBoy.tif[0] TIFF 595x842+0+0 DirectClass 16-bit 17.7Mi 0.000u 0m:0.000000s
BigBoy.tif[1] TIFF 595x842+0+0 DirectClass 16-bit 17.7Mi 0.000u 0m:0.000000s
BigBoy.tif[2] TIFF 595x842+0+0 DirectClass 16-bit 17.7Mi 0.000u 0m:0.000000s
BigBoy.tif[3] TIFF 595x842+0+0 DirectClass 16-bit 17.7Mi 0.000u 0m:0.000000s
BigBoy.tif[4] TIFF 595x842+0+0 DirectClass 16-bit 17.7Mi 0.000u 0m:0.000000s
BigBoy.tif[5] TIFF 595x842+0+0 DirectClass 16-bit 17.7Mi 0.000u 0m:0.000000s
BigBoy.tif[6] TIFF 595x842+0+0 PseudoClass 65536c 16-bit 17.7Mi 0.000u 0m:0.000000s

Comment: oh thank you!  but how i can do this functionality with node js code instead of cmd command?i mean that all this action i would like to perform  through node js not through cmd?is it possible??sorry i just newbee in node  and  sometimes i can give obvious questions
Answer: The imagemagick command is convert images.tiff image%02d.png.
I'm not familiar with the gm module; I would just use child_process for this.
Answer: Take a look this npm module https://www.npmjs.com/package/gm
Also this documentation especially the part of adjoin function
http://aheckmann.github.io/gm/docs.html
From documentation about adjoin function.
join images into a single multi-image file By default, all images of an image sequence are stored in the same file. However, some formats (e.g. JPEG) do not support storing more than one image per file and only the first frame in an image sequence will be saved unless the result is saved to separate files. Use +adjoin to force saving multiple frames to multiple numbered files. If +adjoin is used, then the output filename must include a printf style formatting specification for the numeric part of the filename.
Comment: i will take a look .


How can I insert data from an Access form into a sql table using VBA?

Question: Here is what I have, I'm trying to take fields from an Access form (data comes from one linked sql table) and insert them into another linked sql table:
StrSQL = "INSERT INTO [dbo_Expense_Projection] ([StatusID],[TravellerUFID],[Email]) " & _
          VALUES(" & Me.StatusID & ", " Me.TravellerUFID & ", " Me.SubmitterUFID & ", " Me.email & ")
DoCmd.RunSQL StrSQL

But I am getting this error
Compile error: Sub or Function not defined

Answer: I think you are just missing some double quotes:
StrSQL = "INSERT INTO [dbo_Expense_Projection] ([StatusID],[TravellerUFID],[Email]) " & _
"VALUES(" & Me.StatusID & ", " Me.TravellerUFID & ", " Me.SubmitterUFID & ", """ & Me.email & """)"
DoCmd.RunSQL StrSQL

You can try to print the contents of StrSQL and check the query before running it:
Debug.Print StrSQL

but I prefer not to create SQL strings with concatenated values (what happens if Me.StravellerUFID contains a double quote?)
I would suggest you to insert data using DAO:
Dim rs as Recordset
Set rs = CurrentDb.OpenRecordset("dbo_Expense_Projection")
rs.AddNew
rs!StatusID = Me.StatusID
rs!TravellerUFID = Me.TravellerUFID
' ...other fields
rs.Update
rs.Close

Comment: There is a lot to be said for parameters. They scale better if you need to change the back-end.
Answer: There are also some ampersands missing in the SQL-String:
StrSQL = "INSERT INTO [dbo_Expense_Projection] ([StatusID],[TravellerUFID],[Email]) " & _
          "VALUES(" & Me!StatusID & ", " & Me!TravellerUFID & ", " & Me!SubmitterUFID & ", """ & Me!email & """)"

And I think you should use exclamation mark between "Me" and fieldname. But I do not want to argue with the experts here about that... ;)
Answer: Here is what ended up working:
Dim StrSQL As String

StrSQL = "INSERT INTO dbo_Expense_Projection (StatusID,TravellerUFID,Email)
          VALUES('" & Form!StatusID & "','" & Form!TravellerUFID & "','" & Form!Email & "')"

DoCmd.SetWarnings False
DoCmd.RunSQL StrSQL
DoCmd.SetWarnings True


Valgrind out of memory

Question: This is the message I get when valgrind crashes and stops profiling my app:
<code>    ==16317==
    ==16317==     Valgrind's memory management: out of memory:
    ==16317==        newSuperblock's request for 4194304 bytes failed.
    ==16317==        3013349376 bytes have already been allocated.
    ==16317==     Valgrind cannot continue.  Sorry.
    ==16317==
    ==16317==     There are several possible reasons for this.
    ==16317==     - You have some kind of memory limit in place.  Look at the
    ==16317==       output of 'ulimit -a'.  Is there a limit on the size of
    ==16317==       virtual memory or address space?
    ==16317==     - You have run out of swap space.
    ==16317==     - Valgrind has a bug.  If you think this is the case or you are
    ==16317==     not sure, please let us know and we'll try to fix it.
    ==16317==     Please note that programs can take substantially more memory than
    ==16317==     normal when running under Valgrind tools, eg. up to twice or
    ==16317==     more, depending on the tool.  On a 64-bit machine, Valgrind
    ==16317==     should be able to make use of up 32GB memory.  On a 32-bit
    ==16317==     machine, Valgrind should be able to use all the memory available
    ==16317==     to a single process, up to 4GB if that's how you have your
    ==16317==     kernel configured.  Most 32-bit Linux setups allow a maximum of
    ==16317==     3GB per process.
    ==16317==
    ==16317==     Whatever the reason, Valgrind cannot continue.  Sorry.
</code>
I 've tried using huge swap files but it doesn't get better.
The crash happens long before my swap file is nearly full.
I 'm using Fedora 19.
Does anyone know anything about this?I think I read something on the internet about how there may be a limit to the memory a single process can allocate.If this is the case ,where can I set it?At least give me a good alternative to valgrind people :P.
Thanks in advance
Comment: Judging from the title I'd say you've got some memory leaks. You should run it through- crap.
Answer: " Most 32-bit Linux setups allow a maximum of 3GB per process."
You've allocated 3013349376 bytes, which is awfully close to 3GB. So you probably have a 32-bit OS, and you're just running out of memory for a single process (the other ~200 megs are probably valgrind overhead)

Valgrind out of memory


Can you run the same loop simultaneously 3 times in a single bash script?

Question: If you could just point me in the right direction I'm sure I could figure it out eventually.
I have a loop that works from i=1 to i=75.  But I am able to run this a maximum of 3 times concurrently so all I could figure out is running it in 3 separate terminals as i=1 to i=25, i=26 to i=50, and i=51 to i=75.
Ideally I would want it run in the same script and for all 3 instances of the loop simultaneously and to begin at i=1 and end at i=75, however without overlapping i's which have been completed or are being completed by a different instance of the loop.
Example processing:

Loop1 begins i=1
Loop2 skips i=1, Loop2 begins i=2
Loop3 skips i=1,2, Loop3 begins i=3
Loop2 completes i=2, Loop2 skips i=3, Loop2 begins i=4
Loop3 completes i=3, Loop3 skips i=4, Loop3 begins i=5
Loop1 completes i=1, Loop1 skips i=2,3,4,5 Loop1 begins i=6
Loop1 completes i=6, Loop1 begins i=7
Loop3 completes i=5, Loop3 skips i=7, Loop3 begins i=8

the structure of the loop is basically like this
u=0
while [ $u -lt 1000 ]
do
    ((u++))
    i=$1
    while [ $i -le $2 ]
    do
        curl #(that sends begining command $i)
        sleep 60
        variable1=$(curl $i) #command that outputs a number which can change every 60 seconds
        variable2=$(curl $i) #command that outputs a number which is static
        counter=0
        until [ variable1 -ne $variable2 ]
        do
            ((counter++))
            echo waiting 60 seconds
            echo times waited: $counter
            sleep 60
            variable1=$(curl $i) #command that outputs a number which can change every 60 seconds
            variable2=$(curl $i) #command that outputs a number which is static
        curl #(that sends ending command $i)
        ((i++))
        done
done

Answer: I provide a simple way to accomplish this, and I let you to customize it per your needs:
#!/bin/bash

function myLoopFunction {
  param1 = $1
  param2 = $2

  # Some code...
}

myLoopFunction value1a value2a & # Run 1
myLoopFunction value1b value2b & # Run 2
myLoopFunction value1c value2c & # Run 3

wait # Wait for termination...

Comment: are they able to pass variables through each other like that? so if the Run 2 function changes a variable x from 2 to 3 will Run 1 be able to see that x is now 3 not 2?
Comment: Sure, I edit it for you...
Answer: N=3
for (( i = 0; i < N; i++ ))
do (
    switch $i in
       0) setup_loop_0 ;;
       1) setup_loop_1 ;;
       2) setup_loop_2 ;;
    esac

    echo any commands
    sleep 2
    echo finish
)& done
wait

Notes:

N=3 defines the number of parallel executions.
for (( i = 0; i < N; i++ )); do ... done for loop like in other languages
You can write (( i = 1; i <= N; i++ )) instead of (( i = 0; i < N; i++ )) to get values 1..3 instead 0..2 for variable i.
( ... ) declares a sub-shell.
The & behind ) starts the sub-shell in the background
wait waits until all sub-shells are terminated.


How to display Python web application exceptions in PHP-like manner

Question: In this project I must use Python for a website, I'm looking for the errors to go in my browser instead of getting a 500 page. Any tip ?
Addition
I'm just using plain CGI nothing fancy
I tried this as explained here but it does not work
#!/usr/bin/env python
print "Content-Type: text/plain"
print
import sys
sys.stderr = sys.stdout
f = open('non-existent-file.txt', 'r')

Comment: Are you using a web framework? If so, which?
Comment: Similarly, what server are you using?
Comment: I'm using Apache2 and no framework
Answer: It depends on your Python web framework settings.
For example, Pyramid framework has various setting for enabling traceback in web browser and start an interactive debugging session:
http://docs.pylonsproject.org/projects/pyramid/en/1.3-branch/narr/introduction.html#debugging-settings
It all depends on how your Python web application is wired up and what architecture it uses and so on. Please include full context information in the question for further help.
More information about debugging web applications with Python and WSGI:
http://code.google.com/p/modwsgi/wiki/DebuggingTechniques
If you are not using any framework you need to put everything inside a main level try...except block as Python standard library does not provide tools to convert exceptions to HTML.
  import traceback

  try:
       ...
  except Exception as e:
       # Set content type as text/plain (don't know how)
       traceback.print_exc(e)  # Print out exception as plain text

Comment: apache2 and python3, no framework, also not WSGI but its on my plan to  move to it
Comment: If you are plain Python with no framework, such functionality is not provided. You can write main level HTTP request handling function, which caches the exception and converts it to HTML page. More info about Python exception handling tools: http://docs.python.org/2/library/traceback.html
Answer: I ended up creating a script reading the errors in error.log.
So instead of getting your errors in the same tab you have another tab for them. However don't forget to remove the script avoiding giving info about your system.
#! /opt/python3/bin/python3
#Error Log Viewer

import subprocess

p = subprocess.Popen('cat /var/log/apache2/error.log | tail -5', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

print ('Content-type: text/html\n\n')
print ('''
<!DOCTYPE html >
  ''')
for line in p.stdout.readlines():
    print (line,'
')
print('''''')


Infinite groups admitting field structure

Question: Does every infinitely generated Abelian group admit a field structure?
(i.e. If $(G,+)$ is an infinitely generated Abelian group, then,
is there a binary operation "$\cdot$" such that $(G,+,\cdot)$ is a field?)
Is there any characterization (or classification) of such these groups
(admitting field structure) ?
(What about Abelian groups admitting ring structure with nontrivial multiplication?)
Answer: A field is a vector space over its prime field, so its additive group is either a group of prime exponent $p$, or a torsion-free divisible group, depending on the characteristic. Conversely, any such abelian group is an additive group of an extension of $\mathbb F_p$ or $\mathbb Q$ of appropriate degree.
Comment: Emil: your answer just provides the explanation of my counterexample.
Answer: No. Consider for instance the direct product of all groups of distinct prime order.
Answer: This question is discussed already in MO and  you can find the answer in the links below:
1- https://mathoverflow.net/questions/154852/a-basic-question-about-rings/154882#154882
2- https://mathoverflow.net/questions/154964/is-every-commutative-group-structure-underlying-at-least-one-unitary-commutati/154979#154979
3- https://mathoverflow.net/questions/155179/potentially-identity-elements-in-an-abelian-group


Test for item in output slot of furnace

Question: When i put this command in a command block:
/testforblock ~ ~1 ~-3 minecraft:furnace 0 {Items:[{id:"minecraft:iron",Slot:1b}]}

It gave this error:
The block at 137,85,401 is Furnace (expected: Furnace).

And when i put this in the command block:
/testforblock ~ ~1 ~-3 minecraft:furnace {Items:[{id:"minecraft:iron",Slot:1b}]}

It gave this error:
'{Items:[{id:"minecraft:iron",Slot:1b}]}' is not a valid number

I'm trying to test for an iron ingot in the output slot. Anyone know how to do this?
Answer: There are two types of furnaces:

furnace (furnace turned off)
lit_furnace (Furnace when burning something)

The data Value has to be -1 or the actual rotation of the furnace (-1 means it does not matter).
So change your command to:
/testforblock x y z minecraft:lit_furnace -1

The output slot is 2b and iron is called iron_ingot:
/testforblock x y z minecraft:furnace -1 {Items:[{Slot:2b,id:"minecraft:iron_ingot"}]}
/testforblock x y z minecraft:lit_furnace -1 {Items:[{Slot:2b,id:"minecraft:iron_ingot"}]}

You would have to test if one of these testfors was successful (basically do your redstone 2 times, one for each command).
Source.
Comment: You can use a data value of `-1` to match all possble data values.
Comment: Thats nice, didn't now that
Comment: Thx for the edit

Test for item in output slot of furnace


Is the following in $L^2$?

Question: Suppose we have a probability space $X\times Y$ and product measure $\mu=\mu_X\times \mu_Y$.
Given $f\in L^2(X\times Y)$, I can write $f(x,y)=\sum_{j=1}^{d}\sum_{k=1}^da_{j,k}(x)b_{j,k}(y)$ for some $d\in \mathbb{N}$, $a_{j,k}(x)$ non-zero and $b_{j,k}:Y\to \mathbb{R}$. Can I conclude that each $b_{j,k}\in L^2(Y)$?
Is this just a consequence of Fubini's theorem? Or can this be seen by writing $b_{j,k}$ in terms of $f$? If not, are there further conditions one could impose on the $a_{j,k}$? E.g. boundedness... Thanks!
Answer: No you cannot. Consider a function $b(y)$ with $\int |b| d\mu_Y=\infty$. Now clearly the function $f(x,y)=0$ is in $L^2(X,Y)$, but we can also write $f$ as $b(y)+b(y)+(-b(y))+(-b(y))$, where the functions $a_{i,j}(x)=1$ are non-negative.
You cannot even conclude that the functions $b_{i,j}$ are measureable, since we could do the same trick for a non-measurable function b.
If we however impose, that the $b's$ are non-negative and measurable, then
$a_{i,j}b_{i,j} \leq f$ for all $i,j$, and if $a_{i,j}$ are bounded by a constant $C$ we would have $b_{i,j} \leq \frac{f}{C}$, where $\frac{f}{C}\in L^2.$

Is the following in $L^2$?


Using "declare" in Zsh

Question: I am following this thread: https://stackoverflow.com/a/19742842/5057251
for typeset (or declare) in ZSH, not BASH.
#Declare (or typeset) an array of integers
#declare -ai int_array
typeset -ai int_array
int_array=(1 2 3)
echo "${int_array[@]}"

Then
# Attempt to change 1st element to string. (expect to fail)
int_array[1]="Should fail" || echo "error: ${LINENO}"
echo "${int_array[@]}"

Bash finds the error, gracefully reports error and lineno, prints:
1 2 3

But Zsh accepts, prints:
Should fail 2 3

Not sure why different.
Answer: There are two problems here:

In bash, and zsh, assigning a string to an integer variable causes that string to be evaluated as an arithmetic expression. Thus, this is not an error:
$ typeset -i foo
$ foo="bar"

If bar was a variable previously set to an arithmetic expression, then bar's expansion would be evaluated as such:
$ bar=10+2
$ typeset -i foo
$ foo="bar"
$ echo "$foo"
12

The error in your assignment, of course, is that there's no way to expand Should fail like that. If it were, say, Should - fail (an arithmetic expression subtracting the value of the two variables Should and fail, for example, it would still work:
$ foo="Should - fail"
$ echo "$foo"
0

The second problem is that nothing in the zsh docs indicate that -i may be set for an entire array, and so the -a in -ai is ignored:
bash-5.0$ typeset -ai foo
bash-5.0$ declare -p foo
declare -ai foo=([0]="0")  # the previous value was retained in the array

vs zsh:
% typeset -ai foo
% foo[1]=10
% foo[2]=20
% declare -p foo
typeset -i foo=20  # treated as a normal variable, not array

What you're seeing is essentially int_array being redeclared as an array (without any qualifiers) when you do int_array=(1 2 3):
% foo=(1 2 3)
% declare -p foo
typeset -a foo=( 1 2 3 )

Comment: Tricky.  `declare -p foo`    # very helpful to see what shell thinks
Answer: Using zsh typeset can produce a few possible outcomes:
 -   no errors, works (yeah!).
 -   errors, script fails (fix!).
 -   no errors, but unexpected behavior.  (scratch head)
As an example of last category, this produces no errors, but the typeset -p reveals -i is ignored.
{
unset int_array
typeset -ia int_array
int_array=(1 2 3)
echo $? "-Point A"
typeset -p int_array

    } always {

echo $? "-Point B"
typeset -p int_array
(( TRY_BLOCK_ERROR=0 ))
}
echo $? "-Point C"
echo "survived"

produces
 0 -Point A
 typeset -a int_array=( 1 2 3 )
 0 -Point B
 typeset -a int_array=( 1 2 3 )
 0 -Point C
 survived

The first line unsets int_array.   The typeset command declares
 int_array to be both an array and int, which is not what zsh allows.  The next
 line assigns int_array to a value.   There is no error as the $? tells us,
 but close examination of final typeset  -p int_array reveals what actually
 happened.
With a small change, we can produce errors and use the always block and
typeset -p to find more details.
{
unset int_array
typeset -ia int_array=(1 2 3) # error
echo $? "-Point A"
typeset -p int_array

      } always {

echo $? "-Point B"
typeset -p int_array
(( TRY_BLOCK_ERROR=0 ))
}
echo $? "-Point C"
echo "survived"

040_declare_version2.sh:typeset:135: int_array: inconsistent type for assignment
1 -Point B
040_declare_version2.sh:typeset:140: no such variable: int_array
1 -Point C
survived

The only difference is int_array was given a value in the faulty typeset -ia statement.
 This produces errors, and the script jumps to the always block.
 The (( TRY_BLOCK_ERROR=0)) allows the script to continue
 and not terminate, but the error is still reported at "Point C".
To check shell version:
$SHELL --version
zsh 5.4.2 (x86_64-ubuntu-linux-gnu)

Using "declare" in Zsh


css fixed header and floating content

Question: here is my css:

html {
  height: 100%;
}
body {
  height: 100%;
  width: 300px;
  margin: 0px;
}
div.div1 {
  height:  100px;
  background-color: red;
}
div.div2 {
  background-color: blue;
  height: 100%;
}

the problem is that I want body to be float-based but without scrolling inside it.
The doctype is sctrict. Browser: ff3. Is it possible?
Answer: you can add one more div in div2 to display content in it.
actually that div will have 100px top margin to avoid top div overlapping on your content.
div2 will extend from top to bottom but top 100px won't be used by content div.
so trick is, keep div1's height same with content's top margin. then it'll be fine
html:

div1 div1 div1 div1

    <div2 test

    <div2 test

    <div2 test

    <div2 test

and css will be something like:
html,body {height:100%;width:300px;margin:0px;}
div.div1 {height:100px; background-color:red; position:absolute; width:300px;}
div.div2 {background-color:blue; height:100%;}
div.content {margin-top:100px; float:left; width:100%;}

if you want to hide scroll completely just add overflow:hidden to div.div2
also you can give same background color to container make div2 look seamless.(it wont extend after scroll.)
div.content {margin-top:100px; float:left; width:100%; background:blue;}

cheers

css fixed header and floating content


How to run a project in QT C++ by another project?

Question: Please accept my apologize in advance if my question is very low level!
I have a project in Qt c++ (QT Widget application). I want to have a button in my project (App) that by pressing this button, another project in another directory (e.g. a Console project) starts to run. Indeed, the directories of my projects differ from each other.
I want to know, is it possible to run my console project by a widget project while these projects are not in the same directory? If yes, how?
Thank you!
Comment: Do you mean to ask that you want to launch another console app from your GUI app? The question is not clear
Comment: Yes exactly. I have a GUI app. I want to launch a console project in another directory by using a button in my GUI app. Is it possible?
Answer: You can try to use QProcess.
execute(const QString & program, const QStringList & arguments)

execute(const QString & program)

For example:
QProcess *process = new QProcess(this);
QString file = QDir::homepath + "/file.exe";
process->start(file);

Comment: Thank you for your response! I guess it would work. I will try it and inform you about the result.
Comment: I'm still waiting for your result, my friend.
Answer: You can use QProcess for launching another executable. Find the details here
Comment: Thank you for your response! I guess it would work. I will try it and inform you about the result.
Comment: Hi again, as I told, I am going to open a console project (name.Pro) by using my GUI. I think QProcess method just works for launching executable files and does not work for mu case. Do you have any idea how to open .pro file by my GUI?
Comment: You need to be more specific. I am not getting clarity on your goal from your question. Why do you want to load a project from your program. A project file(*.pro) is used usually by an IDE like QtCreator. What are you trying to achieve by loading the project file to your GUI application? Please be more clear so that we can help you.
Comment: I have some console projects that each one is developed for a particular task. I am working on a GUI to control all these projects (for example changing parameters in these projects and also control when to run each one). It is not possible for me to integrate all these projects in one directory (GUI's directory). Hence, I am forced to run these projects through their current directories, which differ from each other.
Comment: It will be a difficult task to mimic an IDE. There are lots of components involved like qmake, moc, gcc/cl if you are using QtCreator. From what I understood from your comment, I would suggest that you can create a GUI app for editing the pro files of your different projects and then later compile them separately by invoking qmake on your projects files from your GUI program. But if I were you, I would have done it with shell scripts with some custom qmake variables, instead of a full fledged GUI app.


can I give a web client access to the database?

Question: I'm an old web developer thinking that only server side code should access the database to prevent data leaking and corruption.
Now I'm trying a serverless development with google firebase. Since user authentication is managed, it seems possible to configure the database (firestore) access rules so that each user can only modify its own data (or read public data).
This would be nice, because otherwise I should write a server side api to give access to the database from the client. However I'm a little bit scared: is this a suggested practice?
For example: if the user is given authorization to create new objects, how can I check that objects are created consistently?
Maybe I can have a mixed access policy? For read query I can give direct access to the database but maybe I should deploy write queries on the server side?
I think that all of this should be discussed somewhere. Maybe I'm missing some keyword to find the topics.
Answer: Yes. It's totally normal and expected for your web client to have a Firebase API key and be able to access the database directly. As you noted, you're generally relying on security rules to make sure people can only access certain data, as well as make sure that documents written to the database are consistent.
For what it's worth, I'm a fan of the mixed-access policy you're talking about -- especially when it comes to more complex write that might span several documents in the database. It's sometimes easier to keep a separate "pending user writes" collection in your database, and then have a cloud function do more of the heavy lifting of propagating that action throughout your database.
If you want more info, there's a video all about this topic I can recommend :)


Do all gear affixes lose effect if that gear hits zero durability?

Question: Whether we're talking set affixes, legendary affixes or any other regular affixes.
For example, if my Aquila Cuiras gives me 50% damage reduction when I'm at > 90% resource, but that equipped item is damaged down to zero durability, do I lose the conditional damage reduction as well as the 'regular affixes' (like primary stat, attack speed, armour, etc.)?
Answer: Yes.  When gear reaches 0% durability, all bonuses it would normally generate are disabled.


Unable to create admin user in InfluxDB

Question: I have to create an ADMIN role user of InfluxDB at the time of initializing docker container. My script is:
<code>echo "=> Starting InfluxDB ..."
exec influxd

#wait for the startup of influxdb
RET=1
while [[ RET -ne 0 ]]; do
    echo "=> Waiting for confirmation of InfluxDB service startup ..."
    sleep 3
    curl -k ${API_URL}/ping 2> /dev/null
    RET=$?
done
echo ""

RUN su- curl -XPOST 'http://localhost:8086/query' --data-urlencode "q=CREATE USER admin WITH PASSWORD 'password' WITH ALL PRIVILEGES"
</code>
Above script does create the user but issue is that the role of the user is not set to ADMIN. I need a user with ADMIN role. What can be the possible issue here ? Any help would be much appreciated
Answer: Use env variables (applicable for official InfluxDB docker image https://hub.docker.com/_/influxdb):

INFLUXDB_ADMIN_USER
The name of the admin user to be created. If this is unset, no admin user is created.
INFLUXDB_ADMIN_PASSWORD
The password for the admin user configured with INFLUXDB_ADMIN_USER. If this is unset, a random password is generated and printed to standard out.
Comment: But i dont want to use environment variables. I want to create the admin user immediately after the container is up and have to do this with a script. Any help on that @Jan Garaj ?

Unable to create admin user in InfluxDB


How to print all folder names from the parent folder in google drive?

Question: I am trying to print all folder names from the parent folder in google drive
I tried so many methods but not working..
const drive = google.drive({ version: 'v3', auth });
console.log("Drive => ", drive.drives.appdata);
drive.files.list({
    //spaces: 'drive',
    //isRoot: true,
     //pageSize: 10,
}, (err, res) => {
    console.log(err);
    if (err) return console.log('The API returned an error: ' + err);
    const files = res.data.files;
    if (files.length) {
        console.log('Files:');
        files.map((file) => {
            console.log(file);
        });
    } else {
        console.log('No files found.');
    }
});

Above code only giving the file name of those folder but I am trying to print all parent folder names.?
I need to print angular_files, datastructurealgo,DSA,Tools names. These all are folders.
Comment: what do you mean by parent folder names?
Comment: @DaImTo I have updated my question.
Answer: You can use this code from the official documentation to search for folders in Google Drive. The key here is to use q: "mimeType='application/vnd.google-apps.folder'" as parameter of drive.files.list
Sample Code:
const drive = google.drive({ version: 'v3', auth });
console.log("Drive => ", drive.drives.appdata);
drive.files.list({
    q: "mimeType='application/vnd.google-apps.folder'",
    fields: 'nextPageToken, files(id, name)',
    spaces: 'drive',
    pageToken: pageToken
}, (err, res) => {
    console.log(err);
    if (err) return console.log('The API returned an error: ' + err);
    if (res.files.length) {
      res.files.forEach(function (folder) {
        console.log('Found folder: ', folder.name, folder.id);
      });
      pageToken = res.nextPageToken;
    } else {
        console.log('No folders found.');
    }
});

Please note that you might need to tweak the code based on your need.


differece between hibernate, leave and suspend

Question: I would like to know what the difference between those three concepts are. It seems that the closing menu becomes longer every some time, although in the end most people only uses one or two of the options.
Hibernate, suspend and leave. We all know that leave means leave, but apart of the intended punt, what does it mean in this exit (oops!) or leave menu in Ubuntu, or in my case Lubuntu 18.1?
Will we have remain and extended session any time soon? All this allows for so many jokes in the UK.
Answer: Hibernate should mean "suspend to disk". Meaning the state of all your running programs are saved to disk, the computer powers down and it will take zero battery.
Suspend means "suspend to RAM". This will take a small amount of battery while suspended, but it resume faster than hibernate.
I believe "leave" just means end the current session.


Terminology for Permissions Operation

Question: We're working on a user security manager. In the app, there is an operation to overwrite a user's permissions with the permissions of another user, essentially:

Delete all permissions and group membership of the user being modified.
Copy all permissions and group membership of the selected user to the user being modified.

"Copy Permissions" doesn't describe that the user's current information is about to be overwritten.
We've mulled a little, and rejected the following:

Assume
Duplicate
Overwrite

We want the language to inform and warn, but it needs to be brief. Is there a word for this operation that we're missing?
Comment: I am a developer and in our world if that is saved then it is called clone and if it is temporary it is impersonate.
Comment: Clone is pretty good. If you want to make an answer that'd be appropriate?
Answer: I would use the word clone.
I am a developer and that is the word we use.
In many development languages that is exactly what clone means.
If it was just temporary the term developers would use the term impersonate.
For lack of something better I would use the technical term.
Please see the comments.  The OP asked be to add that as an answer.
Comment: I said we use as in developers - I thought that was an explanation of the basis for the why I would use clone.  And it was two not one line.  I edited to try and expand.
Comment: Please see the comments.  The OP asked be to add that as an answer.
Comment: OP may have asked you to add it as an answer, but that doesn't mean it's a detailed enough answer for the site at just one line. You haven't covered off any explanation other than 'I'm a developer and it's what I do'. *Why* do you use that term? Do users understand it as well? Where does it come from? Is it a commonly used term? Explanation and context rather than just one-line answers are what this site is for. We're not here just to help one individual person, but to help *anyone* who finds this question in future. And they'll need detail and reasoning to find it useful.
Answer: I think 'import' or 'transfer' are the best terms to describe this, because you are essentially transferring data from one source to another, and 'importing' the new settings to the user.
Comment: Import is good, but not quite right, since importing doesn't usually also mean overwrite.Transfer implies moving them away from the their source, like transferring money from one account to another.
Answer: I can think of two ways

Search for the right word : "Match"
Provide a warning/note : Stay with "Copy" but put a warning message explaining that existing permission would be deleted and selected user's permission would be copied.

Terminology for Permissions Operation


Removing little move up effect on hover

Question: I have an e-commerce hosted in one of that "ready to sell" online stores, where it doesn't allow me to edit the CSS files but allow me to add css properties via admin panel. The problem that I need help is: The main menu of my site has that effect that do a little move up in the item hovered, as you can see in http://soulfighter.lojaintegrada.com.br/. And I really don't know what to add in my CSS to remove this effect. If i could access the CSS file, I believe I would find this effect and remove, but since i have no access to IT, I really don't know what to add to my css to remove that.
Comment: the url you posted is not found..
Comment: Corrected. Sorry and thanks, Gaby.
Answer: My recommendation would be to learn how to use some developer tools. For example, I am using Chrome.. if I right click and inspect the element, I can then view the styles applied to it, which immediately showed me this:
<code>.menu.superior .nivel-um > li:hover {
    margin-top: -2px;
}
</code>
Remove or override this and your problem should be fixed.
Comment: Oh, I didn't see that in Firebug! Set to margin-top to 0 and it worked. Thanks a lot.
Comment: As it is a hover state, it may not be readily apparent. Inspectors usually have options to toggle on or off different states such as hover or focus, allowing you to see those styles

Removing little move up effect on hover


checking for existence of a value in a Pandas dataframe column

Question: I have a small dataframe, df,  that I am testing some code on, before using the code on a larger set
  id  make   price
  21  Boss    300
  22    LG    400
  23    EE    500
  24  Orange  750

I am trying to find a way of determining if a value already exists in a column before inserting that value.
This code snippet works
newval = 'EE'
for val in df.make:
    if val == newval:
        print(val)
    else:
        print('not the val')

However this snippet, that should more cleanly identify if a value already exists in a specific column of the dataframe, does not appear to work in that it prints 'Available to add', despite 'EE' already existing in the 'make' column.
newval = 'EE'
if newval in df.make:
    print('In there already')
else:
    print('Available to add')

If I test for true or false
exists = 'EE' in df.make
print(exists)

I get False, despite the fact that 'EE' is clearly already in the 'make' column
Why am I not getting True and 'Available to add'
I am sure that I am missing something very simple but cannot see it. Can someone point me in the right direction
Comment: I am actually trying to test some logic to use in a Post function within an API where I might send in a new record periodically and don't want the process to allow duplicate records .. I think I can see the sense in what you suggest but maybe my use case is a bit specific
Comment: do you already have all the new values in a list? it would be easier to find the set difference than to loop each `newval`
Comment: Yes. Thanks. Has some of BEN-YO's suggested solution within it
Comment: I know, it's good that you found a solution, but we should avoid keeping duplicate questions, pleace accept the notice shown on top of the question so it is marked as dup
Answer: Change in to isin follow by any
exists =  df.make.isin(['EE']).any()

Comment: Thank you. Exists now gives me a True. I'll play with this inside my if, else statement to get behaving too
Answer: Your statement 'EE' in df.make is searching for the string in the series INDEX, that's why it returns False. If you change it to 'EE' in df.make.values then it will be True.


How many Mithril per month can a player expect in FFRK?

Question: In Final Fantasy Record Keeper, mithril can be considered the "freemium currency" even though the freemium currency are gems. but since in almost all the places 100 gems = 1 mithril (seemingly), I think its safe to make that statement above.
Disregarding the mithril gained by special giveaways, event dungeons, realms dungeons and missions, how many mithril does a player gains per month by playing the game every day?
I think they mostly would come from daily login, but I am really new to the game.
Answer: From just logging in daily, you'll typically get 1 every day as part of the daily login bonus, plus 3 every 10 days from the other daily login bonus.
That works out to be about 39 for a 30-day month.
If you just started playing, there's a lot of Mythril you can "mine" from the story dungeons, which also will raise your stamina cap at the same time.  It's really worth doing this so that you can get both of these rewards.
Don't knock the amount of Mythril you can earn from the regularly occurring "Challenge Events" either.  Typically these run for two weeks at a time and overlap by one week, so there's almost always 2 going on at the same time.  It's possible to earn 5-10 Mythril from these, depending on the rewards and the size of the event.
There are also special login events/campaigns, and Mythril gained as a "sorry" when DeNA finds/fixes a bug.
If you factor all this together, you can assume you'll generally have enough Mythril to do an 11x Rare Relic pull each month, plus a few left over for resetting Stamina to run dailies or other special events for orbs/greens.
Comment: That is exactly my concern. It seems that every time a nightmare dungeon opens there is a 11x draw for half price. I was wondering if there is enough mithril to do this half-price plus a regular 11x draw (i.e. 75 mithril per month) sustainably.
Comment: This game is very similiar to Love Live School Idol Festival (and several others i'm sure). In these using the freemium to reload stamina is usually a waste of currency. But good advice.
Comment: @Mindwin, I think 75 in a month is a bit tricky.  My suggestion is to do the half price draw, but then bank the rest of your Mythril.  There are special draw events that occur with MUCH better odds of getting unique soul breaks, which is really the reason to draw relics.  Drawing on normal event banners tends to be a bad deal in the long term.  That said, I get suckered into drawing far more often than I really should :P


Is it possible to get a marksman award with a shotgun?

Question: I've been trying to get a marksman award with the shotgun just for the pure "wtf" credit. So far I'm using frag rounds with the Saige 12K and a 7X scope.
Is it even possible though to get a marksman award with something that isn't a sniper rifle? I can get headshots with the shotgun, but it's extremely difficult getting 1 shot kills with headshot and a shotgun
Comment: In BC2 it could have been any weapon, but it had to be Recon class, probably hasn't changed.
Answer: It seems to be possible, although I think this video might have been made during the beta:
(Some NSFW language in the video)

He's using a scope + the slug ammunition type, and he gets the marksman award at the timecode I linked to.
Answer: I have used a similar setup to agent86's video, and have been able to get marksman ribbons. The pump shotgun does more damage, and the slug ammo is needed for any sort of range. The 4x scope is my preferred optics for most engagements.
Here's my loadout:

870 MCS
12g Slug Ammo
Extended Mag
ACOG (4x)

The 870 also has a smaller cone of effect, so you're more likely to get the headshot if you're using buckshot.


Excluding results from grep

Question: So I have a project under svn and I'm searching the file contents. In the result set I get .svn files that I don't want actually to see. for example:
<code>$ grep -i -r "breadcrumb" . -l
./terms_and_conditions/.svn/text-base/index.tpl.svn-base
./terms_and_conditions/.svn/tmp/index.tpl.tmp
./terms_and_conditions/.svn/tmp/index.tpl.3.tmp
./terms_and_conditions/.svn/tmp/index.tpl.2.tmp
./terms_and_conditions/index.tpl
./privacy/.svn/text-base/index.tpl.svn-base
./privacy/.svn/tmp/index.tpl.tmp
./privacy/.svn/tmp/index.tpl.3.tmp
./privacy/.svn/tmp/index.tpl.2.tmp
./privacy/index.tpl
</code>
how can I exclude the files under ".svn" directories from the result set so that I only get
<code>./terms_and_conditions/index.tpl
./privacy/index.tpl
</code>
Answer: Pipe those through:
<code>grep -v '/\.svn/'
</code>
Comment: Works like a charm. But why '/\.svn/' and not ".svn"?
Comment: You could simply use "svn"; it's not likely that you've used svn in your file names.
Comment: @Joe If you don't surround it by slashes or have the dot, it could match other things with "svn" in their path... And @Nerdling I don't see the value in *not* matching accurately when it's so easy, however unlikely.

Excluding results from grep