humming and actual singing?

Question: I have a friend, who is not professionally trained in music. When she hums (with her mouth closed), she hits the right notes and everything. When she actually starts to sing, I felt her notes appear to be all over the place. I have caught her singing when she is not aware she's singing...sort of like she's singing subconsciously, and she managed to hit right notes again. What gives? Is this simply a case of lack of practice?
Answer: Short answer: The behavior you describe is pretty common, and the result of a combination of physiological and psychological differences.
Longer answer: First, humming increases the "internal resonance" your vocal chords produce. This increases your ability to hear yourself while humming, and so if you have any ability to perceive tone, you will also be better able to tune yourself while humming than while singing.
Also, because the air is leaving through your nose, a smaller opening than your mouth, you're introducing more "back pressure", which in moderation actually improves most of the positioning of the diaphragm, mouth, throat and nasal passages that are taught by vocal coaches as "good technique". The throat widens, the soft palate lifts, and the nasal passages open. In addition, because of the back pressure, your exhalation is controlled with less concentration on your part. This results in less variation in tone due to changes in positioning of these things which can push pitches around.
This phenomenon is used by many vocal coaches during warm-ups, to encourage the singers to maintain what they feel when humming as they open their mouth. By doing so, the singers naturally adopt many good habits that can be further tweaked by the coach.
There are also some psychological things at play. If you cannot hear yourself well, or don't want anyone to hear you, you will naturally sing more quietly. For an untrained singer, the two "natural" ways to do this are to drop the breath support (which drops the pitch; imagine the sound a bagpipes makes as the bladder runs out of air and the drones stop), or to close off the throat (which normally pinches notes sharp). Both are bad technique; the "right" way to sing more softly is to use the diaphragm to reduce the amount of air going through the vocal chords without completely dropping breath support. Simply being nervous, knowing that people are listening, will also make a singer trend sharp because of the natural tensing of a whole host of muscles controlling breath and voice.
Being nervous coupled with bad singing technique will cause notes to go totally wild, as the lack of breath control pushes notes flat while the nervousness trends them upward, and one or the other will "win" on each note.
Comment: Hmm, but your "when an untrained singer tries to be quiet, the notes are off" doesn't agree with the OPs description, does it?  When the person mentioned doesn't think someone's hearing her, I'd suspect she *does* sing quietly.  At least more quietly than when she sings "in public".
Comment: When a person knows they are being listened to, they will tense up, and if they don't want to be listened to they will reduce their volume. Both of these will cause the "tug of war" I mentioned where the lack of breath support pulls flat while the tensing up pushes sharp.
Comment: KeithS, great answer!
Answer: Weird! It's probably to do with psychology of performance and social pressures. I base this on the presumptions that:

She doesn't see herself as a singer.
When she's not paying attention to herself, she sounds fine.

Since you have observed her being pitch-accurate (whether singing or humming), we can conclude that she has at least a rudimentary ear, even if it isn't well-developed through training. A rudimentary ear--able to hear a melody, internalize it at some level, and then replicate it--is all one really needs to be able to sing socially (i.e. hold a tune in a bucket, sing in key). There is virtually no difference between singing and humming (humming is simply singing on an 'm' sound).
I would guess that when her notes are all over the place, she's in a sort of "I don't sing; this is what it sounds like when I try to sing" mindset. What results from this mindset are behaviors or habits that are counterproductive to actually singing in key. Maybe she thinks she has to "oversoul" it, sing too loudly, or maybe she's just yelling because the alternative is too embarrassing. I have no idea; you'll have to figure that one out for yourself.
To resolve the issue:

She has to want to sing, and understand that singing is fun and is really nothing like what you see on TV.
She has to agree that she can hum in key.
She has to understand that singing is just humming with one's mouth open.

For an exercise, she could try humming a simple tune on an 'mmmm' syllable, then try it on an 'nnnnn'. Then, slowly and on each note, start on 'nnnnn' before opening to 'aaaaa', and then do the same with 'mmmmmaaaaaaaa'. Last, use only the 'ah' syllable.
That's about as broken-down as I think it can get. Let me know in a comment if any of this was the least bit helpful or applicable to your situation!
Comment: I'd say, more than "wanting" (which seems to be important, no argument) she has to believe in herself, her ability.  Your point 2 is, I think much more important.  (Spoken from personal experience of insecurity)
Comment: she actually gave a couple of "bad" performances and 1-2 people directly and indirectly suggested that singing is not meant for her.... since then, even if her notes are in place, her voice simply shakes! she really wants to sing, but... anyway, ever since I brought her attention to her humming quality, it seems to have gone down as well. she told me she sings even worse when she's alone. She wants to practice but she's afraid if she practices using wrong technique, she may do more harm than good?
Comment: @JürgenA.Erhard, yes, but the thing is sometimes she sings pretty good, sometimes not... so I see the potential, but she can not feel secure with such fluctuation in quality.
Comment: @progtick And the quality will fluctuate as long as she doesn't feel secure.  I don't see any other even potential reason.  If she can sing, at least some of the time, she *can*.  It's only her mind that's in the way.  And yes, we have a Catch-22 there...
Comment: @JürgenA.Erhard ... this catch-22 must also have a solution... have one in mind? :)

humming and actual singing?


On hover effect on a SVG group

Question: I'm working on a pretty big map with lots of different areas and text on top of them, sort of like countries. I want to add a on mouse hover effect when hovering over this area. The effect should add a shadow and change its opacity. When I hover out of the area the opacity should go back to its original and the shadow effect should go away. I managed to do this but when I add text into this area it messes things up. The on hover effect gets called again when I hover on the text that's inside area when it shouldn't be called again at all. I made a fiddle that works until i hover on the text as well. I'm using the D3.js library for the coding.
 var groupAreas = "";

 groupAreas = d3.selectAll(".area-group");

 groupAreas.on("mouseover", fadeInArea)
   .on("mouseout", fadeOutArea)
   .on("click", zoomIn);

 var initialOpacity = 0;

 function fadeInArea() {
   //Get its initial opacity
   initialOpacity = d3.select(this).select("path").style("opacity");

   d3.select(this).transition(500).attr("filter", "url(#shadow-filter-1)").style("cursor", "pointer");
   d3.select(this).select("path").transition(500).style("opacity", 0.7);
 }

 function fadeOutArea() {
   d3.select(this).transition(500).attr("filter", null).style("cursor", "default");
   d3.select(this).select("path").transition(500).style("opacity", initialOpacity);

 }

https://jsfiddle.net/qx5u9uo4/6/
the area has an original opacity of 0.4. When i hover over the area it changes to 0.7 and the shadow effect is added. When I go out, it goes back to 0.4 as it should. Yet if i go in the area and also hover over the text the OnMouseOver gets called again and it then sets 0.7 as original opacity and thus never goes back to 0.4 again when I actually go outside the area.
I think the problem may lie with my order of DOM svg elements?
  <g class="area-group">
    <path id="area-1" d="M502.2 581.4h-53.5v-61l167.4 70.4v34.6H502.2z" />
    <text transform="translate(542.4 614)"> FOO </text>
    <text transform="translate(459.4 571.2)"> BAR </text>
    <text transform="translate(521.1 592.9)"> / </text>
  </g>

Answer: Sounds like you just want to stop the text elements from receiving pointer events:
.area-group>text {
  pointer-events: none;
}

On hover effect on a SVG group


Default constructor in android.os.AsyncTask is deprecated

Question: I have some troubles with this warning in Android Studio in one of my java classes.
Default constructor in android.os.AsyncTask is deprecated.. I use latest target SDK.
<code>public CleanFilesTask(@NonNull Context context, @NonNull Consumer < Integer > callback) {
        Objects.requireNonNull(context);
        mContentResolver = context.getContentResolver();
        mCallback = Objects.requireNonNull(callback);
    }
</code>
How to solve this warning and make it not showing deprecated? XD
Link for full class: https://github.com/D4rK7355608/com.d4rk.cleaner/blob/master/app/src/main/java/com/d4rk/cleaner/invalid/task/CleanFilesTask.java
Comment: From the [`AsyncTask` documentation](https://developer.android.com/reference/android/os/AsyncTask): "*This class was deprecated in API level 30. Use the standard java.util.concurrent or Kotlin concurrency utilities instead.*"
Comment: You forgot to ask an actual question.
Comment: Thanks XD I want it to make it not showing that "deprecated" without disable inspection in settings. I tried to search on Android Developers and didn't find any solution XD
Comment: Ahh, didn't noticed this. Thanks so much!
Answer: according to google doc:

This class was deprecated in API level 30.
Use the standard java.util.concurrent or Kotlin concurrency utilities instead.

you can check concurrent tutorial on this link,
and how to migrate from AsyncTask to concurrent here


Hook_enable vs hook_install [granting permissions to user role]

Question: In Drupal 7, I'm trying to grant a permission to a user role using hook_install and it doesn't work. But it works with hook_enable. Do you know how to make it work with hook_install as well?
function porta_batch_editor_install() {
  $permissions = array('access porta batch editor');
  //grant 'access porta batch editor' permission to pb role
  foreach(array('pb role') as $role_name) {
    $role = user_role_load_by_name($role_name);
    user_role_grant_permissions($role->rid, $permissions);
  }
}

It works with the following approach:
function porta_batch_editor_enable() {
  $permissions = array('access porta batch editor');
  //grant 'access porta batch editor' permission to pb role
  foreach(array('pb role') as $role_name) {
    $role = user_role_load_by_name($role_name);
    user_role_grant_permissions($role->rid, $permissions);
  }
}

Comment: I believe it didnt work with hook_install because I was disabling and re-enabling the module, when I uninstalled and enabled it, it worked(on my dev site). So, afaik, re-enabling a module doesnt trigger hook_install.
Answer: It should work on install. Are you actually uninstalling the module? Disabling and uninstalling is not the same thing in Drupal 7. Uninstall at admin/modules/uninstall, once the module is disabled. You can use drush pm-disable/pm-uninstall module_name.

test.module
function test_permission() {
  return array(
    'test permission' => array(
      'title' => t('Test permission title'),
    ),
  );
}

test.install
function test_install() {
  $test_perm = array('test permission');

  $perms = module_invoke_all('permission');
  // We can find the 'test permission' in $perms.

  $role = user_role_load_by_name('administrator');
  user_role_grant_permissions($role->rid, $test_perm);
}

The above gives administrators the test permission on module install.


calculate $\int_{-\infty}^{+\infty} \cos(at) e^{-bt^2} dt$

Question: Could someone please help me to calculate the integral of:
$$\int_{-\infty}^{+\infty} \cos (at) e^{-bt^2} dt.$$
a and b both real, b>0.
I have tried integration by parts, but I can't seem to simplify it to anything useful. Essentially, I would like to arrive at something that looks like: 7.4.6 here:
textbook result
Comment: yep! But... I can't seem to simplify it to anything useful. Essentially, I would like to arrive at something that looks like: 7.4.6 here http://people.math.sfu.ca/~cbm/aands/page_302.htm
Comment: You need to specify the domain.
Comment: Sorry. done now
Answer: Do you have restrictions on 'a' and 'b'?
For example, they are real and > 0.
Otherwise, things are messy!
See here for details.
Comment: a and b are both real; and b>0.

Hmm.. I should have written this question up a bit better. I apologise.
Answer: Hint:
Use the fact that
$$\int_{-\infty}^\infty e^{iat- bt^2}\,dt = \sqrt{\frac{\pi}{b}} e^{-a^2/4b} $$
which is valid for $b>0$.
To derive this formula, complete the square in the exponent and then shift the integration contour a bit.
Comment: Hey @fabian , what does it mean to 'shift the integration contour'? I am not familiar with such a thing/method?
Comment: Thanks! I think I see what you mean now.
Comment: I think it must be $\,a^2/4b\,$ in the exponent of the exponential, because of that $\,i\,$ there...
Comment: @DonAntonio: I checked again. I believe it is correct. Note that $i a t - b t^2 = -a^2/4b -b(t-ia/2b)^2$.
Comment: You're right, of course. I oversaw that minus sign before the quadratic term. Thanks.
Comment: Actually, you overlooked that minus sign.


Finding compute and sm numbers in a binary file

Question: I have a binary file compiled with cuda enabled features and gcc. I want to know which cuda architectures are included in the binary file?
I mean sm and compute compatibility numbers which are -gencode arch=compute_XX,code=sm_XX.
Comment: https://docs.nvidia.com/cuda/cuda-binary-utilities/index.html#cuobjdump
Answer: NVIDIA ship binary utilites which can display headers and disassemble the binary payloads in object files, libraries, and executables. cudaobjdump can be used as follows:
$ nvcc -arch=sm_62 -std=c++11 -I ./ main.cu -o main
$ cuobjdump ./main

Fatbin elf code:
================
arch = sm_62
code version = [1,7]
producer = <unknown>
host = linux
compile_size = 64bit

Fatbin elf code:
================
arch = sm_62
code version = [1,7]
producer = cuda
host = linux
compile_size = 64bit

Fatbin ptx code:
================
arch = sm_62
code version = [5,0]
producer = cuda
host = linux
compile_size = 64bit
compressed

Which shows both the binary and PTX payloads included in the executable.


Mapping complex objects with reflection

Question: Im making a function that maps two diferent objects (with equivalent properties and types) using reflection and generic objects (T). My function works well with objects with simple properties like int or string types but now I have to add support for object properties or lists wihtin an object. Can I do this recursively or is it not posible ? I can't post the code for work reasons.
The active code is the following:
<code>    public static T MapObjects<T>(object sourceObject) where T : new()
    {
        T destObject = new T();

        Type sourceType = sourceObject.GetType();
        Type targetType = destObject.GetType();

        foreach (PropertyInfo p in sourceType.GetProperties())
        {
            PropertyInfo targetObj = targetType.GetProperty(p.Name);
            if (targetObj == null)
                continue;

            targetObj.SetValue(destObject, p.GetValue(sourceObject, null), null);
        }
        return destObject;
    }
</code>
Can I modify this function to call itself when the property is an object ?
Comment: You can post your own, non-work, sample code so we can see what you've got so far. The majority of questions without any code get closed for the reason "too broad" or something like "questions about 'why isn't this code working' must include code".
Comment: This question is very vague without code. What specifically do you wish to do recursively? Please add a [mcve].
Comment: Why not use AutoMapper?
Comment: Second vote for automapper
Comment: You are asking: Can I modify the code to call itself: Why do you not simply try that and see if it works?
Answer: You can look at Protobuf.net (which can be installed as Nuget package). It is based on Google protocol buffer and is fairly easy to serialize and deserialise objects or copy objects.
Protobuf-Net as copy constructor
https://www.c-sharpcorner.com/article/serialization-and-deserialization-ib-c-sharp-using-protobuf-dll/
Getting started with protobuf-net
Comment: The problem with this answer, is its just a link to a nuget package, with no reference to how it solves the problem
Comment: Added a link for stackoverflow. I can provide a sample code if ud like

Mapping complex objects with reflection


How can I programmatically validate that an user has uploaded an image in CCK?

Question: I have an image field defined using CCK.  I need to detect or validate that the image has been uploaded.  Is it possible?
Thanks to all.
Answer: You may have to use hook_form_FORM_ID_alter().Define your own module and in your module try the following code
<code>function yourModuleName_FORM_ID_alter(&$form, &$form_state) {
  $form['#validate'][] = 'yourModuleName_FORM_ID_validate';
}

//your validation function
function yourModuleName_FORM_ID_validate($form, &$form_state) {
  if (isset($_FILES['files']) && is_uploaded_file($_FILES['files']['tmp_name']['machine_name_of_the_cck_field'])) {
    // File uploaded
  }
  else {
    //File not uploaded
  }
}
</code>
Answer: Even easier, you can do it with Rules on condition "Field xx has changed".
Answer: You can just set the CCK image field as a required field and the form won't validate unless the user uploads an image.


Divs floats em um container com height auto

Question: Estou tendo um problema para estruturar um layout com algumas divs uma do lado da outra e quando não couber mais caixa elas passem para baixo. E o container principal precisa aumentar de acordo com quantas caixa tiver. Mais ou menos assim:

Mas não sei porque  não está funcionando, o container principal não aumenta de tamanho. Meu código:
HTML

CSS
#container{
    width:610px;
    height:AUTO;
    border:1px #FF0000 solid;
}
.caixas{
   width:200px;
   height:200px;
   border:1px #00FF00 solid;
   float:left;
}

JSFiddle
Answer: Você pode usar uma técnica conhecida como clearfix, que consiste em que o próximo elemento ou pseudo-elemento tenha display:block; e clear:both;, garantindo que ele aumente por mais que o conteúdo esteja com float:left;.
Veja este exemplo:
jsFiddle
Esta mesma forma é adotada por frameworks CSS como o Twitter Bootstrap por exemplo.
Comment: Adicionei um exemplo na resposta para ficar mais compreenssível.
Comment: Rapaiz muito obrigado funcionou direitinho.
Comment: Imagine ^^, estamos aqui para nos ajudar ^^
Answer: Fiz algumas alterações
CSS:
#container{
    width:620px; // aumentei para 620
    height:AUTO;
    border:1px #FF0000 solid;
}
.caixas{
   width:200px;
   height:200px;
   border:1px #00FF00 solid;
   display:inline-block; // retirei o float e usei display:inline-block

}

Display: inline-block
Para visualizar o código em funcionamento clique aqui
Answer: Eu particularmente resolvo isso com um float:left no elemento pai. Mas o correto mesmo é usar o clearfix que o amigo Diego Lopes Lima comentou.
Answer: A propriedade CSS "overflow" especifica o que acontece se o conteúdo excede a caixa de um elemento, dando até a possibilidade de controlar as barras de rolagens laterais e horizontais.
Veja mais sobre a propriedade: CSS Overflow
Utilizando ela podemos resolver o seu problema com apenas 1 linha de código, basta adicionar esta propriedade com o valor "hidden" nos estilos do seu container.
Veja como fica seu código ajustado:
#container{
    width:610px;
    height:AUTO;
    border:1px #FF0000 solid;
    overflow:hidden;
}
.caixas{
   width:200px;
   height:200px;
   border:1px #00FF00 solid;
   float:left;
}

http://jsfiddle.net/j7Nk8/3/
Comment: Sua resposta não é correta para está situação.
Comment: Interessante sua opinião. Posso saber porque pensa dessa forma?
Comment: Seu texto realmente explica a funcionalidade da propriedade `overflow` do CSS, porém neste caso o problema apontado pela pergunta é sobre o elemento que encapsula outros elementos que usam `float:left;`. Isso faz com que este elemento não aumente conforme o conteúdo a menos que um elemento ou pseudo-elemento com visualização em bloco seja colocado logo em seguida com `clear:both;`.
Comment: Creio que foi apenas uma confusão de link's, você parece ter pegado o link que eu passei na resposta para ver o erro, e acabou pegando já resolvido, por isso deve ter interpretado errado...
Comment: Talvez eu tenha feito alguma confusão nos links mesmo, mas ainda acho a minha resposta a mais adequada pra pergunta. Usar o último item com "display:block;" realmente funciona, mas pra mim isso é considerado gambiarra. Link corrigido obrigado.
Comment: Bom, considerar uma gambiarra realmente é algo de opinião própria, porém essa tecnica é utilizada como a melhor solusão por os maiores framworks CSS existentes atualmente. Incluindo Twitter Bootstrap, que é a ferramenta front end mais usada no mundo. Se você tiver uma tecnica de clearfix desconhecida mais eficiente com certeza todos nós gostariamos de entender e o criador do Twitter Bootstrap Mark Otto também ficaria feliz em atualizar o repositório.
Caso queira aprender um pouco sobre aqui está o arquivo escrito em LESS: https://github.com/twbs/bootstrap/blob/master/less/mixins/clearfix.less


Why am I getting a black image after replacing all the pixels of a BufferedImage object with magenta colored ones?

Question: I am following a Java Game development tutorial, and I hit a roadblock because I am unable to figure out what is wrong with my code. I am supposed to render a new image by changing each pixel of the buffered image into the color I want. Then I copy that array over to the array in my Game class and I draw the rendered image. The relevant code is directly below. I discuss what I have tried directly after the code snippets.
This code snippet is from my Game class:
private Screen screen;
private BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

// Converts image into array of integers
private int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();

public Game() {
    Dimension size = new Dimension(width * scale, height * scale);
    setPreferredSize(size);
    screen = new Screen(width, height);
    frame = new JFrame();
    pixels = new int[width * height];
}

// Displays images to the screen
public void render() {
    BufferStrategy bs = getBufferStrategy();

    // Checks if the buffer strategy exists. If it doesn't create a triple buffer strategy
    if(bs == null) {

        // Triple buffering
        createBufferStrategy(3);
        return;
    }
    screen.render();

    // Copies array in Screen class to pixels array in (this) class
    for (int i = 0; i < pixels.length; i++) {
        pixels[i] = screen.pixels[i];
    }

    // Must be in chronological order
    Graphics g = bs.getDrawGraphics();
    g.setColor(Color.CYAN);
    g.fillRect(0, 0, getWidth(), getHeight());
    g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
    g.dispose();

    // Display next available buffer
    bs.show();
}

This code snippet is from my Screen class:
private int width;
private int height;
public int[] pixels;

public Screen(int width, int height) {
    this.width = width;
    this.height = height;

    // Size of the pixels array reserves one element for each pixel
    pixels = new int[width * height];
}

public void render() {
    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            pixels[x + y * width] = 0xff00ff;
        }
    }
}

I have tried to "debug" by checking to see if  both of my pixels arrays in the Game and the Screen class are being loaded with the magenta color. I simply did:
for (int i = 0; i < pixels.length; i++) {
            pixels[i] = screen.pixels[i];
            System.out.println(pixels[i]);
        }

and I also tried:
for (int i = 0; i < pixels.length; i++) {
            pixels[i] = screen.pixels[i];
            System.out.println(screen.pixels[i]);
        }

In both cases, the decimal representation of magenta (FF00FF in Hex) gets printed out until I close the window.
Another thing I tried is using the image.setRGBmethod to change the color of the image.
I added this line
image.setRGB(20, 20, 16711935); into the render method as follows:
// Displays images to the screen
public void render() {
    BufferStrategy bs = getBufferStrategy();

    // Checks if the buffer strategy exists. If it doesn't create a triple buffer strategy
    if(bs == null) {

        // Triple buffering
        createBufferStrategy(3);
        return;
    }
    screen.render();

    // Copies array in Screen class to pixels array in Game (this) class
    /* for (int i = 0; i < pixels.length; i++) {
       pixels[i] = screen.pixels[i];
    }
    */

    // Must be in chronological order
    Graphics g = bs.getDrawGraphics();
    g.setColor(Color.CYAN);
    g.fillRect(0, 0, getWidth(), getHeight());
    image.setRGB(20, 20, 16711935);
    g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
    g.dispose();

    // Display next available buffer
    bs.show();
}

A magenta dot showed up in my frame, and I am also able to turn the entire frame into a solid magenta color by modifying the render method in the Screen class. Now, I am wondering why my "original" code isn't working. From what I understand, the setRGB method is much slower than what I originally intended on using to render images, so I don't want to just give up and settle with using setRGB.
I have spent practically the entire day going over all the spelling in my code, making sure those nested for loops in the Screen class are correct, and etc. I am at a loss here. I don't understand what the issue is.
If the code snippets I included are not enough, I have created a Gist of my code in its entirety here.
Comment: Transparency byte ?
Answer: This code gets the color int for the input rgb colors
public static int getIRGB(int Red, int Green, int Blue){
    Red = (Red << 16) & 0x00FF0000; //Shift red 16-bits and mask out other stuff
    Green = (Green << 8) & 0x0000FF00; //Shift Green 8-bits and mask out other stuff
    Blue = Blue & 0x000000FF; //Mask out anything not blue.

    return 0xFF000000 | Red | Green | Blue; //0xFF000000 for 100% Alpha. Bitwise OR everything together.
}

I suspect you are drawing a magenta color with 0% opacity


Point of contact between an ellipse $(5 \cos t , 3 \sin t)$ and an apparent tangent $ x \cos(R) + y \sin(R) =D$ sliding on it.

Question: Let $E$ be an ellipse defined by $ (x^2 / 5^2) + ( y^2 / 3^2) = 1 $ or, equivalently $( 5\cos t , 3\sin t )$ with $0\leq t \leq 2 \pi$.
Let $P= ( 5 \cos R , 3 \sin R) \space 0\leq R \leq 2 \pi$ be a point moving on E.
Let $D$ be the distance from $P$ to the origin : $D = \sqrt {(5 \cos R)^2 + (3 \sin R)^2 } $.
The following straight line , defined by $ x = 5= D$ when $R=0$ , rotates around $E$, and, apparently, is always tangent to $E$  :
$$ x \cos R + y \sin R =D$$.
Desmos construction : https://www.desmos.com/calculator/dmj3tunnoo
My question is : if this straight line is actually tangent to $E$ for all values of $R$, what is its ( moving) point of contact with $E$? Surprisingly ( to me) this point is not $P = ( 5 \cos R , 3 \sin R)$.
Comment: Hint: in the parametrization of the ellipse: $x=5\cos R, y=3\sin R$, $R$ **does not** represent the polar angle of the point (although it does when $R=0,\pi/2$, etc.
Comment: If you draw a circle centered at the origin with radius $D$, your line will be tangent to that circle at the point $(D\cos R,D\sin R)$.
Comment: To find the point of tangency, solve the system of equations $$\frac{x^2}{25} +\frac{y^2}9 = 1\\x\cos R + y \sin R = D$$ for a common solution. If exactly one exists, it will be the point of tangency, as that is the only way a line can intersect an ellipse in a single point. If none exist for some $R$, the line does not intersect the circle. If there are two solutions, the line intersects in two points, and thus is not tangent.
Comment: $(\frac{a^2\cos{R}}{D},\frac{b^2\sin{R}}{D})$
Comment: @Ian-Magnus. Wonderful, thanks!
Comment: Feel free to turn this comment into an answer , in case you've got time for this.
Answer: The tangency point for your tangent is
$$(\frac{a^2\cos{R}}{D},\frac{b^2\sin{R}}{D})$$
What I actually did was (in maxima CAS)
<code>solve([(x/a)^2+(y/b)^2-1,x*cos(t)+y*sin(t)-sqrt((a*cos(t))^2+(b*sin(t))^2)],[x,y]);
</code>
I'm still trying to find an elegant way to see this.
However, the way I was taught to get the tangents was to use the dual curve: parametrize the ellipse: $(x,y)=(a\frac{1-t^2}{1+t^2},b\frac{2t}{1+t^2})$ then the dual is $(X,Y)=(-\frac{y'}{xy'-yx'},\frac{x'}{xy'-yx'})=(-\frac1{a}\frac{1-t^2}{1+t^2},-\frac1{b}\frac{2t}{1+t^2})$ i.e. $X x+Y y+1=0$ is the tangent of the ellipse that has tangency point $(x,y).$
Or if you want $(x,y)=(\sin{R},\cos{R}):$ $(X,Y)=(-\frac{y'}{xy'-yx'},\frac{x'}{xy'-yx'})=(-\frac1{a}\cos{R},-\frac1{b}\sin{R}),$ and again the tangent at $(x,y)$ is $X x+Y y+1=0.$


GridView with multiple DataSources

Question: I have a grid view that will display columns from multiple data sources (3).
The data sources are stored procedures that contains a variety of columns not identical, How can i select the columns from these datasources and bind them to the Grid programtically (from code behind)???
Thanks
Answer: Create three separate datasets (one for each datasource that you'll be retreiving data from) and then merge them in code before binding.

GridView with multiple DataSources


Python - AttributeError: 'str' object has no attribute 'append' - maths game

Question: Trying to make it so a user can add a name, score and what difficulty the user completed the game on to high scores list.
def teacher_page():
    global scores, name, difficulties
    t_choice = None
    while t_choice !="0":
        print("\nWhat would you like to do?")
        print(
        """
        0 - Main Menu
        1 - Add a score
        2 - Remove a score
        3 - View highscores
        """
        )

        t_choice = input("Choice: ")
        print()

    #exit
        if t_choice == "0":
            main_menu()
    #add a score
        elif t_choice == "1":
            names = input("Name of the new user to add?\n")
            name.append(names)
            score = input("What did the user score?\n")
            scores.append(score)
            difficulty = input("And which difficulty did they complete it on?\n")
            difficulties.append(difficulty)
    #remove a score
        elif t_choice == "2":
            names = input("Name of the user you want to remove?\n")
            if names in name:
                name.remove(names)
            score = int(input("What did they score?\n"))
            if score in scores:
                scores.remove(score)
    #view highscores
        elif t_choice == "3":
            print("High Scores:")
            for score in scores:
                print(name, score, "on the difficulty ", difficulties)
    #if the t_choice does not = to 0,1,2,3
        else:
            print("Sorry but", t_choice, "isn't a vaild choice.")

But every-time I want to add a user to the list I get the error message
AttributeError: 'str' object has no attribute 'append'

I've had a look at a few examples but not sure where I'm going wrong.
Comment: Strings don't have an `append` method, as the error says. Are you expecting scores to be a string, or a list? Could be `name` too. Show the exact error with trace.
Comment: Well the problem is that what you think is a list is actually a string.
Comment: Programming/Project/testing2.py", line 121, in teacher_page
    name.append(names)
AttributeError: 'str' object has no attribute 'append'
Comment: Are these global variables `scores, name` a list type?
Comment: So what is the type of your `name` object? It isn't defined in your example, but clearly it is not a list
Comment: These are my global variables
scores = []
choice = None
name = []
difficulties = []
Answer: Initialize your variables as lists right below their declaration.
By default, when you assign raw input to them for the first time, they become strings.
Do something like:
global scores, name, difficulties
scores=[]
name=[]
difficulties=[]

During global declaration. Need not initialize again within the function.


Capturar valor de um campo do tipo email no angular js

Question: Eu tenho o seguinte código HTML com AngularJS:

    //...
    <form name="myForm2">
        <input type="email" id="email" name="email" ng-model="formData.email" required/>
        invalid email {{formData.email}}
    </form>
    //...

O que eu pretendo é, se o utilizador preencher o campo e-mail errado, apareça a mensagem "invalid email valor_preenchido_no_campo".
Acontece que o código acima só retorna a mensagem "invalid email", não estou conseguindo capturar o valor do campo.
O que está errado no código acima?
Comment: Não tenho certeza, mas acredito que ele esteja setando o valor de `formData.email` para `null` porque o valor do `input` é inválido. Vou tentar achar algo na documentação que comprove isso, aí posto uma resposta.
Comment: @gabrielhof penso que tens razão, fiz um teste e coloquei o e-mail correcto e o {{formData.email}} fora do span (porque ele fica oculto) e já aparece. Entretanto reparei que se colocar "email@dominio" ele considera certo e como podemos ver, não está.
Answer: Não encontrei nenhuma parte da documentação do AngularJS que fale sobre isso, mas o comportamento padrão dele é indefinir a propriedade vinculada ao input quando ele não possuir um valor válido.
Isso é discutido nessa issue do GitHub e nessa discussão no Google Groups.
Ou seja, se myForm2.email.$invalid for verdadeiro, a variável formData.email será setada para undefined. Você pode visualizar isso nesse exemplo.
Solução no Angular 1.3.x
Caso você esteja usando a versão 1.3.x do Angular, existe uma solução utilizando ng-model-options. Basta setar a propriedade allowInvalid para true:
<input type="email" id="email" name="email" ng-model-options="{allowInvalid: true}" ng-model="formData.email" required/>

Esse exemplo demonstra essa solução funcionando.


Denoising of microarray data using PCA

Question: I'm looking for references and comments regarding the validaty of the following method for data denoising, which I found while reading a code doing analysis of some gene expression dataset. The dataset consists of columns $x_1, ..., x_n$ of length $m$ (expression levels for $n$ genes observed in m samples). Someone with the knowledge of the dataset said that if we look at the top 10% columns with the maximum variance, we find that those columns have the maximum variance due to some artifacts (noise) in the measurement of expression level of the corresponding genes. In addition, we know that the rest 90% of columns are either not affected by any kind of noise, or are affected by some noise but to a much lesser degree than the top 10% columns.
Now, in the code that I'm examining the following method is used to remove the noise from the dataset. They calculate the principal components $y_1, ..., y_n$ for variables $x_1, ..., x_n$. They took $y_1$ (the leading principal components) and (this is my guess) assume that it mostly captures the variance caused by the artifacts described above. Then they transform the data (all $n$ columns) using the following rule:
$x_i = x_i - (\text{projection of } x_i \text{ onto } y_1)$.
That is, from each column they remove the component that is collinear with $y_1$, and keep the component that is orthogonal to $y_1$.
Can anybody please provide any references for this method or comment on its applicability in this case?
Answer: Maths part:
If you write the PCA decomposition as
$X = S \times L$
with scores $S$ and loadings $L$
reconstructing $X$ without the $i$th principal component becomes
$X_{-i} = S_{\cdot, -i} \times L_{-i,\cdot}
= X - S_{\cdot, i} \times L_{i,\cdot}$
(bit sloppy notation, but you get it; I use $-i$ for leaving out the $i$th component)
The second is easier to calculate if just few components are to be left out (less multiplications needed).
So you just have a normal PCA reconstruction that leaves out some components. Searching for PCA noise filter or the like should give you a wealth of papers.
Does it make sense:

ultimately this can only be known by intimate knowledge of the data
I've seen similar things with PCA on spectroscopic data sets (which share the order of magnitude of variates with the microarrays).
Sometimes some physical / chemical / biological process is a major source of variance. If I can identify this, and can thus reason why it is sensible to exclude this from further analysis, I'm fine excluding the respective source of variance.
This doesn't have anything to do with the general noise level, i.e. I'd still expect that higher PCs carry measurement noise.
That is, in the end, you may want to use PC scores $n$ to $m$ only.
I often find that in such situtations, partial least squares regression (PLS) is a good alternative (if applicable, i.e. you do have an outcome to which you want to correlate your $X$).
However if the artifact is known, you may want to correct/filter it on a "hard modeling" basis (i.e. start from the cause and develop a correction or filter) instead of the PCA, because in future data sets there may be only few measurements affected. Then this artifact does not end up in the top PC, but in some PC. I.e. you cannot rely on where in the PC this artifact will end up.
To sum up: I'm OK with using such an approach for descriptive modelling, but I'd be very careful/suspicious if prediction is intended.

Denoising of microarray data using PCA


Javascript gradually change the saturation

Question: I have some code so that when the key c is pressed, the saturation will increase and when the key c is lifted, it will revert back to normal. I'm wondering how I can make it so that instead of instantly changing the saturation level, the saturation will gradually change throughout the course of half a second and when the key c is lifted, the saturation will gradually decrease throughout a  half second back to the normal saturation level. How can this be done?
Current code:
document.addEventListener("keydown", e => {
  if (e.code === "KeyC") {
document.body.style.filter = "saturate(1.7)";

    }
}, false)

document.addEventListener("keyup", e => {
  if (e.code === "KeyC") {
  document.body.style.filter = "";

  }
}, false)

Answer: I would use use a CSS transition to get the gradual change.
Then instead of setting the saturate value with javascript you can just do .classList.add('saturated') and .classList.remove('saturated') on the element. I made an example with a div:
#myDiv{
  width:200px;
  height:200px;
  background-color: lightblue;
  filter: saturate(1);
  transition: filter 1s ease;
}

#myDiv.saturated {
  filter: saturate(4);
}

here is a working example on JSFiddle: https://jsfiddle.net/martinnester/07fsL2ge/20/


Nature of complex fixed point (in one dimension)

Question: Suppose we have an ordinary differential equation:
$\dfrac{dx}{dt} = f(x)$
To determine the value of the fixed/critical/equilibrium point(s), we set $\dfrac{dx}{dt} = 0$, that is, we calculate the values of $x$ which satisfy the equation $f(x) = 0$.
Suppose a fixed point exists called $x_*$.
To determine the nature of this fixed point, we calculate $\dfrac{dx}{dt}$ to the left and to the right of it. If $\dfrac{dx}{dt}>0$ to the left of $x_*$ and $\dfrac{dx}{dt}<0$ to the right of $x_*$ we say that it is stable. Otherwise, it is unstable.
The analysis above was limited to real fixed points, that is $x_*$ $\in \mathbb{R}$.
How may we generalise and extend the above analysis and determine the nature of complex fixed points in one dimension?
So, suppose we have:
$\dfrac{dx}{dt} = 1 + x^2$. The fixed point is complex and I cannot explain its nature.
Comment: Perhaps you could analyse the system $u' = 1+u^2-v^2$, $v'=2 uv$ instead?
Answer: You have first to decide what is your phase space:
If it is $\mathbb R$, then $x'=1+x^2$ has no constant solutions (what you call fixed points).
If it is $\mathbb C$, then you need to solve $z'=1+z^2$ (this is better) or to transform it in $x'=1+x^2-y^2, \ y'=2xy$ and proceed from there.
Comment: I'm trying my best to proceed from where you left the answer and I fear I'm embarrassingly off the mark. Anyway, here goes. The fixed points of the revised system of your two differential equations gives me $(-i,0)$, $(i,0)$, $(0,-1)$ and $(0,1)$. I then calculate the Jabobian of $A$, i.e. $J(A)$ at each of those fixed points and subtract from it $I\lambda$ where $I$ is an identity matrix. Since these values all give me pure imaginary values for all $\lambda$ at all fixed points, I then say that the fixed point in the original question is a centre. I might need more guidance
Comment: We don't know what is your phase space. If it is $\mathbb C$, then $x$ and $y$ are real numbers (you seem to be taking $x,y\in\mathbb C$). But it is much better to write $z'/(1+z^2)=(\arctan z)'$.


Ocultando máscara de campo nulo Delphi

Question: Eu tenho um campo DBText com informações de telefone, eu formatei o campo dessa forma "!99999-9999;1;_", só que quando aparece um campo nulo, ele acaba exibindo o hífen que separam os números, tem alguma forma de sumir com esse caractere, quando o campo for nulo?
Answer: Use o evento OnSetText:
procedure TDM.cdsCadClientesFONESetText(Sender: TField; const Text: string);
begin
  if Text = '     -    ' then
    Sender.AsString := ''
  else
    Sender.AsString := Text;
end;

Ocultando máscara de campo nulo Delphi


Update a block from another block

Question: I want to write a page that works like this:
http://www.albemarlegallery.com/artists.php
i.e. when I hover over a link from one block, an image in another block updates
How can I do that?
Thanks
Comment: Its just simple Jquery/JS Ajax
Answer: You can use javascript and ajax to update your image
just when hover your link replace src of image It is javascript only
it is not drupal all your html in the same page so it is easy to change any block when hover over another block

Update a block from another block


Bivariate probit model with sample selection

Question: Could you please provide an example and explanation why to use the bivariate probit model with sample selection?
In this context, to what sample selection bias refers to?
Comment: Do you mean a recursive bivariate probit, where one binary outcome appears as a regressor in the other binary outcome equation?
Comment: I don't know if it is called like that, but it involves selection and outcome equation.
Answer: Unfortunately I lost the tex file for these notes, but they are only two pages, so I added screenshots:

I have a paper where we use this approach to look at what happens to bidders who lose to a sniper in their very first auction on eBay. A sniper is another participant who tries to place a bid in the final seconds of sequential ascending auctions with predetermined ending times. The outcome $y_1$ is binary: leaving the auction platform or not. The sniped dummy $y_2$ is in the outcome equation of $y_1$.
The reason you can't just put $y_2$ as a regressor is that sniping is more likely to occur in markets where there are few bidders. It is these kind of markets for which a marketplace like eBay is most attractive to buyers, implying that bidders in these markets may be more likely to return to eBay. Hence, a positive correlation between sniping and auction thinness, and a positive correlation between auction thinness and the likelihood of returning to eBay, will bias downward any effect that sniping has on bidders ceasing to bid in auctions. That is, there is selection into which auctions gets sniped.
We use a recursive bivariate probit strategy to address this concern. There are two ways that bidding occurs on eBay. First, bidders can manually insert their bid into the proxy bidding system. Second, bidders can use sniping software that does this automatically in the last seconds of the
auction without their attentiveness. At nighttime, there are fewer manual bidders active on the site, and consistent with this we observe that more auctions are won by snipers. However, 10pm in New York is only 7pm in San Francisco, while 10pm in San Francisco is 1am in New York. Therefore the
10pm San Francisco bidder is much more likely to be sniped than a 10pm New York bidder. If these bidders are otherwise comparable conditional on observables, then one can use their respective time zones as an instrument for variation in the likelihood of being sniped. This is the basis of
our identification strategy.

Reference:
Matt Backus, Tom Blake, Dimitriy V Masterov, and Steven Tadelis, "Is Sniping A Problem For Online Auction Markets?",    Proceedings of the 24th International Conference on World Wide Web, 88-96.

Response to Question:
Here's a toy example illustrating the fundamental problem with selection, setting aside the bivariate probit stuff. The 250 circles below correspond to people with different levels of education and their potential wage offers. Suppose anyone who gets a wage offer of \$15 or less decides that he would rather go hiking instead of working, so we don't get to see his wage (orange circles). If you fit a linear model to the remaining data (navy circles), the slope will be 20% smaller than on the full sample, so the benefit of going to school will appear $0.50 lower than it really is. One way to think about this is the people with large negative epsilons are more likely to be missing in the low education groups, so it inflates the observed wages in those groups, which tilts the regression line and makes schooling look less effective.
Why does this matter? Let's focus on the fifth highest orange circle with 11 years of education, who may be right on the margin between dropping out of high school (we don't observe his costs here). His offer with 11 years of education is just under \$13. If he thinks the benefit of another year is \$2, he may leave school because he can just start hiking now and not incur the unnecessary cost. Since economists are interested in policy questions (like what would be the net benefit of college loan forgiveness), ignoring the people who went hiking (or aren't in the labor force) would be a poor choice. Using the wrong estimate could lead to some suboptimal investment in education, both individually and socially.
If your goal is to predict what the wage among workers with X years of education is, using the worker data would be OK. It is when you want to make causal statements about what would have happened to someone had they completed more school that you need to worry about selection.

Data:
<code>x   y
10  36.77875
13  29.92348
12  17.84871
10  21.6781
12  10.68797
8   29.45379
12  12.50187
9   22.7946
11  20.16943
12  34.30902
11  34.29064
13  15.70758
12  11.20882
12  33.84629
10  29.01311
14  22.38047
12  54.72863
11  49.56858
15  24.02602
13  36.42536
12  22.71795
10  19.54785
14  38.4038
14  34.30227
10  19.37613
11  2.086503
14  26.4395
9   14.80535
14  26.08193
11  30.91514
13  32.0592
8   34.08197
12  28.76042
13  38.68304
13  47.95863
11  24.46299
14  30.65527
16  54.57944
10  13.10431
14  25.30962
9   32.48787
11  24.64828
12  25.96807
11  16.65392
12  36.22239
14  25.20041
12  17.36436
12  38.27636
11  24.94589
10  31.49921
13  25.5742
12  25.78094
15  45.46352
11  21.08684
13  12.91339
11  33.41261
14  25.76663
14  49.73616
11  22.67634
16  55.26606
12  33.48164
15  33.87222
11  16.43427
10  21.37041
13  29.18699
9   20.20561
10  44.55228
13  47.68126
11  27.97073
12  36.06765
12  35.84951
11  11.26081
15  36.36755
16  23.63187
13  41.6813
12  30.994
13  31.27638
15  38.53747
11  48.27272
12  25.59191
16  44.45938
14  45.71571
14  33.68782
10  33.39376
12  45.53596
13  27.69209
12  26.27091
11  33.25354
11  16.89751
13  29.82576
11  38.67755
12  37.91254
12  32.57379
15  44.98801
8   13.68349
14  37.57533
13  15.75075
13  26.164
11  22.16672
10  30.29593
13  28.82244
17  43.92926
10  3.793436
14  54.33921
11  30.367
15  33.27439
15  11.65642
11  24.98503
11  35.55489
12  12.33667
9   19.50787
9   29.07384
13  39.28975
10  18.6426
13  32.62035
11  39.59964
12  38.74402
13  29.84206
11  28.70477
15  27.76243
12  35.0229
9   10.48161
13  32.94176
13  32.26461
13  20.64163
12  28.0451
11  30.72115
12  36.0846
16  52.26955
14  49.25191
15  48.60603
11  43.55553
14  45.27725
8   21.87545
12  27.19747
14  26.53179
9   18.49253
11  8.361289
12  30.11271
14  34.79089
11  39.50394
11  28.82289
12  29.17985
14  29.04272
12  39.28788
16  49.37336
14  44.76436
13  26.92885
11  39.19863
10  26.79517
14  30.74782
15  36.4241
13  27.07322
8   6.324262
10  29.13576
12  20.5755
10  5.107344
13  29.96143
12  30.87452
11  39.13571
12  31.89077
9   10.86587
9   32.571
13  36.32444
12  22.86062
13  31.54544
14  28.71825
12  35.49273
12  18.8854
8   32.67909
13  46.02027
10  35.3645
10  38.09469
11  21.16621
13  37.33644
14  43.37357
11  16.6026
13  36.44201
13  31.3522
11  35.2338
11  26.09209
14  52.26656
10  30.28688
12  36.23479
10  20.65876
11  42.26967
12  33.70919
14  34.77951
12  22.55819
18  54.19498
10  30.39797
15  33.097
11  27.93202
15  32.32858
14  37.80832
15  53.04989
13  35.48972
12  36.6966
11  36.46019
16  39.18628
14  39.73043
12  29.34012
11  24.64899
10  29.82037
11  29.40948
15  27.87559
10  34.42297
12  46.14198
9   23.11894
13  32.52744
16  43.73385
12  61.2392
10  26.99522
13  31.45339
14  36.8537
10  26.05906
15  40.28445
10  31.6895
14  33.68509
11  28.2475
12  10.36757
11  39.6512
11  41.26844
9   16.99724
12  29.98223
13  41.83167
10  23.86976
11  17.47382
12  41.34653
11  21.89777
12  14.88964
10  8.632276
11  13.11433
11  1.543627
15  48.46469
14  25.4514
16  55.7856
10  30.88486
16  23.78511
14  46.50201
12  29.67507
14  31.63361
9   44.99561
10  36.27057
13  32.96661
13  14.41626
13  46.88454
15  40.52191
16  39.17714
12  33.70162
</code>
Comment: @quirik I have never seen this interpretation and it does not make sense to me. I would looks at the predicted probabilities from the first stage if I wanted to compare.
Comment: How would you interprete the pdf/cdf ratio?
Comment: @quirik I wouldn't, other than in the way I mentioned above. I think this discussion has strayed too far from the original question. I encourage you to start a new question rather than continuing with more here.
Comment: The only mention of something like this that I can find is a very vague statement on p. 183 of Propensity Score Analysis by Guo and Fraser: "In the early days of discussing the Heckman or Heckit models, some researchers, especially economists, assumed that λ [IMR] could be used to measure the level of selectivity effect, but this idea proved controversial and is no longer widely practiced." I still don't get the intuition why someone would do this.
Comment: I found something similiar, as well at: http://isites.harvard.edu/fs/docs/icb.topic255091.files/Class08.pdf (p. 5)
Comment: Are these statements correct: the distribution of navy circles - potential wage offer given years of education is truncated from the left. As a result the OLS is biased because the predicted value is not at the mean of the distribution - the actual mean of the truncated distribution is higher. Therefore, the Heckman method corrects the mean with the coefficient of the IMR so the regression line could pass as close as possible to the new mean of truncated distribution for navy circles. Pdf/cdf ratio or IMR re-normalizes the truncated distribution so the integral underneath equals 1, as well.
Comment: This method corrects the expected value (or conditional mean) with the coefficient times the IMR (not just the coefficient). The corrected fit should pass through the conditional mean of the blue and the orange (not just the blue). I am not sure what "renormalized" sentence means. Typically, normalization involves some sort of division.
Comment: Could you please provide the data set from the employment sample selection example?
Comment: @quirik Edited the post with the data.
Comment: Great, thank you very much! Additionally, could you provide an example where correlation between unobservables of selection and outcome equation could be negative?
Comment: @quirik I think we have let this question ramble on long enough. We are way off topic from the bivariate probit. Please start another question, with a link to this one.
Comment: I did: http://stats.stackexchange.com/questions/231374/heckman-selection-model-and-negative-rho
Comment: So it can be said that if sample is selected, and we don't appy Heckman method, the predicted wage doesn't correspond anymore to the conditional mean of blue and orange, just the blue? Therefore, we are adding the sample selection component to the regression or value indicating how far conditional mean of truncated distribution is from the mean of original (untruncated) distribution (blue and orange). As a result, we can se how this affects the true value of wage offer with the help of coefficient of IMR.
Comment: Yes. There are other methods that accomplish this as well.
Comment: How would graph look like for a truncated sample if depentent variable in main equation was binary as well? How truncated sample affects estimating logistic regression?
Comment: @quirik You would have too few zeroes or ones, so it's effectively the same.
Comment: Let say we observe whether children have mobile phone if their parents voted for Obama. What would be the effects of truncated sample on logit regression? Does this mean that the CDF curve would bi biased and from which side the sample would be truncated?
Comment: Heckman selection model assumes that 1) errors of both selection and main equation are correlated and distributed normally, 2) explanatory variables in selection equation are independent of the error term, 3) explanatory variables in main equation are independent of the error term.

Doubt: how can explanatory variables of both equations be independent of error terms, and at the same time, the errors terms be correlated? Or this is the end result only after we included some unobserved factors that affect both selection and main equation?
Comment: For the sake of the example let's assume we are estimating the effect of age and education on wage. So we are observing only people who actually work and, therefore, have wage. Then we need to estimate selection and outcome equation, respectively. But why do we need to expand our estimate to whole population, i.e. to other non-working part? How are they gonna affect our estimates if they are not working?
Comment: This is not a great example, since both your outcome and endogenous variable are continuous, not binary. The bivariate probit will be an inappropriate model in this case. Employment and college graduate would be better.
Comment: Yes, I am aware of that.  However, could you please help me understand why it is necessary to include the whole population and not only deriving conclusions based on the sample of people given certain criteria.
Comment: @quirik Does this makes more sense now?
Comment: Yes, it makes more sense now. Thank you for your effort. In addition, could you please explain what do you mean by "people with large negative epsilons are more likely to be missing in the low education groups, so it inflates the observed wages in those groups.". I guess that the epsilon is the error term so if it's negative, the predicted wage will be larger than observed wage but I'm confused with other part of the sentence.
Comment: It means that people who receive lower wage offers for reasons that are unobservable to us are more likely to be hiking when they have less education. Note that there are a lot fewer orange circles on the right. This rotates the regression line up and biases downward the estimated wage-school profile.
Comment: OK, so you are saying that people with lower education will have larger epsilons due to some unobserved factors (e.g. intelligence)  other than the number of grades completed that affect the wage offer? As a result, we included only the people with hourly wage > $15 and get downward biased results. Does this also mean that we would get negative coefficient of inverse Mill's ratio which we can interpretate that there are unobserved characteristics (intelligence) which increase the probability of selection into the labour market and increase the probability of downward bias on the wage?
Comment: In addition to my previous question, could you please explain what do you mean by "It is when you want to make causal statements about what would have happened to someone had they completed more school that you need to worry about selection." ? Does this mean knowing what wage offer would hiker with 11 years of education and $13 wage would have if he completed more years of education?
Comment: Everyone has the same kind of epsilons here, regardless of their education: there's no heteroskedasticity in the data. I am saying the people with low education and negative epsilons are more likely to be below the 15 threshold and go hiking, so we do not observe their wage. The sign on the IMR indicates the correlation between the unobserved components in the selection and outcome equations, which in this case should be positive. Your understanding of the causal statements sentence is correct.
Comment: How they will have negative epsilons when they are not observed? What am I missing here?
Comment: It's a potential outcome. Think of it as a wage offer, rather than an actual wage. Just because someone did not accept it, doesn't mean it does not exist.
Comment: So we are performing regression among those who work and those who could potentially work for some wage under $15 to obtain unbiased effect of education on wage. As a result, we cannot observe those who don't work so in order to straighten the biased regression line we need to control for some unobserved factors which are related to education and affect the propensity to participate on labour market and level of wage offer, as well. Is this correct?
Comment: This is turning into its own question! It is much better to ask related questions as separate, new questions. You are right that this is essentially an omitted variables problem. If we observed those factors or had an estimate of them, we could fix this by putting them in. From properties of the bivariate normal distribution, we do have such an estimate, up to an unknown parameter: it is the inverse Mills ratio times the its coefficient in the wage equation. This captures the fact that the wage epsilon no longer zero in expectation since the negative epsilons with low education are hiking.
Comment: @Dimitiy V. Masterov Additionally, how can we interpret IMR? What do we get from the ratio of probability density and cummulative distribution function?
Comment: @quirik The IMR times its coefficient is the expected error term for those working.
Comment: In this context, does this mean by how much the wages are shifted up due to selection effect? In other words, it says how much working people with sample average characteristics who are selected in our sample makes % higher hourly wage than someone with equal average chatacteristics but drawn at random?
Comment: Almost right. The percentage part depends on how how wages are measured or transformed, say with logs. The sample average part is wrong. The IMR is a nonlinear function of variables in the selection equation, so you could evaluate it any values, not just the average ones.
Comment: Yes, it occured to me later that percentage are related with log transformation of wage variable. Regarding other part, if I take average of all IMR values, and then multiply it by the coefficient, would my statement be correct?
Comment: Yup. That a great way of doing it's
Comment: @Dimtriy V. Masterova One more doubt: during selection stage, when we calculate the ratio of pdf and cdf, and get e.g. 1.2 and 2.4 for two observations, does this mean that the later has twice as chance/likelihood to be employed if he obtains more years of education?
Comment: It the meantime I have been doing additional reading and come up with another interpretation: person with pdf/cdf = 2.4 is twice as likely to be selected into the sample of workers and not hikers than person with pdf/cdf = 1.2? This is based on the fact that Heckman models selection  and that pdf/cdf is basically a selection hazard rate or the "risk/chance" to be selected for the sample? Please correct me @Dimitriy V. Masterov


Is the return type wrong?

Question: #include<iostream>
using namespace std;
class binary
{
protected:
    int num;
public:
    binary(int a)
    {
        num=a;
    }
    binary operator - (binary b1)
    {
        binary b(0);
        b.num=~(b1.num-1);
        return b(b.num);
    }
    void display()
    {
        cout<<"Negative is: "<<num;
    }
};
int main()
{
    int a;
    cout<<"Enter no.: ";
    cin>>a;
    binary b(a);
    binary b1=-b;
    b1.display();
}

In the above program, it shows that the return type of overloading operator should be should be of form int&. Can anyone please explain to me what that means?
Comment: `return b(b.num);` is not right. It should be `return b;`. Is that where you see the error?
Comment: If you want to overload unary minus, it's `operator-()` with no parameters; the operand is `this`.
Comment: It is not necessary that an `operator-()` return a reference.  It is usually appropriate that it return by value, since an expression `a - b` gives a result that is neither `a` nor `b`.    There is usually a benefit (for the binary `operator-()`) that the second operand be passed by `const` reference - but that's not what you're asking.
Answer: Is the return type wrong ? yes returning b(b.num); is wrong, it should return only object b.
You are overloading unary minus  using member function, it should have zero argument because member function having this pointer, you can use this pointer to get data member of class.
 binary operator - ()
 {
         binary b(0);
         b.num = ~(this-> num-1);
         return b;
 }

Answer: You improperly declared the unary operator-. There are two variants of operator-: unary and binary. Since this is implicitly on the left hand of operator-, unary operator requires no arguments and binary requires one argument on the right hand. Therefore you declared binary operator-. Please try like below
binary operator - ()
{
    return binary(~(num-1));
}

Answer: binary operator-(binary b1) { ... }

defines the binary - operator between two objects of type binary.
To be able to use
binary b1=-b;

you need to overload the unary - operator. That can be done using:
binary operator-() { ... }

I suspect you want to implement the unary - operator. Your implementation can use this instead of b1. I suggest making he member function const since it does not modify the this object.
binary operator-() const
{
   binary b(~(this->num-1));
   return b;
}

That will also allow you to use:
binary b1 = -binary(10);

Answer: Because you have to parse integer value
But as given in code return b(b.num)
instead of that it should be "return b".

Is the return type wrong?


create bilingual language site with drupal 6

Question: i want to build a multi-language site (Chinese and English). From the documentation, I know I should install the Internationalization module, so i installed it, but there are some parts on my site that are not translated.

There are some parts as the following in every page (the Chinese version):

<a href="<?php print $base_path ?>" title="<?php print t('Home') ?>">测试公司

How do I translate 测试公司 when English is the set language?

On every page's top right part, there are some parts as the following:

  设为首页 | 添加收藏  | 简体中文 English

How do I translate 设为首页, 添加收藏 and  简体中文 to English, when the user access http://example.com/en?
I know I can put that content in a block, then translate it, but it's too weird.
Is there a simple way to get that?
ps:  why this one that i can't translate(english-->chinese)? the code is used to alter the conntact form . $form['mail'] = array( '#title' => t('E-mail'), '#type' => 'textfield', . when i searched the E-mail in the translate interface, i can't find it,but  when i changed E-mail to test. then i can search it. why? thank you.
Answer: You must use the t function on all text if you want translate it directly throw the admin panel.
Comment: Just a side note: `t()` is not used to translate from Chinese to English, but it is used to translate a string in English in the language set for the page, or for the user. If I pass a string in Chinese to `t()`, the function will return the exact same string it got as argument.
Comment: how to use the t function .could you make me an example. thank you
Comment: You've many examples and better explanation in the link I give you for t function. (http://api.drupal.org/api/drupal/includes--common.inc/function/t/6)
Comment: @kiamlaluno you can use the third parameter to tell that your string is Chinese and you can translate it in English as well.
Comment: No, you cannot. The source language is always English or, to be more precise, American English. The parameter you are referring to is described as (Drupal 6 documentation): "`$langcode` Optional language code to translate to a language other than what is used to display the page." It's the language to which the string is translated, not the language from which the string is translated.
Comment: yvan ,how to write the third parameter. when the language is Chinese or when the language is english. the $language object doesn't has an attribute of $langcode. thank you.
Comment: kiamlaluno, why this one can't translate? the code is used to alter the conntact form . $form['mail'] = array(
 '#title' => t('E-mail'),
'#type' => 'textfield',  .  i searched the E-mail in the translate interface, i can't find it, when i change to test. then i can search it. why? thank you.
Comment: @kiamlaluno I was thinking that if you specify the language code in third parameter Drupal will add to in to language code to translate. You're right.
Comment: @runeveryday You string appear for translation only if she appears one time on the foreign language. For it, you should see E-Mail in your Chinese version to have access to the translation.
Comment: @runeveryday When you use `t("E-mail")` you are translating from English, which is what the function is for; to translate from another language to English, `t()` is not the function to use.
Comment: kiamlaluno, i know, i want to translate E-mail to chinese, when i searched the E-mail in the translate interface, i can't find it,but when i changed t("E-mail") to t("test"). then i can search it. why? thank you.


How to keep window visible at all times, but not force it to be on top

Question: I'm creating a "desktop gadget" of sorts, I've disabled manual minimizing  of the window, but now there is another problem: the system can still hide the window if the user presses Windows+D, for example.
When hidden that way, no usual minimize/resize/visibility events are fired.
I want to do something almost like TopMost, but without forcing the window order.
Maybe it's possible to install a global shortcut event using win32 API, and briefly set TopMost to true, but that sounds very hackish.
I found one solution, but it does not seem to work on Windows 10: Keeping window visible through "Show Desktop"/Win+D
 The other common option, which would be writing an actual desktop gadget, is not possible on Windows 10, given their deprecation.
Are there any other methods to keep a window visible (but not on top of the screen) at all moments?
Comment: Yes, a desktop gadget is what it takes.  Removed from Windows.  And Sticky Notes is not sticky anymore, it also gets minimized.  Hopefully they pay you enough.
Comment: The user explicitly presses a key command for "show me my desktop"; what makes you sure that he really means "show me my desktop and this one gadget". What would happen if he had many of these gadgets, all using more screen space than available?
Comment: @SimonSvensson I am aware of all the usability concerns. This application is being developed exclusively to one specific home user that desires it to behave exactly like that. Said user already has the "Sticky Notes" from Windows 7 installed on his Windows 10 machine, and expects similar behaviour.
Answer: This function is working for me:
BOOL FixShowDesktop(HWND hWnd)
{
    HWND hWndTmp = FindWindowEx(NULL, NULL, L"Progman", NULL);
    if (hWndTmp)
    {
        hWndTmp = FindWindowEx(hWndTmp, NULL, L"SHELLDLL_DefView", NULL);
        if (hWndTmp)
        {
            SetWindowLongPtr(hWnd, -8, (LONG_PTR)hWndTmp);
            return TRUE;
        }
    }
    return FALSE;
}

Note, this code is a bit better then from Keeping window visible through "Show Desktop"/Win+D because the window can be overflowed by other windows (like any other window). Using SetParent places window under all other windows.


Show that infinitely many members of $1,11,111,1111,\dots$ are divisible by $2^{2017}+1$.

Question:
Show that infinitely many members of $1,11,111,1111,\dots$ are divisible by $2^{2017}+1$.

I know that the sequence above is equal to $a_n = \frac{10^n-1}{9}$ for $n = 1,2,3,\dots$. I also feel that I should use the pigeonhole principle but do not know how to attack the problem.
Comment: This seems like a recent competition problem. Where is it from?
Comment: @Arthur I've seen problems like this in competitions but it was actually just a problem given by my instructor
Answer: Hint: If $10^n-1$ is divisible by $m$, then so is $10^{kn}-1$ for all $k \in \mathbb N$.


How can I find these two limits?

Question: How can I find these two limits? I've no idea how to improve or continue now. Can someone give me a hint?
1)$$\lim_{x \to 0^+}\left(\frac{\cos^{\pi}(25x)} {\tan^3(x)}\right)=\lim_{x \to 0^+} (\cos^{\pi} (25x)\cot^3(x))$$
2)$$\lim_{x \to 0^-}\left(\frac{\cos^{\pi}(25x)} {\tan^3(x)}\right)=\lim_{x \to 0^-} (\cos^{\pi} (25x)\cot^3(x))$$
Thanks a lot!
Comment: The numerator approaches a positive number and the denominator approaches $0$, from above in the first case and from below in the second case.  That's all you need to know in order to deal with these. ${}\qquad{}$
Answer: 1)$$\lim_{x \to 0^+}\left(\frac{\cos^{\pi}(25x)} {\tan^3(x)}\right)=\lim_{x \to 0^+} (\cos^{\pi} (25x)\cot^3(x))$$ $$\lim_{x \to 0^+}\left((\cos^{\pi}(25x)\left(\frac{1}{\tan(x)}\right)^3\right)=$$ $$\lim_{x \to 0^+}(\cos^{\pi}(25x)\lim_{x \to 0^+}\left(\frac{1}{\tan(x)}\right)^3=$$ $$\lim_{x \to 0^+}(\cos^{\pi}(25x)\lim_{x \to 0^+}\left(\frac{1}{\tan(x)^3}\right)=$$ $$1^{\pi}(\infty)=\infty$$
2)$$\lim_{x \to 0^-}\left(\frac{\cos^{\pi}(25x)} {\tan^3(x)}\right)=\lim_{x \to 0^-} (\cos^{\pi} (25x)\cot^3(x))=$$ $$\lim_{x \to 0^-}\left((\cos^{\pi}(25x)\left(\frac{1}{\tan(x)}\right)^3\right)=$$ $$\lim_{x \to 0^-}(\cos^{\pi}(25x)\lim_{x \to 0^-}\left(\frac{1}{\tan(x)}\right)^3=$$ $$\lim_{x \to 0^-}(\cos^{\pi}(25x)\lim_{x \to 0^-}\left(\frac{1}{\tan(x)^3}\right)=$$ $$1^{\pi}(-\infty)=-\infty$$

How can I find these two limits?


Firebase Firestore: How to implement a "likes" system?

Question: When the currentUser taps the likeButton I run a transaction but I want to check if the user has already liked the post or not. If the user has already liked the post I want to decrease the likeCounter and change the likeButton appearance, otherwise I want to increase it.
My Firestore Database using the collection.document.collection.document.... stuff:
"posts":
    - "post1":
        - uid: user1
        - likeCount: 2
        - caption: "caption1"
        - "likes":
            - "user1":
                - value: true
            - "user2":
                - value: true
    - "post2":
        - uid: user1
        - likeCount: 1
        - caption: "caption2"
        - "likes":
            - "user1":
                - value: true
            - "user4":
                - value: true
    - "post3":
        - uid: user2
        - likeCount: 3
        - caption: "caption3"
        - "likes":
            - "user1":
                - value: true
            - "user3":
                - value: true
            - "user4":
                - value: true

This is my incrementLikes() function, which is called whenever the user taps on the likeButton
func incrementLikes() {
    let ref = Api.Post.REF_POSTS.document(self.post!.id!)

    Firestore.firestore().runTransaction({ (transaction, errorPointer) -> Any? in
        let sfDocument: DocumentSnapshot
        do {
            try sfDocument = transaction.getDocument(ref)
        } catch let fetchError as NSError {
            errorPointer?.pointee = fetchError
            return nil
        }

        guard let oldLikes = sfDocument.data()?["likeCount"] as? Int else {
            let error = NSError(
                domain: "AppErrorDomain",
                code: -1,
                userInfo: [
                    NSLocalizedDescriptionKey: "Unable to retrieve likes from snapshot \(sfDocument)"
                ]
            )
            errorPointer?.pointee = error
            return nil
        }
        transaction.updateData(["likeCount": oldLikes - 1], forDocument: ref)
        if let currentUser = Auth.auth().currentUser {
            ref.collection(K.likesCollection).document(currentUser.uid).delete()
        }
        DispatchQueue.main.async {
            self.likeImageView.image = UIImage(systemName: K.heart)
            self.likeImageView.tintColor = UIColor.black
        }
        return nil
    }) { (object, error) in
        if let error = error {
            print("Transaction failed: \(error)")
        } else {
            print("Transaction successfully committed!")
        }
    }
}

I want to know if my database is structured the correct most scalable way and also where and how should I place the observer to see if the user already liked the post or not.
Comment: The question is a bit unclear. If you want to check if the user has liked the post or not - that would be done by observingSingleEvent the users liked posts for that key and if it exists then decrease the likeCounter of the post. You really won't even need a query as you know the post id to see if it exists. Reading data is covered in the Getting Started Guide [Read Data Once](https://firebase.google.com/docs/database/ios/read-and-write#read_data_once). If that's not what you're asking, can you clarify the question?
Comment: Thank you for your answer, but Im working with Firestore not Realtime Database so the observingSingleEvent method is not available to use, is there a way I can implement it with Firestore?
Comment: Also, where inside the runTransaction method should I place the observer? thanks again
Comment: Whoops, sorry about that. Actually the concept of getting data once also exists in Firestore see [Get Data Once](https://firebase.google.com/docs/firestore/query-data/get-data#get_a_document) and the usage is similar. Get the document and if it exists (document.exists) then decrease the likeCounter. Also, you don't need this *DispatchQueue.main.async* inside Firebase closures as UI calls are run on the main thread and networking calls are run on a background thread automatically.
Answer: While thinking about a way of scaling this I realized instead of loading all the user likes for each post, why not save and load all the post ids the user has liked instead. A post can have 50k, 500k or 5 million likes but a user probably has maybe 1-5k max post likes. You can create a 'liked-posts' collection under the user and you can probably fetch all the posts a user has liked in one read and this will be much faster.
Answer: When I made a social media platform using Firebase, it was easier to get the likeCounter using the number of children in the post. Then, when checking if the likeButton should show if it's liked, just see if their userId is in the children.
The reason I found this better was because:

The counter could easily have bugs if the Internet wasn't secure.
When I wanted users to see who else had liked the post, I had to create the second branch anyways. It actually saves repeating code.

This is how I had it set up:
"posts":
    - "post1":
        - uid: user1
        - caption: "caption1"
                 -"LikedBy":
                     -LikedBy:"user1"
                     -LikedBy:"user3"

// we added "LikedBy": so that instead of using likeCounter,
//you could get the count from it's children.
//To see if it's already liked by the user,
// find the name in this branch. If user1 finds his name in the children,
//it'll return true. That means he's liked it.

    - "post2":
        - uid: user1
        - caption: "caption2"
               -"LikedBy":
                     -LikedBy:"user1"
                     -LikedBy:"user3"
    - "post3":
        - uid: user2
        - caption: "caption3"
              -"LikedBy":
                     -LikedBy:"user1"
                     -LikedBy:"user2"
                     -LikedBy:"user3"

// as you can see this is no longer used

"likesPerUser":
        - "user1":

        - "user2":

        - "user3":

Comment: but if you want to see if user liked post or no, you will load all user liked post ?
Comment: Ahh yes true. I didn't think of that because my app was very small. I guess this isn't the best way to do it after all.


appendChild while inside for loop doesn't work right

Question: I'm trying to create a DIV and append it to all existing DIVs on the page with a for loop.  The problem is while it's inside the for loop, it will add the new DIV only to the last found DIV and not to each one like the FOR loop is supposed to make it do.  Can anybody tell me what I'm doing wrong?
Here's the code I'm working with:
HTML:

First

First

First

First

JS:
var secondDiv, secondDivImg, selectDivContainer;

secondDivImg = document.createElement("span");
secondDivImg.className = "divImg";

secondDiv = document.createElement("div");
secondDiv.className = 'second';
secondDiv.innerHTML = "Second";
secondDiv.appendChild(secondDivImg);

selectDivContainer  = document.querySelectorAll('.Id');

var idLength = document.querySelectorAll('.Id').length;

for (var i=0; i<idLength; i++) {

    selectDivContainer[i].appendChild(secondDiv);
    console.log(i);
    console.log(selectDivContainer[i]);

}

Here's a fiddle
I added a couple of console.log to see and they look like the right thing so I'm a little confused why this happens.  Thanks!
Comment: This would be trivial to do with the jQuery append method http://api.jquery.com/append/
Answer: You'll have to create multiple elements, since you can't append the same element to one document twice. That means your document.createElement() call must be inside the loop.
var selectDivContainer = document.querySelectorAll('.Id');
var idLength = selectDivContainer.length;

var secondDiv, secondDivImg;

for (var i = 0; i < idLength; i++) {
    secondDivImg = document.createElement("span");
    secondDivImg.className = "divImg";

    secondDiv = document.createElement("div");
    secondDiv.className = "second";
    secondDiv.innerHTML = "Second";
    secondDiv.appendChild(secondDivImg);

    selectDivContainer[i].appendChild(secondDiv);
}

EDIT:
Also, you may have noticed that I changed some parts of your code; for example, you should be consistent in quoting; do not use " AND ' unless necessary (they are the same in JS). Also, for idLength, your don't have to call document.querySelectorAll() again.
Comment: They are completely (!) the same in Javascript, with literally no difference. My personal preference is `'`, but that's just my "taste" in code. Also, I chose https://github.com/feross/standard as my coding style and it uses single quotes, too. Thanks for your feedback :)
Comment: Thanks for the answer!  It fixed it and now it all makes much better sense!  About the quotes, should I be using " or ' or it doesn't matter?  I know I've been using them interchangeably but I'd like to use them the proper way.
Answer: This is correct behavior.
The reason is the 2nd sentence of the MDN docs.   After you add it the first time, the child you supply is a reference to an existing node, and then gets moved instead of copied.
From https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild

The Node.appendChild() method adds a node to the end of the list of children of a specified parent node. If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position (i.e. there is no requirement to remove the node from its parent node before appending it to some other node).


ModuleNotFoundError: No module named 'autorizacoes'

Question: Como posso importar uma pasta utilizando Python no Spyder ?
Atualmente tenho a seguinte estrutura de dir
Gestao
|
|_ Aplicacao
    |
    |_ Autorizacoes

No script
import pandas as pd
import imaplib
import email
import autorizacoes

Consigo importar todas as bibliotecas menos "autorizacoes". Utilizando o Visual Code não retorna o erro que estou recebendo agora.
import autorizacoes

ModuleNotFoundError: No module named 'autorizacoes'

Quando se utiliza o Spyder a forma de importar uma pasta é diferente, existe alguma outra forma?
Comment: Em python, para que um diretorio seja um modulo vc precisa acrescentar um arquivo como o nome `__init__.py`.
Comment: Sim, dentro da pasta "autorizacoes" eu já tenho um arquivo chamado "__init__.py"
Comment: Mas não basta ser `init.py` tem que ser `__init__.py`, ou seja tem que começar e terminar com 2 "underlines".
Comment: Além disso, o python é *case-sensitive*, ou seja você tem que usar o `A` maiúsculo assim como colocou no nome da pasta
Comment: Fiz isso também e continua dando o mesmo erro
Comment: Tentou a minha resposta?
Answer: Veja se funciona assim:
1) Crie a estrutura inicial (os comandos abaixos são para linux)
$ mkdir -p gestao/aplicacao/autorizacoes

2) Crie os arquivos __init__.py
$ touch gestao/__init__.py
$ touch gestao/autorizacoes/__init__.py

3) Na pasta autorizacoes crie e edite um arquivo com o nome hello.py e adicione o seguinte conteúdo:
def hellow():
    return 'Hello World!'

4) Na pasta raiz (gestao), crie o arquivo sayhello.py com o seguinte conteudo:
from aplicacao.autorizacoes.hello import hellow

Com o comando tree vc pode ver a estrtura:
$ tree
.
├── aplicacao
│   ├── autorizacoes
│   │   ├── hello.py
│   │   └── __init__.py
│   └── __init__.py
└── sayhello.py

5) Execute sayhello.py na linha de comando:
$ python sayhello.py

A saida deverá ser:
Hello World!

Editada
  Revendo o codigo na sua questão, não fica claro se Autorizacoes é um pacote ou um módulo, se vc tem duvidas a respeito de que seja um pacote e/ou um módulo, veja essa resposta aqui no STOpt. No codigo de exemplo da sua pergunta, vc faz: import autorizacoes, mas se autorizacoes for uma pacote (um pacote pode ser resumido como um diretorio que contem modulos), vc deveria fazer: import autorizacoes.nome_do_modulo
Comment: ainda nada, só consegui importar a pasta utilizando "os.chdir ('caminho da pasta')"
Comment: Fez o teste que eu propus? Exatamente igual? Veja que no seu codigo da pergunta vc faz um `import  autorizacoes` mas se vc estiver na "raiz", vc tem que importar da forma como faço no meu exemplo, com o caminho inteiro, que seria `import aplicacao.autorizacoes`
Comment: Ou se quizesse importar explicitamente as funcoes em um arquivo: `from aplicacao.autorizacoes.nome_modulo import funcao1, funcao2 ...`


Graham Scan Algorithm -> sqrt and arctan2 huge values

Question: I have to implement Graham Scan Algorithm.
This is my code:
    /*
    Graham's algorithm'
    */

    #include <stdio.h>
    #include <stdlib.h>
    #include <conio.h>

    #include <stack>
    #include <vector>
    #include <math.h>

    #include <algorithm>
    #include <cstdlib>

    using namespace std;
    struct Tpoint
    {
        int x;
        int y;
    };

    struct AR{
        double alpha;
        double r;
        int i;
    };

    bool operator<(AR p, AR q){
        if(p.alpha != p.alpha){
            return p.alpha < p.alpha;
        } else {
            return p.r < p.r;
        }
    }

    int det(Tpoint p1, Tpoint p2, Tpoint p3){
        return p1.x*p2.y + p2.x*p3.y + p3.x*p1.y - p3.x*p2.y - p1.x*p3.y - p2.x*p1.y;
    }

    int right_turn(stack<Tpoint,vector<Tpoint> > S,Tpoint p3){
        Tpoint p2;
        Tpoint p1;

        p2=S.top();
        S.pop();
        p1=S.top();
        S.push(p2);

        if (det(p1,p2,p3)>0)
        return 0;

        if (det(p1,p2,p3)<0)
        return 1;
    }

    int main(){

        vector<Tpoint> Q;

        //Stos pointów, na końcu zawiera wynik
        stack<Tpoint,vector<Tpoint> > S;

        Tpoint point;

    Tpoint array[]={3,-2, -3,-2, 6,4, -6,1, 4,5, 0,0, 3,4, -3,3, -2,2, 0,6};
    Tpoint point00=array[0];
    int xMax = array[0].x;
    int yMin = array[0].y;
    int i;
    for (i=0; i<10; i++){
        if (array[i].y<yMin){
            if(array[i].x>xMax){
                xMax=array[i].x;
                yMin=array[i].y;
                point00=array[i];

            }
        }
    }

    //sorting section start

    printf("%d %d \n \n",point00.x, point00.y);
    Q.push_back(point00);

    Tpoint arrayCLONE[10];
    AR arrayAR[10];
    for (i=0; i<10; i++){
                arrayAR[i].alpha=0.0;
                arrayAR[i].r=0.0;
                arrayAR[i].i=i;
                arrayCLONE[i] = array[i];

                array[i].x-=point00.x;
                array[i].y-=point00.y;

    }

    for (i=0; i<10; i++){
        if ((array[i].x != point00.x) && (array[i].y != point00.y)) {
            arrayAR[i].alpha=atan2(array[i].y, array[i].x);
            arrayAR[i].r=sqrt(array[i].x*array[i].x+array[i].y*array[i].y);

            printf("alpha= %d, r= %d \n",arrayAR[i].alpha,arrayAR[i].r);
            printf("x= %d, y= %d\n",array[i].x, array[i].y);
        }else{

        arrayAR[i].alpha=9999;
        arrayAR[i].r=9999;
        arrayAR[i].i=0;
        }

    }

    sort (arrayAR, arrayAR + 10);

    for (i=0; i<10; i++){
        if (arrayAR[i].alpha<1000){
            Q.push_back(arrayCLONE[arrayAR[i].i]);
        //  printf("i =%d \n",i);
            printf("x =%d \n",arrayCLONE[arrayAR[i].i].x);
            printf("y =%d \n",arrayCLONE[arrayAR[i].i].y);
            printf("_____ \n");

        //  printf("index i =%d \n",arrayAR[i].i);
        }
    }

    //sorting section end

    S.push(Q[0]);
    S.push(Q[1]);
    S.push(Q[2]);

    for (int i=3;i<10; i++){
    while (right_turn(S,Q[i])==1)
        S.pop();
        S.push(Q[i]);
    }

    printf("points: \n");
    while (!(S.empty()))
    {
        point=S.top();
        S.pop();
        printf("(%d,%d) ",point.x,point.y);
    }
        printf("\n..");
        getch();
        return 0;
    }

It's not working in sorting section. Functions _arctan2() and _sqrt() have returning large values. I.e sqrt returns -1464986461. Why it happens?
As a result, points are not sorted by alfa, but in not known way. If I manual set order of points, algorithm work properly.
Could you tell me way it is not working?
Comment: I did some Graham scan implementations back in my younger days, and you don't actually need to compute either sqrt or atan (just int operations if points have int coords). Remember that det(A,B,C)=0 if and only if A, B and C are colinear (I used the function you have already defined). In other words, in your operator, you can just check the sign of det instead of the sign of (alpha1-alpha2) which you are currently doing. In case the det is zero, check the square of the distances (sqrt preserves i equalities, so you can just skip the extra, costly, unneeded floating point operation)
Answer: You're trying to print a floating point value as a decimal (int) value.
Do this instead:
printf("alpha= %f, r= %f \n",arrayAR[i].alpha,arrayAR[i].r);

%d means signed decimal integer. Review the documentation for printf
%f means decimal floating point
Answer: Ok, now it works:
    /*
    Graham's algorithm'
    */

    #include <stdio.h>
    #include <stdlib.h>
    #include <conio.h>

    #include <stack>
    #include <vector>
    #include <math.h>

    #include <algorithm>
    #include <cstdlib>

    using namespace std;
    struct Tpoint
    {
        int x;
        int y;
    };

    struct AR{
        double alpha;
        double r;
        int i;
    };

    bool operator<(AR p, AR q){
        if(p.alpha != q.alpha){
            return p.alpha < q.alpha;
        } else {
            return p.r < q.r;
        }
    }

    int det(Tpoint p1, Tpoint p2, Tpoint p3){
        return p1.x*p2.y + p2.x*p3.y + p3.x*p1.y - p3.x*p2.y - p1.x*p3.y - p2.x*p1.y;
    }

    int right_turn(stack<Tpoint,vector<Tpoint> > S,Tpoint p3){
        Tpoint p2;
        Tpoint p1;

        p2=S.top();
        S.pop();
        p1=S.top();
        S.push(p2);

        if (det(p1,p2,p3)>0)
        return 0;

        if (det(p1,p2,p3)<0)
        return 1;
    }

    int main(){

        vector<Tpoint> Q;

        //Stos pointów, na końcu zawiera wynik
        stack<Tpoint,vector<Tpoint> > S;

        Tpoint point;

    Tpoint array[]={-3,-2, 6,4, -6,1, 4,5, 0,6, 3,4, -3,5, 3,-2,  -2,2, 0,0, 1,1};
    Tpoint point00=array[0];
    int xMax = array[0].x;
    int yMin = array[0].y;
    int i;
    for (i=1; i<9; i++){

        if (array[i].y<yMin){
            yMin=array[i].y;

            }
        }

    for (i=1; i<9; i++){

        if (array[i].y==yMin){
                if(array[i].x>xMax){
                xMax=array[i].x;

                point00=array[i];

            }
        }
    }

    //sorting section start

    printf("point00 x=%d y=%d \n \n",point00.x, point00.y);
    Q.push_back(point00);

    Tpoint arrayCLONE[11];
    AR arrayAR[11];
    for (i=0; i<10; i++){
                arrayAR[i].alpha=0.0;
                arrayAR[i].r=0.0;
                arrayAR[i].i=i;
                arrayCLONE[i] = array[i];

                array[i].x-=point00.x;
                array[i].y-=point00.y;

        //printf("x2= %d, y2= %d\n",array[i].x, array[i].y);
    }

    for (i=0; i<11; i++){

        if (((array[i].x != 0) || (array[i].y != 0))) {

            arrayAR[i].alpha=atan2(array[i].y, array[i].x);
            arrayAR[i].r=sqrt(array[i].x*array[i].x+array[i].y*array[i].y);

            arrayAR[i].i=i;
            printf("alpha= %f, r= %f , x= %d, y=%d\n",arrayAR[i].alpha,arrayAR[i].r,array[i].x, array[i].y);

        }else{

        arrayAR[i].alpha=9999;
        arrayAR[i].r=9999;
        arrayAR[i].i=16;
        }

    }

    sort (arrayAR, arrayAR +10);
    Tpoint temp;
    for (i=0; i<10; i++){
        if (arrayAR[i].alpha<1000 && arrayAR[i].alpha>0.0){

            Q.push_back(arrayCLONE[arrayAR[i].i]);
        //  printf("i =%d \n",i);
            printf("x =%d \n",arrayCLONE[arrayAR[i].i].x);
            printf("y =%d \n",arrayCLONE[arrayAR[i].i].y);
            printf("_____ \n");

        //  temp.x=arrayCLONE[arrayAR[i].i].x;
        //  temp.y=arrayCLONE[arrayAR[i].i].y;
        //  printf("index i =%d \n",arrayAR[i].i);
        }
    }

    //Q.push_back(temp);
    //sorting section end

    S.push(Q[0]);
    S.push(Q[1]);
    S.push(Q[2]);

    for (int i=3;i<10; i++){
    while (right_turn(S,Q[i])==1)
        S.pop();
        S.push(Q[i]);
    }

    //  S.push(Q[5]);

    printf("points: \n");
    while (!(S.empty()))
    {
        point=S.top();
        S.pop();
        printf("(%d,%d) ",point.x,point.y);
    }
        printf("\n...");
        getch();
        return 0;
    }

Comment: Why did you change your for-loops to be `for (i=1; i<9; i++)`? You realize that `array[0]` is a valid index, right? It would be nice to mention *what* you changed as well: Your `operator<` was wrong, and you were indeed printing floating points as decimals as my answer pointed out.


New value with one similar column and on different column in R

Question: I need to mutate a new value: "new_value" based on the same ID "ï..record_id". I need all with the same ID to have the same value in "date_eortc".
My data1 looks likes:
data1 %>%
  select( ï..record_id, dato1, galbeta_date, date_eortc)

>    ï..record_id      dato1 galbeta_date date_eortc
1              1       <NA>         <NA>       <NA>
2              1       <NA>         <NA>       <NA>
3              1       <NA>   2018-01-16       <NA>

.....
99            10 2018-02-07         <NA> 2017-12-27
100           10       <NA>         <NA>       <NA>
101           10       <NA>         <NA>       <NA>
102           10       <NA>   2017-12-19       <NA>
103           10       <NA>   2017-12-26       <NA>
104           10       <NA>   2017-12-29       <NA>
105           10       <NA>   2018-01-02       <NA>
106           10       <NA>         <NA>       <NA>
107           10       <NA>         <NA>       <NA>
108           11       <NA>         <NA>       <NA>

In this case I need all with "ï..record_id"=10, then date date eortc should all be "2017-12-27"
So it would looks like:
    ï..record_id      dato1 galbeta_date date_eortc
99            10 2018-02-07         <NA> 2017-12-27
100           10       <NA>         <NA> 2017-12-27
101           10       <NA>         <NA> 2017-12-27
102           10       <NA>   2017-12-19 2017-12-27
103           10       <NA>   2017-12-26 2017-12-27
104           10       <NA>   2017-12-29 2017-12-27
105           10       <NA>   2018-01-02 2017-12-27
106           10       <NA>         <NA> 2017-12-27
107           10       <NA>         <NA> 2017-12-27
108           11       <NA>         <NA>       <NA>

I have tried to make an ifelse statement, but it's not the right one...
data2 <- data1 %>%
  mutate(new_value= ifelse(ï..record_id == ï..record_id , date_eortc, NA))

I hope it makes sense.
Thank you for your time,
Julie
Comment: It would be better if you could share a reproducible excerpt of your data so that we can use it to find a solution.
Answer: We could do a group_by the ï..record_id and fill the NA elements in 'date_eortic' with the non-NA adjacent element
library(dplyr)
library(tidyr)
data1 %>%
   group_by(ï..record_id) %>%
   fill(date_eortic)


Função Pyscript no html

Question: Como eu faço para chamar uma função pyscript dentro do html?
Exemplo:
<!DOCTYPE html>

  <title>Py Test</title>
  <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />

  <py-script>
    def test():
      for x in range(4):
        print(x)
  </py-script>

  <button onClick="test()"> Teste </button>

Answer: Você pode usar o atributo py-*="", trocando o asterisco pelo evento que deseja. Segue a lista de eventos que você poderá adaptar ao py-*: https://developer.mozilla.org/en-US/docs/Web/API/Element#events
No seu caso será o py-click="" e para manipular um elemento na página você pode usar o pyscript.Element
Exemplo de py-click e py-change:

<link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />

<button py-click="ola_mundo1()">Testar</button>

<select py-change="ola_mundo2()">
   <option>valor 1</option>
   <option>valor 2</option>
</select>

<py-script>
# obtêm o elemento do contexto da página
elemento = Element("id-foo-bar").element

def ola_mundo1():
    elemento.innerHTML = "Olá Mundo (botão)!"

def ola_mundo2():
    elemento.innerHTML = "Olá Mundo (alterou o select)!"
</py-script>

Você também pode aplicar ou remover um evento dinamicamente você pode usar o pyscript.Element para aplicar ou o import js, e com js.document você vai poder acessar o contexto da página, mas para criar uma função que comunique terá que adiciona-la usando o método create_proxy do módulo pyodide.ffi
Exemplo:

<link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />

<button id="id-botao">id-botao</button>

<button class="classe-botao">classe-botao 0</button>

<button class="classe-botao">classe-botao 1</button>

<button class="classe-botao">classe-botao 2</button>

<py-script>
import js
from pyodide.ffi import create_proxy

# Element obtêm um elemento por ID
botao_por_id = pyscript.Element("id-botao").element

# js.document obtêm o DOM do contexto da página
botoes_por_classe = js.document.querySelectorAll(".classe-botao")

# cria a função
def ola_mundo(event):
    botoa_atual = event.target
    print("Olá, você clicou no botão:", botoa_atual.textContent)

# cria o proxy pra usar a função no elemento
proxy = create_proxy(ola_mundo)

# adiciona dinamicamente a função
botao_por_id.addEventListener("click", proxy)

# Com for você itera os botões com atributo class="classe-botao"
for botao in botoes_por_classe:
    # adiciona dinamicamente a função
    botao.addEventListener("click", proxy)
</py-script>

E você também pode adicionar um evento sem usar o proxy, usando o método add_event_listener do pyodide.ffi.wrappers, tornando as vezes mais simples:

<link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />

<button id="id-1">Botão id-1</button>
<button id="id-2">Botão id-2</button>

<py-script>
from js import document
from pyodide.ffi.wrappers import add_event_listener

def ola_mundo(event):
    botoa_atual = event.target
    print("Olá, você clicou no botão:", botoa_atual.textContent)

# Com Element
botao_1 = pyscript.Element("id-1").element

# Com js
botao_2 = document.getElementById("id-2")

add_event_listener(botao_1, "click", ola_mundo)
add_event_listener(botao_2, "click", ola_mundo)
</py-script>

Referências:

https://docs.pyscript.net/latest/guides/event-handlers.html
https://docs.pyscript.net/latest/tutorials/py-click.html
https://docs.pyscript.net/latest/tutorials/writing-to-page.html

Função Pyscript no html