Export rendered image corners coordinates

Question: I'd like to know if there's a simple way to get the 3D coordinates of the 4 corners of the active camera: the goal is to export a text file with the rendered image with these coordinates in order to be able to insert the image in a CAD software like autoCAD with the correct orientation and scale, as with a Geotiff image for example.
This should be possible with a python script but the most difficult for me is to get the 3D coordinates of the corners of the image...
Thanks a lot !
Answer: This is how to get camera corners 3D positions:
<code>import bpy

cam = bpy.context.scene.camera
frame_local = cam.data.view_frame(bpy.context.scene)

# Its in local space so transform to global
frame_global = [cam.matrix_world * corner for corner in frame_local]

# Output to System console
locations = ["TopRight   ", "BottomRight", "BottomLeft ", "TopLeft    "]
for location, corner in zip(locations, frame_global):
    print("corner {0}: {1}".format(location, corner))
</code>
Here you can find more that might interest you:
Casting rays into the scene for each pixel


Effective Strategies for writing papers and be more productive?

Question: Have you found any effective strategies for writing papers which you apply every time? Do you have a system as to how you work? What things have worked for you, what things did not?
If you have any tips on how I could become more productive and produce better papers faster, that would be welcome.
I think I am lacking some structure, and sometimes I am finding it difficult to put it all together, and I am wondering how other people do this.
Comment: There is a book called "How to Write a Lot" by Silvia, maybe give it a try?
Comment: I let my colleagues write all the sections I don't like writing ;-)
Answer: For any written work writing an outline is very useful. Write down all the chapters, sections and subsections and in them gather bullet points of the content und key messages, e.g. like this:
<code>Introduction

1. Literature review
2. Scope of work
3. Importance in scientific context

Methods

1. Some experimental methods

Results

1. Some data
</code>
and so on and so forth. The more specific you are, the better. Write down any idea you have now, it might be gone later. If you think of a sentence that sounds good to you, but is somewhere in the middle of your paper, write it down! It can be the seed for a much longer paragraph
I usually like to get literature review out of the way first, because it is the most tedious. Gather the sources you want to cite and construct a nice introduction around them.
From here on it is just writing, no way around it. Personally, I write rough drafts of every section and come back to it later in an iterative process. Some people may like to perfect one section first before going to the other.
If you have trouble concentrating in front of the screen, get up and write somewhere else using pen and paper. Print your rough drafts and write your corrections on them. I am usually more focussed when reading on paper.

I hope some of these tips help. This is not only restricted to papers, but applies basically to any scientific work, theses, reports, etc.


Copy an attribute from one polygon shapefile to another with ArcGIS

Question: I'm very new to GIS, and have been toying with something that intuitively seems simple, but I can't make it work. I have an ArcView license (small municipal government).
I have a parcel polygon shapefile and a building polygon shapefile. I'm trying to copy parcel ID numbers to the building shapefile. The buildings are all wholly contained within the parcels. I cannot seem to find a way to make this work.
Once I know how to do this (which I'm assuming will be easy and obvious once I see it), I will try to do the same for the driveway shapefile, which aren't always completely contained within the parcels.
My end goal is to come up with the area that is neither driveway nor building for about 8000 parcels.
Comment: Actually you don't need to do any attribute joins or copying to accomplish your end goal, you just need to cut the buildings and driveways out of the parcel layer. With a higher license level you'd just need the Erase tool, but with only basic you have to use a somewhat more convoluted solution. Take a look at http://gis.stackexchange.com/questions/103746/ for several possible solutions.
Answer: The tool you are searching for is "spatial join". You can search the toolboxes for it. Use the buildings as target, parcels as join feature.
After that you get a "copy" of your buildings FC. In the attribute table you now will find the parcel numbers for each building. Be carefull with that, if all buildings were completly in the parcels you don't get a problem, if they were not, you have to modify your spatial join (for example you can modify it under "Field Map of Join Features").
You can reach your "end goal" faster, if you use "select by location". Set "select features from" to your parcels and under "source layer" first select your buildings. Click on "apply". Then set "selection method" to "add to the currently selected features in" and set "source layer" to your driveway. Click on"apply" again (Keep in mind, that all features are selectet which intersect with the source layers; you can modify your select by location unter "spatial selection method".). Afer that you have a selection of all parcels with buildings or driveways. Go to the attribute table and click "switch selection" and you have all features without buildings or driveways.


QField Cloud - some layers remain read-only despite different configuration in QGIS

Question: I am working with QGIS and QField Cloud for a while now and despite having to regularly solve sync issues, I'm quite happy with QFieldCloud for my purposes (collecting data in the field).
But now I encountered a sync problem for which I can't find any solution despite having tried every possible sync setting in QGIS and QField and searched the entire internet:
Every time I create a new layer (e.g. a vector layer) and sync it to QFieldCloud, the layer is marked as "read-only" after updating the app.
The layer is stored in the usual QField Cloud folder on my desktop computer where all other editable layers are stored, too. In Project Properties - Data Sources, all layers are set as "Identifiable" and "Searchable", no layer is set as "Read-only". The layers I want to edit while in the field are set to "Offline Editing" in the QField Properties - Action tab.
In order to identify the error, I configured older layers as "Read-only" - after syncing, they were correctly marked as "Read-only" in the app. Switching this setting back also worked. I also recreated several new layers, reinstalled the QField app and synced the entire project again, but the problem keeps persisting: Newly added layers remain read-only despite configured differently.
Any ideas on what is wrong?
I am using QGIS LTR version 3.28.9 and QField 2.8.3
Answer: I encountered the same thing and discovered that the problem was the file type : new shapefile layers showed as "read only" when uploaded in to QField. Solved the problem by adding new Geopackage layers instead of shapefiles.


Getting QGIS / Processing revision number from PyQGIS?

Question: In QGIS, certain processing algorithms change between revision (in my case the merge function between version 2.14.1 and 2.14.7).
How can I access this information from PyQGIS, in order to make a plugin work on both versions?
Answer: Global variables can be used to find out QGIS version. A list of all global variables can be obtained via
QgsExpressionContextUtils.globalScope().variableNames()
[u'qgis_version_no', u'user_account_name', u'qgis_platform', u'qgis_os_name', u'qgis_release_name', u'fw_path', u'qgis_version', u'user_full_name']

and the value of a certain variable, say qgis_version by
QgsExpressionContextUtils.globalScope().variable('qgis_version')
u'2.14.12-Essen'

In some cases it might be helpful to obtain plugin versions as well.
In order to get a list of available plugins, on the python console type
qgis.utils.available_plugins

The version of a distinct plugin can be found out with
qgis.utils.pluginMetadata('thePluginName', 'version')

Answer: In case of changed algorithms from one to another version, one has to keep track on it by
>>> import processing
>>> processing.alglist()
D-Infinity Avalanche Runout-------------------------->taudem:dinfinityavalancherunout
D-Infinity Concentration Limited Accumulation-------->taudem:dinfinityconcentrationlimitedaccumulation
D-Infinity Contributing Area------------------------->taudem:dinfinitycontributingarea
D-Infinity Decaying Accumulation--------------------->taudem:dinfinitydecayingaccumulation

[...]
Then e.g. in case of changed names, one could create a dictionary like
alg_dict = {u'2.14.12-Essen':'qgis:algname_old', u'2.14.15-Essen':'qgis:algname_new'}

if applies.
And with the above answer, you could execute your algorithm depending on the version like
>>> import processing
>>> version = QgsExpressionContextUtils.globalScope().variable('qgis_version')
>>> processing.runalg(alg_dict[version], parameter1, parameter2, ...)


How to crop a round image with transparent background?

Question: I am currently working on a site. I want to create custom radio buttons. The background of the website is an image. So I want the radio button to seamlessly integrate with this background image. I have created the radio button and every time I crop it on paint.net, it comes out with a square black background. The image is saved as a GIF. How can I remove the black background?
Answer: Not sure what is your level of experience or which software is available at your disposal. But a fast answer would be to use a format hat supports transparency.
So you make sure the area around the circle is transparent then export your image as a PNG 24bit with transparency.
It could be done by Photoshop easily not sure how to do it with paint.net.
Let me know
Comment: Thanks. Not so sharp in Photoshop - I use Paint.net... But then also not so sharp in that too. Will give it a go a try to pick up some Photoshop skills. Thanks!
Comment: You can use the save as button and select PNG.


PowerApps :- Failed to load resource

Question: Failed to load resource: the server responded with a status of 401 (The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'Bearer error=access_denied, error_description=Authentication fail. Ticket id xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, redirect_uri=https%3a%2f%2flogin.windows.net%2fcommon%2fwsfed, realm=Microsoft.CRM'.)
Comment: Please provide some context for the issue you're facing, including the steps to reproduce it.
Answer: If you've added sample app and it has Office365 Users or similar connector - just try re-create the datasource with the same name and it will fix the issue.

PowerApps :- Failed to load resource


Make top of type sit on path - illustrator

Question: Im trying to get type to sit on a path, so far ive been able to get it to work but when i try and get the type to sit the right way round (ie. not upside down) it sits on the inside of the path, which is on the wrong side of the circle (as the first image below).
I could align the circle by eye, but im sure there must be an easier way.
Is there a way to get the top of the type to site on the path as the sketch (second image below) ?
Ive also attached an .ai file if any one wants to play around with it. - https://www.dropbox.com/s/ngvexixdckftkpt/type-on-path.ai
Answer:
Select the Path with the type on it.
Choose Type > Type on a Path > Type on a Path Options
Check the Flip box
Set the drop down for Align to Path to Ascender

Personally, if creating the circular badge style with type arching over the top and bottom, I prefer to set both type blocks to align to Center in the Type On a Path options. In this case, the only difference between the two type paths is checking the Flip box. It does create the need to possibly adjust the type paths to be a bit larger.
Answer: At least as long as all your characters are roughly the same height, you can reduce their baseline with the advanced options of the character panel:

This way, the characters will sink below the path you specified. It won't align the tops of lowercase and uppercase, though -- you'll have to set the baseline shift of those characters by hand one by one to achieve the same effect.


HttpWebRequest not returning, connection closing

Question: I have a web application that is polling a web service on another server. The server is located on the same network, and is referenced by an internal IP, running on port 8080.
Every 15 secs, a request is sent out, which receives an xml response with job information.  95% of the time, this works well, however at random times, the request to the server is null, and reports a "response forcibly closed by remote host."
Researching this issue, others have set KeepAlive = false. This has not solved the issue. The web server is running .NET 3.5 SP1.
Uri serverPath = new Uri(_Url);

// create the request and set the login credentials
_Req = (HttpWebRequest)WebRequest.Create(serverPath);
_Req.KeepAlive = false;
_Req.Credentials = new NetworkCredential(username, password);
_Req.Method = this._Method;

Call to the response:
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
_ResponseStream = response.GetResponseStream();

The method for this is GET. I tried changing the timeout, but the default is large enough to take this into account.
The other request we perform is a POST to post data to the server, and we are getting the same issue randomly as well. There are no firewalls affecting this, and we ruled out the Virus scanner. Any ideas to help solving this is greatly appreciated!
Comment: What's the frequency of the disconnects?  Anything interesting in the server log?
Comment: Are you certain it's not the server actually closing connections on you?  It's entirely possible that it's a bug in the server and not on your client.
Answer: Are you closing the response stream and disposing of the response itself? That's the most frequent cause of "hangs" with WebRequest - there's a limit to how many connections you can open to the same machine at the same time. The GC will finalize the connections eventually, but if you dispose them properly it's not a problem.
Answer: I wouldn't rule out network issues as a possible reason for problems.  Have you run a ping to your server to see if you get dropped packets that correspond to the same times as your failed requests?
Answer: Set the timeout property of FtpWebRequest object to maximum i tried it with 4 GB File and it's working great.


In the VAE, why is $z \sim \mathcal{N}(\mu, \sigma^2)$ equivalent to $z = \mu + \sigma \odot \epsilon$?

Question: In the reparameterization trick of a Variational Autoencoder (VAE), instead of sampling noise $z$ from $z \sim \mathcal{N}(\mu, \sigma^2)$, we can use a different method: $z = \mu + \sigma \odot \epsilon$, where $\epsilon \sim \mathcal{N}(0,1)$. I'm having trouble understanding why these two methods are equivalent ?
Comment: Note that $z$ is not noise in the same way that $\epsilon$ is, $z$ here is the latent variable/sample, which is part of the generative process considered in the VAE.
Comment: @nbro, So a latent variable is different from noise ? I thought they are the same. Is it accurate to say that a latent variable $z$ depends on the input $x$, while noise $\epsilon$ does not depend on anything ? Am I correct ?
Answer: I'll attempt a less formal explanation.
The distribution $\mathcal{N}(\mu, \sigma)$ represents a normal distribution with mean $\mu$ and standard deviation $\sigma$. When we sample from this distribution, we obtain a value $z$.
Now, consider the expression $z = \mu + \sigma \odot \epsilon$. Here, $\epsilon$ is a random value sampled from a standard normal distribution, which is a normal distribution with mean $0$ and standard deviation $1$. By multiplying $\epsilon$ by $\sigma$ and adding $\mu$, we effectively scale and shift the standard normal distribution to match the desired mean $\mu$ and standard deviation $\sigma$.
In essence, this expression generates values ($z$) from a normal distribution with the specified mean and standard deviation, $\mathcal{N}(\mu, \sigma)$. By incorporating $\mu$ and $\sigma$ into the sampling process, we ensure that the resulting distribution maintains the desired characteristics.
Answer: I'll give 2 cents.
The point is that Normal distribution can be shifted and rescaled:

if $X$ is a normal gaussian distribution with parameters
$\mu$ and $\sigma^2$, then this $X$ distribution can be re-scaled and shifted via the formula $Z=(X-\mu )/\sigma$ to convert it to the standard normal distribution.

Now, if you write that equation like $X=f(Z)$, you get what you are looking for...
The proof that shows it formally can be found under many other many other answers
Answer: From your unanswered comment it seems you're still not clear about the root cause and mechanism of VAE's reparameterization trick, so it would be beneficial to clarify your expressed confusion by the formal analysis of VAE reference surrogate objective function ELBO part right before the reparameterization:

A variational autoencoder is a generative model with a prior and noise distribution respectively... For example, a standard VAE task such as IMAGENET is typically assumed to have a gaussianly distributed noise; however, tasks such as binarized MNIST require a Bernoulli noise.

Maximizing the ELBO... The form given is not very convenient for maximization, but the following, equivalent form, is:
$${L_{\theta ,\phi }(x)=\mathbb {E} _{z\sim q_{\phi }(\cdot |x)}\left[\ln p_{\theta }(x|z)\right]-D_{KL}(q_{\phi }({\cdot |x})\parallel p_{\theta }(\cdot ))}$$...The distribution of ${q_{\phi }(z|x)}$ and ${p_{\theta }(z)}$ are often also chosen to be Gaussians as ${z|x\sim {\mathcal {N}}(E_{\phi }(x),\sigma _{\phi }(x)^{2}I)}$ and ${z\sim {\mathcal {N}}(0,I)}$

Therefore the prior distribution of $z$ doesn't depend on any input data $x$, and its variational posterior distribution ${q_{\phi }(z|x)}$ is the noise distribution mentioned above and optimized to be close to its prior distribution as shown in the above equivalent ELBO form via chain rule which is convenient for maximization. On the other hand from the original ELBO form $\ln p_{\theta }(x)-D_{KL}(q_{\phi }({\cdot |x})\parallel p_{\theta }({\cdot |x}))$ mentioned in my reference whose KL-Divergence term only contains conditional posterior distributions of $z$ conditioned on input data $x$, thus obviously ${q_{\phi }(z|x)}$ can no longer simply be ${\mathcal {N}}(0,I)$ but usually simply assumed to be variance-scaled and mean-shifted as ${\mathcal {N}}(\mu,\sigma^2)$.
In summary, your reparameterized $\epsilon \sim \mathcal{N}(0,1)$ is exactly same as the unconditioned $z$, and the conditioned $z|x \sim \mathcal{N}(\mu, \sigma^2)$ is simply assumed to be scaled and shifted without any necessary theoretical basis.
Finally of course with basic probability knowledge of Gaussian distribution, if you're given a random variable transformation from $\epsilon$ to $z$, you can simply substitute $z$ for the given known probability density function (PDF) of $\epsilon$ and verify $z$ obtains its desired distribution. But this pure math knowledge has nothing to do with AI here and cannot give above VAE related equivalence insight, and one can always ask why not choose another reparameterization, say as $μ^2+σ/2∗ϵ$, where $ϵ$ is chosen to be some other distribution than $\mathcal{N}(0,1)$.
Comment: I think this does not answer the question. The question is about why $z$ sampled directly from $N(\mu, \sigma)$ is equivalent to the one sampled using the re-parametrization trick, i.e. why the re-parametrization trick is not e.g. $\mu^2 + \sigma/2 * \epsilon$? This is just the usual confusing explanation of why people decide to use the re-parametrization trick, i.e. "you cannot backpropagate through the sampling operation".
Comment: @nbro thanks for your feedback! I thought the last equation in my answer would formally answer the question of statistical equivalence, now I've added further informal explanation at the end to further clarify.


Function and tangent problem

Question: I have the function: $$f(x)=x^3,\forall x\in\mathbb{R}$$
Now, I want to prove that every tangent of $C_f$ (graphical representation of $f$) in a random point $A(a,f(a))$ different from $O(0,0)$ has another same point $B(b,f(b))$ with $C_f$ which slope is $4$ times bigger than the slope of $C_f$ at $A(a,f(a))$, meaning $f'(b)=4\cdot f'(a)$. Any ideas?
Comment: Can you obtain $f'(a)$ and $f'(b)$?
Comment: no, just random points
Comment: What is your definition of a "random" point? Like an arbitrary point?
Answer: The slope of the tangent at $(a,f(a))$ is $f'(a)=3a^2$. So the equation of the tangent is $$y-a^3=3a^2(x-a)$$. Now suppose this line meets the curve again at $(b,f(b))$, with $b\neq a$, then $$\begin{align}&b^3=a^3+3a^2(b-a)\\\implies&b^3-a^3=3a^2(b-a)\\\implies&b^2+ab+a^2=3a^2\\\implies&(b-a)(b+2a)=0\\\implies&b=-2a\end{align} $$
Now the slope of the curve at $x=-2a$ is $3(-2a)^2=4\cdot f'(a)$.
Comment: @Arthur I added the details.
Answer: We have our $a$, our tangent line $C_{f, a}$, which has slope $3a^2$ and goes through $A = (a, a^3)$, which means that the equation for the line $C_{f, a}$ is
$$
y = 3a^2x -2a^3
$$
Now, assuming $a\neq 0$, we're after the second point where the tangent crosses the graph. In other words, we're after the second value of $x$, besides $a$, where the value of the function, and the $y$-coordinate of the line are the same:
$$
x^3 = 3a^2x-2a^3\\
x^3-3a^2x+2a^3 = 0
$$
Now, we know that $x = a$ is one solution to this equation. That means that since the right-hand side is $0$, the left-hand side has $x -a$ as a factor. We try to factor it out, and get
$$
x^3-3a^2x + 3a^2 = x^3-ax^2 + ax^2-3a^2x+2a^3\\
= x^2(x-a) + ax^2-3a^2x+2a^3\\
= x^2(x-a) + ax^2-a^2x - 2a^2x + 2a^3\\
= x^2(x-a) + ax(x-a)-2a^2(x-a)\\
= (x^2+ax-2a^2)(x-a)
$$
so our equation has become
$$
(x^2+ax-2a^2)(x-a) = 0
$$
Actually, since we know that the line is tangent to $f$ at $x = a$ (and not just intersecting), we can actually automatically know that the second degree factor still has $x = a$ as a solution (we can also see that $a^2+a\cdot a-2a^2 = 0$). We can factor that out again:
$$
(x^2+ax-2a^2)(x-a) = (x^2-ax+ax+ax-2a^2)(x-a)\\
= (x(x-a) + 2a(x-a))(x-a)\\
= (x+2a)(x-a)^2
$$
So our equation now says
$$
(x+2a)(x-a)^2 = 0
$$
and we can read the solutions right off: they are $x = a$ (which is the one we knew about) and $x = -2a$. Thus $B = (-2a, (-2a)^3)$ is the second point that the tangent intersects with the graph. The slope at $x = -2a$ is $3(-2a)^2 = 12a^2$, which we can see is exactly four times the slope at $A$, which was $3a^2$.
Note that we didn't really use the assumption $a \neq 0$ during our algebraic manipulations (there were no $\frac1a$ or anything). That's because if $a = 0$, then the second point of intersection is also $x = 0$ (in fact, that one point becaomses a "triple" intersection, since any tangent is a "double intersection" already, which you can see from the factor $x-a$ appearing twice in the factored expression). The slope there is $0$, and $4\cdot 0$ is $0$, so the statement is is still true, in some sense.
Answer: Suppose $a,b \in \mathbb{R}$ are points so that $f'(b) = 4f'(a)$, then
$$3b^2 = 12a^2 \implies b = \pm2a$$
$$f'(b)=f'(\pm2a)=3(4a^2)=4(3a^2)=4f'(a)$$
Comment: You've confirmed that if $f'(b) = 4f'(a)$, then $b = \pm 2a$ and $f'(b) = 4f'(a)$? How does this answer the question? How do you know that this is the point that the tangent line intersects? (By the way, it's probably a typo: your last $f'(a)$ should be $4f'(a)$)
Comment: @Arthur I didn't read the question carefully enough to interpret it in that way, sorry you're right

Function and tangent problem


How to mute laptop speakers independent from headphones Windows 10

Question: I have a work laptop with Windows 10 x64 Enterprise installed on it.  Previously it had Windows 7 x64 Ultimate.  I used to be able to control the headphone volume independent of the speaker volume.  I generally have the speakers muted but the headphones unmuted.  I cannot currently do this, I can't figure out why.
Comment: Thanks for your input, but you may want to edit your question. There isn't a `Windows 10 Ultimate` edition.  It should be [Windows 10 Home, Pro, Enterprise, or Education](http://wincom.blob.core.windows.net/documents/Win10EditionsCompareTable_FINAL.pdf).  The following tutorial may help:  [How to Find Out Which Build and Version of Windows 10 You Have](https://www.howtogeek.com/236195/how-to-find-out-which-build-and-version-of-windows-10-you-have/).
Comment: Sorry, meant to say Windows 10 Enterprise
Comment: No apology necessary.  It is a relatively minor thing, and thanks for the quick follow-up!
Answer: My Windows 10 does remember the volume independently with headphones plugged or unplugged, but not the mute state.
When I want to use the speakers, I put some volume (headphones unplugged), either using the systray volume control or the keyboard volume keys.
Then to mute the speakers back, I do the following, headphones unplugged:

Starting situation:

Drag the volume to zero using the systray control; on reaching zero, it mutes by itself (a cross appears on the volume control)

Click the cross, so that the volume of the speakers is set to zero, unmuted. This is important, because otherwise if I use the headphones, then unplug them, it will play on the speakers. (I assume at the volume set on the speakers before muting them.)
Comment: Ahhhhh...  so instead of muting, set the volume to zero.
Comment: This approach seems to work when my system isn't showing separate controls for speakers and headphones which it's doing right now.  Looks like I need another reboot.
Answer: If this problem persists after rebooting, try the following solution (worked for me on an up-to-date WIN10 Pro):

Find the good old "Control Panel"
Go to "Hardware and Sound"
Open the "Realtek HD Audio Manager"
Click on "Device Advance Settings" in the top right corner
Select "Multi-stream mode" instead of "Classic mode".

That is the trick! The main job is done.
Now right-click on the volume control in the task bar, go to "Playback devices", make sure (if necessary) that all disabled and disconnected devices are shown -
 check by right-clicking - and then you should see the headphones separated from the speakers. Enjoy!
Comment: This provides a deterministic solution. Others depend a lot on fishy steps and get flushed after rebooting.
Comment: @Facebook Can you download and install it?
Comment: None of the other answers worked for me but this one worked perfectly. Before I only had one playback device listed in my volume control, called Speaker/HP. Now I have a dropdown with a second option called Realtek HD Audio 2nd output which controls my headphones only. Thanks!
Comment: This is exactly what I was looking for. Thank you for the answer @Pankrat
Comment: what realtek audio manager version do you have?
Answer: In some cases, the Realtek driver may not provide options to disable "Multi-stream mode" (I am using HP laptop and the software called DTS Audio Control Panel does not)
You can change the audio driver to Microsoft's and it will allow the computer to remember volume for speaker/headphone separately

To change driver, open Device Manager, right click on your audio device, click update device->Browse my computer->Let me pick from a list->choose "High Definition Audio Device". You may need to reboot to apply this change.
Answer: I rebooted my computer and the Playback settings showed a separate controls for headphones and speakers now.

I went to the settings for the speakers and muted them:

Here you can see my headphones aren't muted:

It works as expected when I plug in my headphones my sound unmutes and it mutes again when I unplug them.
Comment: Glad to hear that you resolved the problem!  Just out of curiosity, during your initial troubleshooting procedures you hadn't already tried rebooting the computer?
Answer: i tried every step but didn't work for me. I use Windows 7.
My solution was:
1st - plug the headphone
2nd - choose the volume you want
3rd - in the volume control, click to mute
It disabled the speaker but the headphone continued in the volume i chose.
I hope it helps! ;)
Answer: Version

Open the "Realtek HD Audio Manager"
Click on "Device Advance Settings" in the top right corner
Choose the second option

Then Use Audio Switcher to quickly change playback devices using hotkeys


Real-time wmv video encoding in C#

Question: How to encode video on the fly and send it trough the network from C#?
Can't find a suitable library. I need to encode in WMV and don't mind if the actual encoding is made in C++ as long as the library has a .NET assembly available.
Thanks
Answer: I'm aware of ffmpeg, but it is native C code only.  If you're ok with interoperability this may be your ticket.
Edit: It turns out someone already wrapped this in a .NET assembly.  It's called FFlib.NET.
Answer: I use the Windows Media Format SDK, although I admit I use it directly in C++ native code. I believe it can be called from managed code.
This is now included as part of the Windows SDK here:
http://msdn.microsoft.com/en-us/windows/bb190307.aspx
(or you can download it separately - see the list in the left-hand panel)
Be warned, it is a fair bit to get your head around. However, there are sample code resources which should assist.
Answer: Depending on what you are encoding (size, framerate, hardware, etc) real-time encoding may not even be possible.  Video encoding is VERY CPU intensive.

Real-time wmv video encoding in C#


Moving photos into folders on iphone 5s

Question: How do I move photos from camera roll or My photo stream into other albums or folders in the iphone 5s? I'm using iOS 7.
Comment: What app do you want to use to organize photos into albums? iPhoto for iOS? Something else?
Answer: in ios7:

go to camera roll.
in top right, choose 'select' select the photos
you want to move by clicking them one after another.
when done go to the bottom and click 'add to' then create a new album in bottom of
list and they will be added.
Answer: There's meanwhile the iOS app Utiful for moving photos into folders. Utiful is a complementary photo library, so you can freely move photos between the Camera Roll and the Utiful folders. So, unlike the Photos app than only duplicates photos into albums, Utiful makes it finally possible to physically MOVE photos out of the Camera Roll.
It's available both for iPhone and iPad, here's the link to the App Store: https://itunes.apple.com/us/app/utiful-divide-rule-your-photo/id1034958660?ls=1&mt=8

Moving photos into folders on iphone 5s


After URL redirection, url not displaying new address when clicking on links

Question: I've got this website, http://www.manndirectory.com, it's a Joomla CMS with the SOBI2 business index installed. I've set it up so that their can be different entries based on their building location. SEF is turned on for both Joomla and SOBI2.
I've set up 301 redirects so that if you type in www(dot)manndirectory(dot)com/1407 or www(dot)manndirectory(dot)com/1500, it will take you to a homepage with info for that building.
That works fine but clicking on any link will not change the URL in the address bar.
Here is that code in the htaccess file
Redirect 301 /fashion_directory/1407 http://www(dot)manndirectory(dot)com/index.php?building=1407
Redirect 301 /fashion_directory/1500 http://www(dot)manndirectory(dot)com/index.php?building=1500
I'd rather use URL rewriting than redirection. It's just a temporary solution implemented.
I'd like this URL:
http://www(dot)manndirectory(dot)com/index.php?building=1407
to display as:
http://www(dot)manndirectory(dot)com/1407
And I'd like all subpages to append after the 1407 (ex http://www(dot)manndirectory(dot)com/1407/a/ or http://www(dot)manndirectory(dot)com/1407/activewear/vestiti-fini.html
Can anyone shed some light on this. I realize it is an indepth question to a very intensive problem. But I'm at a bit of a loss.
BELOW IS THE HTACCESS FILE I AM USING:
<code>##
# @version $Id: htaccess.txt 14401 2010-01-26 14:10:00Z louis $
# @package Joomla
# @copyright Copyright (C) 2005 - 2010 Open Source Matters. All rights reserved.
# Joomla! is Free Software
##

#####################################################
#  READ THIS COMPLETELY IF YOU CHOOSE TO USE THIS FILE
#
# The line just below this section: 'Options +FollowSymLinks' may cause problems
# with some server configurations.  It is required for use of mod_rewrite, but may already
# be set by your server administrator in a way that dissallows changing it in
# your .htaccess file.  If using it causes your server to error out, comment it out (add # to
# beginning of line), reload your site in your browser and test your sef url's.  If they work,
# it has been set by your server administrator and you do not need it set here.
#
#####################################################

##  Can be commented out if causes errors, see notes above.
Options +FollowSymLinks

#
#  mod_rewrite in use

RewriteEngine On
# RewriteRule ^/1407$ /tmp

########## Begin - Rewrite rules to block out some common exploits
## If you experience problems on your site block out the operations listed below
## This attempts to block the most common type of exploit `attempts` to Joomla!
#
## Deny access to extension xml files (uncomment out to activate)
#<Files ~ "\.xml$">
#Order allow,deny
#Deny from all
#Satisfy all
#</Files>
## End of deny access to extension xml files
RewriteCond %{QUERY_STRING} mosConfig_[a-zA-Z_]{1,21}(=|\%3D) [OR]
# Block out any script trying to base64_encode crap to send via URL
RewriteCond %{QUERY_STRING} base64_encode.*\(.*\) [OR]
# Block out any script that includes a <script> tag in URL
RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]
# Block out any script trying to set a PHP GLOBALS variable via URL
RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
# Block out any script trying to modify a _REQUEST variable via URL
RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})
# Send all blocked request to homepage with 403 Forbidden error!
RewriteRule ^(.*)$ index.php [F,L]
#
########## End - Rewrite rules to block out some common exploits

#  Uncomment following line if your webserver's URL
#  is not directly related to physical file paths.
#  Update Your Joomla! Directory (just / for root)

# RewriteBase /

########## Begin - Joomla! core SEF Section
#
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/index.php
RewriteCond %{REQUEST_URI} (/|\.php|\.html|\.htm|\.feed|\.pdf|\.raw|/[^.]*)$  [NC]
RewriteRule (.*) index.php
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
#
########## End - Joomla! core SEF Section

Redirect 301 /fashion_directory/1407 http://www.manndirectory.com/index.php?building=1407

#RewriteRule index/building/(.*)/ index.php?building=$1
#RewriteRule index/building/(.*) index.php?building=$1
</code>
Comment: I would suggest stripping out commented code from above file and keep only relevant lines above so you can have better chances of getting answers.
Answer: If you want new URLs you must link to those new URLs from the pages of your site.
URLs are defined in the links that the user clicks on.
Mod_rewrite cannot change the links on the pages of a site. Instead it reacts to a URL request coming from the browser after the link is clicked.
Your .htaccess file is an old version. There were many changes recently made. These changes appeared in the Joomal 1.5.23 and 1.6.2 versions of the file.


Load 1000 record to UITableView with Paging

Question: How do I load 1000 record to UITableView with Paging and load on scrolling ?
Comment: Why do you want to page the content? How are you getting the content / how is it stored?
Answer: Paging in tables is something tricky in iOS.
First of all decide how many rows do you want to display in one page.
According to that load every records when you travel through paging. This will help to work better execution of application.
I recommend you to fist create a UITableView in UIView.
Then add two button at the top of tableview. At first show 1-10 records.
When you click next button show records like 10 to 20 in table view.
and when you click previous butoon show records from 1-10.
Here you have take a variable which counts the no of records displayed.
Hope it will help you.


How to declare a variable of a type that is defined in a DLL or shared library?

Question: I want to define a instance of some structure or variable type that is defined in a DLL to send it to a function using 'ctypes'. I know I can define similar variable/structure types in python/ctypes and then send them but it takes a lot of time to define all types in my code. is there any way to just declare variables of inside DLL types just like c_int or c_char_p in ctypes?
Answer: Which DLL do you use ?
For the winapi.dll, ctypes provides also some useful structures like HWND, RECT, MSG,...
See ctypes.wintypes for more info.
You can also check for ctypeslib which parse a C file for structure and data types.
In my experience, I hardly write down more than a few C structures when calling a dll from python script/program, so it is not an issue. If you have to use a lot of in-DLL structures, you may want to use SWIG instead.
Comment: wpcap.dll is what i want to use.
Comment: have you tried [winpcapy](http://code.google.com/p/winpcapy/) ? There is someone who has your done what you want.


Combining two separate confusion matrix results from two seperate machine learning model to overall increase the True Positive accuracy

Question: What are the steps involved if it is possible to add two confusion matrix results together to get a better final prediction. we have calculated two confusion matrixs as follows from naive bayes and the decision tree True positive totals and lessen the False negatives.
Answer: There's no way to combine two models from their confusion matrices. The only thing  which can be done at this level is to select the best model as the final model.
Combining models is possible at the level of individual predictions. This is called ensemble learning. The most basic method is to assign the majority label using an odd number of models. For example if three models predict 1, 0 and 1 then we select 1 because this answer has more "votes". There are also more complex methods.
Note that the classes in your data are not balanced, class 1 has 35% of the instances. It would be better to use precision/recall/f-score rather than accuracy as a performance measure.


How do I get wires in fallout 4 to connect them to my generators

Question: I am trying to obtain electrical wires to connect to my generators, but I can't figure out how. How do I connect wires to generators in Fallout 4?
Comment: Reflagging this question for opening. As OP at the original question states, using a lightbulb is very different to using standard electronics. While the answer is still there, theres a lot of misdirection in the extra steps, and the question is not the same.
Answer: You don't need to construct wires. Just do the following:
In workshop mode, select the generator (it goes green)
Look at the available commands - one will be "attach wire" - select it
Select the target item (radio transmitter etc)
Press the command for attach
This should complete the action
Comment: But you DO need copper to make the attachment.
Answer: Creating Wires
There's no "wire" object to select from the build menus in the workshop.
Instead, you get close enough to one of the objects you want to connect to interact with it (in workshop mode). You should see an option to "Attach Wire", and the corresponding mapped button. It's Y on the Xbox. Once you've attached the wire to one object, move over to the other object and attach the wire to it using the same button. The option to do so should show up as you hover over the second object. On a large object, you may have to hunt around a little bit to find the right spot to connect to it.
You get experience for creating wires.
Wires have a maximum length. If the two objects are too far apart, you will not be able to connect them. While you are attempting to connect the wire to the second object, you will see a green or red wire hovering in the air. If it's red, that's too far. I'm not certain if there's an absolute maximum length, but if the wire is stretched so far that the lowest part hits the ground, that's too far.
If the two things you want to connect are too far apart, you can build a connector in between and use two wires with the connector in the middle.
To maximize the distance you get out of connectors, you can build the connector right next to the first object, and then move it to the maximum distance afterward.
Materials
You need copper to make wires, even though it does not explicitly tell you this. The copper will not be consumed until you attach the wire to the second object. I don't believe you get any scrap back if you destroy a wire or the object that it's hooked to.
Moving Wires
If you try to move an object with a wire connected to it, the object will turn red if the wire is either stretched too far or intersects with another object.
You can select and move the individual wires as well. Grab the end, and attach it to something else. The same issues of length and and not intersecting with other objects apply here as well.
Answer: You can not actually build a wire. What you have to do, for example, in the mission where you have to clear the starlight drive, for Preston, walk up to the beacon and make sure you have a generator. Walk up to the beacon and press the interaction button and then bring the wire to the generator and press triangle.


SQL-UNION of two SELECT of different column number yields null value

Question: So I am currently working with the EVE Static Database Export, and have run into a snag when trying to report a list of values that I need for the rest of my program.  I am currently trying to get the typeID, name, waste, and quantity required for a blueprint using the following:
SELECT typeid,name,waste,greatest(0,sum(quantity)) quantity FROM (
    SELECT invTypes.typeid typeid,invTypes.typeName name,null AS waste,quantity
    FROM invTypes,invTypeMaterials
    WHERE invTypeMaterials.materialTypeID=invTypes.typeID
    and invTypeMaterials.TypeID=@paramID
  UNION
    SELECT invTypes.typeid typeid,invTypes.typeName name,invBlueprintTypes.wasteFactor
    waste, invTypeMaterials.quantity*r.quantity*-1 quantity
    FROM invTypes,invTypeMaterials,ramTypeRequirements r,invBlueprintTypes
    WHERE invTypeMaterials.materialTypeID=invTypes.typeID
    and invTypeMaterials.TypeID =r.requiredTypeID
    and r.typeID = invBlueprintTypes.blueprintTypeID and r.activityID = 1
    and invBlueprintTypes.productTypeID=@paramID and r.recycle=1
) t GROUP BY typeid,name

Now, this SQL was adapted from a previous set of code that did not return the waste value.  wasteFactor is stored inside of the invBlueprintTypes table of the database.  Whenever I run my program and use this function (I have a separate set of code that loads the values into a C# List array, and currently just ignore acquisition of the "name" value) waste always comes back as a null value.  I am assuming this is because I am doing "null AS waste", but I am unaware as to how merge the two SELECT functions without this, as the first SELECT only originally had 3 values selected for.  I'd greatly appreciate it if anyone had an idea as how I should go about adjusting my code, as I'm fairly new to SQL, and this is a bit beyond my scope of knowledge.  Thanks!
Answer: SELECT typeid,name,max(waste),greatest(0,sum(quantity)) quantity FROM (  ....

Answer: Instead of using (Union) replace it by (Union All)
Comment: Adding a union all would have multiple records, that is not ideal mate.


Component selection PCA

Question: I have just started learning about machine learning algorithms. My senior at work tasked me to learn about dimensionality reduction using principle component analysis. In that he said that the number of components used to redefine the larger dimension raw data can be selected by calculating the reduction in eigen values of the components(slope between the 1st PCA and 2nd PCA,2nd PCA and 3rd PCA and so on) and using a particular threshold. He wants me to find the optimal threshold. I searched online but there was no references about this particular method of component selection. I found other methods like scree plot, cumulative variance, eigen one threshold etc,. Does anyone know anything about this ? Please help.
Answer: I reckon that you haven't done your homework carefully.
The criterion for component extraction is well written in many papers. A popular rule of thumb is selecting eigenvalues larger than 1. Besides, there are also criteria based on boostrapping and cross-validation. You can read in more detail in (Wold, Esbensen, & Geladi, 1987) and cited papers.
References
Wold, S., Esbensen, K., & Geladi, P. (1987). Principal Component Analysis. Chemometrics and Intelligent Laboratory Systems, 2(1-3), 37–52. doi:10. 1016/0169-7439(87)80084-9
Answer: In fact you are right being confused - there is no such thing as a generally optimal threshold. All available criteria are basically arbitrary rules of thumb given to people who need a formal rule. Obviously if you have nothing else to go by, you can use one of them, see the answer by little_monster.
In fact there are many situations in which how many PCs to choose is very ambiguous. What is even meant by "optimality" depends on what the PCs are used for. For example, if you use PCs for principal component regression, you can use things such as cross-validation to choose the number of PCs that is best at predicting the response variable. But in general it's always a trade-off between low dimensionality and explained variance, and what is more important to you or how many more PCs you accept for explaining what higher percentage of the variance cannot in general be "optimally" decided.

Component selection PCA


node js app issues after AWS Instance snapshot

Question: I had a node.js app with nginx running totally fine on a domain i purchased. It was run on an ubuntu server and all was well. I accidentally clicked "create image" on the aws site and ever since then the site doesn't work. The local ip address through port 3000 is working as expected, but the domain is not. It is loading the first html file but cannot GET the stylesheets or javascripts that go with it and none of the css or javascript files are being loaded, rather they are all returning 404. I uninstalled/reinstalled nginx and such but have not had any luck. any ideas? I don't want to change any code or such if possible, as it was working TOTALLY as expected/desired before this. I would like to express again that literally nothing other than clicking one button on aws has caused this issue
here is a config file for nginx
#
server {
listen 80;
listen [::]:80;
server_name example.org www.example.org;
return 301 https://$server_name$request_uri;
}

server {
listen 443 ssl http2 default_server;
listen [::]:443 ssl http2 default_server;
server_name example.org www.example.org;

location / {
proxy_pass http://localhost:3000/login.html;
}
    ssl_certificate /etc/letsencrypt/live/example.org/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.org/privkey.pem; # managed by Certbot
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_ciphers EECDH+CHACHA20:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5;

ssl_session_cache shared:SSL:5m;
ssl_session_timeout 1h;
add_header Strict-Transport-Security "max-age=15768000" always;

}
#

also, here is what was working for my app.js
this may be a good time to ask if i'm doing everything ok, im sure it can be improved as I am still just learning
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser')
var logger = require('morgan');
var User = require("./models/user");
var db = require('./db.js');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var devicesRouter = require('./routes/devices')

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.json());
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/devices', devicesRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

Here is what the server responds when I use it (the first one is me on local host port 3000 and the second one is where it gets all funky, it looks like its trying to access /login.htmlstylesheets/login.css instead of /stylesheets/login/css
Comment: Tell us about the other changes you made. Show us the nginx configuration and the error log entries.
Comment: Michael, i have attempted to clear up any issues you may have had. what bothers me is that i literally did not change anything other than clicking one button accidentally on a web interface
Comment: The "create snapshot" reboots your server, so if you'd set up a Node process to run manually instead of having it fire up as a service, that'd probably cause issues.
Answer: Well, the problem is pretty obvious here:
location / {
proxy_pass http://localhost:3000/login.html;
}

So every time nginx passes a request up to your Node app, /login.html is prepended to the URI path.
My guess is you or someone else made this change days, weeks, or even months ago but never reloaded nginx with it, and it was finally loaded when your server was restarted.
You should instead be passing to http://127.0.0.1:3000, with no trailing path.
location / {
proxy_pass http://localhost:3000;
}

You also should set the document root to the directory containing the root of your static files, and use a try_files to ensure that nginx serves the static files instead of Node. A better configuration would look like:
server {
   ....
   root /srv/www/myapp/public;
   location / {
       try_files $uri @node;
   }

   location @node {
       proxy_pass http://127.0.0.1:3000;
   }
}

Comment: this fixed it. I appreciate the help greatly Michael, it saved me lots of hours of frustration.
Comment: @helpimlost If it solved your problem, you can mark it as solved by clicking the outline of the tick mark so that it turns solid green. Welcome to [sf]!


Thumbing with both hands

Question: Can we use both the hands while thumbing the coins in carrom board or are we limited to single hand only.
Comment: Your question is very unclear, and also appears to be two questions.  Could you please clarify.
Comment: I've removed the second question. It can be asked separately.
Answer: Under IV: How to strike in the official rules

Any hand may be used in play.

Hand in this case is singular. This is somewhat clarified further down...

The elbow of the playing "hand" shall not come within the playing surface nor shall extend beyond the imaginary lines of the arrows. The "hand" may, however, cross the arrow.

This indicates that there should only be one hand in use.
The rules also indicate what the other hand could be used for

While making a stroke, taking support of the Stool or Chair, Stand or Table of the C/B or keeping the legs on the rim of the stand or table by the player is not permissible. However, hands may rest on his body and legs or on the rim of the stool or chair on which he sits.

Furthermore, if you wanted to make an analogy with cue-sports, there is almost always a rule against double stroking or push strokes, as the concept of a "stroke" is one single instantaneous point of contact. Carrom's definition gives some more leeway because we're using fingers instead of cue sticks, but the concept is still the same. Using two fingers undoubtedly results in striking the striker twice.
Answer: Either hand could be used for thumbing but not both at the same time.
Ref: https://icf-media.beepworld.de/laws-of-carrom.htm
IV. HOW TO STRIKE
35) Any hand may be used in play.
Comment: Welcome to the site! When answering a question, it is a best-practice to cite (and link to) a specific source for your answer. These sources provide an authoritative reference and make it easier for the OP to select the Right answer based on objective standards, instead of what could be just a subjective opinion. I would suggest updating your answer with a link to the rules where you found this information.
Answer: You can shoot with either hand and thumbing is allowed:
https://www.quora.com/Why-is-thumbing-allowed-in-the-international-Carrom-game
Comment: Hi lhmit, and welcome to Board Games Stack Exchange. We don't generally accept link-only answers here: [you can see "your answer is in another castle" for why](https://meta.stackexchange.com/questions/225370/your-answer-is-in-another-castle-when-is-an-answer-not-an-answer). We prefer answers to include the important parts of their link, in this case, citing the rules themselves that allow this would be appropriate and the link itself isn't necessary. Pretend the link became a 404 tomorrow (it very well could): what would you include your answer to keep it relevant and reliable?

Thumbing with both hands


Using IOS Accelerate Framework for 2D Signal Processing on Non-Power-of-Two images?

Question: //EDIT...
I'm editing my question slightly to address the issue of working specifically with non-power-of-two images. I've got a basic structure that works with square grayscale images with sizes like 256x256 or 1024x1024, but can't see how to generalize to arbitrarily sized images. The fft functions seem to want you to include the log2 of the width and height, but then its unclear how to unpack the resulting data, or if the data isn't just getting scrambled. I suppose the obvious thing to do would be to center the npot image within a larger, all black image and then ignore any values in those positions when looking at the data. But wondering if there's a less awkward way to work with npot data.
//...END EDIT
I'm having a bit of trouble with the Accelerate Framework documentation. I would normally use FFTW3, but I'm having trouble getting that to compile on an actual IOS device (see this question). Can anybody point me to a super simple implementation using Accelerate that does something like the following:
1) Turns image data into an appropriate data structure that can be passed to Accelerate's FFT methods.
 In FFTW3, at its simplest, using a grayscale image, this involves placing the unsigned bytes into a "fftw_complex" array, which is simply a struct of two floats, one holding the real value and the other the imaginary (and where the imaginary is initialized to zero for each pixel).
2) Takes this data structure and performs an FFT on it.
3) Prints out the magnitude and phase.
4) Performs an IFFT on it.
5) Recreates the original image from the data resulting from the IFFT.
Although this is a very basic example, I am having trouble using the documentation from Apple's site. The SO answer by Pi here is very helpful, but I am still somewhat confused about how to use Accelerate to do this basic functionality using a grayscale (or color) 2D image.
Anyhow, any pointers or especially some simple working code that processes a 2D image would be extremely helpful!
\\\ EDIT \\\
Okay, after taking some time to dive into the documentation and some very helpful code on SO as well as on pkmital's github repo, I've got some working code that I thought I'd post since 1) it took me a while to figure it out and 2) since I have a couple of remaining questions...
Initialize FFT "plan". Assuming a square power-of-two image:
#include <Accelerate/Accelerate.h>
...
UInt32 N = log2(length*length);
UInt32 log2nr = N / 2;
UInt32 log2nc = N / 2;
UInt32 numElements = 1 << ( log2nr + log2nc );
float SCALE = 1.0/numElements;
SInt32 rowStride = 1;
SInt32 columnStride = 0;
FFTSetup setup = create_fftsetup(MAX(log2nr, log2nc), FFT_RADIX2);

Pass in a byte array for a square power-of-two grayscale image and turn it into a COMPLEX_SPLIT:
COMPLEX_SPLIT in_fft;
in_fft.realp = ( float* ) malloc ( numElements * sizeof ( float ) );
in_fft.imagp = ( float* ) malloc ( numElements * sizeof ( float ) );

for ( UInt32 i = 0; i < numElements; i++ ) {
    if (i < t->width * t->height) {
      in_fft.realp[i] = t->data[i] / 255.0;
      in_fft.imagp[i] = 0.0;
    }
}

Run the FFT on the transformed image data, then grab the magnitude and phase:
COMPLEX_SPLIT out_fft;
out_fft.realp = ( float* ) malloc ( numElements * sizeof ( float ) );
out_fft.imagp = ( float* ) malloc ( numElements * sizeof ( float ) );

fft2d_zop ( setup, &in_fft, rowStride, columnStride, &out_fft, rowStride, columnStride, log2nc, log2nr, FFT_FORWARD );

magnitude = (float *) malloc(numElements * sizeof(float));
phase = (float *) malloc(numElements * sizeof(float));

for (int i = 0; i < numElements; i++) {
   magnitude[i] = sqrt(out_fft.realp[i] * out_fft.realp[i] + out_fft.imagp[i] * out_fft.imagp[i]) ;
   phase[i] = atan2(out_fft.imagp[i],out_fft.realp[i]);
}

Now you can run an IFFT on the out_fft data to get the original image...
COMPLEX_SPLIT out_ifft;
out_ifft.realp = ( float* ) malloc ( numElements * sizeof ( float ) );
out_ifft.imagp = ( float* ) malloc ( numElements * sizeof ( float ) );
fft2d_zop (setup, &out_fft, rowStride, columnStride, &out_ifft, rowStride, columnStride, log2nc, log2nr, FFT_INVERSE);

vsmul( out_ifft.realp, 1, SCALE, out_ifft.realp, 1, numElements );
vsmul( out_ifft.imagp, 1, SCALE, out_ifft.imagp, 1, numElements );

Or you can run an IFFT on the magnitude to get an autocorrelation...
COMPLEX_SPLIT in_ifft;
in_ifft.realp = ( float* ) malloc ( numElements * sizeof ( float ) );
in_ifft.imagp = ( float* ) malloc ( numElements * sizeof ( float ) );
for (int i = 0; i < numElements; i++) {
  in_ifft.realp[i] = (magnitude[i]);
  in_ifft.imagp[i] = 0.0;
}

fft2d_zop ( setup, &in_fft, rowStride, columnStride, &out_ifft, rowStride, columnStride, log2nc, log2nr, FFT_INVERSE );

vsmul( out_ifft.realp, 1, SCALE, out_ifft.realp, 1, numElements );
vsmul( out_ifft.imagp, 1, SCALE, out_ifft.imagp, 1, numElements );

Finally, you can put the ifft results back into an image array:
for ( UInt32 i = 0; i < numElements; i++ ) {
  t->data[i] = (int) (out_ifft.realp[i] * 255.0);
}

I haven't figured out how to use the Accelerate framework to handle non-power-of-two images. If I allocate enough memory in the setup, then I can do an FFT, followed by an IFFT to get my original image. But if try to do an autocorrelation (with the magnitude of the FFT), then my image gets wonky results. I'm not sure of the best way to pad the image appropriately, so hopefully someone has an idea of how to do this. (Or share a working version of the vDSP_conv method!)
Comment: It looks like you're just doing autocorrelation here ? I thought Accelerate/vDSP already had autocorrelation functions so that you didn't have to roll your own with FFT/IFFT etc ?
Comment: Hi, the vDSP_acor doesn't seem to actually exist in the Accelerate library. vDSP_conv exists, but it's giving me strange results... perhaps I'm using it incorrectly for doing an image autocorrelation. If you (or anyone) has a working example for using vDSP_conv for autocorrelation it would be great to see it. Part of the issue is just that it is confusing as to what data in expects and outputs, etc.
Answer: I would say that in order to perform work on arbitrary image sizes, all you have to do is size your input value array appropriately to the next power of 2.
The hard part is where to put your original image data and what to fill with.  What you are really trying to do to the image or data mine from the image is crucial.
In the linked PDF below, pay particular attention to the paragraph just above 12.4.2
http://www.mathcs.org/java/programs/FFT/FFTInfo/c12-4.pdf
While the above speaks about the manipulation along 2 axes, we could potentialy perform a similar idea prior to the second dimension, and following onto the second dimension.  If Im correct, then this example could apply (and this is by no means an exact algorithm yet):
say we have an image that is 900 by 900:
first we could split the image into vertical strips of 512, 256, 128, and 4.
We would then process 4 1D FFTs for each row, one for the first 512 pixels, the next for the following 256 pixels, the next for the following 128, then the last for the remaining 4.  Since the output of the FFT is essentially popularity of frequency, then these could simply be added (from the frequency ONLY perspective, not the angular offset).
We could then push this same techniquie toward the 2nd dimension.  At this point we would have taken into consideration every input pixel without actually having to pad.
This is really just food for thought, I have not tried this myself, and indeed should research this myself.  If you are truly doing this kind of work right now, you may have more time than I at this point though.
Comment: This isn't like processing a 20 second audio signal into 5 second chunks.  It's more like processing an audio signal by splitting apart 0-10khz and 10khz-20khz.  You're getting different bands from each, so you'd be adding 2khz with 12khz, or something along those lines...
Comment: This is more of a question than anything, because I'm still developing an intuition for all of this, but doesn't the separability of FFT allow for doing strips of the image 512 at a time, etc?   I watched a vid of someone doing a 2D FFT by doing nested loops of 1D FFTs 1 row of pixels at a time.


Euclidean distance between $x\in\mathbb{R}$ and $\{x\in\mathbb{R} \mid f(x)=0\}$

Question: Is there a generic formula to calculate the distance between an arbitrary real number $x\in\mathbb{R}$ and $$\{x\in {\mathbb{R}}\mid f(x)=0\}$$ where we have little information about $f$? In fact, my primary objective is to establish an inequality between the distance above and $f(x)\cdot f(x)$. Any idea?
Comment: Thanks. No f(x)*f(x) means arithmetic multiplication.  For example f(x)=sin(x). But I would not know the exact form of f.
Comment: ok :)
so $f$ is a real-valued function, right? $f: \mathbb{R} \rightarrow \mathbb{R}$, right?
Comment: The distance between a point $a$ and a set of points $M$ is typically defined as $$d(a,M)= \min_{d \in M}(a,d)$$

Basically, you need to calculate the distance between $(x_1, 0)$ and $(x_2,f(x_2))$, which is
$$\sqrt{(x_2-x_1)^2 + (f(x_2))^2}$$
and minimise it.
Comment: I have some questions:    1. is $f(x) * f(x)$ the convolution of $f$ with itself?      2. do you know at least if $f: \mathbb{R} \rightarrow \mathbb{R}^n$? is $n=2$?
Comment: Let me see if I understand your question right. In your example: Let $f(x)=\sin(x)$ then the distance of your interest for say $x=\pi$ is the distance between $\pi \in \mathbb{R}$ and the point set $\{0,\pm \pi, \pm 2\pi, \pm 3\pi, ...\}$?
Answer: No. Consider that this problem is equivalent to finding the roots of $f$ (if you knew the distance from $x$ to the nearest root, you could check only two points to find the root).
If you know the roots and they are countable, you can of course simply sort them and quickly find the one closest to $x$.
As for finding the distance in practice, you can perform gradient descent or ascent on $f$ with a line search until you locate the root (note that you will need to look in both positive and negative directions to find the closest root -- the gradient of $f$ is not necessarily a reliable indicator of the right direction to search -- and you will need to deal with any critical point of $f$ you find along your search). Specialized algorithms can efficiently find the roots for some classes of function $f$, e.g. polynomials.
Edit: as for relating the distance to $f$, if you can bound $f'$ you can use those bounds to compute bounds on the distance, by way of the fundamental theorem of calculus. You can refine the bound by including more high-order information about $f$ at $x$.


How to detect outliers in randomForest regression models?

Question: The randomForest package in R software includes outlier function for the detection of outliers. This function uses proximity matrix or randomForest object for the outlier detection. The manual says that the type of the randomForest object can not be regression? Why is it so that this function can be used for classification models only? Is there a reasonable way to detect outliers in regression models?
Comment: Here is a method that I developed for Random Forest Regression to Detect Outliers: http://bioinformatics.oxfordjournals.org/content/early/2010/12/05/bioinformatics.btq628
Answer: Basic idea behind this outlier score is how far an object is from a centroid of its predicted class, thus it makes little sense for regression.
Yet you can still produce proximity from regression RF by putting proximity=TRUE argument to the call to randomForest and then force outlier detection on it by calling outlier(<rf object>$proximity), but this will only make assumption that all objects are from one class.
A bit less hopeless idea is to just convert regression problem to classification by splitting continuous decision into several intervals with cut or Hmisc::cut2 and doing outlier detection on this -- but I have never tried it.
Comment: Thank you for explaining that the outlier score is relative to the cluster centroids. I had impression that this was relative to other compounds. Now this restriction makes sense. I'll try to experiment with your other suggestions.


invoking jython methods from java : couldn't locate modules in import

Question: Problem statement: I'm using PySystemState to invoke my jython module in java class and execute some methods on it. Now the problem is that my jython module has some dependencies on some other jython modules located in paralled directories in the same jython project. And as a result when I invoke the target module it throws import exception saying dependent module can't be located.
Structure of my jython project:
<code>jythonproject
  -src
     -folder1<has the module which is invoked from java>
     -folder2 < it has the modules which the module inside folder1 imports with statemet "from folder2 import x"
</code>
Exception => No module named folder2
Please note that in java project I'm setting up JYTHONPATH env variable with path to both folder1 and folder2.
I'm using eclipse environment with jython 5.3.
2)
some more research : I'm using PySystemState to invoke jython modules from java. Here is the spec to load the module and class.
<code> // Constructor obtains a reference to the importer, module, and the class name
 public JythonObjectFactory(PySystemState state, Class interfaceType, String moduleName, String className) {
     this.interfaceType = interfaceType;
     PyObject importer = state.getBuiltins().__getitem__(Py.newString("__import__"));
     PyObject module = importer.__call__(Py.newString(moduleName));
     klass = module.__getattr__(className);
     System.err.println("module=" + module + ",class=" + klass);
 }
</code>
NOw it seems that I'm importing only the module in folder1 and then getting the class inside it to invoke methods. Now since this module has imports from other modules which are located in folder2 and they are not loaded in java code hence it fails to located the module.
Now the question is how should I load dependent modules in folder2 along with the module in folder1 which I need.
Guys I noticed one more thing the module in folder 2 which is imported in module which I'm invoking from java doesn't have a class in it. So module which I'm invoking from java has a class which I'm invoking and that class has dependency on a jython module which has some methods but it's not a class. By any chance is this the reason why it's not working and I'm getting an exception.
Tried few other things and here is the outcome:
Scenario 1:
       pkg1 has module1 with class1
       pkg2 has module2 with class2
And module 1 has an import => from module2 import class2
Now when I invoke class1 from java program this works fine.
Scenario2:
       pkg1 has module1 with class1
       pkg2 has module2 which has method definitions and no class
And module 1 has an import => from pkg2 import module2
Now when I invoke class1 from java program this throws me exception.
Conclusions:
1) we can't use imports from package when invoking a jython class from java.
2) we can't invoke a jython class from java which has imports from a module which doesn't have a class(just method definitions). Because jython will only allow "from pkg import " in this scenario and again we'll have problem as in point 1.
Answer: You probably need to set JYTHONPATH. See related Stackoverflow question here.
Jython does not load PYTHONPATH into sys.path
Comment: Nope that doesn't help. I tried adding path to 'folder2' in JYTHONPATH env variable however the same error


Tinymce Richtext-editor not rendering macro RTE

Question: I'm running a site with umbraco version 4.11.1 and is trying to render the info of a macro within a tinyMCE richtext-editor without any success.
In version 4.11.1 (and perhaps some other versions before this) Umbraco has a button for rendering macros within tinyMCE. If you click this button it will show all the macros that you have been able to render. If I add a macro, it will render out the stuff I've entered in the macro, within an orange-dotted border, which means that the editor understands that I've added the macro.
However, after I save and publish and enter the page where I've added the macro, it doesn't render anything. I came across some posts when I googled the problem and found out that I could trace the problem using a querystring (?umbDebugShowTrace=true) and look through the HTML and see what has been rendered. I found the following HTML:
<code><?UMBRACO_MACRO macroAlias="Testmacro" />
</code>
...which should render, if you ask the people in these posts.
If anyone had this problem, or know how to solve it. Please feel free to participate.
Thanks in advance.
David
Comment: How are you rendering out the TinyMCE property? Can you show us your (I'm assuming) razor code?
Answer: Try
<code> string macro = umbraco.library.RenderMacroContent("<?UMBRACO_MACRO macroAlias=\"Testmacro\" ReusableText=\"1112\" ></?UMBRACO_MACRO>", 1112);

 string result = paragraph.Replace("<?UMBRACO_MACRO macroAlias=\"Testmacro\" ReusableText=\"1112\" />",macro);
</code>
Best regrads


Can your character gain crucial knowledge off-screen?

Question: Can your character gain crucial knowledge off-screen? Let's say your character is a young adult and doesn't know anything about geopolitics, and then there's a 2 year time skip and he's a ruler with a lot of geopolitical knowledge gained off-screen, and knows exactly the political working of a country. Is it ok to do that, or should you somehow show how he gained that knowledge or how he came to learn this? When is it a bad idea to do that?
Answer: Sure. It's a well established "trope" in much the way you describe it. There are even shorthand methods for it.
Consider the movie The Lion King. At the start, Simba is a cub with a few friends and pretty much a total lack of knowledge. Then there's a scene in the movie where we see him and his two best friends walking along. And it goes into silhouette for a while, and the outline of Simba gradually gets bigger. Then it comes back to full color again, and we've got a young-adult Simba with his two friends.
Consider the movie Contact, written by Sagan and starring Jodie Foster. We have an established thing that the young Ellie does, a thing she does with her hair while she is using her shortwave radio. Then we get a transition where the young character is doing this, and a fade out then in, and it's the adult character doing it.
Or, for a much older example, consider the New Testament. We get a few little
glimpses of Jesus's life before He is grown. His birth. A couple little incidents while He's a kid. Then He's fully grown and going around healing people and recruiting His disciples.
It's tough to make the transition interesting and not cliché. It's also possible to lose the reader. You need to have some strong indications it's the same person. Lots of little kids, after Simba was suddenly grown up, turned to their parents and said "Where's Simba?" They had grown to like this happy little cub and suddenly this adult lion is there.
You can use tricks. A couple incidents to bridge the gap can help. Maybe there's some event where he marks being part-way through the transition, a party or a ceremony or a graduation or something. Some things that don't change over the bridge might help. Maybe he has some physical appearance that stays the same. His scar from crawling through that barb-wire fence or something. Or he has mannerisms that stay the same. Some phrase he uses.
You can tie it together by having the adult character recount some formative experience or some such. They remember when they learned some important wisdom they will use now, or what they were doing the last time they referred to this book, or something like that. Or they meet somebody they were close to during the missing period and talk about a shared experience.
Answer: Probably, if you set it up properly.  If we know he's going to become a ruler, and be educated for it, it may be wise to hint that it will be a long and tedious process, and then, after, that it was a long and tedious process.
Blindsiding the reader, however, is hard to carry off properly.  Even if the character is ignorant, some foreshadowing is usually wise, down to having the character laugh off the notion that he would be ruler.
Much depends, of course, on why he is depicted before the time-skip.  Beginning the story in media res as a ruler would have many advantages, though the earlier story might be necessary.
Answer: It is a bad idea to do it cold.
What you can do, is "show" a scene in which the hero discovers an ancient book, or a mentor, or some other trove of knowledge, and begins to train.
Then timeskip over the boring "learning" part to the good parts: "Four Years Later" -- They win their first local election.
Then timeskip again; "Four Years Later", they win their first national election.
And so on. The book Roots could not have been written without huge timeskips, it covers more than a century of descendants. We see people born, and in the next chapter they are adults facing a decision.
What you try to include are the critical character-forming scenes from somebody's life. Their struggles and successes and critical life-changing or character-changing choices. The first time your leader orders soldiers to their death, or the first time they have to personally kill somebody.
Even in the first Harry Potter book, from the first chapter to the second is a timeskip of 10 years. Nothing important happened to Harry in his life before then; he was rescued as an infant, placed with his aunt and uncle, done. Skip forward 10 years, he's about to have a birthday and be whisked away by Hagrid to a new world of magic.
Only include the scenes that change your character or reveal new information about your character. Even if those scenes are years apart.
Your character starts learning. Then timeskip to when your character finishes learning or otherwise changes.


What are the chances of a star colliding with another during a galactic collision?

Question: My specific example for the question is the future collision of the galaxies Milky Way (our own galaxy) and Andromeda in a couple billion years. The star in question is obviously the sun in this case. I want to know the chances of a collision with another star and if it's significant or not.
Comment: @A.C.A.C. Why do you say might? Which bit is sufficiently uncertain to attract a qualifying word? I say the Sun will be alive when the collision takes place.
Comment: There is a whole subsection on this question on the relevant Wikipedia page. https://en.m.wikipedia.org/wiki/Andromeda–Milky_Way_collision
Comment: https://astronomy.stackexchange.com/questions/1911/what-will-happen-to-life-on-earth-when-the-andromeda-and-milky-way-galaxies-coll contains several answers which address this question.
Comment: 5.5 billion years would be to reach the end of the main sequence. More like 7.7 billion to become a white dwarf. e.g https://arxiv.org/abs/0801.4031 @A.C.A.C.
Comment: The sun might be dead by the time that happens so the specific part of that question might not be relevant. But the density of stars in a galaxy is not high in the arms where the the sun is but higher in the galactic core. The stars like the sun will very likely not collide with anything because the volume that the star actually occupy is much smaller than the space between stars in both galaxies.
Comment: I think the chance of our sun being involved in a collision is extreemly low.   That a star will hit another star during the collision, I've heard people say that won't happen, but I find it hard to believe.   But stars are spread out enough that collisions will be quite rare.  (I don't want to answer as I'm not 100% sure).   If stellar collisions are observed within galaxies, I would think they would happen, at least a few times, in a galactic merger.    https://en.wikipedia.org/wiki/Stellar_collision
Comment: @RobJeffries Wikipedia says the collision with Andromeda will happen in 4.5b years and I could have sworn that the sun was expected to be a red giant by then but it now that I read up on it it seems like the sun is expected to last >5.5b years. Originally I thought the 2 events would be sufficiently close enough that there is a high chance that the sun will be a white dwarf by then.
Answer: Let's see what we get from some back-of-the-envelope estimates.
Imagine throwing one star (e.g., the Sun) at the other galaxy. How likely is it we'll hit a star in the other galaxy? Well, it's basically proportional to how big a target each star in the other galaxy is (its cross-sectional area) compared to the size of the whole galaxy, multiplied by the total number of stars in the target galaxy.
Let's assume it's the Milky Way-Andromeda scenario, so each galaxy has about 100 billion stars, and each star is roughly the same size as the Sun (some are much larger, most are smaller). The actual target area for an individual star is a circle with twice the star's radius (we're counting one star just grazing the other as a collision). Let's also assume the stars are more or less evenly distributed in a circular disk. Since "100,000 light years" is a common (and not completely crazy) estimate of the Milky Way's size, that's a circle of radius = 50,000 light years (about $10^{16}$ meters).
So: 100 billion stars in the target galaxy, each with target radius $\sim 2 R_{\odot}$, gives us a total target area of $10^{11} \times \pi (2 R_{\odot})^{2} \approx 10^{30}$ m$^{2}$.
The area of the target galaxy is $\pi R_{gal}^{2} \approx 10^{42}$ m$^{2}$. So the chance of our Sun hitting a star in the other galaxy is $\approx 10^{30} / 10^{42} = 10^{-12}$ -- or about one in a trillion.
The odds of any star from our galaxy not hitting a star in the other galaxy would be $(1 - 10^{-12})^{10^{11}} \approx 0.90$.
So there's only about a 10% chance of one (or more) of the galaxy's 100 billion
stars hitting a star in the other galaxy. And the chances of any one particular star (like our Sun) hitting a star in the other galaxy is about one in a trillion.
Comment: It *is* true that the dense centers of the two galaxies will, if you let the whole merger play out (beyond the first collision) spiral into the common center via dynamical friction and merge, so the odds that *some* stars will collide will be higher.
Comment: Factoring in Roche limit breakups (leading to partial collisions?) and the denser center parts of the two galaxies colliding, which is expected to happen I would think the odds of collision goes up, but running the math on that gets a bit problematic for me.   Still, props on doing the math.
Comment: Well, the original question was about "collisions", so I went with that. I also neglected gravitational focussing, which increases the effective impact parameter and thus the odds of collisions. But that's still not going to get you more than one or two orders of magnitude, which means the chances go from 1 in a trillion to, say, one in 10 or 100 billion. Still utterly insignificant.
Comment: Increased central density doesn't change the base chance for a random individual star (like the Sun) to collide: sure, more stars per square meter in one part of the target galaxy, but they're in a smaller area now, so it's harder to hit the region with those stars. (The math cancels out.)


I would not like to rush to file taxes at the last moment. Does it make sense to file Form 4868?

Question: Although I have all my tax information now in one place, I would like to study itemized deductions better and make sure that I file all my taxes correctly and maximize my returns. Does it make sense to file form 4868 and seek extension to file taxes? Are there any downsides in filing taxes later with an extension?
Comment: As Alex points out, it is an extension on the filing deadline, not the payment deadline.  This is a crucial distinction, as there are potentially **two (2)** penalties (plus interest):  One for paying late and one for filing late.  I found [this page on investopedia.com](http://www.investopedia.com/articles/pf/07/taxextension.asp) useful for understanding the details.
Answer: An extension is an extension to file, not to pay.  If you expect to pay, you'll owe penalties/interest for paying late.

However, an extension of time to file
  is not an extension of time to pay.
  That means, if you owe, you should pay
  the IRS by the April 18th deadline to
  avoid penalties and interest.

Source
FYI you have until April 18th in 2011 because April 15th is a holiday which gives you an extra weekend to work on tax investigation.
Answer: @AlexB is correct.  Unfortunately, I always end up filing with a 4868 because some of the corporate deadlines for filing that I need are after 4/15.  And to be safe, I always OVERPAY my estimated taxes on 4/15 and then later either apply those overpayments to the next tax year or get a refund in October.  When I say safe, I mean pay enough such that regardless of decisions you make about more or less aggressive deductions, you wouldn't pay penalities for underpayments.  If you decide as I do, to be safe, then the disadvantage is that you are giving the goverment a loan for free, and of course, not having that excess payment to use yourself.
Comment: Then again, with savings accounts paying piddly sums like 1.1% it's not like you're going to be giving up huge amounts of money if you overpay a bit. In ~2014 or whenever the Fed actually raises rates, now...
Comment: well, it's not so much the interest you might earn, as getting your hands on the money if you needed it.  But certainly a good point.


NodeJS "No overload matches this call." error with typescript

Question: I'm trying to create NodeJS app from scratch with typescript addition... I was following some tutorial and basically did the same steps as he did yet he didn't receive this error... Did NodeJS or TypeScript get some kind of updates that are causing this error?
Problem is that I'm receiving error on index.ts file POST with getAllUsers controller and I have no clue what is it about:

No overload matches this call.   The last overload gave the following
error.
Argument of type '(req: Request, res: Response) => Promise' is not assignable to parameter of type 'Application<Record<string,
any>>'.
Type '(req: Request, res: Response<any, Record<string, any>>) => Promise' is missing the following properties from type
'Application<Record<string, any>>': init, defaultConfiguration,
engine, set, and 61 more.

Any help is welcome :)
index.ts file:
import * as functions from "firebase-functions";
import * as express from "express";
import {getAllUsers } from "./controllers/usersController";

const app = express();
app.post("/users",getAllUsers);
app.get("/", (req, res) => res.status(200).send("default route!"));

exports.app = functions.https.onRequest(app);

Controller file:
const getAllUsers = async (req: Request, res: Response) => {
  let userArray: any[] = [];

  try {
    const user = await db.collection("userInfo").get();

    if (!user.docs) {
      res.status(404).send("not found");
    } else {
      user.docs.forEach((user) =>
        userArray.push({id: user.id, user: user.data()})
      );
    }
    res.status(200).send("
some html
");
  } catch (error) {
    res.status(500).send("error.message");
  }
};

export {getAllUsers};

Comment: Maybe you have outdated `express` types? Have you `npm -i`'d the latest `express` and `@types/express` ?
Answer: I got stuck for hours for this one. I hope this helped.
Try changing the format of the code from
import {getAllUsers } from "./controllers/usersController";
&
export {getAllUsers};
to
import getAllUsers from "./controllers/usersController";
&
export default getAllUsers;
Have the same problem with importing
After changing the code


Update value of objects with lambda

Question: I have this IEnumerable of type Question.. the class Question has the properties, Question(string) and Id(int)
What I want to do is if the question of any object in the IEnumerable has a length > 25
then "Substring" it and add "..."
So my idea was something like:
ienumQuestions.Where(e=>e.Question.Length > 25).Change(e.Question=>e.Question.Substring(25)+"...");

Now im not sure if that syntax was 100% correct but I hope you get the point..
Is there wanyway to do this?.. i really dont want to create a loop for this.. since I simply dont like loops :)
Thanks in advance!
Comment: You don't like loops? How do you think IEnumerable gets implemented?
Answer: Approach with caution
You could use the renowned ForEach extension method in LINQ to iterate through each item and action it accordingly. Essentially it's the same as the Change method you described, and could look something like this:
ForEach LINQ Extension Method
public static void ForEach<TSource>(this IEnumerable<TSource> source, Action<TSource> action)
{
    foreach(TSource item in source)
    {
        action(item);
    }
}

Implementation
ienumQuestions.Where(e => e.Question.Length > 25).ForEach(e =>
{
    e.Question = e.Question.Substring(0, 25) + "...";
});

// or
ienumQuestions.ForEach(e =>
{
    if (e.Question.Length > 25)
    {
        e.Question = e.Question.Substring(0, 25) + "...";
    }
});

Argument and Extra Reading
I personally dislike the approach of using the ForEach LINQ extension to directly update the objects, I prefer to use it for reference purposes only. I would strongly recommend reading "foreach vs ForEach" before adopting it though, as essentially it goes against the principal of LINQ in the sense that it directly modifies objects within the collection, which is what LINQ was not originally intended to do.
Answer: There is no Change extension in LINQ, both IEnumerable and String are immutable (to slightly different levels) so cannot be changed.
I guess you want a truncate extension somthing like this,
IEnumerable<string> Truncate<T>(
    this IEnumerable<T> source,
    Func<T, string> stringAccessor,
    int length,
    string suffix)
{
    var strings = source.Select(stringAccesor);
    return strings.Select(s =>
        {
            if (s.Length < length)
            {
                return s;
            }

            return string.Format(
                "{0}{1}",
                s.SubString(0, length),
                suffix)
        });
}

Which you could call like this
var truncatedQuestions = ienumQuestions.Truncate(q => q.Question, 25, "...");

Update value of objects with lambda


Entering integers as bytes in serial monitor

Question: I am doing some byte manipulation in Arduino, but when I enter an integer into the serial monitor, such as 1, and my program stores it as byte incomingByte, the value stored in incomingByte is 49 and not 1. How do I enter the ASCII equivalent of an integer?
Comment: The serial monitor is meant to let you enter text, not arbitrary binary data. You can parse the text into numbers in the Arduino.
Comment: You can convert it in your program. For a single digit you can easily convert using `value = incomingByte - '0';` For multiple digits you need to separate the ascii out into digits, subtract 48 ('0' is a simple way to do that without having to remember the ascii value of 0)  and then add them together with the appropriate *10^n scale factors.
Answer: Using the Arduino IDE Serial Monitor, there's not much you can do. But you can use a different serial-port terminal such as RealTerm (for Windows, if that's your thing) which allows for a wide array of serial port nitty-gritty details.
Answer: Check out the ASCII table.
When you enter 1 into the Serial Monitor you are telling it to send the (ASCII) character 1 - which is represented by the decimal value 49, so the byte that is sent is 49.
I don't believe it is possible to enter the decimal value 1 into the Serial Monitor (you'd have to find some way of entering SOH via the keyboard), so the only option is to recognize and accommodate that on the Arduino end.
The usual way to do this is to subtract 48 from the received value. However this is typically written as - '0' which is actually subtract the ASCII value of 0 (this helps indicate that you converting from ASCII)
So...
int intVal = incomingByte -'0';
... should work fine for you if you are receiving single digit integers.
However, if you also want to accommodate multi digit integers (e.g. 123) then it becomes more complex requiring converting each byte to it's integer equivalent and then multiplying it by 10 to the power of it's position/column...
123 = (1 * 10^2) + (2 * 10^1) + (3 * 10^0)
This is a fun little coding task in itself, but if you're not into that kind of thing then parseInt('123'); will get you going faster...
Answer: You can do this little trick:
void loop()
{
while (Serial.available() == 0); //waiting for input
int val = Serial.parseInt(); //read as integer
}


Ubuntu Nexus 7 as USB device does not work

Question: I connected USB cable from Nexus 7 running Ubuntu to my Ubuntu laptop but there is no new USB device found when I run lsusb. Is this function supported?
Comment: try `sudo apt-get install mtpfs mtp-tools gmtp` and then `sudo mtp-detect`, then launch `gmtp`.
Comment: It works half the time, and is too slow. But atleast, it works.
Answer: UPDATE Please take a look below for go-mtpfs example.  go-mtpfs is much more reliable, but the instructions remain very similar.

Automatically mounting Nexus 7
Allow non-root users to mount fuse devices:
sudo vim /etc/fuse.conf
Un-comment **user_allow_other**.

Install mtpfs
sudo apt-get install mtp-tools mtpfs
Make mount point
sudo mkdir /mnt/nexus7
chown youruser:youruser /mnt/nexus7
Add udev rules
sudo gedit /etc/udev/rules.d/99-android.rules
#Nexus7
SUBSYSTEM=="usb", SYSFS{idVendor}=="18d1", MODE="0666"

sudo chmod +x /etc/udev/rules.d/99-android.rules
Add Nexus7 to fstab
sudo vim /etc/fstab
mtpfs /mnt/nexus7 fuse user,noauto,allow_other,defaults 0 0

Restart udev
sudo service udev restart
Access device
mount /mnt/nexus7
umount /mnt/nexus7
Comment: As well as manually mounting/unmounting, Nautilus should display your Nexus 7 in your 'Device' list so that you can more easily access it.
Comment: After having various issues on different devices, I have switched to [go-mtpfs](http://askubuntu.com/a/237388/13247), with most of these instructions remaining the same.
Comment: I highly doubt this will work if it doesn't even show in lsusb. With the right cable, it works with out-of-the-box 13.10
Comment: Glad to know that 13.10 supports this device out-of-the-box.  This is mostly for previous versions of Ubuntu, which require special setup. @NoBugs
Answer: A blog post by Bilal Akhtar has a supposedly more reliable way to connect to Android 4.0+ devices from Ubuntu. The steps are summarized here:

Install the go-mtpfs library, which you'll be using to connect:
sudo apt-get install golang fuse git-core libmtp-dev libfuse-dev
sudo adduser $USER fuse
mkdir /tmp/go
GOPATH=/tmp/go go get github.com/hanwen/go-mtpfs
sudo mv /tmp/go/bin/go-mtpfs /usr/bin/
mkdir ~/MyAndroid

Note: At some point during installation, a screen may come up in your terminal asking if you want to share information about public Go packages you install with the developers. Feel free to answer this question however you want.

Mount your Nexus 7 or whatever using this command after plugging it into your USB port:
go-mtpfs ~/MyAndroid &

When you are finished, unmount your device by using this command:
fusermount -u ~/MyAndroid

I would also like to thank James Gifford for pointing this article out to me on Google+. ;)
Answer: I found that it doesn't work with cheap cables - if it doesn't even show "Nexus" in lsusb, your cable is bad. Try a better one.
Comment: Some cables are "power only" for charging.  No data lines, so those cables of course will not work.
Comment: The one I first tried had 5 connections in the microUSB end, though it doesn't do anything but charge.
Answer: If the Nexus tablet has the Software Data Cable app available, this program will let you easily transfer files via a wireless link.  See:
http://linuxnorth.wordpress.com/2012/04/23/a100-to-ubuntu-file-transfer/
and
http://linuxnorth.wordpress.com/2012/04/24/software-data-cable-addendum/
Answer: In contrast to all the other answers I would still claim that it's not yet possible at all. The question is clearly about "Nexus 7 running Ubuntu" and as far as I understand there is no special service in this first Ubutu port for the Nexus 7 that acts as a USB device. I have a Nexus 7 running Ubuntu here and didn't succeed with any of these solutions mentioned.
I think, all answers so far target Nexus 7 running Android.
Please correct me if I am wrong.
Answer: Install this PPA : https://launchpad.net/~langdalepl/+archive/gvfs-mtp
Update and upgrade.
Hey presto, working MTP support that automounts a Nexus 7 as a browsable folder in Nautilus.