Dificuldade em escrever no cloud firestore

Question: Consegui configurar meu projeto android ao firebase, porém quando testo a cloud firestore não acontece nada. Estou tentando escrever um texto no banco de dados,porém, não se faz a gravação.
main:
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

void main(){

  Firestore.instance
    .collection("usuarios")
    .document("pontuacao")
    .setData({"carlos" : "80", "silvana": "340"});

  runApp(App());

}

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

pubspec.yaml
version: 1.0.0+1

environment:
  sdk: ">=2.1.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2
  firebase_core: ^0.4.4+3
  cloud_firestore: ^0.13.4+2

App/build.gradle
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion 28

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "guerra.guerra"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
    implementation 'com.google.firebase:firebase-analytics:17.2.2'
}
apply plugin: 'com.google.gms.google-services'

Gradle/build.gradle
buildscript {
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.0'
        classpath 'com.google.gms:google-services:4.3.3'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

log
E/flutter ( 1511): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: ServicesBinding.defaultBinaryMessenger was accessed before the binding was initialized.
E/flutter ( 1511): If you're running an application and need to access the binary messenger before `runApp()` has been called (for example, during plugin initialization), then you need to explicitly call the `WidgetsFlutterBinding.ensureInitialized()` first.
E/flutter ( 1511): If you're running a test, you can call the `TestWidgetsFlutterBinding.ensureInitialized()` as the first line in your test's `main()` method to initialize the binding.
E/flutter ( 1511): #0      defaultBinaryMessenger.<anonymous closure> (package:flutter/src/services/binary_messenger.dart:76:7)
E/flutter ( 1511): #1      defaultBinaryMessenger (package:flutter/src/services/binary_messenger.dart:89:4)
E/flutter ( 1511): #2      MethodChannel.binaryMessenger (package:flutter/src/services/platform_channel.dart:140:62)
E/flutter ( 1511): #3      MethodChannel.setMethodCallHandler (package:flutter/src/services/platform_channel.dart:368:5)
E/flutter ( 1511): #4      new MethodChannelFirestore (package:cloud_firestore_platform_interface/src/method_channel/method_channel_firestore.dart:27:13)
E/flutter ( 1511): #5      FirestorePlatform.instance (package:cloud_firestore_platform_interface/cloud_firestore_platform_interface.dart:63:19)
E/flutter ( 1511): #6      new Firestore (package:cloud_firestore/src/firestore.dart:26:42)
E/flutter ( 1511): #7      Firestore.instance (package:cloud_firestore/src/firestore.dart:29:36)
E/flutter ( 1511): #8      main (package:guerra/main.dart:6:13)
E/flutter ( 1511): #9      _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:239:25)
E/flutter ( 1511): #10     _rootRun (dart:async/zone.dart:1126:13)
E/flutter ( 1511): #11     _CustomZone.run (dart:async/zone.dart:1023:19)
E/flutter ( 1511): #12     _runZoned (dart:async/zone.dart:1518:10)
E/flutter ( 1511): #13     runZoned (dart:async/zone.dart:1502:12)
E/flutter ( 1511): #14     _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:231:5)
E/flutter ( 1511): #15     _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:307:19)
E/flutter ( 1511): #16     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:174:12)
E/flutter ( 1511):

Answer: Você fez tudo certinho, mas como você está acessando o Firestore antes do runApp() é necessário tu acrescentar esse código WidgetsFlutterBinding.ensureInitialized();
void main(){

  WidgetsFlutterBinding.ensureInitialized();

  Firestore.instance
    .collection("usuarios")
    .document("pontuacao")
    .setData({"carlos" : "80", "silvana": "340"});

  runApp(App());

}

Dica
O Flutter facilita muito as coisas para nós, até mesmo nos erros...
Se você tivesse prestado um pouquinho mais de atenção na segunda linha do erro, teria notado o seguinte:

E/flutter ( 1511): If you're running an application and need to access
  the binary messenger before runApp() has been called (for example,
  during plugin initialization), then you need to explicitly call the
  WidgetsFlutterBinding.ensureInitialized() first.
Answer: O problema é que você esta tentanto utilizar o firebase antes de inicializar o app e o próprio firebase. tente da seguinte forma:
void main(){
  runApp(App());
}

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      // Initialize FlutterFire
      future: Firebase.initializeApp(),
      builder: (context, snapshot) {
        // Check for errors
        if (snapshot.hasError) {
          return Text('ERRO');
        }

        if (snapshot.connectionState == ConnectionState.done) {
          Firestore.instance
           .collection("usuarios")
           .document("pontuacao")
           .setData({"carlos" : "80", "silvana": "340"});

          return Container();
        }
        return CircularProgressIndicator();
      },
    );
  }
}

Com isso os dados serão salvos após a inicialização ser completada


Adding tables on the master - mysql database replication

Question: I have a simple MySQL replication system set up with a single master and a single slave.  If I add a table to the master, will it show up on the slave?  If I add a column, will it show up on the slave?  How about deletes?
This question can be encapsulated in:
How exactly do schema changes work in simple MySQL replication systems?
Answer: Yes, schema changes replicate as any other event.  MySQL slaves replicate master's binary logs into a relay log and then executes the events.  Of course, this is if replicate-do-db or another variable identifies the specific scope in question to execute the statements.
There was a bug in MySQL, where if you executed alterations by specifying the table as database.table, it would not replicate.  It required a use statement to proceed the queries that matched a replicate-do variable to actually execute the queries.  I believe this is addressed in the current version but is still something to be aware of.
This functionality is well documented on the MySQL Web site.
Comment: I ran into this bug yesterday myself. At least I assume that is the issue. Our replication, according to master and slave status, is working properly. However, there is a data discrepancy. Basically I did this:
update ss_central.styles set style_css = (select style_css from `central_bak_7-14-10-2`.styles where
style_number = $style_number) where style_number = $style_number
Answer: If you add a table to the master, it will show up on the slave. If you add a column, it will show up on the slave. If you delete a column, it will delete from the slave.
Without replication filters, MySQL replicates all data and schema changes. Creation and deletion of databases too.
Having said that, I strongly advocate against replication filters.
See MySQL says replication is fine but data is not copied
For most applications, leaving it wide open is perfectly fine.


Process of carrying out a BER Test

Question: I am subscribed to an ISP supplying a 3meg ADSL line.
Lately (for the last 4 weeks) speeds have dropped from the usual average downstream speed of ~250kbps to just 0.14Mbps (according to speedtest.net) and employees are complaining about lack of access to the server.
I have been calling customer support and logging calls for the last 3 weeks, but they have been unable to determine the source of the problem other than carrying out a few bitstream tests and checking the DHCP renewal times.
I am going to call back and suggest carrying out a BER test. What type of equipment is needed to carry out this test? I have access to a wide range of Cisco networking equipment.
Other: We don't need a leased line as there are less than ten employees.
Answer: A BER test usually requires a loop plug, but some DSL modems are also capable of acting as the loop end (or as a receiver/transmitter for the BER test, which is useful for determining if you have a problem that's only tied to upstream or downstream data).
Double-check with your telco / DSL provider for the procedure they use.
Answer: It is great you have been patient.  Do you have other means of accessing the internet at you location, like CATV, other provider?  After three weeks, it is time to be mean.  Your next call starts with the Tier 1 tell them you have been patient and that you want to speak to the supervisor.  If they don't give the correct response, speak to theirs.
In the past I dealt with a similar situation, though I don't go weeks when someone is taking my money for a service they are not providing, by calling the corporate office and asking to speak with the President / CEO.  Of course I didn't speak to them, but they usually have a person to field those kinds of complaints.  My problem was fixed within hours.

Process of carrying out a BER Test


Full name rather than the domain id in User.Identity.Name

Question: The User.Identity.Name property returns the domain login id.
Which class/property exposes the actual user name?
For user "John Doe" who logs into the web application supplying my_domain\jdoe
**User.Identity.Name -**
Returns : *my_domain\jdoe*

**System.Environment.UserName**
Returns: *jdoe*

Which class/property returns? ... "John Doe"
Comment: @adsi_help, what does WindowsIdentity.GetCurrent.Name return?
Comment: Is there anyone who can explain how this works, is it something unique to IIS or is it part of HTTP?  Can this be replicated with Apache for example?
Answer: If you are thinking Active Directory, you'll need to find the UserPrincipal that corresponds to the given samAccountName and get the DisplayName property from it.  Note that it may not be set.
string fullName = null;
using (PrincipalContext context = new PrincipalContext( ContextType.Domain ))
{
    using (UserPrincipal user
            = UserPrincipal.FindByIdentity( context,
                                            User.Identity.Name ))
    {
        if (user != null)
        {
            fullName = user.DisplayName;
        }
    }
}

Comment: Nicely done; note that adding a reference to assembly ` System.DirectoryServices.AccountManagement` must be added, as well as a `using System.DirectoryServices.AccountManagement;` statement.
Comment: When I try this on my local machine (debug in VS) it works.  When I deploy to my server it get NETWORK SERVICE.  It must be a setting somewhere but I can't figure it out.  Any ideas?
Comment: Did you try my sample using User.Identity.Name as well as Environment.UserName?  For a web app, I think you'll need to use the former (I'll update my post).
Answer: Sounds like instead of the login name, you are after the display name of an Active Directory user account.  What you might want to do is to do an AD search (DirectorySearcher) and get the display name from the search result property.
I'm assuming that you are in an AD environment, since you tagged the question adsi.
Note: If you are working with .NET 3.5, you might want to look at tvanfosson's post.
Comment: Use the new UserPrincipal if you have .Net 3.5 in the System.DirectoryServices.AccountManagement namespace instead.  It's a much better interface to the directory objects.  It exposes more properties that you used to have to get the IADsUser object for.
Comment: Actually, I think it was new in .Net 3.0, not 3.5.
Comment: Thanks tvanfosson! My job working with DirectoryServices ended with .NET 2.0. I'm working in a different area now and did not look at what was new in 3.5.
Answer: The IIdentity interface is that which provides the Name property on User.Identity.  The IIdentity interface can be implemented on any number of classes which know how to lookup users from a data-store (SQL Server, Active Directory, etc).
There is no property of the IIdentity interface which provides "John Doe".  If that information is located in your data-store then you'll need to use the tools specific to that data-store to access it.
That said, its entirely possible that the object which is returned by User.Identity has a property which contains "John Doe" that you might be able to access through some other interface besides IIdentity (our custom IIdentity implementation does this, for example).
Answer: using System.DirectoryServices;

public static string GetFullName(string strLogin)
    {
        string str = "";
        string strDomain;
        string strName;

        // Parse the string to check if domain name is present.
        int idx = strLogin.IndexOf('\\');
        if (idx == -1)
        {
            idx = strLogin.IndexOf('@');
        }

        if (idx != -1)
        {
            strDomain = strLogin.Substring(0, idx);
            strName = strLogin.Substring(idx + 1);
        }
        else
        {
            strDomain = Environment.MachineName;
            strName = strLogin;
        }

        DirectoryEntry obDirEntry = null;
        try
        {
            obDirEntry = new DirectoryEntry("WinNT://" + strDomain + "/" + strName);
            System.DirectoryServices.PropertyCollection coll = obDirEntry.Properties;
            object obVal = coll["FullName"].Value;
            str = obVal.ToString();
        }
        catch (Exception ex)
        {
            str = ex.Message;
        }
        return str;
    }

and the you can just call
var strJonDoeName = GetFullName(User.Identity.Name)

code mock it from here
Answer: Maybe I have made a mistake somewhere, but WinNT://... hasn't worked for domain accounts for me. Additionally, if the user isn't in the same domain as the machine, than PrincipalContext may not find the wanted element (as it searches in the current context, if used as above).
The following should translate the "friendly domain name" as provided by User.Identity.Name to an ldap compliant domain. Using the distinguishName of the domain delivers the needed ldap path information (which has solved my cross domain problem):
(VB.NET, sorry)
Imports System.DirectoryServices
Imports System.DirectoryServices.AccountManagement
Imports System.DirectoryServices.ActiveDirectory
...

Dim strUserName As String
Dim objDirContext As DirectoryContext
Dim objContext As PrincipalContext
Dim objPrincipal As Principal
Dim strLDAPDomainPath As String
...

// User.Identity.Name delivers domain\account or account@domain
// Split User.Identity.Name in domain and account as specified above
strDomain = "my_domain"
strAccount = "jdoe"

// Get LDAP domain relative path (distinguishName) from short domain name (e.g. my_domain -> us.my_domain.com -> DC=us,DC=my_domain,DC=com)
Try
    objDirContext = New DirectoryContext(DirectoryContextType.Domain, strDomain)
    strLDAPDomainPath = Domain.GetDomain(objDirContext).GetDirectoryEntry.Properties("distinguishedName").Value.ToString
Catch objException As DirectoryServicesCOMException
    Throw New Exception("Couldn't get LDAP domain: " & objException.Message)
End Try

// Find user in LDAP
// Nothing results in using current domain controller
Try
   objContext = New PrincipalContext(ContextType.Domain, Nothing, strLDAPDomainPath)
   objPrincipal = Principal.FindByIdentity(objContext, IdentityType.Name, strAccount)

   If Not IsNothing(objPrincipal) Then
      strUserName = objPrincipal.DisplayName
   End If
Catch objException As Exception
   Throw New Exception("Couldn't get user display name: " & objException.Message)
End Try

// strUserName should now contain the wanted full name

Comment: Thanks, as you stated, the WinNT method above did not work. Your code worked like a charm.  Thanks!
Answer: It's now 15 years past the original post, and tvanfosson's post above works great, but now, you can drop most of that code and simply use:
string fullName = UserPrincipal.Current.DisplayName;

This has been tested to work in .NET 4.8


HELP me to find the value of Re(z)+Im(z)

Question: z is complex .
$z=(-1+i)^{2008}+(1+i)^{2008}$,
the value of Re(z)+Im(z)=...
Comment: Update the exponent! We are in 2013.
Comment: this question from my teacher, not me :)
Answer: Hint:$$z=(-1+i)^{2008}+(1+i)^{2008}=(\sqrt2e^{i\frac{3\pi}{4}})^{2008}+(\sqrt2e^{i\frac{\pi}{4}})^{2008}=$$$$=\sqrt2^{2008}+\sqrt2^{2008}=2^{1005}$$
Comment: :ok, thanks :))
Answer: $$-1+i=\sqrt[2]2\,e^{\frac{3\pi i}{4}}\;,\;\;\;1+i=\sqrt[2]2\,e^{\frac{\pi i}{4}}\Longrightarrow\;$$
$$\Longrightarrow(-1+1)^{2008}+(1+i)^{2008}=2^{1004}\left(e^{1512\pi i}+e^{502\pi i}\right)=\ldots$$
Comment: ok, thanks :))...


Adjusted R2 and bias

Question: Consider the population $R^2$:
\begin{equation}
\rho^2 = 1- \frac{\sigma^{2}_u}{\sigma^{2}_y}
\end{equation}
This equation describes the proportion of the variation in $y$ in the population explained by the independent variables.
Suppose I want to find unbiased estimators for $\sigma^{2}_u$ and $\sigma^{2}_y$, respectively. This task is not accurately accomplished by the typical $R^2$ because it estimates $\sigma^{2}_u$ and $\sigma^{2}_y$ using $RSS/n$ and $(TSS/n)$, respectively, both of which are biased. Here, $RSS$ denotes the sum of squared residuals, and $TSS$ denotes the total sum of squares.
To obtain the adjusted R-squared $\bar{R}^2$, I use unbiased estimators for $\sigma^{2}_u$ and $\sigma^{2}_y$, which are $\frac{RSS}{n-k-1}$ and $\frac{TSS}{n-1}$, respectively. Thus,
\begin{equation}
\bar{R}^2 = 1- \frac{RSS/(n-k-1)}{TSS/(n-1)}
\end{equation}
Why is $\bar{R}^2$ not unbiased? Why is the ratio of two unbiased estimators not unbiased? Can you provide some intuition?
Comment: One small point: It's the amount of variance explained by the model.  If you did OLS regression then that would be by the linear relationship. But it's possible that some other model with the same variables would do better (e.g. try fitting OLS to something cyclical).
Comment: Apply Jensen's Inequality to the function $(x,y)\to (y/x)$ defined in the first quadrant.
Answer:
Why is the ratio of two unbiased estimators not unbiased?

Consider two uncorrelated random variables, X and Y each with finite expectation.
We immediately have $E[XY]=E(X)\cdot E(Y)$
But in general $E[1/Y] \neq 1/E[Y]$. So even if X and Y were independent, while you would then have $E[X/Y]=E(X)\cdot E(1/Y)$, you don't in general have $E[X/Y]=E(X)\cdot 1/E(Y)$.
In short,  ratios of independent  unbiased estimators with positive denominator are not unbiased for the ratio of their estimates.
Indeed, if we're  dealing with strictly positive $Y$, then special cases aside, Y and its inverse will be negatively correlated, which implies that $E(Y) \, E(1/Y)>1$. We have
$\text{Cov}(Y\cdot \frac{1}{Y})$ $=E(\frac{Y}{Y})-E(Y)E(\frac{1}{Y})$ $=1-E(Y)E(\frac{1}{Y})$, so negative covariance $\implies E(Y)E(\frac{1}{Y})\,>\,1$, or $1/E(Y)<E(\frac{1}{Y})$.  Hence, in that case,  $E(X)/E(Y)<E(X/Y)$ (under independence).
It may help your intuition a little to simulate random numbers from a variety of distributions with support restricted to within the positive half-line that have finite mean and non-zero variance, and see that the mean of the reciprocal is larger than the reciprocal of the mean.
Here's a quick example with a couple of distributions in R, but you could do something similar in most stats programs, or even in a spreadsheet:
<code>> x = runif(100000,.1,1.1)
> mean(1/x)
[1] 2.396524
> 1/mean(x)
[1] 1.666545

> x=rgamma(100000,3,1)
> mean(1/x)
[1] 0.4984561
> 1/mean(x)
[1] 0.3331215
</code>
Try it with your favourite dozen weird distributions. (See if you can break it.)
While so far this is simply motivation for the direction of bias (I didn't prove negative correlation for Y and its inverse,  nor state the conditions for it to hold), a more  formal argument can be constructed. For example it follows from Jensen's inequality.

Adjusted R2 and bias


Nginx - server change - redirect all traffic to new ip address?

Question: I want to change the server of a website and usually the way of doing it, is this:

Check the TTL of the domain which points to the current IP address.
Change the A-Record of the the current domain to point to the new IP address.

But in this case there are still requests, that will point to the current IP address until all nameservers understood the change.
How can I prevent that? Is the NGINX reverse proxy the right tool to direct all traffic to the new IP address? And if so, do I just need to do it this way on the current server and thats it?
location ~ \ {
    proxy_pass http://newipaddress:8000;
}

Thanks!
Answer: The reverse proxy is the perfect tool for this kind of change for a number of reasons. Here are a few:

As you mentioned some name servers will provide the old ip address to the clients, so some clients will request the old server
with DNS change you would need a new public ip address or at least change your nat configuration on your corporate firewall
in the case there are failures on the new server switching back takes more time due to ttl

So to sum it up: Changing the backend ip on the nginx minimizes changes on the corporate firewall and gives you the possibility to switch very quickly.
Configuration as you mentioned is just:
location ~ \ {
   proxy_pass http://newipaddress:8000;
}

Site note: Alternatively you could write the ip addresses of your backend server and a fitting hostname in your /etc/hosts file and mention this hostname in your proxy_pass directive. This has the advantage that in case of switching servers you just would need to change the entry in /etc/hosts instead of changing multiple configuration files.


Cross Staff Beaming in parts using more than two staves

Question: So I have two somewhat related questions. Firstly, is there a native way in lilypond to work with piano scores with more than two staves? I am hopefully beginning work on a project soon where I will be working with a three staff piano part, and the PianoStaff environment doesn't seem to support having more than two staves. I've been doing some setup and doing a StaffGroup with three staves seems to work fine for the most part but it does change the bracket on the side and I would like to get the curly piano style brace back.
Relatedly, is it possible to utilise cross-staff beaming within StaffGroup and not in a PianoStaff? I've tried just copying and pasting from the official documentation (here), but it doesn't seem to work. I think it's because I have my staves in the score environment rather than just writing directly into the staves as in the examples. I am working with the template from the wizard in Frescobaldi, should I change this, or am I just missing something obvious?
Answer: I think you must be doing something wrong if you find that you cannot fit more than two staves into a PianoStaff. It's a completely general construct and it can contain as many staves as you want. Just put three staves into the PianoStaff like this:
\new PianoStaff \with {
    instrumentName = "Piano"
}
<<
    \new Staff = "top" { ... }
    \new Staff = "middle" { ... }
    \new Staff = "bottom" { ... }
>>

You would then use \change Staff = "top", \change Staff = "middle" or \change Staff = "bottom" in your music, and it should Just Work™. (Just make sure that you change between adjacent staves. Otherwise you will probably get something unreadable .) Here's a little working example for you to play with: http://lilybin.com/prh0gd/1 .
By the way, you can even put staves of different types in it. As an example, I write some guitar arrangements of video game music, and sooner or later, I plan to put them on the Net. Hence, to "appease the crowds" that are always hungry for tabs, I also compile (among others) a version that has a PianoStaff with the standard notation staff and a TabStaff. In some places, I even have two standard staves and a TabStaff, which gives a result like this:

So, as you can see, having three staves in a PianoStaff is perfectly possible.
P. S.: I would be able to help you more if you posted a bit of code that does something else than you expect.
Comment: @JackDoherty, yeah, you could have missed a brace or a quote and you could get an error in a totally unrelated place. Sadly, that's how programming goes. And yes, if you want to change staves, the target staff must exist, so you need to fill it with something (even if it were only spacer rests) up to the point where the change occurs.
Comment: I don't know what I must have been doing last night, but I am sure that I tried putting three staves in a PianoStaff and it was throwing errors, but this morning I tried and it worked fine. There must have been a typo I kept making or something.

Also, for the cross staff beaming, I think what was happening was because I had not filled the above staff with rests properly, it wasn't working. I misunderstood the "keep the bar alive" thing in the documentation.


How to obtain the probability that a gaussian variable is strictly positive?

Question: I am confused that which probability does the integral $\int_{0}^\infty \text{(pdf of gaussian) } dx$ equal to?
(1) the probability $P(X\geq 0)$
(2) $P(X>0)$
I believe it is equal to (1) , then my follow-up question is how to obtain the probability (2)?
This confused my a lot, since in my case, i would need to prove a variable is strictly positive, there is no chance for it to be zero.
Comment: They have the same probability.
Comment: @JoshuaTilley this confused my a lot, since in my case, i would need to prove a variable is strictly positive, there is no chance for it to be zero.
Comment: Is this question too trivial for everyone so there are many downvoted?
Comment: What does "no chance" mean in the context of this question? The other commenters tell you $P[X=0]=0$, which is the best that the theory of probability can tell you.  What is not clear to us whether you are asking if it is impossible for $X=0$ or if you are asking if $P[X=0]=0$, or even if you know the difference between the two statements.  That's probably the source of the downvotes: an unclear formulation of your question.
Comment: thanks for providing this. But 'it is impossible for $X=0$' is equivalent to '$P(X=0)=0$' right?
Comment: You can bet on $X\ne0$ but probability theory really does not actually rule $X=0$ out as being a logical impossibility.  That is, the event $[X=0]$ is a non-empty event that just happens to have probability $0$.  There are lots of other such events, including all events of form $[X=a]$ for each particular real number $a$.
Comment: @kimchilover Yes, $P(X=0)$ is really zero. But, could we rule out the event $X=0$? Lets say, although for each possible value of a continues random variable, the probability $X=a$ is zero, but the event $X=1$ still happens. For example, suppose $X$ to be the height of person, the event $X=1.7m$ still happens.
Comment: $P(X \ge 0) = P(X > 0)$ for any continuous distribution (such as the Gaussian distribution). Therefore, the integral in the question is equal to both ($1$) and ($2$).
Answer: The statement that $X$ is a $N(0,1)$ random variable implies, among other things, that $P[X\ge0]=P[X>0] = 1/2$ and $P[X=0]=0$.
But, in the standard measure-theoretic formulation of what a random variable is, one cannot tell if the event  $[X=0]$ is the empty set, or just a set that happens to have probability $0$. One cannot conclude from $X\sim N(0,1)$ that $X=0$ is impossible, only that $P[X=0]=0$.
Suppose (in the notation of the cited Wikipedia page) that the underlying probability space $(\Omega,\mathcal F, P)$ is $((0,1),\mathcal B(0,1), \lambda)$, where $\mathcal B(0,0)$ is the Borel sets in $(0,1)$ and $\lambda$ is Lebesgue measure, and the random variable $X(\omega)=\Phi^{-1}(\omega)$, where $\Phi$ is cdf of the $N(0,1)$ distribution.   Now, define a new random variable $Y$ by the formula $$Y(\omega)=\begin{cases}X(\omega)&\omega\ne1/2\\17&\omega=1/2.\end{cases}$$
The random variables are (referring to the cited Wikipedia paragraph) equal in distribution (both  are $N(0,1)$-distributed), equal almost surely (because $P[X\ne Y]=0$), but not equal as functions on $\Omega$.  The event $[X=0]$ is  the set $\{1/2\}\subset \Omega$, which has Lebesgue measure $0$, but the event $[Y=0]$ is the empty set, which also has Lebesgue measure $0$.  The event $[X=17]$ is the set $\{\Phi(17)\}$ which has Lebesgue measure $0$, and the event $[Y=17]$ is the set $\{1/2,\Phi(17)\}$ whose Lebesgue measure is also $0$.


How to import spring bean's configuration file in Maven dependency to an other in my Maven project?

Question: I add local maven repository, I add the local dependency in my project.
this dependency encompass a Spring configuration file .
I want to import this file in an other spring configuration file.
What should I do ?

knowing that the dependency tree that includes the file to be imported is as follows:
{dependencyXXX}.jar>{PackageByDefault}>springInjectDateAsString.xml
Answer: You should be able to just put this in your application context:
<code><import resource="classpath*:/springInjectDateAsString.xml" />
</code>
Comment: as a reward, I offer the following jar and maven installation with:  Download this jar :  http://dl.dropbox.com/u/60615128/delivred/abdennour/spring/springBeansReadyByAbdennour22.214.171.124.jar                              To Install :
mvn install:install-file  -Dfile=/springBeansReadyByAbdennour184.108.40.206.jar -DgroupId=slm.abdennour.tn.archetypes -DartifactId=abdennour-java-quickstart -Dversion=18.104.22.168 -Dpackaging=jar -DlocalRepositoryPath=/.m2/repository


How can i redirect a user with devise and cancan in rails 3 when the user comes back to the site and is still logged in?

Question: I am trying to find a way to redirect a user when they come back to the site if they are still logged in. I want them to be redirected to their specific home page. I am using rails 3, devise, and cancan.
Comment: Why would you want to do this? If I leave your site and then come back I probably am coming back to a specific page, in that case I wouldn't want to be redirected. If you want logged-in users to see a custom home page ONLY in place of the normal home page, then just put that as a condition whatever controller you're using for your root path.
Answer: Devise provides the method user_signed_in? that you could user to check if the user is already logged in.  Then you could use current_user to find the home page for the given user.
I would add something like this to the controller that user go through to get to your home page:
if user_signed_in?
  redirect_to current_user.home_page_path
end

Note - This is assuming that your devise model is called User and you have added a method for home_page_path to the user model.
Comment: Good answer. As I commented above -- this code should go in whatever controller action you have assigned to :root.
Answer: The Devise wiki describes a few potential redirect solutions. You'll want to be careful using the user_signed_in? helper, as it will redirect any user that is signed in, rather than users that have just signed in.


Trigger a event on Zoom change SAPUI5

Question: I want an event to be triggered when zoom of the map changes. I am using
sapui5 google maps.  In my view.xml i bound the map as following
<gmaps:Map id="map1" class="googleMap" height="600px" width="100%" zoom="4" lat="100" lng=100" markers="{/co}" ready="onMapReady"  zoomControl = 'true'
zoom_changed  = "renderNewMap">

But it doesn't trigger the event.
Comment: https://developers.google.com/maps/documentation/javascript/events#EventsOverview a couple of lines of code to a add zoom_changed handler, contributions welcome
Comment: just checked zoom_change event already been handled in the code, further to that idle is triggered also, therefore no need to add your own event as the "ready" event is fired
Comment: Please don't delete posts that people have just answered for you.  It makes us regret even trying to help you in the first place.  You can accept an answer that has been provided to show the community you now understand the solution.
Comment: Which post are you referring to??
Answer: I'm afraid John Patterson's Google Maps control doesn't have a zoom event. According to Map.js on Github, only a click and ready event are present.
However, this control is open source though, meaning that you have the possibility to add whatever you think is missing in a subclass, or even your own version of this control.
If you make any useful modifications that could be useful for other people as well, it would also show good etiquette, if you could submit your changes in a pull request. In the open source community this is considered saying "thank  you". When you make a pull request, John could then easily include your contributions in future releases of the Google Maps control.

Trigger a event on Zoom change SAPUI5


Question of putting Roman Numerals on a chord sequence I have

Question: I only have a little knowledge of music theory and was unable to work out how to use roman numerals to denote a chord sequence of one of my old tunes which starts in Fm. I have listed the chord sequence a follows:
Fm  Ebm F#m Bbm played twice, then, Fm Ebm Em  Dm Bdim A
I know this has a modulation at the end but I don't know how to set Roman Numerals to the chords.
Comment: Can I ask what "pluutin" is?
Comment: @Richard "Question of *putting* Roman Numerals on a chord sequence [he has]."
Answer: Roman numerals can be really helpful for music the follows traditional harmonic syntax. But if music is really chromatic, sometimes Roman numerals really aren't helpful at all. Unfortunately, I think your progression is one such case: we can stick Roman numerals to the chords, but it won't tell us much (if anything) that's helpful.

Fm   E♭m  F♯m  Bbm  Fm   E♭m  Em   Dm   B°   A
i    vii  ♭ii  iv   i    vii  v    iv   ii°  I
          ***                 ###

Two caveats of the above progression:

The chord marked *** I have interpreted enharmonically as G♭ minor so as to understand it as ♭II (a modified Neapolitan chord).
The chords beginning at ### are no longer understood in F minor, but in A.

Since Roman numerals aren't all that helpful, we can perhaps better understand this progression as an example of planing. Planing is when we take a particular chord type and just move it up and down in musical space. In this case, you plane a root-position minor chord and move it up and down through the chromatic universe, and then you use it to reach a pretty clear iv–ii°–I cadence in A major.
Comment: Thank you for explaining this Richard, I shall go on learning music theory as best I can.
Answer: Roman Numeral Analysis wouldn't do much good for chord progressions like these because it's not clear what key these progressions belong to, especially the second progression. Something important to note about music theory, compared to other lofty kinds of theory (physics, mathematics, etc) is that music theory does not dictate how one should or shouldn't write. It simply allows us to communicate what's happening in the music in a succinct, formal, and analytic format. What I see in your progression is, instead, a root-movement relationship built on intervals. However just because that's what I see in there does not magically mean that's why you wrote it that way.
The first progression could be said to be "constant structure" minor chords (i.e., entirely minor chords) built upon an increasingly large root movement: Major second/diminished third between Fm/Ebm, minor third between Ebm/F#m, and major third between F#m/Bbm. The second progression looks to me like a chain of seconds of varying sizes: Fm->Ebm = M2, Ebm->Em = m2, Em->Dm = M2, Dm->Bdim = A2(m3), Bdim->A = M2. The diminished and major chords in this progression provide significant color differentiation to break up the monotony of the minor chords.
This is simply how I would explain the construction of these progressions, and I'm sure several other people would have different analyses as well.
Comment: Your second and third sentences should be carved into stone!
Comment: Your explanation is of great interest to me as I knew that most of the chords were not in the key, but borrowed from other keys and therefore it is not helpful to apply roman numerals to them, I don't think the piece really modulates till the Em but feels like it modulates only at the end Bdim to A when set with the tune (top notes).


How to make select option works like a button?

Question: I have created a contact form by using webform module, in that I have added one component as reset and the type is select options.
My requirement is when I choose this reset option from that dropdown and submitted the form, I want to reset my form. I have no idea how can I achieve this. I tried following but not worked, please help me regarding this.
function test_form_alter(&$form, &$form_state, $form_id) {
   if ($form_id == 'webform_client_form_111') {
    $form['submitted']['reset']['#option'] = 'test_reset';
  }
}
function test_reset(&$form, &$form_state){
  $form_state['rebuild'] = FALSE;
}

Answer: You can write a simple jQuery script for achieving this.
$('select').on('change', function() {     // you can refine this with your field id.
  if( this.value == 'reset' ) {           // Replace value for your 'reset' option.
    $('#yourid').find('form')[0].reset(); // Replace id here
  }
})


Example of union of closures that is a proper subset of the closure of the union

Question:
Let $A_j, j\in J$ be a family of subsets of a topologic space $X$. Show that $\cup_j \overline{A_j} \subset \overline{\cup_j A_j}$ and show an example where it's a proper subset.

I thought in $X = \mathbb{R}$ and $A_n = \left(\frac{1}{n+1}, \frac{1}{n}\right), n\in \mathbb{N}$. So we have
$$
\bigcup_{n\in\mathbb{N}}\overline{A_n} = \bigcup_{n\in\mathbb{N}}\left[\frac{1}{n+1}, \frac{1}{n}\right] = (0,1]
$$
and
$$
\overline{\bigcup_{n\in\mathbb{N}}A_n} = \overline{(0,1)-\{1/n : n\in\mathbb{N}\}} = [0,1]
$$
Is this right? The last equality I think is due to every $1/n$ being a limit point of the union of the intervals $A_n$. But I don't see how to prove this much properly, so I don't know if my example is right. Any help will be appreciated.
Comment: Where does the $(0,1)-\{1/n \colon n \in \mathbb{N}\}$ come from? I don't understand that part, but everything else is correct.
Comment: $$\begin{align} A_i \subseteq \bigcup\limits_{j} A_j,\ \text {for all}\ i. \\ \implies \overline {A_i} \subseteq \overline {\bigcup\limits_{j} A_j},\ \text {for all}\ i. \\ \implies \bigcup\limits_{j} \overline {A_j} \subseteq \overline {\bigcup\limits_{j} A_j}. \end{align}$$
Comment: For the converse observe that $$\begin{align} A_j \subseteq \overline {A_j},\ \text{for all}\ j. \\ \implies \bigcup\limits_{j} A_j \subseteq \bigcup\limits_{j} \overline{A_j}. \\ \implies \overline {\bigcup\limits_{j} A_{j}} \subseteq \overline {\bigcup\limits_{j} \overline {A_{j}}} \subseteq \bigcup\limits_{j} \overline {A_{j}}. \end{align}$$
Comment: So in order to find the counter example you need to find a collection of sets $\{A_j \}$ in a topological space such that $\bigcup\limits_{j} \overline {A_{j}}$ is not closed. Clearly then the collection should be infinite. Since $(0,1]$ is not a closed subset of $\Bbb R$ with usual topology your example is perfectly fine to me.
Comment: In your example $\bigcup\limits_{n \in \Bbb N} A_{n} = (0,1).$ So $\overline {\bigcup\limits_{n \in \Bbb N} A_{n}} = [0,1].$
Answer: Consider a bijection $\varphi : \mathbb{N} \rightarrow \mathbb{Q}$.
For each $j \in \mathbb{N}$, let $A_j = \lbrace \varphi(j) \rbrace$. For the usual topology on $X = \mathbb{R}$, $A_j$ is closed as a single point. So
$$\bigcup_{j \in \mathbb{N}} \overline{A_j} = \bigcup_{j \in \mathbb{N}} \lbrace \varphi(j) \rbrace = \mathbb{Q}$$
But
$$\overline{\bigcup_{j \in \mathbb{N}} A_j } = \overline{ \bigcup_{j \in \mathbb{N}} \lbrace \varphi(j) \rbrace} = \overline{\mathbb{Q}} = \mathbb{R}$$


Multitouch image that plays sound after a certain sequence

Question: I am confused how to start building an application like below.
Scenario: I have an image where two bells(bell-1,bell-2) hanging like pendulum.My purpose are-

If i sweep bell-1,it will go right side and back to left side(what a pendulum does) and makes sound.
If i sweep bell-2,it will do like bell-1.
If i sweep bell-1 and bell-2, both bells will go left to right to left (like pendulum) and makes sound.

My question is : What is the best way to do an application like this which will support all android devices.
Any help like document,links or advice will be highly appreciated.
Answer: I thinkg you have two major tasks.

create a pendulam
play multiple sounds

to create a pendulam you can see this project. To specify the animation from xml here is a key part
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
  android:fromDegrees="15"
  android:toDegrees="-15"
  android:pivotX="50%"
  android:pivotY="0%"
  android:duration="2000"
  android:repeatMode="reverse"
  android:repeatCount="-1"/>

And to play multiple sounds use SoundPool. You can find plenty of examples out there.


How to transform Excel Data

Question: I have data coming into Excel (from external source) that looks like:
**Column A**          **Column B**
6/26/2017             null
Temperature           27
Pressure              5
6/27/2017             null
Temperature           29
Pressure              4

I would like to have it like this:
**Column A (Date)**          **Column B (Temp)**          **Column C (PSI)**
6/26/2017                    27                           5
6/27/2017                    29                           4

Since the data comes in via 'Refresh All', how can I take that and push it to columns like this?
Comment: When you say "data coming from an external source", what do you mean exactly? Are you getting a CSV file? Are you connecting to a database in Excel?
Comment: How many column B's does your worksheet have?
Comment: Obviously that was a mistake.  Thanks for pointing it out.. Corrected.
Answer: If you are sure of the periodicity of your data, you may use the OFFSET function.

Add an auxiliary column with an crescent index;
fill the "column date" with =OFFSET($A$1; ($E2-1)*3; 0), where:

A1 refers to your first cell in your external data (6/26/2017)
E2 refers to your index, the cell where my function was applied being F2
Answer: If to be 'pushed' you would need something like VBA, though is possible with a formula (in C2, copied across to D2 and the pair copied down to suit):
=OFFSET(A2,1,1)

but that would then need to be converted to Values (eg with Paste Special) if the surplus column and rows are to be deleted. And this would not 'refresh' as easily as say a PivotTable.
Answer: Try working from the last date to the top.
Dim i As Long

With Worksheets(4)
    For i = Application.Match(1E+99, .Range("A:A")) To 1 Step -3
        .Cells(i, "C") = .Cells(i + 2, "B").Value
        .Cells(i, "B") = .Cells(i + 1, "B").Value
        .Cells(i + 1, "A").Resize(2, 1).EntireRow.Delete
    Next i
    .Cells(1, "A").EntireRow.Insert
    .Cells(1, "A").Resize(1, 3) = Array("**Column A (Date)**", "Column B (Temp)", "**Column C (PSI)**")
End With

How to transform Excel Data


Why Riemann integral is not direction invariant

Question: Denote for $f(x)$ - some Riemann integrable function.
Given a partition $\{x_0 = a, x_1, x_2, \ldots, x_n = b\}$ of $[a, b]$ we define a lower Darboux Sum
$\underline{S} = \sum\limits_{i}\min\limits_{x \in [x_{i-1}, x_i]}f(x)(x_i - x_{i-1})$ and respectively an upper Darboux Sum $\bar{S}$.
I see this as a sum of rectangle areas, where sign is only inherited from the value of $f(x)$, while $(x_i-x_{i-1})$ is just the length of the rectangle basis.

What bothers me, is that

the length of the rectangle basis is independent of the direction I'm
  looking on it (from right or from left), then why does the sign of the
  integral is not independent of the direction?

i.e., why
$$\int\limits_a^b f(x) \mathrm{d}x = -\int\limits_b^a f(x) \mathrm{d}x$$
Answer: For $a<b$, we define $\int_a^b f(x)\textrm{d}x$ as the supremum of the lower Darboux sums. On the other hand, we define $\int_b^a f(x)\textrm{d}x=-\int_a^b f(x)\textrm{d}x$ in order to make the identity
$$
\int_a^b f(x)\textrm{d}x+\int_b^c f(x)\textrm{d}x=\int_a^c f(x)\textrm{d}x
$$
hold no matter the relation of $a,b$ and $c$.
Alternatively, when integrating from $a$ to $b,$ you observe a partition $a=x_0<x_1<...x_n<b$ and observe the Riemann sums $\sum_{j=1}^n f(\xi) (x_j-x_{j-1})$. The analogous construction when integrating from $b$ to $a$ would be to observe a partion $b=x_0>x_1>...>x_n=a$ and the corresponding Riemann sums $\sum_{j=1}^n f(\xi) (x_j-x_{j-1})$, and here, the $x_j-x_{j-1}$ is a negative increment. This is another way to intuit that this convention might be useful.


Error When Hardcoding OpenAI API Key and when using .runtimeconfig in Firebase Function

Question: I'm working on integrating the OpenAI API with a Firebase project and encountering an issue when trying to hardcode the OpenAI API key or using functions.config().openai.key in a backend scheduled function. The function fails with an error stating that the OPENAI_API_KEY environment variable is missing or empty, despite the key being hardcoded.
Here's the relevant part of my code:
.runtimeconfig file:
{
  "openai": {
    "key": "secret-openai-api-key"
  },
  "mongodb": {
    "uri": "secret-mongo-uri"
  }
}

import OpenAI from "openai";

export const generateTextWithOpenAI = async (prompt: string): Promise<string> => {
  try {
    const openai = new OpenAI({
      apiKey: "My-hard-coded-api-key",
    });

    console.log("Starting request to openai API...");
    const chatCompletion = await openai.chat.completions.create({
      messages: [
        {
          role: "user",
          content: prompt,
        },
      ],
      model: "gpt-3.5-turbo",
    });

    return chatCompletion.choices[0].message.content ? chatCompletion.choices[0].message.content : "";
  } catch (error) {
    console.error("Error in generateTextWithOpenAI:", error);
    throw error;
  }
};

The error I get is as follows:

Error in generateTextWithOpenAI: OpenAIError: The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).

Strangely, when I use the API key from Firebase environment configuration in an endpoint it works fine in local testing but in production it gives me the same error as above.
openaiRouter.post("/generate-text", async (req, res) => {
  const prompt = req.body.prompt;
  // Retrieves the API key here
  const openaiApiKey = functions.config().openai.key;
  const openai = new OpenAI(openaiApiKey);

  try {
    console.log("Starting request to openai API...");
    const chatCompletion = await openai.chat.completions.create({
      messages: [
        {
          role: "user",
          content: prompt,
        },
      ],
      model: "gpt-3.5-turbo",
    });

    res.status(200).json(chatCompletion.choices[0].message.content);
  } catch (error) {
    errorResponse(error, res);
  }
});

I've checked the API key multiple times for accuracy and can confirm it is correct. Any ideas on what might be causing this issue or how to resolve it?
Answer: If this is a v2 function and on a newer version of the Firebase SDKs, functions.config() is no longer a thing. You have to use .env or secrets. The error even when hardcoding it's the same issue - Firebase is looking for the env or secret and not finding it, and that's before it runs your specific hardcoded function.


Unable to use Ampersand in Campaign Builder link

Question: Trying to create a campaign link to track in GA. However, our url contains ampersands (&&) &&searchid=so these are being cut from the campaign url. Since GA campaign links use amapersands as the variable separator, how can i get around this? I've also tried using the hex values %26 but this is also not working.
Comment: Actually there shouldn't be a problem with using ampersands - if there were campaign tagging would break the internet since ampersands are the standard delimiter for query string parameters. Can you post a url so we can see if there is some other problem ?
Answer: You could use the campaign tracking links anyway. For example:
www.example.com?utm_campaign=campaign-name&utm_source=source&utm_medium=medium

Would effectively be the same as if you started with something else, like this:
www.example.com?somequeryhere=somevalue&searchid=199&utm_campaign=campaign-name&utm_source=source&utm_medium=medium

As noted above, the campaign parameters for GA to work doesn't have to start with a ? to work.
Comment: Thanks, looks like this will work:  http://www.example.com/?
utm_source=xxxx&
utm_medium=xxxx&
utm_campaign=xxxxx#&&searchid=-123
Comment: Is this your real URL? Because you have alot of spacing in it which might be causing the values to be dropped. You should remove the blank spaces in the URL, otherwise it won't work. Or perhaps you used it intentionally just now for that example?
Comment: Spaces are intentional. Putting the searchid at the end of the campaign link seems to work fine.


Where in the database does fieldset and field instance info live?

Question: Background: I'm writing a module that will hopefully make reverse-engineering specs for site audits easier. (If you're interested, you can see the Topograph module-in-progress on my Github account.)
Basically it's a bunch of byzantine views that use custom handlers to pull things like serialized data out of the DB to display stuff like nodetype settings to the admin user.
I'm having a lot of trouble finding certain things, though. Fieldset info is a major one, as well as settings like whether the field is required. I'm not finding it in the blob of data pulled from the {field_config_instance} table (though I might be overlooking it). Can someone point me to where this info can be retrieved per nodetype/field instance?
Comment: i think field_config_instance for example only has like the `required` setting, if the parent field element options are altered in any way for a bundle (because fields can exist in many bundles) ... so i'm not sure you can rely on looking at 1 SQL table. thats why `field_get_info()` exists.
Comment: That function doesn't seem to exist, and the closest thing I could find, `field_info_field()`, doesn't seem to have fieldset or required info in the return value.
Comment: Does it have to be DB, or can you do it via the API?
Comment: Via the API works fine too.
Comment: `field_info_instance()` should do it, the 'required' setting is under 'settings' in that array. By fieldset info do you mean the stuff field_group provides? If so that's in the field_group table. If you're looking at the db structure in a GUI it's easy to miss the field_group table, it gets buried in amongst the field data/revision tables
Comment: im so tiredd :( im not 100% today
Comment: I found the field_group table, but it appears to be empty (in PHPMyAdmin) despite the fact that I have fieldgroups on several content types.
Answer: Whether a field is required or not can vary by content type (ie, the bundle).  I am pretty sure you need to use field_info_instances($entity_type, $bundle_name).  You can then use field_info_field($field_name) on the results.  Something like:
$fields_info = field_info_instances('node', $bundle);

foreach ($fields_info as $field_name => $instance) {
  $field_info = field_info_field($field_name);
}

dpm() both the $instance and $field_info.  Everything you need should be in those two variables.  This is a snippet from a dynamic exporter I have.
Comment: Fields don't have any related fieldset info as such, some modules (e.g. field_group) provide them but they're stored separately (in a table and as ctools exportables)
Comment: Neither fieldset nor required info is provided by `field_info_instances()` or `field_info_field()`. Clive, if you can tell me where field_group stores fieldset info, please do. I can't find it.
Comment: I will note as a comment, that I am not positive that the fieldset info is in there.
Comment: That makes sense.  I hardly every use groups.


What does "Parameters are fixed and data vary" in frequentists' term and "Parameters vary and data are fixed" in Bayesians' term exactly mean?

Question: I hear the sentence in my question a lot, I kind of understand what it means but never have a clear picture of it. Hope to get the clear picture of what the sentence exactly mean.
Answer: In frequentist philosophy, parameters are treated as non-random objects, while data are treated as random, hence "parameters are fixed and data vary".
In Bayesian philosophy, parameters are treated as random objects, and inference is performed by conditioning on an observed (fixed) set of data, hence "parameters vary and data are fixed". By parameters are treated as random objects, we mean parameters have a distribution, much like observations have distributions.
Note however, the interpretation is that this randomness reflects our belief of what the true underlying parameter is. In other words both Bayesians and frequentists agree that a true fixed parameter exists, but Bayesians further encode beliefs of what values this parameter might take on, in the form of a distribution.
To illustrate the difference in philosophies, consider an inference problem where we aim to construct an interval estimate for some parameter $\theta$ which is associated to the model by the sampling distribution whose density we denote as $f(X | \theta)$.
As a frequentist, you would infer a confidence interval, and a credible interval as a Bayesian.
Under the frequentist paradigm, you observe some data $X=x$ and construct a confidence interval by manipulating $x$, i.e., you have some function $C$ that maps $x$ to some interval. Because $X$ is a random variable, and $C$ is just a function of $X$, we are essentially constructing "random" interval estimates. The parameter is treated as a fixed, unknown constant. The meaning of confidence intervals is thus the probability of this random interval $C(X)$ capturing the fixed unknown constant $\theta$. Note this means if you observed say $100$ values of $x$, and you constructed a 95% confidence interval for each set of observations, you will capture $\theta$ for approximately $95$ of them.
Under the Bayesian paradigm, you begin by encoding your belief of what values the parameter might take on, say with a distribution $\pi_0$. Then you again observe some data $X=x$. To derive a credible interval you infer your updated belief,  encoded as a distribution called the posterior distribution, which we denote $\pi_1$. The posterior distribution is defined as
$$\pi_1(\theta | x) = \frac{f(x|\theta)\pi_0(\theta)}{p(x)}.$$
Here we see our posterior encodes our uncertainty of $\theta$ in the form of a distribution, much like how we encoded our belief prior to observing the data.
The data here is fixed in the sense that our estimate is conditioned upon what is observed. The credible interval is then taken as an interval of the posterior. The credible interval is interpreted as the probability of the parameter taking on values in the interval.
Comment: A statistical model is just a bunch of mathematical objects aimed to explain or describe how certain data came about. Loosely speaking, data are random in the sense that we don't know for certain how they were generated, and the best we can do is to posit they were drawn randomly from a distribution.
Comment: Thank you for the answer. One thing I am kind of still struggling is that how come data have distributions means data is random.
Comment: Great answer! Thank you!
Answer: In Bayesian statistics we condition upon the observed data. The Bayesian part of your statement means that the data are known (and hence fixed to known values) and that the parameters are unknown (and hence allowed to vary and take on any plausible values).
In frequentist statistics, on the other hand, we compare the observed data to data that could have been observed. So we consider all sorts of hypothetical data (the data isn't fixed). The fact that the parameters are fixed is a bit more nuanced. But essentially means that the results are not and do not use probability distributions for the unknown parameters. The frequentist results reduce to statements that assume specific values of the parameters or that are true for any assumed values. E.g., confidence intervals would reject the true parameters (whatever they are assumed to be) at a pre-specified rate.


How to Stretch Midi Notes and Position in Logic Pro X

Question: Reason 999 why FL studio is better than logic, but I want to use Alchemy so here we are.
In FL studio there is an easy option to stretch multiple midi notes and their placement so it is easier to change the duration of a melody or sequence of notes. Example if i had a melody that was 2 beats and I wanted it to change it so its 4 beats I can use command+a(on mac) and then there is a stretch icon to the right of the furthest note selected which allows me to do this.
However when I try this on Logic Pro the notes get stretched but they stay in the same place. I'll add some photos to show what i mean.
FL:

Logic:

Basically I want to know if there is a way to do this in Logic Pro X.
Answer: There are two ways to do this. If you want to double the length and spacing of all notes in a region, then press the option key while dragging the bottom right-hand corner of the region in the tracks window:
This...

...becomes this...

If you just want to edit some notes within a region (which I think is what you are showing), use the Half Speed function found in Functions->MIDI Transform:

Assuming you have selected the notes you want to edit, press Operate Only in the dialog window that opens:

Just one thing to be aware of: this won't change the region length, so you may need to now lengthen the region to see the moved notes.
As with all the MIDI Transform functions in Logic, this gives you a great deal of flexibility. By changing the two number values in the Half Speed window, you could for example, triple the spacing of the notes but half their length etc. etc.


How would you explain the A natural in bar 11?

Question: How would you explain the A natural in bar 11?
How would you explain that the phrase ends in bar 11 and not bar 12?
Answer: This melody could be harmonised in several ways.  But there's a strong implication that from bar 8 the music moves towards G minor, reaching a cadence in that key at bar 14. Hence the A♮ and F♯.  G minor chord has two notes in common with E♭ major, which makes the modulation connected, if somewhat novel.  (E♭ major to G MAJOR would be a 'Chromatic mediant', another common harmonic shift.)
Here's a version (I imagine the standard version?) that harmonises in this way.

Music doesn't have to fall into 4-bar phrases.  This piece has a 4, 3, 4, 3, 4 phrase structure.  Nice, isn't it!  Musical traditionalists might be tempted to add an extra bar (or perhaps a fermata) at bars 7 and 14 in order to even it out into 'correct' 4-bar phrases. (More so 100 years ago than now, perhaps.) I'm glad this version doesn't.
Comment: Eb major and G minor triads have two notes in common.  That's enough to make them sound connected.  But you can modulate anywhere!  There's no requirement to sound as if nothing's changed.
Comment: "There's no requirement to sound as if nothing's changed": indeed, it's rather the point of modulation to sound like something has changed, isn't it?
Comment: Yeah, I noticed that 4 - 3  cadence.  Makes for a nice "unfinished" feeling internal to the piece.
Comment: How is G minor connected to Eb major?


baseballreference.com reading the tables for player statistics (roger maris)

Question: I have been figuring out this site ok but I do not really understand why there are 3 entries for maris in 1958. If I want to figure out his home runs that season. Should I just add up all the 1958 or would there be a particular reason it has been entered 3 times like that instead of once for the whole year?

Here is the link http://www.baseball-reference.com/players/m/marisro01.shtml
Answer: I believe you mean 1958, and if you look at the column named "Tm", notice that of of the three rows for 1958 has "TOT" in that column.
That row contains the totals of the other two rows, so no need to do any extra work.
Note, too, that the stats grid has some power built into it where one can click on two rows that represent the beginning and end of a period to examine, and a pop-up will display the totals for that period.
For example, click on the first and last rows of Maris' stats, and the pop-up will produce totals that match the Career Totals row, i.e. the 1958 rows for CLE and KCA are not included in the totals because they're already accounted for by the 1958 TOT row.  In fact, clear the grid of the previous selection and try clicking on either of the rows that doesn't contain the totals and notice that the row isn't highlighted.  This is likely to prevent one from trying to include all three  1958 rows in one of these ad hoc summaries.  (Note: it also seems that clicking on one of those rows I've described short-circuits that summarization function completely, at least in Chrome on a Mac.)


Precisava de ajuda sobre posicionamento com flexbox

Question:

Commerce

Option1

Option2

Option3

Option4

Option5

Eu queria alinhar a parte "logo" na esquerda do menu, e a parte da class "menulinks" ficasse a direita e que ficasse tambem bem separada os "menulinks" com o da logo tipo uma margem, e que tambem ocupasse 90% da class "menu" de uma forma que nao quebrasse o código usando o flexbox, atualmente me encontro com dificuldade para fazer esse tipo de posicionamento!
Answer: Olá. sugiro pesquisar um pouco sobre a propriedade justify-content.
Pelo que eu entendi você quer algo mais ou menos assim:

header {
  width: 100%;
  display: flex;
  justify-content: space-around;
}

Commerce

Option1

Option2

Option3

Option4

Option5


If useEffect is not called, do something else React.js

Question: and couldn't find the answer on the internet. Is there a way to do something if an useEffect is called and do something else if useEffect is not called. Like an if statement?
like:
**if** (useEffect(() => {
   },[hello]) {
call a function } **else** {
call another function}

The goal is to call a function if the var hello changes and call another one is hello doesn't change. Thank you.
Answer: You can't do exactly what you outlined because React hooks like useEffect cannot be called conditionally.
As the other poster said, your best bet is to call useEffect on each render and trigger branching actions from inside useEffect.
Answer: you can achieve that if you call useEffect on every render and by creating a couple of custom hooks to check the previous values of your state-props.
const Component = (props) => {
  const hasHelloChanged = useHasChanged(hello);

  useEffect(() => {
    if (hasHelloChanged) {
      // your code if hello has changed
    } else {
     // your code if it hasn't
    }
  });

  return <>...</>;
};

const useHasChanged= (value) => {
    const prevValue = usePrevious(value);

    return prevValue !== value;
}

const usePrevious = (value) => {
    const ref = useRef();
    useEffect(() => {
      ref.current = value;
    });
    return ref.current;
}

You can take a look on this thread for more
Comment: Thank you! I've managed to do what I want with your post. But I don't know why sometimes I get a "Rendered more hooks than during the previous render" when I refresh the browser.
Comment: are you using another hook inside your useEffect?
Comment: I'm just using a hook for changing the state init ' useEffect(() => {
      if (hasCountryLabelChanged) {
        if(matchingOption) {
          changeSelectedPathway(matchingOption)
        } else {
          changeSelectedPathway(options[0])
        }
      } else {
       changeSelectedPathway(optionSelected)
      }
    },[hasCountryLabelChanged, matchingOption, optionSelected])'
Comment: if `changeSelectedPathway` is a setState hook, you should add it in your dependency array as well.
Answer: Have you tried using two different useEffect calls, one when hello changes and the the other whenever the other property in question changes.
for example;

useEffect(() => {  // desired action  }), [hello]);

The above effect will always be called whenever the value of hello changes, while;
    useEffect(() => {
// desired action
}), [theOtherPropertyInQuestion]);

will always be called whenever the value of theOtherPropertyInQuestion changes
and if they are not mutually exclusive, you can use
    useEffect(() => {
// desired action
}), [hello, theOtherPropertyInQuestion]);


Hyper Threading and Virtual Machines?

Question: I already looked at this thread: Hyper-V and Hyper-threading: On or off?, but the only answer is Windows specific....
I am building a VM server (using Proxmox VE if that makes a difference) and was wondering about how hyper threading can affect virtual machines...
Specifically, if I max out the number of virtual machines, would hyper threading help, or hurt performance?
Also, the largest virtual machines will be a Terminal Server with ~30 clients (4 Cores/8 GB of RAM), and a file server if that helps.
Update: The server is a Dell R410 with a 1TB RAID 10, 32 GB of RAM and Dual Intel Xeon E5530 (I am not sure about the exact model, but it was an E55xx with 2+ Ghz)
Update: Most VMs will be on KVM.
Comment: I choose Proxmox over ESXi because Proxmox has a few extra features like complete management from a web gui, clustering, the server's specs are not artificially limited by licensing and a few other I can't quite remember.  Plus, 2.0 will include AD authentication which is very useful for us, not sure if ESXi does...
Comment: Have you looked at oVirt?
Comment: Please provide the specifications of the server you plan to use.
Comment: Also curious. Why Promox VE versus ESXi?
Comment: Probably due to the ESXI limit of 16GB of ram on the free license
Comment: @dyasny Not until now, thank you.  I'll look into it.
Answer: In general, I leave HyperThreading ON for VM host servers (VMWare ESXi, KVM, HyperV, etc.). This applies to Intel Nehalem and newer CPUs (5500-series and greater). Additional threads available for scheduling multiple VMs.
You may also want to reevaluate the sizing of your guest systems. Typically, it's best to start small on the CPU allocation with virtual machines. Since you're talking about a terminal server, I'd actually move that to 2 virtual CPUs rather than 4 vCPUs. It's easier for the hypervisor to schedule CPU time for VMs with smaller core counts. RAM is still critical, though, so make sure to make plenty available.
See: http://omtconcepts.com/wp/?p=14
Comment: Not faster... Easier to schedule. See my edit. The machine you mention will have 8 total cores (16, with HyperThreading). Trying to find the resources to schedule a 4-vCPU guest is more difficult than 2-vCPUs. You'll have more contention (and thus, lower performance). If you plan to run other virtual guests on this server, it makes sense to use 1 and 2 vCPU guests.
Comment: Your point about scheduling only applies to hypervisors that do "gang scheduling" where they attempt to run some approximation of "all or none" of the virtual processors at the same time.  For hypervisors that do this, adding more virtual processors will make the VM harder to schedule.  I understand that Kevin updated his question to stipulate that he wants to use KVM, mostly.  But I want to point out that Hyper-V doesn't do gang scheduling.  It relies on paravirtualization of the guest OS to avoid the need for gang scheduling.
Comment: KVM doesn't gang schedule. In fact, only VMWare does this, and even they have added some mechanisms to relax the gang scheduling insanity in v5
Comment: How exactly are two threads **faster** than four?
Comment: I didn't know that about Hyper-V, but this does apply to the other major hypervisors.
Answer: It really depends. If, like you're saying, you're going to "max out", which I suppose means overallocate CPU (assign more virtual CPU cores than you have available, or exactly as many as you have available), then HT should definitely be on.
If you are not overallocating, then it is usually better to test under your specific loads - sometimes HT can actually hurt performance.
Comment: Guess I wasn't clear enough. You CAN overallocate, and depending on the loads in the VMs, CPU might not become the bottleneck at all. Moreover, you should never assign more CPUs to a VM than it absolutely needs, because the more CPUs the VM has, the harder it is to schedule, so many v-cpus can actually hinder performance. As for the 20% performance gain by hyperthreading - this is not an absolute, the number can be slightly higher, lower, zero or even negative - depending on the VM loads.
Comment: I do plan to allocate exactly as many cores/threads as are available, but I do not plan to over-allocate.
Comment: Do you think the host OS needs no CPU time at all? And if you allocate as many v-cores as you have threads with HT on, you're actually overallocating by at least 70-80%, because even when HT does add to performance, it's usually by 20-30% tops, not by 100%, like one could assume from the thread count.
Comment: Ok, so no more than 12 "cores" (75% of 16) allocated?
Answer: There are a lot of variables that affect VM performance. HT is just one of othe variables but it also depends on how the VM are configured.
One of the variables that affect HT depends on the type of Hypervisor being used.
If you are using lightweight virtual machines like VZ, VServer, etc, then it is quite obvious that HT would bring suitable benefits as these VM aren't actually tightly isolated and are more like running multi-threaded software.
If you are using heavyweight virtual machines like KVM, Xen HVM, etc, then it is possible that HT will interfere with things e.g. when a VM is allocated two CPUs but ends up using one HT each on different cores.
So, the best thing to do is still to test your setup to see what suits you.

Hyper Threading and Virtual Machines?


How does logistic regression "elegantly" handle unbalanced classes?

Question: Frank Harrell in this interesting blog post "Classification vs. Prediction" points out that using stratified sampling to handle unbalanced classes is a bad idea, since a classifier trained on an artificially biased data set will then do poorly on real world data set which will be distributed differently from the training data.
He then states that:

Logistic regression on the other hand elegantly handles this situation by either (1) having as predictors the variables that made the prevalence so low, or (2) recalibrating the intercept (only) for another dataset with much higher prevalence.

I'm having a harding digesting this, specifically the idea that logistic regression handles this elegantly:

What does he mean in (1): If a disease is really rare how, would we include that as a feature? Or malicious attacks on a network are very rare compared to legitimate logins, how would that be included as a feature?
In (2): Doesn't recalibrating the intercept in a logistic regression simply amount to playing around with the classification threshold - which can be achieved with all sorts of binary classification methods (and is achieved implicitly by biasing the training data set) ?
Moreover, isn't the bias introduced to the classifier a desirable outcome, given that our purpose is to detect the rare cases (in terms of the precision/recall tradeoff) ?
Answer:
No, we can't include the prevalence as a feature. After all, this is exactly what we are trying to model!
What FH means here is that if there are features that contribute to the prevalence of the target, these will have appropriate parameter estimates in the logistic regression. If a disease is extremely rare, the intercept will be very small (i.e., negative with a large absolute value). If a certain predictor increases the prevalence, then this predictor's parameter estimate will be positive. (Predictors could include, e.g., a gene SNP, or the result of a blood test.)
The end result is that logistic regression, if the model is correctly specified, will give you the correct probability for a new sample to be of the target class, even if the target class is overall very rare. This is as it should be. The statistical part of the exercise ends with a probabilistic prediction. What decision should be taken based on this probabilistic prediction is a different matter, which needs to take costs of decisions into account.
No, there is no threshold involved in logistic regression. (Nor in any other probabilistic model.) Per above, a threshold (or multiple ones!) may be used later, in weighing the probabilistic prediction against costs.
Note the context in which FH discusses re-estimating the intercept: it is one of oversampling to address rare outcomes. Oversampling can be used in logistic regression. One would first fit a model to a sample that oversamples the rare outcome we are interested in. This gives us useful parameter estimates for the predictors we have in the model, but the intercept coefficient will be biased high. Then, in a second step, we can nail down the predictor parameter estimates and re-estimate the intercept coefficient only by refitting the model to the full sample.
FH and I would argue that no, we should not aim for a precision/recall tradeoff. Instead, we should be aiming for well-calibrated probabilistic predictions, which can then be used in a decision, along with, and I am repeating myself, the consequences of misclassification and other misdecisions. And as a matter of fact, this is exactly what logistic regression does. It does not care at all about precision or recall. What it cares about is the likelihood. Which is just another way of looking at a probabilistic model. And no, bias is not a desirable trait in this context.
Comment: No, not really. In the oversampling-and-re-estimation setup, you could say that in the second step, you put point priors on the predictor coefficients so they won't budge... but I'm not sure this is a fruitful way of looking at things. But of course you could run the entire logistic regression with priors.
Comment: Thanks for the detailed response. Does the intercept act as some sort of prior probability here?


Recursive function exponential function

Question: I need implement recursive function exponential function (e^x) with help row Taylor:
e^x = 1 + x + x2/2! + x3/3! + ...
But i can't understand what i do wrong
I have next code:
function fact(n){
    return n * fact(n - 1);
}

function myPow(x, n){
    return x * myPow(x, n - 1);
}

function expon(x ,n){
    if(n == 1){
        return expon(x, n - 1) * x;
    }
    else{
        return expon(x, n - 1) + (myPow(x, n)/fact(n));
    }

}

console.log(expon(1, 10));

Comment: Your factorial function has no boundary. You should include an if statement there when `n == 1` to return 1. Otherwise it's going to continue indefinitely.
Comment: I'm pretty sure the expon function will go for infinity. You need to have another if else statement that says when n =  0 then return 1 because e^0 = 1 and then it will return all the way up the chain recursively.
Answer: Your factorial function has no base case.
function fact(n) {
  if (n == 1)
    return 1;
  if (n < 1)
    return 0;
  return n * fact(n - 1);
}

A similar change will be needed for myPow. Although since powers are funny, I think if n == 0 return 1.
Answer: Your code should look like this:
function fact(n){
  if (n == 1)
    return 1;
  return n * fact(n - 1);
}

function myPow(x, n){
  if(n == 1)
    return n;
  return x * myPow(x, n - 1);
}

function expon(x ,n){
  if(n == 1){
    return 1;
  }
  else{
    return expon(x, n - 1) + (myPow(x, n)/fact(n));
  }

console.log(expon(1, 10));

Comment: I add it but, but it didn't fix problem. I have next error in consol:
"Uncaught RangeError: Maximum call stack size exceeded"
Comment: I forgot to mention the if stament in the myPow method.
Comment: @S.Hagvin you should mark this as the answer since it works for you
Comment: Jonas Meinerz sorry I didn't know it. I only learn this resource
Answer: This looks like an assignment so I won't debug your code but give you some hints.
You seem to not understand how recursion ends with giving a result in the end.
You have to provide a simple case where you return a value with a non recursive call.
Sometimes you don't write any if (bad!), and sometimes there is an if, but both cases use a recursive call.
Answer: This will solve your problem:
function fact(n) {
  if (n == 1) return 1;
  return n * fact(n - 1);
}

function myPow(x, n) {
  if (n == 0) return 1;
  return x * myPow(x, n - 1);
}

function expon(x, n) {
  if (n == 0) return 1;
  return expon(x, n - 1) + myPow(x, n) / fact(n);
}
console.log(expon(1, 10));

Recursive function exponential function


Swift embeded UIView in container of Main UIViewController - how to transition from 1 embeded UIView to the next embeded UIView

Question: I can successfully embed the first UIView in the container by simply dragging the container to the new UIView however to add the transition view, I am not able to replace the current embed view with a new view on key enter event.
Here are my codes for this:
<code>import Foundation
import UIKit

class MainViewController: UIViewController {

@IBOutlet var overlayView: UIView!

@IBOutlet var logoImage: UIImageView!

@IBOutlet var overlayUIView: UIView!

private var embeddedViewController: ViewController!
private var birthdayPickerController: BirthdayPickerController!

required init(coder aDecoder: NSCoder) {
    let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

    self.birthdayPickerController = storyBoard.instantiateViewControllerWithIdentifier("birthdayPickerController") as! BirthdayPickerController

    super.init(coder: aDecoder)!
}

override func viewDidLoad() {
    super.viewDidLoad()

    view.backgroundColor = UIColor(patternImage: UIImage(named: "lasvegas.jpg")!)

    overlayView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.3)

    self.modalPresentationStyle = .OverCurrentContext

    logoImage.image = UIImage(named: "philia");

    let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

    self.embeddedViewController = storyBoard.instantiateViewControllerWithIdentifier("viewController") as! ViewController

    self.embeddedViewController.setOverlayUIView(overlayUIView)
}

let viewControllerIdentifiers = ["viewController", "birthdayPickerController"]  // storyboard identifiers for the child view controllers

/*
@IBAction func didChangeValue(sender: UISegmentedControl) {

    let newController = (storyboard?.instantiateViewControllerWithIdentifier(viewControllerIdentifiers[sender.selectedSegmentIndex]))! as UIViewController

    let oldController = childViewControllers.last! as UIViewController

    oldController.willMoveToParentViewController(nil)
    addChildViewController(newController)
    newController.view.frame = oldController.view.frame

    transitionFromViewController(oldController, toViewController: newController, duration: 0.25, options: .TransitionCrossDissolve, animations:{ () -> Void in
        // nothing needed here
        }, completion: { (finished) -> Void in
            oldController.removeFromParentViewController()
            newController.didMoveToParentViewController(self)
    })
}
*/
}

import UIKit
import Foundation

class ViewController: UIViewController, UITextFieldDelegate{

/*
 * Reference to the container in MainViewController
 * This is where all views are rendered
 */
private var overlayUIView: UIView!

@IBOutlet var backgroundImageView: UIView!

@IBOutlet var anotherTextLabel: UITextView!

@IBOutlet var textField: UITextField!

func setOverlayUIView(overlayView: UIView) {
    overlayUIView = overlayView
}

func textFieldShouldReturn(textField: UITextField) -> Bool {
    self.view.endEditing(true)
    onEnter(textField)
    return false
}

@IBAction func onEnter(sender: UITextField) {
    let msgEntered = textField.text

    anotherTextLabel.text = "Hi \(msgEntered!)!"

    let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

    let birthdayPickerController = storyBoard.instantiateViewControllerWithIdentifier("birthdayPickerController") as! BirthdayPickerController

    birthdayPickerController.name = textField.text!

    overlayUIView.willRemoveSubview(self.view)
    overlayUIView.addSubview(birthdayPickerController.view)

    /*
    self.willMoveToParentViewController(nil)

self.parentViewController?.addChildViewController(birthdayPickerController)

    birthdayPickerController.view.frame = self.view.frame

    transitionFromViewController(self, toViewController: birthdayPickerController, duration: 0.25, options: .TransitionCrossDissolve, animations: {() -> Void in}, completion: {(finished) -> Void in
            self.removeFromParentViewController()
            birthdayPickerController.didMoveToParentViewController(self.parentViewController)
    })
*/

        //self.navigationController?.pushViewController(thirdViewController, animated: true)

        //self.parentViewController!.performSegueWithIdentifier("birthdayPickerController", sender: self)

}

override func viewDidLoad() {
    super.viewDidLoad()

    UIColor.blackColor().colorWithAlphaComponent(0).CGColor

    view.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.3)

    self.textField.delegate = self;

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

/*
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    if segue.identifier == "birthdayPickerController" {
        let birthdayPickerController = segue.destinationViewController as! BirthdayPickerController

        birthdayPickerController.name = textField.text!
    }
}
*/

}
</code>
Answer: I solved this problem.  I used a delegate to pass the parent to the embedded controllers and had the child controllers make a callback to the parent with the new controller class where the parent class will then swap out the old controller for the new controller.


How to use linq-to-typescript orderby function with integers

Question: I have an array of players each of which has a shirt number and I would like to return these in shirt number order (normally 1-11).
I am using the linq-to-typescript library.
I tried
 return from(this.team.players)
  .orderBy(p => p.shirtNumber)
  .toArray();

but it returns players in the order 1,10, 11, 2,3,4.... which looks to me like a string comparison is being performed.  This is despite shirtnumber being defined as number
Comment: Check the github issues of the package you are using. [this one](https://github.com/arogozine/LinqToTypeScript/issues/19). Marked as "enchancement". so not implemented as i believe and uses default alphabetical comparer as plain js Array.sort.
Comment: @SergeySosunov - thanks for that I now have a solution : `.orderBy(p => p.shirtNumber, NumberComparer)` does the trick
Comment: did you use [Blinq](https://github.com/biggyspender/blinq/).
Comment: @UğurDemirel - I have not tried blinq.  linq-to-typescript seems adequate for my needs
Answer: The answer was simple if a little tricky to find.  Sergey's comment above led me the answer, now it seems obvious.
return from(this.team.players)
  .orderBy<number>(p => p.shirtNumber, NumberComparer)
  .ToArray();


ireducible polynomials with coefficients in $\{0,-1\}$

Question: I'm interested in the polynomials of the form $x^n -x^{n-1} - b_{n-2}x^{n-2} - \cdots -b_1 x -1$  with the coefficients $b_k$ being either zero or one.  The prototype is of course the Golden mean $x^2-x-1$. Is there a known name for such polynomials? I would search for info on them, but can't figure out how to form a reasonable search query.
To tighten things up: I'm interested in the ones that are irreducible with respect to one-another (are prime relative to one-another). As far as I can tell, there are the same number of these as there are irreducible polynomials over $\mathbb{F}_2$ -- OEIS A001037 (should that be obvious?). As far as I can tell, they always have just one real root greater than one. I'm interested in the complex roots, too. Some of these show up in papers on "generalized golden means", typically the all-ones case $x^n -x^{n-1} - \cdots -x -1=0$ or the all-zeros case $x^n -x^{n-1}-1=0$, but its not much enlightening. Another factoid: it seems the real roots are dense in [1,2], considering all such polynomials, taking $n\to\infty$. Is there a generating function? I'm guessing that texts in dynamical systems, chaos theory, fractals, subshifts, maybe number theory might discuss these; but under what name?
EDIT: The context for these polynomials is the iterated Beta Transform. I've written a 105-page tract providing a treatment of the Beta Transform, illustrating the usefulness and central natural of these polynomials. It can be found here: https://linas.org/math/solvit.pdf I still don't "understand them", and find this to be annoying.
Comment: In my playing around with polynomials like this with all the $b_n=0$, the roots are all close to the $n^{th}$ roots of unity.  The roots are roughly in a circle in the complex plane since $x^{n-1}(x-1)=1$.  IIRC, Even with $b_n\ne0$, the two highest order terms dominate as $n$ becomes large, so the roots are still roughly arranged in a circle in that case
Comment: Glasser has an approach for finding the roots of the trinomial $x^n-x+t=0$, which you might be able to adapt to the trinomial $x^n-x^{n-1}-1=0$ but you might run into convergence problems with the hypergeometric functions.  https://www.sciencedirect.com/science/article/pii/S0377042700002879
Comment: Ah, yes, thank you. I was seeing roots arranged in circles at various radii; (specifically, at a radius of 1 over the real root, in a related one-off problem in which these arise.)  I see Glasser invokes the multiplication theorem, which is an old favorite of mine... and might provide the doorway I need.
Answer: Not an answer, but here's a MatLab/Octave script to visualize how the roots of
$$x^n-x^{n-1}-1 = 0$$
compare to the roots of unity
$$x^n-1 = 0$$
<code>N = 10;
% x^n - 1 = 0
eta_poly = [1, zeros(1,N-1), -1];
% x^n - x^(n-1) - 1 = 0
r_poly   = [1, -1, zeros(1,N-2), -1];
eta = roots(eta_poly);
r = roots(r_poly);

% Plot the nth roots of unity and the other polynomial's roots
plot(real(eta),imag(eta),'.',real(r),imag(r),'+');
grid on;

% Sort the roots of unity by their arg() in [0, 2*pi)
ae = arg(eta)+2*pi*(arg(eta)<0);
[s,si] = sort(ae);
eta = eta(si);

% Match the closest roots of unity to the roots in r
% and permute r so that it lines up with the corresponding roots of unity
M = length(eta);
c = eta*ones(1,M)-ones(M,1)*r.';
[w,iw] = min(abs(real(c))+abs(imag(c)));
r = (abs(c) <= max(w))*r;

% What's the difference between the roots of unity and the roots of the
% other polynomial?
d = r-eta
r_d = abs(d)
phi_d = arg(d)
</code>
Comment: The case of $x^n-\sum_{k=0}^{n-1} x^k=0$ is interesting: the zeros approach the unit circle surprisingly slowly as $n\to\infty$.
Comment: Also: for small n, the polynomials, roots are the "silver number", pisot number, tribonacci, tetranacci, etc. and have OEIS  A092526 A058265  A109134 A086088 A060006 A293506 A103814 to describe them.


How do I redirect user_view_page to user_profile_form?

Question: I do not really need the user_view_page on my site and I want to redirect calls to user/%user to the user_profile_form. I only want this change for regular users, not for administrators.
I already tried to accomplish this with hook_menu_alter, but that would change it for all users including the administrator.
How can I do this?
Answer: I've solved this problem in the past with the Rules module.
Event:
User Account page is viewed
Condition:
User has role(s)
Action:
Page redirect
Parameter URL:[account:edit-url]
I created the rule and added the screenshot here: https://i.stack.imgur.com/oONeT.jpg
Here is also the exported rule:
<code>{ "rules_test" : {
    "LABEL" : "test",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : { "user_view" : [] },
    "IF" : [
      { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "2" : "2" } } } }
    ],
    "DO" : [ { "redirect" : { "url" : "[account:edit-url]" } } ]
  }
}
</code>
I hope this helps!
Answer: If you don't want to use the Rules module, you can mimic its behavior/do it yourself inside of hook_init(), eg something along the lines of:
<code>function YOURMODULE_init() {
  global $user;

  if (arg(0)=='user' && is_numeric(arg(1)) && !(arg(2)) { // eg user/# and not user/#/edit

    if ( /* whatever logic you need to determine this is not an admin */ ) {

      if ($user->uid==arg(1)) { // same user...
        drupal_goto($_GET['q'] . '/edit');
      } else {
        // either ignore it and allow standard Drupal permissions to deal with it or go someplace else, do a drupal_access_denied() etc
      }

    }

  }

  // any other module init stuff here...

}
</code>
You didn't specify what you want to happen if a user tries to look at another user's page but you can deal with that situation easily above as well.
Comment: Thanks! This is the solution I'll use. Because the link to the user profile page can also be plain '/user' without the user id, i had to change the logic a bit.


qtip2 close button without a title bar

Question: I would like to have a qtip2 tooltip without a title bar, but with a close icon in the corner. Is there a way to spec that, or do I have to muck with the code that creates it? I am thinking of something that floats the button to the left or to the right, allowing the rest of the content to fill the tooltip div.
Answer: Always keep the close markup separately and update with your current qTip Text.
<code>$('.selector').qtip({
    content: {
        text: function(api) {
          var qTipContent = $('.close-markup').html();
          qTipContent += $('.qtip-content').html();
          return $('.qtip-content').html();
        }
    }
});
$('.close-markup').qtip('destroy');
</code>
Try the above code.
Note: Does not require to muck the qTip Close code snippet!
Comment: Edited my answer to understand

qtip2 close button without a title bar