Sets of integers with few sums

Question: Let $S$ be a finite set of integers. Denote by $S^{\leq k}$ the set $\{a_1+\dots+a_\ell : \ell\leq k, a_1,\dots,a_\ell\in S\}$ of sums of at most $k$ elements from $S$. What are best/worst cases for the size of $S^{\leq k}$ in function of $|S|$ and $k$? A trivial upper bound on this number is $|S|^k$. But we can do exponentially better: if $S$ is an arithmetic progression, then we have $|S^{\leq k}| = O(k^2 |S|)$. What other kinds of bounds can we achieve asymptotically? Can we achieve something that is linear in $k$ and $|S|$?
Comment: The interval $[\min(S^{\leq k}), \max(S^{\leq k})]\cap \Bbb Z$ grows linearly in $k$, so $|S^{\leq k}|$ is asymptotically linear in $k$.
Comment: @Arthur: This is true, but this gives a bound in terms of $k, \min(S)$ and $\max(S)$. So we cannot really compare it to the bound $|S|^k$, I guess.
Comment: Am I correct in thinking that you want your big-Oh to be uniform over all choices of $S$? Also, what variable are you letting tend to infinity? As per a general upper bound: $S' = \{1, (k+1), (k+1)^2, (k+1)^3, \ldots, (k+1)^{k-1}\}$ attains the trivial upper bound $|S|^k$.
Comment: The upper bound is not quite $|S|^k $, because commutativity means some sums coincide. The actual upper bound would be $\binom {|S| + k -1}{k} $, the number of choices of $k $ summands from $S $ with repetition. D Poole's construction achieves this upper bound. The lower bound is given by an arithmetic progression, which has $k (|S|-1) + 1$ distinct sums.
Comment: @DPoole The big-Oh notation $O(f(k,n))$ would mean "There exist $C, k_0,$ and $n_0$ such that for all $k\geq k_0$ and $S$ with $|S|\geq n_0$, we have $|S^{\leq k}| \leq C\cdot f(k,|S|)$." So indeed the bound should be uniform across all the sets of a given size.
Comment: @Shagnik: thanks for your comment. I guess the question was not precise enough to have a definite answer. But you certainly answered many interrogations I had, and I think it would be nice if your comments were turned into answers.
Comment: @Shagnik Ahh, yes! I forgot about commutativity. To zarathustra: Here the notation means that, but often the condition is given by context. For instance, I often look at a case where for $k$ fixed and $n \to \infty$, some expression is $O(n^k)$.
Answer: The lower bound is attained by arithmetic progressions containing $0$, which have $|S^{\le k}| = k(|S|-1)+1$. Moreover, any set attaining this lower bound must be an arithmetic progression.
Freiman's theorem, one of the highlights of additive combinatorics, gives stability for this result, saying that any set $S $ with $|S + S| \le C|S|$ must be close to a generalised arithmetic progression.  This means that, in some sense, being similar to an arithmetic progression is the only reason a set should have only a linear number of sums.
For the upper bound, note that commutativity of addition implies that the order within the $k$-tuple of summands doesn't matter. Hence the number of sums is at most the number of selections of at most $k $ elements from $S $ with repetition, which is $\binom {|S|+k}{k} $.
As observed by D Poole, you can construct sets attaining this bound (that is, without any nontrivial relations between the sums) by taking,
$S = \{ 1, b, b^2, b^3, ..., b^{|S|-1} \} $, where $b\ge k $. Writing the sums in base-$b $, we find that the choice of summands is uniquely determined by the digits of the sum.
Here of course the set $S$ depends on $k $.  If we instead think of $S$ as being fixed and $k$ large, then note that $S^{\le k} \subseteq [\min (0,k \min S), \max (0, k \max S)]$, so that gives an alternative upper bound that is linear in $k $ (rather than the previous one, which is polynomial (with degree $|S|$)).
Comment: Thanks for that answer and the useful reference to Freiman's theorem.

Sets of integers with few sums


Is It Possible for a MYSQL Trigger to Return an Error Message if the Trigger Fails for Any Reason?

Question: I am trying to create an after insert trigger in MySQL that writes the message "Insert Failed" to an error table called tbl_error if the trigger fails for any reason.
To solve this problem, I have attempted to use a combination of handlers and signal statements. None have worked.
<code>DELIMITER $$
CREATE TRIGGER trig_statesout_afterinsert AFTER INSERT ON states
FOR EACH ROW
BEGIN

DECLARE EXIT HANDLER FOR SQLEXCEPTION
  BEGIN
    SIGNAL SQLSTATE VALUE '99999'
      SET MESSAGE_TEXT = 'Insert Failed';
    INSERT INTO tbl_error(ErrorMessage) Values ('Insert Failed');
  END;

INSERT INTO statesout (states_id, state, cases, lastupdate)
SELECT s.states_id, s.state, s.cases, current_timestamp()
FROM states as s
WHERE s.states_id = NEW.states_id;

END $$
</code>
I attempted to return information from a diagnostic statement, but that didn't work either.
Because the documentation states that

For SQLEXCEPTION conditions, the stored program terminates at the
statement that raised the condition, as if there were an EXIT handler.
If the program was called by another stored program, the calling
program handles the condition using the handler selection rules
applied to its own handlers.

I split the update logic for the trigger into a separate stored procedure in case the issue was that the SQLEXCEPTION conditions cannot be in the calling object. It didn't work.
Some SO solutions suggest using a "trick" to call a nonexistent table, but the documentation says this is not necessary due to the SIGNAL statement:

Without SIGNAL, it is necessary to resort to workarounds such as
deliberately referring to a nonexistent table to cause a routine to
return an error.

In any case, those solutions only throw errors based on a specific condition, not for any condition.
What am I doing wrong? Is it impossible for a MYSQL trigger to return an error message if the trigger fails for any reason?
Answer: It's not possible to make any change to data if the trigger activates a SQLException.
If the trigger experiences any error, whether handled or not handled, then the INSERT that spawned the trigger is undone, as well as any SQL run by the trigger, and even any SQL run by triggers spawned by actions your trigger executes.
This is related to the idea of atomicity — either the whole action must succeed, or else no part of the action is saved. It's all or nothing.
If you want to log the error, you'll have to check for the error in your application, and then log the error as a separate action. You can't do it in the trigger body.


How to modify $uri to part of uri from request_uri in nginx?

Question: Suppose the value of $request_uri is /a/b/c .
The current value of $uri is /index.php .
Is this possible to change my $uri to /b/c .
I have tried this, which doesn't seem to be working,
if ($request_uri ~* /a/(.*)/(.*)){
  set $uri /$1/$2;
}

But this gives error of duplicate "uri" variable.
I also tried,
if ($request_uri ~* /a/(.*)/(.*)){
  rewrite ^ /$1/$2 break;
}

But $variables don't seem to store values.
Is there a way out? Thanks.
Answer: I managed to do it from here.
It basically needed two rewrites.
rewrite ^ $request_uri;
rewrite /.*/(.*)/(.*) /$1/$2;

The first rewrite modifies uri from /index.php -> /a/b/c.
The second rewrite modifies uri from /a/b/c -> /b/c.


Contador regressivo

Question: Boa tarde,
Quero acrescentar na minha página um contador regressivo, que no final so emita um aviso dizendo que o tempo expirou.
É possivel fazer isso com html?
estou sem  idéia.
Comment: javascript e php poderiam fazer isso juntamente com o html
Answer:

var configMinuto;
    var configSegundo;
    var mostrarValor;
    var evento = null;
    var contador = null;
    var minuto = 0;
    var segundo = 0;

    function IniciarCronometro(valor){
     this.evento = valor;
     this.configMinuto = document.getElementById('min').value;
     this.configSegundo = document.getElementById('seg').value;
     this.mostrarValor = document.getElementById('mostrarValor');

     if (evento=="start"){
      if(!document.getElementById('min').readOnly){
       if(!this.validarNumero(this.configMinuto)){
        alert("Campo minuto não é um número!");
        return;
       }
       if(!this.validarNumero(this.configSegundo) || document.getElementById('seg').value > 59){
        alert("Campo segundo não é um número válido (0 a 59)!");
        return;
       }

       document.getElementById('min').readOnly = true;
       document.getElementById('seg').readOnly = true;
       this.minuto = document.getElementById('min').value;
       this.segundo = document.getElementById('seg').value;

       document.getElementById('mostrarValor').classList.remove('mostrarValor');
       document.getElementById('mostrarValor').classList.add('mostrarValor2');
       document.getElementById('exibe').classList.remove('Classexibe');
       document.getElementById('exibe').classList.add('Classexibe2');

      }else{
       if(this.segundo == 0 && this.minuto != 0){
        this.segundo = 59;
        this.minuto--;
       }else{
        this.segundo--;
       }
       if(this.minuto == 0 && this.segundo == 0){
        document.getElementById('min').readOnly = false;
        document.getElementById('seg').readOnly = false;
        this.mostrarValor.value = "03:00";

        document.getElementById('mostrarValor').classList.remove('mostrarValor2');
        document.getElementById('mostrarValor').classList.add('mostrarValor');
        document.getElementById('exibe').classList.remove('Classexibe2');
        document.getElementById('exibe').classList.add('Classexibe');

        clearTimeout(this.contador);
        return;
       }

       novoMinuto = null;
       novoSegundo = null;
       if(this.minuto <= 9){
        novoMinuto = "0" + this.minuto;
       }else{
        novoMinuto = this.minuto;
       }
       if(this.segundo <= 9){
        novoSegundo = "0" + this.segundo;
       }else{
        novoSegundo = this.segundo;
       }
       this.mostrarValor.value = novoMinuto + ":" + novoSegundo;
      }
     }
     clearTimeout(this.contador);
     this.contador = setTimeout('IniciarCronometro(evento)', 1000);
    }

    function validarNumero(valor){
     return !isNaN(parseFloat(valor)) && isFinite(valor);
    }
html, body {
 height: 99%;
}
body {
 background-color: #f0f0f0;
}
.mostrarValor{
 text-align: center;
 border:0px solid white;
 font-size: 50pt;
}
.mostrarValor2{
 text-align: center;
 border:0px solid white;
 font-size: 50pt;
 animation: fade 10000ms infinite;
}

.Classexibe, .Classexibe2{
 text-align:center;
}

section {
 width: 450px;
}

.btn {

 width:100px;
}
<!DOCTYPE html>

<meta charset="UTF-8"/>
<title>CRONÔMETRO</title>
<link rel="stylesheet" type="text/css" href="style.css" />

   <fieldset class="Classexibe" id="exibe">

<input class="mostrarValor" type="text" id="mostrarValor" size="2" readonly="readonly" value="03:00"/>

    <input type="hidden" id="min" size="2" maxlength="3" value='3'/>
    <input type="hidden" id="seg" size="2" maxlength="2" value='0' />
           <input class="btn" type="button" value="INICIAR" id="btnIniciar" onclick="IniciarCronometro('start')">
   </fieldset>

Comment: era desta forma ?, Bom o primeiro bloco vem dentro de uma tag
Comment: @olifreitas vai ser necessário pegar o que está dentro do body pelo menos, para você ter o código com eficiência
Comment: então e eu respondi, para isso acontecer você deve copiar o ID e o evento onclick do botão iniciar e colocar em algum botão, seja no botão logar ou pode ser também em algum link
Comment: Obrigado! Só uma duvida...o primeiro bloco começa direto assim "var configMinuto;"?
Comment: No caso eu so preciso msm do contador em si, mas eu tento tirar esses campos Minutos e Segundos
Comment: Sem querer abusar, vc saberia me dizer no momento que pagina é aberta o cronometro ja começa a rodar?
Comment: @olifreitas Você tera que colocar o id e o evento onClick no botão de logar
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/68398/discussion-between-victor-and-olifreitas).
Comment:

assim?
Comment: copie a tag  e tudo que esta dentro dela eu editei o código deixando bem simples agora , lembrando que ... deve copiar até o
Comment: Muito obrigado! mas o eu tentei dizer foi que no momento que  pagina é carregada o cronometro ja começa a rodar, sem precisar de clicar num botao iniciar.

Contador regressivo


Rationale behind the modulations in Alice Cooper's Poison

Question: I was playing along to Poison and noticed a curious chord progression:
<code>[Verse]

(in Dm)
i            VI       III         VII
Dm           Bb       F           C
  Your cruel, device, Your blood, like ice

(in Gm)
i          VI           III     V
Gm         Eb           Bb      D
  One look, could kill, my pain, your thrill

[Chorus]

(in Gm)
i         VI              III         VII
Gm        Eb              Bb          F
  I wanna love you but I better not touch

(in Cm)
i         VI              III    VII
Cm        Ab              Eb     Bb
  I wanna hold you but my senses tell me to

(in Am)
i            VI             III         VII
Am           F              C           G
stop - I wanna kiss you but I want it too much

(in Dm)
i         VI                  III      VII
Dm        Bb                  F        C
  I wanna taste you but your lips are venomous -

i    VI  III VII
Dm   Bb  F   C
poison

       i      VI       III        VII
       Dm     Bb       F          C
You're poison running through my veins you're

i    VI   III VII
Dm   Bb   F   C
poison

i       VI     III         VII
Dm      Bb     F           C
I don't wanna break these chains
</code>
Apart from the leadup into the chorus, there seems to be a i VI III VII progression (if I've labelled those correctly) that runs throughout; looking at the chorus, the key changes from Gm → Cm → Am → Dm, staying in Dm for the last few lines.
I couldn't see any consistent relation between those keys (or with the last chord of the previous progression) but the chords obviously work well with the melody; does anyone have insight on how Cooper might have chosen those key changes or if this is a known technique?
Answer: It's just a walk "up" the cycle of fifths. The reverse VII-III-VI would be a common pattern;  in a minor key, it tends to would like V-I-IV in the relative major. The reversed pattern doesn't sound like one is moving to the relative major. I don't know if that's the reason it was composed, it is an effect. One important point is that the voice-leading is going to be fine so things sound good. Reversed cycle of fifths movement isn't unusual; it isn't strongly functional but does make a nice passing progression.
Comment: I'm not sure if I follow walking up the cycle of fifths, if we're walking up from G, it would be G -> D -> A -> E?
Comment: Yes. Here it's Bb-F-C.
Comment: Ah apologies, I realise I wasn't asking the question clearly (have edited it from chord progressions to the key change) - I've seen i VII III VI used a lot in pop music (https://www.youtube.com/watch?v=E6dlIJrjmME) and as you pointed out the last 3 are cycle of fifth walk ups - my question was more around why those key changes were chosen (Gm → Cm → Am → Dm)


Google route planner zoom center

Question: Im using Google route planner on my website with directions panel on the side. When you click on certain part of a jurney it gets zoomed in on the map but its not centered. Is it possible to center it in the midle of the map?
Answer: There is no implemented option to control anything when you click on the panel.
But what you can do: When you click on the panel, the infoWindow opens.
You may create your own infoWindow-object  and pass it as infoWindow-option to the directionsRenderer.
Then you'll be able to control the infoWindow. Observe the domready-event of the infoWindow(it will fire before the infoWindow opens), and set the center of the map to the value returned by the getPosition()-method of the infoWindow.
<code>// Show directions
if(!Demo.iw){
  Demo.iw=new google.maps.InfoWindow();
  google.maps.event
    .addListener(Demo.iw,'domready',
                 function(){Demo.map.setCenter(this.getPosition());});
}
Demo.dirRenderer.setOptions({
                    map         : Demo.map,
                    panel       : Demo.dirContainer,
                    infoWindow  : Demo.iw,
                    directions  : dirResult
});
</code>
Comment: hey again, i have almost the same problem [here](http://stackoverflow.com/questions/13952810/show-info-window-in-center-of-the-map-google-avoid-highways), could you plz help me again? i got an answer there but its not nearly as good as this one here
Comment: It looks like the problem is not almost the same, it's exactly the same, so my answer also would be the same.

Google route planner zoom center


Model selection basics

Question: I have ran three regressions and they are all very statistically significant.
How do I choose which one is the best to use?
i.e do I look for high F-statistic, low p-values ect.
Comment: There are many techniques. But the most important thing is your approach. You can let the data drive the decision, via model fit statistics, stepwise regression, comparison of likelihood functions etc. Or you can let the theory drive the decision. Personally I think theory should be what determines your decision to include or exclude variables.
Comment: "best" at what? measured how?
Comment: Are all 3 regression models fit to the same data?
Comment: @SYS_V Yes they do.
Answer: The general approach to model selection involves assessing the accuracy of a model when fit to previously unseen data. This is the rationale behind use of training and test data sets - models are first fit to training data sets, and the model that produces the most accurate predictions when applied to test data sets is then chosen as "best".

In order to evaluate the performance of a statistical learning method on
  a given data set, we need some way to measure how well its predictions
  actually match the observed data. That is, we need to quantify the extent
  to which the predicted response value for a given observation is close to
  the true response value for that observation. In the regression setting, the most commonly-used measure is the mean squared error (MSE), given by $$MSE = \frac{1}{n}\sum_{i=1}^{n}(y_{i}-\hat{f}(x_{i}))^2$$ The MSE is computed using the training data that was used to fit the model, and so should more accurately be referred to as the training MSE. But in general, we do not really care how well the method works on the training data. Rather, we are interested in the accuracy of the predictions that we obtain when we apply our method to previously unseen test data.[1]

Cross-validation can be employed to evaluate model performance to aid in the model selection process:
Cross-validation in plain english
Meaning of cross-validation
How to choose a predictive model after k-fold cross-validation?

1. An Introduction to Statistical Learning with Applications in R
Answer: Best to use for what purpose?  If it's purely for prediction and you don't care about explanation, you can go with the one that has the lowest AIC, BIC, SBC or some similar score.
If it's for explanation, then go with the one that best advances the field you are researching.
Comment: I'm interpreting that as choosing a model to get whichever answer you wanted before the experiment. I'm interpreting that as suggesting, for instance, that if I know that my field would be very interested in knowing that that a covariate is significant, I should select that covariate. I very well could be misunderstanding, but it seems that this procedure (or others like it) is astatistical.
Comment: Could you please clarify for me what "the one that best advances the field you are researching" means. Thanks!
Comment: I'm not sure how to make it clearer.  Look at the different models.  Which one helps your field the most? Which answers your research questions best? etc.

Model selection basics


Why is the Python 3.8 shell not executing parts of the code?

Question: I tried executing this code from a Python 3.x book but the Python 3.8 shell will only execute the first two lines of code. If I remove the second line of code it will execute the code that is still there just fine for some reason. Is this a bug or is there something wrong with the code? I have tried restarting the shell and executing the code from a new file but nothing seems to be helping.
<code>print("hello")
firstname=input("what is your first name? ")
print("thanks.")
surname=input("and what is your surname? ")
</code>
Comment: Are you providing the input it's asking for? Type something and hit enter.
Answer: This code works fine for me. You have to fill out the first input form before the second one will become available. And make sure you are hitting enter after you enter the text.


Publish only minified versions of JavaScript files (ASPNET Core)

Question: Although there are several articles on this issue, I can't seem to find any that are recent and apply to ASPNET Core 2.x, Visual Studio 2017.
How do I only publish my minified versions of JavaScript (.js) files?
It would be nice to do this via the publish profile (.pubxml) so that I can include/exclude by setting up different publish profiles (Dev, UAT, Staging, Production.
Comment: If you are referring to creating a bundle of minified files, that doesn't solve the original .js file from being published...where anyone can view it by adjusting the URL.
Comment: there is MVc bundle, wont this work for you ?
Comment: I mean you could have two diffrent bundles, one On release and other on debugg, the same could also be applied with diffrent attr to. have a look at this, not sure if this is the answer your looking for though.https://stackoverflow.com/questions/3788605/if-debug-vs-conditionaldebug
Comment: Sure, I can create two bundles, but it just seems so hacky.  I just don't know why you can't have something in your publish config that would help say, don't deploy these files.  That is my question.
Comment: This just doesn't appear possible, so I wrote a post build powershell that just deletes CSS and JavaScript files where a minified version exists.
Answer: Just exclude all .css/.js files and then include .min files. The last rule overrides the previous.
<ItemGroup>
   <Content Update="wwwroot\**\*.css" CopyToPublishDirectory="never" />
   <Content Update="wwwroot\**\*.min.css" CopyToPublishDirectory="always" />
   <Content Update="wwwroot\**\*.js" CopyToPublishDirectory="never" />
   <Content Update="wwwroot\**\*.min.js" CopyToPublishDirectory="always" />
</ItemGroup>

Comment: Appears to work and is super simple, and understandable.
Answer: Publish profiles are essentially project file overrides and use the same schema as project files. Microsoft supplies an example here: https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/visual-studio-publish-profiles?view=aspnetcore-2.2#exclude-files
<ItemGroup>
  <Content Update="wwwroot/content/**/*.txt" CopyToPublishDirectory="Never" />
</ItemGroup>

Additionally, you can set any file in your project to be included or excluded based on build configuration directly in the project:
Conditional Content Based Upon Configuration
Comment: I had tried something similar to this, without success. Because "Never" is used, I was negating my patterns to allow only min file versions.
Comment: Ah, good point; did you try the Exclude attribute? https://learn.microsoft.com/en-us/visualstudio/msbuild/msbuild-items?view=vs-2019#use-the-exclude-attribute -
Comment: Bottom line...publish doesn't support multiple globbing syntax, either by placing patterns in an array using [] or by just separating them with commas.  I've tried so many variables and nothing works.


Listar todos os triggers no SQL Server

Question: Existe algum comando, que liste todas as triggers de um banco no SQL Server?
Answer: SELECT * FROM sys.triggers

Coloquei no GitHub para referência futura.
Documentação.
Answer: Seria isso que você está procurando?
SELECT Object_Name(parent_id) AS [Nome Objeto],
       type_desc              AS Tipo,
       modify_date            AS [Data Modificação]
FROM   sys.triggers

Answer: Você pode usar o select abaixo.
SELECT
     sysobjects.name AS trigger_name
    ,USER_NAME(sysobjects.uid) AS trigger_owner
    ,s.name AS table_schema
    ,OBJECT_NAME(parent_obj) AS table_name
    ,OBJECTPROPERTY( id, 'ExecIsUpdateTrigger') AS isupdate
    ,OBJECTPROPERTY( id, 'ExecIsDeleteTrigger') AS isdelete
    ,OBJECTPROPERTY( id, 'ExecIsInsertTrigger') AS isinsert
    ,OBJECTPROPERTY( id, 'ExecIsAfterTrigger') AS isafter
    ,OBJECTPROPERTY( id, 'ExecIsInsteadOfTrigger') AS isinsteadof
    ,OBJECTPROPERTY(id, 'ExecIsTriggerDisabled') AS [disabled]
FROM sysobjects
INNER JOIN sys.tables t
    ON sysobjects.parent_obj = t.object_id
INNER JOIN sys.schemas s
    ON t.schema_id = s.schema_id
WHERE sysobjects.type = 'TR'

Ele retorna além do nome da trigger a tabela que a usar.
Documentação com select do objeto trigger.

Listar todos os triggers no SQL Server


Textview inside custom layout of ActionBar doesn't go rtl

Question: I have this custom layout in my app bar.
My problem is that not only the text is not shown completely, but also it sticks to the left instead of right.
I have set all gravity, direction layout_gravity attributes to right and rtl, both in code and in layout.xml files. But no success.
Here is the screenshot: (as can be seen only the "right" part of the text "Should stick right" inside the textview is shown.)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|right"
android:background="@color/black1"
android:gravity="right|center_vertical"
android:layoutDirection="rtl"
android:orientation="horizontal">

<ImageView
    android:id="@+id/search_mag_icon"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@color/blue4main"
    android:src="@drawable/abc_ic_search_api_mtrl_alpha" />

<com.jahanjooy.haftdong.views.DelayAutoCompleteTextView
    android:id="@+id/text_view_vicinity"
    android:layout_width="150dp"
    android:layout_height="wrap_content"
    android:background="@color/black1"
    android:gravity="right"
    android:imeOptions="flagNoExtractUi|actionSearch"
    android:inputType="textCapSentences"
    android:layoutDirection="rtl"
    android:shadowColor="@color/white1"
    android:textColor="@android:color/white" />

<TextView
    android:id="@+id/text_view_hint"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"

    android:layout_gravity="center_vertical|right"
    android:background="@color/blue1"
    android:gravity="right"
    android:layoutDirection="rtl"
    android:text="should go right"
    android:textColor="@color/white1"
    android:textSize="15dp" />

<ProgressBar
    android:id="@+id/progress_bar"
    style="?android:attr/progressBarStyleSmall"
    android:layout_width="20dp"
    android:layout_height="20dp"
    android:indeterminate="true"
    android:indeterminateTint="@android:color/white"
    android:indeterminateTintMode="src_atop"
    android:visibility="gone" />

<ImageView
    android:id="@+id/ic_filter_cone"
    android:layout_width="30dp"
    android:layout_height="30dp"
    android:src="@drawable/ic_filter" />

Activity:
/**/
    /**/
    Toolbar parent =(Toolbar) layout.getParent();//first get parent toolbar of current action bar
    parent.setContentInsetsAbsolute(100,10);

    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);

    ActionBar.LayoutParams lp = (ActionBar.LayoutParams) layout.getLayoutParams();
    lp.rightMargin= 0;
    lp.width = metrics.widthPixels/2;
    lp.gravity = Gravity.RIGHT;
    layout.setLayoutParams(lp);
    layout.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);

    TextView hint = (TextView) findViewById(R.id.text_view_hint);
    LinearLayout.LayoutParams ll= (LinearLayout.LayoutParams) hint.getLayoutParams();
    ll.rightMargin = 0;
    ll.width = metrics.widthPixels/2;
    ll.gravity = Gravity.RIGHT;
    hint.setLayoutParams(ll);
    hint.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
    hint.setTextDirection(View.TEXT_DIRECTION_RTL);

       /**/

Answer:     android:shadowColor="@color/white1"
    android:textColor="@android:color/white" />

<TextView
    android:id="@+id/text_view_hint"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical|right"
    android:background="@color/blue1"
    android:gravity="right"
    android:layoutDirection="rtl"
    android:text="should go right"
    android:textColor="@color/white1"
    android:textSize="15dp" />

<ProgressBar
    android:id="@+id/progress_bar"
    style="?android:attr/progressBarStyleSmall"

Replace the TextView with a RelativeLayout and put the TextView in it.as shown below
<RelativeLayout
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:background="@color/blue1">

<TextView
    android:id="@+id/text_view_hint"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="should go right"
    android:textColor="@color/white1"
    android:textSize="15dp"
    android:layout_alignParentRight="true"/>

</RelativeLayout>

give the required width to RelativeLayout, wrap_content to TextView. Set your TextView background to RelativeLayout. Add
android:layout_alignParentRight="true"

will move the TextView to right side.And removed other gravity attributes.


I have a Type but need help on creating generic Func

Question: I have an object myClassType of Type
string typeName = @"MyCompany.MyApp.MyDomain.MyClass";
Type myClassType = Type.GetType(typeName);

and I want to create a lambda expression (similar to the one below), but how do I get the MyClass from the myClassType so that I can pass it to the Func
Expression.Lambda<Func<MyClass, bool>>()

Is it possible to do so? any alternative ways or suggestions welcome.
Comment: so do you need an object from `myClassType` type definition? Then use `Activator.CreateInstance(myClassType)` and cast it to `MyClass`. Notice there is an inconsistency: you have one type defined in two different ways: in string and in usual way as Type parameter
Comment: Would the result from Activator.CreateInstance(myclassType) can be used in Func ?
Comment: I am not looking to create an instance object of that type, but to use that type myClassType to create a Func<**MyClass**, bool>
Comment: Are you wanting to create an `Expression>` or just a `Func`?
Comment: Actually I want to create Expression.Lambda>(...)
Answer: Use
Expression.Lambda(...)

Non generic signature and treat the result as your known type.


Remover duplicatas de uma lista mantendo a ordem

Question: Eu tinha a lista:
A = [12,   15,  10,  15,  12,  10,  10,  10,  15,  12,  12,  15,  15,  15]

, ao fazer:
ASemRepetidos=set(A)

fico com ([10, 12, 15]), como se vê, se em A o meu primeiro elemento é o 12, em set(A) passa a ser 10, ou seja eu perco a ordem original dos elementos...
Se:
B=[0.2, 0.3, 1.1, 0.2, 0.2, 0.7, 0.4, 0.6, 0.1, 0.3, 0.7, 0.4, 0.5, 0.5]
Ao fazer este código:
indice=[]
feitos = [] # vou guardar aqui todas as chaves que já ocorreram no loop.
indic = {} # Se quiseres ter uma ligação directa entre chave e indice...
for k in A:
    if k in ASemRepetidos and k not in feitos:
        indice.append(A.index(k))
        feitos.append(k)
        indic[k]=A.index(k)
obtenho os indices da 1ª ocorrencia de cada valor repetido e portanto posso fazer:
Re=[]
for g in indice:
    Re.append(B[g])

obtendo da lista B os valores do 1º índice que se repete.
Mas se em vez de querer apenas o valor do 1º índice repetido quiser a soma de cada conjunto repetido, mas de todos os conjuntos, e mantendo a ordem de ocorrência da chave desses conjuntos em A e não do set(A) como faço?
Eu já tinha este dicionário:
ASemRepetidos = set(A)

def indicesDeElementoNaLista(elementoProcurado, lista):
    return [i for (i, elemento) in enumerate(lista) if elemento == elementoProcurado]

def elementosNasPosicoes(lista, posicoes):
    return [lista[i] for i in posicoes]

dicionarioResultante = {}

for elemento in ASemRepetidos:
    posicoes = indicesDeElementoNaLista(elemento, A)
    elementosCorrespondentes = elementosNasPosicoes(B, posicoes)
    dicionarioResultante[elemento] = elementosCorrespondentes
print(dicionarioResultante)

e para a soma de cada conjunto fazia:
A = [12,   15,  10,  15,  12,  10,  10,  10,  15,  12,  12,  15,  15,  15]
print set(A)
B = [0.2, 0.3, 1.1, 0.2, 0.2, 0.7, 0.4, 0.6, 0.1, 0.3, 0.7, 0.4, 0.5, 0.5]
B_lin = {} # coloque um nome mais adequado ao seu contexto

for elemento in set(A):
    posicoes = indicesDeElementoNaLista(elemento, A)
    elementosCorrespondentes = elementosNasPosicoes(B, posicoes)
    B_lin[elemento] = elementosCorrespondentes
B_Total=[]
for chave in set(A):
    B_Total.append(sum(B_lin[chave]))
    print chave, B_lin[chave]
#print B_Total

e obtinha:
set([0, 1088, 1602, 1089, 9999, 1107, 1615, 1616, 1010, 1011, 1108, 1015, 1114, 1115])
set([10, 12, 15])
10 [1.1, 0.7, 0.4, 0.6]
12 [0.2, 0.2, 0.3, 0.7]
15 [0.3, 0.2, 0.1, 0.4, 0.5, 0.5]

ou seja o set ordena do 10-12-15, enquanto que eu precisava que a ordem se mantivesse: 12-15-10, porque depois os resultados da pesquisa dos elementos por índice na lista não são coerentes com os apresentados nesta função da soma e a ideia é os valores serem no final passados para um Excel pela forma em que surgem inicialmente.
Se em vez da soma quiser o mínimo de cada conjunto faço:
Ili = []
listas_min = []
ind=[]
for i in range(len(indice)):
    valor = A[indice[i]]
    listas_min.append([])
    for j in range(len(A)):
        if A[j]==valor:
            listas_min[i].append(B[j])
            ind.append(j)
    Ili.append(min(listas_min[i]))
#print(Ili)
print ind

e funciona, dá-me o valor mínimo para cada conjunto. Tentei retornar também o respectivo índice da lista original (A) e não em ASemRepetidos em que isso acontece, através de .index mas não não consegui.
Comment: O minimo de cada conjunto não tem um indice respectivo mas sim o conjunto dos indices. È isto que pretendes? Se sim guarda o j no loop quando A[i]==valor.
Comment: em que sitio mesmo do código é que tenho que guardar? não está a dar...
Comment: Logo a seguir a listas[i].append(B[j]). Faz outra lista como a "listas" para guardar os indices.
Comment: Tive que fazer uma alteração de novo no código porque não estava a calcular bem os mínimos, agora já está mas se fizer isso que dizes não dá.. dá-me os índices todos em vez de dar o do valor do mínimo de cada conjunto...
Comment: Pensei que era isso que querias. Editei o fim da resposta com codigo para tirares o indice do minimo de cada conjunto.
Answer: Se percebi o problema bem então a seguinte solução deverà resolver o problema:
somas = []
listas = []
for i in range(len(indice)):
    valor = A[indice[i]]
    soma = 0
    listas.append([])
    for j in range(len(A)):
        if A[j]==valor:
            soma = soma + B[j]
            listas[i].append(B[j])
    somas.append(soma)
print(indice)                  # Indice correcto
print([A[i] for i in indice])  # Valores de A nos indices correctos
print(somas)                   # Somas por cada indice correcto
print(listas)                  # listas por cada indice correcto (que foram somadas)

, o resultado é:
[0, 1, 2]
[12, 15, 10]
[1.4, 2.0, 2.8000000000000003]
[[0.2, 0.2, 0.3, 0.7], [0.3, 0.2, 0.1, 0.4, 0.5, 0.5], [1.1, 0.7, 0.4, 0.6]]

, e este codigo foi corrido logo a seguir a encontrares os valores do primeiro indice que se repete:
indice=[]
feitos = [] # vou guardar aqui todas as chaves que já ocorreram no loop.
indic = {} # Se quiseres ter uma ligação directa entre chave e indice...
for k in A:
    if k in ASemRepetidos and k not in feitos:
        indice.append(A.index(k))
        feitos.append(k)
        indic[k]=A.index(k)

EDITADO:
Para teres os minimos e e indices dos minimos:
minimos = []
indminimos = []
for i in listas:
    minimos.append(min(i))
    indminimos.append(B.index(min(i)))
print(minimos)
print(indminimos)

, que resulta em:
[0.2, 0.1, 0.4]
[0, 8, 6]

Comment: Quando faço o minimo em vez da soma faço assim:

minimos = []
listas_min = []
for i in range(len(indice)):
    valor = A[indice[i]]
    listas_min.append([])
    for j in range(len(A)):
        if A[j]==valor:
            #minimos.append(min(I_ac2[j]))
            listas_min[i].append(B[j])
    minimos.append(min(listas_min[i]))
print minimos

e funciona, dá-me o valor mínimo para cada conjunto. Tentei retornar também o respetivo indice da lista original (A) e não em ASemRepetidos em que isso acontece, através de .index mas não não consegui...
Comment: @SofiaRaimundo È bastante dificil perceber codigo a partir de um comentario. Faz uma edição na tua pergunta ou abre uma questão nova (eu sugiro que abras novas questões para novas perguntas caso contràrio os posts ficam confusos e desnecessariamente longos).
Comment: Já editei, portanto a minha dúvida agora é só a última parte, relativa ao indice do mínimo @armatita


src sem imagem não desaparece

Question: Eu estou a usar o JSON com base de dados e eu estou com um problema: quando não há uma imagem no JSON, em vez da tag  não aparecer, ela aparece como se a imagem desse erro:

Existe alguma forma de quando o src nao é encontrado no JSON, a tag img não aparecer?
Código:
var image3: obj.imagem3;
var image: obj.imagem;

$("#imagemareas3").attr("src", this.image3);
$("#imagemareas").attr("src", this.image);

JSON:
[
    {
        "titulo": "Exemplo",
        "imagem": "",
        "imagem3": "",
        "id": 0
    }
]

Comment: Exatamente. Não faz sentido você inserir o elemento `` na página se o `src` será vazio.
Comment: Sim, não inserir a imagem na página ¯\\_(ツ)_/¯
Comment: Se te interessa vc sabia que vc pode estilizar e customizar uma imagem que não carrega? Elá não precisa aparece assim vc pode tratar a imagem que falha no carregamento, leia mais aqui https://pt.stackoverflow.com/questions/321138/como-fazer-um-estilo-para-imagem-quebrada-quando-a-imagem-n%C3%A3o-carrega
Comment: @AndersonCarlosWoss mas eu preciso disso porque em outros arrays do json ja tem la uma imagem mas para caso não tenha uma imagem aquilo desaparece
Answer: O ideal seria a TAG img nem existir no DOM e não esconder a mesma. Como notei que faz uso do jQuery, deixo abaixo algumas opções com o framework e também uma opção com CSS (que não recomendaria, uma vez que você não quer a imagem no DOM).
Opção 1 (recomendada)
Você poderia adicionar as imagens no DOM, apenas se o endereço não fosse vazio. Segue abaixo um exemplo:
html

javascript
// código javascript para adicionar elas na div
if(obj.imagem)
   $('#images').append('');
if(obj.imagem3)
   $('#images').append('');

Opção 2
Você também pode remover a imagem do DOM caso a propriedade não seja preenchida. Segue abaixo um exemplo:
this.image3 ? $("#imagemareas3").attr("src", this.image3) : $("#imagemareas3").remove();
this.image ? $("#imagemareas").attr("src", this.image) : $("#imagemareas").remove();

Opção 3
Mas caso insista em manter a TAG no DOM você pode fazer uso do CSS para esconder a imagem (vale lembrar que é apenas uma solução de contorno e não recomendo o uso), segue exemplo:
img[src=""],img[src="null"], img[src="undefined"] {
     display: none;
}

Comment: @DavidMv combinado, eu atualizei a resposta com uma segunda opção.
Comment: A "segunda opção" deveria ser a primeira (e única) opção. Eu recomendaria primeiro ensinar a fazer certo, depois fazer gambiarra (opcional).
Comment: @AndersonCarlosWoss você está correto, vou atualizar a resposta!
Comment: @AndersonCarlosWoss obrigado a observação, resposta atualizada.
Comment: Está correcto assim que poder eu dou-te o certo!

src sem imagem não desaparece


Databinding Enum to ComboBox

Question: I'm getting a very unusual error on a project that use to work where I'm trying to bind an ENUM to a combo box.  To ensure I've not made coding errors, I've made a new usercontrol using SO Question 58743 and ageektrapped as samples for a self contained user control.  I'm using .Net4 Client Framework as the environment and VS2010.  The xaml is -
<UserControl x:Class="Barcode.Views.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:System="clr-namespace:System;assembly=mscorlib"
             mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300">

    <UserControl.Resources>
        <ObjectDataProvider MethodName="GetValues"
                            ObjectType="{x:Type System:Enum}"
                            x:Key="AlignmentValues">
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="HorizontalAlignment" />
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </UserControl.Resources>
    <Grid>
        <ComboBox Name="myComboBox" SelectedIndex="0" Margin="8"
                  ItemsSource="{Binding Source={StaticResource AlignmentValues}}" />
    </Grid>
</UserControl>

The error that I'm getting on the ComboBox is Error   144 Unable to cast object of type 'System.String' to type 'System.Windows.DataTemplate' after building the project.
I'm at a loss as to what could be causing this error.
Answer: Looks like you may be missing the namespace on your HorizontalAlignment. Add a relevant namespace where the HorizontalAlignment type resides.
xmlns:local="clr-namespace:Barcode.Views"

Then modify your XAML to make use of the newly defined namespace...
...

<x:Type TypeName="local:HorizontalAlignment"/>

...

EDIT:
With this being the HorizontalAlignment enum type from within the framework then your code should work as is. I tested it to be certain and it indeed works; as I placed an instance of the UserControl on my Window and it worked without a hitch. Set up an empty project and start from scratch to see if the problem still exists as you may have other factors causing the issue.
Comment: Actually for this demo, I was trying to get the Horizontal alignment enums (left, right, center) as a know enum that works.  This is how many of the demos have been written.
Comment: @photo_tom Added addition commentary, just copied/pasted your code and it does indeed work
Comment: @Aaron - That what is I've seen.  However, in this project and another new project, I cannot get the code to run without the error.
Comment: @photo_tom So you went to add new UserControl and selected WPF UserControl (not WinForms) within the IDE then copied/pasted the above code and changed the x:Class for the UserControl and it will not compile?
Comment: @Aaron - After compile, the combo box is reporting being in an error state.  If I go to run it, I will be a XAML parsing error.  But I just tried building a completely new solution and it works there.  There must be something corrupt in my solution, but I cannot figure out what.
Comment: @photo_tom Could be global templates within your App.xaml or other embedded resource. Make sure you have all your varying templates commented out in some fashion and see what happens.
Comment: @Aaron - That was it.  There is a problem with global template.  Thanks.

Databinding Enum to ComboBox


Passing String Parameters with C++ and Assembly x64

Question: i have this code
#include <iostream>
#include <conio.h>

using namespace std;
extern "C" char * DDD(char * h, int j);

int main()
{
char * g = "RRRR";
cout << "HELLO Says " << DDD(g, strlen(g)) << endl;
_getch();
return 0;
}

and this
.data
gh db 'Y'
.code
DDD proc
lea rbx, [rcx]
push rbx
a20:
mov al, gh
mov byte ptr [rbx], al
inc rbx
dec rdx
cmp rdx, 0
jnz a20
pop rbx
mov rax, rbx
ret
DDD endp
end

what im doing is to replace RRRR to become YYYY. i get errors at
mov byte ptr [rbx], al

it says access violation.
im new to assembly and i just want to know how to solve it. correction of assembly code is appreciated too.
thanks.
Answer: The "RRRR" string is stored in read-only memory. You should replace its declaration by something like char g[] = "RRRR"; to be able to write to it.
Comment: That's a good thing. Please consider accepting the answer if it fitted your need!


I want to select branch id,branch location where sum of total item is greter than 11 in mongodb

Question: entire_collection[{
    "_id" : ObjectId("571ca6076e589915f893ee8c"),
    "cbill_details" : [
        {
            "c_branch_id" : "b25",
            "c_branch_location" : "Kolkata",
            "c_total_item" : NumberInt(5),

        },
        {
            "c_branch_id" : "b27",
            "c_branch_location" : "Kolkata",
            "c_total_item" : NumberInt(7),

        },
    ]
}
{
    "_id" : ObjectId("571ca6076e589915f893ee8f"),
    "cbill_details" : [
        {
            "c_branch_id" : "b25",
            "c_branch_location" : "Kolkata",
            "c_item" : NumberInt(9),

        },
        {
            "c_branch_id" : "b27",
            "c_branch_location" : "Kolkata",
            "c_item" : NumberInt(3),

        },
    ]
}]

group by "c_branch_id" and "c_branch_location" where the sum of "c_item">11 in mongodb
here b25 in 1st document contains item= 5 and in 2nd document, item =9.so the b25 wise total item is (5+9)=14 and in case of b27 total item is 10. then after executing query the output will be b25 and its corresponding location.
Comment: Use MongoDB [Aggregation](https://docs.mongodb.org/manual/aggregation/) with [unwind](https://docs.mongodb.org/manual/reference/operator/aggregation/unwind/)
Answer: fistly you need aggregation query to match data for your question
and your query is like this
db.entire_collection.aggregate(
{$unwind : "$cbill_details"},
{$group : {"_id" : {"c_branch_id" : "$cbill_details.c_branch_id",
                    "c_branch_location" : "$cbill_details.c_branch_location"},
                    "total_item" : {"$sum" : "$cbill_details.c_total_item" }}},
{$match : {"total_item" : {$gt : 11}}}
)

and your document is  a bit diffrent because your one field is "c_total_item"and another filed is "c_item"
and mongodb agregation documention link is here : https://docs.mongodb.org/manual/aggregation/


mstmp, Google Apps

Question: I'm using Google Apps for my domains email, but should I use mstmp and hook it into sending via Google Apps? The reason I ask this is if I have to send high volumes of email, for example people signing up to my site in quick succession and receiving emails, or batch sending of emails, will Google support/allow this?
Thanks.
Answer: Google Apps only supports sending a maximum of 2,000 e-mails per day, per account.
Pasted from their FAQ:

Q: I have to send out a lot of emails
  on a daily basis. Does Google Apps
  have a sending limit?
A: Each account can currently send
  email to 2,000 external recipients per
  day to prevent abuse of our system and
  to help fight spam. If one of your
  mail accounts reaches the limit, the
  account will be temporarily unable to
  send mail.

Source: http://www.google.com/apps/intl/en/business/faq.html

mstmp, Google Apps


Passing a ball trough different bags - bayes theorem

Question: So let's say we have 3 bags that all contain 5 white and 4 black balls. Now we take a ball from the first bag, pass it to the 2nd bag, take the ball out of there and pass it to the third bag, and finally a ball from the third to 1st bag again.
What's the probability that the number of whites increased in the first bag?
The answer is 0,244 but I'm not sure how to get it.
For the number of white balls to increase in the first bag as far as I understand we can only take a black ball from there, from the second bag we can take ether black or white and from the third bagonly white so we pass it into the first bag. How to write this down?
Comment: Write down the conditional probabilities for the cases.
Comment: A tree diagram works well.
Answer: You're right:
This is of course the probability that the ball picked from bag 1 was black, and the one from bag 3 at the end is white, for otherwise, you don't get any increase in white balls for bag 1.
So, consider the following events:
A) black ball from bag 1 to bag 2 + white ball from bag 2 to bag 3 after that
B) black ball from bag 1 to bag 2 + black ball from bag 2 to bag 3 after that
Calculate the probability of each of these paths, and then multiply A by $0.6$ (because bag 3 has 6 out of 10 white balls now) and $B$ by $0.5$ (because bag 3 has 5 out of 10 white balls now) and add them up.
No Bayes' theorem needed.
So:
$P(A) = \frac{4}{9}\cdot \frac{5}{10}$ (5 out of 10 in bag 2 are white)
$P(B) = \frac{4}{9}\cdot \frac{5}{10}$ (5 out of 10 in bag 2 are black)
And $P = P(A)*0.6+P(B)*0.5$
Comment: Alrighty I was doing something like this, but for some reason didn't get the exact number, thanks!:)
Comment: @CyprusN Did this get the right number? I didn't even calculate ..  Oh yes, it does, since it's 1.1*2/9 = 1.1*0.222 = 0.2444.. Cool! Glad I could help!
Comment: @Bram28: well, actually , you  *have applied* the Bayes Theorem!
Comment: @Bram28 I have another question lol. So let's say we have 3 rooms and we lost a key in one of them. Probability to find the key in 1st one is A, in the 2nd B, if we search them nicely the prob. to find in 1st is A1 in 2nd is B2 and in 3rd C2. So I had a question about whats the probability that the key is in the 3rd room, I did A2*(1-A)+(1-B)*B2 and get the answer, but the second question is whats the prob that the key is in the 3rd room if we search them. I tried doing (1-A2)*(1-A)+(1-B2)*(1-B)+C but the answer isn't correct, any ideas?]
Comment: Its another  question, so make another post.
Answer: The only draw sequences that work are
$$\text{B,W,W}\;\;\text{or}\;\;\text{B,B,W}$$
The sequence $\text{B,W,W}$ occurs with probability
$$
\left(\frac{4}{9}\right)
\left(\frac{1}{2}\right)
\left(\frac{3}{5}\right) = \frac{2}{15}
$$
and the sequence $\text{B,B,W}$ occurs with probability
$$
\left(\frac{4}{9}\right)
\left(\frac{1}{2}\right)
\left(\frac{1}{2}\right) = \frac{1}{9}
$$
hence the desired probability is
$$\frac{2}{15} + \frac{1}{9} = \frac{11}{45}$$


Inductive sets with chains of finite elements.

Question: An inductive set is said to be a partially ordered set P that satisfies the hypothesis of Zorn's lemma when nonempty (that is every chain in P has a least upper bound).
1)Now is it true that if a poset P satisfies the condition that every chain in P is finite , then P is inductive;
2)As a result every finite poset is inductive and the discrete poset is inductive  ;
Answer: If a partial order is finite, then every chain is finite, and therefore has a maximum, which is indeed the least upper bound of that chain.
As for the partial order given by the $=$ relation, indeed, it satisfies the hypothesis of Zorn's lemma, and indeed, every element is maximal.
Comment: by discrete I mean every set   with partia order such that $x\leq_P y \Leftrightarrow x=y$
Comment: Ah. Okay. I'll edit my answer.
Answer: The hypothesis of Zorn's lemma isn't that every chain should have a least upper bound, but rather that every chain has an upper bound.
Every finite non-empty chain has a maximum, which is an upper bound.


Is there a common left hand position in accordion?

Question: I'm an amateur accordion player who is having difficulties with the bass side. There's no problem when I'm using close keys such as jumping from C to A. But when I need to jump to a further key such as from A to Bb, I usually press a wrong key.
Is there a common (or natural) left hand position preferred by accordionists? I mean, is there a way that accordionists position their left hand on the accordion? Do they know it just by looking at the chords in the song?
I've watched several accordionists on Youtube and couldn't figure out any specific style.
If the answer is no, what do you recommend me to improve my left hand? Do you recommend any source of exercise set?
Comment: This is a very generic point, but one thing that really helps me with my violin technique is to ask my teacher. You may be able to find an accordion teacher who would do a one-off lesson. Who knows, you may end up coming back for more.
Comment: Thank you for your comment. I actually have a teacher. He told me that I could put my hand as I like. But I wondered if there is any common technique for that.
Comment: You could pick up converter/MIII accordion.  That way one gets a lot of practice in finger changes, intervals and so on.  The normal standard bass play rarely requires that kind of stuff.  The somewhat less resource-intensive version is practicing the bass line play on standard bass.  Try finding music that uses the standard bass for a lot more than Oom-pah accompaniment.  If you can play scales and later melodies by ear on the standard basses, you'll be a lot better acquainted with distances and finger changes and so on.
Answer: The accepted answer states proposes the middle finger on the key bass to start.  It is listed under "as a general rule (for my songs so far)".  I tend to suspect that the parenthetical remark points to little actual experience underlying the urge to provide a helpful answer to another beginner.
That's actually a rather strange starting position: the typical Oom-pah accompaniment using (lower case chord, upper case bass note) C-c-G-c (4/4) or C-c-c-G-c-c (3/4) can be fingered 4-3-2-3 and 4-3-3-2-3-3 respectively (assuming that thumb-index-middle-ring-pinky are numbered 1-2-3-4-5).  While minor key Oom-pah C-cm-cm-G-cm-cm can be played well using the 4-2-3-2 pattern, it is more usual to revert to 4-3-4-3 here: minor keys tend to involve a lot of switching between major, minor, and seventh chords, and playing the basic minor pattern starting with 4-2 rather than the major-typical 4-3 requires planning ahead for comparatively little gain.  One could make do by playing everything 4-2-3-2, but that makes for crowded fingers in the major chord scenario.
Apropos seventh chords: you don't want to be playing the bass note with the middle finger (second row) when the actual chord to be played with the index finger is in the fifth or even sixth row.
Don't take my word for it: just look at a number of videos from convincing players: while they are rather flexible in what kind of fingers they use while playing runs etc, the basic action starter is almost always the ring finger.
Note that this is for playing the customary 2+4 (2 bass rows, 4 chord rows) layout.  If you are playing 3+3 (some French button accordions, and quite fewer Italian ones) with a focus on bass runs, the starting position might conceivably be different.  And don't get me started on the Belgian bass system...
Answer: I think your answer might depend on what style (and key, and so on) of music you are playing, as well as what size (style? I don't know the word) of accordion you are using.
I use the standard 120-button size accordion, and as a general rule (for my songs so far) I place my middle finger on C to start. I think I shift my middle finger to the key of the song I'm playing in.
If a song requires chords that are not easily accessible from a "root" position of middle finger on the base of the key, you may want to find a nicer position or learn to shift. Exercises that helped me learn to shift were simply practicing arpeggios and scales, starting slowly while reading the chord chart, and moving towards memorization and faster speeds. You could also try playing the bass line of difficult songs alone. I'm sure your instructor has more ideas for left-hand improvement etudes.
Answer: The 4-3 tech is now used more common than the old 3-2 tech, means the ring finger is used on the bass & counter bass bottons-ie 4th finger.
Answer: Everyone's hands are different. Try different finger arrangements. If you have long fingers try 6 rows of bass. If you have short fingers try 5 rows of bass.
I have short stubby fingers, so I play a 26 key 48 bass piano accordion. To reach the circle of 5ths I use my middle finger, and when playing alternating bass I use my index and forefinger.
Best of luck
Answer: I switch back and forth between 3-2 and 4-3 depending on what chord I need to play next...CM7 vs Cm7 vs Cm6 for example
Comment: Could you expand this to explain what 3-2 and 4-3 are, and give more detail about your examples?


Why does my Excel function have too many arguments?

Question: Can anyone tell me what is wrong with this function? Thanks so greatly!!
=IF(B4<7500, "POOR",IF(B4<10000, "GOOD","GREAT",IF(B4>12500,"EXCELLENT"))
Comment: Hint: What condition is supposed to trigger "GREAT"?
Comment: IF takes three parameters. You feed it four. That's one too many.
Answer: Here you go:
<code>=if(B4 < 7500, "POOR", if(B4 < 10000, "GOOD", if(B4 < 12500, "GREAT", "EXCELLENT")))
</code>
Note, this assumes that your B4 values are numbers, so you can add error handling if needed.
Answer: You could use a lookup function instead of nested IFs. Either store the values in a table in a spreadsheet (easy to maintain) or write the value pairs into the formula:
<code>=LOOKUP(B4,{0,7500,10000,12500},{"poor","good","great","excellent"})
</code>


Is $ S = \{(x,y) \in \mathbb{R}^2 \colon x^2 = y^3\} $ an immersed submanifold of $\mathbb{R}^2$?

Question: I know that it is not an embedded submanifold because it is not locally Euclidean with the subspace topology, and I feel that it is not an immersed submanifold, because its tangent space at $(0,0)$ has dimension $2$ which would mean that it has to be a smooth manifold of dimension $2$. But if that happens, then since we have that the inclusion map is a smooth immersion, it ends up being both a smooth immersion and a smooth submersion (since the dimensions of $S$ and $\mathbb{R}^2$ are equal) which means that it's a local diffeomorphism. But, it is also bijective onto its image meaning that it is a diffeomorphism onto $S$ with the subspace topology, which is a contradiction. Kindly let me know if my reasoning and conclusion are correct or not.
Answer: (This is basically the same argument as the one in Example 5.45 of J.Lee's book Introduction to Smooth Manifolds)
The answer is no. Suppose that somehow we could make $S:=\{(x,y)\mid x^2=y^3\}$ into an immersed submanifold of $\mathbb{R}^2$. Then $S\setminus\{(0,0)\}$ can be considered as a smooth manifold in two ways- first, as an open submanifold of $S$, and second, as an embedded submanifold of $\mathbb{R}^2$ (for it is a disjoint union of graphs of smooth functions). Now it is a fact that if a subset of a smooth manifold is an embedded submanifold with respect to some smooth manifold structure, then there is no other smooth manifold structure making the same set into an immersed submanifold. Therefore, the two smooth manifold structure for $S\setminus\{(0,0)\}$ coincide. Since $S\setminus\{(0,0)\}$ is 1-dimensional, it follows that $S$ has to be $1$-dimensional, too.
Now let $\gamma:(-\varepsilon ,\varepsilon )\to M$ be any smooth curve starting at the origin. Write $\gamma(t)=(x(t),y(t))$. Because $y(t)$ attains its global minimum at $t=0$, we have $\ y'(0)=0$. We also have $x(t)^2=y(t)^3$ for all $t$; differentiating the both sides and evaluating at $t=0$ gives $x'(0)=0$. Thus $\gamma'(0)=0$. Since $\gamma$ was arbitrary, it follows that the tangent space $T_{(0,0)}M$ of $M$ at the origin is $0$-dimensional, a contradiction.
Comment: For future readers: the proof of the fact mentioned in the first paragraph follows from the proof of Theorem 5.31 in the book.
Answer: To find out the dimension of $S$ you have to consider the tangent space at a smooth point.
Since  $S$ is the zero set of the function $f(x,y)=x^2-y^3$, a point $(x,y)$ is smooth (i.e. admits a neighbourhood diffeomorphic to euclidean space) iff $Df(x,y)\neq 0$.
This shows that $0$ is not a smooth point and it also shows (by using the implicit function theorem) that $S\backslash \{0\}$ is indeed a smooth 1-dimensional submanifold of $\mathbb{R}^2$.
On the other hand you can see that the map $\gamma:\mathbb{R}\rightarrow \mathbb{R}^2, \gamma(t) = ( t^3,t^2)$ is smooth map onto $S$. This is a topological embedding but not an immersion (since $\gamma'(0)=0$).
Edit: $S$ is not an immersed submanifold. Assume otherwise, then there is an immersion $I=(I_x,I_y):\mathbb{R}\rightarrow  \mathbb{R}^2$ onto $S$. We may assume that $I(0)=(0,0)$. Again by the implicit function theorem we find a neighbourhood $(-\epsilon,\epsilon)$ of $0$, such that $I((-\epsilon,\epsilon))$ is an embedded submanifold of $\mathbb{R}^2$. $I$ has to be injective, because otherwise its image $S$ would contain a loop, which is impossible since we already know that $S$ is homeomorphic to $\mathbb{R}$. Injectivity of $I$ implies that $I_x$ is strictly monotic (assume increasing), thus $I((-\epsilon,\epsilon))=S\cap\{I_x(-\epsilon)<x<I(\epsilon)\}$. (We have just assured that the singularity at $(0,0)$ does not come from a self intersection nor from approaching itself) But this implies that $S\cap\{I_x(-\epsilon)<x<I(\epsilon)\}$ has a one dimensional tangent space at $(0,0)$ which is not true as you've already found out.
Comment: Yes, this was the first parametrization that came to my mind, but I realised that it isn't an immersion. So then, is $S$ an immersed submanifold?
Comment: $S$ being an immersion would mean that the singularity at the origin comes from a self intersection and that locally all intersecting branches would be submanifolds. My edit shows that this is not true.
Comment: Why does $S$ being an immersed submanifold imply that there is an immersion from $\mathbb{R}$ onto $S$?
Comment: That is simply the definition. What is an immersed submanifold to you?
Comment: Or is your question why the domain of the immersion is $\mathbb{R}$ rather than some other manifold $N$?. That has an easy answer: $N$ has to be $1-$dimensional, because $S\backslash\{0\}$ is and up to diffeomorphisms there are only two $1-$dimensional manifolds, the real line and the circe. If $N$ was a circle, then the image of the immersion would be compact, but $S$ is not. Hence $N=\mathbb{R}$.
Comment: I'm using John M. Lee's Intro to Smooth Manifolds, and he defines a subset $S$ of a manifold $M$ to be an immersed manifold if $S$ is endowed with a topology, with respect to which it is a topological manifold (without boundary), and a smooth structure with respect to which the inclusion map from $S$ to $M$ is a smooth immersion.


Como dividir uma string em MySQL?

Question: O meu banco de dados MySQL contém uma tabela t_usuario com uma coluna nome, onde há um registro com o nome Gustavo Henrique Almeida Martins.
Como posso fazer um SELECT para retornar apenas o nome Gustavo?

id_usuario
nome

1
Gustavo Henrique Almeida Martins
Answer: Você pode usar a função SUBSTRING_INDEX.
O primeiro parâmetro é o valor que você deseja dividir, o segundo é por qual caractere a string será divida e o terceiro é qual dos valores cortados você deseja.
SELECT
   SUBSTRING_INDEX(NOME, ' ', 1) AS PrimeiroNome
FROM USUARIOS

Veja funcionando no SQL Fiddle
Comment: Aqui deu certo. Valeu!
Comment: @GustavoMartins Por nada. Para constar: você pode aceitar a resposta que mais te ajudou marcando o **V** do lado esquerdo dela.
Comment: Quem votou contra poderia aproveitar e me dizer qual o problema? =D
Answer: Acredito que vai ajudar:
SELECT
    SUBSTRING_INDEX(SUBSTRING_INDEX(nomecompleto, ' ', 1), ' ', -1)  AS primeironome
    ,TRIM( SUBSTR(nomecompleto, LOCATE(' ', nomecompleto)) ) AS sobrenome
FROM
    suatabela

SQL Fiddle

Como dividir uma string em MySQL?


Expose a SQL server database with a load balancer

Question: We have several Machines that communicate with each other inside a VPC on AWS. All of them are in privete subnets with no public IP address.
One of those machines is a MSSQL server, our main Database.
In our office we have a vpn tunnel with this vpc and can use private IPS.
I am trying to securely gain access over the internet to the database from my home, trying to not modify the database instance.
I created a public load balancer that listens to tcp 1433 and passes the traffic to the instance also to port 1433; this gives me database access however I am worried it is not secure.
I would like the traffic to be encrypted going to the load balancer and then hitting the DB like as regular traffic after that.
Is this possible using a load balancer?
I have a domain, and a certificate throu aws certificate manager.
Comment: Your problem and question are unclear. Would you say your problem is you want secure access to the database from home, as well as work? Can you explain why you created a load balancer, and how that is relevant to the question? How have you configured secure database access from work? What is your subnet setup?
Comment: Hope it's more clear now
Answer: The easiest way to do this is to create the database with "publicly accessible" turned on, which must be done at creation time. Once this is done you must ensure the security group is opened up to allow access from the IPs you desire. I believe AWS provides the route to the internet, I don't think you have to route it.
Another option would be to establish a VPN session into your work network, and from there use the existing VPN onto the database instance.
If you haven't created the database with that option you could use some kind of a bastion host as a proxy. That is described quite well here, I see no need to copy and paste the answer. This question and answer gives more detail on setting up a bastion host.
Using a load balancer as a proxy is an interesting choice, I'd never even considered that as it's not typically done that way. Load balancers would typically sit in a public DMZ, with the web servers in another subnet, and the database another subnet back, so the ELB shouldn't have database access. A flat network with your servers and database in the same subnet increases risk. I would probably prefer to use an EC2 instance, as I can add more security. You could make it a VPN endpoint and use it as a proxy.


bad substitution shell- trying to use variable as name of array

Question: #!/bin/bash
array=( 2 4 5 8 15 )
a_2=( 2 4 8 10 )
a_4=( 2 4 8 10 )
a_5=( 10 12 )
a_8=( 8 12 )
a_15=( 2 4 )
numberOfTests=5
while [ $i -lt ${#array[@]} ]; do
    j=0
    currentArray =${array[$i]}
    *while [ $j -lt ${#a_$currentArray [@]} ]; do #### this line i get ->>>> bad substitution*
        ./test1.sh  "${array[$i]}" -c "${a_"$currentArray "[$j]}" &
        let j=j+1
    done
    let i=i+1
done

so Im trying this code, loop over an array(called array), The array should point out
the array number we are now looping(a_X). And every time to point out the current place and value.
can anybody help me how im using the $currentArray to work properly so I can know the length of the array and the value?
I get in the line I marked an error.
Thank you guys!
Comment: `bash` doesn't do nested parameter expansions. It's not clear how to accomplish what you want. What version of `bash` are you using? (Namerefs in `bash` 4.3 may make this easy/possible.)
Answer: The simplest solution is to store the full names of the arrays, not just the numerical suffix, in array. Then you can use indirect parameter expansion while iterating directly over the values, not the indices, of the  arrays.
# Omitting numberOfTests has it does not seem to be used
array=(a_2 a_4 a_5 a_8 a_15)
a_2=( 2 4 8 10 )
a_4=( 2 4 8 10 )
a_5=( 10 12 )
a_8=( 8 12 )
a_15=( 2 4 )
for arr in "${array[@]}"; do
    currentArray=$arr[@]
    for value in "${!currentArray}"; do
        ./test1.h "${arr#a_}" -c "$value" &
    done
done


What does recycling the app pool actually do exactly?

Question: I have had a number of problems in the past that have been solved by simply recycling the app pool.
I am currently getting an error occurring about once every other day (SQL server timeout oddly enough) that will continue persist until the app pool is recycled and so I wondered what does this do exactly?
Many thanks,
Kohan.
Answer: The app pool is the webservices deployed on your iis instance. They can either be backend services behind your website or front end webservices. Either way if you are getting a timeout from a SQL server instance it means that these webservices are either losing their connection to the database or it's become non-responsive for that DB session.
By refreshing the pool you are fundamentally restarting the application and re-establishing the DB connection(s).


JAVA inheritance access

Question: I'm currently learning JAVA and got confused on the access in inheritance. The case below:
public class Father{
    private int age;

    public void setAge(int a){
        age = a;
    }

    public void getAge(){
        System.out.println(age);
    }
} //End of Father

public class Son extends Father{

} //End of Son

public class Test{
    public static void main(String[] args) {
        Father F = new Father();
        Son S = new Son();

        F.setAge(40);
        F.getAge();

        S.setAge(20);
        S.getAge();

        //System.out.println(F.age);
    }
} //End of Test

In the case above, "age" is a private variable in Father. Although Son extends Father, this private variable "age" is not inherited. Which means there is no variable in Son.
But when I put them into Test, running result shows "40" and "20", as if there was an int variable in Son. How to explain this?
Comment: Good answers are already given below, but one design comment... logically it would seem better to rename your parent class to "Human" or "Person" rather than "Father".  There's nothing in the Father class which is specific to "human who has offspring", so it would probably serve you well to name it something more generic.
Comment: Thanks guys, I just found another question http://stackoverflow.com/questions/4716040/does-subclasses-inherit-private-fields and that explained thoroughly.
Comment: Lesson learnt, many thanks :) @paulk23
Answer: age is inherited. It's just that you can't access it directly from son.
If you want to access it directly in son then mark it as protected and not private, i.e. declare
 protected int age;

in the Father class.
(By the way, the normal thing to do would be to have getAge() return an int, and your calling function write the age to the console).
Answer: setAge() and getAge() are the public methods and the instance variable is being accessed through those methods, which are directly inherited.  The instance variable is not being accessed directly, i.e. by direct manipulation outside methods in the class Father.
Answer: Private variables are still there in subclasses; they are just not visible to the subclass.  Since the getAge() method is public in the superclass, and thus in the subclass, you can still invoke it to cause the private variable to be printed.
Comment: lol, meant to add the example to my answer but we all jumped on this one :-)
Comment: Yeah, I don't think your edit makes any sense in the context of my answer.  In the context of your answer, it would make sense.
Answer: Your setters and getters are public so they are exposed in to the sub-class Son.  The code for the setter and getter is contained in the super-class Father which has access to the private field 'age' in that class definition.
If you were to change the setter and getter to private then the sub-class Son would not have access to age field in the super-class Father.
public class Father{
    // only this class may access the field directly
    private int age;

    // this class,sub-classes and package classes may set the age
    protected void setAge(int a){
        age = a;
    }

    // you can get the age from anywhere
    public void getAge(){
        System.out.println(age);
    }
} //End of Father

JAVA inheritance access


Problems with parsing JSON for D3

Question: I am building an app with Flask and Python, and I want to pass some of my Python-generated results into JSON, so that they can be visualized with D3 under a container fluid. To do this, I am trying to use the Jinja method var myjson = {{jsonDict|tojson }};. Here jsonDict is a variable in my Python code that is a string of a dict, where single quotes have been replaced with double quotes with a regular expression, so that it looks like proper JSON. I am also using the JS method root = JSON.parse( myjson );. I believe that the combination of these two should solve my problem, but when I run the code, however I am getting the error:
(index):2222
Uncaught SyntaxError: Unexpected token y in JSON at position 0
uo  @   d3.v3.min.js:3
i   @   d3.v3.min.js:1

Here is the D3 template that I am trying to use:
http://bl.ocks.org/mbostock/7607535
Here is my implementation of this D3 (just the relevant script):

As you can see, I replaced the original JS lines from the D3 code:
d3.json("flare.json", function(error, root) {
  if (error) throw error;

with:
var myjson = {{ jsonDict|tojson }};
    root = JSON.parse( myjson );

    d3.json("root", function(error, root) {

As I have my code now, if I inspect the page, the svg shows up on the webpage in the correct place, but it is blank.
I am new to D3 and Javascript. Any help would be much appreciated! Thank you!
EDIT - console logs
if I do console.log(myjson), the console prints the string of the JSON properly (see below)
if I do console.log(root), the console prints
Object {children: Array[2], name: "flare"}
children:Array[2]
name:"flare"
__proto__:Object
__defineSetter__: __defineSetter__()
__lookupGetter__:__lookupGetter__()
__lookupSetter__:__lookupSetter__()
constructor:Object()
hasOwnProperty:hasOwnProperty()
isPrototypeOf:isPrototypeOf()
propertyIsEnumerable:propertyIsEnumerable()
toLocaleString:toLocaleString()
toString:toString()
valueOf:valueOf()
get __proto__:__proto__()
set __proto__:__proto__()

So it seems that the JSON.parse method is failing me somehow.
EDIT -- my JSON string that is being passed from Python into var myjson
{"name": "flare", "children": [{"name": "concept0", "children": [{"name": "intermediate host", "size": 700}, {"name": "abstrusus brevior", "size": 700}, {"name": "stage larva", "size": 700}, {"name": "anterior extremity", "size": 700}, {"name": "crenosoma vulpi", "size": 700}]}, {"name": "concept1", "children": [{"name": "infected cat", "size": 700}, {"name": "abstrusus infection", "size": 700}, {"name": "domestic cat", "size": 700}, {"name": "feline aelurostrongylosis", "size": 700}, {"name": "cat infect", "size": 700}]}]}

pagesource for console.log(myjson)
{"name": "flare", "children": [{"name": "concept0", "children": [{"size": 700, "name": "intermediate host"}, {"size": 700, "name": "abstrusus brevior"}, {"size": 700, "name": "stage larva"}, {"size": 700, "name": "anterior extremity"}, {"size": 700, "name": "crenosoma vulpi"}]}, {"name": "concept1", "children": [{"size": 700, "name": "infected cat"}, {"size": 700, "name": "abstrusus infection"}, {"size": 700, "name": "domestic cat"}, {"size": 700, "name": "feline aelurostrongylosis"}, {"size": 700, "name": "cat infect"}]}]}

EDIT - I think the problem can be seen in console.log(root). I've checked other D3 visualizations and the log should typically look like this:
Object {name: "flare", children: Array[5]}
children: Array[5]
depth:0
name:"flare"
r:470
value:21000
x:470
y:470
__proto__:Object

Comment: use console.log(root) to see what root is in the developer console of whatever browser you're using. Verify you root is proper JSON, and in the right format D3 is expecting.
Comment: @SnarkShark Thanks - and is that exactly how it's listed in the page source? Would you mind copying the output line beginning `var myjson =` ?
Comment: You are using `tojson()` in your jinja template. **This function converts the given object into JSON representation.** so why do you need to use `JSON.parse()` afterwards? Can you not just pass in `myjson`?
Comment: The `d3.json` takes a url as its parameter, its an ajax request in essence, but you already have your data there so dont need to call this. Try running your code without the `d3.json()` function
Comment: @Craicerjack, if you'd like, you can copy/paste your response about the `d3.json()` function as a answer to my question, that way I can accept it as the best answer and you'll get credit for answering a question :)
Comment: console.log(root) shows up as an "Object", but console.log(myjson) prints out the JSON string properly (but doesn't define it as an object or anything). I've used JSON.parse before on this same data (but different D3 code) and it worked fine. I guess I need a different method to make it read as JSON? Thanks for your input!
Comment: Can you share the JSON string? It looks like the format may not be valid.
Comment: @Owen I have added it at the bottom. Thanks!
Comment: @Owen, sorry I didn't see this sooner! Yup, `var myjson` is listed in the page source exactly the same as my JSON string. I'll add it to my post as well.
Comment: @Craicerjack, I just tested it and you are correct that  `JSON.parse()` makes no difference in my code. Without it, (and re-naming the `tojson()` object "root" instead of "myjson"), I still get the console error: "Uncaught SyntaxError: Unexpected token y in JSON at position 2222" and the D3 visualization does not show up. (Position 2222 is the `if (error) throw error`)
Comment: Looking at your code again and you have `d3.json("root", function(error, root) {` this is passing in the string `"root"` to the `d3.json` method and not the variable `root`. You should remove the double quotes from this
Comment: @Craicerjack When I removed the `d3.json()` function it worked as it should! Thank you! I would like to better understand WHY I cannot use the function here. Is it because I only need the function if I have a url because of ajax?  Thanks again! :D
Answer: Because you are already passing your json to your client via your flask application there is no need to use d3's d3.json() method. d3.json() is essentially an ajax GET request which requests the file from the server.

d3.json(url[, callback])
Creates a request for the JSON file at the specified url with the mime
  type "application/json". If a callback is specified, the request is
  immediately issued with the GET method, and the callback will be
  invoked asynchronously when the file is loaded or the request fails;
  the callback is invoked with two arguments: the error, if any, and the
  parsed JSON. The parsed JSON is undefined if an error occurs. If no
  callback is specified, the returned request can be issued using
  xhr.get or similar, and handled using xhr.on.

You already had your data stored in a variable on in your javascript so there was no need to request it from the server.
Also when you tried to request it you were passing in an invalid url.
Removing the d3.json() function and just running the rest of the code should work.

Problems with parsing JSON for D3


How to make nested Service calls in Angular2 using observables?

Question: Below are my component file and service file. What I want to do is that the after verification() service method on its success callback i.e., inside subscribe I want call another service method i.e., signup(). But, its not working showing me following error:

Previously in angular1 if i do this it would work but not here:
sampleService.meth1().success(function(){
            //statement1...
            sampleService.meth1().success(function(data){
            //statement2...
        }).error(function(){})
    }).error(function(){});
})

Signup.component.ts
import { Component, Input } from '@angular/core';
    import { Router } from '@angular/router';
    import {User} from '../shared/model/user';
    import {SignupService} from './signup.service';
    import 'rxjs/add/operator/map';
    import 'rxjs/add/operator/catch';
    import 'rxjs/add/operator/debounceTime';
    import 'rxjs/add/operator/distinctUntilChanged';
    import 'rxjs/add/operator/switchMap';
    import 'rxjs/add/operator/toPromise';

    @Component({
        moduleId: module.id,
        selector: 'ym-signup',
        templateUrl: 'signup.component.html',
        styleUrls: ['signup.component.css'],
        providers: [SignupService]
    })

    export class SignupComponent {

        @Input()
        user = {};

        constructor(private router:Router, private signupService:SignupService) {
        }

        signup(selectedUser:User) {
            this.signupService.verification(selectedUser)
                .subscribe(data => {
                        swal({
                            title: 'Verify token sent on your Email.',
                            input: 'password',
                            inputAttributes: {
                                'maxlength': 10,
                                'autocapitalize': 'off',
                                'autocorrect': 'off'
                            }
                        }).then(function (password) {

                            this.signupService.signup(password)
                                .subscribe(data => {

                                        localStorage.setItem('user', JSON.stringify(data));
                                        this.router.navigate(['dashboard']);
                                    },
                                    error => alert(error));
                        })
                    },
                    error => alert(error));
        }

        goBack() {
            this.router.navigate(['login']);
        }
    }

Signup.service.ts
import {User} from '../shared/model/user';
import { Headers, Http } from '@angular/http';

import 'rxjs/add/operator/toPromise';
import {Injectable} from '@angular/core';
import {Response} from "angular2/http";
import { Observable }     from 'rxjs/Observable';

@Injectable()
export class SignupService {

    private postUrl:string = '/api/users/signup';
    private verify:string = '/api/users/verify';
    constructor(private http:Http) {
    }

    verification(user:User):Observable<JSON> {
        let headers = new Headers({
            'Content-Type': 'application/json'
        });

        return this.http
            .post(this.verify, JSON.stringify(user), {headers: headers})
            .map(this.extractData)
            .catch(this.handleError);
    }

    signup(token:string):Observable<any> {
        let headers = new Headers({
            'Content-Type': 'application/json'
        });

        return this.http
            .post(this.postUrl, JSON.stringify({verificationToken:token}), {headers: headers})
            .map(this.extractData)
            .catch(this.handleError);
    }

    private extractData(res: Response) {
        let body = res.json();
        return body || { };
    }

    private handleError(error: any) {
        let errMsg = (error.message) ? error.message :
            error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.error(errMsg);
        return Observable.throw(errMsg);
    }

}

Comment: Use arrow function instead of `function`
Answer: Judging by the error Cannot read property 'signup' of undefined it looks like you're calling signup() on a non-existing object.
And it's correct, you're creating the closure as .then(function (password) { ... }) which doesn't capture the surrounding context this and therefore is called with this = window which is not what you want obviously.
See: https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html
So you can easily fix it with an arrow function:
.then(password => {
    this.signupService.signup(password)
        .subscribe(data => {
             localStorage.setItem('user', JSON.stringify(data));
             this.router.navigate(['dashboard']);
        }, error => alert(error));
})

Comment: thx it worked I was not expecting that sweetalert was causing the problem. One more thing if you can help after the verification() success I want to prompt user for input and then put that input in signup() method before calling.
Comment: Well, most easily before calling `this.signupService.signup(password)...` ask the user for credentials with JavaScript's standard `prompt()` function that shows a popup window. See http://www.w3schools.com/jsref/met_win_prompt.asp
Then use the value in `signup()` method
Answer: In the signup method you are giving a function as the callback for then.
You should as arrow function instead to keep the same context.
 signup(selectedUser:User) {
            this.signupService.verification(selectedUser)
                .subscribe(data => {
                        swal({
                            title: 'Verify token sent on your Email.',
                            input: 'password',
                            inputAttributes: {
                                'maxlength': 10,
                                'autocapitalize': 'off',
                                'autocorrect': 'off'
                            }
                        }).then(password => {

                            this.signupService.signup(password)
                                .subscribe(data => {

                                        localStorage.setItem('user', JSON.stringify(data));
                                        this.router.navigate(['dashboard']);
                                    },
                                    error => alert(error));
                        })
                    },
                    error => alert(error));
        }

Answer: Use Observable.forkJoin() to run multiple concurrent http.get() requests. The entire operation will result in an error state if any single request fails.
Please find the snippet usage below :

getBooksAndMovies() {
        Observable.forkJoin(
            this.http.get('/app/books.json').map((res: Response) => res.json()),
            this.http.get('/app/movies.json').map((res: Response) => res.json())
        ).subscribe(
            data => {
                this.books = data[0]
                this.movies = data[1]
            },
            err => console.error(err)
        );


Subspaces of different dimension

Question:
Suppose I have 2 finite dimensional vector spaces $W, V$, and $\text{dim } V > \text{dim} W$

Is it possible that some subset of $W$ is a basis for $V$?
Answer: No. Assume, for contradiction, that such a subset exists. Then it would be linearly independent (by assumption) and would span not just $V$ but also $W$. So being a subset of $W$ that is both linearly independent and a spanning set for $W$, the set would be a basis for $W$. But then $\dim W = \dim V$, a contradiction.
Answer: Unfortunately, the answer is YES it is possible, assuming that the vector spaces can be over different fields.
Consider the following two vector spaces:

Let $W$ be the vector space $\Bbb C$ over the field $\Bbb C$, which is one-dimensional with basis $\{1\}$
Let $V$ be the vector space $\Bbb C$ over the field $\Bbb R$, which is two-dimensional with basis $\{1,i\}$

We have $\dim W<\dim V$ and yet $\{1,i\}$ is a subset of $W$ which also acts as a basis for $V$.
The point being, a set might be linearly dependent in one vector space while being linearly independent in another depending on the field used.

Subspaces of different dimension


Why won't jpeg save properly to AWS S3 from django

Question: I'm trying to save a user uploaded file directly to S3 without saving it locally. This project is using Django 1.9 and Boto3.
The relevant code is:
p=request.FILES['img'].read()
s3=boto3.resource('s3',
    aws_access_key_id=settings.AWS_ACCESS_KEY_ID,
    aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY)
b = s3.Bucket(settings.AWS_STORAGE_BUCKET_NAME)
b.put_object(Key="media/test.jpg", Body=p)

This correctly uploads a file called 'test.jpg' to the media folder.
However, if I download 'test.jpg' from Amazon and try to open it in an image viewer, I get the message: "Error interpreting JPEG image file (Not a JPEG file: starts with 0xf0 0xef)". The jpg file is also only 26kb whereas the original was 116kb.
What is going wrong? I assume I am passing the wrong data as Body in the put_object method. But what should p be instead?
Update and Solutions
With JordonPhilips's help, I realised that because I had already opened the uploaded image earlier in the view with Pillow, the request.FILES['img'] socket had already been read.
The solution I went with was to remove the Pillow code, leaving the boto upload as the first access of request.FILES['img'].
However, I also figured out a solution if you want to do something to the image first (e.g. in Pillow):
from Pillow import Image
import cStringIO as StringIO
import boto3

and then in the view function:
im = Image.open(request.FILES['img'])
# whatever image analysis here
file2 = StringIO.StringIO()
im.save(file2,"jpeg",quality='keep')
s3 = boto3.resource( 's3', aws_access_key_id=settings. AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY)
b = s3.Bucket(settings.AWS_STORAGE_BUCKET_NAME)
b.put_object(Key="media/test.jpg", Body=file2.getvalue())

Comment: @JordonPhillips Thanks for the suggestion, looked at my code in more detail and found the problem. I had already opened the file 10 lines earlier with PIL `im = Image.open(request.FILES['img'])`. If I don't do that, it gets sent to Amazon just fine with `Body=request.FILES['img']`
Comment: Could you inspect 'p' to see what it looks like before you send it along?
Comment: you can pass the `file` object directly to `put_object`: `p=request.FILES['img']`
Comment: @JordonPhillips p is of type `str` and len 0 !?
Comment: @ahmed Then I get `ClientError: An error occurred (BadDigest) when calling the PutObject operation: The Content-MD5 you specified did not match what we received.`
Answer: It looks like your problem was that you were trying to read the socket multiple times. You can only read the socket once, so you need to keep reference to important information.


force to download remote image immediately without HTML5

Question: I trying to force to download a remote image (url with https protocol), I failed to attempts do it on client (cannot use HTML5, thanks to IE8), so I'm trying to use server side (php).
The only way how to do it I found thanks following answer, is using curl. Other way like readfile($file_url), always return an empty file. The problem with using curl - downloading starts after image is downloaded to server and it can take some time. Can we start loading directly from the source?
But if somebody know a way how to download an image on client side, that already on the page, it will be great!
Comment: The question isn't clear... do you perhaps mean *upload* to the server rather than download?
Comment: What do you mean by 'force'?
Comment: No, the main idea to allow user download image from the page (like "save image as..."), but image is situated on other server.
Comment: And the hoster of these remote images is OK with what you are trying to do – you have their explicit consent?
Comment: Yes, it is ok, it is our other server just some content should be shown on other site.
Answer: You can use fopen('http://server/img.jpg'), and fread():
$handle = fopen("http://www.example.com/image.jpg", "rb");
while (!feof($handle)) {
  echo fread($handle, 8192);
}
fclose($handle);

plus headers.
Comment: $handle is empty after fopen, maybe some problems with php.ini, but "allow_url_fopen" is set to "On" state
Comment: one more thing that remote images url has https protocol
Comment: The default is not to verify peer, so certificate shouldn't be a problem.
Comment: but it was a problem, php_openssl was disabled, your solution works as well as readfile($file_url), when php_openssl is set to enabled. Thanks!


Likert item as independent variable for ANOVA?

Question: I am trying to analyze data based on a sample size of around 50 and would appreciate advice on which statistical test would be most appropriate. Participants, on a single questionnaire, were asked to complete two different sections. Variable 1: rating Likert items on a scale from 1-5 (strongly agree to disagree). Variable 2: rating Likert items of a validated tool on a scale of 1-9, which is averaged to obtain a single number.
My research question is: Do those who 'agree' with the statement in the first section significantly differ in terms of their scores on the variable 2, compared to those who 'disagree'? (ex. Do participants tend to 'agree' with "I like to read books for pleasure." have higher IQs (variable 2) than those who 'disagree'?)
I was advised by a colleague to run a one-way ANOVA with variable 1 (categorical) as IV and variable 2 (continuous) as DV.
Question 1:
My independent variable is the three groups: 'agree', 'neutral', and 'disagree.' (I combined strongly agree with agree because of low frequencies and likewise for strongly disagree and disagree.) However, there are many more participants in the 'agree' category than in the 'disagree' category. The distribution is, on average, around 44 agrees, 3 neutrals, and 3 disagrees. Do the (very) unequal sample sizes prevent me from performing ANOVA, or any other tests? Which test would be most appropriate for this analysis?
Question 2:
I would like to run analyses on all of the Likert items, which is more than 10 statements. (ex. Seeing how IQs correlate with agreement to many statements including "I like to read books for pleasure," "I watch a lot of TV," "I exercise more than 30 minutes each week," etc.) I was planning to do a Bonferroni correction to adjust for the multiple tests. Would this be correct, and help make my analyses more robust?
Note: The continuous data are not normally distributed (there is negative skewness), but I seem to be able to correct the skewness using logarithmic transformation.
Any advice or suggestions for papers to read would be appreciated. Thank you!
Comment: ANOVA is definitely a bad choice, as your data are ordinal, not nominal. Collapsing the 5 ratings into 3 also wastes information. It's difficult to answer without information about the structure of the questionnaires. Do you assume each is unidimensional, or do you really want to treat each item as a separate construct?
Comment: @NickStauner Thanks for pointing out the ordinality of the variable. Missed that. Questionnaire: the first section is a series of 10+ Likert items. These questions were constructed by our team (not a validated tool). Each item has its own importance and we would like to treat the items separately in the analysis. The section section is the Likert scale that is averaged to obtain a single score. Does this help?
Answer: A way to improve upon ANOVA with an ordinal predictor is to use dummy codes in penalized regression. Penalized regression takes advantage of the ordering among the response categories in Likert scale data: it reduces overfitting by smoothing differences in slope coefficients for dummy variables corresponding to adjacent ranks. See Gertheiss and Tutz (2009) for an overview of penalized regression for ordinal predictors. I've discussed penalized regression here a few times before:

Effect of two demographic IVs on survey answers (Likert scale)
Continuous dependent variable with ordinal independent variable
Can we use ordinal or multilevel predictors directly into logistic regression?

Unfortunately, this approach probably won't do well for categories with very few observations, and I don't know of any that would. Inferential power is necessarily limited with samples so unbalanced as to have very few observations in groups of interest. Correcting for familywise error would raise the bar even further out of reach, even if that's where it belongs. Whether it is depends on whether you mean to test one big hypothesis several times on separate but related measures, or whether you want to evaluate each hypothesis test separately; familywise error adjustment isn't necessary for the latter.
If you can't collect more data, might as well give the test a shot, but give some thought to the degree of evidence you want to see. You probably won't have enough power to distinguish small differences from the null hypothesis with p < .05, so using the Neyman–Pearson framework for dichotomizing p values interpretively is probably unrealistic (more so than usual, that is). There are less polarized ways of understanding p values – one might also call them more equivocal ways, but that's probably more appropriate with relatively weak evidence anyway. For more on interpreting p values, see for instance:

Is the exact value of a 'p-value' meaningless?
Why are 0.05 < p < 0.95 results called false positives?
Now that I've rejected the null hypothesis what's next?

The recommendation to focus on effect size estimation and confidence intervals may help here too, because it is in essence a recommendation to focus on what you can know from your data, even if it's not "enough to reject" a null hypothesis. Plotting your results may help give you a sense of what's really going on too. Don't feel that confirmatory hypothesis testing is your only option unless you have good reason to; you may be able to get some good ideas of hypotheses to test further by just exploring your data, even if you can't really conclude anything very firmly from what you have.
One last option to consider is treating your Likert scale data as continuous. This is a big assumption (that you're effectively already making with regard to your Variable 2), so keep it in mind when interpreting anything you do based on that...but it would allow you to compute correlations between each item's ratings and your Variable 2. In this case especially, you'd not want to collapse the dis/agree and strongly dis/agree categories. Also bear in mind that a t-test of a correlation assumes bivariate normality, so you might want to consider alternatives for any hypothesis tests on those effect size estimates as well.

Reference
Gertheiss, J., & Tutz, G. (2009). Penalized regression with ordinal predictors. International Statistical Review, 77(3), 345–365. Retrieved from http://epub.ub.uni-muenchen.de/2100/1/tr015.pdf.
Comment: Thank you! I will look into penalized regression as an alternative to ANOVA. I don't quite understand your point with not having enough power for p < .05. I was able to find statistically significant differences with ANOVA (p < .05). Were you trying to say that there isn't enough power for this finding to be meaningful?
Comment: @user49440: No, I was just betting that your effect size would be too small to detect with *N* = 50. Sounds like you're on to something though! Penalized regression will just reduce the estimated differences between adjacent levels of the predictors. E.g., if the DV is lowest for people who disagreed and highest for people who agreed, penalized regression will make more moderate predictions for people who were neutral. This might make your effects seem smaller or simpler, but theoretically, that is probably the more appropriate prediction for future samples / the rest of the population.