2D sampling with multidimensional transformations

Question: I'm currently learning mathemetical concepts of distribution and the way to use them in a ray tracer with the book "Physically Based Rendering".
Let's start by uniformly sampling an hemisphere:
As you probably know, a way to generate the uniformly distributed direction is to use the inversion method.
Let us denote by $p$ our uniform probability density function:
$p(\omega) = \cfrac{1}{2\pi}$ and so $p(\theta, \phi) = \sin(\theta)p(\omega)$.
Then you compute $p(\theta)$, $p(\phi | \theta)$, you integrate your cumulative distribution function and you invert the function.
My questions are:

What does $p(\theta, \phi)$ really mean?
What is the transformation between $p(\omega)$ and $p(\theta, \phi)$?
In the book, to find $p(\theta,\phi)$ they state that $p(\theta, \phi) d\theta d\phi = p(\omega)d\omega$, but why?

I know that for $p(\omega)$, our random variable is a given $\omega$ (a direction), so the function represents a relative probability for this direction (so a solid angle, because the relative term implies a direction and a delta area around this direction).
But for $p(\theta,\phi)$, our random variable is now the couple $(\theta,\phi)$. To what extent is it different from a direction?
Comment: @DanHulme Do you have any answer for this post ?
Comment: Note that the @username notifications only work for users who have already commented on this particular post. It's just coincidence that the person mentioned happens to have posted an answer...
Comment: @trichoplax It's not a complete coincidence. I think I did get notified, because I'd previously edited the question, and the comment reminded me that I was intending to come back and post an answer when I got more time.
Comment: Interesting. I didn't realise that edits did that. It makes sense though... Thanks for letting me know.
Comment: @trichoplax I just tried my luck
Answer: I'm not sure I've correctly understood the question, but here goes.
You're trying to sample directions uniformly, so you've got $p(\omega)$, which is the probability of getting a particular direction. But what is a direction? You actually need your probability distribution to produce numbers in some representation, and the easiest representation to deal with is lat-long (i.e. two angles). So the thing you actually need to sample from is the probability distribution of pairs of angles. This is what $p(\theta, \phi)$ is: the joint probability of two variables.
$p(\omega)$ and $p(\theta, \phi)$ mean the same thing geometrically, but the former gives you an abstract direction you can't sample from directly, while the latter more usefully gives you two numbers that represent a direction.
The reason for your third bullet point is to do with the point you've made about how it isn't just a single direction. These aren't really functions: they're distributions. A direction is infinitesimal, so you can't have a probability of just one direction. What you actually need to do is integrate it over the directions you're interested in.
$$
\int p(\omega)d\omega = \int_0^{2\pi}\int_0^\pi p(\theta, \phi)d\theta d\phi = 1
$$
Whichever representation you use, the integral over the hemisphere has to be 1, because it's a probability distribution.

I'm not sure if I need to explain this or if you already understood, but here's the origin of the $sin(\theta)$. When you do the double-integral on the right, you're splitting the problem up into a series of rings, or slices of the unit sphere. Each ring has constant $\theta$ while $\phi$ goes from $0$ to $2\pi$. Also, the area of each individual ring decreases as $\theta$ increases: the ring at the equator is huge, while the last "ring" at the pole is tiny. The area decreases as $sin(\theta)$. Because we want each unit of area of the sphere to have the same probability, we need the smaller rings to get a smaller share of the probability.
As Florian R. explains, you can do that by including the $sin(\theta)$ factor in the integral, or you can put it inside the definition of $p(\theta, \phi)$ like the book does.
Comment: @Yoo Rather the transformation from integrating over *ω* to integrating over *θ* and *ϕ* is the transformation from integrating in cartesian to integrating in spherical coordinates. While you already define *p(ω) = sin(θ)p(θ,ϕ)*, I'd rather not change *p* at all, using *ω=(sin(ϕ)cos(θ), sin(ϕ)sin(θ), cos(ϕ))* and using *dω = sin(θ)dθdϕ*. I think that should make it clear that *p* stays the same, we are just transforming the coordinate system of the integration. This is, however, subjective and if you redefine *p* to include *sin(θ)* like you did, the resulting equation will be the exact same.
Comment: @FlorianR. The question already describes that *sin(θ)* is inside *p(θ, ϕ)*. The questioner didn't seem to have trouble with it and it's a bit of a side issue, so I didn't really pay any attention to it.
Comment: @Yoo Ah, I'm sorry. Dan just added an explanation and maybe to help you visualize it, think of [a map using latitude/longitude](https://en.wikipedia.org/wiki/Equirectangular_projection). The south pole appears enormous, and if you were to integrate something along latitude and longitude, the poles would be overrepresented. The sin(θ) factor removes this bias towards the poles. Also, you might want to read up on integration by substitution for the general case.
Comment: That wouldn't generally be true, but it is true here because of the extra constraint that the distribution is uniform. *Any* probability distribution has to integrate to 1, but this one also has the same value everywhere. (Or to put it another way, the two integrals have to be equal for *every* region you integrate over.)
Comment: In your equation, you transform from integration in cartesian coordinates to integration in sphere coordinates. Shouldn't you add *sin(ϕ)* there to account for this coordinate transformation? Alternatively, you might define *p(θ, ϕ)=sin(ϕ)p(sin(ϕ)cos(θ), sin(ϕ)sin(θ), cos(ϕ))*, but I think it will be more clear if the *sin(ϕ)* factor is distinct from *p(θ, ϕ)*.
Comment: @DanHulme Thanks for your answer.
Ok it's good to see p(w) as an abstract representation.
In my question, I didn't understand how to compute $p(\theta, \phi)$. According to your answer, to calculate $p(\theta, \phi)$ you state that _integrals equality_ involves _integrands equality_ so $p(\omega)d\omega$ = $p(\theta, \phi)d\theta d\phi$, am I right ?
But is it still right if in this case integration domains are not the same for the two integrals?
Comment: @FlorianR do you state that the transformation from $p(\omega)$ to $p(\theta, \phi)$ is the transformation from cartesian coordinates to spherical coordinates ?
Comment: @FlorianR You are right to precise that p is the same thing no matter its starting set ($\omega$, or {\theta, \phi}). It's the probability density function, used to find the relative probability of a direction, am I right ?

I think you are misunderstanding what I understand and what I don't (my bad, my question can be confusing).
**Even though I state that $p(\omega) = \sin(\theta)p(\theta, \phi)$, i don't know why it is true.** (That's why I asked the third question in my post), and because I don't know why is true, I can't plainly understand what is the transformation.
Comment: @Yoo Is my edit helpful? At first I thought I had understood what you understand and what you don't, but I'm not so sure now.
Comment: @FlorianR. Oh, that's a good way of describing it. I might use that one in future.
Comment: @DanHulme yes your edit is helpful, it is always good to restart from scratch to be sure that everything is understood.
Comment: @FlorianR.Thanks, it's useful to have a "viewable" way of what the integral means.
Comment: @DanHulme

However, Florian and you explained why $d(\omega) = \sin(\theta)d(\theta)d(\phi)$, am I right ?

Let me ask the question:
**Why can we state that $p(\omega)d(\omega) = p(\theta,\phi)d(\theta)d(\phi)$ ? An equality that is in the book.** This is the equality I want to prove, because it would infer that $p(\omega) = p(\theta, \phi) \sin(\theta)$, the questions I asked in my post.

**Is it because the _integrals_ (in the Dan's answer) are equals so their _integrands_ are equals ?**
I'm looking for a concrete, and rigorous proof of the equality.
Comment: @DanHulme To be clear, in th book they state that:

$$p(\omega)d(\omega) = p(\theta, \phi)d(\theta)d(\phi)$$ so
$$p(\omega)\sin(\theta)d(\theta)d(\phi) = p(\theta, \phi)d(\theta)d(\phi)$$ so
$$p(\omega)\sin(\theta) = p(\theta, \phi)$$.

And I can't rigorously demonstrate the first equality.


why isn't file.writelines(str) working in a while loop

Question: When I create todo-item, I want to add input content to my file. Why can't I achieve the expected effect when I add a string in file.writeline()?
I want to use file.writeline() to write the content entered by the user into a file.
while True:
   user_action = input('Type add, show, edit, complete or exit: ')
   user_action = user_action.strip()

   match user_action:
       case 'add':
           todo = input("Enter a todo: ") + "\n"
           todos.append((todo))
           file = open("todos.txt", "w")
           file.writelines(todo)

Comment: Personally I would not add to the file within the loop. Open once and write all data once.
Answer: writelines takes a list, not a string. For what you are trying to do I'd recommend write, which does take a string. If you do this you'd also need to open the file in append mode, which means you pass "a" and not "w". The whole code would look like this:
todos = []

while True:
    user_action = input('Type add, show, edit, complete or exit: ')
    user_action = user_action.strip()

    match user_action:
        case 'add':
            todo = input("Enter a todo: ") + "\n"
            todos.append((todo))
            with open("todos.txt", "a") as file:
                file.write(todo)

Comment: `with open("todos.txt", "a") as file:` - why would you do this within the loop?
Comment: Partly to retain as much of OP's code as possible. Also because it looks like OP wants to have operations to add, view, and edit the list; so the user might need to see the entire file, including things added before the program began running. This could be done with a list, but it might make more sense as well as give OP more practice to open and close it within the loop. Doing it all at the end would work too of course! :)
Answer: Issue: You were opening file in 'w'(write) mode because of which, everytime you attempt to write into the file, the previous content gets overwritten.
Solution: Open file using 'a'(append) mode
Improvement: Do not open a file inside a loop (this leads to unwanted processing), better to open it (just once) after collecting all todos.
Assumption: I hope you're using "default case" at the end of the match statement (for eg: case _)

Here is the final code:

todos = []

while True:
    user_action = input('Type add, show, edit, complete or exit: ')
    user_action = user_action.strip()
    match user_action:
        case 'add':
           todo = input("Enter a todo: ") + "\n"
           todos.append((todo))

        case _: break

with open("todos.txt", "a") as file:
    file.writelines(todos)


Alphabetic ascending filling dataframe column until another column is True/changes, then start again

Question: My aim is to fill "Links" column alphabetically ascending until "Node" changes(or "NewNode"=True)
Here's what i have tried.
import pandas as pd
import numpy as np
import string

data = {'Node': ['Node_1', 'Node_1','Node_1','Node_1','Node_2','Node_2','Node_2']}
df = pd.DataFrame(data=data)

l=list(string.ascii_uppercase)

def link_def(x):
    a = 0
    if x == 'True':
        l[0]
    else:
        a = a+1
        l[a]
    return l[a]
df['NewNode'] = np.where(df['Node'].shift() != df['Node'],True,"")
df['Links'] = df['NewNode'].apply(lambda row : link_def(row))

and this is the output
     Node NewNode Links
0  Node_1    True     A
1  Node_1             B
2  Node_1             B
3  Node_1             B
4  Node_2    True     A
5  Node_2             B
6  Node_2             B

Desired output is
     Node NewNode Links
0  Node_1    True     A
1  Node_1             B
2  Node_1             C
3  Node_1             D
4  Node_2    True     A
5  Node_2             B
6  Node_2             C

How can I get the desired output?
Answer: You can achieve this with vectorial code, using groupby.cumcount and a mapping:
df['NewNode'] = df['Node'].ne(df['Node'].shift())
df['Links'] = (df.groupby(df['NewNode'].cumsum())
               .cumcount()
               .map(dict(enumerate(string.ascii_uppercase)))
              )

If you don't need the intermediate "NewNode" column:
df['Links'] = (df.groupby(df['Node']
                          .ne(df['Node'].shift())
                          .cumsum())
               .cumcount()
               .map(dict(enumerate(string.ascii_uppercase)))
              )

NB. this is limited to 26 replacements.
output:
     Node  NewNode Links
0  Node_1     True     A
1  Node_1    False     B
2  Node_1    False     C
3  Node_1    False     D
4  Node_2     True     A
5  Node_2    False     B
6  Node_2    False     C


Is "every non-empty set is injective" equivalent to AC?

Question: It is well known that "every surjection has a section" is an equivalent form of the axiom of choice (in fact, for me it is the most natural formulation of the axiom of choice). In detail, the statement is that for any map $f:X\to Y$ such that for every $y\in Y$ there is an $x\in X$ with $f(x)=y$ there is a map $s:Y\to X$ with $f(s(y))=y$ for every $y\in Y$.
Consider the statement "every injection with non-empty domain has a retraction". In detail, for any map $f:X\to Y$ such that $X$ is not empty and $f(x)=f(x')$ implies $x=x'$ for any $x,x'\in X$, there is a map $r:Y\to X$ with $r(f(x))=x$ for every $x\in X$.
Is this statement also equivalent to the axiom of choice? If not, is it weaker or stronger? What are some "well-established" set-theoretic principles equivalent to it?
Comment: Almost a duplicate: https://math.stackexchange.com/questions/903645/existence-of-a-set-function-axiom-of-choice
Answer: No. Fix a point $x'\in X$ and define$$\begin{array}{rccc}r\colon&Y&\longrightarrow&X\\&y&\mapsto&\begin{cases}x&\text{ if $y=f(x)$ for some }x\in X\\x'&\text{ otherwise.}\end{cases}\end{array}$$
Comment: @მამუკაჯიბლაძე: When the standard proof (full classical logic, with choice, with everything) is four lines, **check the four lines** and see where the axiom of choice might have been involved. It's a much shorter process than even writing the question. In fact, I am pretty sure that answering your question is shorter than writing *this* comment.
Comment: Thank you! I now think it is probably equivalent to excluded middle or something like that...
Comment: @AsafKaragila You are right - almost :D I am mostly interested in the last part. From the answer I got impression that it is probably equivalent to excluded middle
Answer: Previous answer shows proving your statement does not require the axiom of choice. Your statement, however, implies the weak excluded middle. We will work over CZF and take the terminology $0=\{\}$ and $1=\{0\}$.
Let $\phi$ be a $\Delta_0$-formula. Take $a = \{0\mid \phi\}$ and consider the inclusion map $i:\{0,1\}\to \{0,a,1\}$. Assume that $i$ has a corresponding retraction $r:\{0,a,1\}\to \{0,1\}$, then $r(a)=0$ or $r(a)=1$.
Now assume that $r(a)=0$ and $\phi$. The combination of them implies $r(1)=0$. However $r(1) = r(i(1)) = 1$, a contradiction. Hence $r(a)=0$ implies $\lnot\phi$. Similarly we can prove $r(a)=1$ implies $\lnot\lnot\phi$. In summary, we have $\lnot\phi\lor\lnot\lnot\phi$.
As the proof suggests, your statement implies weak excluded middle for any formulas if we assume the full separation.
Comment: Let $a := \{x \in 2 | (x = 0) \vee (x = 1 \wedge \phi)\}$ and let $i$ be the inclusion $a \subseteq 2$. Let $r : 2 \to a$ be a retraction. If $r(1) = 0$ then $\phi$ is false. Hence if $\neg \neg \phi$ holds then $r(1) \neq 0$, and so $r(1) = 1$, implying $\phi$. We have shown $\neg \neg \phi \Rightarrow \phi$, which is double negation elimination and equivalent to excluded middle.
Comment: That's nice! Is it clear that the "actual" (strong) excluded middle cannot be similarly implied?
Comment: @მამუკაჯიბლაძე I have tried, but I still have no idea on this.
Comment: @aws Nice proof!


Can connect to WiFi but cannot go on the Internet (Ubuntu 12.04)

Question: I recently got myself a new HP Pavilion dm4-2102eo with a built-in Intel Centrino Wireless-N 1030 WiFi adapter. After messing a bit around with the partitions on the hard drive, I finally got to install the latest version of Ubuntu (12.04), now running a dualboot setup with the pre-installed Windows 7 (using GRUB).
So far everything has been running smoothly. Ubuntu quickly found drivers for almost all of my computer's hardware. That included drivers for the Wireless-N 1030 card -- or so I thought!
After having installed Ubuntu, I connected to my home WLAN (which was visible along with a range of other wireless networks in my neighborhood). I entered my WPA password and connected successfully. I opened up Firefox, typed in gmail.com, hit Enter and... Nothing happened! It kept on loading until it finally gave up and said that the connection could not be established.
I am now back on my Windows partition where the Internet works flawlessly. So does it on my iPhone, my mother's iPad and my brother's MBP. Since a lot of different devices are able to log onto our wireless network, the problem must lie within the Ubuntu installation.
I have taken screenshots of the connection settings (see here) and of the output of running the command  ifconfig in Terminal (see here).
I am confident with Terminal and know how to do some basic operations but I have no clue of where to start here. I have been searching for solutions online but it seems that most people have different setups and need different solutions. I hope that you guys will be able to help me out.
Thank you so much!
Best regards,
Sebastian
Comment: Who did the setup for your router? Maybe you have MAC Access control enabled? Then you need to add your new wifi device to the list of allowed internet users. (just a thought)
Answer: When I look at your pictures I see that your device has sent packets back and forth and gotten an IP address from your DHCP server, probably on your router.
Is 192.168.1.1 your router? How does that address and the addresses for your domain name servers match up with what Windows displays?
Assuming 192.168.1.1 is your router, let me suggest some debugging steps.
Please open a terminal session with Alt-Ctrl-T and enter:
ping 192.168.1.1

you should get repeated answers from that address.
ping 18.104.22.168

and
ping 188.8.131.52

and
ping 184.108.40.206

These will tell you whether you can reach your router, your domain name servers, and a google domain name server.
If you configure your router with a web browser you can also enter:
firefox http://192.168.1.1

If you can reach everything but the 220.127.116.11 and 18.104.22.168 addresses you may have to configure your system to use a different domain name server--just a hunch.
To communicate with a website like ubuntu.com you need:

A valid address for your computer and a working interface to go with it. ✓
A valid address for your router on that network, matching your address prefix. ?
A valid address for a domain name server ?
Internet connectivity from your router to the domain name server (probably, if the domain name server addresses on Ubuntu match Windows)
Internet connectivity from your router to ubuntu.com. (✓, assuming you can reach ubuntu.com from Windows)
Answer: My friend, if you use the software called Unup router, then please remove it. This can be the main cause of the problem.
Comment: You should tell him why, shouldn't you?


Angular2 how to pass data throught router

Question: I'm devolping a web application using Angular v2.0.0. Since I have a sub-navigation in my app I would like to pass some data to a sub-page, that loads its own component, through the <router-outlet>.
As i can see on Angular2 documentation I can reach this purpose if i include a sub-page directive in the main component template, but this isn't what i need.
I'd like to use code like the following:
app.routes.ts
export const routes: RouterConfig = [
    { path: '/', redirectTo: '/one' },
    { path: '/one', as: 'One', component: OneComponent },
    { path: '/two', as: 'Two', component: TwoComponent },
    { path: '/three', as: 'Three', component: ThreeComponent }
];

export const APP_ROUTER_PROVIDERS = [
    provideRouter(routes)
];

main.component.ts
@Component({
    moduleId: module.id,
    selector: 'main',
    templateUrl: 'main.component.html'
})

export class MainComponent {
    maindata: Object = {name:'jim'};
}

main.component.html

Home

One |
Two |
Three

<router-outlet [data]="maindata"></router-outlet>

one.component.ts
@Component({
    moduleId: module.id,
    selector: 'one',
    inputs: ['data'],
    templateUrl: 'one.html'
})

export class OneComponent {
    @Input() data;
}

one.component.html

{{ data.name }}

...

How to do this?
Comment: You have to use a service
Answer: You can pass data directly into a component through the route using resolvers. First step is to register the resolver:
@NgModule({
  ...
  providers: [
    ExampleService,
    {
      provide: 'foo',
      useValue: () => {
        return {
          msg: 'Something something something'
        };
      }
  ]
})
export class AppModule {}

Then make use of it in the routes:
export const AppRoutes: Routes = [
  ...
  {
    path: '/one',
    component: OneComponent,
    resolve: {
      foo: 'foo'
    }
  }
];

The final thing to do is to make use of it in the component:
@Component()
export class OneComponent implements OnInit {

  foo;

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.foo = this.route.snapshot.data['foo'];
  }
}

See this ThoughtRam post for more
Comment: @smartmouse Well you said you want to "pass some data to a sub-page." You didn't say you want to manipulate it and pass it back. Also - of course it deals with objects. You get an object passed to the component which you can do whatever you want with.
Comment: Your solution is unidirectional and doesn't deal with obejcts.
Answer: You can pass argument, for example argument id for 'user' link would be written as 'user/:id' and you can take this argument later. Also, you can use @Input() and @Output() annotations
Comment: I mean passing data, not just an ID


EF5 Code First TransactionScope without escalating to MSDTC

Question: I'm using EF5 code first, and I need to wrap multiple calls to SaveChanges() in the same transaction.  I'm relatively new to using transactionScope, and can't seem to tweak the options on it to accomplish what I'm looking to do.
The following code resides in a service class that gets injected with an instance of my DbContext class.  I do not create additional instances of DbContext anywhere in this class.
At first I tried the following.  The code is nice and clean, but it attempts to escalate to to DTC during the SaveChanges method in the GenerateInvoice function.
using (var scope = new TransactionScope())
{
    // This function does some work and calls SaveChanges
    Guid invoiceId = GenerateInvoice(cart);

    // This function also does some querying and calls SaveChanges
    DeleteCart();

    // Transaction should only commit if both functions above were successful
    scope.Complete();

}

I did some research and changed the code to the following which does not escalate to DTC, but I'm not sure if it's the best approach.
IObjectContextAdapter adapter = (IObjectContextAdapter)_context;

adapter.ObjectContext.Connection.Open();

using (var scope = new TransactionScope())
{

    // This function does some work and calls SaveChanges
    Guid invoiceId = GenerateInvoice(cart);

    // This function also does some querying and calls SaveChanges
    DeleteCart();

    // Transaction should only commit if both functions above were successful
    scope.Complete();

    adapter.ObjectContext.Connection.Close();

}

Is there a simpler way to get transaction support with EF5 code first across multiple SaveChanges without escalating to DTC?
Thanks
Answer: Not that I have found.  And it makes sense as well.  By calling SaveChanges() more than once, you are potentially opening up multiple connections to the database.  The only way to coordinate the transaction across these connections is with a distributed transaction (hence MSDTC).
The best solution I could come up with was to only call SaveChanges() once.  This might mean restructuring some code, but it is best if all the entities that are needed to be transactional all commit at the same time.
Only calling SaveChanges() once also allows the EF change tracker to use its cache and save a lot of communication between the app and the db.
Comment: I agree, it does make sense.  `SaveChanges` opens and closes the connection itself.  I was just hoping there was a better answer :)  Restructuring is possible, but would result in duplicated code.  I have a DeleteCart method that deletes the cart.  This can be called by consumers of my service directly, but also internally at other times (there are many ways a cart can be deleted).
Comment: It might not mean duplicate code.  For example, if you are building a web application, there are patterns that will open up a dbcontext at the beginning of the request and then `SaveChanges()` at the end of the request.  Therefore, anything that happens inside the request is committed.  This is leaning towards more true persistence ignorance.
Comment: This is a good reference question: http://stackoverflow.com/questions/10585478/one-dbcontext-per-web-request-why
Comment: Thanks for the reference.  I can see how what you said could be used very nicely in the command / handler pattern.
Comment: Marked as answer because this led me to my answer which is to handle the transactions at a higher level.


Why is $x$ not equal to $75$ degrees?

Question:
Someone told me,

Draw $B C$. Let $\angle D B C=y$. Then $30+2 y=180 \Rightarrow y=75$. Now, notice
that ABCD is a cyclic quadrilateral. As a result, $x+y=180 \Rightarrow x=105$ but

I cannot see their logic.
Comment: Notice that $DBC$ is an isosceles triangle which implies angle $DBC$ is equal to angle $DCB$. Then use the fact that opposite angles in a cyclic quadrilateral are supplementary
Comment: Which part of the solution don't you understand?
Comment: Just to answer the title question: The angle at A subtends arc BCD, which is more than a semicircle. So that angle is more than a right angle.
Answer: The following may be easier: Since $\text{m}\angle BDC = 30$, the arc $BC$ must span twice that, or $60$ degrees. Then, by symmetry, we have arc $CD$ spanning $\frac{360-60}{2} = 150$ degrees, so arc $BCD$ spans $210$ degrees. Therefore, $\text{m}\angle BAD = \frac{210}{2} = 105$ degrees.
Comment: (+1) Sometimes referred to as the [inscribed angle theorem](https://en.wikipedia.org/wiki/Inscribed_angle)
Answer: Draw diameter from D , it meets the circle at E. we have:
$\overset{\frown}{EB}=\frac 12 [\overset{\frown}{EB}=60^o]=30^o$
$\Rightarrow \overset{\frown}{BCA}=30+180=210^o$
$\Rightarrow x=\frac 12\overset{\frown}{BCA}=\frac {210}2=105^o$
Answer: As triangle BCD is isosceles triangle and angle BDC = 30, we get angle DBC = DCB = 75.
Join AC.
BC is common chord so angle BDC = angle BAC = 30.
Similarly angle DAC = angle DBC = 75 as CD is the common chord.
You can see the theorem here Angles in same segment are equal.
Angle x = angle DAC + angle BAC = 105

Why is $x$ not equal to $75$ degrees?


ahk_id will be the same over different machines? (AutoHotKey script)

Question: Does filtering/matching by a specific ahk_id will work only on the machine where I got the ahk_id from? Or it's "global" and will work across different machines?
Also, how does the ahk_id is generated?
Thanks
Comment: This number is a window handle assigned by OS, it changes each time that app runs.
Comment: Oh, you're right! Do you want to write it as an answer or I'll do it?
Answer:
Each window has a unique ID, also known as a HWND (short for handle to window). This ID can be used to identify the window even if its title changes.
The ID of a window is typically retrieved via WinExist() or WinGet and is a specific arbitrary number. It changes each time a program runs.
ahk_id is used to identify a window based off the windows unique ID (HWND).

https://autohotkey.com/docs/misc/WinTitle.htm#ahk_id


Uploading to nested buckets in google cloud storage

Question: In google cloud storage, i have bucket called cats inside a root bucket called images. Im using the google-api-ruby-client gem to upload files. Im able to upload a file to the root bucket 'images' but uploading to 'images/cats' does not work. I am aware that the buckets in google cloud storage do not have a notion of slash, so I'm unable to figure out how to specify the name of the nested bucket.
result = client.execute(
  api_method: api.objects.insert,
  media: media,
  parameters: {
    uploadType: 'resumable',
    bucket: 'images/cats',  #This does not work !. Just images works.
    name: 'kitty.jpeg',
  },
  body_object: {contentType: 'image/jpeg'}
)

This is giving the error NoMethodError: undefined method query_values for nil:NilClass. The code works if i just use 'images' for the value of the bucket.
How can i make the upload work for nested buckets as well ?
Thanks
Answer: Google Cloud Storage doesn't have true directories - it has a flat namespace. You can partially simulate directories by using "/" characters in your object names, and using prefix and delimiter queries when listing buckets.
The problem you're seeing is caused by the fact that bucket names can't contain "/". Try instead using the bucket "images" and object names that start with "cats/".
Comment: This answer helped me with performing a download on a file with the Node.js client.


Javascript set variable to input, then navigate to page

Question: I have an input where, theoretically, the user types in a box, presses enter, and the browser navigates to the input text with .html appended at the end. I originally was trying to deal with submitting the form, but the form no longer submits after I added preventDefault();. What I have now doesn't seem to set the variable to the form element, and then doesn't get to the URL part. My code:
<form name="answerarea">
<input type="text" name="input">
</form>

then
function sendanswer( e ) {
if ( e.keyCode === 13 ) {
    e.preventDefault();
    var answer = this.document.answerarea.input.value;
    if (answer) { this.location.href = answer + ".html"; }
    }
}

document.answerarea.input.onkeypress = sendanswer;

Any clue why it's not working? Thanks.
Comment: Get rid of the `this.` ...
Answer: The this keyword would most likely point to the current element, which would be the input field. Try this instead.
function sendanswer( e ) {
    if ( e.keyCode === 13 ) {
        e.preventDefault();
        var answer = this.value;
        if (answer) {
            window.href = answer + ".html";
            return false;
        }
    }
}

document.getElementsByTagName('input')[0].addEventListener("keyup", sendanswer);

The context of this will change depending on how sendanswer is called. ex : with .apply or .call will allow you to change the context.
See also http://jsfiddle.net/KtXpV/ for an example.
Answer: You are calling the function on the keypress event of input, so this will refer to the input, which does not have an input or location object inside it..
modify your code as follows:
function sendanswer( e ) {
 if ( e.keyCode === 13 ) {
 e.preventDefault();
 var answer = document.answerarea.input.value;
 if (answer) { window.location.href = answer + ".html"; }
 }
}

Comment: Thanks so much! This worked. Also learned quite a bit about javascript from this endeavor.
Comment: too bad SO has a chat option, i've seen new users asking friends to upvote their copy pasted answer and downvote the original. ~ LOL


Unable to install Minecraft Java, error code 0x80131509

Question: As said, each time I try to install Minecraft (Java Edition) through the official newest version of the installer on my laptop, it just shows me this error code. I cannot find any information about it online, and Microsoft's helping team didn't help at all.
I already tried reinstalling the installer, I finished all of the possible update of my PC but nothing works.
It always says:

"Verify that you are connected"
"Then retry to update. We were unable to update windows. (0x80131509)"
Comment: Can't answer because I don't have enough reputation, so just download minecraft for Windows 7 and install. It will work. cheers
Comment: Using microsoft store upgrade worked!
Answer: Open the Microsoft Store and make sure that you are signed in to your Microsoft account. Then, download all upgrades. The problem is not your Windows version but a component of Windows.
Comment: Microsoft store upgrade for Minecraft worked!
Comment: This worked for me. I merely installed two xbox related updates from the store, then it worked.
Comment: This is the only thing that worked for me, thanks.
Answer: Taken from: MS Windows Forums

Even though you say your Windows is updated to the latest version, if
you're getting the error 0x80131509 then it's highly likely you aren't
running the latest Windows 10 build.
The latest build is version 1903 (OS Build 18362.175).  Are you
running this?  To check, you can either type winver into the Windows
search box or, hold down the Windows key and tap R on your keyboard.
In the Run box, type winver and press enter.
If you're not running Windows version 1903 try this:

Try running Windows update from Windows Settings → Update and Security.

If that doesn't work, you can update via the Windows Media Creation Tool.

Download the Tool and save it somewhere like your Windows Desktop.
Double click on program to run it. Choose 'Upgrade this PC now' and
follow the onscreen instructions.
Comment: I am running the 21h1 version (OS build 19043.1320), and even after trying to update with the method you proposed, my PC stays in 21h1. Do you have any other way i could avoice the problem ?
Answer: Mojang's Official Support Twitter has made a post (or rather retweeted one by their status account) about issues with Java users that own Game Pass not being able to use the game:

We're aware that Game Pass members cannot yet access Minecraft Java Edition! We're working on getting a resolution in place and will update soon.

From what I've researched, they released a new launcher and it seems to have some issues on their end.  You will have to wait for them to release a fix unfortunately.  The Mojang Status account made a post saying it should be fixed, but it does not appear to be for a number of users (see twitter replies chain).
Answer: For those of whom updating Windows didn't work, download Minecraft for Windows 7. That will run.
Comment: How does one do this? Is this even an option considering Windows 7 is EOLed?
Comment: Windows 10 is doing some extra checks which are failing. Technically there wouldn't be much difference between the both (windows 7 and 10).
Comment: The Minecraft website doesn't make this an easy link to find, guiding you somewere else where it isn't listed, but the page with the Windows 7 MSI installer is here: https://www.minecraft.net/en-us/download  (Using this is what eventually worked for me, after upgrading everything and failing.)


How to prevent terminal window from closing when Linux Bash Script terminates?

Question: I've written a simple bash script for deleting some temporary files that match a certain pattern:
#!/bin/bash
cd ~/some_project/some_dir
rm */*.xml

I've saved it as 'script', chmodded it to +x via terminal. Now when I double click this file, I get the option to Run it in terminal or display its output. If I click Run in terminal, the script correctly works, however the terminal window closes immediately. I'd rather the window stay open so I can see if there were any errors (and possibly get rm to display names of deleted files if possible).
I'm looking for a simple way to keep the terminal from closing until a keypress happens.. is there such a way?
Answer: Add read command to the end of your script. It will wait for a complete line of input (that is, Enter key).
Answer: read -rn1

See help read for more information.
Comment: `-r`: If this option is given, backslash does not act as an escape character. `-n`: read returns after reading *nchars* characters rather than waiting for a complete line of input. `1`: the *nchars*.
Comment: I like the solution to the body character minimum message, lol


How can I use Steam without connecting to Steam's servers?

Question: I'm not trying to hack anything here. To clarify my question, I'll give you the situation.
I'm an engineer who is also an avid gamer. Where I work, we get downtime from time to time where we engineers are basically just sitting and waiting for something to do. During this time, our boss (who is also an avid gamer) allows us to bring our laptops and connect to the company network.
The problem we have run into is that we cannot connect to the Steam servers because of the company's firewall. We can connect to Origin with no problem and even download games from it, but we can never access Steam's servers. We have tried a few things to get around it, but nothing successful so far. I guess what I am looking for is some way to get access to Steam's servers the same way I can access the Origin servers.
Comment: @DanWhite You should post that as an answer.
Comment: Have you tried setting up a vpn (or remote acces like noMachine nx) on your home network, connect to it from work and ... profits? If the game is online, that might raise your latency and ping to unplayable level but if your home and work connections are good, it shouldn't be that bad. I would favor vpn over a remote access to avoid the latency of the keyboard and mouse input in remote access.
Comment: "*I'm not trying to hack anything here.*" **Aren't you though?** As far as I can tell you're still asking how to bypass your company's firewall to access a blocked resource. Regardless of whether that block is in place for security, productivity or bandwidth reasons, bypassing it is still almost certainly a violation of your company's IT policy.
Comment: Proxy server. Connect to steam via a proxy, it's not that difficult/expensive, see https://www.linode.com/docs/networking/squid/squid-http-proxy-ubuntu-12-04
Your company firewall shouldn't be able to block steam access because your computers will be accessing your own VPS IP, not Steams.
Comment: Why do you need an access to Steam? Just to start the game or to use dedicated servers for muliplayer sessions?
Comment: Would asking your boss who actively encourages this to have the firewall rules adjusted be unreasonable?
Comment: @NanbanJim You can still be concerned about the bandwidth, of course, but I would personally view that as a lesser concern than security. If security is misconfigured, malware can cost the company millions in lost time, stolen data and brand damage. What's the worst that can happen when someone downloads a 70 GB game like GTA5 (which is currently one of the biggest PC game downloads)? Like the only thing that I could think of is a data cap issue or your ISP not liking that you download games on a business-only line.
Comment: The question title (how to use Steam without accessing Steam servers) is different from the question body (how to access Steam servers at work when blocked by firewall). The answer to the title question is "use offline mode". The answer to the body question is more complicated. Please edit one or the other so that they are asking the same thing.
Comment: How about bying GSM modem (usb one) and a cheap data plan? You won't download games, but you shoul'd be able to log in to Steam easily.
Comment: `We can connect to Origin with no problem` If you're saying this, you need to take a closer look at Origin: connecting to it **is a problem.**  Pretending to be a Steam clone is how EA gets you to install it, but what it really is is a really disgusting piece of malware that spies on you and reports all sorts of personal data back to EA for them to do heaven-only-knows-what with.  If I was running a network I wouldn't want Origin anywhere near it!
Comment: Are there any vacancies where you work?
Comment: @Thorbjørn may have a good idea. If they're concerned about bandwidth, which is a completely legitimate concern, they could look into QoSing you guys way down.
Comment: @NanbanJim I wouldn't be concerned about the bandwidth. Besides the game download itself (which you definitely should do at home), the vast majority of games have a VERY small footprint, like only a few KB/s at most. You're likely to have a bigger footprint from something like email traffic. The main reason is for security concerns: malware might use the open ports or accessible addresses for payload delivery, outside communication, and other nasty stuff.
Comment: I would be, Nate, and I'm one of the people in my company that would need changing the firewall rules. Trusting the user to not update our to be set not to auto update us just asking for it to happen and clobber your corporate bandwidth.
Comment: I agree security is the first concern, but part of security is data availability. If not properly QoSed then this download could choke out legitimate traffic. That could include monetary transactions, along with other businesses critical applications. This is from experience with similar situations. I only thought it would be a mere nuisance until I actually saw it happen on my network.
Answer: I believe your problem can mostly be circumvented by using Steam's offline-mode.
You say you have the game on "your laptop". I assume this is a personal laptop you can take home from time to time.
Here's what you do. In your home, with unhindered access to Steam, download the games you want and start them once. This way Steam can verify your right to run those games at least once. After this, put Steam to off-line mode. It will remember the verifications you did (for limited time, a couple of weeks, according to @badp) and you should be able to use the laptop and its Steam installation to play the games without needing to connect to the Steam's server.
Depending on the game, you may even have the game online without needing to connect to Steam's servers.
Comment: There are also some games that use Steam as a CDN rather than as DRM; these, once installed, will work all the time whether Steam is online, offline, or not running at all. Kerbal Space Program, for example. I don't know if there's a definitive list, but if you're worried about the offline-mode time expiring, focusing on those games might be a good idea.
Comment: Offline mode still requires you to check in every couple of weeks.
Comment: @Medinoc That's wrong you can still get achivements and they sync with your account next time you sign in. This works with any Steamworks game (the majority of games released in the last few years).
Comment: Plus, if you've got the games installed already, you're in the office and Steam _isn't_ in offline mode you could try the suggestions here: http://gaming.stackexchange.com/questions/19234/is-there-any-way-to-start-steam-in-offline-mode-without-logging-in-first on how to get Steam into Offline mode, don't know if they're still valid though.
Comment: Plus you won't get achievements.
Comment: @badp I was aware that there was some limit to the time the verification stays in memory. I just wasn't sure how long it was.
Answer: Other than contacting the firewall's administrator and whitelisting Steam servers there's not much you can do. As suggested in comments below you can connect to Steam using proxies.
I know this doesn't solve your problem, but maybe it will be sufficient to someone else. I had the same problem with my University, where Steam logon server was blocked. A friend of mine found a workaround that surprisingly worked:

When at home, connect to Steam and log in.
Put your notebook in sleep mode.
Power on the notebook at work.

Steam should be connected, games can be downloaded and you can chat with friends, but all games using steam servers (eg. Counter Strike etc.) won't be playable. Nevertheless, it's still more than you could do before (unless they fixed it somehow).
Comment: This will only work if the network admins are naive enough to only block the login servers rather than all addresses associated with steam though.
Comment: This answer is incorrect, setting up a proxy is an option.
Comment: I think this is a slightly better solution than offline mode. It allows more capabilities and is arguably even less trouble. The only problem is that it forces you to keep Steam open all day (potentially not the brightest thing to do at work, for a number of reasons) if you want to use it at all.
Comment: @JamesTrotter Indeed, as I said it doesn't actually solve the OPs question but may help some other people.
Answer: I had this problem in my University. I simply connected to my 3G on the phone and logged into Steam there. It doesn't consume a lot of data just to log in and authenticate your game to start. Don't expect to play online games though. Even if you have fast 3G/4G connection the latency will still be a problem.
Look on Google how to turn your phone into a WiFi hotspot according to your phone's model and system. Good luck with the games friend!
Comment: This could be a problem if you have steam autoupdates turned on. Game updates would start downloading without notice and your mobile data plan is likely to drain very quickly.
Answer: I run OpenVPN on a VM at home. A little port forwarding on the router is all it took to get set up properly. (It's free for <10 concurrent connections). I used to use DropBox to host the VM on my desktop and started it up when I knew I'd need it. Now, I have an old PC sitting there doing nothing else.
System requirements are low (512MB Ram, 1 CPU is more than you'll ever need)
Use port 443 and almost any firewall will let you connect without issues (whitelisting firewalls being the exception but they're rare outside Gov't/Defense).
Doesn't matter where I am or what I want to do, I connect to the VPN and it works.
There is a performance hit - you'll get the worst speed of your VPN server/your current location and there's a (small) latency overhead but I've been able to play CS:S in the office with a ping of < 50ms.
As an added bonus, it works for my (Android) mobile too
Comment: I'm going to give this a whirl. I've never set up anything like this before, but I'm game for trying new things. Thanks!
Comment: No worries. You need to download the OpenVPN Access Server if you want to self-host (rather than using someone else's servers, in which case you can just download the desktop client). See [here](https://openvpn.net/index.php/access-server/overview.html) for the server options.
Answer: If you have access to a SSH session on a remote server, you can download ProxyCap or Proxifier, make a Socks5 using SSH via PuTTy, use the Socks5 with ProxyCap or Proxifier and start Steam using the -tcp argument by making a shortcut to Steam.exe to your Desktop (or anywhere else) and it to the start parameters.
Answer: Use VPN services. I use Astrill which is a paid service because I have other needs besides connecting to Steam, but there should be plenty of free ones out there. A good VPN can connect you to Steam with your full network capacity without any issue.


TCP/IP server client

Question: I just started using Linux. I have dual boot setup and I am familiar with socket programming but on windows in visual studio c#. Now I am trying to build a simple application that will run on Ubuntu.
I have some questions like were to start?
If one for instance server is running on windows can client be on Ubuntu? Can I just write the code in eclipse compile and run it or I need first to preform some configuration in terminal window for Linux?
I want to understand and learn how to  send data wireless form one PC to another without using ROUTER in a middle if it's possible? And with router in a middle then it suppose to be simpler I think.
Comment: What does a router have to do with TCP sockets here? If hosts can reach each other then TCP can perfectly set up a connection to the remote host. Please include in your question what you have tried/found exactly (include code and links). Also: what programming language are we talking about here for Ubuntu? Or do you even only need a shell script? Please **edit** your question to include all this information and try to improve your post as well (you're not likely to get any answers here as it currently stands).
Comment: Have you tried to Google on the subject? because there's a lot out there!
Comment: By the way, a quick search for doing this in Python (works for virtually all operating systems): http://wiki.python.org/moin/TcpCommunication
Answer:
If one for instance server is running on windows can client be on Ubuntu?

The TCP/IP suite is the TCP/IP suite. It does not matter if that runs on Ubuntu, Windows or any other OS. The data on the network is in a well described format, regardless of the OS or even the CPU's Endianness.

Can I just write the code in eclipse compile and run it or I need first to perform some configuration in terminal window for Linux?

To use TCP over IP (or UDP over IP, or ICMP) you will need to configure the network the regular way. There is nothing special of different between you have learned how to do that in windows or in a Linux distribution.

I want to understand and learn how to send data wireless form one PC to another without using ROUTER in a middle if it's possible?

That is called an ad-hoc wireless network. Your wireless cards needs to support that.

And with router in a middle then it suppose to be simpler I think

I assume that with router you mean a wireless access point?
Because a normal router does not do wireless.
(Disclaimer: many devices are a combination of (Fibre|ADSL-)modem, router and wireless access point. However these are still separate function and you really should understand how things work.)
I suggest that you start with learning the basic way how TCP/IP works and then look up how wireless works. If you still have problems after that come back and ask a specific single question.
This is a nice place to start.

TCP/IP server client


How can I upgrade new react app version without hard refresh?

Question: I Upgrade my react app and when I want to release it, clients can't see my changes until they do a hard refresh (Ctrl+F5).
How can I upgrade it without need to hard refresh by clients?
Comment: If you're using webpack you could hash your bundle filename: https://webpack.js.org/guides/caching/
Comment: [HMR](https://webpack.js.org/concepts/hot-module-replacement/) might lead to an interesting solution. I have never seen anyone doing this in production. [This SO answer](https://stackoverflow.com/questions/24581873/what-exactly-is-hot-module-replacement-in-webpack/24587740#24587740) also explains well.
Answer: If you don't use webpack or systemjs,  you can pull version number at the end of the file url


PhP Error; Trying To Print To Console

Question: Specific Problem:
echo '';

Error In Console:
Uncaught SyntaxError: Unexpected token >

Please let me know if you have alternative ways of printing out to console in php.
Comment: `echo '';`
Comment: JavaScript knows nothing about PHP operators and variables. Not only PHP and JavaScript are different languages; they also typically run on different computers.
Comment: http://php.net/manual/en/language.types.string.php
Answer: You need to terminate the string.
echo '';

Variables are only evaluated in strings enclosed in double quotes ("). If you use single quotes (') you have to concatenate them yourself with the dot (.) operator.
EDIT: I put the double quote on the wrong side of the variable.
Comment: I updated my answer. `echo '';`
Comment: I now get this error: Uncaught SyntaxError: missing ) after argument list
Comment: `str_replace(['"', "\n"], ['\"', '\n'], $conn->error)`

PhP Error; Trying To Print To Console


strtol differs in debug and release mode

Question: I use following code in c++ compiling with visual studio 2008:
char input = 'K';
long output= strtol(&input , NULL, 36);

In debug mode it works fine, the output is 20.
But in release mode it makes strange outputs, like 604663109.
It also works, when I set disable code optimization, but that can't be the solution.
I also know, how to calculate it by hand, but I want to know, why there is a difference between debug and release mode?
EDITED: Sorry, it has to be char and not char*. But same error.
Comment: Does removing the address-of operator make difference? I would also suggest to declare input as const char*
Comment: Sorry, it has to be char and not char*. But same error.
Comment: With GCC, your original code: "warning: deprecated conversion from string constant to 'char\*'" and "error: cannot convert 'char\*\*' to 'const char\*' for argument '1' to 'long int strtol(const char*, char\*\*, int)'". Your new code after edit: "error: invalid conversion from 'const char\*' to 'char'". Can you post the truly really _actual code_ please? Thanks.
Answer: strtoul doesn't work on char, only on null terminated strings. You'll have to use a null terminated string, or find another way. E.g.
char input = 'K';
...
char temp[2] = { input, '\0' };
long output = strtol(temp, NULL, 36);

Comment: Wow, now it works. Thanks very much. But why did it work in debug mode?
Comment: Because you didn't have a null terminated string. This is an example of *undefined behaviour* (UB), and it's common for programs with UB to *seem* to work, even though they are really bugged. It's one of the things that makes C++ hard.
Comment: @SpeziFish most likely the debugger zeroed the bytes in memory after your char, in release they had some different value (whatever was there before). But as stated by john, it's undefined behavior.
Answer: Since &input doesn't point to a null-terminated character array, the code has undefined behaviour.
This should work:
const char* input = "K";
long output = strtol(input , NULL, 36);

The reason it appears to work in the debug build is probably that the compiler has inserted "magic" values around the input variable in order to enable detection of stack corruption, and a zero happens to be placed at &input + 1.
Comment: Thanks, good to know. But can't change the type of 'input', so john's solution is the better one :-)
Answer: Your call is wrong, you shouldn't take the address of the pointer!
It should be:
strtoul(input, NULL, 36);


Ionic 2: Reorder items from Firebase

Question: I am currently creating an Ionic notes app where I will allow the user to rearrange the items in the list with the reorderArray() function. However, I am using Firebase so I get this error on this.notesList.

Argument of type 'Observable' is not assignable to parameter of
  type 'any[]'. Property 'length' is missing in type 'Observable'.

I am not sure how to use this with Firebase so anything would help. Here is my code:
HTML:

  <ion-list reorder="true" (ionItemReoder)="reorderItem($event)">

    <ion-item *ngFor="let note of notesList | async">
      <ion-checkbox (ionChange)="addToTrash(note.id)"></ion-checkbox>

      <ion-label>

{{ note.name }}

        {{ note.note_date | date: 'shortDate' }}
        {{ note.text }}
        {{ (notesList | async)?.length }}
      </ion-label>

    </ion-item>

  </ion-list>

Typescript:
export class NotesPage {

  notesList: Observable<any>;
  editmode: boolean = false;
  trash = [];

  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    public database: AngularFireDatabase,
    public loadingCtrl: LoadingController,
    public alertCtrl: AlertController
  ) {
    this.loadNotes();
  }

  loadNotes() {
    const loader = this.loadingCtrl.create();
    loader.present().then( () => {
      this.notesList = this.database.list('/notes').valueChanges();
      loader.dismiss();
    })
  }

  reorderItem( indexes ) {
    this.notesList = reorderArray(this.notesList, indexes);
  }

}

Answer: this.notesList is an Observable in your case. reorderItems can only order array-likes. so something like this should do the trick.
notesList: any[];

[...]

loadNotes() {
  const loader = this.loadingCtrl.create();

  Observable.fromPromise(loader.present()).switchMap(() => { //1
    return this.database.list('/notes').valueChanges(); //2
  }).subscribe((list) => { //3
    this.notesList = list; //4
    loader.dismiss();
  });
}

reorderItem( indexes ) {
  this.notesList = reorderArray(this.notesList, indexes);
}

execute promise loader.present "the rxjs way"
switch to the second Observable. .valueChanges() returns an Observable.
subscribe to second Observable to get the streamd value
write the value to this.notesList to trigger UI-Bindings

Edit
{{ (notesList | async)?.length }}
has to be
{{ notesList?.length }}
because notesList is not async (anymore).
There are (at least) two ways of displaying values that are streamed through observable pipes. One is the async pipe in the template and one is the way i explained. The async pipe subscribes to the observable under the hood and returns the value. But with the pipe you can't reorder the items that easy.
Comment: This is great thank you. However, I got a Runtime Error that says InvalidPipeArguement: '[object Object],[object Object],[object Object],[object Object]' for pipe 'AsyncPipe'

Ionic 2: Reorder items from Firebase


Inside a Metal shader code, how to define an in/out parameter variable of a function?

Question: I have this function:
void myFunct(const int A, ?out? int B){B = B + A;}

How to declare B in such a way that the function can update its value and return it to the caller?
Comment: Assuming standard C++ sematics in Metal, `void myFunct(const int A, int &B) { B = B + A; }`
Answer: Metal is a C++ based programming language that allows you to pass a pointer to a function. To do so, simply declare the function parameter as a pointer type.
void myFunct(const int A, device int *B)
{
   *B = *B + A;
}

device int *C = 0;
myFunct(1, C);

You can also pass variable by reference:
void myFunct(const int A, device int &B)
{
   B = B + A;
}

device int *C = 0;
myFunct(1, *C)

or pointer by reference:
void myFunct(const int A, device int *&B)
{
   *B = *B + A;
}

device int *C = 0;
myFunct(1, C);

Comment: thanks 0xBFE1A8, however what the difference between using &B like @bg2b suggest and using *B ?
Comment: & indicates a reference.  It's basically a pointer under the hood, but you don't have to write *B.  Also, you're guaranteed that the reference points to something (it can't be a null pointer).  Either method will work though.
Comment: @loki in c++, we can pass parameters to a function either by pointers or by reference. In both the cases, we get the same result. [What are the reasons we use one over the other?](https://stackoverflow.com/questions/57483/what-are-the-differences-between-a-pointer-variable-and-a-reference-variable-in)


Here-API: How find the Air and road distance between two locations?

Question: I am using developer.here API.
My endpoint is  discover.search.hereapi.com/v1/discover?apiKey=###&q=delhi&at=13.08362,80.28252&limit=5
it's returning the distance. but there is no identification of the distance calculated by road or air? is there any way to send the param specifically by road, or by air?
Answer: It is by air. You can get the road distance if you use the routing API and supply your initial position and the position of the result.
Comment: If it helps, I built a demo: https://codepen.io/cfjedimaster/pen/QWNxmLE?editors=1011


Problems linking to SDL2 inside of Eclipse CDT on Fedora 19

Question: I am having troubles linking SDL2 to a C++ application inside of Eclipse CDT Kepler on Fedora 19 64bit. Here is what I did:

To install SDL2 I ran the line sudo yum install SDL2-devel.i686
Created a new .cpp file with copy paste code just to test the environment from here
Add the SDL2 library to the GCC C++ Linker: Project Properties -> C/C++ Build -> Settings -> GCC C++ Linker -> Libraries -> Libraries (-l) -> add: libSDL2.so

Then when I saved and built the program I got the fallowing error:
    Invoking: GCC C++ Linker
    g++  -o "SDL2 Test"  ./src/SDL2\ Test.o   -llibSDL2.so
    /usr/bin/ld: cannot find -llibSDL2.so
    collect2: error: ld returned 1 exit status
    make: *** [SDL2 Test] Error 1

So then I did a file system search for SDL2 and found that the libSDL2.so exists in /usr/lib/ and /lib/. Shouldn't either of those be the default location for searching for libraries? What am I missing?
(If it matters, within the .cpp file itself there are no errors, all SDL commands are recognized, it is just the linker)
Answer: I have found the answer. I am using a 64bit version of Fedora, and trying to use 32bit libraries. I assumed that because I was developing a 32bit application, that I should use 32bit libraries. But, it worked when I uninsulated the 32bit and installed the 64bit libraries.
Also, eclipse on Linux assumes that the 'lib' prefix and '.so' postfix exist, so you do not need them when you add them to the linker within eclipse (just SDL2).


Where do Abadon Crusher Mutants spawn on the surface of the world?

Question: In Rage 2 the Crusher achievement requires you to kill an Abadon Crusher Mutant with your Pheonix vehicle. As far as I can tell the only location where Abadon Crusher Mutants spawn and are still accessible with the Phoenix is at "D and D's Hood" in The Wilds region. Unfortunately, I killed these two massive mutants before I knew of the achievement.
Since "Digg the Smasher" and "Dugg the Basher" are already dead and I don't have a saved game where they are still alive I do not seem able to earn this achievement. Are there any other locations where Abadon Crusher Mutants will spawn and I can kill with my Phoenix?
Answer: There is a guide for this achievement.
The answer is yes, there are a few random spawn locations where Abadon Crusher Mutants may spawn.

The first location is in southeast of the town 'Gunbarrel' in a meteorite craters. The second random spawn location is in the southwest of the town 'Wellspring'.
  I found (later) a third random spawn location. Directly above from the first MBTV location in Broken Tract.


How much pressure should you apply when rolling on paint?

Question: I hate painting, as I know many people do.  One of my issues has always been the streaks that are left on the wall.  I got to thinking that perhaps I'm applying too much pressure when I'm painting, and that's what is causing the streaks to show (even after a 2nd or 3rd coat).
So, how are SUPPOSED to paint?  Are you supposed to load the roller up with a bunch of paint and only apply light pressure?  Or do you just want to saturate (but not dripping) the roller and push a bit when rolling?
I know it's a simple question but I'm really bad at painting, that's all I can say.
Comment: Quality of paint is what I've found to be most important in avoiding this issue.  And 2 coats.
Comment: If you use too much paint on the roller, or push to hard and squeeze paint out on the sides, you end up with streaks of "thicker" paint.   The thickness difference can show through multiple coats, and this particular issue can actually be worse with a good quality paint.
Comment: @Tyson I like to think the paint I use is good (Valspar Signature).  It's like the middle of the line for that brand.  Even then, my poor painting skills lands me with a tacky looking paint job.  I agree with you 100% though.  The thicker and better the paint, the less rubbish it looks.  I feel like I could make a bad paint job with anything though.
Comment: Not enough coats.  This is sometimes exacerbated by cheap paint.  In bold colors, the base is nearly transparent, and what makes a paint a color is the *pigments*. If he's squirting the pigments from the same mixer as the cheap paint, they are cheap pigments. Also that looks like the inside of a building, which are almost always painted with off-whites, A bold color like that will always have trouble covering an off off-white even if it's applied perfectly.  **More coats.**
Answer: Don't stretch your paint.
The problem is probably not pressure (assuming that you remain consistent), but what I call "stretch". Folks tend to stretch the paint load of their roller or brush too far. With experience you'll learn what's the appropriate coverage area for a loaded roller.
The goal, of course, is to end up with a uniform film of paint on the wall. If you're working your roller out past its range, you're forcing the dry roller through the film and creating voids in it. Instead, try this:

Load the roller with paint. My technique is to pull some paint from the pool up the slope of the pan, and then work the roller into it a few times so that I have even coverage all the way around the nap.
Make contact with the wall 6-12 inches away from the newly-painted region. This drops the initial load of fresh paint on dry land, so to speak, and creates a temporary repository of paint.
Work back to the previously painted zone, overlapping somewhat. Roll direction isn't important at this point.
Work remaining excess paint from the repository outward, stopping when it becomes difficult to get coverage. This is the extent of coverage for that roller payload. Do not increase pressure to gain more coverage.
Give the newly painted area one more roll, all in the same direction, blending with the previous area. Keep an eye out for voids and runs, which should be rare. At this point the roller should be fairly dry and not leaving edge lines. If it is, roll the edges out on new wall to clean them up, then re-roll the working area.

Using this technique I get consistently good results. For most interior wall situations, a coverage zone for a loaded roller is about 2ft. by 3ft. Maybe less.
I also paint almost exclusively with quality 3/8" nap rollers. I don't mind a bit of stipple, which helps hide roller lines and wall imperfections.
Or you have other problems.
All this said, if you're seeing streaks after a third coat, something else may be going on. Maybe you're rolling too long after the film starts drying. Maybe your roller has residual primer or paint of another color in it. Maybe the paint needs better mixing.
Comment: I agree with people trying to "stretch" the paint on the roller, but I also think that sometimes people will instinctively try to push harder to get better coverage and ring as much paint as they can out of each roller load. I think a good tip would be, When your roller starts to run out of paint, reload it, don't press harder.
Comment: No, great answer, I was really just referring to the first sentence.  You said "The problem is probably not pressure...".  I'm saying I think pressure is a definite problem and is caused by stretch, trying to squeeze the "last drop" out of each roller load.
Comment: All good stuff, and I would add that it is important to keep a "wet edge"; in other words be prepared to complete an entire wall, work quickly enough and in small enough sections so that you are never rolling into dry areas. Don't know who mentioned it but the darker the color the less "hiding pigment" (titanium dioxide), so applying darks usually needs more coats, especially over light colors.
Comment: While conventionally true, I've found that modern latex paints don't experience lift-off or other side effects of over-rolling dry-ish areas (assuming an adequately wet roller). More important to me is to roll out edging brush patterns before *they* dry.
Comment: I agree if a properly loaded roller is worked from 1 area to a fresh area you should see any streaking right away I usually do not work in straight lines but fan the paint, if always working in a line streaks are hard to avoid.
Answer: When I paint with a roller, I only do a small squarish area at a time, no larger than 3 feet square. I load up the roller, then roll it across the area in a zigzag pattern, then (without reloading the roller) repeat the process at a 90 degree angle to the first pattern, blending the paint into the previously painted area.
Then I load up the roller again before proceeding to the next unpainted "square."
(For corners and edges, I paint those with a brush or corner roller before using the roller. This allows the bush marks to be smoothed out by the roller.)
This method helps to ensure uniform coverage.

Some paint pigments are semitransparent -- reds are especially so. When used with a deep base (instead of a pastel base), it can take many coats to get even coverage. Sometimes it helps to use a tinted primer before the first coat of paint.
Answer: That looks like you are not applying the paint thick enough, either you are applying coats too thin, or you are applying too few of them.
Buying a quality paint is well and good. But bold colors like that require a deep base, which is almost transparent.  In those, the pigments do all the heavy lifting.  The pigments come from a carousel, and you notice the paint shop only has one or two such carousels.   That means they are using the same pigments on the cheap and good paint alike, so the cost of the cheap paint can cover the pigments.
This looks like a building interior, and almost always, they are painted with pastel (off-white) paints.  So essentially you are covering white with a bold color.  A big change like that asks a lot of the pigments.  You can't possibly get it done with one coat, and may need 3 or even 4.  What's more, it's natural for coverage to be imperefect, and that'll really show on one coat.  With 2-3 it will average out.
Answer: Really interesting to read all the different techniques folks use! Most of my ceiling heights are 2.4m or 8 foot and I find a loaded roller will hold enough paint to cover one "floor to ceiling" strip. Hit the wall in the middle and then roll the paint up and down several times (keeping broadly within the rollers width). Load up the roller and repeat. NEVER stop in the middle of the wall. Keeping a wet leading edge is vital which is why I don't go in squares as you'll always have one dry edge. Going top to bottom in one go means I'll always have a full height 'wet' leading edge.
Also as already mentioned, a longer pile is easier work. I usually use a middle length pile which is perfect for the flat drywall I'm working on.
ALWAYS use a roller pole, which counterbalances the weight of the loaded roller head (and saves your back!). It also allows easy application of the right amount of pressure. Holding the roller directly means it's very difficult to apply the same pressure as you bob up and down. I use an aluminium extendable one on it's shortest length, around 70cm or so.
Pressure, hmm. Yes you do need to apply an even pressure but it's not very much. Too little and you won't move the paint up and down the wall, but too much and you'll get lines at the edges of the roller.
Oh, and good paints usually don't need more than two coats (unless you're going for a huge colour change/difference).
Answer: Wanted to up-vote Handymans post.
Read it,
do it.
That's exactly how to professionally roll out a wall.
the only thing I Might add to that is - never paint out of a flat pan / tray - you spend all your time fighting it, moving / spilling it, and refilling it mid wall / ceiling.
Always roll out of a 5 gallon bucket with a "grid" that is made for that. It is cheaper than a tray anyway. Put as much as you need, up to about 2 gallons, of paint in the bottom of the clean empty 5 gallon bucket. Now you have enough paint to get something done without stopping to refill. The grid also allows excess paint to be released from the roller.
Comment: Welcome to Home Improvement! This is interesting, but doesn't answer the original question. Please [take our tour](//diy.stackexchange.com/tour) so you'll know how better to contribute here.
Answer: I disagree with some answers . As far as using a pole , yes when you need the reach . But I disagree that u paint better with one . You paint best when grasping the roller frame directly . Use a light touch , too much force can leave a ridge at either or both ends . Not exactly sure what the one person was saying but if the person meant to just roll up and down a wall from top to bottom then move over . Bad idea you will see al kind of vertical lines


NSMutableArray and pointer: an operation on the pointer is an operation on the original array (?)

Question: This is kind of a long way to go to ask a simple question, but given how confusing pointers in Objective-C are for some, maybe verifying what's going on here will help others, as well as myself.
So, in a nutshell, I have a UITableView whereby you can enable editing and delete a row. I want to delete the row from the table view, and the data source(s). The original data source is in a model class, but I have a pointer/property containing the data in my local table view controller. When I delete a row from the table view via editing, it appears to work and delete the data...but I don't understand why. I think it's because of my fundamental misunderstanding of pointers.
In my model class with an NSMutableArray:
@property (nonatomic,retain) NSMutableArray *allAlarms;
// ... plist gets read and serialized to an array ...
allAlarms = [NSMutableArray arrayWithArray:[plistValues objectForKey:@"Alarms"]];

In a UITableViewController class, I pull that mutable array in via a property during viewWillAppear:
@property (nonatomic, retain) NSMutableArray *alarms;

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    // retrieve values from data controller
    self.alarms = [dataController returnAllAlarms];
    [self.tableView reloadData];
}

When the delegate method for editing is exercised, I do this, and it works...
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
    // Delete the row from the local data source
    [self.alarms removeObjectAtIndex:indexPath.row];
    // The above line appears to delete it in the local pointer as well as in the original property in the model class
    // so I just have to tell the data controller to save plist for when it's read back in via viewWillAppear
    [dataController writePlist];
    // Delete the row from the table view
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}

}
Why does what is going on in my tableView:commitEditingStyle:forRowAtIndexPath ultimately work? Does removing an item from a pointer to an NSMutableArray in my local class also remove it in the original pointer in the remote class because the former is a pointer to the latter?
I need to understand because there are other operations I'll be performing on this local pointer and want to make sure I'm not being redundant in wanting to perform it on the remote property, etc. Is there anything about what I'm doing unintuitive and redundant, or will it make more sense as I continue to learn Objective-C & use pointers more?
Answer: Yes, it sounds like you don't quite understand how pointers work. Rather than trying to explain it all myself, I'll point you to this thorough chapter on pointers.
One thing to note is that in Objective-C, you never allocate objects on the stack1. Objects are always allocated on the heap, and a pointer returned to you. (like malloc().) This is why there is always an asterisk (*) in the type of an object2. Both your model and controller have pointers to the same underlying array. self.alarms = [dataController allAlarms] doesn't copy the array, it copies the pointer3.
When you call removeObjectAtIndex:, it doesn't change anything about the pointer—a pointer is just a number—it dereferences the pointer and operates on the underlying object in memory.
1. With one minor exception, Blocks.
2. Excluding id, which is typedef'ed.
3. If you do want to copy the array, use the (copy) property attribute rather than (retain).
Comment: Thanks for the reference (and I will read it) but I misunderstand pointers despite all the textbook reading, so I figured I'd just dive in and try. But I think I (basically, sort of) get what you're saying: so both these pointers just reference the same array. By creating a pointer to a pointer, I'm just referencing the same array. And a removeObjectAtIndex on either pointer will remove the object from the same array. Using retain just said "give me ownership of that same object in memory." Am I on the right track?
Comment: Yep, you've got it. Just a few corrections on terminology: When you set `self.alarms`, that's not a pointer to a pointer. It's a copy of a pointer. (a pointer to a pointer looks like `NSError **`) Or another way to think about it, it's a copy of a number. The same thing happens when you assign, say, an int to an int. (`int i = 5, j = 3; j = i;`) If you were using `i` and `j` as array indices, setting `j` to `i` doesn't set `array[3]` to `array[5]`. It just changes the value of `j`. Returning to pointers, the `int`s are your pointers and `array` is all of memory.
Comment: This is starting to make sense. Thanks a lot for your help.


Location with High Salvagable Materials Drop Rate

Question: So with the February Monthly Achievement; we need to salvage 500 items.  This comes out to roughly 18 per day (assuming you play every day this month); but for the sake of argument lets say I want to salvage 25 items per day.
What areas have mobs that will drop salvageable items at an acceptable rate?
Ideally; I'd think you'd want enemies that would typically drop armor/weapons.  Ones that drop rare crafting materials (while helpful) seems to be less important.  Also; it seems like you'd want to avoid enemies that drop bags (as you get no salvage points for them).
My assumption is that I'd want to run dungeons a bunch of times (3 fractals seem to fill up a good chunk of my inventory) as well as areas with lots of humanoid enemies (pirate/bandit camps)
Another viable strategy seems to be spinning up a new alt and ranking up my crafting skill and then salvaging the created items.  (Currently my main is an ele with Tailor/Artificer; so fire up a ranger with Leatherworking/Huntsman)
Comment: You can actually swap out professions on the one character - you can relearn a previous profession (for a fee) with no loss of skill.
Comment: I'd say specifically farming for salvagable items to do your monthly is probably just wasting time. Generally speaking this one should just come naturally from playing. Just do what you'd normally do and you'll have plenty to salvage!
Comment: I'm finding this easy by just playing normally. I'm salvaging all my white and blue items.
Comment: I got this achievement just by salvaging items I constructed while levelling professions
Comment: Just to follow up; I spent some time last night and found that Fireheart Rise seems to be a decent area.  There's several events (take back the beach, reclaim the quarry, etc.) that have lots of Fire Legion.  Also found that the TP seems to have adjusted for the monthly achievement; some rares are actually cheaper than commons.  Ended up buying around 150 cheap items to catch up my current pace.  Looks like my winning strategy will be to work on my map completion/dungeon requirement; and then supplement with TP purchases.
Comment: I don't really know where you can find the perfect salvageable-drop monster, but seeing my progression in the salvage percentage I guess the achievement is balanced so with your standard playing you should get it.
Otherwise, if you run out of time on the last days you can always buy the cheaper items from vendors or trading post (as David B suggested) and it should do the trick!
Answer:
How can I aquire 500 salvage-able items with minimal effort or cost?

Right now there are Malachite Copper Rings available for 31 copper each (58k of them).  These are just the first item I found and may not be the cheapest possibility.
If you bought 500 of these, it would cost 1g55s.  If you salvaged them (using cheap honor kits) and only got 500 copper ore, you would recoup 70s at immediate sale prices.  That would net out to 85s cost.


How do I make a USB RS232 dongle show up in /dev/ttyUSB*?

Question: I have a couple of FTDI based USB to Rs232 serial dongles. Sometimes when I plug them into my Ubuntu 10.04 laptop, they show up as /dev/ttyUSB0 and /dev/ttyUSB1, which is what I want to have happen. But sometimes they don't. When they don't, sometimes rebooting fixes the problem and sometimes it doesn't. They always show up in lsusb hanging off of Bus 5:
Bus 005 Device 003: ID 0403:6001 Future Technology Devices International, Ltd FT232 USB-Serial (UART) IC
Bus 005 Device 002: ID 0403:6001 Future Technology Devices International, Ltd FT232 USB-Serial (UART) IC
Bus 005 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub

I can see them if I do ls /dev/bus/usb/005 as 002 and 003. But if I pass /dev/bus/usb/005/002 to pyserial, which is what I'm using to access /dev/ttyUSBx, I get SerialException("Could not open port: [Errno 13] Permission denied: '/dev/bus/usb/005/002'",).
Comment: Don't access /dev/bus/usb/* with pyserial It is a direct connection to your USB device so you need to talk USB to it, not serial..
Answer: If you don't need the serial device for braille devices, you may wish to disable brltty (you can remove the package), which used to be the culprit for ttyUSB devices at least before Lucid.
I definitely hadn't seen USB RS232 dongles still get claimed by brltty since the Lucid release though.
Comment: This is a pretty common issue among Arduino uC developers.
Comment: Thanks for the tip.  I'll try it the next time I see the problem and accept your answer then.
Comment: I went ahead and removed the `brltty` package and things seem to work.  @Evan - the USB device in question is based on an FTDI interface, which I think is what's used in Arduino too. Maybe there's an issue specific to that USB chip.
Comment: @mtrw Arduino **does** use the FTDI chip as it's serial/USB interface.


How to push metric to Opentelemetry with go-sdk

Question: I try to push metric to opentelemetry with go-sdk but I found nothing about doc for it. so far I try with this code but idk what the next step, to be honest, I'm bit confuse with the provider and reader stuff, I'm new in monitoring
    func main() {
    ctx := context.Background()

    res, err := resource.New(ctx, resource.WithAttributes(semconv.ServiceName("my-service")))
    if err != nil {
        panic(err)
    }

    ctx, cancel := context.WithTimeout(ctx, time.Second)
    defer cancel()
    conn, err := grpc.DialContext(ctx, "localhost:4317", grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock())
    if err != nil {
        panic(err)
    }

    metricExporter, err := otlpmetricgrpc.New(ctx, otlpmetricgrpc.WithGRPCConn(conn))
    if err != nil {
        panic(err)
    }

    exporter, err := prometheus.New()
    if err != nil {
        panic(err)
    }

    provider := metric.NewMeterProvider(metric.WithReader(exporter))
    meter := provider.Meter("github.com/open-telemetry/opentelemetry-go/example/prometheus")

    counter, err := meter.Float64Counter("foo", instrument.WithDescription("a simple counter"))
    if err != nil {
        panic(err)
    }
    counter.Add(ctx, 5)

    reader := metric.NewPeriodicReader(metricExporter, metric.WithInterval(1*time.Second))

}

the source information i have so far its from here Sample and here Sample
Answer: First, it is worth noting that the OTel Go metrics API and SDK are not currently considered stable. I will try to keep my answer focused on higher level items which are included in the stable OpenTelemetry metrics specification so that it doesn't become outdated. Anything go-specific which follows is subject to change.
It looks like you're trying to set up two different types of exporters. The prometheus exporter is scraped by Prometheus, and the otelmetricgrpc exporter creates a connection which pushes metrics over OTLP to a receiver like the OpenTelemetry Collector. You likely only need one and not both of those things. The first sample you linked is actually only for traces, not metrics, but the principal is largely the same.
The entry point for metrics in any OpenTelemetry SDK is a meter provider. The meter provider handles metric related configuration and aggregation and export of data. It is also how users acquire meters. Each code module typically has its own meter. From that meter metrics are created, and from those metrics data points are recorded. All metric points are aggregated together and flow back through the meter provider.
In order to read metrics from a meter provider you need a metric reader of some kind. If you are trying to push metrics using a protocol like OTLP, you would use something like the periodic exporting metric reader which periodically collects metrics from the meter provider and exports them using an exporter.
If you were trying to use a pull-based metric system like prometheus, the exporter acts like the metric reader and reads metrics each time the scrape endpoint is requested by the metric system. This is what is done in the second sample you linked. The serveMetrics function opens a webserver that listens on port 2223 and handles requests to localhost:2223/metrics. Each time a GET request comes in on that endpoint, the metrics are aggregated according to the meter provider configuration and returned in the response body. This allows a system like Prometheus to periodically request metrics from your application.
Comment: Thanks that good information for me, So its not worth use Otel Go for this moment, can we just use the Prometheus directly, im use AWS ECS its clusters so i cant register every ip address when scale up and scale down automatic any idea to handle this case?
Comment: Correct you will not be able to have prometheus scrape your ECS containers directly. Amazon recommends using OpenTelemetry to export to the AWS Distro for OpenTelemetry collector in that case. I would say the Go SDK is likely ready to be used for most usecases but obviously it is not officially stable so it's up to your particular risk/change tolerance. Another option is to use the cloudwatch agent which is what I would call the "legacy" solution.


Can one instance of a class (not the class itself) be the parent of many instances of another class?

Question: Root Problem
I am trying to build a render engine with Vulkan in C++. I am trying to remove the asset meshes, textures, and similar from within the engine structure where I had it for testing purposes to its own separate class. I need to access some of the objects stored in the render engine class because each asset need to be able to add themselves to the vector of vertices, and have access to the same VkDevice for example.
First attempt
The first method I tried was making the asset's constructor take the render engine as one of its arguments, then taking pointers to all the objects that I would need from the render engine for the asset. I still think that this method might work, but I could not declare the class for the render engine before the class for the asset because the render engine needs a vector of all the assets that it was managing in this scenario. Neither could I declare the class for the asset before the class for the render engine because then I could not take the render engine as an argument for the asset's constructor. This feels like it should have a trivial solution, but I could not find one, so I went off to try my second method.
Second attempt
The second method I tried was inheritance. However, I realized as I was experimenting with it that I did not know of a way to get one instance of the render engine class to be the parent of many instances of the asset class. Each asset wanted its own render engine, but I needed for each asset to inherit from the same render engine so that the render engine's objects would be the same for all assets and to avoid having many instances of the render engine to manage.
Final thoughts
I think that there is probably a simple way to do the first option, but I think that in the long run the second option will be more rewarding as it will be easier to manage, cleaner, lead to better organized code, and even teach me more about this great language that I am beginning to explore. I would prefer a solution that involves the second method, but I also don't really know if this is possible because it seems like inheritance does not work on a per instance basis. Finally, I am very much open to new ideas that do not involve either of these options.
Final question
Is there a method of going about inheritance that allows for many instances of one object to inherit from one instance of another object in C++?
Comment: You can't inherit instances, only classes. Also, the assets inheriting the "render" class (or object if that was possible) doesn't make sense. Remember that inheritance is an "is a" relationship. An "asset" is not itself a "renderer". An asset can be *renderable* but doesn't have to be.
Answer:
Is there a method of going about inheritance that allows for many instances of one object to inherit from one instance of another object in C++?

No, you are mixing apples and oranges here.
Inheritance is a way to build one class off of one or more base classes. It has nothing to do with instances of those classes, and in C++ classes are not objects. So by deriving a class D from another class B you define D but you do not create any instances of either B or D.
When you create objects (instances) of D, these objects will all have the same binary layout that will include data members from B and D. That is, every object of class D will contain a base subobject of class B. You cannot create an object of class D without its base subobject of class B or with a different binary layout, e.g. by referencing B at a different address.
You could share data between different objects by using references or (smart) pointers, like std::shared_ptr. But this has nothing to do with class inheritance. You will have to use references and (smart) pointers as data members of your classes.
Answer:
Can one instance of a class (not the class itself) be the parent of many instances of another class?

Technically yes... if those many instances are all sub objects within one complete object. Example (which is probably something that no one would ever write):
struct Base {};
struct Second : virtual Base {};
struct Third1 : Second {};
struct Third2 : Second {};
struct Derived : Third1, Third2 {};

Here, there is one instance of Base within Derived, and that Base instance is the (virtual) base of two separate instances of Second, both of which are indirect bases of Derived.
Even though the answer was "yes", I don't know if this would be of use in any use case.


Wifi keeps disconnecting on Asus x541U running Ubuntu 17.04

Question: This problem only started occurring after I did a fresh install of Ubuntu 17.04. Whenever I restart, the internet works, for like 15 minutes at most, and then the internet will disconnect, and sometimes, reconnect. It will say connection established, but it won't always load sites after "reconnecting". There are multiple issues I am looking at here but they have the same source: Wifi cutting off randomly. I do use PIA VPN but even without the VPN, I seem to be encountering this issue. Anybody know how to proceed?
The device is Asus x541U, I have googled, none of the fixes work or are relevant to my device
As per request:
lspci -knn | grep Net -A3; rfkill list
:~$ lspci -knn | grep Net -A3; rfkill list
03:00.0 Network controller [0280]: Realtek Semiconductor Co., Ltd. RTL8723BE PCIe Wireless Network Adapter [10ec:b723]
    Subsystem: Lite-On Communications Inc RTL8723BE PCIe Wireless Network Adapter [11ad:1723]
    Kernel driver in use: rtl8723be
    Kernel modules: rtl8723be
0: hci0: Bluetooth
    Soft blocked: yes
    Hard blocked: no
1: phy0: Wireless LAN
    Soft blocked: no
    Hard blocked: no

I have already tried this: Rtl8723be WiFi incredibly weak
That query was about a weak signal, I am getting absolutely no connection at all now, after having followed the instructions there.
Comment: Possible duplicate of [Rtl8723be WiFi incredibly weak](https://askubuntu.com/questions/883673/rtl8723be-wifi-incredibly-weak)
Comment: Please [edit] your question and add output of `lspci -knn | grep Net -A3; rfkill list` terminal command.
Comment: I've had the same problem once. It kept disconnecting for some reason.  I just reinstalled Ubuntu and it worked fine for me after that. I believe I had this problem when I was using 14.04 which isn't supported anymore. I have no idea. I would do a fresh install but there are probably other ways to solve this I just don't know them. Wait for others to respond and try their recommendations first before doing a fresh install. Or search the forums to see if you can get an answer.
Comment: The problem is that I *just* did a fresh install like, a few weeks ago.
Comment: I just added it
Comment: Tried the instructions on that. Now the Wi-Fi doesn't work at all
Comment: Tried ant_sel=2 and it is working now, so far. If it runs stable for an hour or so then that'll be great.
Comment: Nope. After restarting no connections show up, and in a way now it's worse
Answer: I am experiencing the identical problem using ubuntu 17.04. I am using a Gigabyte GA-H97N-Wifi motherboard. This has been going on for several months, approximately since the time I started using the "802.11n" network in my home.
I attempted the following fixes:
nmcli nm enable false; sleep 0.5; nmcli nm enable true
# Fails, as "nm" is not a recognized option of nmcli
sudo service network-manager restart
# No change in status
sudo systemctl restart NetworkManager
# No change in status
rfkill block wifi; sleep 3 rfkill unlbock wifi
# No change in status

I have attempted to downgrade the connection from 802.11n, on start-up:
sudo modprobe iwlwifi 11n_disable=1

This may delay the failure; but a failure in wifi always comes eventually.
When I use "iwconfig" to check the status of wlan0, I note that sometimes "Tx excessive retries" goes from "0" to "1" simultaneous with the failure of the Wifi (checking every 2 minutes).  However, this does not occur 100% of the time; I would say about 90% of the time.
Finally: I note there was an update, which I installed 30 minutes ago (Oct 3 2017), and the wifi has operated fine for the past 30 minutes, which might be a several-month-long record!  EDIT: It didn't help!


Why is Scala's behavior in case of overloading with by-name parameters different from the case with by-value parameters?

Question: Given this Scala code:
object test {

  def byval(a: Int) = println("Int")
  def byval(a: Long) = println("Long")

  def byname(a: => Int) = println("=> Int")
  def byname(a: => Long) = println("=> Long")

  def main(args: Array[String]) {
      byval(5)
      byname(5)
  }
}

the call byval(5) compiles correctly, but byname fails to compile:
ambiguous reference to overloaded definition

Why? I would expect to observe the same behavior for by-value and by-name parameters with respect to overloading… How can it be fixed?
Answer: That's because JVM does not support a "by-name" parameter, so Scala has to implement it in another way. => X actually compiles to a Function0[X], which erases to Function0[Object], which makes it impossible for Scala to distinguish two methods that differ only by the expected type of a by-name parameter.
Comment: http://scala-programming-language.1934581.n4.nabble.com/Erasure-not-allowing-a-signature-overloading-scenario-td1952173.html
Comment: @JPP That's a question that has been asked before. One simple way would be to make the first argument mandatory and not part of the vararg. Other methods involve implicit parameters, but I don't recall the exact tricks.
Comment: Thanks Daniel, this explains the why. Now how can this be worked arouned (if at all possible)?
Comment: @JPP: Don't use overloading in this particular case.
Answer: Possible workaround without overloading (in addition to what has been said earlier), if you don't want to use different method names:
def byname[A](a: => A)(implicit manifest:Manifest[A]) =
manifest.erasure match {
   case erasure if(erasure.isAssignableFrom(classOf[Long])) => println("=> Long")
   case erasure if(erasure.isAssignableFrom(classOf[Int])) => println("=> Int")
}


How can i make a function always return the same result on my test

Question: i have a function named "exchange" that depends of another named "getQuote", that returns a value from an api. How can i make "getQuote" always return a specific value to test "exchange"
getQuote function:
async function getQuote(from_symbol: string, to_symbol: string): Promise<any>{
    const options = {
        method: 'GET',
        url: 'https://alpha-vantage.p.rapidapi.com/query',
        params: {
            from_symbol: from_symbol,
            function: 'FX_INTRADAY',
            interval: '5min',
            to_symbol: to_symbol,
            outputsize: 'compact',
            datatype: 'json'
        },
        headers: {
            'X-RapidAPI-Key': API_KEY,
            'X-RapidAPI-Host': 'alpha-vantage.p.rapidapi.com'
        }
    };

    try{
        let response = await axios.request(options);
        let QuoteData = await response.data;
        let current_time = (QuoteData["Meta Data"]["4. Last Refreshed"]);
        let quote_data = (QuoteData["Time Series FX (5min)"][current_time]);
        let quote_value: number = parseFloat(quote_data["1. open"]);
        return quote_value
    }catch(err){
        console.log(err);
    }
};

exchange function:
    async exchange(cash: number, from_coin: string, to_coin: string): Promise<void>{
        if(this.cash[from_coin] < cash) return;

        this.removeCash(cash,from_coin);

        let quote: number = await getQuote(from_coin, to_coin);
        let converted_cash = cash * quote;

        this.deposite(converted_cash, to_coin);
    }

my unitary test:
describe("testing user methods", ()=>{
    const user = new User({cash: {"BRL": 100, "USD": 0}});
    it("exchange should work", ()=>{
        let value = 100;
        let from_coin = "BRL";
        let to_coin = "USD";

        user.exchange(value,from_coin,to_coin);
        expect(user.cash["USD"]).toBe(19.2);
    })
});

i tried to mock "axios" but it always returns undefined, i don't have idea what to do;
Answer: In this unit test, your concern is with testing the exchange function. So you should just mock getQuote itself to return the values you want and forget about Axios here.
In a separate test for getQuote, you can deal with mocking axios. How do I test axios in Jest?