Is it possible to write a regex which checks if a string (javascript & php code) is minified?

Question: Is it possible to write a regular expression which checks if a string (some code) is minified?
Many PHP/JS obfuscators remove white space chars (among other things).
So, the final minified code sometimes looks like this:
PHP:
$a=array();if(is_array($a)){echo'ok';}

JS:
a=[];if(typeof(a)=='object'&&(a instanceof Array){alert('ok')}

in both cases there are no space chars before and after "{", "}", ";", etc. There also some other patterns which can help. I am not expecting a high accuracy regex, just need one which checks if at least 100 chars of string looks like minified code.
Thanks in advice.
PURPOSES: web malware scanner
Comment: Is a regex solution a requirement?  Or would procedural code be sufficient?  (e.g. Checking if a piece of code has fewer than 5% whitespace would be a decent check--this isn't a check a regex can do, though, at least not without a for loop repeating the regex.)
Comment: You could just minify it and compare the length with the original version; if it's approximately the same, then it's minified.
Comment: As for JavaScript, you can use Closure Compiler's API to compress it, and check how many characters have been saved. If it's less it probably is already minified.
Comment: Yes, i need a regex solution. But if you can provide a php function - it would be helpful. Thanks.
Comment: You may be able to come up with something that checks for code which *appears* to be minified. But there are many ways to minify scripts and each produces different output, so a formal concept of a script being minified or not is tough to nail down.
Answer: I think a minifier will strip all newline characters, although there might possibly be one at the end of the file still if the minified code was pasted back in a text editor. Something like this will probably be fairly accurate:
/^[^\n\r]+(\r\n?|\n)?$/

That just tests that there are no newline characters in the whole thing except for possibly one at the end. So no guarantees, but I think it will work well on any longish block of code.
Comment: there are many situations where newlines are mandatory, and thus will never be stripped, also many minified files still contain header info most minifyers will keep headers starting with /*! ... */ intact
Answer: The short answer is "no", regex cannot do this.
Your best bet will probably be to do a statistical analysis of the source files, and compare against some known heuristics. For instance, by comparing the variable names against those often found in minimized code. A minimized file probably has a lot of one-character variable names, for instance... and won't have two-character variable names until all the one-character variable names are exhausted... etc.
Another option would be simply to run the source file through a minimizer, and see if the output is sufficiently different from the input.  If not, it was probably already minimized.
But I have to agree with sg3s's final sentence: If you can explain why you need this, we can probably provide more useful answers to your actual needs.
Comment: @Ken: If you're happy with false positives, then just use a random number generator.  It will probably be exactly as accurate as a minimizer detector for malware detection, and much easier to write.
Comment: @Ken - How on Earth do you expect a minified-code detector to help you with that? Both legit code and malware are frequently minified.
Comment: In that case we're definitly looking at a parser that somehow checks how optimized the code is. There really isn't a simple way for this. You'll have to have the logic to know what is and what isn't optimal in a scipt. Needless to say you're building something that can match jslint for checking code optimizations
Comment: @Justin: detector/scanner will point me to files which I should check for potential malware code. Like I said before I am not expecting a high accuracy. Just need something paranoid. Any false-positive thing is ok.
Answer: No. Since the syntax/code and its intention doesn't change and some people who're very familiar with the php and/or js will write simple functions on one line without any whitespace at all (me :s).
What you could do is count all the whitespace characters in a string though this would also be unreliable since for some stuff you simply need whitespace, like x instanceof y heh. Also not all code is minified and cramped into a single row (see jQuery UI) so you can't really count on that either....
Maybe you can explain why you need to know this and we can try and find an alternative?
Answer: You can't tell if it's got minified or just written like that by hand (probably only applies for smaller scripts). But you can check if it doesn't contain unnecessary whitespace.
Take a look at open source obfuscator/minifier and see what rules they use to remove the whitespace. Validating if those rules were applied should work, if regex get to complex, a simple parser might be needed.
Just make sure that string literals like a="if   ( b )" are excluded.
Answer: Run it through a parser for that particular language (even a prettifier might work fine) and modify it to count the number of unused characters. Use the percentage of unused chars vs. number of chars in documents as a test for minification. I don't think you can do this accurately with regex, although counting whitespace vs. document content might be okay.


ADFS 2019 OAuth Access Token Lifetime

Question: Is it possible to change the access token lifetime in ADFS?
I have an Application Group configured that issues tokens perfectly fine. I just want to know if I can somewhere change the lifetime of access and refresh tokens you get via OAuth.
Only thing I found were some settings about Relaying Party Trusts, but I don't really have those.
Answer: I had the same / very similar issue and I wasted a lot of time going through the Internet to find the answer for this.
I think the issue is that most of the docs and blogs online were made using ADFS 2.0 and 3.0 which neither had the Application Group setting (at least true for version 2.0). I believe Win 2016 comes with ADFS 4.0
In short to change the token lifetime for an Application group WebApi, do the following (to set the token lifetime to 60 min for https://relyingtrust.com as an example):
<code>Set-AdfsWebApiApplication -TokenLifetime 60 -TargetIdentifier "https://relyingtrust.com"
</code>
For more info refer to Set ADFS Web API Application
Comment: Works as advertised. Thanks for providing the link.

ADFS 2019 OAuth Access Token Lifetime


ModelState.IsValid false for empty string field

Question: My Model fields accepting numbers and empty string :
[DisplayName("Height")]
[RegularExpression (@"^\d*$", ErrorMessage="Height must be a number or left out   blank")]
public string Height { get; set; }

[DisplayName("Width")]
[RegularExpression(@"^\d*$", ErrorMessage = "Height must be a number or left out blank")]
public string Width { get; set; }

My view:
<%= Html.LabelFor(x => x.Width) %>:
<%= Html.TextBoxFor(x => x.Width) %>

<%= Html.LabelFor(x => x.Height) %>:
<%= Html.TextBoxFor(x => x.Height) %>

In controller action :
[HttpPost]

public ActionResult Edit(MyModeltype model)
{
    model.Width = String.IsNullOrEmpty(model.Width) ? "" : model.Width; //NEEDED?
    model.Height = String.IsNullOrEmpty(model.Height) ? "" : model.Height; //NEEDED?

    if (ModelState.IsValid)
        SaveSettings(model);

    return View("SomeView");
}

When I provide empty textboxes, Model.Width and .Height are passed as nulls and ModelState.IsValid is false. I just need to be able to pass the empty string. When omitting the regex attribute, same problem, so its not the regex. Thank you!
Answer: I don't see you displaying the error message in your View.  So that might be causing the problem, though I'm not sure.  Anyway try this and see if it works:
<%= Html.LabelFor(x => x.Width) %>:
<%= Html.TextBoxFor(x => x.Width) %>
<%= Html.ValidationMessageFor(x => x.Width) %>

<%= Html.LabelFor(x => x.Height) %>:
<%= Html.TextBoxFor(x => x.Height) %>
<%= Html.ValidationMessageFor(x => x.Height) %>

Comment: this didn't help. Was this for debugging purposes ?
Comment: No it's the built in way for the framework to display error messages if your regular expression on the model property fails.  You probably should include if you want client side validation to work properly.  Also having empty strings on fields that are not marked as required should work.  Are there any other properties on your model that is not set properly by your View?  That would cause the model state to be invalid.
Answer: Try adding the DisplayFormat attribute to your model's properties:
[DisplayFormat(ConvertEmptyStringToNull = false)]
[DisplayName("Height")]
[RegularExpression (@"^\d*$", ErrorMessage="Height must be a number or left out   blank")]
public string Height { get; set; }

[DisplayFormat(ConvertEmptyStringToNull = false)]
[DisplayName("Width")]
[RegularExpression(@"^\d*$", ErrorMessage = "Height must be a number or left out blank")]
public string Width { get; set; }

This will ensure empty textbox values are not converted to NULL.
Alternatively, you could explicitly define your getters and setters to convert nulls to empty strings:
private string _width;
public string Width
{
    get { return _width ?? string.Empty; }
    set { _width = value ?? string.Empty; }
}


Simple Vyatta configuration / BGP routes not injecting into routing table

Question: I have a exceptionally simple setup I'm playing with however I'm banging my head against the wall as to why it's not working.
Right now I have two Vyatta routers (R1, R2) connected locally. Both are connected via a cross connect. I've setup a BGP session between the two - that's working as intended. There is no route-maps / policies in place. I'm simply trying to advertise a single route from R1 to R2 via BGP (I'm not using any IGP yet, merely a static route).
Everything is seemingly working as it's supposed to - R1 and R2 have a BGP session open and R2 see's the routes R1 is attempting to advertise:
<code>vyatta@R2# run show ip bgp neighbors 10.0.50.10 received-routes
BGP table version is 5, local router ID is 10.0.60.10
Status codes: s suppressed, d damped, h history, * valid, > best, i - internal
Origin codes: i - IGP, e - EGP, ? - incomplete

Network          Next Hop            Metric LocPrf Weight Path
*> 10.0.2.0/24      10.0.50.10                             0 1 i

Total number of prefixes 1
</code>
Now the problem is that's just routes it's seeing however it's not actively adding it to the routing table. Running show ip bgp will list nothing as well as show ip bgp neighbor 10.0.50.10 routes. R2 can access the next hop (R1) at 10.0.50.10.
Am I missing something terribly obvious?
Answer: Lets assume You are advertising for example route 192.168.1.0/24 from R1.
R1 needs to have this route installed in its routing table.
So You need to have any of these for example:
- an interface that is actually UP with IP from 192.168.1.0/24. If it is DOWN (no link) You will not get that route advertised via BGP. (Why advertise something if interface is down?)
- a route to 192.168.1.0/24 to null0 may force it to advertise it
- 192.168.1.0/24 in routing table from any other source like a static entry, and entry from another protocol like ospf.
reassuming: BGP will not advertise something (network) that doesn't exist in your routing table.
Comment: @WinkyWolly: Please post both from R1 and R2 - 1. show ip bgp summary  2. show ip route 3. show ip bgp
Comment: I've added a static route on R1 so it did advertise the route over BGP. I can confirm by checking the "show ip bgp neighbor 10.0.60.10 advertised-routes" command. R2 is also receiving those routes by checking the "show ip bgp neighbor 10.0.50.10 received-routes". However those routes are not being placed in the routing table in R2. There is no route-map / policy enabled on R2 at this time.
Comment: It may be worth noting I'm now advertising from R2 -> R1 as I was trying to see if I can get it working. The 10.0.60.0/24 route is advertised but not being shown in R1's routing table. http://pastie.org/private/f0huvqpxz3gea54akkxiww
Comment: @WinkyWolly I have strong impression that something very important and obvious is missing in Your config. Can You post Full config from R2 ?
Comment: I concur! Here is the relevant configuration from R2 - I only excluded things such as users / system stuff (NTP, etc). There are no active policies on either router. http://pastie.org/private/mtyeq0mthkkmneawhyhddq


Is truncated mean a biased estimator

Question: We have data $X_1, \dots, X_n$ which are i.i.d copies of $X$. Where we denote $\mathbb{E}[X] = \mu$, and $X$ has finite variance.
We define the truncated sample mean:
$\begin{align}
    \hat{\mu}^{\tau} := \frac{1}{n} \sum_{i =1}^n \psi_{\tau}(X_i)
\end{align}$
Where the truncation operator is defined as:
$\begin{align}
    \psi_{\tau}(x) = (|x| \wedge \tau) \; \text{sign}(x), \quad x \in \mathbb{R}, \quad \tau > 0
\end{align}$
The bias for this truncated estimator is then defined as:
Bias $:= \mathbb{E}(\hat{\mu}^{\tau}) - \mu$
In previous question it is shown that we can upper bound the truncation
$\begin{align}
    |\text{Bias}| = |\mathbb{E}[(X - \text{sign}(X)\tau) \mathbb{I}_{\{|X| > \tau\}}]| \leq \frac{\mathbb{E}[X^2]}{\tau}
\end{align}$

I was now wondering if it can be shown that:
$\begin{align}
    0 < |\text{Bias}|
\end{align}$
That is, is the truncated mean estimate biased?
Comment: It depends on the distribution of $X$ and the choice of $\tau$.  I believe in most cases it is biased, which can be verified by some simple simulations.
Comment: What does the AND operator $x\land y$ mean for real numbers $x$ and $y$? Bitwise AND? How is this related to "truncation"?
Comment: @cdalitz In probability theory, for $x, y \in \mathbb{R}$, "$x \wedge y$" is a commonly used shorthand for $\min(x, y)$.  Similarly, $x \vee y$ means $\max(x, y)$.
Answer: To elaborate my comment, consider first that $X \sim U(-2, 2)$ and $\tau = 1$. In this case $E[X] = 0$ and $E[\psi_\tau(X)] = 0$, hence the bias is $0$.
On the other hand, if $X \sim U(-1, 2)$ and $\tau = 1$, then $E[X] = \frac{1}{2}$ but $E[\psi_\tau(X)] = \frac{1}{6}$, which gives the bias of $-\frac{1}{3}$.
Therefore, if you are faced with a non-trivial statistical inference problem, I tend to believe $\hat{\mu}^\tau$ is biased (as unbiasedness requires $E_\mu(\hat{\mu}^\tau) = \mu$ for every distribution in the parametric family).  To see this more clearly, I suggest you tabulating a table of biases for the family of normal distributions $\{N(\mu, 1): \mu > 0\}$.  Of course, the question may have a more definitive answer if you can restrict the underlying distribution family to a specific one.
Comment: Thank you, I guess that if a distribution is symmetric with mean zero then the truncated mean will always be unbiased.
Comment: If the truncation is instead defined in terms of symmetric order statistics, as in trimmed means, the property stands for a distribution symmetric around its unknown expectation.
Comment: @DylanDijk That's true.  But as I stated, then it is not a "non-trivial" estimation problem.  If a distribution is symmetric with mean $0$, then its mean is certainly $0$, there is nothing to infer about.  But as a probabilistic statement, that's fine.

Is truncated mean a biased estimator


JDK 8 not available in classpath

Question: I  have Java 7  in my machine from a long time .And now I have installed Java 8 too .The problem is even after changing the JAVA_HOME & path variable  to point to  jdk 8,  I still get jdk 7 in the classpath.
Snapshot of the environment variables below
But I get the below when checking the version in windows.Is there anything else I should do to get it pointed to jdk8?
C:\Users>java -version
java version "1.7.0_71"
Java(TM) SE Runtime Environment (build 1.7.0_71-b14)
Java HotSpot(TM) 64-Bit Server VM (build 24.71-b01, mixed mode)

Snapshot of the environment variables below
Comment: are you changing overall system variables or user system variables ? cause the screenshot you shared , suggests that there is a user variable defined already for that user
Comment: I haven't had to update any of these system properties in more than  15 years. Just let the Java installer do its work.
Answer:
Remove java.exe, Javac.exe and javaw.exe from system32
Remove oraclePath like some text in path of system variable(from jdk8 it will create a new system variable when installing)
Comment: Removed the java.exe & javaw.exe from System 32.Its working now:)Thnx
Answer: Four things that come to mind:

You seem to have edited the user variables. Have you looked at the system variables? I would prefer to set the JAVA_HOME and PATH variables at system level.
Have you restarted cmd/Windows?
You could type where java in your cmd to see where Windows finds Java(s).
What is your PATH variable? Looking at your snapshot I it to contain at least %JAVA_HOME%\bin.
Answer: Can you check in your System variables that in the PATH variable, there is no path to your JDK 7?
Even if you define or override a Path variable in the "user" variables, Windows just concatenate the system variables with the user ones, in this order.
So if there is a path to your JDK 7 in System path, you will have this kind of value :
PATH=;.....;D:\java\jdk8;%MAVEN_HOME%
Answer: Go in control panel and type java in the search box type java. Click on the link on the java label. Then click on tab java. You will see the active runtimes. Untick the one you don't need.

JDK 8 not available in classpath


List outline of books related to another book by a node reference field

Question: I am using the book module with four content types: A, B,C and D.
A is the content type for child pages and the rest are allowed in book outlines.
I also have a node reference field in A that allows users to select nodes of type A related to the one they are creating.
I am trying to use views to display all the nodes that are related to a certain type A node and also display the outline of these related nodes.
E.g. viewing Book A.1 related topics and their outline:

Book A.1

Book A.2

Page A.2.1
Page A.2.2

Book A.3

Page A.3.1
Page B.3.2
Page C.2.2

I have gotten as far as displaying all the related nodes to a certain node but I am not being able to display their outline.
Any help/critics appreciated.
Answer: Have you tried views to create the outline.
A simple custom module will also do the trick and then you can use the generated result to show in the block as outline. In my opinion this is the best and fastest possible way to do your job.
Comment: I am using views as I mentioned on the question, but once i get the nodes referenced I cant get their outline


Cannot create a managed object context on iOS

Question: I created a non core data project. I now want to use core data. In the build phases, I linked my binary with CoreData.framework. In my application delegate method, I want to manually create a managed object context like so
NSManagedObjectContext *aContext = [[NSManagedObjectContext alloc] init];

When I do the above, I get the following error,
Receiver 'NSManagedObjectContext' for class message is a forward declaration.

Any suggestions on what I might be doing wrong?
Comment: Have you included #import  in your application delegate's header?
Comment: Thanks that works. A better solution would be to put it in the `prefix.pch` file.
Comment: Also, be wary of using a class called message. This will conflict with other classes in iOS. I have had this affect me before.
Answer: You need to import CoreData/CoreData.h in your application delegate's header file:
#import <CoreData/CoreData.h>

Since you probably use it through outyour application you should put it in the precompiled header file, YourApp-Prefix.pch:
#ifdef __OBJC__
    #import <UIKit/UIKit.h>
    #import <Foundation/Foundation.h>
    #import <CoreData/CoreData.h>
#endif

Comment: If your app uses Core Data throughout, you can also add the same line to the YourAppName-Prefix.pch file in your project's Supporting Files directory.
Answer: Just write #import < CoreData/CoreData.h > in your implementation file. It will work


Is having a routing.yml file necessary?

Question: I'm new to Drupal 8, and was curious why some modules have a *-routing.yml file, while others don't.
Why is this the case? Does this mean that modules lacking in a *-routing.yml file don't have any routing URLs?
Comment: There are other ways to provide routes beside routing file. The routing file is for static routes that you know you have. There is the  \Drupal\Core\Entity\Routing\EntityRouteProviderInterface for example, which allows you to provide routes programmatically - so based on the configuration the routes will change - hence cannot be placed in the routing file.
Answer: *.routing.yml is used to define custom endpoints and their receiving controllers. It's the config version for hook_menu in D8. If the module does not introduce custom paths, then it will not need one.

Is having a routing.yml file necessary?


Why two different app using aviary sdk not installed in same device?

Question: I have developed two apps using Aviary SDK, Both have different keys.
The app links are :
Photo Sketcher
Photo Editor
I am facing an strange issue while installing both apps from play store. If one installed already in a device then while installing other, It's giving me duplicate provider authority.
But I have created different secret keys for both apps and put those respectively. Even though I am getting this error.
How can I resolve this issue ?
Comment: Can you post the Manifest files for each of the two apps?
Comment: Yeah sure! Give me a minute :P
Comment: This thread will be help I guess. http://stackoverflow.com/questions/6420130/android-duplicate-provider-authority-problem
Comment: Thanks IBunny, I cant update my code now, will do at night and will let you know. :)
Comment: @Code-Guru I wanted to thank you, but you were not in the room ,but here I can, Thank you :)
Answer: Check Manifest file of both apps, you have probably put same authority (eg. android:authorities=com.exaple ) for both of your provider. Change and make it unique for both app. You can use package name likeandroid:authorities="{your.package.name}.YourProvider".
Comment: Yes! that was my issue, I found it earlier. Thanks anyway :)


Unable to add Teams/SharePoint file attachment in a task to ' Tasks by Planner and To Do '

Question: I have a fully built API, that creates tasks into MS Teams "Tasks by Planner and To Do".
MS actual graph API used POST https://graph.microsoft.com/v1.0/planner/tasks
Sample API:
{

  "routeId": "7fcxxxxx-xxxx-xxxx-xxxx-5d35838xxxxx",
  "userId": "77cxxxxx-xxxx-xxxx-xxxx-5f09858xxxxx",
  "tenantId": "dcdxxxxx-xxxx-xxxx-xxxx-31002a1xxxxx",
  "title": "Task: Add you task title",
  "hospitalAssignment": null,
  "percentComplete": 0,
  "createdTimestamp": "2021-04-20T01:51:49Z",
  "startDateTimestamp": "2021-04-20T18:10:15Z",
  "dueDate": "2021-11-20T11:47:33.000Z",
  "Notes": "Add some useful notes here",

  "checklistItems": [
    {
      "title": "itema"
    },
    {
      "title": "itemb"
    }
  ],

  "attachments": [
    {
      "url": "https://www.google.com",
      "alias": "link"
    },
    {
      "url": "https://teams.microsoft.com/file/....",
      "alias": "Test Document 1"
    },
    {
      "url": "https://random.sharepoint.com/sites/...",
      "alias": "Test Document 2"
    },
  ],

  "comments": "null,",
  "priority": null
}

Hitting the above API creates a task in the planner as seen below

So, here is an issue -  when I try to click on link it took me to the browser and opens up google which is fine. Now, when I click on Test Document 1 or Test Document 2 it throws an unknown error and Sorry, something went wrong respectively.
After that, I created the task manually and adding the attachments from Add Attachment and paste the links to the file there, then click the files works and opens up the documents.
Comment: Can you please add the full details of the API that you call and the complete ( redacted) sample of the body.
currently it is not clear which API or Version you call or wether it is an POST or a PATCH
Comment: Can you also clarify how you aquire the Teams/SPO file URLs ? and weather or not the file  is shared with the owner of the task
Comment: Also see this reference to (a Flow)[https://powerusers.microsoft.com/t5/Power-Automate-Community-Blog/Create-Planner-Task-and-Include-Attachments-From-Outlook-Email/ba-p/245121] that crates a Sharing-Link to a SPO hosted document before adding it as a Task Attachment;
Answer: Assuming you are referring to adding / updating the Planner Task Details for a PlannerTask;
there is a sample provided of adding (PATCH) a pptx file using a 'teams path' as you referred to it.
Note that the path must be (url)encoded.
Tasks - plannerTaskDetail < references
https://learn.microsoft.com/en-us/graph/api/resources/plannerexternalreferences?view=graph-rest-1.0
{
  "https%3A//contoso%2Esharepoint%2Ecom/teams/agile/documents/AnnualReport%2Epptx":
  {
    "@odata.type": "microsoft.graph.externalReference", // required in PATCH requests to edit the references on a task
    "alias": "Agile Team Annual Report",
    "lastModifiedBy": {
      "user": {
        "id": "ebf3b108-5234-4e22-b93d-656d7dae5874"
      }
    },
    "lastModifiedDateTime": "2015-09-21T17:45:12.039Z",
    "previewPriority": "0009005756397228702",
    "type": "PowerPoint"
  }
}


Inverse Function Theorem/ Polynomial

Question: I was thinking about this after I read about Jacobian conjecture. But I can't see what I did wrong? Maybe you can help me.
Let $F: \mathbb{C}^n \to \mathbb{C}^n$ be of the form  $F(x_1, \dots, x_n)= (F_1(x_1, \dots, x_n), \dots,   F_n( \dots , x_1, \dots, x_n) )$ for some $F_1,\dots , F_n \in \mathbb{C}[X_1, \dots, X_n ]$, which I will call polynomial, with constant Jacobian determinant $\det DF$.
Then by Implicit Function Theorem $F$ has a local inverse $F'$ around $0$. Since $F$ is analytical $F'$ is also analytical.
We also know that $ DF' = (DF)^{-1}= \frac{1}{\det DF} \text{adj}(DF) $
but the adjugate is computed in terms of the minors of $DF$, $\det DF$ is constant and thus $DF'$ is given by polynomial functions in its components, in particular $D^k F =0$ for some $k\in \mathbb{N}$. Thus $F'$ is polynomial  because of its Taylor expansion. Since $F'$ is polynomial it is defined on the whole space $\mathbb{C}^n$.
Now we have $F' \circ F\mid_U= \text{id}$ for some open neighborhood $U$ of $0$, but this implies $F' \circ F= \text{id}$ since $F' \circ F$ is a polynomial.
Comment: Hi user60589. There were some '$' signs missing, hence the edit.
Comment: Why do you presume the adjugate is polynomial? Computing cofactors involves determinants of sub-matrices.
Comment: They are sub-matrices of $DF$ which consist of the derivatives of $F_i$, so the determinant of it is again a polynomial?
Comment: I think copper.hat is right. The minors involve divisions, and it could happen that you were dividing polynomials with no common factors in the process, which would not yield a polynomial in the end.
Comment: A minor is just a determinant? Why should they involve divisions? Or am I wrong?
Answer: You have used the wrong formula
$$df^{-1}(y)=(df)^{-1}(y)$$
instead of the correct formula
$$df^{-1}(y)=(df)^{-1}\bigl(f^{-1}(y)\bigr)\ .$$
Answer: Look what you did wrong:
$$Id=D(F\circ F^{-1})=DF\circ F^{-1} \cdot DF^{-1}\Rightarrow DF^{-1}=(DF\circ F^{-1})^{-1},$$
thus, $DF^{-1} \neq (DF)^{-1}$, which seems to be your crucial assumption.

Inverse Function Theorem/ Polynomial


How are the notes organized on a tongue drum?

Question: Disclaimer: I don't now much about music theory.
Anyway, my wife just bought one of those, which I think is called a "tongue drum":

What strikes me is that, as bad as I am at playing music, whatever I randomly do on it, however I play it, it seems to make harmonious music. Or at least, much more harmonious than what I could randomly do on a piano or a guitar. My son, who is 5, plays with it too, and it just works. It seems this thing prevents anyone from playing dissonant music.
I played some other versions of this instument, which I'm pretty sure had a different number of notes, and probably organized differently, and the result was similar.
So, is there a particular method of selecting/organizing notes on an instrument which will make any sequence played with it sound harmonious? Is there a theory behind this?

Edit: So I pushed the investigations further, as the notes still seemed a bit alien, compared to what we usually find on classical instruments.
I used some phone app that measures the frequency of what it gets from the phone mic (typically made for tuning instruments) to get a map of what we had, and here are the results (the raw frequency figures are certainly a bit inaccurate, but I'm pretty sure the resulting notes are correct):

So it seems based on the regular major diatonic scale, but not arranged as the typical CDEFGAB: it has missing notes, a few additional bass and treble notes chosen further away from the main group, and the notes are all over the place.
I don't know what to conclude from this. But it really feels like this organization makes melodies easier on the ear than what you could randomly do with 9 consecutive white keys on a piano. But maybe the clear sound of the instrument itself is also playing a role, here. I don't know.
Comment: Well, Wikipedia says "The steel tongue drum is often tuned to pentatonic scales but can be tuned to the diatonic scale, the chromatic scale, or any set of notes the maker chooses." If even a 5-yo can't make it sound bad, my money's on pentatonic.
Comment: I'd guess the note selection is either diatonic (e.g. only the white keys on a piano) or pentatonic (e.g. only the black keys on a piano).
Comment: @YourUncleBob I'm pretty sure I can manage to make some rather ugly melodies only with the white keys on the piano. It doesn't seem to be the case with this instrument.
Comment: @ dim please provide  a link to a place which sells that, or better yet, to a "user manual" .  Having never seen this, and your picture being not-very-clear, we can't comment on what notes it produces.
Comment: @Carl Here is a wikipedia page: https://en.m.wikipedia.org/wiki/Steel_tongue_drum. And here is a random shop (there are lots of them, but those are mainly handmade/artisanal products, so there is typically no user manual/datasheet): https://metalsounds-shop.com/en/7-steel-tongue-drum
Comment: @YourUncleBob - my money's with yours! First thought. But second was that there's 8 notes available... An odd number to use. (Yes, o.k. it's even...) I guess the main point is the notes are so ephemeral, the last one's gone before the next one starts?
Comment: @Tim but if you have two (or more) mallets....
Comment: @CarlWitthoft - you hide all but one... (or better still, the lot, or better still, buy a xylophone to play real tunes..!)
Answer: Like the commenters, my money is on your tongue drum being tuned to the pentatonic scale. To answer your very final question, yes - there is theory behind why the pentatonic scale sounds so "universally good" and why it is generally 'easy' to utilize and play against melodically and harmonically...
A major pentatonic scale has an absence of tritone due to the missing 4th and 7th intervals (it is missing the fa and ti within the do-re-mi-fa-so-la-ti-do.) This also allows for a distinct absence of tension, or "pull," from one note to the next within the scale itself...
This is not to say that a pentatonic scale cannot be dissonant, however. If you smash all of the notes of the pentatonic scale at once on a keyboard, for example, it does not sound "good." There is dissonance... But, there is so little dissonance that it doesn't sound "terrible" either...
According to the wiki:

Pentatonic scales were developed independently by many ancient civilizations—an indication that pentatonic scales are based upon a naturally occurring phenomenon.

So, the other part of this question rests on the way one plays the specific instrument itself. Unless you or your son bash the thing against a wall, it's generally always going to "sound good." As for your first question, it would be way more easily answered if you provided the exact brand that your wife purchased, or the exact random shop she bought it from... But, it's probably pentatonic.
EDIT
So, it looks like your tongue drum is tuned to a C major scale, with multiple octaves for the tonic (C) and the 5th (G). There are plenty of explanations of the special relationship between the tonic and the 5th so, I won't go into that here. But, there are other explanations as to why you 'can't fail' when you play this thing. Firstly, 7 out of the 9 notes will 'always sound good' together - again, take away the F4 and the B3 and you have the pentatonic scale...
But, for the most part, I'd say the can't-fail-phenomenon rests in the way this instrument is played, as I said before. One creates the sound by striking the tongues with two hands - it creates a kind of melody and rhythm simultaneously. The only harmony that something like produces is in the resonance of the notes as they sustain until the tongues are muted or struck again. If you and your son play the thing together and bang only the B, C, and D all at once, it's the closest you'll likely get to having it sound 'bad.'
Finally, the can't-fail-phenomenon is based on the fact that you are playing the tongue-drum by itself, with no other voices... I suspect if you played along with other instruments playing in Bb minor, for example, it would likely not sound so great.
If any instrument can keep you relatively within one octave, while adding only octaves for the tonic and the 5th, then it will always sound good. But, it's not going to be very versatile as far as playing in different key signatures...
Comment: For your information, following your answer, I made further experimentation to find the actual notes. There is some pentatonic there, indeed, but still with very unusual things. You can check my edit.
Comment: Actually, I was confused, it's not the pentatonic scale, I meant the regular heptatonic scale. Or is it called diatonic? Somethingtonic, anyway...
Comment: Hmmm... I just read your edit. I'll edit my response a bit. as well


Insert only specific columns with DBT

Question: As of now, I have an INSERT INTO clause, that works like this:
insert into final_table (name, age, created_at)
select *
from person_table

The final_table has 4 columns: ID (incremental/serial), name, age and created_at. The person_table has only name, age, and created_at.
When I translate it to the dbt logic, it looks like this:
{{
    config(
        materialized = 'incremental'
    )
}}

with person_table as (
  select *
  from person_table
)

select
   name,
   age,
   created_at
from person_table

{% if is_incremental() %}
    AND created_at > (select max(created_at) from {{ this }})
{% endif %}

However, dbt keeps compiling as an INSERT CLAUSE containing the ID (that it is auto-generated). Does anyone know how to insert only the specific columns that I want?
Comment: If `id` doesn't exist in the source, just create a model downstream from this model that uses `row_number()` to add it. You could also modify your incremental model to compute the ID if you want to do that in this model. Would it be helpful if I typed a solution with that? (there may be unintended side effects)
Comment: What RDBMS are you using? Most data warehouses don't support auto-incrementing pks.

If you run your code with `--full-refresh`, the result should be a table with only three columns: `name, age, created_at`
Comment: I'm using Snowflake. Yes, but I need the ID column so the issue is that I can't pass it, because it is an auto-generated column. This seems like a pretty basic feature, that I don't find anyone talking about in dbt!
Comment: Oh my god, yes! Hahah I'm new to dbt, and this part is preventing to move forward
Answer: You can use row_number to fake an auto-incrementing key in Snowflake.
In a model materialized as a table, that would be as simple as:
select
   name,
   age,
   created_at,
   row_number() over (order by created_at asc) as id
from person_table

But since this is an incremental model, your inner query will be filtered before row_number() is computed, so we need to add on the maximum value of id in the table if the model is being run in incremental mode:
{{
    config(
        materialized = 'incremental'
    )
}}

{% if is_incremental() %}
    {% set max_id = "(select max(id) from " ~ this ~ ")" %}
{% else %}
    {% set max_id = 0 %}
{% endif %}

with person_table as (
  select *
  from {{ ref('person') }}
)

select
   name,
   age,
   created_at,
   {{ max_id }} + row_number() over (order by created_at asc) as id
from person_table
where 1=1
{% if is_incremental() %}
    AND created_at > (select max(created_at) from {{ this }})
{% endif %}

Note that, if you --full-refresh this model, and records were deleted from person_table, then any records created after the deleted records will have their IDs changed. No real way around that, unfortunately! If you need an immutable ID, I would suggest hashing some combination of name, age, and created_at using md5 or dbt_utils.surrogate_key. Of course, those hashed ID's would not be monotonically increasing.
Comment: Thanks a lot, man. It is a shame that we have to work with such a turnaround on dbt. Seems like such a basic feature...
Comment: By the way, do you know if is it possible to have two models with the same name in dbt? Because I have a table that is going to consume data from two sources
Comment: model names have to be globally unique but you can use `alias` to get them to materialize to tables in your database with the same name. https://docs.getdbt.com/docs/building-a-dbt-project/building-models/using-custom-aliases

Insert only specific columns with DBT


How to play B major? What is the finger placement?

Question: One other thing is, is there more one way to play B major? Why are there different fingerings for just the B major chord? For example:
Comment: There are no chromatic scales here. All you are seeing are seven different voicings for a B major chord on the ukulele. Take note of the numbers on the left of each marking, indicating the frets.
Comment: Is this for ukulele? I've suggested an edit to add the uke tag.
Comment: Related: http://music.stackexchange.com/a/7676/6556
Answer: A major chord is a triad of three notes: the root note, the major third, and the perfect fifth. For the B major chord, the notes are B, D♯, and F♯.
Any combination of those three notes on your strings will form a B major chord. If the lowest note played is a B, the chord is in root position; otherwise, the chord is an inversion, which changes the character of the sound. When playing solo ukulele, this will depend partly on whether you use high G or low G tuning.
Which fingering you use in practice depends on what other chords or notes you play, as it's easier to transition between some fingerings. Different neck positions and fingerings can also produce subtle differences in tone. Skilled listeners will be able to tell the difference between chord voicings, but they are all still "B major" chords.
Each of the examples in your fingering chart show exactly which frets to play on each string to create those three notes. The fret numbers are on the left side of the chart, and the notes to play are shown above the strings. For example, in the first fingering, you play B on the fourth fret of the G string, D♯ on the third fret of the C string, F♯ on the second fret of the E string, and B on the second fret of the A string. In the very last fingering, you play on the F♯, B, and D# on the 11th frets, and B on the 14th fret. These two fingerings will play the chord in different octaves, with different inversions, but they are both still B major chords.
Comment: Cleaned up comments - as Bradd says, you may wish to work on the absolute basics first...
Comment: I'm not sure what you mean by "chromatic scales" here. On the G string, each fret plays a different note: 1=G♯, 2=A, 3=A♯, 4=B, 5=C, 6=C♯, 7=D, 8=D♯, 9=E, 10=F, 11=F♯, 12=G. You can use that string to play any of the notes in a B-major chord: fret 4 for the B, fret 8 for the D♯, fret 11 for the F#. Does that help? Should I edit some of this into the answer?
Comment: I have updated my answer to include some information about how to read the fingering chart. I hope it helps you. If you still don't understand, you may need to get somebody to help you with the basics of playing your ukulele, including how to read fingering charts.
Answer: You ask 'Why are there different fingerings JUST for the B chord'. If that's what you meant, there are just as many fingerings for MOST chords. The examples shown are different mixes of the 3 notes needed for a major chord. If you look carefully,the 2nd and the 3rd diagrams actually have the same 3 notes on the same 3 strings on the same 3 frets (exactly as a guitar,top 4 strings, but in a different key),but obviously the fingerings will be different. Check others and you will see similar pattern copying.
Answer: There are (as I remember) 7 different position of a chord in a guitar (or ukulele). Which consist the triad notes (for minor 1-b3-5 and 1-3-5 for major).
If you ask about B major chord, which all major chord have 1-3-5 rule, which in B major it will be: B-D#-F#. All of your images shown those three notes.
In your images, they're the same three notes, B-D#-F#, but in different position or(/and) different octave.


Failing to upload file with curl in heroku php app

Question: I'm getting the response "failed creating formpost data" from curl whenever I try to upload a file. I'm sensing from other posts on the web that it's the filepath that's wrong, but I can't seem to get an absolute path on heroku.
When i do dirname(__FILE__) all I get is /app/www/ that can't be right can it? How do I get the absolute file path in a heroku app?
this is my entire line for the image path to be included in post data
"@".dirname(__FILE__).'/images/wallimages/'.random_pic()

and my curl setup:
$ch = curl_init('https://url.com/'.$url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $attachment);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $result = curl_exec($ch);
    if(curl_errno($ch))
    {
        return 'Curl error: ' . curl_error($ch);
    }
    curl_close ($ch);
    return $result;

Answer: I suspect the root cause of your problem may be this line from the manual:

As of PHP 5.2.0, value must be an array if files are passed to this option with the @ prefix.

In any case, try this code and if it doesn't work, let me know what error message(s) you get so I can debug:
$uploadPath = rtrim(dirname(__FILE__),'/').'/images/wallimages/'.random_pic();
if (!is_file($uploadPath)) die("The file '$uploadPath' does not exist");
if (!is_readable($uploadPath)) die("The file '$uploadPath' is not readable");

$postFields = array (
  'nameOfFileControl' => "@$uploadPath",
  'someOtherFormControl' => 'some value'
  // Adjust this array to match your post fields.
  // Ensure you keep the array in this format!
);

$ch = curl_init('https://url.com/'.$url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

$result = curl_exec($ch);

if(curl_errno($ch))
{
    return 'Curl error: ' . curl_error($ch);
}
curl_close ($ch);
return $result;

Comment: I was able to debug it myself with your additional code. That's really been bothering me so thanks a lot!


how to use value from the for-loop outside it java

Question: import java.util.Scanner;
public class App {
   public static void main(String[] args) {
       double input;
       double netto=0;
       Scanner value = new Scanner(System.in);

       for(int x=0;x<4;x++){
           System.out.println("Please enter the number");
            input = value.nextInt();
           if(input>=300){
               netto= input - input*0.30;
           }
           else {
               netto =input- input*0.20;
           }

       }
       netto=+netto;

       System.out.println(netto);

   }
}

i want that the code adds the results after subtracting part of them according to the entered value.
the problem is that the code saves the last result only and shows it.
Comment: This line does nothing: `netto=+netto;` It just assigns the value of the variable `netto` to itself.
Answer: Seems like you meant to accumulate the values into netto using += instead of overriding it with =:
for (int x = 0; x < 4; x++) {
   System.out.println("Please enter the number");
   input = value.nextInt();
   if (input>=300) {
       netto += input - input * 0.30; // Here
   }
   else {
       netto += input - input * 0.20; // And here
   }
}


Name this topological space

Question: For each $n \in \mathbb{N}$, define the circle $S_n$, which passes through the origin by:
$$S_n := \left\{ (x,y) \in \mathbb{R}^2 : x^2+\left(y-\tfrac{1}{n}\right)^2=\tfrac{1}{n^2}\right\}$$
I know that the union of all $S_n$ is taken as the base space for some topological space. Can anyone remember the name and/or supply a link? I think it has the word earrings in the title.
Comment: I dub this topological space "Steve." Most people call it the Hawaiian earring, though.
Comment: Ha ha ha! Thanks @CameronBuie that's the one.
Answer: I believe you're thinking of the Hawaiian earring.
Comment: ...Also known as "Steve"
Comment: ...I think I prefer Steve.

Name this topological space


Facebook login in iOS app for multiple users on one device

Question: My app will be used by multiple users.
How can I integrate facebook in a way so that the safari doesn't save any user credentials & throw a login page each time some one tries to login.
I already used FBSessionLoginBehaviorForcingWebView to force a web view login within the app but the problem is, when the first user tries to login to fb via the view presented within the app, the control then goes to safari for authentication & it just saves the creds.
So when other user tries to log in, & enters his credentials in the app local UIWebView, the control again goes to safari, which already has previos creds stored & the new user just cannot authenticate.
So basically the first user is permanently logged in. Clearing the cookies for web view doesn't work. I cant clear them for safari.
Help
Thanks in advance.
This is what I have been doing
if([FBSession activeSession].isOpen)
{
   [[FBSession activeSession] closeAndClearTokenInformation];//Also, clearing all the local cookies
}
else
{
  AppDelegate *delegate = [UIApplication sharedApplication].delegate;
  delegate.session = [[FBSession alloc] init];
  [FBSession setActiveSession:delegate.session];
  [delegate.session openWithBehavior:FBSessionLoginBehaviorForcingWebView    completionHandler:^(FBSession *session1, FBSessionState status, NSError *error) {
    if (!error) {
       [self openSession]; // your method
    }
   }];
 }

- (void)sessionStateChanged:(FBSession *)session state:(FBSessionState) state error:(NSError *)error{
switch (state) {
    case FBSessionStateOpen:
    {
        [FBRequestConnection startForPostStatusUpdate:@"Some message"completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
            if (!error) {

                //logout again
                NSLog(@"startForPostStatusUpdate SUCESS");
            }
            else {
                //logout again
                NSLog(@"startForPostStatusUpdate FAIL");
            }
        }];

    }
        break;
    case FBSessionStateClosed:
    {
        NSLog(@"FBSessionStateClosed");
    }
        break;
    case FBSessionStateClosedLoginFailed:
        [FBSession.activeSession closeAndClearTokenInformation];
        break;
    default:
        break;
}
if (error) {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:error.localizedDescription delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alertView show];
}
}

Also, modified the app delegate with your methods.
Answer: Found a solution. Basically, calling the following:
[FBSession.activeSession closeAndClearTokenInformation];
[FBSession.activeSession close];
[FBSession setActiveSession:nil];

Only clears the local FB session information but not the Safari cookies. So, after I log in the user, I clear the Safari cookies:
NSHTTPCookie *cookie;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [storage cookies]) {
    [storage deleteCookie:cookie];
}
[[NSUserDefaults standardUserDefaults] synchronize];

It isn't very elegant, but it works. Now, when the next user tries to log in, it forces them to enter their credentials.
Answer: You just need to use this method after you want to close the FB Session.
[FBSession.activeSession closeAndClearTokenInformation];

This will clear the Facebook Token, and whenever button will be pressed for Facebook share, it will ask for new token credential and it will show Facebook login view again.
Use following code in AppDelegate
    // This method will handle facebook session.
    - (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
    {
    // Facebook SDK * login flow *
    // Attempt to handle URLs to complete any auth (e.g., SSO) flow.
    return [FBAppCall handleOpenURL:url sourceApplication:sourceApplication fallbackHandler:^(FBAppCall *call) {
        // Facebook SDK * App Linking *
        // For simplicity, this sample will ignore the link if the session is already
        // open but a more advanced app could support features like user switching.
        if (call.accessTokenData) {
            if ([FBSession activeSession].isOpen) {
                NSLog(@"INFO: Ignoring app link because current session is open.");
            }
            else {
                [self handleAppLink:call.accessTokenData];
            }
        }
    }];
}

// Helper method to wrap logic for handling app links.
- (void)handleAppLink:(FBAccessTokenData *)appLinkToken {
    // Initialize a new blank session instance...
    FBSession *appLinkSession = [[FBSession alloc] initWithAppID:nil
                                                     permissions:nil
                                                 defaultAudience:FBSessionDefaultAudienceNone
                                                 urlSchemeSuffix:nil
                                              tokenCacheStrategy:[FBSessionTokenCachingStrategy nullCacheInstance] ];
    [FBSession setActiveSession:appLinkSession];
    // ... and open it from the App Link's Token.
    [appLinkSession openFromAccessTokenData:appLinkToken
                          completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
                              // Forward any errors to the FBLoginView delegate.
                              if (error) {
                                  //TODO: Show error here
                              }
                          }];
}

Add following code where you are opening session for Facebook
/***********************************************************************
 This method opens browser or App Url to FB authentication and change FB
 session state
 ************************************************************************/
- (void)openSession
{
    NSArray *permisssions = [[NSArray alloc] initWithObjects:@"email",@"user_photos",nil];
    [FBSession openActiveSessionWithReadPermissions:permisssions
                                       allowLoginUI:YES
                                  completionHandler:
     ^(FBSession *session,
       FBSessionState state, NSError *error) {
         [self sessionStateChanged:session state:state error:error];
     }];
}

/***********************************************************************
 This method will be called whenever FB Session state changed
 It also shows an error message if any error occurs
 ************************************************************************/
- (void)sessionStateChanged:(FBSession *)session
                      state:(FBSessionState) state
                      error:(NSError *)error
{
    switch (state) {
        case FBSessionStateOpen: {
            NSLog(@"FBSession Open State");
            //Enter your code what you want to perform when session is open
        }
            break;
        case FBSessionStateClosed:
        case FBSessionStateClosedLoginFailed:
            // Once the user has logged in, we want them to
            // be looking at the root view.
            NSLog(@"FBSession State Closed");

             [FBSession.activeSession closeAndClearTokenInformation];
             [FBSession.activeSession close];
             [FBSession setActiveSession:nil];
            break;
        default:
            break;
    }

    if (error) {
        UIAlertView *alertView = [[UIAlertView alloc]
                                  initWithTitle:@"Error"
                                  message:error.localizedDescription
                                  delegate:nil
                                  cancelButtonTitle:@"OK"
                                  otherButtonTitles:nil];
        [alertView show];
    }
}

Now when ever user tap on Facebook Share button check that session exists or not. If not then call openSession method. It will open facebook login view.
Comment: Yeah. Tried it, not helping. I have tried deleting all the cookies also, but to no help.
Comment: Problem is not the session or token, they are cleared but safari is remembering the credentials? so it creates a new session with previously saved creds.
Comment: I updated my answer. It works for me. Please try this. I am very sure it will work for you.
Comment: Thanx, let me try. I'll let you know
Comment: `[FBSession.activeSession closeAndClearTokenInformation];
[FBSession.activeSession close];
[FBSession setActiveSession:nil];`
where you are clearing cache use complete code I written above. I also updated my answer.
Comment: Just a question, is your app in sandbox mode? in 'developers.facebook.apps/APP_NAME'
Comment: you must disable sandbox mode.
Comment: not working for me, I dunno, where I am making a mistake. Everytime a new login window appears, no problem in that, when I enter creds, it takes me to safari or fb app, there is a previous user already logged, though it asks me to login as a diff user, can i see your code, if you don't mind? :)
Comment: sorry dear. but its confidential. I cannot show you the code. Do more research. Go thorugh this link. https://developers.facebook.com/docs/ios/session/
Good Luck
Answer: There is a sample in the Facebook Github repository, showing how to switch between multiple users.
It looks like it requires use of the custom login flow.


Postgresql insert if does not exist

Question: I have the following query
INSERT INTO address (house_number, street, city_id)
    values(11, 'test st', (select id from city where LOWER(city) = LOWER('somecity')))

Is there anyway to insert "somecity" in the city table if "somecity" does not exist in city then after inserting, it would return the ID for the inserted row?
I did find this answer that says upsert can be used to achieve this
https://stackoverflow.com/a/31742830/492015
but I can't find an example that inserts if select does not return the row.
Comment: The best option here would be using a trigger on address table that would do a lookup in the city and insert it if not present.
Comment: Another option would be to create a function that would do the lookup and whenever the city does not exists you insert it and return the id
Comment: Aaaaand to make this comments more fun: Nice job with the Night King! B)
Comment: You can create a *view* on the address table that takes the city name and a trigger on that view to accomplish what you want.
Comment: @JorgeCampos is there any example of using triggers to insert data into another table?
Comment: @Arya https://stackoverflow.com/a/24607012/460557
Answer: Instead of nesting the INSERTs, you could use a CTE
to perform the INSERTs one after the other but as a single statement:
WITH tmp AS (
    INSERT INTO test_city (city) VALUES ('somecity')
    ON CONFLICT (lower(city)) DO UPDATE SET city = excluded.city
    RETURNING id, city
)
INSERT INTO test_address (house_number, street, city_id)
SELECT house_number, street, id
FROM (VALUES (11, 'test st', 'somecity')) val (house_number, street, city)
LEFT JOIN tmp USING (city)
RETURNING *

Using this setup:
DROP TABLE IF EXISTS test_address;
DROP TABLE IF EXISTS test_city;
CREATE TABLE test_address (
    house_number int
    , street text
    , city_id int
    );
CREATE TABLE test_city (
    id int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY
    , city text
    );
CREATE UNIQUE INDEX test_city_uniq_idx ON test_city USING btree (lower(city));
INSERT INTO test_city (city) VALUES ('Somecity');

and with the INSERT above, the query
SELECT * FROM test_address;

yields
| house_number | street  | city_id |
|--------------+---------+---------|
|           11 | test st |       1 |

and
SELECT * FROM test_city;

yields
| id | city     |
|----+----------|
|  1 | somecity |

Note that the CTE replaces
(select id from city where LOWER(city) = LOWER('somecity'))

with an INSERT .. ON CONFLICT .. DO UPDATE statement:
INSERT INTO test_city (city) VALUES ('somecity')
ON CONFLICT (lower(city)) DO UPDATE SET city = excluded.city
RETURNING id, city

I used DO UPDATE instead of DO NOTHING so that RETURNING id, city will always return something. If you use DO NOTHING, then nothing is returned when there is a conflict.
Note however that a consequence of using city = excluded.city is that the original 'Somecity'
gets replaced by 'somecity'. I'm not sure you'll find that behavior acceptable, but unfortunately I haven't figured out how to do nothing when there is a conflict and yet return id and city at the same time.

Another issue you may have with the above solution is that I used a unique index on lower(city):
CREATE UNIQUE INDEX test_city_uniq_idx ON test_city USING btree (lower(city));

This allows you to use the identical condition in the INSERT statement:
INSERT ... ON CONFLICT (lower(city))

as a substitute for the condition LOWER(city) = LOWER('somecity') which appeared in your SELECT statement. It produces the desired effect, but the trade-off is that now you have a unique index
on (lower(city)).

Regarding the followup question
of how to insert into more than 2 tables:
You can chain together more than one CTE, and the subsequent CTEs can even reference the prior CTEs. For example,
CREATE UNIQUE INDEX city_uniq_idx ON city USING btree (lower(city));
CREATE UNIQUE INDEX state_uniq_idx ON state USING btree (lower(state_code));

WITH tmpcity AS
(
   INSERT INTO
      city (city)
   VALUES
      (
         'Miami'
      )
      ON CONFLICT (lower(city)) DO
      UPDATE
      SET
         city = excluded.city RETURNING id, city
)
, tmpstate as
(
   INSERT INTO
      state (state_code)
   VALUES
      (
         'FL'
      )
      ON CONFLICT (lower(state_code)) DO
      UPDATE
      SET
         state_code = excluded.state_code RETURNING id, state_code
)
INSERT INTO
   address (house_number, street, city_id, state_id)
   SELECT
      house_number,
      street,
      tmpcity.id,
      tmpstate.id
   FROM
      (
      VALUES
         (
            12,
            'fake st.',
            'Miami',
            'FL'
         )
      )
      val (house_number, street, city, state_code)
      LEFT JOIN
         tmpcity USING (city)
      LEFT JOIN
         tmpstate USING (state_code)
         ON CONFLICT (street) DO NOTHING

Comment: Thanks for your answer, I'm using your first example with CTE, it's working well, how would I add more tables like city to it? I also have a state table and a zipcode table.
Comment: You can [chain together more than one CTE](https://stackoverflow.com/a/21387005/190597), and the subsequent CTEs can even reference the prior CTEs.
Comment: This is what I constructed, something tells me I messed it up. https://pastebin.com/jejQ51di
Comment: I think you are almost there, except the VALUES tuple should repeat `'Miami', 'FL'`, and the join condition should be `LEFT JOIN tmpstate USING (state_code)`. I've edited post above to show what I mean.
Comment: Thanks, that works, but I ran into another complication when adding the CTE for the county table. Since there are cases where the same name for a county could belong to more than one state, I have to create an index on two columns for the county table. `CREATE UNIQUE INDEX county_uniq_idx ON county USING btree (lower(county), state_id);`  But `ON CONFLICT` only supports one column. I tried using ON CONFLICT ON CONSTRAINT shown here https://pastebin.com/BTd4hSZT, but unfortunately that does not work. What do you think is the best solution?
Comment: Nevermind, it looks like ON CONFLICT does support two columns
Comment: Another question if you don't mind. When chaining CTE, how do I access the id from the last CTE? for example https://pastebin.com/jdihGePs I'm using tmpstate.id to get the id, is that the correct way of doing it?
Comment: Use the [`INSERT .. SELECT .. FROM table` pattern](https://dba.stackexchange.com/a/46477/2037),
where `table` is a `LEFT JOIN` between `VALUES` and `tmpstate`. Above, the last SQL example uses this pattern to insert `tmpcity.id` and `tmpstate.id`. An `INSERT` inside a CTE has exactly the same syntax as an `INSERT` outside a CTE.
Comment: What do you think if I use `citext` datatype instead of `text`? it's pretty much a case insensitive `text` datatype.

Postgresql insert if does not exist


How do you 'continue' like with for loops when iterating with a closure in javascript

Question: Using underscore.js is there a way to breakout of the each if a certain condition is met?
_.each([1,2,3], function(value) {
  if (value == 2) {
    // continue 2
    return false;
  }
});

I'm sure returning false did the trick in prototype.js
Comment: [This issue addresses the problem that you cannot do this](https://github.com/documentcloud/underscore/issues/211). Underscore has a `breaker` property you can return internally to break `_.each`. it's not public
Comment: You could always throw an exception, but that seems pretty clumsy.
Answer: I'm not sure if you can actually stop the loop but you could use a boolean to stop the code in the loop from executing:
var keep_going = true;
_.each([1,2,3], function(value) {
  if(keep_going){
    if (value == 2) {
      // continue 2
      keep_going = false;
    }
  }
});

Answer: Looks like you should return breaker, which isn't in scope it seems. So, without modifying _, you can't easily break out of iteration. The === there will ensure that returning {} won't cause the loop to break; you need a reference to breaker, which you don't have.
 // The cornerstone, an `each` implementation, aka `forEach`.
  // Handles objects implementing `forEach`, arrays, and raw objects.
  // Delegates to **ECMAScript 5**'s native `forEach` if available.
  var each = _.each = _.forEach = function(obj, iterator, context) {
    if (obj == null) return;
    if (nativeForEach && obj.forEach === nativeForEach) {
      obj.forEach(iterator, context);
    } else if (_.isNumber(obj.length)) {
      for (var i = 0, l = obj.length; i < l; i++) {
        if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return;
      }
    } else {
      for (var key in obj) {
        if (hasOwnProperty.call(obj, key)) {
          if (iterator.call(context, obj[key], key, obj) === breaker) return;
        }
      }
    }
  };

Comment: You might want to report this as a bug or feature request. Also note that if your object supports `forEach`, then you can't break also.
Comment: Here is how prototype.js handles it: http://www.prototypejs.org/api/enumerable/each
Comment: So is it possible to break out of the native forEach?
Answer: You can't. As Stefan posted above, if your browser does not support Array.prototype.forEach (which is a long shot these days), you could return breaker -- if you had access to it. But unfortunately, you don't, because breaker is defined as {} in a closure in the underscore.js library.
Unfortunately, the behavior of JavaScript is that two objects are not equal to one another unless they are the exact same object. Therefore, ({}) === ({}) is false -- and so returning {} from your function will not pass an equality check with the internal breaker variable.
So, you can't break out of loops like this without roundabout methods like posted above. And, according to the MDC, there is no way to break the native forEach that is used.
Answer: It may very well be that .each does not support skipping.
You can do it the roundabout way:
var skip = false;
_.each([1,2,3], function(value) {
  if (true === skip) {
    return;
  }
  if (value == 2) {
    skip = true;
    return false;
  }
});

But I'm sure there is a better function for it.
Comment: Yoda conditions I write because my sanity I want to keep. Also triple equals I use because coercion I do not like. And why are Yoda conditions not necessary in JavaScript? You can still incorrectly write `if (skip = true)`
Comment: In JavaScript, Yoda conditions not necessary are. ;)
Comment: Okay, maybe it's a matter of taste. I just don't like them, but I do see your point.
Comment: Why not be consistent then and write `if (2 == value)`? :p


Convex hull of union of polytopes in halfspace representation

Question: Suppose I have two polytopes in $\mathbb{R}^n$ given in H-representation as
$P_1: \{x | H_1 x\leq b_1 \}$
$P_2: \{x | H_2 x\leq b_2 \}$
My question is, if it is possible to efficiently (i.e., avoid going to the V-representation) compute the halfspace representation of the convex hull of their union, i.e., find $H_3$, $b_3$ such that
$\mathrm{convh}\{P_1 \cup P_2\} = \{x | H_3x\leq b_3\}$.
Note that if $P_1$, $P_2$ are given in V-representation, I can efficiently determine the V-representation of the convex hull of their union without ever needing to compute the halfspace representation. However, so far I was not able to find a "dual" procedure utilizing only the H-representation.
If it is relevant for a possible solution, the polytopes $P_1$ and $P_2$ are generated by applying a linear mapping to some other polytope $P_0=\{x|H_0x \leq b_0\}$, i.e., in my special case I have that
$P_1=A_1 P_0 = \{x|H_0A_1^{-1}x\leq b_0\}$
$P_2 = A_2 P_0 = \{x|H_0A_2^{-1}x\leq b_0\}$
where $A_1$, $A_2$ are $n\times n$ nonsingular matrices.
Comment: I have two comments: Firstly, the "dual" of the convex hull of two polyhedra in $\mathcal{H}$-representation is roughly the intersection of two polyhedra in $\mathcal{V}$-representation.
Comment: Secondly, if you don't insist on having a minimal (in the number of variables) $\mathcal{H}$-representation, then you could introduce additional variables. E.g. the convex hull of $P_1$ and $P_2$ can be written (with a few exceptions) as $\{\mathbf{x}\mid \exists \mathbf{y},\lambda\ H_1\mathbf{x} + H_1\mathbf{y} + \mathbf{b}_1\lambda \leq \mathbf{b}_1 \land -H_2\mathbf{y} - \mathbf{b}_2\lambda \leq \mathbf{0}\}$. Bold letters are vectors. The formula above holds for polytopes having at least an interior point.
Answer: I do not think that what I wanted to achieve is possible.
However, I have eliminated the need for such a procedure by restructuring my computations. (More specifically, instead of propagating the mappings $A_1$, $A_2$ forwards from $P_0$, I now iterate the inverse mappings $A_1^{-1}$, $A_2^{-1}$ backwards starting from a "desired" target set until I end up in some feasible $P_0$. As a side effect, this eliminates the need for matrix inversion).


Modifying a function $X \to \mathbf{C}$ into a nowhere vanishing map.

Question: Suppose $X$ is a normal space (compact, if this would help here), and $f : X \to \mathbf{C}$ is continuous. Set $K = f^{-1}(\{0\})$ and let $E \supset K$ be some open neighborhood of $K$ such that $f$ is bounded away from $0$ on $X \backslash E$.
My question is the following. Is it possible to construct (or prove the mere existence of) a continuous map $g: X \to \mathbf{C}$ such that $g$ vanishes nowhere and it coincides with $f$ on $X \backslash E$? My intuition tells me yes.
However, I have difficulties constructing such a $g$.
If $u : X \to [0,1]$ is an Urysohn function which vanishes outside $E$ and equals $1$ on $K$, setting $g := f + u$ will work when $f$ is real-valued and positive on $E$, but otherwise it might brake down. This can be avoided by writing $f(x) = |f(x)| e^{ i \arg f(x) }$, and then setting $g(x) := ( |f(x)| + u(x) ) e^{i \arg f(x) }$, however this is ill-defined whenever $f(x) = 0$, so then the question would be if $x \mapsto e^{i \arg f(x) }$ can be continuously extended from $X \backslash K$ to $X$, in such a way that this extension does not vanish. If we think of this as a map from $\overline{X \backslash K}$ (continuously extended to $\partial K$) into $\mathbf{C}$, then Tietze's extension theorem gives us an extension, but this might vanish on $K$. This seems like a dead end to me.
There are probably some other constructions that I'm overlooking. Or maybe there exists some cunning counter-example?
Any advice is welcome. :-)
Answer: Here is a counterexample: Let $X = \mathbb{C}$, $f(z) = z$, and $E= \{ z \in \mathbb{C} : |z| <1\}$. If such a $g$ would exist, then it would be a map of the closed unit disk into the punctured plane with $g(z)=z$ for $|z|=1$. Then $h(z) = \frac{g(z)}{|g(z)|}$ would be a continuous retraction of the closed unit disk onto its boundary, and we know that such a map does not exist.
Comment: Indeed, nice example. I guess I was hoping too hard for this to be true, that I became blind for the simple examples.


Uniform continuity of $f(x):=\inf\{r \in D : x \in U_r\}$

Question: I have a sequence of sets $\{ U_r\}_{r\in D}$ in a topological group $G$, where $D$ is the set of dyadic numers in $[0,1]$ such that
$U_{1/2^n}$ is a neighborhood of the identity $e \in G$, $U_{1/2^n}^{-1}=U_{1/2^n}$ and $$U_{1/2^{n+1}}U_{1/2^{n+1}} \subseteq U_{1/2^n}$$ for all $n$. Also I have that $$U_{1/2^n}U_{k/2^n} \subseteq U_{(k+1)/2^n}$$ for $1\leq k<2^n.$
I need to show that the function $f:G \to [0,1]$ defined by
$$f(x):= \inf\{r \in D : x \in U_r\}$$
is uniformly continuous. I have show that $f$ is continuous, but I am stuck in showing uniform continuity.
Comment: Maybe you could add you proof of continuity of $R$. Sometimes a little tweak in your proof could yield uniform continuity (although I guess you tried that).
Answer: The idea should be that $f$ gives you the "distance from $x$ to $e$", and $U_r$ works as a "ball of radius $r$".
So you should prove that if $yx^{-1}\in U_{1/2^n}$ then $|f(x)-f(y)|\leq 1/2^n$, or equivalently
$$f(y)-1/2^n\leq f(x)\leq f(y)+1/2^n.\tag{$*$}$$
For the first inequality of $(*)$, use the definition of $f(x)$ as an infimum and the inclusion $U_{1/2^n}U_{k/2^n}\subseteq U_{(k+1)/2^n}$.
The second inequality of $(*)$ follows with the same argument with the roles of $x$ and $y$ interchanged (and symmetry of $U_{1/2^n}$).
Note that that this is right uniform continuity (for the right uniformity of $G$).
Comment: Thank you. I showed the continuity of $f$ in a more complicated way, the argument does not work for uniform continuity. Now I can show left and right uniform continuity using your answer.


joining two or multiple PCollection *without* key in dataflow

Question: Suppose
   PCollection p1 has {1,2,3}
   PCollection p2 has {A,B,C}
I would like to generate PCollection which has pairs from p1 and p2 like
{A,1}, {B,2}, {C,3}
I would appreciate any help.
Thanks,
K
Comment: Any combination of 1:1 mapping is fine. like {A,3} {B,1} {C,2} is also ok.
Comment: Can you tell more about what you're trying to achieve using this? It's a somewhat odd operation so I suspect there might be a better way to achieve your actual end goal.
Comment: There is no specific relation between P1 and P2. It's like the list of guys and the list of girls. I just need the list of 1:1 mapping.
Comment: But what do you do with the mapping afterwards? Also, how many are there: would they fit in memory? And what would you want to do if the collections have different sizes, or if one or both are unbounded (streaming)?
Comment: thx. jkff. p1 will the same or larger than p2. so, some elements in p2 may not have matching. the size of collection will may not fit in memory.  they are bounded. The result of the mapping will be used for some other service, which is not dataflow.
Answer: I think I'd recommend using a stateful ParDo to assign sequential numbers 1, 2, ... to elements of each PCollection, and then use a CoGroupByKey to perform a join. That means each PCollection will be sequentially processed using 1 worker, but I currently can't think of a way to implement this particular operation more efficiently.


Very difficult to reach truss-rod with provided Allen key

Question: Disclaimer. I am a total guitar beginner; I have no intention of messing with the truss rod if there is no need to, but after I bought my strat-type, I started noticing what I think are intonation problems and decided to spend some time studying the anatomy of the instrument to see where the problem may be. I don't think that the real problem is the neck relief here, but what I noticed on the neck seems weird to me and opinions are appreciated.
This is a picture of my strat-type guitar with an Allen Key fully insterted into the truss rod nut. This is not any key; it is actually the one that came with the instrument.

I am perplexed because the wrench is very close to the wood. Even if the strings were not there, I would not be able to turn the key without damaging the sides of the truss rod hole.
Actually, I tried loosening the strings, removing the string trees, and tried to use the long leg of the Allen key (like this guy here, see the 7th picture). Well, if I do this, I am not even able to reach the nut. I believe the problem in this case is the lower side of the truss rod hole, that is preventing me from aligning the key to the nut.
In short, it seems that the geometry of that thing is a little messed up. As I said before, that key came with the instrument, and its short leg is actually longer than other Allen keys that I have in my house; this means that with those other Allen keys I would not even reach the nut.

Is there something wrong with the neck?
Is the truss rod broken or went out of place?
What does the truss rod nut look like on real Strats?
Would I need something like this if I were do adjust relief?

More info
The guitar is a Glarry GST.
Update
From the answers and comments, I gather that it is advisable to have a special tool. This and this look like they are the same thing, with the non-fender one being much cheaper.
Update #2
@Tetsujin is right about sizes. In the end I got a 4 mm Allen T-key with ball end from the same manufacturer, which is the metric version (i.e. it's basically a little thinner) of the imperial one that I posted before. I can confirm that the imperial one will not fit the nut on my Glarry. If you have a Fender or Squier I presume you should be fine with the imperial one, but I can't say for sure.
Comment: What is the make and model of this guitar? I'd be inclined to use a long wobble Allen key. Snap-On will provide! The shop will also be able to enlighten you.
Comment: Thank you! It's a Glarry GST aka the cheapest electric ever. I added a link in the original post.
Answer: The truss rod on real Strats is at the other end. You can't even see it until you take the scratch plate off, or reach it until you loosen the neck. You got an easy one there ;)
and yes, get a long key with a ball-end, like the Fender one. All you're fighting with after that is they put an 'overkill' string-guide in the way.
The long handle means you're not fighting against the head or access hole edges, the ball-end gives you flexibility as it doesn't have to be in the socket dead straight, it works at an angle.
Blow-up of linked advert, showing ball-end

I suppose I should mention that a Strat copy will not necessarily use the same American allen key sizes as Fender, they're quite likely to be metric, so double check before you buy.
Comment: Thank you! I'll check. It seems like 3/16" (like the Fender tool) is about right but I'll do more research. Thanks!


Simulink generate code with unsupported istruction (ceil)

Question: Generating code by Simulink (Matlab R2011A on MacOS 64bit)
I got a problem: it uses ceil function inside the code, but it isn't supported on my target platform.
I'm generating using ERT, for Arm Cortex processor (on a Cypress PSoC).
Is it possible to solve this problem?
I tried the solution without success.
Also in Code Generation - Interface, I tried to disable floating-point or not-finite numbers... but in this way every signal of my project raises some errors (same behaviour also changing it data-type).
Really thanks to anyone suggests me what I can try to do
Comment: Are you sure that you don't have ceil… have you tried ceil(2.3) on matlab interface? It is quite strange for you not to have ceil on matalb…
Comment: The problem is that ceil() is generated inside the code for my ARM... and it doesn't support that instruction...
Answer:
You could write your own ceil function and include it in whatever your output code is for your target device. Assuming you are generating C-code, the function would look something like:
int ceil (double number) {
    if (number == 0)
        return 0;
    if (number > 0) {
        if (number - (int) number > 0)
            return (int) number + 1;
        else
            return (int) number;
    }
    else {
        if (number - (int) number < 0)
            return (int) number - 1;
        else
            return (int) number;
    }
}

With a prototype in your header file like:
int ceil (double);

Now your C-code can call integerValuedNumber = ceil(doubleValuedNumber) and it should work. You can also do this with macros in the C-file (see nintendo's answer).
EDIT: I corrected my code to use proper type casting syntax for C. Basically what you are doing with the (int) number syntax is taking the double-valued number variable and forcing it to be an integer. You can find more information about data types in C here, or Google "type casting C" or "data types C" for more information.
Also, some additional parenthesis might be needed, like return ((int) number) + 1; and similar. I am a little rusty on my C-programming, but hopefully this gets you going toward a viable solution.
EDIT 2: I corrected the return data type of our self-defined ceil function. You would want this to return an int, or maybe long. Again, check out documentation on data types in C if you are not sure what data type is appropriate for your application. If the values you are applying ceil to are not very large (less than +/- 2^15 for instance) then int is probably fine.
Comment: Thank you: this is very useful. By the way I found a different solution to my problem that uses ceil() native implementation (inside math.h library).
Comment: Thank you for your answer... but not existing ceil(), also int() doesn't exist... :(
Comment: @PierpaoloCira Sorry about that, I had the wrong syntax. I corrected my answer to include the correct type-casting syntax for C. I make no guarantees that my code is exactly what you need, but it might get you started on the right path.
Comment: Ah yes, math.h. Now why didn't I think of that? That is the best solution, I am sure.
Answer: Ok... I solved.
The problem was in the destination environment (PSoC Creator).
As explained here http://www.cypress.com/?id=4&rID=42838 :

Go to Project -> Build Settings -> Linker -> General -> Additional Libraries. Type m in the Additional Libraries field.
  If you are not adding this Additional Library then you will get the following Build error "undefined reference to `sqrt'" where sqrt is a math function.

Nothing changes if the problem is with sqrt() or ceil(), because they are in the same library (math.h).
PS: thank you Engineero... your solution is very useful, and can be apprecied from other people with my problem (but in other environments).


Leitura de Json com PHP

Question: Galera, estou com uma dúvida na leitura do Json com PHP.
O Json é esse:
{"message":"Oi Gente","report":[{"0":[{"port":"gsm-2.3","phonenumber":"00000000000","time":"1970-01-08 10:00:26","result":"fail"}]}]},

mas não consigo exibir seus valores.
Agradeço desde Já!
Comment: QUal é o valor que queres?
Answer: Faz assim:
$json = '{"message":"Oi Gente","report":[{"0":[{"port":"gsm-2.3","phonenumber":"00000000000","time":"1970-01-08 10:00:26","result":"fail"}]}]}';
$json_dec = json_decode($json, true);

Depois se quiseres por exemplo a message:
echo $json_dec['message'];

DEMONSTRAÇÃO
Se quiseres por exmplo o time em report:
echo $json_dec['report'][0][0][0]['time'];

DEMONSTRAÇÃO

Leitura de Json com PHP


Looking for fingering advice for fast opening section of "Cynthia's Battle" theme

Question: I've just started learning this arrangement by Marasy8 on youtube from a nostalgic video game of mine (Cynthia's Battle theme for any Gen IV'ers), and I'm at the bit right after the opening chords. The left hand went down easily enough, but Marasy8's fingering isn't as easy to see for the right hand. I'd usually go with what feels most natural to me (I've linked my interpretation here), but considering how fast this piece plays and the fact that I don't have a ton of experience, I don't want to start speeding things up until I'm sure my fingering's the best it can be.
To keep the question as self-contained as possible, I'll provide the following information in addition to the links, which may be susceptible to rot. I could not find any sheets for this particular arrangement after checking thoroughly for them online, so I've instead opted to learn with the help of a Synthesia video I found on youtube.
The notes with my fingerings are as follows (E5 would denote an E is played with the finger 5), with the first E occurring in the 6th octave, i.e. E6:
E5 Bb2 C#3 F#1 Bb4 C#1 F#4 G5 F#4 E3 Bb1 C#2 F#1 Bb3 F#1 G1 A2 F#4 E3 C#2 Bb1
Is there anything I could change before I commit it to muscle memory?
Comment: This fingering is easier to discern if one [slows down the video](https://music.stackexchange.com/questions/103584/how-can-i-slow-down-a-youtube-video-im-trying-to-analyze-or-transcribe). Perhaps that will give you the solution you need. Otherwise, please add to the question an indication of the notes being played and your current fingering. that will allow someone to answer without transcribing the recording and in a way that will be helpful to future readers.
Comment: @Aaron I see, thanks for pointing that out. I did try playing the video frame by frame, and some strokes were simply not discernible between frames. I will edit my question with the information you've suggested, but I find it strange that you've suggested an edit but still chose to close-vote.
Answer: I see nothing wrong with your fingering. Allowing it's comfortable for you, committing the fingering to memory seems fine.
That said, here is my own preferred fingering. Try it out and see if you want to adopt any or all of it.

5-2-4   1-5-1   4-5-4   3-1-4   1-4-2   1-2-5   4-2-1

This fingering depends on a very quick release of finger 5 that allows the hand to "retract" back to its natural relaxed position. If finger 5 lingers on its note, then I would adjust this way:

5-2-3   1-4-1   4-5-4   3-1-4   1-4-2   1-2-5   4-2-1
    *     *
Comment: I had to check through my question for mistakes and the original arrangement to see if I'd heard wrong, but I couldn't find anything erroneous on my part. Could you explain to me how you've arrived at F# for the 19th note rather than E?
Comment: @Brxan I'm not sure I can give you a satisfying answer, I just clearly hear the F#. As a step in that direction, you might listen for the fact that the pitch preceding the final C# is lower than it rather than higher. You could try slowing the video -- YouTube will preserve the pitch.
Comment: Would the F# you hear not be the 18th note? I hear an E, C# and Bb after it. The same is reflected in a Synthesia video that seems to be accurate to my ears, which I could link if you're sure you haven't misread my original post.
Comment: @Brxan It's the eighteenth note -- one octave below the F# just before. You're welcome to link the Synthesia video. I'll take a look when i can.
Comment: Gladly, you can find it here: https://www.youtube.com/watch?v=Yscu6KSMG3M . No rush.
Comment: @Brxan Okay, that clarifies things. I don't hear the E at all in the first recording, but now I see she's playing the F# with her left hand, and the E is clearly present in the Synthesia version. I've updated my answer.
Comment: I see, glad we're on the same page. I can see the benefits of your preferred fingering - some stretches are shortened and the jump to get finger 4 to the last F# is eliminated, making the transition to the final notes feel noticeably safer. That last part's definitely the more reliable route to go.
Comment: @Brxan Glad that helped. It was a successful collaboration.
Comment: Couldn't agree more.


Group content by taxonomy term, but then also list all terms in each row

Question: I'm looking for help with creating a view.
I have a content type, Thing. Thing has a field on it where you can select multiple terms in a taxonomy, Category. I want my view to look like this:
Category 1

Thing 1

Category 1
Category 2

Thing 2

Category 1
Category 3

Category 2

Thing 1

Category 1
Category 2

So basically, I want to group by the terms and then list out all terms underneath each Thing. I also don't want groups to end up with headers of "Category 1, Category 2," and I want to make sure each of the terms is listed under each instance of the Thing in the view.
Thanks for any help!
Answer: I figured it out!
Instead of just adding Category as a single field in the View and trying to figure out how to configure that to show each Category for a Thing row but only one Category header per group, I have the Category field on there twice - one that does not display multiple in one row (for the headers), and one that does display them all within one row (to list out all Categories for a Thing).
I hope this possibly helps someone else!


How to install cross compiler (on ubuntu 12.04 LTS) for microprocessor SA1100?

Question: Can someone please tell me how to install the cross compiler (programming language C) for the SA1100 microprocessor? I have ubuntu 12.04 LTS. I´m a complete noob to Linux, I just installed Ubuntu yesterday. I need a special variant of the GCC compiler that is named "arm-unknown-linux-gnu-gcc" but don know how to do it.
Can someone please help me?
Comment: Did you try `apt-get install gcc-arm-linux-gnueabi` or `apt-get install gcc-4.7-arm-linux-gnueabi`? I also strongly recommend being able to compile an ordinary C program for your Linux system (i.e. learn the basics of `gcc`, `make` ... commands and how to use some editor like `emacs` or `gedit` ...) and the cross compiler you want also depends upon the system running on your SA1100 hardware board.
Comment: I do know how to compile an ordinary C program. That was `gcc -o hello hello.c`. I already tried `apt-get install gcc-arm-linux-gnueabi` and installed but cross compiling still doesn´t work. I want to cross compile the programs  with (for example) `arm-unknown-linux-gnu-gcc -O2 -Wall -o hello hello.c` but it tells me the command couldn be found. Can you also tell me what `make` is for? Thank you, I appreciate your help!
Comment: You should actually use `gcc -Wall -g hello.c -o hello` ; About `make`, read http://www.gnu.org/software/make/manual/html_node/index.html and use the `arm-linux-gnueabi-gcc`  program as your cross-compiler
Comment: Additional hint, use `dpkg -L gcc-arm-linux-gnueabi` to learn about the files installed by package `gcc-arm-linux-gnueabi`
Comment: @BasileStarynkevitch You may want to post an answer.
Comment: I know use arm-linux-gnueabi-gcc -O2 -Wall -o hello hello.c to cross compile. Will this program work on an Intel-SA1100 microprocessor?
Comment: It needs at least a Linux kernel and an libc to run
Comment: Ok, yeah of course. I´m sending the files by using `minicom` (serial). I now understand. Thank you for the help! :)
Comment: http://askubuntu.com/questions/250696/cross-compile-for-arm
Answer: As I told in comments, try
apt-get install gcc-arm-linux-gnueabi

or
apt-get install gcc-4.7-arm-linux-gnueabi

I also strongly recommend being able to compile an ordinary C program for your Linux system (i.e. learn the basics of gcc, make ... commands and how to use some editor like emacs or gedit ...) and the cross compiler you want also depends upon the system running on your SA1100 hardware board.  Don't forget to pass -Wall to any GCC compilation. You probably want to be able to debug your program (pass -g to GCC at compilation, and use the gdb debugger). When your program is running well, compile it with -O2 to ask GCC to optimize its machine code.
Learn to use GNU make -e.g. to write Makefile-s- by reading its documentation and use the arm-linux-gnueabi-gcc as the cross-compiler program. (You might want to use remake to debug your Makefile-s when make does not help enough)
You can get the list of files installed with a package with e.g. dpkg -L gcc-arm-linux-gnueabi
A cross compiled program executable for ARM very probably needs a Linux kernel with some libc (or link it statically) at least on the ARM motherboard, and you need some way to transmit the binary program from the Linux desktop to the ARM hardware.
Answer: Add the ppa: https://launchpad.net/gcc-arm-embedded
The source codes for both are same. Currently supports Ubuntu 10.04/12.04/13.04/13.10/14.04 32 and 64 bit.
Detailed explanations to Launchpad PPA can be found at https://help.launchpad.net/Packaging/. That website explains how a PPA is set up and how to add existing PPA and install software from it.
Here are quick steps to install toolchain from this PPA on Ubuntu before 14.04. Open a terminal and type :

sudo add-apt-repository ppa:terry.guo/gcc-arm-embedded
sudo apt-get update
sudo apt-get install gcc-arm-none-eabi

To remove installed toolchain, just do :
sudo apt-get remove gcc-arm-none-eabi
To update the toolchain, just repeat step 2 and 3.


Conversão de código Java para C#

Question: Eu gostaria de uma ajuda para converter o seguinte código em Java para C#.
public static long convertStringToBitboard(String Binary)
{
    if (Binary.charAt(0)=='0')
    {
        return Long.parseLong(Binary, 2);
    } else
    {
        return Long.parseLong("1"+Binary.substring(2), 2)*2;
    }
}

Tentei utilizar ferramentas que realizam a tradução automática, mas não obtive exito. Pesquisando pelo Google também não consegui fazer.
A dúvida mesmo são as linhas
return Long.parseLong(Binary, 2);
return Long.parseLong("1"+Binary.substring(2), 2)*2;

Aguardo uma ajuda. Eu pra falar a verdade já perdi a esperança de fazer isso funcionar em C#, espero que consiga com a ajuda de vocês :)
Desde já obrigado.
Answer: A única coisa que muda é que o método para converter uma string para um inteiro de 64 bits é o Convert.ToInt64 ao invés de Long.parseLong.
Note também que a convenção de escrita de código C# diz que os métodos devem ser escritos em PascalCase e que os parâmetros devem ser escritos em camelCase (neste caso é igual à convenção do Java).
Tanto Java quanto em C# o código poderia ser escrito de uma maneira mais curta.
public static long ConvertStringToBitboard(string binary)
{
    return binary[0] == '0' ? Convert.ToInt64(binary, 2) : Convert.ToInt64("1" + binary.Substring(2), 2) * 2;
}

Nas versões mais modernas do C# (6+) é possível escrever em forma de expression body e usar interpolação de string.
public static long convertStringToBitboard(string binary) =>
    binary[0] == '0' ? Convert.ToInt64(binary, 2) : Convert.ToInt64($"1{binary.Substring(2)}", 2) * 2;

Comment: Eu posso ao menos saber o motivo do voto contra?
Comment: Muito obrigado LINQ. Sou novo aqui. Estou marcando a pergunta como solucionada. Bem... não foi eu que negativei. Mais uma vez muito obrigado.

Conversão de código Java para C#


Why youtube viewcount attribute does not give the latest viewcount visible in youtube site?

Question: I am fetching the youtube viewcount from the Youtube XML data obtained from the url : https://gdata.youtube.com/feeds/api/videos/VIDEOID?v=2
But I observed 2 things about the viewcount attribute in the xml data:

The viewcount attribute is not created as soon as the video is uploaded. It takes 1 to 2 days for the viewcount attribute to appear in the XML.
Once the viewcount attribute appears,if I view a video several times(say 4), and check the viewcount, it is 4 in Youtube site(mobile version and desktop version) but less than 4(say 1) in the XML data

This is creating a problem for me coz I have to display the viewcount(which is same as in Youtube site)  in my application. Is there any other way of fetching the Youtube video viewcount which is the latest?
Please suggest.
Answer: It is noted in the API documentation that there might be a delay in the statistics data under Expected latency for data updates http://code.google.com/apis/youtube/2.0/reference.html#Overview:

Statistics, such as the number of times a video has been viewed or the
  number of comments available for a video, are typically updated within
  30 minutes to two hours after the upload completes. However, this
  delay may be longer under heavy API server loads.
On an ongoing basis, statistics for a video are typically updated
  every 30 minutes to two hours. However, updates may occur less
  frequently under heavy server loads or for videos that are viewed very
  infrequently. In search feeds, updates to ratings and view counts
  could take as long as a couple of weeks for infrequently viewed
  videos.