input declaro não é acessivel no javascrit e php

Question: Criei um formulário e estou tentando pegar os dados de um radio button, e de um input, porém não estou conseguindo acessar eles via POST no php nem no javascript no qual estou utilizando uma função para desabilitar os campos
Html
<form name="cdUsuario" class="cadastroUsuario" type="submit">

                  <input id="nome" name="nome" value="<?php echo $result['nm_nome'] ?>" type="text" disabled>

                  Primeiro Nome

                  <input id="sobrenome" required name="sobrenome" value="<?php echo $result['nm_sobrenome'] ?>" type="text"  disabled="disabled">
                  Sobrenome

                  <input id="email"  required name="email_altera" type="email" class="validate" value="<?php echo $result['nm_email'] ?>" disabled="disabled">
                  E-mail

                    <input required name="Cd_sexo" value="Masculino" type="radio" id="rd_masculino" <?php echo $Result_sexoM ?> disabled="disabled"/>
                    Masculino
                    <input required name="Cd_sexo" type="radio" value="Feminino" id="rd_feminino" <?php echo $Result_sexoF ?> disabled="disabled"/>
                    Feminino

                  <input id="telefone"  name="telefone" type="text" value="<?php echo $result['cd_telefone_fixo'] ?>" maxlength="11" disabled="disabled">

                  Telefone

                  <input id="celular" required name="celular" type="text" value="<?php echo $result['cd_telefone_movel'] ?>" maxlength="11"disabled="disabled">
                  Telefone Celular

                  <input id="senha" required name="senhaEdita" type="password" value="<?php echo $result['cd_senha'] ?>" class="validate" disabled="disabled">
                  Senha de Acesso

                        <input type="checkbox" id="perfilprofissional" name="boxProfissional"
                         onclick="Mudarestado('formProfissional')">
                        Perfil Profissional

               <select class = "browser-default">
                    <option value = ""  disabled selected>Área de Atuação</option>
                  <option value = "1">Informática</option>
                  <option value = "2">Aparelhos Eletrônicos e Eletrodomésticos</option>
                  <option value = "3">Aulas</option>
                  <option value = "4">Autos</option>
                  <option value = "5">Consultoria</option>
                  <option value = "6">Eventos</option>
                  <option value = "7">Moda e Beleza</option>
                  <option value = "8">Reformas e Serviços Gerais</option>
                  <option value = "9">Saúde</option>
                  <option value = "10">Serviços Domésticos</option>
                  <option value = "11">Comércio</option>
                  <option value = "12">Esportes e Lazer</option>
               </select>

                  <input id="email" type="email"  name="Ped_email">
                  Formação

            <textarea id="textarea2" class="materialize-textarea" data-length="120"></textarea>
            Observações

                    <button  type="submit" class="btn blue center-align"  name="Salvar" id="SalvarDados" >Salvar

                    </button>

                    <button class="btn blue center-align"  name="Editar" id="EditarDados">Editar Dados

                    </button>

                    <font color="red"
<h7 class="emailCadastrado"></h7>

                <font color="green"
<h7 class="sucessoCadastro"></h7>

        </form>

javascript

php
include_once("usuario_class.php");
$nome=$_POST['nome'];
$sobrenome=$_POST['sobrenome'];
$telefone_fixo=$_POST['telefone'];
$telefone_movel=$_POST['celular'];
$email=$_POST['email_altera'];
$sexo=$_POST['Cd_sexo'];
$senha=$_POST['senha'];

a mensagem de retorno do php é a seguinte: Undefined index in Cd_sexo
Comment: Você só postou parte do código. Cadê o resto do código referente a nome, sobrenome etc...?
Comment: atualizei amigo
Comment: Não são postados porque estão disabled. E seu código js pra tirar os disableds tenta referenciar os inputs por um id que não bate com o que está no html
Comment: Erra isso mesmo vlw cara
Answer: Alguns erros no seu código:

<input id="senha" required name="senhaEdita"... correto é com id senhaEdita para que seja coerente com $("#senhaEdita").prop("disabled", false);
 <input id="senhaEdita" required name="senhaEdita"

<input required name="Cd_sexo" faltou id="Cd_sexo" mas como tem masculino e feminino coloque id="Cd_sexoM" e id="Cd_sexoF" respectivamente e no script
        $("#Cd_sexoM").prop("disabled", false);
        $("#Cd_sexoF").prop("disabled", false);

Da forma que sua tag form está é via GET, portanto no PHP tem que ser $_GET e não $_POST
Caso opte por $_POST então a tag form deve ser method="post"
<form name="cdUsuario" class="cadastroUsuario" action="" method="post">

Quando devo usar função GET e quando devo usar função POST

existe algo que não invalida seu código porém no futuro poderá causar algum transtorno:

Telefone Celular

e
Senha de Acesso

os dois valores do for são iguais, acerte isso!

Um exemplo de transtorno poderia ser  .find( "label[for='senha'...
Answer: Ta meio confuso isso ai mas vamos la.
Na sua tag form voce precisa incluir <form method="POST">...</form>
Na sua funçao click do editar tem que tirar
$("#Cd_sexo").prop("disabled", false);

e incluir
$("#rd_masculino").prop("disabled", false);
$("#rd_feminino").prop("disabled", false);

E não se esqueça que radios e checkboxes só existem na variavel $_POST se eles tiverem setados, caso contrario nao existem entao verifique antes assim:
$sexo = isset( $_POST['Cd_sexo'] )? $_POST['Cd_sexo'] : '';


Alterar Lista com uma função no python

Question: Estou desenvolvendo alguns exercícios do livro "Curso Intensivo de Python" mas travei no exercício 8.10 proposto:
EX:
8.10 – Grandes mágicos: Comece com uma cópia de seu programa do
Exercício 8.9. Escreva uma função chamada make_great() que modifique a
lista de mágicos acrescentando a expressão o Grande ao nome de cada
mágico. Chame show_magicians() para ver se a lista foi realmente modificada.
Meu programa do exercicio 8.9 ficou assim:
  print("===================== EX-01 ================")
  magicos = ["Mario", "João", "Maria"]
  '''Exibe uma saudação aos magicos'''
  def nomes_dos_magicos(nome):
      for magico in magicos:
          print("Olá,", magico)

saudacao = nomes_dos_magicos(magicos)

Minha dificuldade esta em armazenar esse novo valor "Grande" antes dos nomes dentro da lista original e não apenas na função
Answer: Para isso, é necessário alterar o valor da váriavel mágicos quando chama a função nomes_dos_magicos.
Aqui uso a função enumerate para poder aceder ao indíce da lista quando estamos a fazer o for loop:
print("===================== EX-01 ================")
magicos = ["Mario", "João", "Maria"]
'''Exibe uma saudação aos magicos'''
def nomes_dos_magicos(nome):
  for i, nome in enumerate(magicos):
      magicos[i] = "O Grande " + nome

nomes_dos_magicos(magicos)
print(magicos)
Comment: Ahh sim,no caso essa alteração para ***"O grande"*** não seria aplicada a lista original definitivamente, e sim, na chamada da função, por exemplo: quando eu chamasse a função de saudação do exercício anterior essa modificação também deve estar la porque a lista original foi modificada
Answer: Você pode usar também a função range:
print("===================== EX-01 ================")
magicos = ["Mario", "João", "Maria"]
'''Exibe uma saudação aos magicos'''
def nomes_dos_magicos():
    for i in range(len(magicos)):
        magicos[i] = "O Grande " + magicos[i]

nomes_dos_magicos()
print(magicos)

Ou, se quiser usar list comprehension, a função fica assim:
def nomes_dos_magicos():
    global magicos
    magicos = ["O Grande " + magico for magico in magicos]

Veja que, na prática, é dispensável definir uma função se você usar list comprehension neste último caso. Mas, como é um exercício, é isso aí.

Alterar Lista com uma função no python


LiveAuthClient broken?

Question: It seems very much that the current version of LiveAuthClient is either broken or something in my setup/configuration is. I obtained LiveSDK version 5.4.3499.620 via Package Manager Console.
I'm developing an ASP.NET application and the problem is that the LiveAuthClient-class seems to not have the necessary members/events for authentication so it's basically unusable.

Notice that InitializeAsync is misspelled aswell.
What's wrong?
UPDATE:
I obtained another version of LiveSDK which is for ASP.NET applications but now I get the exception "Could not find key with id 1" everytime I try either InitializeSessionAsync or ExchangeAuthCodeAsync.
https://github.com/liveservices/LiveSDK-for-Windows/issues/3
I don't think this is a proper way to fix the issue but I don't have other options at the moment.
Answer: I'm a little late to the party, but since I stumbled across this trying to solve what I assume is the same problem (authenticating users with Live), I'll describe how I got it working.
First, the correct NuGet package for an ASP.NET project is LiveSDKServer.
Next, getting user info is a multi-step process:

Send the user to Live so they can authorize your app to access their data (the extent of which is determined by the "scopes" you specify)
Live redirects back to you with an access code
You then request user information using the access code

This is described fairly well in the Live SDK documentation, but I'll include my very simple working example below to put it all together.  Managing tokens, user data, and exceptions is up to you.
<code>public class HomeController : Controller
{
    private const string ClientId = "your client id";
    private const string ClientSecret = "your client secret";
    private const string RedirectUrl = "http://yourdomain.com/home/livecallback";

    [HttpGet]
    public ActionResult Index()
    {
        // This is just a page with a link to home/signin
        return View();
    }

    [HttpGet]
    public RedirectResult SignIn()
    {
        // Send the user over to Live so they can authorize your application.
        // Specify whatever scopes you need.
        var authClient = new LiveAuthClient(ClientId, ClientSecret, RedirectUrl);
        var scopes = new [] { "wl.signin", "wl.basic" };
        var loginUrl = authClient.GetLoginUrl(scopes);
        return Redirect(loginUrl);
    }

    [HttpGet]
    public async Task<ActionResult> LiveCallback(string code)
    {
        // Get an access token using the authorization code
        var authClient = new LiveAuthClient(ClientId, ClientSecret, RedirectUrl);
        var exchangeResult = await authClient.ExchangeAuthCodeAsync(HttpContext);
        if (exchangeResult.Status == LiveConnectSessionStatus.Connected)
        {
            var connectClient = new LiveConnectClient(authClient.Session);
            var connectResult = await connectClient.GetAsync("me");
            if (connectResult != null)
            {
                dynamic me = connectResult.Result;
                ViewBag.Username = me.name; // <-- Access user info
            }
        }

        return View("Index");
    }
}
</code>
Comment: This looks great. I haven't tried this yet, but it looks like exactly what I've been looking for the past 2 days. Thank you Jared.

LiveAuthClient broken?


UPDATE AJAX + LARAVEL

Question: Eu preciso fazer uma update em minha tabela VIEW quando o usuário assistir 90% do vídeo do Vímeo, porém não consigo utilizar essa lógica com o Laravel.
Eu tenho esse seguinte código em PHP normal:

Aí dentro do arquivo ajax.php consigo fazer meu UPDATE. Porém não consigo jogar isso para o Laravel...
Tentei isso mas não funcionou.
View

Rota
$this->post('ajax', 'SchoolController@ajaxView')->name('ajaxview');

Controle
public function ajaxview(Request $request)
 {
     return view('school.salavirtual.ajaxview');
 }

Comment: Coloca aqui o código do seu ajax.php
Comment: Ele está reconhecendo esse código ($.post('{{route('ajaxview')}}') como uma rota do laravel?   faz um teste e tenta mudar para $.post('/ajax').....
Comment: Código do meu ajax.php

<?php

//Quando o vídeo acabar o javascript vai mandar um post pra esse arquivo. Aqui vc recupera com o nome que passou dentro do $.post
$jSON = null;

$tempoDoVideo = $_POST['tempo_video'];

//Nesse arquivo vc faz a atualização no banco e se quiser mandar um retorno, só inicializar a variável $jSON
$jSON['atualizado'] = true; //pode mandar valores de volta pro outro arquivo tbm

if ($jSON){
    echo json_encode($jSON);
}
Answer: você precisa colocar o código do ajax.php no seu controller, mas no lugar de echo vc pode apenas retornar a variavel $jSON. Por padrão o laravel vai converter sua resposta para json.

UPDATE AJAX + LARAVEL


Can I install an app from an other app and then launch its intent immediately when opening it?

Question: Background: I have an app which needs to use an intent from an other app. If this other app is not installed when its intent is needed, I would like to offer it for download and install.
Question: If the downloaded app is opened (by the user) immediately after installing it, I would need it to open the specific intent the first app needs instead of opening it as normal. See image below.
What options do I have available, is there a common pattern for this? Thanks in advance.
Answer:
If the downloaded app is opened (by the user) immediately after installing it, I would need it to open the specific intent the first app needs instead of opening it as normal.

That is not possible, strictly speaking. There is nothing stopping the user from pressing Open, and that will behave as normal -- you cannot change this.
If you are the author of the, um, "Monkey Trampoline" app, you could work out various hacks to recognize that it is being opened after an install from, um, "Animal Olympics", so it can route its logic accordingly (use a custom sticky broadcast, have the second app use some IPC to ask the first app "yo, am I supposed to do something special?", etc.).
It is also conceivable that ACTION_PACKAGE_ADDED will be broadcast before the user clicks either Done or Open (or HOME or BACK or whatever). In that case, you could listen for that broadcast, determine that, indeed, the app just installed does involve simian somersaults, and call startActivity(). This will be a bit jarring for the user, insofar as all of a sudden they'd be transported from the install process into this new app. And, since the precise timing of ACTION_PACKAGE_ADDED is undocumented, your mileage may vary (e.g., the user could still get a chance to tap Open before the broadcast winds its way to your app).
Comment: @peter_budo: If I understand you correctly, what you want is not possible. As noted in this answer, use `ACTION_PACKAGE_ADDED` to trigger running the third-party app, and design your app such that such apps are "nice to have" but not essential. After all, any given third-party app may not be available on all devices, or in all geographic areas, to which your app may be available.
Comment: Sorry for potential hijack here Mark, but I have similar question. I know I can start installation with market search as `startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=pname:com.package.name")))`. Is there a way to call on installation dialog with a package name so I can listen for potential cancel click?
Comment: @peter_budo: Sorry, I do not understand your question.
Comment: My application needs com.evernote.skitch so then in intent I can send image and start annotation. However this is failing if Skitch missing.  I use PackageManager to check if app present if not I would start above intent, but this leave space for user not installing from opened market search result. So if I could start "installation" dialog I could listen  for cancel button click. So I'm trying to find out how/where to call this dialog. Does it make sense?
Comment: Agree on 3rd-party dependency. Skitch is used just as part of prototype so not worried. I was just trying to explore some possibilities. Thank you for help. PS: Hope to meet you on Droidcon London ;)


Meta Tags on Frontpage

Question: It doesn't seem I can get my meta tags to appear on the page--front.tpl.php on a Drupal 7 site.
I feel like I have all the correct settings in the Meta tags module configuration, and I have cleared all caches. It works perfectly fine for all pages, just not the front page. This is driving me bonkers.
Any ideas?
Answer: Below are the steps without touching the files and using the drupal admin interface.

Go to admin/config/search/metatags/config/global:frontpage/edit
Add the Page title, Description etc and Save
Refresh the front page and check. Done !!
Comment: Thanks. This is the correct answer. The rest is just a waste of time.
Comment: Yes, indeed, how did you know that?
Answer: Try printing
<?php print render($page['content']['metatags']); ?>

in your page.tpl.php or page--front.tpl.php if youre using Meta tags
Comment: Wouldn't that print metatags in body instead of head, or this doesn't matter?
Answer: What module are you using for Metatags?
I believe the most popular one is metatags_quick. If you are using this I think you need to set the homepage metatags with the "Path-Based Metatags".  You should be able to find this at site.com/admin/config/search/metatags_quick/path_based
Comment: I finally figured this out.

Assuming you have Meta tags quick, you can go to the 'path based meta tags" tab and add the following as a path:

node

You then assign the appropriate metatag data.

-Mac
Comment: I wanted to do this, I have metatags quick, but how do you specify the homepage?  Im not sure how you specify the "frontpage" as a path?  Its perfect for 'views', but I cant figure out how to use for frontpage.
Answer: Found a quick and easy solution that shows meta tag description on page view source HTML for anonymous visitor, also Bing SEO Analyzer detects.

Go to Meta Tag (Quick) settings from Configuration admin menu.
Under the section Create and Attach, check box for Description for Taxonomy Term
Click Attach
Click Submit
Go to admin Structure menu, Taxonomy, Section, List terms
Edit Home to add a description in the (Meta) Description field.

Works

Meta Tags on Frontpage


LilyPond: Allow dynamics (or other outside-staff objects) within the staff

Question: I tried
\version "2.22.1"
\language "english"

{
  \dynamicUp
  \once \override DynamicLineSpanner.staff-padding = #0
  \once \override DynamicLineSpanner.Y-offset = -3
  b'\f
}

and
\version "2.22.1"
\language "english"

{
  \dynamicUp
  \once \override DynamicLineSpanner.staff-padding = #0
  \once \override DynamicLineSpanner.Y-offset = -4
  b'\f
}

But that doesn't seem to suffice and the dynamic just skips to under the staff above a certain threshold.
Is there a way to allow dynamics to touch the staff, like in the following example?

Ideally this would be obtained with all other grobs adjusting to this change, so if I'm not mistaken extra-offset is not a solution.
This is a wider view of the traditional engraving:

And this is the (less satisfying) best approximation I've managed on Lilypond:
Comment: Why do you want the dynamic mark inside the staff?
Comment: @ElementsinSpace The same reason traditional engravers use that: space economy and sometimes esthetics (e.g. to avoid a single dynamic marking in a system create an unseemly gap between the staff and some other outside-staff layer like a tempo marking or some other text script). Added more screenshots
Answer: The way to disable staff collision avoidance for the dynamic marking (or any outside-staff object) isn't by turning the staff-padding of the DynamicLineSpanner to #0 but its outside-staff-priority to ##f.
I deduced that from the LilyPond Learning Manual: 4.4.3 Outside-staff objects, particularly from the part under "The outside-staff-priority property" where they talk about slurs and articulations.
The dynamic will then be centered in the staff. The Y-offset can then be modified with an \override and the X-offset with a \tweak (per LilyPond Notation Reference: 4.6.2 Changing spacing) like so:
\version "2.22.1"
\language "english"

{
  \dynamicUp
  \once \override DynamicLineSpanner.outside-staff-priority = ##f
  \once \override DynamicLineSpanner.Y-offset = #2
  b'-\tweak X-offset #-0.75 \f
}

Comment: Yes. Generally by having a value for `outside-staff-priority` gives the grob the outside-staff-interface, thus Lilypond will not allow it to intersect with the staff.


order of parameters in differential forms

Question: I am completely mystified about parameters in differential forms and wherever I looked it's just glossed over.
Take for example the $2-$form $\omega = dx\land dy$ in $\mathbb{R}^n$.
Usually it's just defined like that, but given two vectors $(x,v_1), (x,v_2)$ in the tangent space at $x$, it shold be that $dx \land dy = dy \land dx$, since
$$(dx \land dy) (x)((x,v_1), (x,v_2)) = $$
$$- (dy \land dx)(x)((x,v_2)(x,v_1))=$$
$$ (dy \land dx)(x)((x,v_1)(x,v_2))=$$
According to my book, tough, $dx \land dy = - dy \land dx$.
Where am i wrong?
Answer: First of all, you're writing incorrect equations. Once you evaluate individual terms, there are no more wedges. The correct equation, using your (cumbersome!) notation, is
\begin{multline*}
(dx\wedge dy)((x,v_1),(x,v_2)) = dx((x,v_1))dy((x,v_2)) - dx((x,v_2))dy((x,v_1)).
\end{multline*}
And of course from this you see that, in fact, $dx\wedge dy = -dy\wedge dx$.
Answer: Answering my own question.
It's a misunderstanding of the anticommutativity of the wedge product of alternating tensors. I previously thought for some reason that, given $f,g$ alternating k-tensor and m-tensor respectively on $V$, with $V$ vector space over $\mathbb{R}$,
$$(f \land g) (x_1, ..., x_k, ..., x_{k+m}) = (-1)^{km} (g \land f) (x_{k+1}, ..., x_{k+m}, x_1, ..., x_k)$$
while of course it is:
$$(f \land g) (x_1, ..., x_k, ..., x_{k+m}) = (-1)^{km} (g \land f) (x_1, ..., x_k, ..., x_{k+m})$$
so the error is in the first equality.
Comment: I'm puzzled why you didn't respond to my answer 5 days ago. No, your lines are still nonsense (as I said, once you evaluate on vectors you do not have a wedge product, and your definition of the wedge product is just wrong). Regardless, your claim here is incorrect for general $k$ and $m$. It holds only when both $k$ and $m$ are odd. Maybe you should understand why that is.
Comment: Now the lines should be correct. I wasn't trying to evaluate the tensor, just applying anticommutativity of the wedge product
Comment: Maybe I'm doing some other mistakes now, but that's the one I've found. Please tell me if I'm still wrong or if I'm making another mistake altogether
Comment: You *are* evaluating when you write $dx((x,v_1))$; that is a scalar, so it makes no sense to write things like $dx((x,v_1))\wedge dy((x,v_2))$.
Comment: I'm sorry, you are right. I'm gonna correct it to show what I actually meant


Is the destructor called if the constructor throws an exception?

Question: Looking for an answer for C# and C++. (in C#, replace 'destructor' with 'finalizer')
Comment: @loyc-etc, C++ and C# are pretty different in their semantics.  This is really two separate questions.
Comment: The joy of compiling from the command-line is you don't need to set up a project. Just load up a file in a text editor, compile very easily, and run :)
Comment: I think the thing to do here is set up a throw-away project (or two: one per langauge) and do a check to find out.
Answer: It does for C# (see code below) but not for C++.
using System;

class Test
{
    Test()
    {
        throw new Exception();
    }

    ~Test()
    {
        Console.WriteLine("Finalized");
    }

    static void Main()
    {
        try
        {
            new Test();
        }
        catch {}
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}

This prints "Finalized"
Comment: This may be true for C#, but not C++.
Comment: I thought ~Test was a finalizer in C#, not a destructor? Ah I see the ~ syntax is sugar for setting up a finalizer. In the case that my ctor could throw, I expect I'd want to manually add the finalizer as the last step of the ctor to avoid cleaning up non-existent messes.
Comment: @Logan: It depends on which version of the C# spec you read as to whether they call it "finalizer" or "destructor".
Comment: @Jon: Is there any other C# specification than Ecma-334?
I know they exist, in fact they are published on your website ( http://csharpindepth.com/articles/chapter1/Specifications.aspx )
I mean ... Too bad there are no *Standard* specifications for versions higher than 2.0.
That said (protest) ...
The semantic of C# Finalizer is not like C++ Destructor (Obviously, you know it).
In the C# example I think more appropriate to replace the Finalizer for a Disposer.
Comment: @FernandoPelliccioni: No, there isn't a later version of the ECMA spec than that. As for disposal - the question *specifically* asks about a finalizer. Changing it to use disposal wouldn't answer the question.
Answer: Preamble: Herb Sutter has a great article on the subject:
http://herbsutter.wordpress.com/2008/07/25/constructor-exceptions-in-c-c-and-java/
C++ : Yes and No
While an object destructor won't be called if its constructor throws (the object "never existed"), the destructors of its internal objects could be called.
As a summary, every internal parts of the object (i.e. member objects) will have their destructors called in the reverse order of their construction. Every thing built inside the constructor won't have its destructor called unless RAII is used in some way.
For example:
struct Class
{
   Class() ;
   ~Class() ;

   Thing *    m_pThing ;
   Object     m_aObject ;
   Gizmo *    m_pGizmo ;
   Data       m_aData ;
}

Class::Class()
{
   this->m_pThing = new Thing() ;
   this->m_pGizmo = new Gizmo() ;
}

The order of creation will be:

m_aObject will have its constructor called.
m_aData will have its constructor called.
Class constructor is called
Inside Class constructor, m_pThing will have its new and then constructor called.
Inside Class constructor, m_pGizmo will have its new and then constructor called.

Let's say we are using the following code:
Class pClass = new Class() ;

Some possible cases:

Should m_aData throw at construction, m_aObject will have its destructor called. Then, the memory allocated by "new Class" is deallocated.

Should m_pThing throw at new Thing (out of memory), m_aData, and then m_aObject will have their destructors called. Then, the memory allocated by new Class is deallocated.

Should m_pThing throw at construction, the memory allocated by "new Thing" will be deallocated. Then m_aData, and then m_aObject will have their destructors called. Then, the memory allocated by new Class is deallocated.

Should m_pGizmo throw at construction, the memory allocated by "new Gizmo" will be deallocated. Then m_aData, and then m_aObject will have their destructors called. Then, the memory allocated by new Class is deallocated. Note that m_pThing leaked

If you want to offer the Basic Exception Guarantee, you must not leak, even in the constructor. Thus, you'll have to write this this way (using STL, or even Boost):
struct Class
{
   Class() ;
   ~Class() ;

   std::auto_ptr<Thing>   m_pThing ;
   Object                 m_aObject ;
   std::auto_ptr<Gizmo>   m_pGizmo ;
   Data                   m_aData ;
}

Class::Class()
   : m_pThing(new Thing())
   , m_pGizmo(new Gizmo())
{
}

Or even:
Class::Class()
{
   this->m_pThing.reset(new Thing()) ;
   this->m_pGizmo.reset(new Gizmo()) ;
}

if you want/need to create those objects inside the constructor.
This way, no matter where the constructor throws, nothing will be leaked.
Comment: Another scenario, should m_pGizmo throw at new, m_pThing still leaks right? Thanks..
Comment: No, because m_pThing is a smart pointer. If m_pThing did construct correctly, its destructor will be called if m_pGizmo throws.
Comment: Herb Sutter's article is wrong for C# and Java. The finalizers appear to be run even if the constructors throw an exception.
Comment: @David Leonard: You're wrong for C#. I'm not a C# lawyer, but with some Googling, I found the following article which says the construction of a C# object is OUTSIDE the implicit try/finally of the "using" statement. Thus, the Dispose method is NOT called. See: http://www.codeproject.com/KB/cs/tinguusingstatement.aspx and http://msdn.microsoft.com/en-us/library/aa664736.aspx
Comment: @David Leonard: You're ALMOST wrong for Java, as Herb Sutter's article places the construction of the object outside the try/finally, doing manually in Java what is automated in C#. I guess you could declare the reference outside, and write the new inside the try/finally, but there must be some reason why it is not done. A little research, though, will reveal that one should avoid using finalize() in Java because its execution can't be relied upon. I am not a Java lawyer, so I have no fast answer.
Comment: @paercebal Dispose is not the same thing as a finalizer.
Comment: @Travis : You're right. As Sutter's article is about disposers, not finalizers,when David Leonard was writing "*Sutter's article was wrong, The finalizers appear to be run even if the constructors throw an exception*", I wrongly assumed he messed up names (thus, my answer about C# disposers, or Java's finally clause in Sutter's example). The good thing is that your comment gave me the occasion to read the ulterior comments on Sutter's about finalizer executing even when the constructors throws: Another reason to not use them...
Answer: The destructor of the class still being constructed is not called, because the object was never fully constructed.
However, the destructor of its base class (if any) IS called, because the object was constructed as far as being a base class object.
Moreover, any member variables will have their destructors called too (as others have noted).
NB: this applies to C++
Comment: "destructors of all base classes", to be pedantic. The standard has a whole lot of words how it works in MI when one ctor throws.
Answer: In C++, the answer is no - object's destructor is not called.
However, the destructors of any member data on the object will be called, unless the exception was thrown while constructing one of them.
Member data in C++ is initialized (i.e. constructed) in the same order as it is declared, so when the constructor throws, all member data that has been initialized - either explicitly in the Member Initialization List (MIL) or otherwise - will be torn down again in reverse order.
Comment: But it should be noted that a raw pointer member which may have been initialized using new will *not* be automatically deleted.
Comment: He's quite correct actually. If you have a `T*` member initialized with `new T`, then you actually have two objects: the new'ed T and the `T*` itself. Like an `int`, a `T*` has no destructor. Hence, when the `T*` member is deleted, the T pointed to is not.
Comment: Agreed.  The task of deleting that pointer normally belongs in the destructor, and since the destructor is not called, there's a memory leak (unless a try/catch is written within the constructor to take care of this).  The safer alternative is to use auto pointers or smart pointers.
Answer: If the constructor doesn't finish executing, the object doesn't exist, so there's nothing to destruct. This is in C++, I have no idea about C#.
Answer: For C++ this is addressed in a previous question:  Will the below code cause memory leak in c++
Since in C++ when an exception is thrown in a constructor the destructor does not get called, but dtors for the object's members (that have been constructed) do get called, this is a primary reason to use smart pointer objects over raw pointers - they are a good way to prevent memory leaks in a situation like this.
Answer: C++ -
Nope. Destructor is not called for partially constructed objects. A Caveat: The destructor will be called for its member objects which are completely constructed. (Includes automatic objects, and native types)
BTW - What you're really looking for is called "Stack Unwinding"
Comment: Actually, I'm writing an STL-style collection, so I call constructors and destructors manually. Therefore I was wondering whether it's normal to call the destructor in case of an exception. But this "partial destruction" you describe must be done by the compiler, so I don't have to.
Answer: Don't do things that cause exceptions in the constructor.
Call an Initialize() after the constructor that can throw exceptions.
Comment: Please, could you explain why? The "Initialize()" idiom is an antipattern in most cases in C++. Perhaps you're mistaking with "don't ever throw an exception from a Destructor?"
Comment: I know, designing a class with "Initialize()" beats the purpose of having a class at all.
Comment: There are plenty of valid reasons for creating classes with an init method, especially when dealing with concurrency.  Sometimes you need object creation to be cheap, even when the primary initialization of that object is expensive.
Comment: Google's code guidelines discourage using exceptions at all, so they discourage throwing from the constructor ( http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Exceptions ).
Comment: On the other hand, pretty much everybody else says to throw from a constructor because that is the only way to signal the constructor failed ( http://herbsutter.wordpress.com/2008/07/25/constructor-exceptions-in-c-c-and-java/ ).


Dúvida na consulta SQL "between" ou "in"

Question: Estou gerando um relatório entre data, conforme a figura abaixo:

Porém, quando entro com a data inicial:
Ano inicial: 2014 Mês inicial: 6
e
Ano final: 2015  Mês final: 5
não traz os dados, a consulta interpreta que mês inicial 6 é maior que mês final 5.
Caso eu utilizar a cláusula IN a consulta retorna apenas os meses 6 e 5 e não retornando o mês 4, porém quando utilizado o BETWEEN não retorna nenhum dado.
Segue a consulta.
BETWEEN
WHERE v.verba_ano BETWEEN $ano AND $ano_fnal AND v.verba_mes BETWEEN $mes AND $mes_fim

IN
$WHERE= "WHERE v.verba_ano IN($ano,$ano_fnal) AND v.verba_mes IN($mes,$mes_fim)";

Comment: É em PHP, certo ?
Answer: O BETWEEN espera que o primeiro parâmetro seja menor que o segundo, o que causa o seu problema.
Utilizar o IN também não resolve seu problema porque ele não trabalha com intervalos, mas sim com valores isolados. Ex: data IN (3,8) não irá trazer o intervalo 3 a 8, mas sim exatamente os valores 3 e 8
Solução
Altere sua consulta para selecionar a data completa, no formato AAAA-MM-DD.
Procure sempre armazene no seu banco colunas de datas com o tipo DATE.
O dia você pode gerar dinamicamente a partir da query:
SELECT * FROM tabA
WHERE verba_data BETWEEN '{$ano}-{$mes}-01' AND last_day('{$ano_fnal}-{$mes_fim}-01');

Segue um exemplo no sqlfiddle.
Comment: gmsantos, uma duvida, testando aqui, encontrei um erro, seguinte: quando eu insiro a ano inicial: 2014 e o mês inicial: 06 e o ano final: 2015 e o mês final 05, a consulta não retorna nada por que o mês inicial é maior que o mês final 05 ... alguma outra alternativa ? obrigado
Comment: @hulckb você juntou a data em somente um campo ? é do tipo date?
Comment: gmsantos, ajuntei conforme o seu esquema '{$ano}-{$mes}-01' AND last_day('{$ano_fnal}-{$mes_fim}-01'); o tipo do campo func_ano é INT e o tipo do func_mes é TINYINT
Comment: Você precisa juntar os campos func_ano com func_mes para um novo campo do tipo data, assim você estará fazendo do jeito correto. O MySQL como outro banco de dados tem tipos de dados para datas,
Comment: eu já ajuntei gmsantos, tem um exemplo ai ? abraços
Comment: Coloquei no corpo da resposta, último link
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/24987/discussion-between-gmsantos-and-hulckb).
Answer: Faz assim (se for php e mysql)
WHERE STR_TO_DATE(CONCAT_WS('-', v.verba_ano, v.verba_mes), "%Y-%m") BETWEEN STR_TO_DATE('{$ano}-{$mes}', "%Y-%m") AND STR_TO_DATE('{$ano_fim}-{$mes_fim}', "%Y-%m")

Comment: obrigado pela contribuição Adir Kuhn
Comment: Se minha resposta for a certa para seu problema marque como solução, tks
Answer: Tenta algo assim, comigo funcionou.
WHERE (v.verba_ano BETWEEN $ano AND $ano_fnal) AND (v.verba_mes BETWEEN $mes AND $mes_fim)

Comment: Ola Pedro, tentei a sua dica e não deu certo, mesmo assim, muito obrigado por contribuir
Answer: Comparar datas fica fácil se você inverter mes/ano para ano/mes em um único valor inteiro: No seu exemplo, 06/2014 a 05/2015 você compararia se a data está entre 201406 e 201505.
where (verba_ano * 100 + verba_mes) between 201406 and 201505

Onde 201406 = $ano*100+$mes e 201505 - $ano_fim*100+$mes_fim
Se precisar do dia também a formula fica
ano * 10000 + mes * 100 + dia

Answer: Deu certo aqui, segue o código abaixo:
AND STR_TO_DATE(CONCAT_WS('-',i.func_ano,i.func_mes,'01'),'%Y-%m-%d')
BETWEEN STR_TO_DATE('$ano-$mes-01','%Y-%m-%d')
AND STR_TO_DATE('$ano_fnal-$mes_fim-01','%Y-%m-%d')


Ask user for URL on registration and create feed from the URL on his/her profile page

Question: I know i should be using the Feeds module for this but i want to know how will i turn that particular URL into feed automatically when user enters his feed URL.
Basically i want to let users show their github activity feed on their drupal profiles.
URL for it is something like this https://github.com/githubusername.atom
So in a feed, the URL still remains standard and if i just ask them to enter their github username and generate the feed accordingly, that would be really amazing. I know how to do it in php but i don't know drupal moduling. It would be great if anyone could help me with it or give me ideas on how to do it.
Answer: Since you already know how to do it in PHP, you could use the Panels module. You can then use a Panel to display the user's profile, and you can add a "Custom" field with your php inside.
You could also do something similar by using the Display Suite module and adding a custom code field.
Of course that would require you put php directly into the UI, which isn't always considered the best approach but can be done. To get the user's username, you'd put a field in their profile asking them the user name. That value would then be stored in the $account object.
Comment: Well it did clear a lot out.
I have made a custom code for user profile as i could not find any other solution to it. Thanks anyway.


How can Facebook's session get mixed up because of NAT and/or Proxy

Question: Have received some reports from a customer (a very large company) they reported issues from clients who are using Facebook.
These clients claim that once in a while when they log in to Facebook they end up in someone else's session.
I know that network is NATed then Proxied before getting to Facebook.com.
Although I'm not able to explain how this issue can occur.
Is it possible that the Proxy is not sending the right session back to the clients?
How can they end up with someone else's session since Facebook is cookie based session??
Anyone seen this before?
Answer: There's a known vulnerability that makes Facebook susceptible to cross-site scripting attacks.  It's possible that something like this is going on.
Here's a write-up of it.
Comment: Thanks for the answer, although, could that explain how a non-techy person end up browsing a colleague's facebook account simply by going on facebook.com?
Answer: Are they using a proxy service on the firewall?  It may be possible that facebook related pages containing session cookies are getting cached.  Depending on the order pages are loaded it could replace the session cookie with someone else's cookie.
It should be less of a problem with https connections which shouldn't be cached.
Answer: NAT couldn't be the source of it, however a session is merely a cookiestring and if the same cookie string is sent out to multiple computers, then basically both computers would end up in the same session.
A proxy could do that, but that would mean that both facebook and the proxy does some rather problematic stuff. afaik facebook only sends out the session cookie string after login on the https site, which means that it shouldn't have been cached.


role delegation module : how to fine-tune the 'edit-administer-users' permissions?

Question: Using role delegation module , i allow a user say 'mat' with a 'site_admin' role to assign other users to a 'VIP_role'.
The problem is role delegation needs apparentely 'administer users permission' being selected for 'assign' actions to work.
When logging in with 'mat' credentials that's been set with 'administer users permission', it gives some back office links that i would like to restrict.
How could I restrict 'role delegate' to editing existing users and assign them roles ?
Comment: if all else fails, you could set up a series of [Rules](https://www.drupal.org/project/rules) to defer those addresses to some other page based on the role of the current user
Comment: @Geoff could u provide an exemple on how to do that?
Answer: The two modules you will need:
Rules:

The Rules module allows site administrators to define conditionally
  executed actions based on occurring events (known as reactive or ECA
  rules). It's a replacement with more features for the trigger module
  in core and the successor of the Drupal 5 workflow-ng module.

and Context Redirect:

This module provides a Context reaction which redirects to a given
  internal or external url if the context conditions are met.
You could use this module to redirect users of specific roles to a
  page of your choice, or redirect them based on a path in the site
  (node/2, 'page.htm') to another page or external URL
  (ht-p://www.google.com). Dozens of conditions can be cooked up with
  Context and redirect users to where they need to go.

set up a new rule, have it react on a url (based on whatever url you want to restrict)
set a condition that the user be of the role for which you are trying to limit access
set an action - presumably a redirect to a different page, or perhaps a custom page that tells them they don't have permission to view that url
Answer: i did it this way , unsetting menu links depending on role
<code>  http://drupal.stackexchange.com/questions/136399/how-to-unset-admin-menu-links-programmatically
</code>


What should I do while designing stratified cluster randomized sampling survey if cluster size is large/smaller than I expect?

Question: I am design a sampling strategy for a health survey in long-term care facilities (LTCFs). I refer to the article here
 and want to ask question about the cluster size.
I am thinking of doing a stratified cluster randomized sample (addition question, if I sample everyone in a single LTCF, is it still a 2-stage sampling? or just 1-stage? Is that I need to sample some LTCF, and then sample some resident in the sampled LTCF, then this can be called as 2-stage sampling? I am getting lost in the terminology jungle), something like this one I asked before. After reading a few books and articles, I think I need to use both stratification and clustering so to have better balance on inflating/deflating the standard error for my measurement.
I have assigned the size of a cluster to be 60 and then do a sample size estimation (approx. 3000), my question is as follow:
Say if I sampled a "small" LTCF, only 20 residents inside, I need 40 more, what should I do? To sample additional cluster?
In another way round, if I sampled a "large" LTCF, with 400 residents inside, I only need 60, should I only do a simple random sampling to pick up the 60 residents I need?
The "unequal cluster size" has been a nightmare to me for quite sometime, right now I have no clue how to process this kind of data appropriately (as I can't do it as if the data is collected by simple random sampling, right?).
I am reading Sharon L. Lor's Sampling - Design and Analysis; and Steven G. Herringa's Applied Survey Data Analysis. Can anyone give me some clue, perhaps in the 2 books, that can give me some insight on getting out of the nightmare? Recommendation of other books/articles is also welcomed. Thanks.
Answer: It is techincally only a one-phase study design when you do not select at random your ultimate sampling units from within your primary sampling units. This Amstat article has some info about that:
http://www.amstat.org/sections/srms/proceedings/y2008/Files/301835.pdf
However, you're getting into deep water when you do this pseudo random sampling within units. Without appropriate weighting, you will obtain an unrepresentative sample. For instance, suppose small LTCF are fundamentally different, less staff, less residents, etc. If you sample exhaustively from these PSUs whereas other PSUs with larger measures-of-size (MOSs) are sampled at a fraction (say 5-20% as you mentioned), your smaller LTCFs will be overrepresented. Hence, by virtue of random sampling within PSUs, you make it into a 2-phase design, hence you'll need either reweighting or homogeneous sampling frequencies within PSUs to ensure your estimates are unbiased.


How to cancel task but let her to finish the chunk?

Question: I have a program (.NET Core C#) that delete data from DB, for each account - deletes all the data related to the account.
I want to add an option to stop the program but finish the deletion for the person the program is on and then stop and exit.
I want to do something like this, when I press any key then the program will finish printing 10 entries and then stop and exit. this is for example :
public static void Main(string[] args)
{
    // ???

}

static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
    Console.WriteLine("Shutting down...");
    // Cleanup here
}

private static async Task MyTask(CancellationToken cancellationToken)
{
    Print(cancellationToken);
}

public static void Print(CancellationToken cancellationToken)
{
    while (cancellationToken.IsCancellationRequested!)
    {
        for (int i = 1; i < 10; i++)
        {
            Console.WriteLine(i);
        }
    }
}

I would like to any idea you have,
Thanks!
Comment: Maybe I do not understand the complete question: When I have to break/cancel situation, I will have to check an condition on the begin (or end) of the loop, and this has to be set from outside (yeah, maybe if this is async or thread you have to solve that communication task) but basically: It comes down to a "if (breakcondition) ...."
Comment: i mean to get imformation from outside , e.g ctrl+c or something else, and when i click it, let the program finish to delete the account data her is on, and then stop and exit.
Answer: Just don't pass cancellationToken to dbContext. Check cancellationToken manually when ever you can stop your program.
private static async Task DeleteAllAccounts(CancellationToken cancellationToken)
{
    var accounts = await GetAccountsAsync(cancellationToken);
    foreach (var account in accounts)
    {
        await DeleteAccountAsync(account, CancellationToken.None);
        if (cancellationToken.IsCancellationRequested)
            break;
    }
}

Comment: You might consider using `ThrowIfCancellationRequested` instead, since this will put the task into a cancelled state instead of RanToCompletion. If you check 'IsCancellationRequested' the caller has no real way to know if all accounts where deleted or not.
Comment: Hey,thanks for the answer!
how i can get information from outside ?
i meant when i click ctrl+c or something else
Comment: @Xodya check out this link. https://stackoverflow.com/questions/1119841/net-console-application-exit-event
Comment: hey i think it's not help me...
can you write for me small example please? with what you wrote up and with canceltoken from outside ...
Comment: @Xodya if you looking for detecting ctrl+c check this link too https://www.meziantou.net/detecting-console-closing-in-dotnet.htm


Raspberry Pi and GitLab

Question: Is there a way I can run GitLab (http://gitlab.org/gitlab-ce) and GitLab CI (http://gitlab.org/gitlab-ci) on a Raspberry Pi device running Raspbian?
I want to have my own internal Git box where I can store code and possibly allow other friends access to upload their code too. Is it possible?
Thanks.
Answer: Official way for the Pi 2
There is a very easy way to install it on the Raspberry Pi 2.
wget https://s3-eu-west-1.amazonaws.com/downloads-packages/raspberry-pi/gitlab_7.9.0-omnibus.pi-1_armhf.deb
sudo dpkg -i gitlab_7.9.0-omnibus.pi-1_armhf.deb

You might prefer to go to the official page in order to get latest version. It's fast and easy, they recommend at least 1Gb swap.
On the Pi B and B+ you will hit the memory limit very soon and get degraded performance as you grow, but on the Pi 2 it works nicely, specially if you mount your repos on an external USB hard disk.
Answer: It is possible to install GitLab on the Raspberry Pi. You will need the Raspberry pi model B  reversion 2012 or model B+ (512mb of RAM). Installing GitLab takes a very long time.
Steps:

Get a fresh copy of the latest Raspbian and expand the file system. Be sure to boot to text mode.
Free-up space by typing: sudo apt-get purge xorg lxde xinit openbox lightdm && sudo apt-get autoremove && sudo apt-get clean
Add some more swap space by typing: sudo dd
if=/dev/zero of=/swapfile1 bs=1024 count=524288 (this will take a minute or so)
Activate the swap space by typing sudo mkswap /swapfile1 && sudo chmod 0600 /swapfile1 && sudo swapon /swapfile1
Get an external hard drive and format it as ext4. (very important)
Add the Git user: sudo adduser --disabled-login --gecos 'GitLab' git
Delete everything in /home/git sudo rm -rf /home/git/* && sudo rm -rf /home/git/.*
Add the following in /etc/fstab: (sudo editor /etc/fstab)
/swapfile1 none swap defaults 0 0
/dev/sda1 /home/git ext4 defaults 0 0
Reboot: sudo reboot
Follow the instructions here for the latest version of gitlab (currently 7.7): https://gitlab.com/gitlab-org/gitlab-ce/blob/7-7-stable/doc/install/installation.md

Notes: On step "Install Gems", when you type sudo -u git -H bundle install --deployment --without development test mysql aws, It will take several hours, especially while fetching the gem sources and installing "kgio". You can ignore all incompatibility messages during this process.
Another thing to note is that creating a project inside GitLab takes a very long time. Just return to the dashboard if it takes more than a minute.
Answer: You can find GitLab requirements here. If you have Raspberry Pi model B (512MB of RAM), I think that you can run GitLab but you might encounter performance issue.
I'd suggest that you take a look here to find lighter systems.
Comment: I had a look at Gitorious as an alternative but I don't know whether the Pi can handle that either
Comment: Maybe use cgit (http://git.zx2c4.com/cgit/) which is a very fast and lightweight systemm
Answer: I use Gitolite on a small server and it's pretty awesome.  There is no web UI.  Gitolite itself is just a git repo you push and pull changes to to control access
https://github.com/sitaramc/gitolite
Answer: On your expanded, up-to-date raspbian, edit the swap space config file:
sudo vi /etc/dphys-swapfile

Change CONF_SWAPSIZE from 100 to 1000
Follow the instructions for the latest GitLab, at the moment:
https://gitlab.com/gitlab-org/gitlab-ce/blob/8-14-stable/doc/install/installation.md
Happy gitting!
Comment: you may want to include why the user should increase the swapsize.
Answer: For those still interested in running versioning systems (and more) on a Pi, I wrote an article of what I tested here. In my experience, recent versions of GitLab are very difficult to run on a Pi 2/3, but work well on Pi 4. For Pi versions < 4 I suggest Gitea, for Pi == 4, I suggest GitLab. In the article, I listed docker images that can be used to run both services in a few minutes:

https://hub.docker.com/r/carlonluca/gitea
https://hub.docker.com/r/carlonluca/gitlab

In the article there are also info on CI/CD with Jenkins and GitLab.

Raspberry Pi and GitLab


O que esse código significa/faz?

Question: Bom, estou aprendendo a usar JavaScript, principalmente a trabalhar com index, e sempre me deparo com isso, mas quero entender direito o que cada parte significa, pois não quero usar sem realmente entender...
var i;
for (i = 0; i < x.length; i++) {
  txt = txt + x.options[i].text + "
";
}

Comment: Eu fechei por 2 motivos. Primeiro, que aparentemente tem um erro no código (length do x e não do options). Precisaria de um [mcve] para validar. Segundo que se não deixar clara a parte que entendeu, dá pra ficar o dia todo fazendo perguntas similares cada vez que muda um pequeno detalhe sem que seja útil pra qualquer outra pessoa na busca. . Estudar a postagem disponível neste link pode fazer uma diferença muito positiva no seu entendimento e aproveitamento do site para as próximas: [Guia de sobrevivência do Stack Overflow em Português](https://pt.meta.stackoverflow.com/q/8045/70).
Comment: Só pra adiantar o assunto, a finalidade do site é (ao menos era, originalmente) criar um repositório de conhecimento que sirva para futuros visitantes com problemas do mesmo tipo. A sua, como não tem um problema de fato, só serve para seu caso específico, o que cai mais no modelo helpdesk/ajuda individual. Mas isso tudo está bem melhor explicado no link, além de várias outras coisas extremamente relevantes. O fato de ter erro acaba piorando a situação, pois se trata de um pedido de explicação de funcionamento de algo que não funciona;
Comment: bom, obrigado pela explicação, eu acho...
Answer: Minha sugestão é aprender a programar passo por passo, entender cada mecanismo da linguagem, ir estruturadamente formando seu conhecimento. Nunca vi alguém (deve existir em algum lugar) que conseguiu aprender bem só lendo códigos dos outros. Como complemento pode ser útil.
Este código nem é muito bom, a não ser que tenha um contexto maior, mesmo assim é improvável. E justamente por não ter um contexto dá pra falar só sobre o mecanismo e não a intenção geral.
Variáveis deveriam ter seu escopo limitado ao menor trecho possível, neste caso é o próprio for, então por que a declaração da variável está fora? A não ser que tenha algum motivo parece que a pessoa que escreveu não sabe bem o que está fazendo. Embora o var não ajuda muito, e pro escopo ficar realmente restrito deveria usar o let (o que dá alguma polêmica porque alguns navegadores não o aceitam, mas eu tenho a impressão que isto é tão pouco e gera tanta dificuldade que pra navegadores antigos deveria ter outra versão do código de qualquer jeito, ou ainda poderia fazer uma tradução posterior com Babel.
Esse laço é bem padrão e percorre todo um array, ele vai da posição 0 desse array até o número anterior ao seu tamanho (se começa do 0 a última posição é o tamanho -1, o que dá certo porque foi usado o operador <(menor que), então quando for igual ele já não executa mais). Ele vai adicionando um no índice em cada passo, o tal do i++, isto é o mesmo que i = i + 1 que é pegar o valor de i, somar 1 e guardar o novo valor em i mesmo.
Dentro a execução é ir concatenando uma string em cada passo. Não tem o código mas ele deve começar com um texto vazio ou um cabeçalho único. A parte da direita da expressão é o que faz essa concatenação, ele pega o valor já existente e soma com o resto a seguir, e guarda tudo na própria variável que tem então um novo valor que será usado no próximo passo. Poderia ser escrito assim:
txt += x.options[i].text + "
";

O que está sendo concatenado são duas partes, uma expressão com uma variável e o literal que é uma tag HTML que quebra a linha.
A parte da variável está bem esquisita e provavelmente errada, mas novamente, sem contexto não posso garantir.
Quando percorre o objeto x espera-se que ele seja um array. E vai andando nos elementos dele, algo assim:
x[i]

Porém não é o que está sendo feito. Como o índice está sendo usado em options este é o array e é ele que deve varrer, portanto é um erro pegar o tamanho de x, deveria pegar o tamanho de x.options que é um objeto dentro do outro.
Por fim dentro desse array options tem algum objeto, que não sabemos qual é, mas ao que tudo indica um dos membros dele (uma propriedade que ele tem) é text e é isto que está pegando.
Assim este código deveria ser algo assim:
let txt = "";
for (let i = 0; i < x.options.length; i++) {
    txt += x.options[i].text + "
";
}

Note que por options ser um array tem uma propriedade chamada length. Se isto não está dando erro então x também tem, mas não está varrendo o mesmo objeto. Pode estar até funcionando por coincidência, mas acho que nem roda.
Se quiser pode eliminar as chaves já que é só uma linha:
let txt = "";
for (let i = 0; i < x.options.length; i++) txt += x.options[i].text + "
";

A variável txt vai fora do laço mesmo porque ela provavelmente será usada fora, se não então não faz sentido ter isso.
Lembrando que só use o let se tiver certeza que não rodará em navegadores recentes ou se fará alguma tradução para rodar nos antigos.
Não entendeu tudo? Provavelmente porque está faltando o fundamento de cada coisa, por isso que precisa ir construindo o conhecimento de forma estruturada, um tijolo de cada vez, e começando pelo alicerce, ir subindo a parade, fazendo o teto, o acabamento, etc. Se não souber explicar por conta própria cada mecanismo individual não pode passar para a próxima.
Tentando fazer um exemplo funcional que eu acho que era a intenção dese código que parece todo errado:

let x = document.getElementById("exemplo");
let txt = "";
for (let i = 0; i < x.options.length; i++) txt += x.options[i].text + "
";
console.log(txt);
<form>
  <select id="exemplo" size="4">
    <option>Facebook</option>
    <option>Twitter</option>
    <option>Linkedin</option>
    <option>Instagram</option>
  </select>
</form>

Coloquei no GitHub para referência futura.
Comment: É porque desestruturou seu aprendizado. Note que está tentando aprender por um exemplo errado e por não entendê-lo não pode detectar isso, imagina quanta coisa não dá erro, você não aprendeu o fundamento daquilo e aprende algo errado desta forma.
Comment: Obrigado pela explicação. Bom, pra aprender melhor eu costumo praticar desenvolvendo alguns códigos que vêm à cabeça, mas só quando eu acho que já tenho o conhecimento necessário, mas vez ou outra me deparo com uma situação dessas, de coisas as quais não entendo a estrutura completa...enfim, foi uma resposta bem completa, vai ajudar bastante...
Comment: Sim, é um código de um terceiro, mas não levei pro meu código, só queria entender direito como que a estrutura trabalhava pra dar o valor pra essa variável i que ele cria... Ah! E o elemento que ele tá usando como array é uma tag , e cada index dela é uma ...

O que esse código significa/faz?


PHP - Database query or POST

Question: I have a search page that allows the users to filter other users by various categories (age, gender, country, region, ethnicity, etc). The first time the search function is called it gets all the possible values for each category from the database. Just wondering though...
Is it better to POST this data back each time the page is re-loaded (in a serialized hidden form field) or should I retrieve this information from the database every time the page is loaded.
If i understand the situation correctly, the serialized POST option would increase the sites bandwidth consumption as the data is traveling from the users machine, to the server and back to the users machine again. On the other hand, querying the database everytime would increase the load on the server/database, but would only use half the bandwidth.
If thats the case, what option should I go for...
I know that it probably doesn't make much difference for the amount of traffic i'll be getting, but I want to learn the best methods of doing this sort of stuff :P
Answer: Generally, I would always keep things under your own control. Which means keeping it between your server and your database.
You have no control over the speed of a user's internet connection, or network latency etc.
Also, if you want to keep things between requests, have you thought about using sessions or cache? A cache, such as APC would allow you to store the data on the server for the next request, so it needs neither Database or bandwidth.
Comment: Thanks... I was looking at APC a few days ago, looks really cool. Had plans to use that on another part of the site but didn't think about using it in this situation. Might look into that :P
Answer: I think, "POST back" approach is generally not good:

This may lead to security issues
Usually connection between database and web-server has higher bandwidth, then connection between client and web-server

I'd recommend either to use data caching on web-server side (see other answers for links), or to implement client-side data filtering / sorting - there must be ready-to-use javascript libs for that.
Comment: Thanks for the advice... Could you expand more on the security issues of POST-ing back the data?
Comment: Potential security issues depend on implementation details. If there is some server-side logics, which handles serialized data, which comes from user, some specific changes in this data may break logics, or overload service, etc. If there are some controls in user list, user may generate invalid user name/id with, for example, SQL injection. The principle is clear: all data, which comes from user, must be validated. The more data comes from user, the more possible problems you have to consider, the more validation you have to implement
Answer: Facebook and many other companies employ memcache to store the search results and query this cache so as to minimize requests to the database.
You can store the search results of your first search in memcache and since this is the superset of the data subsequently filtered through using the various parameters, all subsequent requests will be made against the cache as opposed to the database.
Answer: By serializing your result and sending them back via POST you have to "print" them into your form somehow, which means it can be tempered with, no it's definitely not a viable solution.
Caching your results in memcache, APC, etc. could be a great alternative. If you don't want to or cannot one of these solutions, there's already the database engine cache that will take care of most of the overhead for you.
One last thing, a search page should use a GET method according to HTTP/REST specifications: POST must be used for inserting, while GET must be used for retrieving.

PHP - Database query or POST


Lightgbm, time-series and spikes repeated on a yearly basis

Question: I have a data set (time-series) with the shape {$2190$x$63$}. There are 63 variables, 2 products ($A$ and $B$) worth of 3 years of daily data, thus I have $1095$ observations per product and total of $2190$ observations.
Important note: Product $A$ has spikes every 30th of December.
I've built a lightgbm model which overall works just fine. I've chosen lightgbm because the number of products will be much larger, increasing the size of the dataset. Let's say $20$ products, $1095$ observations per product, $63$ variables, which totals $20*1095=21900$ rows and $63$ columns.
My problem: min_data_in_leaf affects how well spikes of the product $A$ are forecasted.
As far as I can tell, when you have a relatively large dataset {$21900$x$63$} (it can go WELL beyond it), min_data_in_leaf should be large enough to make sure that your model is not overfitting. The problem is, no matter how many products will be included (expanding my data), large min_data_in_leaf will fail to capture these spikes because to distinguish them from other observations I need to specify a small value of min_data_in_leaf. At least to my understanding.
My thoughts on it:

I should stick to tuning other parameters that control overfitting and keep min_data_in_leaf fairly low;
Maybe I need to do more feature engineering? (I've tried, unsuccessfully)

Any help is greatly appreciated!
Visualisation. 1 year of data (I have 3) + forecasts:

My parameters (early stopping is on):
lgb_params = {'boosting_type': 'gbdt',
              'objective': 'regression',
              'metric': 'rmse',
              'learning_rate': 0.01,
              'subsample': 0.8,
              'subsample_freq': 1,
              'feature_fraction': 0.6,
              # 'max_depth': -1,
              'num_leaves': 100,
              'min_data_in_leaf': 30,
              'max_bin': 100,
              'n_estimators': 10000,
              'boost_from_average': False,
              'verbose': -1}

Answer: Generally, if your objective is to maximize predictive performance, you should choose the hyperparameters that maximize your expected predictive performance (eg. by choosing the parameters which lead to maximal performance on holdout data). It's not common to set hyperparameters by hand unless you have some specific goal in mind. If you see significantly better performance with min_data_in_leaf:30 than min_data_in_leaf:100, go with 30, all other things being equal. No need to overthink it.
To your thoughts...
1. I should stick to tuning other parameters that control overfitting and keep min_data_in_leaf fairly low
Never really a bad idea to experiment with more hyperparameters. And in this case, if you know that certain quirks of your dataset will lead to a low value of min_data_in_leaf  performing well, it might make extra sense to experiment with other types of regularization. The LightGBM Parameters Tuning page lists around eight other hyperparameters that can reduce overfitting. But again, this should be done in the context of maximizing performance on holdout data. If more regularization leads to a worse predictive model, why are you adding it?
2. Maybe I need to do more feature engineering? (I've tried, unsuccessfully)
That would not solve the problem with min_data_in_leaf. If you only have 40 observations where date='Dec 30' you're only going to have 40 observations where is_dec_30=True.
Comment: Sincerely appreciate your answer! Yes, I agree that one should not manually choose parameters, I got mine as a result of CV and decided to play around with some of them to better understand my data. Your answer to my question pertaining feature engineering is particularly insightful, I haven't thought about it that way. Thank you one more time!


Second Borel-Cantelli lemma via the moment method

Question: Let ${E_1,E_2,\dots}$ be a sequence of jointly independent events. If ${\sum_{n=1}^\infty {\bf P}(E_n) = \infty}$, show that almost surely an infinite number of the ${E_n}$ hold simultaneously. (Hint: compute the mean and variance of ${S_n= \sum_{i=1}^n 1_{E_i}}$. One can also compute the fourth moment if desired, but it is not necessary to do so for this result.)
Question: From the hint, we want ${\bf P}(\lim_n S_n = \infty) = 1$. i.e., $S_n$ diverges almost surely, yet I didn't see immediately how the mean ${\bf E}(S_n) = \sum_{i=1}^n {\bf P}(E_i)$ and the variance ${\bf Var}(S_n) = \sum_{i=1}^n {\bf P}(E_i)(1 - {\bf P}(E_i))$ is applicable here, the Chebyshev's inequality does not seem to convey too much information.
Answer: $$
     P\left(\vert S_n - E S_n \vert > \dfrac{1}{2}ES_n\right) \le \dfrac{4\text{Var}(S_n)}{(ES_n)^2} = \dfrac{4\sum_{k = 1}^n P(E_k)(1 - P(E_k))}{(\sum_{k = 1}^n P(E_k))^2} \le \dfrac{4}{\sum_{k = 1}^n P(E_k)} \rightarrow 0
$$
Or, equivalently,
$$
    P\left(\vert S_n - E S_n \vert \le \dfrac{1}{2}ES_n\right) \rightarrow 1
$$
But,
$$
    \{\vert S_n - ES_n \vert \le \dfrac{1}{2}ES_n\} \subseteq \{S_n \ge \dfrac{1}{2}ES_n\}
$$
Therefore,
$$
     P\left(S_n \ge \dfrac{1}{2}ES_n\right) \rightarrow 1
$$
Now, for $M > 0$, we can choose $n_0$ such that
$$
   \dfrac{1}{2} ES_n \ge M \ \forall n \ge n_0
$$
Thus,
$$
    P(S_n \ge M) \ge P\left(S_n \ge \dfrac{1}{2}ES_n\right) \forall n \ge n_0
$$
Finally, since
$$
   \bigcap_{M \in \mathbb{N}} \bigcup_{n \in \mathbb{N}} \{S_n \ge M\} \subseteq \{\lim_n S_n = \infty\}
$$
we can conclude that $\mathbb{P}(\lim_n S_n = \infty) = 1$
Comment: Sure, I did it myself in the OP, thank you.
Comment: Thanks for the feedback, can you specify where the condition of independence is being used?
Comment: The independence assumption is used in the calculation of the variance: $$ \text{Var}(S_n) = \sum_{k = 1}^n \text{Var}(1_{E_k}) = \sum_{k = 1}^n P(E_k)(1 - P(E_k)) $$
Answer: One can use the Paley-Zygmund inequality (the second moment method). As the sequence $S_n$ is non-decreasing, $\lim_n S_n = \lim \sup_{n \to \infty} S_n$, and it suffices to show that ${\bf P}(\lim \sup_{n \to \infty} S_n = \infty) = 1$.
Fix some large $M > 0$. For any $0 \leq \theta \leq 1$ small, let $n' = n(\theta)$ be sufficiently large with $\theta{\bf E}S_{n'} > M$. For all $n \geq n'$, the Paley-Zygmund inequality gives ${\bf P}(S_n > M) \geq {\bf P}(S_n > \theta {\bf E}S_n) \geq (1 - \theta)^2\frac{({\bf E}S_n)^2}{({\bf E}|S_n|^2)} = (1 - \theta)^2$ (by the independence hypothesis, $({\bf E}S_n)^2 = {\bf E}|S_n|^2$). In particular, ${\bf P}(S_n > M) \to 1$.
We thus obtain ${\bf P}(\lim \sup_{n \to \infty} S_n > M) = \lim_{N \to \infty}{\bf P}(\bigvee_{n \geq N}(S_n > M)) \geq \lim_{N \to \infty} {\bf P}(S_N > M) = 1$, since $M$ is arbitrary, the claim follows from continuity from above.


After executing a user_defined function i am getting an error

Question: I have 27 states of India for which a water quality has to be tested and plotted.
state_1 <- subset(train,train$State.Name=="ANDHRA PRADESH")
ANDHRA <- as.data.frame(table(state_1$District.Name,state_1$Quality.Parameter,state_1$Year),stringsAsFactors = FALSE)
str(ANDHRA)
names(ANDHRA) <- c("District.Name","CHEMICAL","YEAR")
an <- ggplot(ANDHRA,aes(ANDHRA$CHEMICAL,ANDHRA$Freq,fill=ANDHRA$District.Name))
an+geom_bar(stat="identity",position = "dodge")+facet_grid(.~ANDHRA$YEAR)+
labs(title="TREND of Chemical Compostion in Andhra Pradesh Villages",x="Chemicals",y="Number Of Cases",fill="Districts in Andhra Pradesh")

So i created a user defined function and it loads into the global environment with no error.
district_analysis<-function(a,b,d) {
b<- subset(train,train$State.Name=="a")
d<- as.data.frame(table(b$District.Name,b$Quality.Parameter,b$Year),stringsAsFactors = FALSE)
names(d) <- c("District.Name","CHEMICAL","YEAR")
an <- ggplot(d,aes(d$CHEMICAL,d$Freq,fill=d$District.Name))
an+geom_bar(stat="identity",position = "dodge")+facet_grid(.~d$YEAR)+labs(title=paste0("TREND of Chemical Compostion in ", a, " Villages"),x="Chemicals",y="Number Of Cases",fill=paste0("Districts in", a))
return(an) }

so i pass the data with arguments,but i get this error.
> district_analysis(KERALA,bb,dd)
Error in labs(title = "TREND of Chemical Compostion in ", a, " Villages",  :
object 'KERALA' not found
Called from: labs(title = "TREND of Chemical Compostion in ", a, " Villages",
x = "Chemicals", y = "Number Of Cases", fill = "Districts in",
a)
Browse[1]> n

what might be the reason?
edited
------now the error------
It seems its not identifying "KERALA" as object.
Comment: As the error says, the number of columns in 'd' is 3 whereas you are passing a vector of 4 elements as `names`
Comment: you have numerous problems with strings and quotes - in your function, `have:train$State.Name=="a"` where you probably want a. Also, you should probably be quoting your 'KERALA' input
Comment: you are absolutely right but when i pass the arguments with double quotes also. i am getting a plot with nothing on it.Can you check the  code. i believe in the title tag also its not returning the value
Answer: The error is straight forward. You need to define 3 names and not 4 (I don't see CHEMICAL/Freq in the table you are creating one line above the when with the error)
Comment: yes , i have edited that. now it is not able to identify the state name i pass.Please help.


How can you show that $\int_3^\infty f(y)dy \lt \infty $ where $f(y)=\frac{e^y}{y^y}$?

Question: How can you show that $\int_3^\infty f(y)dy \lt \infty $ where $f(y)=\frac{e^y}{y^y}$ ?
Answer: Hint:
$$\frac{e^y}{y^y}\le\frac{\left(\frac{ey}3\right)^y}{y^y}=\left(\frac e3\right)^y$$
which holds for all $y\ge3$
Comment: Oh, whoops.  :P  My bad.
Answer: Hint
$$e^y \leq \left(\frac{e}{3}\right)^y y^y$$ for any $y\geq 3$. So $$\int _3^\infty e^y y^{-y}\,dy \leq \int _3^\infty \left(\frac{e}{3}\right)^y\,dy=\int _3^\infty \exp\left(y \log\left(\frac{e}{3}\right)\right)\,dy=\frac{e^3}{27 (\log (3)-1)}$$


Objeto Não Definido

Question: Estou com problemas com um objeto no Node.Js com Express.Js.
Ele está informando os seguinte erro.
Error: Route.get() requires callback functions but got a [object Undefined]
    at C:\contatooh\node_modules\express\lib\router\route.js:162:15
    at Array.forEach (native)
    at Route.(anonymous function) [as get] (C:\contatooh\node_modules\express\lib\router\route.js:158:15)
    at Function.app.(anonymous function) [as get] (C:\contatooh\node_modules\express\lib\application.js:421:19)
    at module.exports (C:\contatooh\app\routes\home.js:6:6)
    at module.exports (C:\contatooh\config\express.js:21:2)
    at Object.<anonymous> (C:\contatooh\server.js:5:38)
    at Module._compile (module.js:434:26)
    at Object.Module._extensions..js (module.js:452:10)
    at Module.load (module.js:355:32)

O código está aparentemente correto.
Arquivo de Rota
var controller = require('../controllers/home');

// app/routes/home.js
module.exports = function(app) {

    app.get('/index', controller.index );
    app.get('/', controller.index );
}

Arquivo do Contrller
// app/controllers/home.js
module.exports = function() {
    var controller = {};
    controller.index = function(req, res){
        //retorna a página index.ejs
        res.render('index', {nome: 'Express'});
    };
    return controller;
}

Arquivo de Configuração
var express = require('express');
var home = require('../app/routes/home');

module.exports = function(){
    var app = express();
    // Váriavel de Ambiente
    app.set('port', 3000);

    //middleware
    app.use(express.static('./public'));

    //Define qual view sera utilizada
    app.set('view engine', 'ejs');
    //Define onde novas views serão salvas
    app.set('views', '../app/views');

    home(app);
    return app;
}

Alguém pode me ajudar ?
Answer: Acho que defeniste o controller de forma errada. Como está exportas uma função e não o objeto controller , daí o erro.
Quando fazias var controller = require('../controllers/home'); a variável controler seria:
function() {
    var controller = {};
    controller.index = function(req, res){

onde faltam req e res, e onde nem sequer está acessível no escopo exterior o controller.
Faz assim:
// app/controllers/home.js
var controller = {};
controller.index = function(req, res){
    // retorna a página index.ejs
    res.render('index', {nome: 'Express'});
}

module.exports = controller;

Comment: Sergio Obrigado, deu certo!!!

Objeto Não Definido


QNetworkAccessManager:upload an executable file to apache server

Question: I am trying to upload an executable file to the server using this code:
<code>    QFileDialog dialog(this);
    dialog.setDirectory(QDir::home());
    QStringList fileNames = QFileDialog::getOpenFileNames(this,tr("Open File"));
    if(fileNames.count() == 1)
    {
        QFileInfo fi(fileNames.at(0));

    }
</code>
the path of file is the content of variable fileNames and i extract the filename from the path with fileNames.at(0).
How I can upload the file..
I am trying with this code but file is not uploaded:
<code> QByteArray postData;

 postData.append(path);

 QString url ="http://localhost/upload.php";
 //type header
 req.setHeader(QNetworkRequest::ContentTypeHeader,"multipart/form-data");
 req.setUrl(url);

 manager=new QNetworkAccessManager(this);
 reply=manager->post(req,postData);
</code>
...
Any help would be appreciated..
Answer: I have read the above thread,and i am trying with this piece of code but the problem remains..uploading fails:
<code> file=new QFile(path);
 file->open(QIODevice::ReadOnly);
 postData.append(file->readAll());

 QString url ="http://localhost/uploadFile.php";
 //type header
 req.setHeader(QNetworkRequest::ContentTypeHeader,"application/octet-stream");

 req.setUrl(url);

 manager=new QNetworkAccessManager(this);

 reply=manager->post(req,postData);
 connect(manager,SIGNAL(finished(QNetworkReply*)),this,     SLOT(replyFinished(QNetworkReply*)));
</code>
}
<code> //////php file///////

// The software package name
 $fileName = trim($_POST['fileName']);

// Make directory
mkdir("files/$fileName");

// Upload file
move_uploaded_file ($_FILES['upload'] ['temp_name'],  "files/$fileName/{$_FILES['uploadFile'] ['name']}")
</code>
Comment: And what about bigger files. You're reading... let's say 400MB file into memory at once. You can simply pass QIODevice to post, so QNetworkAccessManager will read it when it needs to put more data into socket.
Answer: Read Uploading a file using post() method of QNetworkAccessManager
Basically you need to create the data object to be posted on the heap not on the stack! Try creating your QByteArray on the heap and follow the answer to make it go away when request is finished.


How to create a set of css rules for safari

Question: Background
I'm fixing a web app with an iframe but the iframe behaves differently on the iPhone than other devices so I need to give it its own set of styling.
What I've tried
So I've tried a bunch of different styles and can get it to work mostly but not at the same time as the other mobile browsers. I need a way to point the styles to just the iphone safari browser.
I tried to write styles like this:
<code>html[data-browser="iPhone"] .signup-iframe{
  /* the styles */
}
</code>
Question
I put these changes on my server and then test on the iphone directly but it doesn't seem to get my new styles, why?
Comment: 1) Maybe it's better to go back to the beginning and consider what the differences in behaviour are. If there's a cause, maybe we can get rid of the cause rather than applying patches. 2) It looks like you're trying to give styles to iframe content from the container page, is that right? That won't work well.
Comment: yeah I thought so, but I've already tried stripping out the css. iphone and android treat iframe so differently I thought that adding styles to the individual devices would be the best solution. No I'm not trying to style the contense of the iframe, I'm styling the containing div it goes in (position, display height etc.).
Comment: Is your site live? I mean, can you provide a link?
Comment: its on a private server for work and I cant give it out, sorry. But what I don't understand is why the targeted css like above isnt working
Answer: ipods have different value in data-browser
It turns out that my code was working and that since I was using an old Ipod not an Iphone the value in data-browser was not matching up. It did, however work in Iphone when I checked on an Iphone 4 and Iphone 6.
Stupid mistake but hopefully this will help other people testing on an Ipod.


Não estou conseguindo ordenar as notas com o uso de struct

Question: Queria ordenar as notas dos alunos, só que não estou conseguindo fazer por que na hora de receber as notas estou utilizando o índice j, acho que isso é o problema só que não sei como resolver.
 #include<stdio.h>
 #include<stdlib.h>

double ordena(double *a, double *b);

struct notas
{
  double notas[3];
  char nome[100];
};

int main(void)
{
  int i, j;
  struct notas aluno[2];
  for(i = 0; i < 2; i++)
  {
    printf("Informe os nomes dos alunos :");
    scanf("%s", aluno[i].nome);
    system("cls");
    for(j = 0; j < 3; j++)
    {
        printf("Informe as notas do aluno %d:", j + 1);
        scanf("%lf", &aluno[i].notas[j]);
        system("cls");
    }
    system("cls");
   }
   for(i = 0; i < 2; i++)
   {
      for(j = i + 1; j < 3; j++)
       {
        ordena(&aluno[i].notas[j], &aluno[j].notas[j]);
       }
   }
   for(i = 0; i < 2; i++)
    {
      printf("Nome dos alunos %s:", aluno[i].nome);
       for(i = 0; i < 3; i++)
       {
        printf("%.2lf\n", aluno[i].notas[j]);
       }
  }
  system("pause");
  return 0;
}

double ordena(double *a, double *b)
{
  double o;
  if(*a > *b)
  {
    o = *a;
    *a = *b;
    *b = o;
  }
   return 0;
}

Comment: A função que tem chamada `ordena` na verdade não ordena e simplesmente troca valores de variaveis, o que se costuma chamar de `swap`. Comece por ler sobre bubblesort por exemplo, que é dos algoritmos mais simples de ordenação.
Answer: A função ordena que você escreveu não faz nada mais do que a troca dos elementos. O certo seria fazer a ordenação dentro da função. Ex:
void ordena(double vet[]) {
    int i, j;
    double aux;

    for (i = 1; i < 3; i++) {
        aux = vet[i];

        for (j = i - 1; (j >= 0) && (aux < vet[j]); j--) {
            vet[j + 1] = vet[j];
        }

        vet[j+1] = aux;
    }
}

Para ordenar é só chamar:
for(i = 0; i < 2; i++){
   ordena(alunos[i].notas);
}

E na hora de fazer a exibição dos valores você está usando a váriavel 'i' em 2 laços for diferentes no mesmo escopo. O certo seria assim:
for(i = 0; i < 2; i++){
     printf("Nome dos alunos %s:", alunos[i].nome);
     for(j = 0; j < 3; j++) {
        printf("%.2lf\n", alunos[i].notas[j]);
     }
}

E só para terminar evite sempre declarar variáveis com o mesmo nome da struct em que ela pertence, se não o seu código ficará difícil de ler. O que eu sugiro é que ao invés de 'notas', declares a struct com o nome 'Alunos' já que ela guarda informações sobre os alunos.


What is $B^{-1} y$? Linear Algebra/Matrices

Question: Link to problem
I have included the question and its solution in the image above. In the part where the solution says "we know that $y$ is in the span of $b_1$ and $b_2$ so $x_3 = 0$", I do not get how and why $x_3 = 0$?
Answer: In the $\mathbb{R^3}$ vector space we can take any $2$ vectors and use then to form a set of $3$ linearly independent vectors to form the basis of $\mathbb{R^3}$. A basis spans $\mathbb{R^3}$. So we can get $b_3$ from the linear combination of $b_1$ and $b_2$ and a $3rd$ linearly independent vector. This implies that $b_3$ can be written in form $b_3=c_1b_1+c_2b_2$. Now you can substitute this and observe why $x_3=0$.
Answer: '$y $ is in the span of the first and second column of $B $' is stated in the question. So basically we are told in the question statement that for some $x_1,x_2$, $y=x_1b_1+x_2b_2$.
Comment: You might want to add that $b_3$ is independent of $b_1, b_2$ (since $B$ is invertible) and thus $x_3 = 0$.
Comment: @Richard I see how b3 is independent of b1, b2 as B is invertible but can't the same be said about b1 and b2? For example, b1 and b2 each are independent of b3; now this won't make x1 and x2 = 0 would it?
Comment: No, since $y$ is in the span of $b_1$ and $b_2$. This simply means that you can write $y$ as $x_1b_1+x_2b_2$ for a specific choice of $x_1$ and $x_2$.


Python/Pandas - Unstack or Melt multidimensional table

Question: I'm having a beginning to the language issue with unpivoting a table. I'm hoping that it's just a vocabulary thing and I'll be off and running.  I have a table with three dimensions, within the dimensions, there are three elements and this table covers three time periods.  The tables that I work with are more complex than that, but this one is already ridiculously wide.

male_female
Total
Total
Total
Total
Total
Total
Total
Total
Total
M
M
M
M
M
M
M
M
M
F
F
F
F
F
F
F
F
F

adult_youth
Total
Total
Total
A
A
A
Y
Y
Y
Total
Total
Total
A
A
A
Y
Y
Y
Total
Total
Total
A
A
A
Y
Y
Y

urban_rural
Total
U
R
Total
U
R
Total
U
R
Total
U
R
Total
U
R
Total
U
R
Total
U
R
Total
U
R
Total
U
R

2021
46
22
24
22
11
11
24
11
13
22
8
14
5
1
4
17
7
10
24
14
10
17
10
7
7
4
3

2020
48
22
26
22
11
11
26
11
15
26
10
16
7
2
5
19
8
11
22
12
10
15
9
6
7
3
4

2019
50
22
28
22
11
11
28
11
17
30
12
18
9
3
6
21
9
12
20
10
10
13
8
5
7
2
5

I want it to look like:

year
male_female
adult_youth
urban_rural
Value

0
2021
Total
Total
Total
46

...

40
2020
M
A
U
2

...

80
2019
F
Y
R
5

I'm just at a loss on how to transpose it into something that can be pivoted or crosstabbed  with modifications. I've tried stack and unstack, melt, transpose, wide_to_long, but I just can't get the syntax, or the procedure for peeling off layer. This has been a manual process, but it's somethat that if I could master, would allow me to use Excel and Tableau less, and get more done.
Comment: What does your original table *actually* look like, paste the version you get from `print(df)` formatted as code. It's impossible to tell exactly what sort of MultiIndex columns going on or not.
Comment: Don't reply here, edit your question~
Comment: Change `pd.read_csv(...` to `pd.read_csv('df_pivoted.csv', header=[0,1,2], index_col=[0])` like I have below.
Comment: Thank you! In two lines of code, you have done what I was not able with hours of spaghetti code and Dr. Googling.
Answer: Reading a Multi-Dimensional Table in CSV format:
df = pd.read_csv('df_pivoted.csv', header=[0,1,2], index_col=[0])

...

male_female Total                                         M                                      F
adult_youth Total             A             Y         Total             A           Y        Total             A            Y
urban_rural Total   U   R Total   U   R Total   U   R Total   U   R Total  U  R Total  U   R Total   U   R Total   U  R Total  U  R
2021           46  22  24    22  11  11    24  11  13    22   8  14     5  1  4    17  7  10    24  14  10    17  10  7     7  4  3
2020           48  22  26    22  11  11    26  11  15    26  10  16     7  2  5    19  8  11    22  12  10    15   9  6     7  3  4
2019           50  22  28    22  11  11    28  11  17    30  12  18     9  3  6    21  9  12    20  10  10    13   8  5     7  2  5

Doing:
df.index.name = 'year'
out = df.unstack().reset_index(name='value')
print(out)

Output:
   male_female adult_youth urban_rural  year  value
0        Total       Total       Total  2021     46
1        Total       Total       Total  2020     48
2        Total       Total       Total  2019     50
3        Total       Total           U  2021     22
4        Total       Total           U  2020     22
..         ...         ...         ...   ...    ...
76           F           Y           U  2020      3
77           F           Y           U  2019      2
78           F           Y           R  2021      3
79           F           Y           R  2020      4
80           F           Y           R  2019      5


Need help reprogramming a short batch program to macOS bash

Question: I've written a batch program (long time ago now) to backup my data from one external drive to another. It scans the drive, makes a directory file of all the folders in it, and counts the number of lines (and thus folders). From there it reads from that file, one line at a time, and copies the contents of each folder in the list in the directory file to the other drive, only copying what was new or modified from the last time it copied, and if something was on the backup drive, that had been deleted from the source drive, it left it there. It just kept adding, not deleting. This was intentional, don't worry.
Here is the script:
@echo off

set /p Drive=The Archive Drive Letter:
cls
set /p Drive2=The Archive II Drive Letter:

dir %Drive%:\ /B >directory

@setlocal enableextensions enabledelayedexpansion

set lines=0

:the
set location=directory

set /a "lines = lines + 1"

set curr=1
for /F "delims=" %%a in ('type %location%') do (
    for %%b in (!lines!) do (
        if !curr!==%%b set foldername=%%a
    )
    set /a "curr = curr + 1"
)

xcopy "%drive%:\%foldername%" "%Drive2%:\THE ARCHIVE Backup\%foldername%\" /S /M /Y

timeout -t 2

goto :the

endlocal

I need help with making an identical program to run under MacOS bash.
I have experimented with the equivalent commands and researched how things are done in bash, but I have very limited experience with using MacOS.
I appreciate that some things are done differently under bash, such as drive naming. In my batch script above, I have a call for a user variable to confirm the drive letters, but that was only a failsafe in case drive letters change (as they do). However under MacOS drives are called via names, which I won't be changing so that part of the code I'm happy to remove.
In my specific case,
The source drive is located at "/Volumes/The ARCHIVE"
The destination drive is located at "/Volumes/The ARCHIVE II"
Any help is much appreciated, and I'm happy to take on any ideas that may improve my somewhat messy approach to things.
Thanks!
Edit:
I ran the command (with the -n switch), and after having some difficulties with the "bad interpreter" error, which I've solved, I'm returned a list of all my files on the source drive. I assume this will return to none after one backup, and only subsequent changes on the source drive??
Also, I'm returned a line that says "total size is 528045001932" I assume this is in bytes, and therefore when converted to gigabytes comes to 528GB, or 491GB (depends on 1024 vs 1000 bytes per kilobyte). Only thing is, my total amount of data on the source drive is more than that. Does that mean that rsync has missed some data, or has it skipped some of it because it found matches on the destination drive?
Comment: Try using `rsync`, it's included in bash (`man rsync`)...
Comment: `rsync` is *not* included with `bash`; it is a completely separate program that you can start from `bash` (or any other shell, for that matter). It may or may not be installed already.
Comment: I did notice that, especially when reading the man page for it. For me it's installed with MacOS, and so I assume it is with others, but thanks for pointing that out anyhow :)
Comment: [This should be a good reference](https://ss64.com/osx/).
Comment: Thanks for the rsync suggestion. I'm giving it a go now, and I'll let you know how it works out. This should make things a lot simpler than my setup I had with windows.
Comment: @chepner: That is what I meant; anything that is already available to use within bash without having to install it separately is technically *included* (as a tool in available in bash) — at least from where I sit :)
Comment: Whether or not you need to install `rsync` separately is completely dependent on your operating system or distribution; it has nothing to do with `bash`.
Answer: Just use rsync.  You could set a cron job to run a bash script that rsync's one directory to another.
just save the following as something like copier.sh
#!/bin/bash
rsync -rv /Volumes/ARCH /Volumes/ARCH2

then add the file to crontab.
Check the man pages for rsync and crontab if you need help
EDIT:
I forget MacOS prefers you to use launchd now. You should read up on how to use launchd but I'll give you an example that may or may not work.
Create a plist file called something like com.directoryCopier.plist and place it in the /Library/LaunchDaemons directory.  The file should look something like this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.directoryCopier</string>
    <key>ProgramArguments</key>
    <array>
        <string>/Users/Path/To/copier.sh</string>
    </array>

    <key>StartInterval</key>
    <integer>86400</integer>

    <key>StandardErrorPath</key>
    <string>/tmp/copier.err</string>

    <key>StandardOutPath</key>
    <string>/tmp/copier.out</string>

    <key>RunAtLoad</key>
    <true/>
</dict>
</plist>

Start the service by rebooting or by entering the command
sudo launchctl load /Library/LaunchDaemons/com.directoryCopier.plist

You can read more here
https://developer.apple.com/library/content/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html
I probably left some stuff out but I'm sure someone will correct me.
Good luck
Comment: @mklement0 you are correct.  I edited my answer, thanks.
Comment: I just saved as a .command, with the rsync command inside and that works just fine for me. Thanks for everyones help


Gradient descent converges after $ T \leq O(\log(1/\varepsilon))$ iterations for $f(x)=x^T A x$ where $A$ is positive definite matrix

Question: Let $f(x)=x^T A x$, where $A$ is a positive definite matrix ($A \succ 0$).
I need to show that there exists a step size  $\eta$   such that $ T \leq O(log(1/\varepsilon))$ iterations of gradient descent are sufficient to achieve $\varepsilon$-optimal solution (i.e.
  $f(w_T)\leq\varepsilon$ ).
I have proven the following:

$\nabla f(x)=2A$, so the next step for gradient descent is  $w_{t+1}=w_t-\eta\cdot\nabla f(w_t)=w_t-\eta \cdot2Aw_t=(I-2\eta A)w_t$
Let $B=(I-2\eta A)$
Let $\lambda > 0$ be eigenvalue of $A$ with the corrseponding eigenvector $v\neq0$.
So $Bv=(I-2\eta A)v=Iv-2\eta Av=v-2\eta \lambda v=(1-2\eta\lambda)v$.
Hence, $1-2\eta\lambda$ is eigenvalue of $B$ with eigenvector $v$.
Choose $\eta$ such that $0<1-2\eta\lambda<1$, or equivalently $\eta < \frac{1}{2\lambda}$
Notice that if $v$ is eigenvector of $A$, so $f(v)=v^TAv=v^T\lambda v =\lambda \lVert v \lVert^2$
$f(x)=x^TAx$ is convex, so $f(\lambda x)\leq \lambda f(x)$.
Now, set $w_1$ (starting point) for the gradient descent be an eigenvector of $A$ with the corresponding eigenvalue $\lambda $.
As shown above, that if $w_1$ is an eigenvector of $A$ with eigenvalue $\lambda$, it follows that $1-2\eta\lambda$ is an eigenvalue of $B$. So inductivly $w_{t+1}=Bw_t=(1-2\eta\lambda)^t w_1$.
Now, using all this information, we get

$\begin{align*} f(w_{t+1})=f(Bw_t)=f((1-2\eta\lambda)^t w_1) \leq (1-2\eta\lambda)^t \cdot f(w_1)=(1-2\eta\lambda)^t \lambda \lVert v \lVert^2 \end{align*}$
We want $f(w_{t+1}) \leq \varepsilon$, so    $(1-2\eta\lambda)^t \lambda \lVert w_1 \lVert^2 \leq \varepsilon$
Now after solving for $t$, I got
$\begin{align*} t \geq \frac{1}{\ln{(1-2\eta \lambda)}}\cdot -\ln{(\frac{\lambda\cdot \lVert w_1 \lVert^2}{\varepsilon})} \end{align*}$
The problem is that $1-2\eta \lambda \leq 1$ so $\ln{(1-2\eta \lambda)}<0$ and it breaks the ineqality.

If anybody could help me finding the mistake or solving this problem.
Notice: I need to show that without using Lipschitz property.
Thank you in advance.
Answer: This is solved. It came to my mind that
$$ t \geq \frac{-\ln{(\frac{\lambda\cdot \lVert w_1 \lVert^2}{\varepsilon})}}{\ln{(1-2\eta \lambda)}}$$
On the RHS we have a positive number (because $0 <(1-2\eta \lambda) < 1$  so  $\ln{(1-2\eta \lambda)<0}$.
This means that it is enough to have $T=O(\log(1/\varepsilon))$ steps to get to $\varepsilon$-accuracy (and of course any more steps will give us a better bound, but it still works).
Hope it helps someone.


Logging specific successful SSH login and disconections

Question: Good Day,
I have trying to log successful ssh login and disconnection times for specific users. i.e. I would like to trigger a bash script when the ssh connection is established and when it is closed.
I have been trying to comprehend the PAM.d modules without much success except that pam_exec may be what I am looking for.
Here is the journalctl log when the user I am after disconnects and then reconnects:
May 31 00:47:31 myhostname.com sshd[11517]: Connection closed by 188.8.131.52
May 31 00:47:31 myhostname.com sshd[11517]: Transferred: sent 10160, received 12196 bytes
May 31 00:47:31 myhostname.com sshd[11517]: Closing connection to 22.214.171.124 port 24976
May 31 00:47:31 myhostname.com sshd[12377]: pam_unix(sshd:session): session closed for user myuser
May 31 00:47:31 myhostname.com systemd-logind[4406]: Removed session 24778.
May 31 00:47:52 myhostname.com sshd[11964]: Connection from 184.108.40.206 port 24989 on 22.214.171.124 port 22
May 31 00:47:55 myhostname.com sshd[11964]: Postponed publickey for myuser from 188.8.131.52 port 24989 ssh2 [preauth]
May 31 00:47:56 myhostname.com sshd[11964]: Accepted publickey for myuser from 126.96.36.199 port 24989 ssh2: RSA SHA256:R0y/xxxxxxxxxxxxxxxx/HuC6vZp/xxxxxxxxxxxxxx
May 31 00:47:56 myhostname.com sshd[11964]: pam_unix(sshd:session): session opened for user myuser by (uid=0)
May 31 00:47:56 myhostname.com systemd-logind[4406]: New session 24786 of user myuser.
May 31 00:47:56 myhostname.com systemd[1]: Started Session 24786 of user myuser.
May 31 00:47:57 myhostname.com sshd[11964]: User child is on pid 12009

Is there an efficient (possibly PAM) way to execute a script when the "session" is closed and opened for "myuser?
And if possible would it be possible to expose the associated PID as shown in the last line?
Thanks
Answer: So, after a lot of searching and experimentation. I came to realization that neither PAM nor all the fancy features of ssh and its daemon could be used to achieve my objective. I found out that establishing an ssh reverse tunnel using the -N option is not the same as a normal ssh login. I'll attempt to explain why.
With that out the way this is what I had done.
SSH Access Control is quite nicely summarized in this article. Which illustrates where PAM fits into the SSH process. PAM allows for various "modules" to supplement and enhance the authentication/login process. One such module which I eluded to in my question was pam_exec(). Which I included at the end of the /etc/pam.d/sshd file as follows:
    session    optional    pam_exec.so debug log=/tmp/pam_exec.log seteuid /usr/local/bin/login_auth

The idea was, when a user establishes an ssh connection this would fire of a script that could log/take some action. The script worked however the "shell" in which the command is executed is limited in that is only has a minimal set of session information. i.e. normal SSH environment variables like SSH_CONNECTION were not available and any environment variables sent from the the remote client (-o SendEnv=LC_MYVAR) were also not available (LC_MYVAR). Turns out this is only true for reverse tunnel type ssh connections which do not typically establish a shell thanks to the -N option.
Anyhow, one could very nicely use the above method to capture the username and ip of any connection and even further information like SSH_CONNECTION for interactive logins.
I need to clarify at this point what I was trying to achieve. I have multiple devices in the "field" that are programmed to establish a reverse ssh tunnel when they can. The idea was to monitor server side when each device connects and disconnects thereby having visibility on connection issues. The problem is that I set them all up with the same user and sshkey. So to differentiate them is only possible on remote port that I set for them to be available through. 2222, 2223,2224,2225,2226, etc. I need to obtain and log this information on connection and disconnection.
Finally I have had to concede and use a log tail approach like:
tail -F /var/log/auth.log | grep "Connection closed by" | /usr/bin/myscript