Need to make Anonymous user create node through a Form but can't

Question: I need to make anonymous user create a node through my site. The node which is create would be unpublished, which an admin can publish later.
I wrote the following code which works perfectly but the only gripe is that Anonymous can't submit it.
I also gave the permission in the Permission - Node: Create new content but nothing works ...
Any Idea please ....
This is what I did:-
<?php
       if (isset($_POST['submit'])) {

                  //Core Form Elements.
                  $employee_name = $_POST["EName"];
                  $role          = $_POST["Role"];
                  $office        = $_POST["Office"];
                  $location      = $_POST["Location"];

                  $my_node = new stdClass();
                  $my_node->type = "my-node-type";
                  node_object_prepare($my_node);

                  $my_node->title    = $title;
                  $my_node->language = LANGUAGE_NONE; // Or e.g. 'en' if locale is enabled

                  $my_node->field_employee_name[$my_node->language][0]['value']    = $employee_name;
                  $my_node->field_employee_role[$my_node->language][0]['value']    = $role;
                  $my_node->field_office[$my_node->language][0]['value']           = $office;
                  $my_node->field_location[$my_node->language][0]['value']         = $location;

                   $my_node->uid = $user -> uid;

                  $my_node->body[$my_node->language][0]['value']   = $story;
                  $my_node->body[$my_node->language][0]['format']  = 'filtered_html';

                  $path = './sites/default/files/animage.png';

                  $path = 'node_created_on' . date('YmdHis');
                  $my_node->path = array('alias' => $path);

                  if($my_node = node_submit($my_node)) {

                      node_save($my_node);
                      echo "
 Thank you, Node Recieved.
";
                      echo "Node with nid " . $my_node->nid . " saved!\n";

                  }
              }

              else {

              ?>

<?php print render(field_view_field('node', $node, 'body', array('label'=>'hidden'))); ?>

                <form method="post" enctype="multipart/form-data" id="node_submission" action="<?php echo $PHP_SELF;?>">

                  Name:
                  <input type="text" name="EName" id="employee_name" value="<?php echo $user -> name; ?>" placeholder="Full Name" required />

                  Role:
                  <input type="text" name="Role" id="role" value="" placeholder="Your Role in the Firm" required/>

                  Office:
                  <input type="text" name="Office" id="office" placeholder="Your Primary Office" required/>

                   Title
                  <input type="text" name="Title" id="title" placeholder="A Concise Title to your Story"/>

                  What's your description:
                  <textarea type="text" name="Story" id="story" placehold="Your Amazing Story" required></textarea>

                  <input type="submit" name="submit" value="Submit" class="submit-button btn btn-lg btn-primary" />
                  <input type="reset"  name="clear" value="Clear" class="clear-button btn btn-lg btn-secondary" />

                </form>
              <?php
              } ?>

Comment: Incorrect way of using Drupal. Please read next https://www.drupal.org/node/1702548 about forms. Read about https://www.drupal.org/node/1388922 for saving node programmatically.
Comment: I don't think it is recommended to give permission to anonymous to submit nodes without any email verification or any sort of filtering. Your server may get filled with spam nodes even if they are unpublished it will still remain in database.
Answer: The correct way to implement this as to follow the drupal standard to create a form and save the contents of the node on submit.
 function MYMODULE_menu() {

        $items['Demo'] = array(
            'title' => 'Demo',
            'description' => 'Example form',
            'page callback' => 'drupal_get_form',
            'page arguments' => array('user_detail_form'),
            'access callback' => TRUE,
        );

return $items;

}

function user_detail_form(){

 $form['employee_name']= array(
      '#title' => 'Employee Name :',
      '#type'  => 'textfield',
      '#required' => TRUE,
      '#attributes' => array('placeholder' => 'Full Name'),
     );

     $form['role']= array(
      '#title' => 'Role',
      '#type'  => 'textfield',
      '#required' => TRUE,
      '#attributes' => array('placeholder' => 'Your Role in the Firm'),
     );
 $form['office']= array(
      '#title' => 'Office',
      '#type'  => 'textfield',
      '#required' => TRUE,
      '#attributes' => array('placeholder' => 'Your Primary Office'),
     );
 $form['title']= array(
      '#title' => 'Title',
      '#type'  => 'textfield',
      '#required' => TRUE,
      '#attributes' => array('placeholder' => 'A Concise Title to your Story'),
     );
 $form['story']= array(
      '#title' => 'What's your description:',
      '#type'  => 'textfield',
      '#required' => TRUE,
      '#attributes' => array('placeholder' => 'Your Amazing Story'),
     );
 $form['submit']= array(
      '#type'  => 'submit',
      '#value' => 'Submit'
     );

return $form;

}

function user_detail_form_submit($form, $&form_state){

   global $user;
 $employee_name = $form_state['values']["employee_name"];
                  $role          = $form_state['values']["role"];
                  $office        = $form_state['values']["office"];
                  $location      = $form_state['values']["location"];

$my_node = new stdClass();
                  $my_node->type = "my-node-type";
                  node_object_prepare($my_node);

                  $my_node->title    = $title;
                  $my_node->language = LANGUAGE_NONE; // Or e.g. 'en' if locale is enabled

                  $my_node->field_employee_name[$my_node->language][0]['value']    = $employee_name;
                  $my_node->field_employee_role[$my_node->language][0]['value']    = $role;
                  $my_node->field_office[$my_node->language][0]['value']           = $office;
                  $my_node->field_location[$my_node->language][0]['value']         = $location;

                   $my_node->uid = $user -> uid;

                  $my_node->body[$my_node->language][0]['value']   = $story;
                  $my_node->body[$my_node->language][0]['format']  = 'filtered_html';

                  $path = './sites/default/files/animage.png';

                  $path = 'node_created_on' . date('YmdHis');
                  $my_node->path = array('alias' => $path);

                  if($my_node = node_submit($my_node)) {

                      node_save($my_node);
                      echo "
 Thank you, Node Recieved.
";
                      echo "Node with nid " . $my_node->nid . " saved!\n";

                  }

           //Add desired code to implement

}

For more information click Here
Hope it works for you!
Comment: you can check if user is anonymous and then set `$my_node->status=NODE_NOT_PUBLISHED`
Comment: Unfortunately, this doesn't work for anonymous either. It works for all the other user types except anonymous ...
Answer:
Create a new content type, with fields as per your requirement.
From content type edit page, uncheck the 'Published' option.
From the permission page (/admin/people/permissions)
Give the Anonymous User to permission : Create new content

Hope it will work for you.
Comment: This is exactly what I am doing. But it doesn;t work.


Slideshow showing 3 slides (prev - active - next)

Question: I am trying to accomplish the following:
I have a content type that contains title, img and body.
i want to show the nodes in a slideshow, like for example flexslider.
Nothing special so far.
i now want to show 3 slides at once, the 3 slides cover 100% width, where the 1st slide is the previous slide, the middle one is the active slide and the 3rd one is the next slide.
(The 1st and 3rd slide have some opacity on them to mark the active slide)
i have tried to do this with flexslider, jcarousel and jquery cycle but without aky success.
I managed to show 3 slides at once, but then i cannot navigate through the slides.
Any suggestions on how you guys would approach this would be very welcome!
Thanks in advance!
Edit:
After some more research i created 3 flexsliders (each in their own content pane) that i put into one page manager page.
I then floated them next to each other.
I configred each flex slider to skip 0,1 and 2 slides accordingly.
I now still have the remaining issue of controlling the 3 slideshows through one next and previous buttons.
Any suggestions for this would be very welcome!
Answer: Edit2:
I found the solution by studying the flexslider module. You can manipulate sliders by #ID with the following commands:
<code>(function ($) {
$(document).ready(function(){
$(".page-about-livio #flexslider-2 .flex-next").click(function() {
    $('#flexslider-1').flexslider("next");  //Go to next slide
    $('#flexslider-3').flexslider("next");
});
$(".page-about-livio #flexslider-2 .flex-prev").click(function() {
    $('#flexslider-1').flexslider("prev");  //Go to next slide
    $('#flexslider-3').flexslider("prev");
});
});
})(jQuery);
</code>


how to configure apache server

Question: I'm working on a system that needs to manage databases for 1000 users (at maximum). I used Apache server, and MySQL for this task.
Since I'm new to the whole thing my question is:

Is it possible to configure Apache server so it locks writing on a record whenever a user is updating that record?
Is it the right choice? I mean is it better for me to implement my own server or just use Apache?

I'm using python 2.6 and Windows x64, pyqt4 for the interface.
I would really appreciate it if you guys could give me any advise related to this (like: Don't use python, use C++).
Comment: and by the way , this system will be to handle all the tasks progress inside the company , manage assets and file versions , and organize work overall .
Answer: httpd doesn't handle the database itself. You need to ask these questions of the language/framework you will be using, rather than the web server.
Comment: can you please explain more ,( sooo sorry for my noobie question ) iv'e been programming GPUs and writing AI for games only . that's all my back ground :(   )
Comment: The web server only handles the HTTP connection part. If you want to run an actual program then it needs to hand off control to the program itself, which can be written in pretty much any language. Most languages have web frameworks that are used in order to handle common operations more easily. http://wiki.python.org/moin/WebFrameworks
Comment: @lgnacio , thank you very much , i think i'll start learning django now :) .sorry cant give +1 because of my reputation on this site ^^.
Answer:
i'm working on a system that needs to
  manage the data bases of 1000 user...

1000 total 'users/week' or 1000 online at a single time?
1- Already answered: Apache doesn't lock database tables, MySQL can handle that part.
2- Is Apache the right choice?
IMO, you can have 3+ years of experience and still debate the answer.

Apache is easy to learn the basics,
but generally uses a lot of
resources.
The right choice is to use something lightweight upfront (i.e. lighttpd or nginx / google 'caching
server' or 'reverse proxy server'.)
with Apache handling the rest (as
little as possible)
Answer: It's hard to answer such a confused question but here are some key points:
Apache doesn't deal with the database at any level. Thats handed by the web application and the locking is handled by MySQL itself.
Questions regarding the choice of programming language are out of place here, as that has nothing to do with system administration. Further, it has no direct bearing on the issue of a web server and database server.
If you feel confident that you can write your own web server and thereby eliminate Apache that's entirely up to you. Knowing nothing at all about your level of competency as a programmer we cannot say whether that's a good or bad decision, although being aware of the time and effort it has taken to bring any web server to a production ready state does give us some clues as to the likely outcome of writing your own.

how to configure apache server


What should I further study to learn to write music better

Question: Okay I hope this doesn't get downvoted. I am trying to get back to learning to write music (on the computer). I started in 2011 and having learned software, basic music theory I kept failing  despite numerous attempts (I had some success but not much). I stopped about 3.5 years ago. I was hoping maybe someone could get me on the right track.
The music I am going for:

 ^(first track in the background here; probably 99% representative of my taste; I'd be really happy if I could compose something like that)

 ^(and all TF2 music)
Basically, I like jazz harmonies (~70's spy jazz), psychedelic, dissonant sound. Quite a fan of the whole tone scale.
I learned basic (perhaps, sub-basic?) theory from this book: https://www.amazon.com/Theory-Computer-Musicians-Michael-Hewitt/dp/1598635034
I suppose what I learned was insufficient, for my purposes at least, since I struggled a lot. I think the theory I learned might be enough for primitive tuz-tuz house music, but not for what I am going for. At least that was my experience. What should I further learn/read?
Main problem I would usually face:
1) I could never develop an interesting musical snippet (write something complimentary to it). Would usually have to loop it. I'm very lost as to how to progress a piece (including how to transition between one idea to another) and don't understand its logic (unless it is house which where it's generally repetition of clearly delineated bars). When I listen to:

 it's a mess, I can't follow what's going (same with any piece harder than a house track, although to a lesser extent).
2) Once I "learned basic music theory" all chord progression/melodies I would come up would usually be much more boring for some reason than those that I had come up before I learned any theory (those weren't anything special obviously).
I also learned to play through scales, in addition to some chords. But I was slow with chords and scales didn't help much. I usually see people playing through chord progression on the fly when writing music. Is that an important skill? It seems like they're just trying out old stuff they learned, but I'm not sure. In general, I'm not interested in playing the keyboard more than necessary for writing/producing music.
Thank you.
EDIT: Here's a helpful related question: Want to learn composing and producing music with a DAW. Where do I start?
Comment: theory is descriptive, not prescriptive. You can still compose your own music - you don't need to follow it BUT the theory helps explain why certain intervals sound well. It is entirely possible to make a minor 2nd sound well, independent of music theory.
Comment: How should I learn an instrument? I'm not interested in playing tbh, not my cup of tea, I've tried many times (guitar then keyboard) and failed. I'm bad at playing evenly and I hate a musical piece by the time I learn it properly, because I've listened to it so many times .Maybe that's why I'm bad at music writing, because I can't learn to play an instrument... I want to learn keyboard skill necessary to write music, but I don't know how. Learning individuals pieces doesn't help, and I tried learning scales—I'm not sure what to do with them. _Do I need to learn to improvise?_
Comment: @Lenny, yeah I know about intervals. My problem is developing a piece in time instead of looping a musical idea... Sometimes I can write a piece where melodies and progressions flow nicely without too much repetition and transition well, but I have no idea how to arrive at that deliberately. It's like black magic when it happens. I suppose it's some kind of more advanced theory.
Answer: This is a pretty big question, but I think there's a way forward.
As you've discovered, music theory in and of itself doesn't necessarily lead to music. It gives us a language to describe music, and can give us musical ideas, but it's not a recipe for making a song. Especially if there's a pedant around to inform you that music without words cannot be called a song.
I learned a lot through imitation. You have some example songs. Can you play them? Even if you don't learn an actual instrument, can you recreate the melody and chords on your computer? This is not a magic bullet, but it's how I learnt (or am learning, let's be honest) to arrange for concert band. Sure, it's a different skill, but I think you might be able to learn in the same way. Once you can recreate, it's easier to create.
This might also help you escape the looping trap. Loads of new musicians just loop the same phrases over and over, and add new bits throughout the song. There's absolutely nothing wrong with that, but there's a whole world of other compositional techniques out there waiting to be discovered. Imitation might help you discover them.
Finally, do consider learning an instrument, even at a basic level. Keyboard or guitar would be a good place to start. Theory makes much more sense when combined with actual practice. And you might accidentally get inspired! It's an occupational hazard. That, and buying more music gear. Gear Acquisition Syndrome is a real killer.
Comment: Thank you for the nice comment. I will try to recreate melodies and harmony of songs I like. Unfortunately, I've always struggled with learning an instrument. I'm restless since childhood and I've never been able to play evenly (and music teachers (guitar) didn't want to deal with me). Then I failed and failed and failed on my own; also learning a piece would desensitize me to it by the time I was getting good at playing it, so I would eventually start to hate it. I guess it's not my cup of tea, composition is what draws me (but I'll have to use quantize ;) ).
Answer: Learning music theory is/was an excellent choice for you to make, it helps so much with writing music as you can generally work out why something doesn't sound too great.
The most important tip that I can give you (and this is something I was told by a professional composer): just keep writing music. No matter how bad it is, keep writing. As with any skill, practice makes perfect (or more accurately: practice makes progression, no ones perfect.
You say that you end up falling back on really basic chord progressions. Force yourself to write with more obscure progressions: 75% of the time it will sound bad/weird; but sometimes something will sound great. Use theory to come up with some good progressions: eg. use major thirds for a spacey sound, and just practice writing with those chord progressions.
Your main question is what you should study further. Continue to study theory, as well as general music and how different instruments work together. Study other people's music and their scores: this helped me loads. For example, I asked my teacher (over the summer holidays) for all the John William's scores the school owned. I spent 6 weeks studying how he writes and trying to replicate a similar style in my own music. Play other people's music as well, it will help you get a feel for particular styles. Eg. find the TF2 soundtrack transcribed for piano or something and practice that. Practice and listen to as many DIFFERENT styles/composers/artists music as you can. This is how you develop your own style and how new genres are actually born: eg. Bhangra is a fusion between Classical Indian and Western Pop.
I come back to my first point. KEEP WRITING MUSIC. This is the most important tip anybody can give you. If you don't keep writing music, no matter how bad it is, you won't improve. In all your spare time, practice writing. Sometimes write for a specific purpose/genre, other times just see what spills out of your head. Mix it up.
Keep writing, keep composing.
Comment: Playing without mistakes or evenly doesn't matter in the slightest if all you're doing is trying to get to grips with the ideas involved. Yeah, I used to have a pot of chords and I'd pick like 2 random chords out of the pot then try to compose just alternating between the 2. Many passages of film music alternate between just 2 chords and a fair amount of classical uses only 2 or 3. This helped me tonnes just to learn how chords and melodies have relationships when you're playing outside of a 'normal' 4 chord pop progression.
Comment: And as for your mention of not being able to play all the way through, that's fine as well, I have the same problem especially with longer pieces. Perhaps (after listening to this piece), just learn the introduction and the sections that you really enjoy listening to/ the main motifs of the piece. This way you can quickly extract the important sections of a piece without spending hours and hours learning every ornament and semi-quaver.
Comment: Thank you very much. As regards boring chord progressions, I think it's to do with my not enjoying simple classical harmonies— there's just not enough dissonance (major, minor scales are too "simple" sounding to my ear, I like a shift towards more chromatic/atonal action). I think you're right about learning other people's music, although I'll probably go for learning individual bars, melodies, chord progressions—I've always had a hard time playing a piece from end to finish (on guitar or piano) evenly and without mistakes.
Answer: I am taking an online course in Jazz Composition from a well-known college. I've played guitar for many years and learned a fair amount of theory, but this course has really taken me to another level. Theory helps to a certain extent, but there are many approaches to create melody and harmony which are partly theory and partly craft. Studying standards has really helped me (as opposed to just reading the music). Some of these programs also offer specific courses in composition for film, and if they are like mine, they will push you, but also give you some support.
Hope this helps.
Comment: @Max - standards are well known, well loved tunes that have become part of the genearl jazz repertoire over time. Autumn Leaves is one such.


Imprimindo um array permanente no html

Question: Bom dia , estou desenvolvendo um sistema de cadastro, mas após imprimir os dados na tela ao recarregar os dados impressos desaparecem. Alguma solução?  Grato.
var aluno = [];
var dados = ["Nome: ", "Email: ", "Telefone: ", "Turno: ", "Modalidade: ", "Vencimento: "];
var listaDeAlunos = [];

//adiciona os valores do input no array aluno
function gravarDados(nome, email ,telefone, turno, modalidade, vencimento){

  aluno.push(nome, email, telefone, turno, modalidade, vencimento);

}

//adiciona o array aluno no array listadeAlunos
function adicionarAluno(aluno, dados){
  for(i = 0; i<= 5; i++){

    listaDeAlunos.push(dados[i] + aluno[i]);

  }

}

function mostraLista(listaDeAlunos){

  let lista = document.getElementById("lista");

  for(i=0; i< listaDeAlunos.length ; i++){

  let item = document.createElement('li');
  item.appendChild(document.createTextNode(listaDeAlunos[i]));
  lista.appendChild(item);
  }

}

function cadastrarAluno(nome, email, telefone, turno, modalidade, vencimento){
  //pega os valores dos inputs
  var nome = document.getElementById('nome').value;
  var email = document.getElementById('email').value;
  var telefone = document.getElementById('telefone').value;
  var turno = document.querySelector('input[name="turno"]:checked').value;
  var modalidade = document.querySelector('input[name="modalidade"]:checked').value;
  var vencimento = document.getElementById('vencimento').value;

  gravarDados(nome, email, telefone, turno, modalidade, vencimento);

  adicionarAluno(aluno, dados);

  mostraLista(listaDeAlunos) ;

  }

Answer: Para gravar os dados seria necessário uma base de dados. Existe também a localStorage no lado do cliente que persiste mesmo depois de recarregar. A localStorage só permite gravar strings por isso é preciso converter o array em JSON.
function adicionarAluno(aluno, dados){
  for(i = 0; i<= 5; i++){
    listaDeAlunos.push(dados[i] + aluno[i]);
  }
  localStorage.setItem("listaDeAlunos", JSON.stringify(listaDeAlunos));
}

function mostraLista(listaDeAlunos){

  let lista = document.getElementById("lista");
  listaDeAlunos = JSON.parse(localStorage.getItem("listaDeAlunos"));

  for(i=0; i< listaDeAlunos.length ; i++){

    let item = document.createElement('li');
    item.appendChild(document.createTextNode(listaDeAlunos[i]));
    lista.appendChild(item);
  }

}

Imprimindo um array permanente no html


High G and G# splitting/jumping to the next harmonic on saxophone

Question: I had asked this question on SaxOnTheWeb a while ago, but I'm still battling with this problem, and it makes certain pieces (like The Beatles' "Come Together") virtually unplayable.
Important information:

In case size matters, this is a tenor.
I started having this problem after a few years of playing saxophone. It had not been an issue beforehand (except, perhaps, during my first 1-2 lessons on a different horn, but back then it was low G and G# splitting/going up).
This happens on all of my mouthpieces.
This happens on all my reeds (even more often and pronounced on synthetic).
Most of the time, slurs from C and C# are involved (both middle and high) or tonguing a few G's/G#'s in succession.
It doesn't appear to be an issue with the horn itself, as the problem didn't go away after (properly conducted) maintenance.
I haven't had any major dental or medical work done on the oral cavity, and there haven't been any structural changes from other sources either. The only change I can think of was growing a beard, but it's not like it grows on my lips or inside my mouth.

The only reason I can think of for the problem is a change in embouchure, but I have not been able to qualify it, as it's rather sporadic. Pulling my cheeks in a bit (restricting the width of the airstream inside my mouth) while opening up the throat seems to help most of the time, so does "thinking" of the note before playing it, but I still don't understand why I have to be doing that when everything used to be fine with those 2 notes before.
Having played the instrument without the octave key could be related.
What is going on? Are there any exercises I could do to make sure it never happens? I've been doing everything I can daily, including but not limited to:

Playing large jumps (2 or more octaves) slurred.
Playing harmonics on the low-end notes and "matching" proper fingerings with them.
Playing with and without the octave key.

I'm at my wits' end at this point.
Comment: There are two octaves holes on a sax: when the octave key is pressed, one is opened for notes lower than G, and the other from G and higher. One of these could be leaking, and not the other one, thus favoring a bit the octave register in some range… Depending on the note you come from, the octave can also favored a bit, so if the effects add up… Anyway, that is just a wild guess… But also check that these valves are properly closing, using a thin cigarette paper for instance…
Comment: The way I usually do is: open the valve you want to test, slide a cigarette paper between the hole and the pad, close the valve and see if the paper slides freely. You should also check for only part of the pad. If it slides it means that it is not hermetic… That's just a trick, I hope it helps though as these days it is hard to get one hand on another sax :/…
Comment: "It doesn't appear to be an issue with the horn itself": it would still be worth trying with another one, could be a small leak on the octave system (which is actually not opening the same hole for pitches higher than the G…)
Comment: Would also maybe worth checking all the pads over the G… That's puzzling me, let us know if you find a reason!
Comment: @Tom, thank you. I'd considered that, but why does the problem only occur with G and G# and none of the other notes below? And only when slurring in from certain notes (or just tonguing multiple G's/G#'s in succession)? I'll have to think of a way to get my hands on another tenor somehow, which isn't easy these days...
Comment: @Tom, thank you, I am aware of the 2 vents being present. How would I go about using cigarette paper to check for leaks though? Could it also be done with blowing smoke through the pipe? That's how I normally do it on flute. Would be _really_ strange if the repair technician somehow managed to miss that. The octave mechanism is the first thing they normally check.
Comment: @Tom, thank you! I'll give it a try... Not sure how helpful it will be with the neck vent, because the pad there is quite small and not too flat either, but I'll check. I find it puzzling as well. It's very inconistent. Some days I don't experience it at all. Today, for example, was split- and jump-free. On new reeds it doesn't seem to happen at all, until they get "broken in"... Sometimes high G and G# get "stuck" completely, in that I cannot play them at all (no air passes through), but that happens almost exclusively on synthetic reeds.
Comment: @Tom, I performed both the smoke test and the cigarette paper test, and the tone holes don't appear to be leaking. The paper slides from underneath the top pad with just a little bit of force, but I think that's normal. The lower vent closes significantly better. Maybe I'm hitting the palm D# key without noticing it? Hence the problem with G and G# in the upper range only?
Answer: Assuming your instrument is in good condition, I'm pretty sure it's the embouchure. One important thing to remember is that no matter how you do voicing and tone imagining etc., finally it all comes down to five basic physical aspects which together decide the tone 1. point of contact between lower lip (jaw) and the reed 2. the amount of pressure you're giving to this point 3. how much the lips are used for changing color (more "u" or more "i") 4. the speed of air flow 5. the angle of air flow entering the tip opening, which is controlled by the tongue.
According to the studies you've done, I think your 1. position is too forward and 2. is too strong. A forward jaw position makes the reed to vibrate in higher frequencies more easily, and since you can easily blow the altissimi I guess you're giving too much force on this point, more than your teacher.
I can suggest two ways to deal with it.

If the results on all the other notes are fine, just treat the G2 and G#2 with special care. Every time you meet these guys, draw back a bit your jaw, or just bite less hard, or give more lips instead of bite. Or, since normally on a tenor there's no need for enormous effort on embouchure adjusting especially on a note like G2:

Judging by provided situation, I suspect you might also have intonation deviation on many other notes and a overall too straight forward / sharp tone color. Therefore you can try changing the point of contact a bit backward, playing with more "u" lips instead of "i" biting. Once you can successfully play multiple G2 fast staccato, see how other notes sound using the same embouchure. If you really need a clear study objective, try the extreme opposite exercise of playing without using the octave key: play all the first octave notes but with octave key added (all normal first octave fingering plus octave key) and make them still sound in the 1st octave. Through this exercise you will have to adjust your overall embouchure to allow the reed to vibrate in low frequencies.

Good luck with the studies!
Comment: Thank you! 1) Treating G and G# with special care seems to produce more issues. The problem seems to be psychosomatic in part, meaning I occasionally slip up simply because I am "afraid" of these notes (think about them too much). 2) That's weird as well. My upper jaw actually protrudes beyond the lower jaw ("weak chin"). The exercise you recommend (playing the lower octave _with_ the octave key) is one of my daily exercises... Tone is within acceptable range throughout the instrument (with a deviation of no more than 15 cent).
Comment: You know, everyone's physical aspects are different and unfortunately I can't control your posture in person, I'm thinking that since the "u" trick works, perhaps you have a very thin lower lip? Having a very thin lip is kinda like placing the lower teeth directly on the reed (which makes the reed squeak easily). Anyways, it seems that the better solution for you is to find that sweet spot between "u" and "i" with patience
Comment: What helped me from within your answer was changing to a more "u" kind of embouchure, but I feel that it interferes with opening my throat and my attempts at learning circular breathing (it's kind of impossible to puff out one's cheeks with an "u" lip positioning). And I still don't understand why I'm getting this problem after years of playing the instrument. It doesn't make sense. What could've possibly affected my embouchure to such a degree?
Comment: Yeah, I realise that. My posture hasn't been better after I picked up flute as a second instrument. According to women, my lips are very thick. But, if it helps, I am putting the skin below the lip between the reed and the teeth instead of the lip itself (like I said, "weak chin"). I'd tried extending the lower jaw and rolling my lower lip out, but it doesn't work for me. So weird I got to this point after years of playing the instrument just fine. Maybe my flute embouchure affected it somehow? That's what I'm inclined to believe after diligently reading through your answer and applying it.
Answer: I have the same trouble and am an advanced player. Recently, I traded tenors for a rehearsal with my friend and I could play the G2 and G#2 easily with no trouble at all. I had tried all other mouthpieces, reeds etc. Could be the saxophone. Another very smart friend of mine said that around those notes is a "dead zone" and that makes sense to me that I would get overtones not desired. He suggested that I try alternate necks for my saxophone. I am thinking of just trying other tenors....
Comment: Thank you! Have you had that problem with your tenor from the very beginning? What horn do you play if you don't mind me asking? Also, not sure what exactly you mean by "dead zone".


Euler-Langrange equation for improper action integral

Question: The Euler-Lagrange equation is used to optimize the functional $S[q]=\int_a^b L(t,q(t),\dot q(t))dt$ with $[a,b]\subset\mathbb{R}$. What if $b=+\infty$ and/or $a=-\infty$? Should any assumptions be added so that the Euler-Lagrange equation is still a necessary condition of optimization?
Answer: The Euler Lagrange equation still applies in this case. Even when the interval is $[a,b]  = [-\infty, \infty]$, recall that the Euler Lagrange equation is derived using
$$\frac{d}{dt} S (q+ t \phi) \bigg|_{t=0} = 0$$
where $\phi$ is a function with compact support in $[a,b]$. The end points of this interval does not come into play.


ArrayList.get() return null value

Question: I'm starting with java and I'm facing an issue.
I create an array lsit, and add object to it.
Then I create a method to return this object, but this method return a "null" value.
I can't figure out how to solve this issue.
Here is the error:
Exception in thread "main" java.lang.NullPointerException
    at StarSystem.getPlanetString(StarSystem.java:29)
    at StartActivity.main(StartActivity.java:9)

here is the code:
Main: In here I just display data on screen:
import java.util.Objects;

public class StartActivity {

    public static void main(String[] args) {
        StarSystem starSystem = new StarSystem();

        starSystem.getPlanetString();

    }
}

Planet: this class is used to create planets:
public class Planet {

    final double planetMinRadius = 1000;
    final double planetMaxRadius = 100_000;
    double temperature;
    double powerReceived;
    int radius;

    public Planet() {
        radius = 1247;
    }

    public int getRadius() {
        return radius;
    }

}

StarSystem:: in this class, I generate a starSystem object and want to link it with a list of Planets:
import java.util.ArrayList;

public class StarSystem {

    final int minNumberPlanet = 3;
    final int maxNumberPlanet = 10; //10
    int numberPlanets = 5;
    double positionX, positionY;
    ArrayList<Planet> planets;

    public StarSystem() {
        ArrayList<Planet> planets = new ArrayList<Planet>(numberPlanets);

        for (int planetPosition = 0 ; planetPosition < numberPlanets ; planetPosition++) {
            Planet planetToAdd = new Planet();
            System.out.println("planetToAdd.toString :" + planetToAdd);
            planets.add(planetToAdd);
            Planet p = planets.get(planetPosition);
            System.out.println("p.toString : " + p);
        }
    }

    public void getPlanetString() {
        System.out.println("TEST");
        Planet a = planets.get(1);
        System.out.println("a.toString" + a);
    }

}

thanks in adavance for your help
Comment: Can you provide a [mcve]?
Comment: Nothing in the code you're showing so far reproduces what you're saying happens, so: prove that what you're claiming is indeed what happens by forming the [mcve] that Sweeper asked for. It's not just "for us", it's also "for you, to demonstrate to yourself that what you think is happening, is actually happening". ArrayLists are bounded, so will throw an error if `position` is a bad number, and `new Planet()` yields "not a null", so where is the _actual_ code that shows you trying to get out a planet but getting `null` back? (and please read through that link, it explains _how_ to make one)
Comment: `ArrayList planets = new ArrayList(numberPlanets);` in the constructor is **SHADOWING** the `planets` field, so the field is never assigned a value. Any good IDE would have warned you about this. *You are using an IDE, right?!?* --- Remove `ArrayList`, so the code uses the field, not a local variable.
Comment: Add the constructor for the planet class at least.
Comment: I just add the Planet class
Comment: I shared the full minimal code. I can reproduce the error with the updated code shared. Still can't find the solution. thanks for your help
Comment: I simplify the code for clarity.
Comment: Yes ! It works ! Thank a lot !
Yes I use an IDE: Eclipse, but it does not show any error...
Can you recommand a better IDE ?
Comment: @AnthonyLEVILLAIN - IntelliJ. It's a great mystery of the universe that anybody ever used Eclipse given IntelliJ is both much better and older. IDK, did maybe IntelliJ not originally have the free Community Edition version?
Answer: I see nothing wrong with your code. I suspect your problem lies in code you are not showing us.
We can make this a lesson in Debugging 101.
Do not combine clauses of code, as that makes debugging difficult. Another benefit is that the Java compiler can better optimize. So separate you new planet instantiation from adding to the list.
Drop in some println calls to see your values in action.
By the way, when you know the likely number of elements in a list, specify that number as an initial capacity.
numberPlanets = determineNumberOfPlanets();
System.out.println( "numberPlanets: " + numberPlanets ;
ArrayList<Planet> planets = new ArrayList<Planet>( numberPlanets );

for (int planetPosition = 0 ; planetPosition < numberPlanets ; planetPosition++)
{
    Planet p = new Planet() ;
    System.out.println( "planetPosition: " + planetPosition ;
    System.out.println( "p.toString(): " + p ) ;
    planets.add( p );
    Planet p2 = planets.get( planetPosition ) ;
    System.out.println( "p2.toString(): " + p2 ) ;
}

Write your code to fail fast. Whenever handing off objects between chunks of code, check their validity.
Java offers some handy utility methods to check for nulls. The method Objects.requireNonNull returns the first argument you pass, unless null. If null, this utility throws an exception. To customize the message of that exception, pass a message string as the second argument.
Planet p2 = Objects.requireNonNull( planets.get( planetPosition ) ) ;  // Another way to check for null. Throws exception if null.

Comment: Thank you for your helpful comments regarding way of debugging.
I just edit my initial text so you can see the full code
Comment: I shared the full code and changed according to your remarks, but I'm still not able to find a solution. Could you please have a quick look? Thank you
Comment: I simplified the code for clarity.
Comment: With enough code in the question, the [real problem](https://stackoverflow.com/questions/61546889/arraylist-get-return-null-value#comment108872899_61546889) has reared its head.
Comment: sorry about that, it was my first post, I will know for the next time. And I got some advices to debbug my future code ;)

ArrayList.get() return null value


Is the function $f(x)= x(\pi-x)$ $2\pi$-periodic?

Question: Is the function defined as follows:
$$
f(x) = \left\{\begin{align}0 \ \ -\pi \le x \le 0 \\ x(\pi - x) \ \ 0 \le x \le \pi \end{align}\right.
$$
$2\pi$-periodic or not?
My attempt:
The function is defined on $[-\pi, \pi]$. First we must check that if $x$ is in $[-\pi,\pi]$, $x + 2\pi$ remains in $[-\pi, \pi]$, which is wrong since
$-\pi\leq x \leq \pi$
$\implies\pi\leq x + \pi\leq 3\pi$
$\implies  x + 2 \pi\in [\pi,3\pi] \text{ and not in } [-\pi, \pi].$
So the $f$ is not $2\pi$-periodic.
Comment: Your function has so far only been defined on an a length-$2\pi$ interval. Exactly one periodic function satisfies the given information.
Comment: If a function is only defined on $[-\pi,\pi]$, then it is $2\pi$-period if and only if $f(-\pi)=f(\pi)$. (But being $2\pi$-period on $[-\pi,\pi]$ is not a very informative property. Perhaps you have mis-stated the question?) Your argument is false, because the periodicity or not of a function only depends on its values within its domain $-$ see [this definition](https://en.wikipedia.org/wiki/Periodic_function#Definition).
Comment: Looks quadratic to me if I understand this correctly.
Comment: Nobody can tell you if the function is periodic unless you give its definition on the whole domain. So far it is defined only on $[-\pi,\pi] $.
Comment: One conventional thing so do is to say "$f$ is the $2\pi$-periodic function with ..." and then write your statement.  It is to be understood that $f$ is defined for all $\mathbb R$ and the other values are obtained using the $2\pi$-periodic property.
Answer: It is not $2\pi-$periodic since $f(x)=0$ with $x\in[-3\pi, -\pi]$ an $f(x)\not=0$ $\forall x\in[-\pi, \pi]$.


Are there any known backward compatibility issues with upgrading Newtonsoft.JSON?

Question: Are there any known backward compatibility issues with upgrading Newtonsoft.JSON, specifically in my case from 4.5.9 to 6.0.8?
Comment: If you start at [james.newtonking.com](http://james.newtonking.com/) and go back through the pages you will be able to find all the changes. (I suggest you go back to version 4.5.8 and work forwards from that.)
Comment: I've successfully upgraded multiple projects from 6.x to 10.x without issue.
Comment: I work on an client application that used web api 1 which depended on newtonsoft.json 4.x that we upgraded to web api 2 that depends on v6.0.5 of newtonsoft json without seeing any issues.  The objects that were getting serialized/ deserialized were fairly simple.
Answer: I don't see any incompatibility issues with mine. I have upgraded mine from v5.0.8 to v6.0.8 and it works fine. But I thought just to check out the changes from v4.5.9 for you as I am also curious.
So, here is the list of changes made from v4.5.9 to v6.0.8.
<code>v4.5.10
Change - Improved duplicate object reference id error message

v4.5.11
Change - Silverlight and Windows Phone assemblies in NuGet are strong named again
Change - Improved CamelCasePropertyNamesContractResolver camel casing property names
Change – Explicit JValue conversions are more flexible when converting values

v5.0.1
Change - NaN and Infinity floating point values are serialized as strings by default
Change - Minor breaking changes to JsonSchema type
Change - Upgraded Windows Phone assembly to WP8
Change - DateTime IDictionary keys are now serialized in ISO date format
Change - DataContractAttribute is no longer inherited to match DataConctractSerializer behavior
Change - StringEnumConverter converts empty strings to null for nullable enums
Change - Guids serialize to a binary UUID in BSON instead of a string
Remove - Removed SL4 library
Remove - Removed WP7 library

v5.0.2
Remove - Removed WP8 library

v5.0.3
(Fix)

v5.0.4
Change - Changed .NET 4.5 portable library and WinRT library to use compiled expressions reflection

v5.0.5
Change - Changed some explicit interface methods on JArray to public to support use with ImpromtuInterface

v5.0.6
(New features and fixes)

v5.0.7
Change - Extension data is now written when serializing

v5.0.8
(Fix)

v6.0.1
Change - Changed assembly version to 126.96.36.199
Change - .NET 4 Portable build targets MonoTouch and MonoDroid in NuGet package
Change - .NET 4 Portable build targets WP8 and SL5 instead of WP7 and SL4
Removed - DefaultMemberSearchFlags on DefaultContractResolver is obsolete
Removed - SerializeObjectAsync, DeserializeObjectAsync, PopulateObjectAsync on JsonConvert are obsolete

v6.0.2
(New feature)

v6.0.3
Change - Blank XML elements will be written as an empty string instead of null
Change - JValue with a null value will be written as null instead of empty string
Change - DateFormatString is now used when reading JSON

v6.0.4
Change - Limited integer parsing size to JavaScript integer size
Change - Validation that numbers don't end with an invalid character

v6.0.5
(New features and fixes)

v6.0.6
Change - Omit fields array for F# discriminated union serialization when there are no fields
Change - Escape property names in path on readers/writers/tokens when a name contains special characters
Change - Provide line numbers for end tokens on JTokenReader

v6.0.7
(New features and fixes)

v6.0.8
(New feature and fixes)
</code>
I hope this post could help others who is making decision to upgrade or not.
Cheers,
Sam


Neural network to find a linear equation representing the data points

Question: Is it possible to use a neural network to do linear regression? Like can you use a neural network to output coefficients/weights (a1, a2, ..., an, and b) of a linear equation representing the features (x1, ..., xn)?
y = a1 * x1 + a2 * x2 + .... + an * xn + b
Comment: The answer by Sycorax is correct. However, I wonder if the common implementations of neural networks allow for specifying zero hidden layers. Is there a reason why you would not use a linear regression directly?
Comment: Ah I see. I was merely curious if you could use neural networks. Thanks!
Answer: A neural network with zero hidden layers and an identity activation in the final layer is identically linear regression.
The predictions of this network are given by $$
\hat y = Xa + b
$$
which is the same as linear regression.


Prove that exists a linear continuous functional satisfying...

Question: Let $E$ be a normed space over the field of real numbers.
I have to prove that given two convex sets $A$, $B$ in $E$, with positive distance between then, there exists a linear continuous functional such that the infimum of its value on the set $A-B$ its equal to that distance, and it has norm 1.
I have a strong guess that this question can be solved using the geometric Hahn Banach (second form), taking the closure of $(A-B)$, wich is still convex and closed, and the set $\{0\}$. But this give me a inequality, and I dont know how to continue.
I need a hint.
Answer: Let $d=\inf_{x\in A-B} ||x|| $ then $d$ is the distance between the sets $A,B.$ Consider the ball $K=K(0, d) =\{ x\in X : ||x||<r \}$ and the set $C=A-B $ since both the sets are convex, $K$ is open then there exist a linear functional of norm $1$ such that $f(k)<s\leq f(c) $ for all $k\in K$ and $c\in C.$ But for $c\in C $ we have $f(c)\geq 0 $ and $f(c) \leq ||c|| $ hence $\inf_{c\in C} f(c) \leq \inf_{c\in C} ||c|| = d$ thus $d\geq s$ but $\sup_{k\in K} f(k) =d\cdot \sup_{||x||\leq 1} f(x) =d $ thus $s\geq d.$  Therefore $s=d=\inf_{c\in C} f(c).$


React beautiful DND - I get "Unable to find draggable with id: 1"

Question: In the code below the UI renders two "Column" components and each column contains two draggable elements called "Tasks". When the user drags a "Task" between columns the code works - up to a point. When the user continuously drags the task components around eventually they will stop dragging and the user gets an error that says:

Unable to find draggable with id: X

I don't know why this happens nor how to fix it.
Note: I am assuming the way the library works is when you drag elements you need to reorder and update your state in the onDragEnd function.
Here is my code:
app.js
import React,{useState} from 'react';
import {DragDropContext} from 'react-beautiful-dnd';
import helper from './helper_functions'

import Column from './Components/Column';

function App() {

  let initialState =   [
    {
      groupName:"Today",
      tasks:[
          {id:"1", title:"Test-1"},
          {id:"2", title:"Test-2"}
        ]
    },
    {
      groupName:"Tomorrow",
      tasks:[
          {id:"3", title:"Test-3"},
          {id:"4", title:"Test-4"}
        ]
    },
  ]

  const [taskList, setTasks] = useState(initialState)

  function onDragEnd(val){

     let result = helper.reorder(val.source,val.destination,taskList);
     setTasks(result)
  }

  return (
    <DragDropContext onDragEnd={onDragEnd}>
       <Column droppableId="Today" list= {taskList[0].tasks} type="TASK"/>
       <Column droppableId ="Tomorrow" list = {taskList[1].tasks} type="TASK"/>

 context hello world

    </DragDropContext>
  );
}

export default App;

src/helper_functions
export default {
    reorder:function(source,destination,taskDataArr){

     let taskData = [...taskDataArr]

 //     //_____________________________________________________________Source data
    let sourceGroupIndex = taskData.findIndex((val, index) => {                // iterate and find "Today" (or other) index in list data
        return val.groupName === source.droppableId
    });

    let draggedTask = taskData[sourceGroupIndex].tasks.find((val, index) => {  // Get specific task object based on index
        return source.index === index
    }); // dragged object

    let sourceListCopyWithElementRemoved = taskData[sourceGroupIndex].tasks.filter((val, index) => {
        return index !== source.index // removes dragged element from array
    });

    // //__________________________________________________________________Destination data

    let destinationGroupIndex = taskData.findIndex((val, index) => {  // iterate and find "Tomorrow" (or other) index in list data
        return val.groupName === destination.droppableId
    });

    taskData[destinationGroupIndex].tasks.splice(destination.index, 0, draggedTask); // insert dragged item to new place
    taskData[sourceGroupIndex].tasks = sourceListCopyWithElementRemoved

    return taskData

  }

}

src/Components/Column
import React from 'react';
import {Droppable} from 'react-beautiful-dnd';
import Task from "../../Components/Task"

function Column(props){
   const { classes, droppableId, list, type} = props;

   let style = {
    backgroundColor:"orange",
    height:"300px",
    width:"400px",
    margin:"100px"

   }

   console.log(list)

    return (

       <Droppable droppableId = {droppableId} type={type}>
       {provided => (

{droppableId}

            {list.map((val,index)=>{
               return <Task id={val.id} key={index} index={index} title={val.title}/>
            })}

           {provided.placeholder}

        )
       }
       </Droppable>
    )
}

export default Column

src/Components/Task
import React from 'react';
import {Draggable} from 'react-beautiful-dnd';

function Task(props){
    const { classes, id, index,title } = props;
    let style = {
    backgroundColor:"red",

   }

    return (
       <Draggable draggableId ={id} index={index} type="TASK">

         {(provided) => (

{title}

        )}

       </Draggable>
    )
}

export default Task

Comment: Dear bro @William, For such a case like your question. it is better to put a reproduction of your project on GitHub or GitLab and leave its link here, someone like me checks out the project and finds the bug. Literally, I ask you this.
Comment: @William can you provide some fiddle for this?
Comment: Okay, thanks for the polite response. I'll do that after work.
Comment: Looks like someone below created a codesandbox
Answer: If you are getting this error on React 18
Unable to find draggable with id:

Try removing StrictMode
Comment: Seconded. This works for me, but I'd like to keep strict mode-- what's happening here?
Comment: there is drop-in replacement that fixed this issue here:
https://github.com/hello-pangea/dnd
Comment: why the strict mode is affect this behavior ?
Comment: Rather than replace the whole library or turn off Strict Mode, try using this solution: https://github.com/atlassian/react-beautiful-dnd/issues/2350#issuecomment-1318179729
Comment: @MarcinHubert I believe that fork is a good enough solution that it warrants it's own answer. I would upvote it if it were.
Comment: this code helped me to solve a problem:
https://github.com/atlassian/react-beautiful-dnd/issues/2399#issuecomment-1175638194
Comment: Wow. This solved my problem as well. I am on Next 13
Comment: I'm using `hello-pangea/dnd` and the problem still happens, don't know if it's my faut. Edit: was my fault, I forgot to add the `key` to my `Draggable` , now the everything works fine.
Answer: There are a few issues with your code:

Error Unable to find draggable with id: X

In the Column component you used index as a key for the tasks. I think this is what causes this error.
Using the task id as key, in Column, makes this error go away.

reorder has some issues:

it removes a task when dropped in the same column
raises an error when a task is dropped outside the columns

I had a bit of fun with you code and tried another way to reorder. This way of reordering might come in handy if you ever add a more columns - there is still room for improvements.
Hope it helps!
Comment: Using `ID` that is the same for `draggableId` `prop` instead of `index` for `key` prop solved my problem
Comment: @SyedAqeel Thanks, man!! sometimes comments are better than answers.
Comment: I had `key` as `index` instead of `id` - thank you ;-)
Answer: Not for this case, but
For every one - check provided.draggableProps not provided.dropableProps
 <Draggable draggableId ={id} index={index} type="TASK">

         {(provided) => (

{title}

        )}
</Draggable>

RBD try find node by provided.draggableProps. Missing this props got error: Unable to find draggable with id: X
Answer: I had a similar issue, I was mapping through multiple draggable and had missed the key prop,
Adding the key to Draggable fixed the issue for me
{tasks.map((t, index) => (
  <Draggable
    draggableId={t._id}
    index={index}
    key={t._id} >
     ....
  </Draggable>
}

Comment: Thanks! I added `key={task.id}` for my `Draggable` wrapper and also added `key={column.id}` to my `Droppable` wrapper and it works out of the box!
Comment: Works like a charm. Thank you. Just pass your id instead of the index and the issue will be fixed
Comment: @AgostinhoNeto solution works for me ,the issue was with droppable key , Thanks
Answer: For Error:

Unable to find draggable with id: X

Remove Strict mode in React js.
If you are using Next.js you can find the strict mode in next.config.js file

For Error:

Invariant failed: Draggable[id: 1]: Unable to find drag handle do the following

{process.browser && (

          <DragDropContext onDragEnd={onDragEnd}>
                     //Your code with droppable and draggable
           </DragDropContext>

)}

Related issue
Comment: It worked but now I am getting hydration error in Next.js
Answer: Removing <React.StrictMode> fixed it for me.
Answer: I ran into the same issue however the following steps helps me
Step 1:
draggableId should be string, not an integer

as per https://github.com/atlassian/react-beautiful-dnd/issues/1512
Step 2:
if you are coming from EggHead tutorial, this might have missed.
Try to add a key property as mentioned in the top answer
<Draggable key={item.id} draggableId={item.id.toString()} index={index} >

Answer: If you still getting this issue, there was a simple solution for you. Just remove <React.StrictMode> from the index.js.
Answer: The library is not being maintained any longer. I switch to the fork:
https://github.com/hello-pangea/dnd
And all issues were resolved.
Comment: Thank you so much for this. Was tearing my hair out trying to get the unmaintained version to work!
Comment: All the tutorials worked perfectly in a sandbox but failed miserably on my local machine. Your tip saved me. Thanks a lot for this
Answer: If you are looking for a solution

Without removing Strict Mode
Without replacing the whole react-beautiful-dnd library

1. Create this StrictModeDroppable component in your project:
import { useEffect, useState } from "react";
import { Droppable, DroppableProps } from "react-beautiful-dnd";

export const StrictModeDroppable = ({ children, ...props }: DroppableProps) => {
  const [enabled, setEnabled] = useState(false);

  useEffect(() => {
    const animation = requestAnimationFrame(() => setEnabled(true));

    return () => {
      cancelAnimationFrame(animation);
      setEnabled(false);
    };
  }, []);

  if (!enabled) {
    return null;
  }

  return <Droppable {...props}>{children}</Droppable>;
};

2. Then replace <Droppable> components in your project with <StrictModeDroppable>.
It should work!

Source: https://github.com/atlassian/react-beautiful-dnd/issues/2399#issuecomment-1175638194
Comment: This should be the top answer here.
Answer: Try converting the integer value to a string. It'll solve the issue as it solved mine
{tasks.map((t, index) => (
  <Draggable
    draggableId={t._id.toString()}
    index={index}
    key={t._id} >
     ....
  </Draggable>
}

Answer:
There is a YouTube lesson on react-beautiful-dnd. He posted his
lesson progress in the Code Sandbox enter link description here
You can open it and make sure. But I have on "react": "^18.1.0" does
not work and gives an error

Unable to find draggable with id:X

And on older versions of react everything also works without
errors.Try for example another version of react"^17.0.2"ю It worked
for me

Also remember, when installing the react-beautiful-dnd library, were there any dependency conflicts? Maybe you have not established all the connections and because of this it does not work correctly. In any case, as a test, I suggest downloading the code from the lesson and checking in my project whether it works or not. If it works, it means an error in the code, if not, then react-beautiful-dvd does not work correctly
Answer: I hope this will help someone. If you are experiencing this even your code is correct. Please check your react version. In react version 18.0, dnd will show unable to find draggable with id warning. Current solution to downgrade to 17 and it works flawlessly. I searched for the solution like remove strict mode, using dynamic import and other things but currently it's related to react 18.
Answer: It works with react-beautiful-dnd and React 18 in StrictMode.
https://github.com/atlassian/react-beautiful-dnd/issues/2399#issuecomment-1175638194
Answer: Post it here, since this is the top link the Google for the same error.
It might be the case, that you do not render an element with the provided.dragHandleProps

      {someCondition && (

               <DragIndicatorIcon {...provided.dragHandleProps}/>

      )}

In this case move {...provided.dragHandleProps} outside the condition

      {someCondition && (

               <DragIndicatorIcon {...provided.dragHandleProps}/>

      )}

Found this solution here
Answer: Resolved this issue by converting draggableId into string
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: For those who are experiencing the same problem with the @hello-pangea/dnd library,
converting the id to string worked for me.
<Draggable key={ticket.id} draggableId={ticket.id.toString()} index={index}>

Answer: Make sure you have provided - draggableId, key and ref
Answer: To mirror @MarcinHubert's comment in one of the answers, Atlassian no longer maintains this repo, and there is a drop-in replacement that is being actively maintained that fixes this problem: https://github.com/hello-pangea/dnd
Comment: In my case, even using this lib, the error was present, but it was my fault. I basically forgot to add `key` attribute to the `Droppable`, only the `Draggable` had the key, now both have, and everything works fine.
Answer: I actually faced the same issue but the above solution worked for me. I was using Next.js 14 and typescript:

"use client";

import { useEffect, useState } from "react";
import { Droppable, DroppableProps } from "react-beautiful-dnd";

export const StrictModeDroppable = ({ children, ...props }: DroppableProps) => {
  const [enabled, setEnabled] = useState(false);

  useEffect(() => {
    const animation = requestAnimationFrame(() => setEnabled(true));

    return () => {
      cancelAnimationFrame(animation);
      setEnabled(false);
    };
  }, []);

  if (!enabled) {
    return null;
  }

  return <Droppable {...props}>{children}</Droppable>;
};

<DragDropContext onDragEnd={handleDragEnd}>
      <StrictModeDroppable droppableId="items">
        {(provided) => (

            {stateItems.map((item, index) => (
              <ListItem key={index} id={index.toString()} index={index}>
                {item}
              </ListItem>
            ))}
            {provided.placeholder}

        )}
      </StrictModeDroppable>
    </DragDropContext>


Format of result from Round

Question:
Possible Duplicate:
how to display number in a certain format in php

echo round(10.1232, 2); // return 10.12

this working ok, but:
echo round(10, 2); // return 10

i would like receive 10.00. How can i make it?
Comment: `10` (as a float) and `10.00` (as a float) are the same number *rendered* as different *string representations*; trailing zeros in the fraction are of no consequence to the *value* of a number.
Answer: Use number_format()
echo number_format(10, 2, '.', '');

Answer: PHP also has printf:
printf( "%.2f\n", round(10.1232, 2) );
printf( "%.2f\n", round(10, 2) );

In fact, the rounding is handled by printf anyway...  So this should be the same:
printf( "%.2f\n", 10.1232 );
printf( "%.2f\n", 10 );

Comment: If you use printf, you wouldn't need to also use round. Just `printf('%.2f', 10.1232);` is fine.

Format of result from Round


How to Add Label to docker image using build job's parameter which is passed while running job manually

Question: I am trying to add a label to docker image during build time. I don't want to add static label like version=2.0.
I have to use build job parameter to add label.
Suppose VERSION is the parameter passed during build time. I want to use it in label as below:
version=${VERSION}
WHAT should I do?
VALUE OF VERSION comes from jenkins job and provided by user while he trigger the build job.
Answer: You could use the ARG instruction (doc). You can see a similar use case to yours in the doc where the Dockerfile is defined as:
FROM ubuntu
ARG CONT_IMG_VER
ENV CONT_IMG_VER=${CONT_IMG_VER}
RUN echo $CONT_IMG_VER

The variable ${CONT_IMG_VER} is then given during build time:
docker build --build-arg CONT_IMG_VER=v2.0.1 .


syslog-ng not flushing the pipe to external program

Question: I have written a python script that takes log entries from syslog-ng and writes them to MongoDB (I couldn't do it with afmongodb driver because I need to do some special processing).
This is how it looks like in syslog-ng.conf:
destination d_mongodb_events {
  program("/home/test/syslog_piper.py"
    template("$UNIXTIME|$PRIORITY|$FACILITY|$SOURCEIP|$SEQNUM|$PID|$PROGRAM|$MSGONLY\n")
    flags(no_multi_line)
    flush_lines(1)
    flush_timeout(1000)
  );
};

And this is the script: (with logic removed)
import sys
try:
    lines = sys.stdin.readlines()
    for line in lines:
        # process `line` and save to DB

except Exception, e:
    f = open('/tmp/error.txt','ab')
    f.write(e)
    f.close()
    exit(0)

Script works - that is, if I run it from the command line it waits for input and inserts the lines in DB as soon as I press Ctrl+D - and exits.
With syslog-ng it is different. The entries are passed to the script, but only after I stop syslog-ng daemon. Also, while syslog-ng is running, I see my script running too (in the process list). I have tried setting flush_lines() and flush_timeout() (see configuration above) but I can't make syslog-ng flush its output.
My guess is that there is something wrong with the way I handle pipelines, but I can't figure it out. Can anyone spot the problem?
UPDATE: if I send 1000 messages some of them get pushed through, so I guess there is some buffering going on. Anyone knows which setting to tune?
SOLUTION: It looks like Python buffers a lot of its input/output. This is from the man pages:
 -u       Force  stdin,  stdout  and  stderr to be totally unbuffered.  On
          systems where it matters, also put stdin, stdout and  stderr  in
          binary  mode.   Note  that there is internal buffering in xread-
          lines(), readlines() and file-object  iterators  ("for  line  in
          sys.stdin")  which  is  not  influenced by this option.  To work
          around this, you will want to use "sys.stdin.readline()"  inside
          a "while 1:" loop.

So basically I had to change the program to use sys.stdin.readline(). Huge thanks to Janne.
Answer: I have not hooked any Python scripts to syslog-ng, but with Perl scripts I have to turn off the output buffering before they work in real-time. In Perl-speak, that is $|=1.
I am not much a Python guy, but I guess running your Python script with -u or setting up variable PYTHONUNBUFFERED might help.
Comment: Janne, big **THANK YOU** for this one! :) Actually `-u` didn't help, but reading manual pages (`man python`) revealed this gem: *-u: ... Note  that there is internal buffering in xreadlines(), readlines() and file-object  iterators  ("for  line  in sys.stdin")  which  is  not  influenced by this option.  To work around this, you will want to use "sys.stdin.readline()" inside a "while 1:" loop.* Solved. :)


Personalize Shiny interface

Question: how can i personalize my shiny application, by default, siderPanel is placed in the topleft, mainPanel in the centre anf if i had somme summary it's in the bottom...
In my application, siderpanel, mainPanel and verbatimTextOutput are one above the other, can you help me to replace it ?
<code>shinyUI(fluidPage(
  tags$head(

    tags$link(rel = "stylesheet", type = "text/css", href = "bootstrap.css"),
    tags$style(HTML("
      @import url('//fonts.googleapis.com/css?family=Lobster|Cabin:400,700');
    "))
  ),

  headerPanel(h1("Représentation de Weibull",
                 style = "font-family: 'Lobster', cursive;
        font-weight: 500; line-height: 1.1;
        color: #00BFFF;")),
  fluidPage(
    fluidRow(
    column(3,
    sidebarPanel(
      wellPanel(
        fileInput("file1", "Choisir votre 1er fichier tabulé"),

        checkboxInput("fit_weibull", label = "Ajuster une loi de Weibull", value = FALSE),

        conditionalPanel(
          condition = "input.fit_weibull == true",
          uiOutput("slider"))
      ),
      wellPanel(
        fileInput("file2", "Choisir votre 2e fichier tabulé"),
        checkboxInput("fit_weibull2", label = "Ajuster une loi de Weibull", value = FALSE),
                conditionalPanel(
                  condition = "input.fit_weibull2 == true",
                  uiOutput("slider2"))
      )
    )),
    column(9,
    mainPanel(
      list(tags$head(tags$style("body {background-color: #F8F8FF; }"))),
      plotOutput("plot.weibull"),
      conditionalPanel(
        condition = "input.fit_weibull == true",
        verbatimTextOutput("km_lim"),
        verbatimTextOutput("coefficients")

      ),
      conditionalPanel(
        condition = "input.fit_weibull2 == true",
        verbatimTextOutput("km_lim2"),
        verbatimTextOutput("coefficients2")

      )
    ))

  )
)
</code>
Comment: Please I need help, i got something but is's very ugly on the screen !
Comment: problem solved ! i used "fixedRow" !
Comment: you should answer your own question so someone else might find it useful if they find your post
Answer: Your question is solved with CSS, you can change the properties of each element. Remember the id of each panel and with this, you can fix whatever you want. Nevertheless this is a hard working task, I believe that is better to personalize with a package like shinythemes or shinydashboard.
This packages help you to customize your web application but if you want to move the position of one of this elements, you will have to change the CSS properties.
For example:
<code>             float: right
             width: 70%
             height:10%
             margin: 0 0 0 0 (top-right-bottom-left)
</code>

Personalize Shiny interface


Drupal 7 ckeditor relative path setup issue

Question: We are developing a site using drupal 7
So we created drupal site with name of myapp, so the url is http://localhost/myapp
Also another developer is working for same site in his development machine with the name of myapp2
so its http://localhost/myapp2
I have installed ckeditor for rich content and configured relative path for inserting images.
When I insert an image in myapp site the relative path comes like 'myapp/sites/all/files/images/img1.jpg' instead of 'sites/all/files/images/img1.jpg'
hense when I share my database with my other team member uses myapp2 they are not able view the inserted images. their path looks like this 'myapp2/myapp/sites/all/files/images/img1.jpg'
I have used pathologic to setup the two users urls in Text Format setting page
like http://localhost/myapp and http//localhost/myapp2 but not works as expected.
any one help me what else I can do to solve the issue.
Answer: Pathologic will solve your problem, in the configuration of the filter put both http://localhost/myapp & http://localhost/myapp2 and the filter should work everything out
Answer: Finally I tried the solution found by searching various sites.
I put these two path items into text formats setting
http://localhost/myapp/
/myapp/
/

now its working. :)
So, since the other user who have myapp2 in his development system, there would chances for forming images path like myapp2/sites/..., hence we have to add more filter items like below
http://localhost/myapp2/
/myapp2/
/


What should be datatype of mysql table column, for storing notes

Question: I am working on a web application which stores notes created by users. I am confused between whether to store notes as separate files on filesystem, or use database column for saving the text.
If mysql is better solution then what datatype should I use(content can be simple text or html)?
Answer: If you need speed, you can use MySQL. You need to use either BLOB or if it is just text, use TEXT as the datatype. Use a good DB engine (MySQL, SQLite, etc). Then, for maximum performance, use memcached to cache content.
Keep in mind a couple things:

MySQL has a query cache. If you are issuing the same queries repeatedly, you can gain a lot of performance without adding a caching layer.
MySQL is really fast anyway. Have you load-tested to demonstrate it is not fast enough?

Another thing is, it is hard to search on flat files. If you use MySQL, not only it is faster, but also it is easier for you to search.
Answer: What you could do is creating a mysql table with these fields :
ID (INT), CreationDate (DATETIME), Content (TEXT)
If you want to store simple text or html, it all depends on your needs (Is the user able to put a special font on his note ? A special color ?), but don't forget to escape the text correctly.
From then, you can easily retrieve an user's note by it's ID, and also easily sort them by creation/modification date. Using an SQL database gives you a large flexibility.


Condição IF - Boa prática de utilização

Question: Durante uma codificação tive que realizar o desenvolvimento da seguinte maneira:
IF (Condicao1 = True)
  IF (Condicao2 = True)
    IF (Condicao3 = True)
       Imprime(Mensagem);

A maneira que realizei é considerado a melhor prática?
Existiria uma maneira melhor de realizar isto?
Comment: Conhece o operador lógico *and*? `If (condicao1 and condicao2 and condicao3) Imprime(Mensagem)`
Comment: Não sei se usar and é o mais recomendavel. Pode ter casos em que não se deseja validar uma igualdade de todas as condições de forma unica. Acredito que o switch possa ser a solução quando se quer validar condição por condição, ou o OR, dependendo do caso.
Comment: É interessante você especificar qual a linguagem você utiliza. Algumas linguagens tratam operadores relacionais `AND/OR` em modo de `short-circuit` e dessa forma um `AND` pode funcionar como vários `IF` encadeados, mas outras linguagens não usam esse modo.
Comment: Relacionada(ou duplicata):[Por que em algumas situações if's são considerados ruins?](https://pt.stackoverflow.com/questions/4731/por-que-em-algumas-situa%C3%A7%C3%B5es-ifs-s%C3%A3o-considerados-ruins)
Comment: Relacionado: [Qual a diferença entre Switch, Case e If, Else?](https://pt.stackoverflow.com/questions/58192/qual-a-diferen%C3%A7a-entre-switch-case-e-if-else)
Answer: Aparentemente a forma que você estruturou não é a melhor. Digo isso porque você não utiliza chaves nos ifs, o que sugere que sejam apenas para o que está sendo exibido no código, ou seja, validar se as três condições são verdade; sendo, imprime. Assim, a melhor alternativa é utilizar o and , como já dito em um comentário:
IF (Condicao1 && Condicao2 && Condicao3)
    Imprime(Mensagem);

Porém, se existirem comandos a serem executados no caso de algumas delas ser falsa, você estruturou da maneira correta.
IF (Condicao1 = True) {
  IF (Condicao2 = True){
    IF (Condicao3 = True){
       Imprime(Mensagem);
    } else {
      // codigo
    }
  } else {
    //codigo
  }
} else {
  //código
}

Caso não precise de algum dos "senões", use a primeira forma.

Condição IF - Boa prática de utilização


Rewrite matrix equation as a quadratic programming problem

Question: Given real-matrix $X_{n\times p}$ how can the problem of minimizing $Tr(X^TA_{n\times n}X)$ under the constraint $Tr(X^TC)=\phi$ be posed as a standard convex quadratic program given by the form:
minimize $(1/2)x^TAx + q^Tx$ under the constraint $Mx = b$.
This is how far I got: $Tr(X^TAX)=\sum_{i=1}^nX_{i\cdot}AX_{i\cdot}^{T} =VDV^T$
where D is a block diagonal matrix with A's on the diagonal repeated $p$ times and $V$ is $vec(X)$, that is has columns of $V$ stacked on to it as a vector.
Can you verify if this is correct? Also does $V$ have rows stacked into it or columns stacked into it? What would $M,b,q,x$ be in the quadratic program formulation?
Answer: You are right. Usually $\operatorname{vec}$ stacks columns.
Since $A$ appears twice, I will use $Q$ for the Hessian of the quadratic:

$x = \operatorname{vec}(X)$,
$Q = I \otimes A$, where $I$ is the identity and $\otimes$ the Kronecker product,
$q = 0$,
$M = \operatorname{vec}(C)$,
$b = \phi$.
Answer: You can directly solve your problem. Using Lagrange's conditions, we obtain the following linear system
$BX+\lambda C=0,Tr(C^TX)=\phi$, where $B=A+A^T$ and $\lambda\in \mathbb{R}$ is unknown.
If $B$ is invertible and $Tr(C^TB^{-1}C)\not=0$, then $X=-\lambda B^{-1} C$ and consequently $\lambda=-\phi/Tr(C^TB^{-1}C)$. Finally $X=\dfrac{\phi}{Tr(C^TB^{-1}C)}B^{-1}C$. If $B$ is not invertible, then use its pseudo inverse.
EDIT. $f(X)=X^TAX=\dfrac{1}{2}Tr(X^TBX)$. If $B\geq 0$, then $f$ admits a minimum, otherwise the minimum does not necessarily exist. Moreover, if $B$ is not invertible, then $f(X_0)=0$ for $X_0\in \ker(B)$ and $Tr(X_0^TC)=\phi$; in this case, the minimum is $0$. Finally we may assume that $B>0$. Under this hypothesis, the condition $Tr(C^TB^{-1}C)\not= 0$ is equivalent to $C\not=0$.
The value of the minimum is $\dfrac{\phi^2}{2Tr(C^TB^{-1}C)}$ when $B$ is invertible and $0$ otherwise.


Prove that $(3+5\sqrt{2})^m=(5+3 \sqrt{2})^n$ has no positive integer solutions?

Question: Is my proof ok? I set $b=3+5 \sqrt{2}$, so that we have $b^m=(b+2-3 \sqrt{2})^n$  , or $b^m=(b+\sqrt2(\sqrt2- 3))^n$. Since $RHS<LHS$, $n>m$ .  However, from what we know about binomial expansion, we will have a $b^n$ on the $RHS$ which will not cancel out with anything since it is the highest power, so we will never be able to reduce the $RHS$ to just $b^m$ . I don't really like my proof, is there a better one? And does this have a solution for rational powers, and how can you prove that it does/doesn't? Thanks.
Answer: If there is a solution, there is one where the $\sqrt{2}$are replaced by $-\sqrt{2}$. Multiply.
We get
$$(3+5\sqrt{2})^m(3-5\sqrt{2})^m=(5+3\sqrt{2})^n(5-3\sqrt{2})^n.$$
That gives $(-41)^m=7^n$, impossible unless $m=n=0$.
Can't have non-zero rationals either. Just raise to the appropriate integer power and use basically the same argument.
Comment: There is a fancier way of seeing it. But imagine expanding either one using Binomial Theorem. There will be on each side an integer part and a $\sqrt{2}$ part. They must match, since $\sqrt{2}$ is irrational. So if on each side you replace the $\sqrt{2}$ part by changing sign, the sides are still equal, but you have the expansions of the conjugates.
Comment: Thanks I understood the multiplication, but how do you know that you can replace the $\sqrt2$ with a -$\sqrt2$?
Comment: Ok thanks. I don't actually know the binomial theorem (haha I know I used it in my proof but I just know the first part) but I can understand what you're saying.
Answer: I don't understand your statement about not cancelling.
Hint: consider the function $f(a + b \sqrt{2}) = (a + b \sqrt{2})(a - b \sqrt{2}) = a^2 - 2 b^2$, and note that $f(xy) = f(x) f(y)$.
Comment: My statement about not canceling is saying that if we take the RHS to the power $n$, we will necessarily have a $b^n$ on the RHS and we don't have a $b^n$ present on the LHS, so the RHS can never equal the RHS.
Comment: But other terms might cancel the $b^n$.
Comment: But $b^n$ would be the highest power of $b$, so there is only one term with $b^n$
Comment: For example, $(1+2 \sqrt{2})^m = (9+4 \sqrt{2})^n$ does have solutions (namely $m=2n$).  How does your argument fail in that case?
Comment: You're right, I looked at this as if $b$ is a variable, and there is no other $b^n$ which could cancel it, but $b$ is actually a constant and it can be canceled out by the other constants. Thanks.


Identityserver from duende behind caddy has http in the openid config

Question: I am running an identity server from duende behind a caddy reverse proxy and both are running in a docer container. I also run a blazor server app in another container where I want to authenticate. Locally this is working fine, but when I run them behind the proxy, the .well-known/openid-configuration delivers http:// endpoints and therefore the blazor app can not authenticate, because it does not allow authentication through http. The http is between caddy and the identity server. As this is running on a machine and is not crossing the evil net, I thought that might be ok. I think what I need to do is, generate a certificate for the identityserver and proxy via https instead of http. But I also do not want to generate certs by hand all the time or keep an eye out for that. A UseHttpsRedirect() in the startup made my service unavailable for caddy and just simply running it on 443 without a certificate also broke the call between caddy and the indentity server. I also found a tip where I could set the IssuerUri to https in the options, but this does not affect the other endpoints and therefore I still can not authenticate, because in the openid config there are still http endpoints (except the issuer)
Does anybody have an idea how I could do that and not create the certs by hand?
caddyfile:
identity.fading-flame.com {
    reverse_proxy http://identity-server-prod
}

Startup for IS
services.AddIdentityServer(options =>
                {
                    options.IssuerUri = $"https://{Environment.GetEnvironmentVariable("IDENTITY_BASE_URI")}";
                    options.EmitStaticAudienceClaim = true;
                })

Or maybe something like that for caddy?
Identityserver4 openid-configuration omits host port running nginx reverse proxy
Answer: Ok, I found a similar thread on GH that was with nginx, but the answer is still working with caddy.
https://github.com/IdentityServer/IdentityServer4/issues/324#issuecomment-324133883
Basically, before the identity server middleware, I have this one:
    app.Use((context, next) =>
    {
        context.Request.Scheme = "https";
        return next();
    });

    app.UseIdentityServer();

Then the openid config returns https endpoints and everything is fine. What was still missing for me was the same thing for the blazor server app, because I use the auth framework there aswell and the redirect url is http because of the same reason with caddy. So in the blazor app this fixed the callback from Identity server, pretty sure it has to be before authentication, but I did not test it out:
    app.Use((context, next) =>
    {
        context.Request.Scheme = "https";
        return next();
    });

    app.UseAuthentication();

Hope this helps someone some day ;)
Comment: I solved it. PathBase was messing up with the value, but setting the scheme to `https` works fine. Thanks
Comment: I've tried, in local it's showing https in the discovery document. However when deployed in AWS Fargate cluster it still shows http. Do you know what could be messing with it? Do you use any additional forwarded headers?
Comment: I am running it on a private server, dont know if aws does something different on aws, but that would be weird. The order matters, though and if you have an `if (development)` somewhere that might be switched on a production build. Maybe run it locally in release and check?


Setting number from xml in java

Question: package com.android.SMStest;

import android.app.Activity;

import android.content.Context;

import android.os.Bundle;
import android.telephony.SmsManager;

import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.telephony.TelephonyManager;
import android.widget.TextView;

public class SMStestActivity extends Activity {
private TextView txtPhoneNo;
private EditText txtMessage;
private Button btnSendSMS;
private EditText smsamount;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    smsamount = (EditText) findViewById(R.id.smsamount);
    btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
    txtMessage = (EditText) findViewById(R.id.txtMessage);
    txtPhoneNo = (TextView) findViewById(R.id.txtPhoneNo);
    TextView textgetLine1Number = (TextView) findViewById(R.id.txtPhoneNo);
    // retrieve a reference to an instance of TelephonyManager
    final TelephonyManager phonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    textgetLine1Number.setText(getLine1Number());

    btnSendSMS.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            String phoneNo = phonyManager.getLine1Number().toString();
            txtPhoneNo.setText(phoneNo);
            String message = txtMessage.getText().toString();
            if (phoneNo.length() > 0 && message.length() > 0)
                sendSMS(phoneNo, message);
            else
                Toast.makeText(getBaseContext(),
                        "Please enter both phone number and message.",
                        Toast.LENGTH_SHORT).show();
        }
    });
}

// ---sends an SMS message to another device---
private void sendSMS(String phoneNumber, String message) {
    int i;
    SmsManager sms = SmsManager.getDefault();
    for (i = 0; i < 10; i++) {
        sms.sendTextMessage(phoneNumber, null, message, null, null);
    }

}

public String getLine1Number() {
    return ((TelephonyManager) getSystemService(TELEPHONY_SERVICE))
            .getLine1Number();
    }
}

I am using this to enable the app I am making to send a certain amount of text messages to the phones MDN to stress test the sms capabilities. The problem I am running into is getting the number the user enters in the UI to actually control how many sms the app sends. The way I have it now will send the set amount of sms set in the programming with for (i = 0; i < 10; i++) {. I need to be able to make this accept what the user enters so they can set their own amount. I have tried it as an integer with private Integer, but the app just force closes when you click the send sms button. I have tried to use getText().toString(), but it keeps telling me to set it as an integer. Any ideas to help an android newbie out?
Answer: You need to parse the string, so just change:
for (i = 0; i < 10; i++) {

to:
int amount = 10; // just making 10 the default if the EditText has an invalid value
try {
    amount = Integer.parseInt(smsamount.getText().toString());
}
catch (NumberFormatException) {}

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

Comment: Thank you so much, worked like a charm :). The only thing I had to do a little different was to change catch (NumberFormatException) {}, to
 catch (NumberFormatException smsamount) {}.

Setting number from xml in java


If $\,A^k=0$ and $AB=BA$, then $\,\det(A+B)=\det B$

Question: Assume that the matrices $A,\: B\in \mathbb{R}^{n\times n}$ satisfy
$$
A^k=0,\,\, \text{for some $\,k\in \mathbb{Z^+}$}\quad\text{and}\quad
AB=BA.
$$
Prove that $$\det(A+B)=\det B.$$
Comment: You made no attempt yourself? Upvoters, why?
Comment: @Lost1 my upvote is "+1, interesting question" rather than "+1, you showed your attempt."
Comment: What does the star in $\mathbb N^*$ mean? if $A^k=0$ for any $k$ then clearly $A=A^1=0$ and then $A+B=B$...
Comment: A clearer formulation would be $A^{k} = 0$ for *some* positive integer $k$, that is, $A$ is nilpotent.
Comment: @tour $k$ is fixed
Comment: @tour I don't follow: how $\;A^k=0\implies A=A^1=0\;$?? For example, for $\;k=3\;$ , say.
Answer: Here's an alternative to the (admittedly excellent) answer by Andreas:
Since $A$ and $B$ commute, they are simulaneously triangularizable. However, since $A$ is nilpotent, for any basis in which $A$ is triangular, the diagonal entries of $A$ will in fact be $0$. Thus in the chosen basis, the diagonal entries of $A + B$ and $B$ agree, so the determinants (being the product of the diagonal entries in this basis) are equal.
Comment: You don't need basis. If $A$ and $B$ are simultaneously triangularizable, i.e., $A = S T_1 S^{-1}$ and $B = S T_2 S^{-1}$, then$$\det(A+B) = \det(S(T_1+T_2)S^{-1}) = \det(S)\det(T_1+T_2)\det(S^{-1}) = \det(S)\det(T_2)\det(S^{-1}) = \det B.$$
Comment: Thanks a lot! In fact, in my answer I was going through the details of simultaneous triangularizability, and I was also trying to avoid the use of a basis unless absolutely necessary, as I was taught ages ago.
Comment: @AndreasCaranti: I agree it's nicer to do things without bases, but this line of reasoning was just so short that it seemed appropriate
Comment: @VedranŠego: Yes, one can conjugate rather than explicitly reason with the basis (although conceptually these are the same). My main focus was on your next to last equality, which is (in my opinion) the core of the argument. +1 for the nice short line though
Answer: We shall consider the following two cases:
Case I: $\det B=0$. Then, there exists a vector $u\ne 0$, such that $Bu=0$, and as $AB=BA$, then
$$
(A+B)^ku=\sum_{i=0}^k\binom{k}{i}A^{k-i}B^ju=A^ku+\sum_{i=1}^k\binom{k}{i}A^{k-i}B^iu=0,
$$
and hence $A+B$ is not invertible and thus $\det(A+B)=\det B=0$.
Case II: $\det B\ne 0$. Then it suffices to show that $\det (I+B^{-1}A)=\det I$. Note that $A$ commutes with $B^{-1}$ as well and $(B^{-1}A)^k=(B^{-1})^kA^k=0$. So it suffices to show that if $C^k=0$, then $\det (I+C)=\det I$. Let $F=I+C$. We know that $$(F-I)^k=C^k=0.$$ This means that ALL the eigenvalues of $F$ are equal to $1$, as $F$ is annihilated by the polynomial $p(x)=(x-1)^k$, and hence its determinant (product of its eigenvalues) is equal to $1$, i.e., $$\det (I+C)=\det F=1.$$
Comment: The last part might be formulated slightly simpler: if $C^k=0$ then the eigenvalues of $C$ are all zero, then the eigenvalues of $I+C$ are all one, then $det(I+C)=1=det(I)$
Comment: @leonbloy: Indeed.
Answer: Let $U$ be the generalized eigenspace of $B$ with respect to a particular eigenvalue $\lambda$. Since $A B = B A$, we have $A U \subseteq U$.
(If $v \in U$, so that $(B - \lambda I)^{s} v = 0$ for some $s$ and vector $v$, then $(B - \lambda I)^{s} A v = A (B - \lambda I)^{s} v = 0$, that is, $A v \in U$.)
Now on $U$ we will have $B = \lambda I + N$, where $N$ is nilpotent, and $I$ is the identity on $U$. From $A B = BA$ we get $A N = N A$, so $N+A$ is nilpotent. (If $A^{t} = N^{t} = 0$, then $(A+N)^{2t-1} = 0$.)
Now on $U$ we have $A + B = \lambda I + (A + N)$. So we see that $U$ is also the generalized eigenspace of $A + B$ with respect to the eigenvalue $\lambda$. (This is because $(A + B - \lambda I)^{2t-1} = (A + N)^{2t-1} = 0$ for the same $t$ as above. Also, we are actually showing that the $\lambda$-generalized eigenspace of $B$ is contained in the $\lambda$-generalized eigenspace of $A+B$, but the situation is symmetric, as $B = (A+B) - A$, with $A (A+B) = (A+B) A$.)
So $B$ and $A + B$ have the same eigenvalues with the same multiplicities, hence they have the same determinant.
This actually shows that they have the same characteristic polynomial. But they need not have the same minimal polynomial, as the example $A = \begin{bmatrix}0&1\\0&0\end{bmatrix}$, $B = \begin{bmatrix}1&0\\0&1\end{bmatrix}$ shows.


How do I fix a broken tar file?

Question: I have a 46GB tar file containing an .img of an old partition. Unfortunately, it produces a 0-byte file when un-tar'ed.
The tar file was produced on linux, I'm on windows now. I have tried WinRAR, and tar (from unixutils).
Note: It was actually originally a tar.bz2, but apparantly bzip2 defaults to deleting the original archive when decompressing, so now all I have is the tar file.
Anyway, what can I do about it?
Answer: Can you untar it on Linux? If you don't have a convenient Linux machine, perhaps you could set up one on a virtual machine to try. I'm sort of assuming this backup is worth the effort.
Some older tools don't necessarily work properly with files greater than 4 GB in size. You may be running into this problem; it might be worth trying recent tools to see whether that helps.
Answer:
Try to untar it on filesystem which can support size > 4 GB.
Run 'file  x.tar' to see if it is acutally tarred or tar bzipped or something else.
You wrote bzip2 deleted original file. That means you should have .tar.bz2 and not .tar. Am I missing something here?
Uncompress on latest Linux, I have faced problems when files dont get uncompressed on windows but work fine on linux.
Comment: 1: This was on NTFS. 3: **decompressing** the `tar.bz2` with bzip2 left me with only a `.tar`. I will try 2 and 4 with a livecd tonight.

How do I fix a broken tar file?


Why is getting three personal fouls in the first half of an NCAA basketball game a big deal

Question: I know five personal fouls calls for an ejection, but I cannot find anywhere why three fouls before halftime is a big deal.
Thank you for help
Comment: Who says three fouls before half-time *is* a big deal? I feel like we're missing some context here.
Comment: It comes down to math, I believe. By reaching three personal fouls before halftime, you are already 60% of the way to the limit. This suggests you will not be able to play as aggressively in the second half of the game or else be at risk of ejection.
Answer: "Big Deal" here is subjective. There is no rule in the rule book that says "If a player accumulates three fouls before halftime, panic"
From the coach's perspective, he would be at least slightly concerned should this situation arise (his player is 3/5 of the way to fouling out, with over 1/2 the game to play); how concerned would be dependent on his strategy, his plans to adjust his strategy for the second half, how effective that player has been during the game so far, and dozens of other non-measurable reasons