Contractible manifold that is not uniformly contractible?

Question: I'm looking for an example of a contractible Riemannian manifold which is not uniformly contractible.
Definition: Let $ X $ be a metric space. We say $ X $ is uniformly contractible, if for all $r>0$ we have a $R>r$ such that
every $r$-ball $ B_r(x) $ around any point $ x \in X $ is contractible inside the
bigger ball $ B_R(x) \supset B_r(x) $.
In general I'm quite unclear about the notion of uniform contractibility. Is there any references which I can look at?
Comment: You misstated the definition of uniform contractibility. Which books on coarse geometry and geometric group theory did you check?
Comment: @MoisheKohan Could you please tell me what the correct definition is? Also right now I'm looking at John Roe's "Lectures on coarse geometry". He says "X is uniformly contractible if, for every $R>0$ there is $S>0$ such that, for every $x \in X$, the inclusion $B(x;R) \to B(x; S)$ is nullhomotopic".
Comment: That's the right definition. Now compare to what you wrote. It is all about the right order of quantifiers.
Comment: Thanks for pointing it out. Edited it.
Answer: Start with a sequence of round 2-spheres $S(x_i, i)$ of the radius $i$. Now, remove from each sphere an open  spherical cap with the perimeter of the unit length. The result is a contractible surface $S_i$ with boundary $C_i$ with the path metric induced from the sphere. But the contractivity function diverges to infinity as $i\to \infty$ because you need the entire surface to contract the circle $C_i$ to a point. Next, you want to connect the surfaces $S_i$ to form a contractible space. The simplest thing to do is just to wedge them at one point and take a path-metric. That's your example. With a bit more thought, you can modify this example to get a contractible Riemannian surface which is not uniformly contractible. You drill countably many holes in the plane so that each hole has unit circumference. Attach $S_i$ along the boundary of each hole. Lastly, smooth out the metric along each $C_i$.
Comment: perfect, thanks.


Object reference not set to an instance of an object error on response

Question: I am getting Object reference not set to an instance of an object. error on SoapUI. I used loggers to check if record holds the right StartTime and EndTime but for some reason I get that error when I try to add the record object which contains userId and TimePeriod into the response. Also, result is the variable which has the info returned from the DataAccess layer. Any help on this will be appreciated.
GetUserResponse response = new GetUserResponse();
UserRecord record = new UserRecord();
record.UserId = userId;
record.timePeriodList = new List<TimePeriod>();
for (int i = 0; i < result.Count; i += 2)
{
    TimePeriod timeData = new TimePeriod();
    timeData.StartTime = result[i].Time;
    timeData.EndTime = result[i + 1].Time;
    record.timePeriodList.Add(timeData);
}
response.UserRecordList.Add(record); // line I get that error

Here is the code to my response:
public class GetUserResponse
{
    private List<UserRecord> userRecordList;

    public List<UserRecord> UserRecordList
    {
        get { return userRecordList; }
        set { userRecordList = value; }
    }
}

public class UserRecord
{
    private string userId;
    private List<TimePeriod> timePeriodList;

    public string UserId
    {
        get { return userId; }
        set { userId = value; }
    }

    public List<RbeActivationPeriod> TimePeriodList
    {
        get { return timePeriodList; }
        set { timePeriodList = value; }
    }
}

public class TimePeriod
{
    private DateTime startTime;
    private DateTime endTime;

    public DateTime StartTime
    {
        get { return startTime; }
        set { startTime = value; }
    }

    public DateTime EndTime
    {
        get { return endTime; }
        set { endTime = value; }
    }
}

Comment: Where is `response` declared? Is `userRecordList` instantiated?
Comment: I can't see it in your code but I assume that you have instantiated your variable response?
Comment: @erik I edited the post for you. Sorry forgot the declaration on the post.
Comment: @DarrenDavies yes response is declared. Does userRecordList need to be initiated? I have edited the post to reflect changes. Thanks
Comment: Problem line is `timeData.EndTime = result[i + 1].Time;`
Comment: Why do you suspect that? `record` holds the right info from what got returned from the logger @Satpal
Comment: I'm thinking you need to declare a new instance of userRecordList
Answer: You need to declare a new instance of the list UserRecordList as it will be null when you attempt to insert an element.
GetUserResponse response = new GetUserResponse();
response.UserRecordList = new List<UserRecord>();

Alternatively you can add this at the class level or in the constructor.
public class GetUserResponse
{
    private List<UserRecord> userRecordList = new List<UserRecord>();

    public List<UserRecord> UserRecordList
    {
        get { return userRecordList; }
        set { userRecordList = value; }
    }
}

Comment: It says `Index was out of range. Must be non-negative and less than the size of the collection.` on that response.add line now
Comment: @user4756836 - most likely this line `timeData.EndTime = result[i + 1].Time;` however this is a different question so you should accept this as the answer (It appears to have solved your problem) and repost a new question with the index out of range exception.


Um pouco mais sobre File.WriteAllBytes

Question: Como exibir um progresso sincronizando a seguinte função:
File.WriteAllBytes(string path, byte[] content);

Esse método deve ser chamado de acordo com um System.Threading.Thread
Ex:
Thread wnd;
string wnd_file;
byte[] wnd_bytes;

void Install(string path, byte[] content){
   wnd_file=path; wnd_bytes=content;
   wnd = new Thread(new ThreadStart(BackgroundProgressTASK));
   wnd.Start();
}

void BackgroundProgressTASK(){
  File.WriteAllBytes(wnd_file, wnd_bytes);
}

Desse modo o aplicativo não sofra nenhuma travada durante o momento em que escreve o arquivo!
Answer: Não dá. Este método é bloqueante mesmo. Ele deve executar por completo sem interferência externa. Você pode criar thread (e esta forma nem é a mais recomendada de fazer isso) que não vai resolver. O único jeito é criar um método que vá escrevendo aos poucos onde você tenha controle.
A pergunta está um pouco confusa. Para fazer o indicador de progresso não é necessário ter uma thread ou outro mecanismo semelhante. Se quer que todo o aplicativo continue livre para executar a melhor forma é usar uma técnica de as assincronicidade no método todo que faz o que você deseja. Veja um exemplo nessa resposta.
Note que tentar executar GUI com threads diferentes você não consegue executar GUI em mais de uma thread. Pelo menos não em condições normais. O que dá para fazer é usar um BackgroudWorker (tem um exemplo de indicador de progresso). Simplificando seria algo assim (não testei):
var backgroundWorker = new BackgroundWorker(); //estará fora do método de escrita

using (var stream = new FileStream(wnd_file, FileMode.OpenOrCreate)) {
    using (var writer = new BinaryWriter(stream)) {
        var remain = wnd_bytes.Length;
        var written = 0;
        while (remain > 0) {
            var size = Math.Min(4096, remain);
            writer.Write(wnd_bytes, written, size);
            written += size;
            remain -= size;
            backgroundWorker.ReportProgress(written * 100 / wnd_bytes.Length);
        }
    }
}

Coloquei no GitHub para referência futura.
Na documentação existe um exemplo de como escrever um método de escrita assíncrono. Mas se entendi o que você descreveu, não precisa disto.
Comment: Ok, se ainda tiver outras dúvidas é só ir criando perguntas.
Comment: então seu código me ajuda bastante mas o que eu quero é simplesmente criar um programa que realizasse a instalação de outro programa sem importar arquivos do tipo .zip ou outros!
Comment: outra coisa é eu tentar aplicar um thread em WebBrowser.Navigate("http://google.com") o Thread é iniciado mas a não tem ação nessa função!

Um pouco mais sobre File.WriteAllBytes


Date field Start and End limit

Question: When we create a date field in node form, we can set START and END years to be shown in that date field.
If we are creating a date field programatcaly, how do we do that?
I have a date field, my_date, I want to to show only next 5 years from now on.
Any help?
$form['my_date'] = array(
  '#type' => 'date',
  '#date_format' => 'd-m-y',
  '#default_value' => format_date($primary_start1, 'custom', $format),
  '#date_type' => DATE_DATETIME,
  '#date_timezone' => date_default_timezone(),
  '#date_format' => 'm/d/Y',
  '#size' => 20,
  '#access' => TRUE,
);

I tried to see structure bu creating a date field and printing the form, but found nothing.
Answer: We can do it like this...
$form['my_date'] = array(
  '#type' => 'date',
  '#date_format' => 'd-m-y',
  '#default_value' => format_date($primary_start1, 'custom', $format),
  '#date_type' => DATE_DATETIME,
  '#date_timezone' => date_default_timezone(),
  '#date_format' => 'm/d/Y',
  '#size' => 20,
  '#access' => TRUE,
  '#after_build' => array("custom_range_date")
);

using '#after_build' => array("custom_range_date")
function custom_range_date($form_element, &$form_state){
    // We unset the current values
    unset($form_element['year']['#options']);

    // Now we set the range we want
    $max_age = date('Y') - 100; // 100 years ago
    $min_age = date('Y') - 7; // 7 years ago

    // Now we populate the array
    $form_element['year']['#options'] = array();
    foreach (range($max_age, $min_age) as $year){
        $form_element['year']['#options'][$year] = $year;
    }

    // We return our modified element
    return $form_element;
}

SEE: https://www.drupal.org/node/1165138

Date field Start and End limit


How to Fire a Method When the Component Changes in Angular

Question: In Angular,
There is a ngOnInit() method in component.
I want the opposite of this method. Is there any method when the component is closed ?
Is there a way to catch in its TypeScript file if the component is closed ?
I mean,
ExampleComponent.TS

    ngOnInit() {
        // opened component
    }

    ????() {
        // closed component
    }

Answer: ngOnDestroy is what you need. It's called right before the component has been disposed.
Comment: Thanks. @PampaZiya


SQLite com Javascript não funciona

Question: Estou conhecendo o SQLite agora, para tentar implantar em uma aplicação mobile, fiz este teste baseado em alguns códigos da web mas não consigo retornar uma gravação dos dados com sucesso, até faz o select mas retorna 0 registros, como mostra o trecho: alert(r.rows.length);
var db = openDatabase("appLocal", "1.0", "base de dados da aplicacao",

200000);

// criando a tabela caso ela não exista
db.transaction(function(transaction){
    transaction.executeSql('CREATE TABLE IF NOT EXISTS tb_teste ("teste" TEXT)', [], null, db.onError);
    alert("criou");
});

// aqui vai o insert
db.transaction(function(transaction){
  transaction.executeSql("INSERT INTO tb_teste(teste) VALUES('testex');", db.onSuccess, db.onError);
    alert("inseriu");
});

// consulta no banco
db.transaction(function(transaction){
    transaction.executeSql("SELECT * FROM tb_teste", [], db.getResults, db.onError);
    alert("selecionou");
});

// função callback de erro
db.onError = function(transaction, e) {
  alert("Aconteceu um erro!");
  console.log(e.message);
}

// função de callback de sucesso de insert
db.onSuccess = function(transaction, e) {
  alert("Dados Gravados com Sucesso!");
  console.log(e);
}

// função temporaria que lista resultados
db.getResults = function (transaction, r) {
    //console.log('deu certo!');
    //console.log(r);
    alert(r.rows.length);

   for(var i = 0; i < r.rows.length; i++){
       alert(r.rows.item(i)[['teste']]);
       alert("rodou");
   }
}

Answer: O problema está acontecendo na chamada da função transaction.executeSql para inserir dados na tabela.
Essa função não aceita parâmetros de callback para erro ou sucesso (testado no Google Chrome, mas para outros browsers, pode funcionar de forma diferente).
A linha de comando para fazer o INSERT deve ficar assim:
transaction.executeSql("INSERT INTO tb_teste(teste) VALUES('testex');")

ou assim:
transaction.executeSql("INSERT INTO tb_teste(teste) VALUES(?);", ['testex']);

Veja funcionando no jsfiddle

Uma dica:
Conforme a documentação Web SQL Database - W3C, esta API (SQLite) está obsoleta e o seu uso não é recomendado.
Para armazenar dados no cliente, você pode utilizar:

Indexed Database API
Web Storage

SQLite com Javascript não funciona


Não consigo posicionar lista

Question: Galera não tô conseguindo posicionar a lista com id sub1 usando css, a outra tá posicionando normal. Não tô conseguindo saber o por que, alguém pode me ajudar?
Segue o codigo:

        <title>Menu</title>

Menu1

Menu2

Menu3

Menu4

Menu5

opcao1

opcao2

opcao3

Answer: Provavelmente é por causa do css dos submenus...
Tenta colocar cada #menu li -> position: relative
Depois disso, você ajusta cada submenu (position: absolute) com top e left.
EDIT:
Criei um exemplo funcionando no codepen pra você entender melhor:
http://codepen.io/Gabcoder/pen/oYwdZK
Dicas:

Use classes em vez de id quando houver repetição de css.
Atributos como text-decoration: none; são desnecessários, pois já são definidos assim por padrão.
Comment: tentei, nada aconteceu
Comment: Conseguiu? Se a resposta te ajudou, não se esqueça de avaliar ;)
Answer: Se ele é um sub menu, ele deve ficar dentro do principal:

Menu1

opcao1

opcao2

opcao3

Menu2

Menu3

Menu4

Menu5

Não consigo posicionar lista


Translating a site where default is in two languages

Question: Drupal is written in English. We have created some custom modules where the strings in the module are written in French. These are passed through the t() so can be translated.
I am a little confused how I can show my site in both French and English when the default site language English is in both language. Please could you point me in the correct direction?
Comment: Are you using the langcode option in https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/t/7 to specify that the custom strings are fr?
Comment: No just a standard t() in the module.
Answer: When you pass string through t() without specifying a langcode, then it will default back to English.
So, if string is a French word, it will be handled as an English word.
Two options:

Always use English words in t() and use the translate interface to
translate it to French.
As per https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/t/7
set the langcode as such t($string, $args = array(), $options =
array('langcode' => 'fr'))
Comment: It's probably worth saying that the implication of this is that every call to t() in the custom modules needs to be recoded to change the text string to English. Once that's done you can create a fr.po file for the module, with trasnslations for all the strings into French.
Answer: I'm not sure from your question whether you have successfully got your site working in both English & French, just in case, have you reviewed everything at https://localize.drupal.org/translate/languages/fr
It is normal practice that if you're writing custom modules which will be used across multiple languages, the strings in the module are written in English, as you point out that Drupal is written in English, then provide a translation using po files


Self executing functions in python

Question: I have used occasionally (lambda x:)(<some input>) in python, to preserve my namespace's (within the global namespace or elsewhere) cleanliness.  One issue with the lambda solution is that it is a very limiting construct in terms of what it may contain.
Note: This is a habit from javascript programming
Is this a recommended way of preserving namespace?  If so, is there a better way to implement a self-executing function?
Comment: In what situation do you want to do this where you couldn't just write a separate function and call it?
Comment: For example, if I wanted to string several function calls inside each other, but didn't want to pollute the namespace with a function that would only be called in a specific place.
Answer: Regarding the second half of the question

is there a better way to implement a self-executing function?

The standard way (<function-expression>)() is not possible in Python, because there is no way to put a multi-line block into a bracket without breaking Python's fundamental syntax. Nonetheless, Python do recognize the need for using function definitions as expressions and provide decorators (PEP318) as an alternative. PEP318 has an extensive discussion on this issue, in case someone would like to read more.
With decorators, it would be like
evalfn = lambda f: f()

@evalfn
def _():
    print('I execute immediately')

Although vastly different syntatically, we shall see that it really is the same: the function definition is anonimous and used as an expression.
Using decorator for self-excuting functions is a bit of overkill, compared to the let-call-del method shown below. However, it may worth a try if there are many self-execution functions, a self-executing function is getting too long, or you simply don't bother naming these self-executing functions.
def f():
    print('I execute immediately')
f()
del f

Answer: For a function A that will be called only in a specific function B, you can define A in B, by which I think the namespace will not be polluted. e.g.,
Instead of :
def a_fn():
    //do something
def b_fn():
    //do something
def c_fn():
    b_fn()
    a_fn()

You can:
def c_fn():
    def a_fn():
        //do something
    def b_fn():
        //do something
    b_fn()
    a_fn()

Though I'm not sure if its the pythonic way, I usually do like this.
Comment: However, this is no different from what JavaScript does.
Comment: this is not solution, because, we must call c_fn()
Comment: I never realized this, coming from a javascript background, but I just realized that python creates namespaces for functions.
Comment: @Justanotherdunce: Functions defined inside a function are simply additional local variables. In effect, this is a little like a namespace.
Comment: Isn't there anything like main function like in Java in python that allows self execution?
Answer: You don't do it. It's a good in JavaScript, but in Python, you haven either lightweight syntax nor a need for it. If you need a function scope, define a function and call it. But very often you don't need one. You may need to pull code apart into multiple function to make it more understandable, but then a name for it helps anyway, and it may be useful in more than one place.
Also, don't worry about adding some more names to a namespace. Python, unlike JavaScript, has proper namespaces, so a helper you define at module scope is not visible in other files by default (i.e. unless imported).

Self executing functions in python


What type of hosting do I need? Informational site using Drupal, MYSQL, PHP, and more

Question: A few friends and myself are working on a game for Android. I am looking to create a site that people can visit to be informed and updated about this game. It is mostly informational but in the future it could grow and I would possibly implement drupal and store login credentials in a DB.
What do I "need" in a hosting service from what I have described? They offer all sorts of security and stuff for $239437.33. I don't think I "need" these things.
In addition to what I need, who matches those needs?
Comment: You need to define your requirements and then sit down with various hosting providers to see what they have that meets your needs.  None of the Stack Exchange sites can do this for you, though we are happy to help if you have specific questions.
Comment: Try asking your favorite webhost; they usually have support people where you can tell them what you want (Drupal + MySQL + PHP) and they'll tell you the cheapest plan that can do it (which should be **very** cheap, those are low requirements)
Comment: You'll probably find better answers for this on webmasters.SE, shopping questions are typically considered off-topic for ServerFault.
Answer: I'd probably start with shared hosting that offers PHP (version 5.2+) and MySQL.  If you can find one with a Drupal auto-installer, even better.  I assume the store will be a Drupal module, in which case you'll probably only need one database.
If you're in the UK, I'd recommend Heart Internet (the Home Pro package offers what you need, they have auto-installers too).
If the site starts getting busy, you can start thinking about a VPS, but shared hosting is much cheaper and easier and sufficient in many cases.
Comment: Thank you very much for this answer! I've been asking around trying to find the appropriate place to ask. Sorry for being out of the context of serverfault. I'd vote up but I'm at -2 rep LOL :D
Answer: I would actually recommend a VPS if you're willing to take on the technical requirements. A VPS gives you root access to a server of your choosing.
AWS and Linode are two great options(AWS is free for a micro). If you're not technically inclined enough to take on a server; look for a host that offers php/mysql(most do) and that should do you. I would shy away from a hosting provider that offers anything 'unlimited' though.


Copy settings from one Web.config to another except AppSettings and ConnectionStrings

Question: Is it possible, through code, to copy settings from one Web.config file to another (except AppSettings and ConnectionStrings)?
I have a situation where a single MVC3 project has been deployed to multiple servers in different locations. There is an auto-updater on all of these that will pull in the latest version. Typically when this would run, it would only overwrite the application folders and NOT the Web.config file.
I just upgraded the project to MVC4. This changes basically everything in the Web.config file except the AppSettings and ConnectionStrings. All of the installations of this project would have slightly different values here.
How would I go about writing some code that will update the Web.config file, but preserve all of the AppSettings and ConnectionStrings?
Answer: .NET provides ways to get configuration from other config file. Refer this article:http://blog.andreloker.de/post/2008/06/Keep-your-config-clean-with-external-config-files.aspx
Basically, you can use "configSource" attribute to define which config file to refer. Note that the configuration file should be in same directory. if not, Refer here to solve the problem. .NET Config Files configSource outside the application directory folder


Predefined field collection items in node edit form

Question: I have a Products taxonomy with all possible product names offered by the organization, Order content type to place an order and ordering form. Order content type includes field collection with term reference field referencing to Product taxonomy. The case is that I need to predefine field collection items with all possible selected Product terms on ordering form.
Items number = count(Products terms)
I tried to use field_multiple_value_form function to generate items, but in this case I can't predefine default value for field inside field collection item (or can?).
<code>$products_taxonomy = taxonomy_vocabulary_machine_name_load('products');
$product_tree = taxonomy_get_tree($products_taxonomy->vid);

if (is_array($product_tree)) {
  $field_instance = field_info_instance('node', 'field_fc_o_position', 'order_request');
  $field_instance['cardinality'] = count($product_tree);
  $field_instance['type'] = 'field_collection_item';
  $field_instance['columns'] = array();

  $form_state['field']['field_fc_o_position'][LANGUAGE_NONE]['items_count'] = count($product_tree);
  $instance = $form_state['field']['field_fc_o_position'][LANGUAGE_NONE]['instance'];

  $form['field_fc_o_position'][LANGUAGE_NONE] = field_multiple_value_form(
    $field_instance,
    $instance,
    LANGUAGE_NONE,
    array(),
    $form,
    $form_state
  );
}
</code>
Question is how to generate empty field collection items on ordering form and default value for select field inside each new item?
Thank you!
Answer: I do not think that this will work in the way you wish, since Field Collections are entities rather than normal fields.
It sounds to me like you need to use form_alter to update your input form.
Checkout this link on Drupal.org for one method that might work:
Finally - found a solution... (D7)


Firebase + Android + Spring para criar microserviços

Question: A ideia é a seguinte:
Eu tenho uma aplicação em android que irá consumir meus serviços que eu irei criar usando Spring. Entretanto, esses serviços devem ter alguma segurança, onde apenas pessoas autenticadas no meu aplicativo podem consumir tais serviços.
Já na minha aplicação Android eu irei usar o Firebase para controlar as autenticações, usando email e senha. Assim, eu não irei precisar configurar nada de segurança no meu servidor, como por exemplo usar o Spring OAuth2.
Minha dúvida é: Assim que o usuário se autenticar no meu aplicativo e em seguida ele quiser consumir algum serviço que eu disponibilizei usando o Spring no Servidor, como por exemplo um GET LIST de alguma coisa, como eu valido que o usuário está autenticado no meu aplicativo, e assim eu posso dar acesso a ele ao serviço pedido?
Answer: Você pode checar se ele está logado, pela documentação temos o seguinte método:
<code>mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
            } else {
                // User is signed out
                Log.d(TAG, "onAuthStateChanged:signed_out");
            }
            // ...
        }
    };
</code>


Envio de dados entre Activitys com PutExtra - Gerenciamento

Question: Estou com o seguinte problema:
Tenho três telas:

Main
Activity 2
Activity 3

Na primeira Activity (Main) eu mando um dado por putExtra para a Activity 2 (id usuario). A Activity 2 é a tela de perfil, e em determinado momento eu mando para uma terceira Activity (ex: tela visualização foto).
Até ai funciona com o envio PutExtra e GetExtra. O problema está quando eu clico no botão voltar, está dando um erro e parando a aplicação.
Até já procurei e tentei implementar algo como startActivityForResult, mas não compreendi direito e não funciona.
O problema está especificamente na volta da Activity 3 para Activity2, pois mesmo eu tentando enviar o codigo do usuario novamente para essa tela está dando conflito, pois a Activity 2 já tem em seu inicio um GetExtra, que por sua vez veio da Activity Main.
Exemplo:
Activity Main:
public class MainActivity extends AppCompatActivity {

    private Button btnIrAct2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnIrAct2 = (Button) findViewById(R.id.btnIrAct2);
        btnIrAct2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent2 = new Intent(MainActivity.this, Activity2.class);
                intent2.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent2.putExtra("id_empresa", "12345");
                startActivity(intent2);

            }
        });

    }
}

Activity 2:
public class Activity2 extends AppCompatActivity {

    private Button btnIrAct3;
    private String mId_Empresa = null;
    static final int SERVICO_DETALHES_REQUEST = 1;
    private TextView tvResultado;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_2);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        /*  Recebe id de outra tela*/
        mId_Empresa = getIntent().getExtras().getString("id_empresa");

        tvResultado = (TextView) findViewById(R.id.tvAct2);
        tvResultado.setText(mId_Empresa);

        btnIrAct3 = (Button) findViewById(R.id.btnIrAct3);
        btnIrAct3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent3 = new Intent(Activity2.this, Activity3.class);
                intent3.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent3.putExtra("id_empresa", "12345");
                startActivityForResult(intent3, SERVICO_DETALHES_REQUEST );

            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (requestCode == SERVICO_DETALHES_REQUEST && resultCode == RESULT_OK) {
            String resultBack = data.getStringExtra("id_empresa");
        }
    }

}

Activity 3:
public class Activity3 extends AppCompatActivity {

    private String idEmpresa = null;
    private TextView resultado;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_3);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        /*  Recebe id de outra tela*/
        idEmpresa = getIntent().getExtras().getString("id_empresa");

        resultado = (TextView) findViewById(R.id.tvAct3);
        resultado.setText(idEmpresa);

    }

    @Override
    public void finish()
    {
        Intent data = new Intent();
        data.putExtra("id_empresa", "12345");
        setResult(Activity.RESULT_OK, data);
        super.finish();
    }

}

Preciso resolver esse conflito. Enviar o mesmo dado como PutExtra da Activity 3 para Activity 2, porém a Activity 2 já espera um GetExtra da Activity Main.
Answer: Você está colocando a flag FLAG_ACTIVITY_CLEAR_TOP nas suas intents que abrem as activities 2 e 3. Ao colocar essa flag, você remove as activities anteriores da sua pilha. Se esse não for o comportamento desejado, você tem que remover essa flag(FLAG_ACTIVITY_CLEAR_TOP) e, então, não vai precisar do startActivityForResult() da activity 2 para a 3.
Mais detalhes em: FLAG_ACTIVITY_CLEAR_TOP


LibGDX Desktop flicker

Question: This question has been posted before, but i have problems with flickering sprites in libGdx.
I have looked everywhere on stackoverflow, google, etc but nothing helped me.
The sprites only flicker when they move. It flickers less when i move them slower, but it flickers a lot when a little bit faster. This is very annoying and ofcourse unplayable.
This is my code:
package com.wouter.DuelArena;

import com.badlogic.gdx.Game;
import ...

public class DuelArena extends Game {

Sprite player;
float playerX;
float playerY;

boolean fireBool;
Sprite fireSprite;
Texture fireText;

OrthographicCamera cam;

Texture playerTexture;
SpriteBatch batch;

@Override
public void create() {
    fireBool = false;
    fireText = new Texture("data/droplet.png");
    fireText.setFilter(TextureFilter.Linear, TextureFilter.Linear);
    fireSprite = new Sprite(fireText);

    playerTexture = new Texture("data/bucket.png");
    playerTexture.setFilter(TextureFilter.Linear, TextureFilter.Linear);

    player = new Sprite(playerTexture);
    player.setSize(70, 128);
    playerX = 0f;
    playerY = 0f;

    cam = new OrthographicCamera();
    cam.setToOrtho(false, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());

    batch = new SpriteBatch();
}

@Override
public void dispose() {
    super.dispose();
}

@Override
public void render() {

    Gdx.gl.glClearColor(1,  1,  1,  1);
    Gdx.gl.glClear(Gdx.gl10.GL_COLOR_BUFFER_BIT);

    cam.update();
    batch.setProjectionMatrix(cam.combined);

    batch.begin();

    player.draw(batch);
    input();
    update();

    batch.end();

    super.render();
}
private void update()
{
    player.setPosition(playerX, playerY);

    if (fireBool)
    {
        fireSprite.setX(fireSprite.getX() + 300 * Gdx.graphics.getDeltaTime());
        fireSprite.draw(batch);

        if (fireSprite.getX() > 1280)
            fireBool = false;
    }
}
private void input()
{
    if (Gdx.input.isKeyPressed(Keys.LEFT) && player.getX() > 0)
    {
        playerX -= 200f * Gdx.graphics.getDeltaTime();

    }
    if (Gdx.input.isKeyPressed(Keys.RIGHT) && player.getX() < 1280)
    {
        playerX += 200f * Gdx.graphics.getDeltaTime();
    }
    if (Gdx.input.isKeyPressed(Keys.SPACE) && !fireBool)
    {
        fireBool = true;
        fireSprite.setPosition(playerX, playerY + 35f * Gdx.graphics.getDeltaTime());
    }
}

@Override
public void resize(int width, int height) {
    super.resize(width, height);
}

@Override
public void pause() {
    super.pause();
}

@Override
public void resume() {
    super.resume();
}

}
Thanks beforehand!
Comment: I'm not sure it could cause this, but you should remove the `super.render();`
Comment: But you're most probably right! I read in a tutorial you can't delete the super.render, but that was when our renderfunction was empty! So what i do is a double render, which means my screen is cleared twice! Thanks a lot! You made my day :)
Answer: The problem is the position of the call to the super.render:
super.render();

In a Game class, the super.render needs to be the first line in the code, not the last, like this:
@Override
public void render(){
    super.render(); //<-----

    Gdx.gl.glClearColor(1,  1,  1,  1);
    Gdx.gl.glClear(Gdx.gl10.GL_COLOR_BUFFER_BIT);
    cam.update();
    batch.setProjectionMatrix(cam.combined);

    batch.begin();
    player.draw(batch);
    input();
    update();
    batch.end();
}

It is actually very important to put it there if you override the render method in Game, because thats the one that calls the render of the current Screen. You aren't using Screens in this example, but if you are using Game you probably should (will :p).

LibGDX Desktop flicker


Check model's ModelState in FileStreamResult action in ASP.NET MVC

Question: I have a page that a user selects what he wants to download, the submit button posts the form to
public FileStreamResult GetFiles(FileSelectionModel model)
{
   //zips files into one zip
   return File();
}

However, what if the model wasn't in a valid state? How do I check it? It wouldn't let me return View() or return RedirectToAction() here
thanks
Answer: Change the return type of your action from FileStreamResult to the more generic ActionResult, then you can return View() or RedirectToAction().
HTHs,
Charles


Como gerar ruído em uma imagem usando python?

Question: Como gerar um ruído periódico do tipo Moiré em uma imagem em níveis de cinza usando Python?
Comment: Esta biblioteca está perto do que você precisa, talvez juntando alguns blocos consiga atingir o resultado do Moiré: http://scipy-lectures.github.io/advanced/image_processing/
Answer: Baseado no conceito de Moiré da Wikipédia e um pouco de Geometria Analítica, criei uma pequena rotina para aplicar o efeito em uma imagem sobrepondo-a com ela mesma.
Segue a rotina:
from PIL import Image
import math

def moire(source, target, angle, distance, offsetx = 2, offsety = 2):

    #imagem de entrada
    img = Image.open(source)
    pm = img.load()
    # imagem de saída (usando a mesma para gerar sobreposição)
    imgout = Image.open(source)
    pmout = imgout.load()

    # valores para as transformações
    cosseno = math.cos(angle)
    seno = math.sin(angle)
    # distância em cada eixo
    dx = distance * cosseno
    dy = distance * seno

    for x in range(0, img.size[0], offsetx):
        for y in range(0, img.size[1], offsety):
            # calcula coordenada transformada (rotação + deslocamento)
            x2, y2 = dx + math.floor(x * cosseno - y * seno), dy + math.floor(x * seno + y * cosseno)
            # ajusta valores fora da imagem (como se a mesma repetisse infinitamente)
            if x2 < 0:
                x2 = img.size[0] + x2
            elif x2 >= img.size[0]:
                x2 = x2 - img.size[0]
            if y2 < 0:
                y2 = img.size[1] + y2
            elif y2 >= img.size[1]:
                y2 = y2 - img.size[1]
            # desenha ponto transformado
            pmout[x, y] = pm[x2, y2]

    # salva a imagem
    imgout.save(target)

Note que na primeira linha faço o import da biblioteca de imagens Pillow (sucessor do PIL).
Em seguida, está a função que recebe os seguintes parâmetros:

source: imagem de entrada
target: local onde gravar o resultado
angle: ângulo do moiré, isto é, o quanto a imagem será rotacionada
distance: distância do moiré, isto é, o quanto a imagem será deslocada a partir da sua origem em relação ao ângulo informado
offsetx: a frequência com que os pontos do moiré serão aplicados na coordenada x, isto é, o valor 1 indica que todos os pixels serão processados, o valor 2 indica que um pixel sim e outro não e assim por diante.
offsety: idem ao anterior na coordenada y

Exemplos
Data a imagem:

Exemplo 1
# gira a imagem em 45º e aplica o efeito em todos os pontos
moire(r'linhas.png', r'linhas-output-1.png', math.pi / 4, 0, 1, 1)

Exemplo 2
# gira 30º, ponto sim, ponto não, e desloca 50 pixels nesse ângulo
moire(r'linhas.png', r'linhas-output-2.png', math.pi / 3, 50, 2, 2)

Exemplo 3
# gira 18º e desenha apenas a cada 5 pontos
moire(r'linhas.png', r'linhas-output-3.png', math.pi / 5, 0, 5, 5)

Answer: Essa foi a solução à qual eu cheguei - pode não ser a mais elegante, nem a mais eficiente - mas serviu ao propósito:
    from scipy import misc
    import numpy as np

    orig = misc.imread('bear_original.jpg')
    sh = orig.shape[0], orig.shape[1]
    noise = np.zeros(sh, dtype='float64')

    X, Y = np.meshgrid(range(0, sh[0]), range(0, sh[1]))

    A = 40
    u0 = 45
    v0 = 50

    noise += A*np.sin(X*u0 + Y*v0)

    A = -18
    u0 = -45
    v0 = 50

    noise += A*np.sin(X*u0 + Y*v0)

    noiseada = orig+noise
    misc.imsave('bearnoise.jpg', noiseada)

Ruído
Ruído aplicado na imagem


Linear probability model with crossentropy (log) loss

Question: For better or for worse, some people shoehorn binary $y$ variables into an ordinary least squares linear regression.
$$
\mathbb E[Y\vert X]=\hat y=X\beta
$$
If we encode the $y_i$ as either $0$ or $1$, we can make this work. The usual OLS estimate of $\hat\beta_{ols}=(X^TX)^{-1}X^Ty$ will work. However, the statistical properties are lacking.

We can predict impossible probability values like $-0.2$ and $+1.4$.

The OLS solution corresponds to maximum likelihood estimation for a Gaussian likelihood, even though we know the likelihood to be binomial.

If, however, we still use a linear model of the probability but minimize crossentropy loss, which is equivalent to maximum likelihood estimation for the correct binomial likelihood, instead of square loss, what happens?
$$
\text{Crossentropy Loss}$$$$
L(y,\hat y)=-\dfrac{1}{N}\sum_{i=1}^N\bigg[
y_i\log(\hat y_i)+
(1-y_i)\log(1-\hat y_i)
\bigg]
$$
NEW INFO
As an update, R's glm function is unhappy when I use a binomial family and an identity link function (which I think is exactly what I mean). This could just be the particular numerical method used by the function, but that strikes me as points against the idea of minimizing a different loss function in a linear probability model.
NEWER INFO
I find evidence against this idea (which I don't claim is a good idea, just an idea) in this quick R simulation (which takes code from a simulation I found on Cross Validated and have used many times).
set.seed(2022)
N <- 1000
x1 <- rnorm(N)           # some continuous variables
x2 <- rnorm(N)
z <- 1 + 2*x1 + 3*x2        # linear combination with a bias
pr <- 1/(1+exp(-z))         # pass through an inv-logit function
y <- rbinom(N, 1, pr)      # bernoulli response variable

L1 <- glm(y ~ x1 + x2, family = binomial)
L2 <- lm(y ~ x1 + x2)
L3 <- glm(y ~ x1 + x2, family = binomial(link = "identity"))

The logistic regression in L1 compiles. The linear probability model in L2 estimated via ordinary least squares compiles. The linear probability model estimated by minimizing crossentropy loss in L3 gives an error message, Error: no valid set of coefficients has been found: please supply starting values, that I have not bee able to resolve by tacking on a start in the glm argument. This might just be the particular numerical method used in this function, but this sure seems like a strike against my idea to minimize the crossentropy loss but keep the linear model.
However, I still wonder if this is an issue of the numerical optimization not working for these illegal $\log$ values, or if there is something theoretically wrong with $\hat\beta = \underset{\beta\in\mathbb R^p}{\text{argmin}}\{L(y,\hat y)\}$
(Maybe the right way to write the $\text{argmin}$ would be $\underset{\beta\in S}{\text{argmin}}\{L(y,\hat y)\}$ for $S=\{\beta\in\mathbb R^p\vert L(y,\hat y)\in\mathbb R\}$.)
Comment: @kjetilbhalvorsen Just seeing that it once worked convinces me that the statistics side of this model is fine, no matter what the software implementation requires. Thanks for the links!
Comment: Here are some posts about binomial regression with identity link function, it can work well:  https://stats.stackexchange.com/questions/198439/are-there-any-reasons-to-use-the-identity-link-in-logistic-regression-or-any-ot, https://stats.stackexchange.com/questions/139917/r-binomial-family-with-identity-link, https://stats.stackexchange.com/questions/471374/generalized-linear-model-and-identity-link-whats-its-benefit,
Comment: @kjetilbhalvorsen Maybe it's my R version, but the code at some of those links looks like what I ran and had fail to compile. Weird.
Comment: Weird ... but those posts are old and R might have changed. You might investigate and if necessary ask at R-help
Answer: I anticipate there is a real problem with this approach because there is no way to enforce that $L$ can be computed in the case where -- as you mention -- $\hat{y}$ is outside the unit interval.  In those cases, the summand can not be computed.
Comment: `glm.fit` does that by step-halving if the Fisher scoring algorithm gives in-sample predictions outside (0,1). See https://github.com/SurajGupta/r-source/blob/a28e609e72ed7c47f6ddfbb86c85279a0750f0b7/src/library/stats/R/glm.R#L288 (and the result of `binomial("identity")$validmu`)
Comment: +1 I've wondered about that, but I also wonder if that would force the in-sample predictions to be valid probabilities.
Answer: You can't use cross-entropy loss with a linear model. Notice that it calculates $\log(\hat y)$ and $\log(1 - \hat y)$, while $\hat y$ can be negative or bigger than one, so logs would be undefined (NaN in practice) and it simply won't work. For it to work, you would either need to adapt the loss function so that for $\hat y < 0$ and $\hat y > 1$ it returns something like $\infty$, but then it's not the elegant cross-entropy loss that we know anymore. Another solution might be to transform $\hat y$ so that it is constrained, for example by truncating it (again, not nice) or using something like a logistic function...
Comment: This was my concern, but why wouldn't that just force the optimization to pick parameters that assure all $\hat y_i\in (0,1)?$
Comment: @Dave NaN is an invalid result for an optimization algorithm, there is no way it could use it as it doesn't tell it if it gets closer or farther away from the optimum.
Comment: @Tim I disagree; common in the OR community is to rewrite constraint violations as a cost of $\infty$ (which we can coerce NaNs to be), and algorithms based on line searches or trust regions can handle this (such as the BFGS implemented in R's "optim").
Comment: @JohnMadden you disagree with what? This is what I said in the answer.
Comment: @Tim Sure but we can simply view Dave's $\hat{y}\in(0,1)$ as a nonlinear constraint, and then feel good about returning $\infty$ if it is violated.
Comment: @Tim Disagree with "NaN is an invalid result for an optimization algorithm, there is no way it could use it as it"
Comment: @JohnMadden there is a difference between `Inf` and `NaN`, `Inf` is higher than all the other values, `NaN` cannot be compared to numerical values.
Comment: Hmm actually there may be issues with unbounded below costs.
Comment: @JohnMadden and this is what I suggested in my answer :)
Answer: In glm function if the family=binomial is chosen, then link function must be logit like L3 <- glm(y ~ x1 + x2, family = binomial(link = "logit")) otherwise it will throw error. If link=linear is chosen then it is assuming a linear model and the purpose of Logistic Regression is lost.
Secondly, if the logistic regression is implemented from scratch then either Frequentist way is to be adopted in which IRLS i.e. Iterative Reweighted Least Squares algorithm is the most popular one or if Bayesian is adopted then there are two routes either by pure MH sampling or MH sampling within Gibbs approach can be adopted.
Comment: Thanks for responding; `link = "probit"` compiles with no errors, so something about this is false.
Comment: You said that the link function must be logit, which is not the case.
Comment: And the linear probability model would have the same purpose as logistic or probit regression: estimating probability of class membership (which is not quite the same as classification).
Comment: `link = "probit"` also applied for Binary Classification task only the link function is different, `gaussian` in this case.
Comment: See https://stats.stackexchange.com/questions/139917/r-binomial-family-with-identity-link  for how to use identity link function with binomial regression.
Comment: @Dave: Yes I was wrong. Logistic Regression inherently calls for Logit link function. But when the link function is used as Gaussian inside Binomial family then no more stays Logistic Regression, it becomes Probit Regression. But both Logit and Probit has the same purpose i.e. for Binary Classification.
Comment: How can probability be linear??? As far my knowledge it is a nonlinear function. I may be wrong. Except Uniform probability distribution no other probability function is linear.
Comment: We posit that the probability of an event (conditional on the features) follows the first equation in my question, rather than following a transformation of $X\beta$ like we do in logistic or probit regression. That doesn't mean we're right, but it could be a viable model.


Showing an equation is an invariant manifold?

Question: Does anyone know how to show this? Thanks!
$ \frac{dx}{dt} = x $
$ \frac{dy}{dt} = 2x^2 $
Show that x = 0 and y = $ x^2 - 2 $ , are invariant manifolds for the vector field.
Comment: In case you have nothing else in mind, why not solving the equations first?
Comment: i thought you had to show that the manifold is tangent to the vector field
Comment: Exactly, one way (in case you don't know any other, you don't say anything about what you tried... you really should), is what I suggested.
Answer: I am no mathematician, but following the Wikipedia entry on an invariant manifold, we can say that $x=0$ is an invariant manifold because $\frac{dx}{dt}$ remains $0$ for $x=0$. As for the parabola $y=x^2-2$, take the time derivative of $y-x^2-2$ and show that it equals to zero.
$$\frac{d}{dt}(y-x^2-2)=0$$
I hope this helps.


How to use C++ Builder OPENARRAY in a custom function

Question: I would like to use OPENARRAY (or an alternative, if you have one) to pass multiple placeholder variables into my function. I know that it can be used for String::Format in this way:
UnicodeString Text1 = "abc";
int Num2 = 1;
String::Format("Some %s and %d", OPENARRAY(TVarRec, (Text1, Num2));

What I would like is to use Text1 and Text2 variables in something like this:
MyFunction("Some %Txt1 and %Num2", OPENARRAY(TVarRec, ("%Txt1", Text1, "%Num2", Num2));

Or perhaps:
MyFunction(OPENARRAY(TVarRec, ("Some %Txt1 and %Num2", "%Txt1", Text1, "%Num2", Num2));

So it would accept the text and replace the placeholder variables with appropriate variable content.
What I don't know is how do I read OPENARRAY parameter content from MyFunction.
So the function would look like:
UnicodeString MyFunction(UnicodeString Txt, ?WHAT-HERE?)
{
// read openarray here and replace vars
return StringReplace(Txt, ?WHAT-HERE?);
}

So I don't know how do I accept the OPENARRAY variables. Also, if you have an alternative solution to passing placeholder, variable in similar manner (without the use of C++11), that would also be welcome.
Answer: When passing a Delphi-style Open Array to a function, two things are actually passed:

a pointer to the first element of the array
the index of the last element of the array (NOT the length of the array, as you might expect!).

So, in your example, you can declare your function like this:
UnicodeString MyFunction(UnicodeString Txt, const TVarRec *Values, const int Values_High)

And then loop through the array using normal pointer arithmetic.
TVarRec can hold many different data types, so you have to look at its VType field to know what kind of data it is actually referencing, and then access the appropriate data field.  Some values (integers and single characters) are stored directly in the TVarRec itself, while others (strings and other class types) are referenced by pointer instead.
For example:
UnicodeString MyFunction(UnicodeString Txt, const TVarRec *Values, const int Values_High)
{
    if (((Values_High + 1) % 2) != 0)
        throw Exception("uneven number of values!");

    for (int index = 0; index <= Values_High; index += 2)
    {
        String OldValue, NewValue;

        switch (Values[index].VType)
        {
            case vtString:
                OldValue = * static_cast<const ShortString*>(Values[index].VString);
                break;

            case vtPChar:
                OldValue = Values[index].VPChar;
                break;

            case vtPWideChar:
                OldValue = Values[index].VPWideChar;
                break;

            case vtAnsiString:
                OldValue = * static_cast<const AnsiString*>(Values[index].VAnsiString);
                break;

            case vtWideString:
                OldValue = * static_cast<const WideString*>(Values[index].VWideString);
                break;

            case vtUnicodeString:
                OldValue = * static_cast<const UnicodeString*>(Values[index].VUnicodeString);
                break;

            default:
                throw Exception("illegal value type at index %d!", ARRAYOFCONST(( index )) );
        }

        switch (Values[index+1].VType)
        {
            case vtInteger:
                NewValue = Values[index+1].VInteger;
                break;

            case vtBoolean:
                NewValue = Values[index+1].VBoolean;
                break;

            case vtChar:
                NewValue = Values[index+1].VChar;
                break;

            case vtExtended:
                NewValue = * static_cast<const Extended*>(Values[index+1].VExtended);
                break;

            case vtString:
                NewValue = * static_cast<const ShortString*>(Values[index+1].VString);
                break;

            case vtPChar:
                NewValue = Values[index+1].VPChar;
                break;

            case vtWideChar:
                NewValue = Values[index+1].VWideChar;
                break;

            case vtPWideChar:
                NewValue = Values[index+1].VPWideChar;
                break;

            case vtAnsiString:
                NewValue = * static_cast<const AnsiString*>(Values[index+1].VAnsiString);
                break;

            case vtCurrency:
                NewValue = * static_cast<const Currency*>(Values[index+1].VCurrency);
                break;

            case vtVariant:
                NewValue = * static_cast<const Variant*>(Values[index+1].VVariant);
                break;

            case vtWideString:
                NewValue = * static_cast<const WideString*>(Values[index+1].VWideString);
                break;

            case vtInt64:
                NewValue = * static_cast<const __int64*>(Values[index+1].VInt64);
                break;

            case vtUnicodeString:
                NewValue = * static_cast<const UnicodeString*>(Values[index+1].VUnicodeString);
                break;

            default:
                throw Exception("illegal value type at index %d!", ARRAYOFCONST(( index )) );
        }

        Txt = StringReplace(Txt, OldValue, NewValue, TReplaceFlags() << rfReplaceAll);
    }

    return Txt;
}

MyFunction("Some %Txt1 and %Num2", OPENARRAY(TVarRec, ("%Txt1", Text1, "%Num2", Num2)) );

On a side note, when a function takes an open array of TVarRec values, you should use the ARRAYOFCONST() macro instead of the OPENARRAY() macro directly, eg:
String::Format("Some %s and %d", ARRAYOFCONST(( Text1, Num2 )) );

MyFunction("Some %Txt1 and %Num2", ARRAYOFCONST(( "%Txt1", Text1, "%Num2", Num2 )) );

Comment: The `sysopen.h` header file contains several useful macros for dealing with open array parameters: `OPENARRAY()`, `ARRAYOFCONST()`, `ARRAYSIZE()`, `EXISTINGARRAY()`, and `SLICE()`.
Comment: Thank you for the very detailed reply - you've practically created the whole function for me, much more than I asked for - but still - amazing work and great answer! Also, much appreciate the `ARRAYOFCONST` tip!


Problem with Leibniz Rule (Differentiation under the integral sign)

Question: I was fooling around by differentiating some functions under the integral sign, and I seem to have stumbled on a problem I don't quite understand. There is another question here which asks something similar at the end, but the answer doesn't address it.
Consider the following integral: $$I = \int_{-\infty}^\infty \frac{\sin(k x)}{x} \text{d}x = \int_{-\infty}^\infty \frac{\sin(u)}{u} \text{d}u = \pi,$$
where I've used the substitution $u=kx$. Clearly, this integral is independent of $k$, and so $$\frac{\text{d}I}{\text{d}k} = 0.$$
However, if I use differentiation under the integral sign:
$$\frac{\text{d}I}{\text{d}k} = \int_{-\infty}^\infty\frac{\partial}{\partial k}\left( \frac{\sin(k x)}{x}\right) \text{d}x = \int_{-\infty}^\infty \cos(k x) \text{d}x,$$
where I have used Leibniz's Integral Rule, since the sinc function in the integral is continuous, and the integral converges. (Are there any assumptions that I'm missing here?) The problem is that this seems to imply that $$\int_{-\infty}^\infty \cos(k x) \text{d}x = 0,$$
which doesn't make sense! (Does it?) I study physics, so I have a habit of being slightly sloppy with mathematics. It wouldn't surprise me that there's some assumption that needs to be satisfied when differentiating under the integral sign that this function does not satisfy, but I can't figure out what it is. Can anyone tell me what I'm doing wrong?

EDIT:
Ok, so I have a slightly better idea of what I'm doing wrong, but I'm still not completely comfortable with it.
$$I = \int_{-\infty}^\infty \frac{\sin(k x)}{x} \text{d}x = \begin{cases} \,\,\pi& \quad k>0 \\-\pi& \quad k<0\end{cases} = \pi \,\, \text{sgn}(k),$$
where $\text{sgn}$ is the signum function. Using the fact that $$\frac{\text{d}}{\text{d}k} \text{sng}(k) = 2 \delta(k),$$ I get that
$$\frac{\text{d}I}{\text{d}k} = 2\pi \delta(k),$$ and so
$$\int_{-\infty}^\infty \cos(kx)\text{d} x = 2\pi \delta(k),$$
which seems to be the real part of the well known relation
$$\int_{-\infty}^\infty e^{i k x} \text{d}x = 2 \pi \delta(k).$$
So it looks like this might make sense if I think in terms of distributions. I'd appreciate any further input, though.
Comment: $u$ is not independent of $k$.....so $I$ is also not.
Comment: @SaketGurjar I really don't think that's true. As far as I know, the integral is $\pi$. Could you show me how it depends on $k$?
Comment: Consider : $f(x,y)=\sin(xy)$. Now if you use the substitution $u=xy$, $f(u)=\sin{u}$. Now think....is $f$ independent of $x$ due to this substitution?......$u$ still depends on $x$
Comment: The integral of the cosine over the real axis doesn't exist in the usual way, but why doesn't it make sense that if it is anything, then it may as well be $0$?
Comment: What I'm saying is that before the step where you wrote $\frac{dI}{dk}=0$, you claimed that "clearly this integral is independent of $k$".....this is what I feel is not true
Comment: @SaketGurjar You're right, I just realised that it depends on the sign of $k$, but I still think that your argument was a little simplistic.
Comment: I agree with @Allawonder ... Look up the rule for differentiation under the integral sign.  See what the hypotheses are.  It cannot give you a divergent integral like $$\int_{-\infty}^\infty \cos(k x) \text{d}x$$ as the answer, can it?
Comment: @GEdgar That's exactly my question. I can't see anything wrong with what I've done, though I'm beginning to get an idea.
Comment: I don't think you have done anything wrong in differentiating the integral as you have shown....its just that i dont think its going in the direction of calculating the integral.
Comment: @Allawonder I've realised something that I missed before, and it seems to be a little less problematic now. I've edited the question, but I'm still not completely happy with it.
Answer: Let's follow THIS explanation of integration under the integral sign.
Consider
$$
I_{A,B}(k) := \int_A^B \frac{\sin{kx}}{x}\;dx, \qquad k>0 .
$$
We will have to do limits $A \to -\infty$ and $B \to +\infty$ afterward.
We get
$$
\frac{d}{dk}\;I_{A,B}(k) = \int_A^B \left[\frac{\partial}{\partial k}
\frac{\sin{kx}}{x}{}\right]\;dx = \int_A^B\cos(kx)\;dx
$$
BUT these limits all fail exist:
$$
\lim_{A \to -\infty, B \to +\infty}\frac{d}{dk}\;I_{A,B}(k) \\
\lim_{A \to -\infty, B \to +\infty}\int_A^B \left[\frac{\partial}{\partial k}
\frac{\sin{kx}}{x}\right]\;dx\\
\lim_{A \to -\infty, B \to +\infty} \int_A^B\cos(kx)\;dx
$$
So the assertion that they are all equal is not much help.
Now, this limit does exist
$$
\lim_{A \to -\infty, B \to +\infty} I_{A,B}(k)
=\lim_{A \to -\infty, B \to +\infty}\int_A^B
\frac{\sin{kx}}{x}\;dx
$$
But (as we see here) you cannot use this phony rule
$$
\frac{d}{dk}\lim_{A \to -\infty, B \to +\infty} I_{A,B}(k)
=\lim_{A \to -\infty, B \to +\infty} \frac{d}{dk}I_{A,B}(k)
$$
It can easily fail!
Comment: Great! This actually answers my question as to what was wrong (I had a suspicion it had something to do with limits). But if you take the definition in the Wikipedia page you've linked, what exactly is it in the **statement** of the theorem that is not satisfied?
Comment: $f(x,k)$ is continuous, $f_x(x,k)$ is also continuous in both $x$ and $k$, and $A$ and $B$ being constants satisfy the other conditions. As you've shown, using the Leibniz rule here isn't valid, but does that mean that the linked theorem is incomplete? Do we also need that $f_t(x,t)$ be continuous, perhaps?
Comment: The theorem on that page is for $A$ and $B$ finite.  Not $\pm \infty$.  By writing this with $\pm\infty$ on there, you implicitly assumed (incorrectly) that the limit of the derivative is the derivative of the limit.
Comment: I see, it doesn't seem to be explicitly specified though, but I think I understand. Thanks! Just one further question if you have the time: could you take a look at my edit above? It seems like if I think of differentiation in the sense of distributions, I seem to get something that is plausibly sensible. What do you think?


Changing strings on acoustic guitar - any difference in the strings in the package?

Question: I have bought a package of strings for my guitar. Are there any differences with the strings in the package - yes there is the nylon ones for EAD and the clear ones for GAE, but apart from that?
I have bought Ernesto PALLA and I can see numbers next to the barcode - anything to take into account?
I can see there is a difference in the thickness of the strings, should I just rely on my sight on this - thickest E....E.
Comment: For a named brand of strings, they ought to be marked with the string gauges - the numbers are bigger for the thicker strings. The exact range of the numbers depend whether you have "heavy" or "light" strings but they will vary from about 8 to10, up to about 40 to 45.
Answer: Yes, you should rely on your eyesight.
Your thickest wound string will be low E.
The next thickest wound string will be A.
The next thickest wound string will be D.
The thickest nylon string will be G.
The next thickest nylon string will be B.
The skinniest nylon string will be high E.


How to get onclick to work multiple times

Question: sorry if this is a stupidly simple question I'm very new to all this. Im making a very basic Rock Paper Scissors game. I wanted to make a button to clear the results on the page to uncluttered it a bit. However my reset button only works on the first click. I'm not too sure what's going wrong here. I'm sure its a simple solution im just very inexperienced.
const player = {
 currentChoice: null
}
const computer= {
  currentChoice: null
}
const choices = ["Lapis", "Papyrus", "Scalpellus"];

function computerChooses(){
  const randomIndex = Math.floor(Math.random()*choices.length);
  computer.currentChoice = choices[randomIndex];
  displayResult("The computer chose " + computer.currentChoice);
}
function playerChooses(){
  const lapis = document.getElementById("Lapis");
  lapis.onclick = function a(){player.currentChoice = choices[0];
   displayResult("The player chose " + player.currentChoice);
computerChooses();
compareChoices();

   }

  const papyrus = document.getElementById("Papyrus");
  papyrus.onclick = function b(){
    player.currentChoice = choices[1];
    displayResult("The player chose " + player.currentChoice);
    computerChooses();
  compareChoices();
  }

  const scalpellus = document.getElementById("Scalpellus");
  scalpellus.onclick = function c(){
    player.currentChoice = choices[2];
    displayResult("The player chose " + player.currentChoice);
    computerChooses();
    compareChoices();

  }

}

function resetText(){
 const resetButton = document.getElementById("resetButton");
  resetButton.onclick = function d(){
    document.querySelector("p").innerHTML = " ";

  }

}
function compareChoices(){
  if(computer.currentChoice ===   player.currentChoice){
   displayResult("It's a tie you both chose " + computer.currentChoice);
  }else if(computer.currentChoice === choices[0]){
    if(player.currentChoice === choices[1]){
      displayResult("The player wins! The computer chose " + computer.currentChoice + " and the player chose " + player.currentChoice);
    }else{
      displayResult("The computer wins! The computer chose " + computer.currentChoice + " and the player chose " + player.currentChoice);
  }
}else if(computer.currentChoice === choices[1]){
  if(player.currentChoice === choices[2]){
    displayResult("The player wins! The computer chose " + computer.currentChoice + " and the player chose " + player.currentChoice);
  }else{
    displayResult("The computer wins! The computer chose " + computer.currentChoice + " and the player chose " + player.currentChoice)
  }
}else if(computer.currentChoice === choices[2]){
  if(player.currentChoice === choices[0]){
    displayResult("The player wins! The computer chose " + computer.currentChoice + " and the player chose " + player.currentChoice);
  }else{
    displayResult("The computer wins! The computer chose " + computer.currentChoice + " and the player chose " + player.currentChoice);
  }
}

}
function displayResult(result){
  const resultText = document.createElement("p");
  resultText.innerText = result;
  document.body.appendChild(resultText);
  const resetButton = document.getElementById("resetButton");
  resetButton.onclick = function f (){
    resultText.innerText = null;
    ;
  }
}

playerChooses();
resetText();

Answer: It may be better if you also linked your HTML for your question, but it looks like each time you call displayResult(), you create a new paragraph tag (p) that gets appended to the body. In the function resetText(), you retrieve the first instance of the p tag with document.querySelector("p"), which doesn't account for the newly created elements (if that makes sense).
The best fix to this would be to use document.querySelector("p") in replace of the document.createElement("p").
Answer: Hi I did some adjustments to your code and for me seems to work:
document.addEventListener('DOMContentLoaded', () => {
   const player = {
       currentChoice: null
   }
   const computer = {
       currentChoice: null
   }
   const choices = ["Lapis", "Papyrus", "Scalpellus"];

   function computerChooses() {
       const randomIndex = Math.floor(Math.random() * choices.length);
       computer.currentChoice = choices[randomIndex];
       displayResult("The computer chose " + computer.currentChoice);
   }

   function playerChooses() {
       const lapis = document.getElementById("Lapis");
       lapis.onclick = function a() {
           player.currentChoice = choices[0];
           displayResult("The player chose " + player.currentChoice);
           computerChooses();
           compareChoices();

       }

       const papyrus = document.getElementById("Papyrus");
       papyrus.onclick = function b() {
           player.currentChoice = choices[1];
           displayResult("The player chose " + player.currentChoice);
           computerChooses();
           compareChoices();
       }

       const scalpellus = document.getElementById("Scalpellus");
       scalpellus.onclick = function c() {
           player.currentChoice = choices[2];
           displayResult("The player chose " + player.currentChoice);
           computerChooses();
           compareChoices();
       }
   }

   function resetText() {
       const resetButton = document.getElementById("resetButton");
       resetButton.onclick = function d() {
            console.log("clicked");
            Array.prototype.slice.call(document.getElementsByTagName("p")).forEach(
              function(item) {
                item.remove();
                // or item.parentNode.removeChild(item); for older browsers (Edge-)
            });
       }
   }

   function compareChoices() {
       if (computer.currentChoice === player.currentChoice) {
           displayResult("It's a tie you both chose " + computer.currentChoice);
       } else if (computer.currentChoice === choices[0]) {
           if (player.currentChoice === choices[1]) {
               displayResult("The player wins! The computer chose " + computer.currentChoice + " and the player chose " + player.currentChoice);
           } else {
               displayResult("The computer wins! The computer chose " + computer.currentChoice + " and the player chose " + player.currentChoice);
           }
       } else if (computer.currentChoice === choices[1]) {
           if (player.currentChoice === choices[2]) {
               displayResult("The player wins! The computer chose " + computer.currentChoice + " and the player chose " + player.currentChoice);
           } else {
               displayResult("The computer wins! The computer chose " + computer.currentChoice + " and the player chose " + player.currentChoice)
           }
       } else if (computer.currentChoice === choices[2]) {
           if (player.currentChoice === choices[0]) {
               displayResult("The player wins! The computer chose " + computer.currentChoice + " and the player chose " + player.currentChoice);
           } else {
               displayResult("The computer wins! The computer chose " + computer.currentChoice + " and the player chose " + player.currentChoice);
           }
       }

   }

   function displayResult(result) {
       const resultText = document.createElement("p");
       resultText.innerText = result;
       document.body.appendChild(resultText);
   }

   playerChooses();
   resetText();
});

The issue is you are only removing the text of the element, but the element itself is still into the DOM, and whenever you click on reset you rely only on the first element.
My suggestion would be create a div and put all results into that div, then you just erase the content from the div.
Also you dont need to create again into displayResult the same function that you have, the trick here is to loop over all  elements that you created and delete them.
But this can be easily done without this loop if you put everything into a div as I wrote before.
Comment: Suggest to highlight the change you made on the code to make it more friendly on reading
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Python recognise decimal input as string

Question: code:
import random

los = random.randint(1, 9)
print(los)
i = 0
strzal = 0
print(type(strzal))
while los != strzał or strzał == "exit":
       if i < 1: strzal = input("Wprowadź liczbę pomiędzy 1 a 9:    ")

       if i >= 1: strzal = input("Spróbuj jeszcze raz: ")
       if strzal != los: print("")
       i += 1
       print("i: ", i, " los: ")
       print(type(los), los,  "strzał: ", type(strzał), strzał )
       print("Gratulacje! trafiłeś.")

and result on linux:
9
<class 'int'>
Wprowadź liczbę pomiędzy 1 a 9: 4
Nie trafiłeś. Spróbuj jeszcze raz bądż wprowadź "exit"
i:  1  los:  <class 'int'> 9 strzał:  <class 'str'> 4
Spróbuj jeszcze raz: 5
Nie trafiłeś. Spróbuj jeszcze raz bądż wprowadź "exit"
i:  2  los:  <class 'int'> 9 strzał:  <class 'str'> 5
Spróbuj jeszcze raz: exit

Comment: All input comes in as string. If you need to cast it to a different type:
`input("Wprowadź liczbę pomiędzy 1 a 9:    ")` should be
`int(input("Wprowadź liczbę pomiędzy 1 a 9:    "))`
Answer: You created an integer los.  You accept an input string strzal.  If you want to compare them, you need to cast one to the type of the other.  You probably want to make the input an integer:
zal = int(strzal)
if zal != los:
   print("")

Else, you could make your random number a string:
strlos = str(los)
if strzal != strlos:
   print("")


mysql query data insertion through php

Question: <?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "test";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$value1=$_POST['txtname'];
$value2=$_POST['cellnumber'];
$value3=$_POST['dist'];
$value4=$_POST['specialization'];
$value5=$_POST['membername'];
$value6=$_POST['date'];
$sql = "INSERT INTO students (StudentName, CellNumber, District, Specialization, PromotionMember, Date)
VALUES ('$value1', '$value2', '$value3', '$value4', '$value5', '$value6')";
if (!mysqli_query($sql)) {
die ('Error: ' . mysql_error());
}
else
{
echo ("معلومات ارایه شده شما ثبت شد");
header("Location: register.html");
}
mysqli_close();
?>

connection is successfull but data insertion is getting error on line 23 which is (if (!mysqli_query($sql)) { )
enter image description here
Comment: Do you understand what is written in error text?
Comment: Did you try to find a manual for `mysqli_query`? Here, I did it for you http://php.net/manual/en/mysqli.query.php
Comment: Your code is vulnerable to [*SQL injection*](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1).
Comment: Stackoverflow is not a programming-service. Did you checked your error-logs?
Answer: Your query doesn't run because you are using the MySQLi function wich need 2 parameters to execute your query.
So instead of
mysqli_query($sql)

you have to do:
mysqli_query($conn, $sql)

Your code also looks vulnerable to SQL Injections, so you want to know how to escape the strings in MySQLi. I recommend you to use prepared statements.
I hope this will help!
Comment: Thank you I make changes and that problem solved, but still its not inserting the data

Connected successfully Error:
Comment: My error is exactly (Connected Successfully error:) and its on line 23 which is (die ('Error: ' . mysql_error());)
Comment: @GhufranAtaie Change `mysql_error()` to `mysqli_error($conn)`
Answer: Try this code...
$sql = "INSERT INTO students (StudentName,CellNumber, District, Specialization, PromotionMember,      Date)VALUES ('$value1', '$value2', '$value3', '$value4', '$value5', '$value6')";
$q=mysqli_query($conn,$sql);
if (!$q) {
die ('Error: ' . mysqli_error($conn));
}else{header("Location: register.html");}

Answer: Try This code..
$sql = "INSERT INTO students (StudentName, CellNumber, District, Specialization, PromotionMember, Date)
VALUES ('$value1', '$value2', '$value3', '$value4', '$value5', '$value6')";
$qw=mysqli_query($conn,$sql);

if($qw)

{

header("Location: register.html");

}

Comment: Why should the OP "try this code"? A **good answer** will always have an explanation of what was done and why it was done in such a manner, not only for the OP but for future visitors to SO.

mysql query data insertion through php


Norms of integral ideals representing an integer

Question: Let $K$ be a number field. Given an unramified prime $p \in \mathbb{Z}$ and integer $\alpha \geq 1$ denote by $R(p^{\alpha})$ the set of ideal classes (in the class group) occupied by integral ideals of $K$ with norm $p^{\alpha}$.
Question 1. Am I correct in my understanding that $R(p)$ consists of only one ideal class where-as $R(p^{\alpha})$ with $\alpha > 1$ can consist of several ideal classes?
Question 2. Am I correct in my understanding that if $p$ is ramified then even $R(p)$ can consist of several ideal classes?
Comment: What have you tried? What do you know? Where are theses questions from?
Answer: The answer to question 1 is "no", $R(p)$ can consist of more than one ideal class.
For example, take $K = \Bbb Q(\sqrt {-23})$ and $p = 3$. Then there are two ideals with norm $p$: $(3, \frac{1 + \sqrt{-23}}2)$ and $(3, \frac{1 - \sqrt{-23}}2)$. They are not in the same ideal class.
This makes the statement of question 2 not so meaningful - it is true, nevertheless.
Comment: Thanks, this is very useful! I was also wondering about the following : If in the factorization $(p) = \prod \mathfrak{p}$ I know the norm of each $\mathfrak{p}$ and the ideal class to which they belong, does this determine $R(p)$ ?
Comment: Of course, every ideal having norm $p$ must appear in the factorization of $(p)$ (although the converse is not true).
Comment: Thanks a lot, this clarified a lot of confusion.


What is the difference between new and scrub tyres and what is the advantages?

Question: In the 2021 Spanish Grand Prix, the battle game between Verstappen and Hamilton changed thanks to the 2-stop strategy by Mercedes. When Lewis pit for the second time, Lambiase (Verstappen's engineer) tells Verstappen that Hamilton changed the tyre to scrub medium.
Why does Mercedes change the tyre to scrub medium to Lewis and not a new tyre set? Does scrub medium have better advantages because after Lewis pit, Bottas also pit but this time, it is a new set of the tyre instead of the scrub tyre?
Answer: The why part of your question (that is: why Hamilton / Mercedes put on a used / scrubbed set of tyres as opposed to a new set) is simply down to tyre allocation for the race, the race scenario, and the tyres Hamilton had used up to that point.
At the start of the race, Hamilton had:

1 set of Hards (new)
1 set of Mediums (new)
1 set of Mediums (used)
3 sets of Softs (used)

As shown in the below graphic:

Hamilton started on a set of Softs (those that he qualified in). Then at his first pit stop, those tyres were changed for a set of new Mediums. Therefore, on the second pit stop, Hamilton was left with only a new set of Hards, a used set of Mediums, and two sets of used Softs.
While Hamilton could have used the new Hards, they would unlikely have given the pace Mercedes would have liked to re-catch Verstappen, and thus overtake him. Similarly, a used set of Soft tyres were unlikely to reach the end of the race (Hamilton had pitted on Lap 42 of 66, as shown below) when being used to chase, and then overtake, a car ~20 seconds ahead.

The above image also shows that Bottas pitted on Lap 53 for used Softs.


Create html field with formatting buttons and store result in mySQL

Question: I am new to coding and I am trying to find a way to create an input field on a web page that has formatting buttons to enable e.g. bulleted lists, bold and underlined text etc. much like the text box that I am just using to post this question.
I already searched this site and googled but all I find is how to customize submit buttons or how to format input fields (like background color or general text appearance) but this is not what I am looking for.
I want to be able to create a custom formatted input like a bulleted list with some words that are bold or underlined and I want to store this formatted input in a mySQL database. If I then search the database and display the results on my page, I want the output to be formatted exactly as I submitted it.
So the questions are:

How do I create the input box with formatting buttons to customize my input? Is this possible with standard HTML? Do I need Javascript or PHP? If so, which functions and libraries to use?
How do I keep the formatting while storing the data in a database? I think I read elsewhere that storing HTML tags is not recommended?
Comment: You have 6 separate questions here. There should be one question per post. As for you programming problem, tackle one problem at a time. Get a page up, then start adding functionality.
Answer:
How do I create the input box with formatting buttons to customize my input? Is this possible with standard HTML? Do I need Javascript or PHP? If so, which functions and libraries to use?

You'd want to use a plugin. The plugin itself would most likely require minimal (if any) actual coding knowledge, and more likely just a copy+paste of relevant code from the plugin's instructions. Most plugins come with incredibly easy to follow startup guides.
Do a google search for "text editor plugins for website" and you'll get some solid results. The most common is probably CKEditor.
Regarding necessary technologies, PHP and JavaScript are not "one-or-the-other". JavaScript is a client-side language, meaning it manipulates the page in front of the user, not the actual data. For data manipulation, storage, retrieval, etc, you'd use a server-side programming language - like PHP. Of course, you can link these two technologies together to function as one, but that's not really in-line with what you're asking.
As you'd assume, storing this information obviously requires a database. Most databases are modified using some variation of SQL (though again, there are alternatives). Judging by your tags, it seems you're familiar with the idea of MySQL. Your PHP code would prepare the SQL and tell your MySQL database, "Here's some SQL - please execute it for me", and it would either go through successfully, or throw back an error for the PHP to interpret.

How do I keep the formatting while storing the data in a database? I think I read elsewhere that storing HTML tags is not recommended?

For a basic starter site, storing HTML in a database is alright. As you get to bigger and bigger projects, you may want to consider a more adaptable solution so that your data isn't all hard-coded HTML, but for what it sounds like you're doing I don't think you'll have to worry.
A text string with some simple bold and italic tags is completely acceptable - it's only when you start to store entire elements or sections that you'd want to start considering other options.
Comment: I tried your suggestion and used the CDN version of CKEditor. It was very easy to setup and I stored the formatted output successfully in mySQL as a BLOB. Thank you for the help!
Comment: Glad to hear it! Remember to mark the answer as "accepted" if you found it a correct, sufficient, and complete response to your question!


Why button inside form block my event listener?

Question: I have created a simple js code:
var testContainer = document.getElementById("test");
var butt = document.getElementById("test-button");

butt.addEventListener("click", function(){
    var paragraph = document.createElement("p");
    paragraph.innerText = "test";
    testContainer.appendChild(paragraph);
});

With HTML code:
<form>

  <button id="test-button"> test </button>
</form>

And here is the JSFiddle.
My question is why when <button> is inside <form> then my event listener is blocked and it cannot add a new element to
?
I don't understand why it's not valid.
Answer: Working fiddle.
Since the button is inside a form it will be considered as a submit button, so when you click in the button the form will be submited then the event will not fire, To avoid that you could add type='button' to the button like :
<button id="test-button" type="button">test</button>

Or use preventDefault() like :
butt.addEventListener("click", function(e){
    e.preventDefault();

    var paragraph = document.createElement("p");

    paragraph.innerText = "test";
    testContainer.appendChild(paragraph);
});

Hope this helps.
Answer: It appears your button is triggering the form to submit, thus refreshing the page. Try adding e.preventDefault() to your click handler to prevent the form from submitting..

var testContainer = document.getElementById("test");
var butt = document.getElementById("test-button");
butt.addEventListener("click", function(e) {
  e.preventDefault();
  var paragraph = document.createElement("p");
  paragraph.innerText = "test";
  testContainer.appendChild(paragraph);
});
<form>

  <button id="test-button">
test
</button>
</form>
Answer: Change the type of your button to
type="button"


Intuitive understanding of the difference between consistent and asymptotically unbiased

Question: I am trying to to get an intuitive understanding and feel for the difference and practical difference between the term consistent and asymptotically unbiased.  I know their mathematical/statistical definitions, but I'm looking for something intuitive.  To me, looking at their individual definitions, they almost seem to be the same thing.  I realize the difference must be subtle but I just don't see it. I'm try to visualize the differences, but just can't.  Can anyone help?
Comment: Just remember that these are frequentist and not general ideas.
Comment: See also this thread, https://stats.stackexchange.com/a/239919/28746
Comment: Thank you @AlecosPapadopoulos.  I'm not sure how I missed that thread!
Answer: Asymptotic unbiasedness $\impliedby$ consistency + bounded variance
Consider an estimator $\hat{\theta}_n$ for a parameter $\theta$.  Asymptotic unbiasedness means that the bias of the estimator goes to zero as $n \rightarrow \infty$, which means that the expected value of the estimator converges to the true value of the parameter.  Consistency is a stronger condition than this; it requires the estimator (not just its expected value) to converge to the true value of the parameter (with convergence interpreted in various ways).  Since there is generally some non-zero variance in the estimator, it will not generally be equal to (or converge to) its expected value.  Assuming the variance of the estimator is bounded, consistency ensures asymptotic unbiasedness (proof), but asymptotic unbiasedness is not enough to get consistency.  To put it another way, under some mild conditions, asymptotic unbiasedness is a necessary but not sufficient condition for consistency.
Asymptotic unbiasedness + vanishing variance $\implies$ consistency
If you have an asymptotically unbiased estimator, and its variance converges to zero, this is sufficient to give weak consistency.  (This follows from Markov's inequality, which ensures that convergence in mean-square implies convergence in probability).  Intuitively, this reflects the fact that a vanishing variance means that the sequence of random variables is converging closer and closer to the expected value, and if the expected value converges to the true parameter (as it does under asymptotic unbiasedness) then the random variable is converging to the true parameter.

Comment: @lmaosome -- see https://math.stackexchange.com/questions/239146/consistency-and-asymptotically-unbiasedness for a proof. Basically just apply C.S.
Comment: Your answer seems to be at odds with [this one](https://stats.stackexchange.com/questions/280684/intuitive-understanding-of-the-difference-between-consistent-and-asymptotically/395074#395074). Is the other answer wrong? Or maybe yours is? Or are the answers not in conflict?
Comment: @RichardHardy: Thanks for pointing that out.  I have made a minor edit to clarify the (mild) additional condition required for the stated implications.  The pathological case in the other answer occurs because of an unbounded variance.  I have now edited to add bounded variance as an assumption for the present implications.  (My goal here is to give a general "intuitive" answer that avoids pathological cases.)
Comment: very nice post! it would be nice if you could sketch the proof for the first implication.
Comment: for asymptotic unbiasedness it suffices to have consistency + uniformly bounded $1+\epsilon$ moments for some $\epsilon>0$ (see https://math.stackexchange.com/questions/3909755/uniformly-lq-bounded-and-convergence-in-probability-implies-lp-converg)
Answer: They are related ideas, but an asymptotically unbiased estimator doesn't have to be consistent.
For example, imagine an i.i.d. sample of size $n$ ($X_1, X_2, ..., X_n$) from some distribution with mean $\mu$ and variance $\sigma^2$. As an estimator of $\mu$ consider $T = X_1 + 1/n$.
(Edit: Note the $X_1$ there, not $\bar{X}$)
The bias is $1/n$ so $T$ is asymptotically unbiased, but it is not consistent.
Comment: I have come across this several times and each time I think it is wrong at first because I miss that you use X_1, rather than the sample mean, in constructing T (the Wikipedia example for "biased but consistent" uses the sample mean + 1/n, so this is similar enough to be confusing). I'm putting this note here in case others have the same thing happen to them.
Answer: I would like to clarify that consistency in general does not imply asymptotic unbiasedness. Consider an estimator for $0$ taking value $0$ with probability $(n-1)/n$ and value $n$ with probability $1/n$. It is a biased estimator since the expected value is always equal to $1$ and the bias does not disappear even if $n\to\infty$. However, it is a consistent estimator since it converges to $0$ in probability as $n\to\infty$.
Asymptotic unbiasedness does not imply consistency either as it is mentioned in other answers. For example, the periodogram is an asymptotically unbiased estimator of the spectral density, but it is not consistent.
Roughly speaking, consistency means that for large values of $n$ we are going to be close to the true value of the parameter with a high probability, i.e. estimates are going to be close to the true value of the parameter. Asymptotic unbiasedness means that for large values of $n$ on average we are going to be close to the true value of the parameter, i.e. the average of estimates is going to be close to the true value of the parameter, but not necessarily the estimates themselves.
Comment: I think you mean that the probability is $(n-1)/n$, otherwise the probability of 0 is greater than 1 for all $n$.
Comment: @Santiago You're absolutely right! Thanks!
Comment: @RichardHardy It is not asymptotically unbiased, the bias does not disappear even when $n\to\infty$. It is an example of an estimator that is consistent but not asymptotically unbiased. This comes from the fact that convergence in probability does not imply convergence in mean without additional assumptions. The first part of Ben's answer is wrong.
Comment: @Cm7F7Bb, shame on me! I read your answer too hastily and what I wrote was wrong. I will see if Ben has any comment on that so that we can reconcile our views.
Comment: You are correct that we need an additional (mild) condition for consistency to imply asymptotic variance.  I have added this additional condition into my answer.
Answer: There are "unbiased but not consistent" estimators as well as "biased but consistent" estimators:
https://en.wikipedia.org/wiki/Consistent_estimator#Unbiased_but_not_consistent
So, they are not the same thing.
Also, there is a long discussion about this topic here:
What is the difference between a consistent estimator and an unbiased estimator?
Comment: I believe this answer misses the mark as as the question is about the difference between asymptotic unbiasedness and consistency and not between biasedness and consistency
Answer: If the estimator is bounded then consistency implies asymptotic unbiasness by the dominated convergence theorem.
Answer: Asymptotic unbiased: As $n \rightarrow \infty$, bias converges to $0$.
Consistent: As $n \rightarrow \infty$, variance of the estimator converges to $0$.
Comment: I have issue with this characterization of consistency. By this definition, a constant estimator, i.e. $\hat\theta = 1$, would be consistent for every parameter.


Get current URL and find nav items matching part of it, then show submenu

Question: I have a navigation menu which has submenus hidden by default. I want to display the submenu of the nav item that matches the current location, if I am on a page other than the home page.
I can find out the current pathname:
var currentUrl = (window.location.pathname);

I know how to scan href parameters:
$('ul.see li a[href^="/' + location.pathname.split("/")[1] + '"]');

to get the submenu first directory.
How can I navigate through the nav items and add a class to a parent li item?
My menu markup is as follows:

About

The Salon

Our Story

Joe Mills

Stylists

Products

Services

Colour

Cutting & Styling

Waving & Straightening

Treatments

So as you see if I am /services/colour, I would like to show the services submenu.
Answer:
Q: How can I navigate through the nav items and add a class to a parent li item?

Assuming you are AT your anchor tag with:
var $a = $('ul.see li a[href^="/' + location.pathname.split("/")[1] + '"]');

Then, you can use the .closest() method to get to the closest LI
$a.closest('li')

Then, add the class you desire...and then navigate up to it's .closest('ul') if you need to add a class there, etc.
Comment: Thanks for your help Kevin, I got it sorted, but this looks like a legit solution


Server 2012 file server security - File access through software only?

Question: I have just setup a server 2012 essentials R2 box as a test bed for my small business.  Its running Essentials R2 as a VM on a Essentials R2 host.  I have set it up to be the DC and DHCP server and joined a client.
My next task is to use it as a file server but I am not quite sure how to set it up.  All the client interactions with the file server will be through client side software.  I therefore do not want any access to the files apart from through the software.
I have looked at the ntfs permissions and there is a permission called "List Folder/Read Data" however I am unsure this will do what I want.
Is it possible to give access to the files but not allow access through the windows explorer / command line?
Comment: Have you looked here? http://technet.microsoft.com/library/hh831487
Answer: It depends on how, exactly, the application interacts with the file and the user.
The root question is: "Is there a way to use a different security principal that the one from the user login session to access the file" ? If the answer is "no", then you can't restrict it.
More pragmatically:
If the application is a traditional desktop application used either remotely (application running on the client's computer accessing the file through a SMB share) or locally (for instance through Terminal Services), then no, you usually cannot restrict the access to the file using permissions because the process uses the user's identity to access it.
If the application is a n-tier application (for instance, a web app), then you usually can put extra restriction on data file access: you restrict the rights of the users and allow whatever level of access is necessary to the security principal that will be used (that's usually done by assigning a specific service service account to the relevant process). Be mindful, however, of the fact that it is possible for a n-tier application to impersonate the user access token. In such a case, you should make sure that the files you want to protect are, in fact, not available though SMB at all (for instance, by placing them into a drive or folder that is not accessible from any SMB share available to the users).
Note that, regardless of what the answer to the above it, if the application supports UNC path, you could make it less likely for the user to access the file by hiding it under a hidden network share. All you need to do to hide the share is to add a dollar sign ($) at the end of it's name. It will not prevent anyone but the less tech-savvy users from acessing the file should they want it but it might prevent accidents.
Comment: Thanks for the response.  The main data I wanted to secure was an Access Database file that sits on the file share.  As far as I can tell from your response and further reading it is not possible to do what I want.  As far as I can see my best bet is to obscurate the file share as you said by hiding it and by disabling access to the network browser for clients in windows.  Thanks for the help


How to change icon in button in ReactJS?

Question: I'm using material-ui Raised button and want to change the icon in the button when it is clciked.
<RaisedButton primary={true}>EXPAND</RaisedButton>

The button looks like this now
Any suggestion.Thanks!
Answer: On your initial state set expanded=false and then:
<RaisedButton primary={true}
              onClick={() => this.setState({expanded: !this.state.expanded})}>

   EXPAND
</RaisedButton>

Comment: Worked as i wanted. Thanks a lot for your help.
Answer: You can use ClassNames javascript library. - https://github.com/JedWatson/classnames
let classes = classNames({
              "fa" : true,
              "fa-minus": this.state.something,
            });


asp.net delete popup using javascript and c#

Question: I am bit struggling to understand how it works when you want to delete something using server side. I know how to use MessageBox but it is not ideal. I am advised to use popup on server side.
What I am trying to do is that when you click the button, popup should display to ask you if you are sure you want to delete it. If yes, delete it based on C# delete events. If no, cancel it. How to work with both of javascript and C#?
I got problem When I click the button, popup happens, and when i click yes, delete it which is working BUT when I click no, still delete it. How to handle with yes and no in C# or javascrpit? No idea how to do this.
Your excample code means alot to me. I need to understand. Thanks!!
Javascript

Answer: client side:
  function confirm() {
        var confirm_value = document.createElement("INPUT");
        confirm_value.type = "hidden";
        confirm_value.name = "confirm_value";
  if (confirm("Do you Want to Delete?")) {
            confirm_value.value = "Yes";

        } else {
            confirm_value.value = "No";
            return false;
        }
 document.forms[0].appendChild(confirm_value);
    }

On server side:
    protected void btnDelete_Click(object sender, EventArgs e)
{
           string confirmValue = Request.Form["confirm_value"];
         if (confirmValue == "Yes")
     {
     }
    else
    {
    }
}

Answer: If you have a server button with both client and server events. You can check the client side, and decide weather the server side should be executed or not. for example :
add a CSS class to your button.
$('.CssClassOfYourButton').click(function (evt) {
            if (condition)
                return false;
                // Post Back will not happen
            }
            if (confirm('Are you sure? \nDoing this will ......... .')) {
                return true;
               // if user clicks yes ,Post Back will happen and server side delete event is executed.

            }

        });