English translation for "rubato"

Question: Most italian musical indications and concepts are easy to translate in one or two words (largo, presto, crescendo, ...) but it is difficult to find even an approximation to rubato.
Any suggestions?
Comment: Why not literally? Stolen time or robbed time. Cause that's what you do.
Comment: @Tom : to me, a good translation in this case, is one that goes already half-way explaining the musical concept behind the word for someone who never thought about that.
Comment: @Tom : Because it is just one side of the coin. The kind of translation I am looking for is not only from italian. It is also from musicalian.
Answer: "Flexible time" is probably the closest translation that gets the point across.  However, "stolen time" or "robbed time", as Raskolnikov suggests, would be the most accurate translation.  The English speaker unfamiliar with it would just need to think about it a little: stealing time from some notes and giving it to others.  Heck, maybe "Robin Hood time" would be a good name too :P
Comment: +1 Robin Hood time. Probably the best **name** there is. And it is easy to remember the explanation after have heard it the first time. (Also +1 for having a complete answer)
Comment: Nice idea!
Answer: How about some Elasticity?
Possible Usages: In Elastic Tempo; Elastic; With Elasticity
Answer: A couple of subjective suggestions, none of which I find very good:

"Free pace"
"Moving tempo"

The problem is that this freedom must be within keeping the average tempo.
Answer: I think "flexible tempo" could work.
Answer: According to Wikipedia, this is stolen or robbed as in stolen/robbed time.
A musician playing with rubato would "rob" from a part of the phrase they would want to be slower, and speed up later on according to the music. For example if you had a rising passage, you may wish to slow down to emphasize it, but resume your normal tempo after.
And this is further outlined by Anthony Tomassini, Chief Classical Music Critic  for New York Times:

Let me start my answer by trying to define, for those who need some help, this loose term "rubato." It describes the practice of playing with expressive and rhythmic freedom. Specifically "tempo rubato" means "robbed time," a term that indicates that strict time in a passage is ignored temporarily while some time is "robbed" from one passage or group of notes and given to another. There are intense debates within the field over the degree of rubato that is considered tasteful and appropriate.
Answer: Google Translate (which doubles as a dictionary) says it means stolen but can also mean bent.
Comment: Bent makes sense. And for guitarists it would be a good image (you bend the tempo, like you bend a string to change its pitch).

English translation for "rubato"


Determine if NHibernate entity has cascading records

Question: I'm looping though and inserting into my DB several million records. Performance is a number one priority.
I want to take advantage of using Stateless sessions but as you may be aware they do not support cascading objects on more complex entities.
If there a general way I can determine whether an entity has cascading records or doesn't? if it does I'll use regular sessions and if doesn't - stateless ones.
Does it make sense to do something like this? If so what's the best way to do it?
<code>protected virtual ISession Session
{
  get { return ....SessionFactory.GetCurrentSession(); }
}

protected virtual IStatelessSession StatelessSession
{
   get { return ....SessionFactory.OpenStatelessSession(); }
}

public virtual T SaveOrUpdate(T entity)
{
    if(entity.HasCascadingrecords) //<- Something like this
    {
        Session.Save(entity);
    }
    else
    {
         StatelessSession.Save(entity);
    }
}
</code>
Answer: Let's follow these to get some more initial details:

NHibernate ClassMap get column name for property
Exploring nhibernate mapping

And at the end, we can use snippet like the one below:
<code>// get type of the Entity we need
var entityType = typeof(TEntity);

// get persister
var entityType = typeof(TEntity);
var factory = ... // get factory
var persister = factory.GetClassMetadata(entityType) as AbstractEntityPersister;

// check this setting
var hasCascades = persister.HasCascades;

// use it somehow
return hasCascades
</code>


Arranging 3 Rows of 4 letter as triplets with restrictions

Question: Given the following matrix:
$$\begin{bmatrix}
a & b & c & d\\
e & f & g & h\\
i & j & k & l
\end{bmatrix}$$
how many sets of 3 letter sets using all the letters once can be made if:

Letters in the same row can't be in the same 3 set.
As in 1 plus not all 3 letters can be from the same col ( but 2 can ).

For example: $$\{ \{a , g , k \} , \{ b, f , j \} , \{ c, e, l \} , \{ d , h, i \} \}$$ meets the first condition but not the second.
I started out on the first part by choosing pairs for each letter in the first row disregarding order: $$\frac{\binom{8}{2}\binom{6}{2}\binom{4}{2}}{4!}$$
I know I need to use inclusion exclusion for the second half, but I'm not sure how to proceed.
Comment: What happened with the answers to [this question](http://math.stackexchange.com/q/97351), and to [this other one](http://math.stackexchange.com/q/100414)?
Answer: This partly answers this question and partly the previous version. I will fix this answer in may be a day's time. Please bear with me!

Am I missing something obvious?

For the first problem: To construct a set: you need to choose a letter from each row. This can be done in $\binom 4 1^3$ ways. The second set can be obtained in $\binom 31^3$ ways and so on.And, these are considered as a set. Hence there is no notion of order of an element in a set unless we define one.  Hence the number is $\dfrac{\binom 4 1^3 \binom 3 1^3 \binom 2 1^3 }{4!}=16 \cdot 9 \cdot 4=576 $ ways.

$$$$

For the next problem:

The first set can be formed as follows: by choosing the first element in $\binom 4 1$ ways. Now, for the second element note that, you can take the element below the first choice, whence you'll have $\binom 3 1$ ways for the third element or some other element in $\binom 3 1$ ways, whence for the third element you're left with $\binom 2 1$ choices. Briefly summarised, we can have first sets in $\binom 4 1 \left(\binom 3 1+\binom 2 1 \binom 3 1 \right)=4(3+6)=36 $ ways.
The second set can be chosen in $3+(2+3)+(3+2+2)$ ways
The third set can be chosen in $1$ way.

So...
Comment: @Robert You have made my life a bit complicated. Let me edit. Please wait.
Comment: These are sets of sets, so order doesn't matter.
Comment: I'm not sure, but on the exam they said explicitly to use inclusion exclusion.  Maybe I'm missing something in the wording...
Comment: Let me edit. Please note that first problem is done best this way.
Comment: I apoligize, I misread the second part of the question.  Not all 3 letters can be from the same col, but 2 of them can be.


Not getting complete URL parameters

Question: My url is node/3?filter-value=67&filter-value=80 and when i try to do this code:
$param = \Drupal::request()->query->all();`

$param['filter-value']

It shows the value 80 only. I want to get both of them.
Comment: This is a question about PHP in general, see https://stackoverflow.com/questions/353379/how-to-get-multiple-parameters-with-same-name-from-a-url-in-php
Answer: if you don't want to change the structure of your url.
you can use Explode function
I have made a helper function try it out:
function getParamsOfUrlWithSameKey(){
  $current_uri = \Drupal::request()->getRequestUri();
  $items = explode('?', $current_uri);
  $res_param = [];
  if (isset($items[1])) {
    $params = explode('&', $items[1]);
    foreach ($params as $param) {
      $param_value = explode('=', $param);
      $key = $param_value[0];
      $value = $param_value[1];
      $res_param[$key][] = $value;
    }
  }
  return $res_param;
}

The return of this function will be something like:
array:1 [▼
   "filter-value" => array:2 [▼
     0 => "67"
     1 => "80"
   ]
 ]

Answer: You'll need to use array notation in the URL:

node/3?filter-value[]=67&filter-value[]=80

Then get('filter-value') will return an array with both values.
See https://stackoverflow.com/questions/6243051/how-to-pass-an-array-within-a-query-string for more information.

Not getting complete URL parameters


mpi "for UD mlx5 connect on mlx5_0 failed: No such device"

Question: mpi error is below
[1689646357.071467] [05af046533e9:124545:0]       ib_device.c:1466 UCX  ERROR   ibv_create_ah(dlid=49152 sl=0 port=1 src_path_bits=0 dgid=fe80::1270:fdff:fe44:5170 sgid_index=0 traffic_class=0) for UD mlx5 connect on mlx5_0 failed: No such device
[1689646357.072612] [05af046533e9:124545:0]      ucp_worker.c:2657 UCX  WARN  worker 0x55741a624b40: 1 pending operations were not flushed
Abort(138006287) on node 0 (rank 0 in comm 0): Fatal error in internal_Init_thread: Other MPI error, error stack:
internal_Init_thread(60)......: MPI_Init_thread(argc=0x7ffeb4a07608, argv=0x7ffeb4a07610, required=1, provided=0x7ffeb4a0760c) failed
MPII_Init_thread(232).........:
MPIR_init_comm_world(34)......:
MPIR_Comm_commit(722).........:
MPIR_Comm_commit_internal(510):
MPID_Comm_commit_pre_hook(158):
MPIDI_UCX_init_world(288).....:
initial_address_exchange(145).:  ucx function returned with failed status(ucx_init.c 145 initial_address_exchange Address not valid)

the error is when i use mpi in docker.
when I write a hello-world cpp file ,and compile it ,and run mpirun -np 2 ./hello
Answer: perhaps you haven't install ib/roce network interface card(NIC) driver
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).

mpi “for UD mlx5 connect on mlx5_0 failed: No such device”


AWSSDK s3 .net question. My multipart upload crashes after 15mins of transfer

Question: I'm uploading rather a lot of data (30gb+) across thousands of files. The whole process takes a while but I've been finding that consistently after 15 mins of transfers, the upload process fails and I get errors for each file that is currently being transferred (I'm doing it multithreaded so there are multiple uploads at once). The error code I'm getting is "error: Amazon.S3.AmazonS3Exception: The difference between the request time and the current time is too large. ---> Amazon.Runtime.Internal.HttpErrorResponseException: The remote server returned an error: (403) Forbidden. ---> System.Net.WebException: The remote server returned an error: (403) Forbidden."
Seeing as its exactly 15 mins from the start of the whole process that this thing crashes, I think its maybe that the client is timing out, however I've set my client's timout to 45 mins I think:
<code> {
     var client = new AmazonS3Client(new AmazonS3Config()
     {
         RegionEndpoint = RegionEndpoint.EUWest2,
         UseAccelerateEndpoint = true,
         Timeout = TimeSpan.FromMinutes(45),
         ReadWriteTimeout = TimeSpan.FromMinutes(45),
         RetryMode = RequestRetryMode.Standard,
         MaxErrorRetry = 10
     });

     Parallel.ForEach(srcObjList, async srcObj =>
     {
         try
             {
                 var putObjectRequest = new PutObjectRequest();
                 putObjectRequest.BucketName = destBucket;
                 putObjectRequest.Key = srcObj.Key;
                 putObjectRequest.FilePath = filePathString;
                 putObjectRequest.CannedACL = S3CannedACL.PublicRead;

                 var uploadTask = client.PutObjectAsync(putObjectRequest);

                 lock (threadLock)
                 {
                     syncTasks.Add(uploadTask);
                 }

                 await uploadTask;
             }
             catch (Exception e)
             {
                 Debug.LogError($"Copy task ({srcObj.Key}) failed with error: {e}");
                 throw;
             }
     });

     try
     {
         await Task.WhenAll(syncTasks.Where(x => x != null).ToArray());
     }
     catch (Exception e)
     {
         Debug.LogError($"Upload encountered an issue: {e}");
     }
 });

await transferOperations;

Debug.Log("Done!");```

</code>
Comment: The error is due to server is closing the connection .  See following for timeout on Amazon : https://docs.aws.amazon.com/amazonswf/latest/developerguide/setting-timeouts.html?force_isolation=true
Comment: I see, how would I configure it to do otherwise?
Comment: It is documented on the site.
Comment: Thanks, I don't think I'm using swf though.. I'm just using regular 'ole s3 and uploading stuff to it from my c# application
Comment: I'm not sure.  I suspect the same limits are applied to any transfer on Amazon.
Answer: The documentation doesn't specify the maximum timeout value, but given that you're seeing 15 minutes exactly, it stands to reason there is some upper limit to the timeout value, either a hard limit or something in the S3 bucket's settings.
This answer suggests a clock synchronization difference might also be the case, but then I'd wonder why the transfer starts at all.


Vuejs 2.0 v-model conflitando com v-bind:value em elementos diferentes

Question: Tenho um formulário com alguns inputs que tem v-model e outros com v-bind:value recebendo um valor inicial pelo 'data'. Toda vez que digito algo em um campo com v-model ele reseta o valor dos campos com v-bind:value para o valor inicial.
O erro acontece apenas na versão 2.x do vuejs.
jsfiddle com um exemplo: https://jsfiddle.net/ypeacuth/

new Vue({
  el: '#app',
  data: {
    nome: 'Ted',
    sobrenome: ''
  }
})

  <input type="text" id="nome" name="nome" v-model="nome">
  <input type="text" id="sobrenome" name="sobrenome" :value="sobrenome">

Comment: A explicação do @rnd_rss está correta... Quando você faz `` você está dizendo que a propriedade `value` vai ser sempre o que estiver dentro de `data.sobrenome`.. E como `data.sobrenome` é uma _string_ vazia e nunca é modificado, o comportamento do Vue é tornar o `value` uma _string_ vazia sempre que renderizar o componente.
Answer: Esse é mesmo o comportamento das diretivas, lembre que só o v-model tem two way data binding, ou seja se você alterar o input ou o valor que está no seu data o vue mantém eles 'sincronizados'. Já com o :value isso não acontece se você alterar o valor do input não vai alterar o valor no data pois ele tem one way data binding, nesse caso a reatividade acontece somente do data para o input. Então se entendi direito o que você precisa vai ser necessário alterar o :value para v-model.
new Vue({
  el: '#app',
  data: {
    nome: 'Ted',
    sobrenome: ''
  }
})

  <input type="text" id="nome" name="nome" v-model="nome">
  <input type="text" id="sobrenome" name="sobrenome" v-model="sobrenome">

Fontes: https://v2.vuejs.org/v2/guide/forms.html#Value-Bindings
Comment: Você pode usar o :value para setar um valor inicial, porém por ele não vai ser possível atualizar o sobrenome(a variável que esta no data), se preencher alguma coisa no input do sobrenome o :value não atualiza o valor do input no sobrenome, é sempre e somente o sobrenome(que está no data) atualiza o input. Mas se você vai precisar setar um valor inicial e depois esse valor pode ser atualizado o jeito é mesmo usar o v-model


Local basis of parallel vector fields with respect to an arbitrary affine connexion.

Question: I would like to show that for any connexion D on $\mu: N \rightarrow M$ (N, M are manifolds), and any point $n$ in $N$ there is a local basis $\{X_i\}$ of vector fields over $\mu$ such that each $X_i$ is parallel at n, that is, $D_t X_i = 0$ for all t in the tangent space $N_n$.
Can someone point me the way for a proof?
Other answers in this site refer to a Riemmanian structure, orthonormal basis, normal coordinates, etc..
Comment: What do you mean by "connection on $\mu$"? A connection is usually defined for a vector bundle $E \rightarrow M$ over a manifold $M$. If the vector bundle is $TM$ then we say this is (an affine) connection on $M$.
Comment: An affine connection $D$ on $\mu$ assigns to each element on $N_n$ an operator which maps vector fields over $\mu$ into elements of $M_{\mu (n)}$ that satisfies the usual axioms for connections (linearity over the elements of $N_n$, linearity over the vector fields, Leibniz rule and smoothness). Just in case, a vector field over $\mu$ assigns to each $n$ in $N$ a vector in $M_{\mu (n)}$. I'm learning through an old book, maybe that is the case. I believe the definitions are very similar.
Comment: Ah, ok. This is usually called a connection along $\mu$ or a connection on the pullback bundle $\mu^{*}(TM)$ over $N$.
Answer: Choose a coordinate system $\varphi = (y^1,\dots,y^k)$ around your point $n \in N^k$ such that $n$ corresponds to $(0,\dots,0)$ and choose some basis $X_1|_{\mu(n)}, \dots, X_m|_{\mu(n)} \in T_{\mu(n)}M$. Define
$$ X_i(\varphi^{-1}(y^1,\dots,y^k)) = P_{\varphi^{-1}(sy^1,\dots,sy^k), s = 0, s = 1}(X_i|_{\mu(n)}). $$
In other words, $X_i$ at (the point corresponding to) $(y^1,\dots,y^k)$ is obtained by parallel transporting $X_i|_{\mu(n)}$ radially from $(0,\dots,0)$ to $(y^1,\dots,y^k)$. The $X_i$ are well-defined, smooth and linearly independent because parallel transport is a linear isomorphism and by constructing, they are parallel (usually only) at $n = \varphi^{-1}(0,\dots,0)$.


Fudge: @patch not working when from X import Y'ing instead of import X?

Question: I came across a strange bahviour of the patch decorator in Fudge 1.0.3. It does not patch the module when importing classes via
from <module> import <class>

but works fine when importing
import <module>

with the corresponding code adaption.
Here's a minimalized setup:
mdle.py:
class Klaas(object):

    def __init__(self):
        # easyest way to signal this class has been instantiated accidently
        raise Exception(">:[")

some.py (test not working):
from mdle import Klaas()
def instantiate():
    instance = Klaas()

some.py (test working):
import mdle
def instantiate():
    instance = mdle.Klaas()

some_test.py:
import unittest
import fudge

import some

class SomeTest(unittest.TestCase):

    @fudge.patch("mdle.Klaas")
    def test_somethingb(self, Klaas_mock):
        klaas_inst = (Klaas_mock.expects_call()
                            .returns_fake())

        # Receiving the exception
        some.instantiate()

Should I patch in a different way? Is this a limitation of Fudge, or a bug?
Comment: Note that `@fudge.patch("mdle.Klass")` is only going to work if *that's the name being used*. If you `from mdle import Klass`, switch the patch target to `"Klass"`.
Comment: I don't know `fudge` at all but I can guess it looks like to `unittest.mock.patch` behavior. Take a look at this answer http://stackoverflow.com/questions/28546137/python-mock-with-from-x-import-y/28570892#28570892
Comment: Thanks for the clarification. Unfortunately the [documentation](http://farmdev.com/projects/fudge/api/fudge.html#fudge.patch) is not quite clear about that: `A test decorator that patches importable names with fakes`. You should make an answer, if you like.
Answer: You have to patch the name where the object is being referenced, not where it's being defined.
Remember modules are just objects with a dict of names pointing to other objects (a class is an object too). The same object can have multiple (possibly identical) names in different modules. Patching makes a name temporarily point to a Fake rather than to the original object.
I assume in your first (not working) some.py module you meant:
from mdle import Klass

That creates a name some.Klass that gets used in that module. The name happens to match the name in mdle by default, but you actually have two names pointing to the same class object. It's the name in some you need to patch if you want to use a fake instead, because that's the name used to reference the class in the module under test.
Your test patches mdle.Klass which is not the name used in some, so your code still picks up the real class object using its own unpatched name. You need to patch some.Klass instead in this case.
In your second (working) some.py you import the whole mdle module and reference the class using the name in that module. That's why patching mdle.Klass works in that case, you're patching the name that's being used.
Comment: Thanks for your (late) response. It makes sense now. "I assume ... you meant" - Yes, I meant `from mdle import Klass` (probably typed the reduced example to simplify the example).


Exception while using LoadFile() in powershell

Question: Here is ia piece of code from my powershell script:
$PatchSummaryTextBox.LoadFile($ReadMeFilePath.FullName)
$PatchSummaryTextBox =  New-Object windows.forms.RichTextBox
represents a text box in which I want to load content from file mentioned in $ReadMeFilePath.FullName path.
While executing, this throws an exception:
Exception calling "LoadFile" with "1" argument(s): "File format is not valid."
At line:1 char:30
+ $PatchSummaryTextBox.LoadFile <<<< ($ReadMeFilePath.FullName)
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException
Output of $ReadMeFilePath.FullName is
D:\Work\HotfixHandling Testing\V03.02.01 Hotfixes\V03.02.01P9\Readme.txt
which is correct path.
Can anyone suggest what could be possible reason for exception?
Answer: The reason is RichTextBox.LoadFile(string path) expects you pass a path to a RTF file. A file called Readme.txt is likely to be plain text. As per documentation:

With this version of the LoadFile method, if the file being loaded is
  not an RTF document, an exception will occur. To load a different type
  of file such as an ASCII text file, use the other versions of this
  method that accept a value from the RichTextBoxStreamType enumeration
  as a parameter

As for a solution, use overloaded version that supports plain text files.


Comportamento da função preg_match() para abreviação de nomes

Question: Montei uma função que recebe um nome completo com X nomes e sobrenomes e retorna apenas o primeiro nome e o último sobrenome. Caso tenha um conectivo(de, da, do, dos, etc) antes do último sobrenome, ele anexa no resultado.
Porém a função preg_match(), está retornando o contrário esperado pela minha regex.
Exemplo:
function abrevia($var) {
$nomes = explode(" ", $var);
$a = reset($nomes);
$c = end($nomes);
if (count($nomes) > 2) {
    $b = prev($nomes);
    if (preg_match('/^[^A-Z]*$/', $b{0})) {
        return implode(" ", array($a, $b, $c));
    }
}
return implode(" ", array($a, $c));
}

$a[1] = "João Testador dos Testes";
$a[2] = "João dos Testis Testando do Teste";
$a[3] = "João do Teste";

$b = array_map('abrevia', $a);

var_dump($b);

Retorna:
array (size=3)
1 => string 'João dos Testes' (length=16)
2 => string 'João do Teste' (length=14)
3 => string 'João do Teste' (length=14)

Dúvida:
Esta função abaixo, não deveria retornar false(0)?
$b = "da";
var_dump(preg_match('/^[^A-Z]*$/', $b{0})); //retorna 1

Answer: A sua duvida foi respondida, mas você esta prevendo que os dados vão vir sempre formatados como você quer, ou seja nomes e sobrenomes com a primeira em maiúscula e o conectivo em minúsculo...
assim reduziria as possibilidades de erros:
<?php
    function abrevia($var) {
    $nomes = explode(" ", $var);
    $a = reset($nomes);
    $c = end($nomes);
    if (count($nomes) > 2) {
        $b = prev($nomes);
        if (preg_match('/^[deaos]{2,3}$/i', $b)) {
            return implode(" ", array($a, $b, $c));
        }
    }
    return implode(" ", array($a, $c));
    }

    $a[] = "João Testador dos Testes";
    $a[] = "joão dos testis testando teste";
    $a[] = "João do Teste";
    $a[] = "João Testador Das Dores";
    $a[] = "João Testador de Melo";
    $a[] = "João Testador Da Silva";

    $b = array_map('abrevia', $a);

    var_dump($b);
?>

retorna:
array(6) {
  [0]=>
  string(15) "João dos Testes"
  [1]=>
  string(10) "joão teste"
  [2]=>
  string(13) "João do Teste"
  [3]=>
  string(14) "João Das Dores"
  [4]=>
  string(12) "João de Melo"
  [5]=>
  string(13) "João Da Silva"
}

Comment: É porque vem de um Active Directory, aonde os dados são padronizados, não há essa possibilidade porque quebraria uma regra de cadastro.
Answer: $b = "da";
var_dump(preg_match('/^[^A-Z]*$/', $b{0}));

Sua regex diz, combine no inicio de linha(^) algo que não sejam letras maiusculas entre A-Z([^A-Z]) seguido de qualquer caracter(*), quando  é passado $b[0] preg_match() aplica a regex apenas em d já vc está passando o indice da string, o retorno é 1 por que a combinação aconteceu.
Comment: O `^` dentro de uma lista`[]` nega o que estiver nela. Nesse [link](http://aurelio.net/regex/guia/metacaracteres.html) tem a lista completa dos metacaracteres.
Comment: Entendi, qual o operador de negação para letras maíusculas?
O que define que "não seja", ao invés do "seja" ?

O índice da string eu apliquei porque no caso, no meu AD, os nomes dos colaboradores sempre usam o conectivo com minúscula, mas não entendi porque ficou "não seja" ao invés de "seja" minúsculas? Fiquei um bom tempo quebrando a cabeça porque funcionou meu script, mas ao contrário. rs
Comment: Agora ficou claro!
Answer: Tente isso.
/**
 * Abreviar Nome
 * @param String $string Name user
 * @return string
 */
function FirstAndLastName($string) {
    $nome = explode(" ", $string);
    $first = $nome[0];
    $last = end($nome);
    if (count($nome) == 1) {
        $result = $nome[0];
    } else {
        $result = $first . ' ' . $last;
    }

    return $result;
}

Comment: Não funciona, precisa mostrar os conectivos como João da Silva, sua função eliminaria o "da".
No caso, a minha função está correta, só tinha uma dúvida com relação ao retorno da `preg_match()`.
Answer: faz assim
 $nome = 'JOAO DOS TESTES';
 $retira = array(' DE ', ' DOS ', ' E ', ' DO ', ' DA ', ' DAS ', ' DI ');
 $nomeLimpo = str_replace($retira, ' ', $nome);


Trouble Rendering Dynamic Texture from OffscreenCanvas in Three.js Shader

Question: I'm working on a React Three Fiber project where I'm trying to render a dynamic texture from an OffscreenCanvas that's being updated in a WebWorker. However, all I'm getting is a black render on my mesh, and I'm struggling to pinpoint the issue.
I'm using THREE.CanvasTexture for the texture, a custom shader for the material, and a useFrame loop to update the texture. Below are the simplified and relevant parts of my code:
Component (component.ts):
import { useRef, useEffect, useState } from "react";
import { useFrame } from "@react-three/fiber";
import * as THREE from 'three';
import TextureShader from "./TextureShader";

const MyComponent = () => {
  const [texture, setTexture] = useState<THREE.Texture>();
  const meshRef = useRef<THREE.Mesh>(null);

  useEffect(() => {
    const offscreenCanvas = new OffscreenCanvas(100, 100);
    const canvasTexture = new THREE.CanvasTexture(offscreenCanvas);
    setTexture(canvasTexture);

    // Initialize and post message to worker (not shown for brevity)

    // ... other initialization code ...
  }, []);

  useFrame(() => {
    if (texture) {
      texture.needsUpdate = true;
    }
  });

  return (
    <mesh ref={meshRef}>
      <boxBufferGeometry args={[1, 1, 1]} />
      <TextureShader uTexture={texture} />
    </mesh>
  );
};

export default MyComponent;

Shader (TextureShader.ts):
import { shaderMaterial } from '@react-three/drei';
import * as THREE from 'three';

const vert = /* glsl */`
varying vec2 vUv;
void main() {
  vUv = uv;
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`;

const frag = /* glsl */`
uniform sampler2D uTexture;
varying vec2 vUv;
void main() {
  gl_FragColor = texture2D(uTexture, vUv);
}
`;

const TextureShader = shaderMaterial({ uTexture: new THREE.Texture() }, vert, frag);

export default TextureShader;

WebWorker (worker.ts):
// Simplified worker logic for drawing on the OffscreenCanvas
self.onmessage = (event) => {
  if (event.data.canvas) {
    const canvas = event.data.canvas;
    const ctx = canvas.getContext('2d');

    // Drawing logic (e.g., ctx.fillRect(...))
  }
};

The texture should be dynamically updated by the WebWorker, but when applied to the mesh using the custom shader, it only renders black. The shader works fine with static colors, so I suspect the issue lies in either the dynamic texture update process or how the OffscreenCanvas is managed.
What I've tried:
Ensuring needsUpdate is set to true for the texture in the useFrame loop.
Verifying that the WebWorker is correctly drawing on the OffscreenCanvas.
Using a simpler material to rule out shader issues.
Questions:
Could the issue be related to how the OffscreenCanvas is handled in the WebWorker?
Is there a specific way to update a THREE.CanvasTexture from an OffscreenCanvas being drawn in a WebWorker?
Any insights or suggestions would be appreciated
Answer: Just like when we transfer an ArrayBuffer instance it gets detached and its length is set to 0 and you can basically not do anything with it anymore, when transferring an OffscreenCanvas instance, it is also detached, its width and height are set to 0 and you can't access its drawing buffer anymore.

const canvas = new OffscreenCanvas(50, 50);
console.log("before", canvas.width, canvas.height); // 50, 50
// Transfer the OffscreenCanvas (even to the same JS context)
(new MessageChannel()).port1.postMessage("", [canvas]);
console.log("after", canvas.width, canvas.height); // 0, 0

What you could do, is to get your OffscreenCanvas from a <canvas> element, using its transferControlToOffscreen() method. Doing so, the placeholder <canvas> content would get updated every painting frame (basically at the same rate as requestAnimationFrame, and you'll be able to draw it from your main context.
(Using 2D contexts for ease of demonstration, but CanvasTexture should work the same.)

const placeholder = document.createElement("canvas");
const offscreen = placeholder.transferControlToOffscreen();
const worker = new Worker(
  URL.createObjectURL(new Blob(
    [document.querySelector("[type=worker-script]").textContent],
    { type: "text/javascript" }
  ))
);
worker.postMessage(offscreen, [offscreen]);
worker.onmessage = (evt) => {
  const ctx = document.querySelector("canvas").getContext("2d");
  ctx.drawImage(placeholder, 0, 0);
};

<canvas></canvas>

However, doing so, you're always one frame late, and you may face browser bugs (for instance my Firefox fails to use the placeholder canvas as source correctly).
So instead you will probably want to transfer ImageBitmap objects from your worker thread, calling canvas.transferToImageBitmap() and remember to close() it when you're done loading it as CanvasTexture.

<canvas></canvas>


Incrementar vencimentos a parcelas com Jquery?

Question: Possuo um form dinâmico e fiz uma função para somar 30 dias após o primeiro vencimento, mas se insiro datas tendo o dia 31 ou dia 01 está fazendo os calculo errados, exemplo:
se insiro 31/12/2017 como sendo 1º vencimento, em 3 parcelas deveria ficar assim
1º 31/12/2017
2º 30/01/2018
3º 01/03/2018

Mas está saindo assim:
1º 31/01/2018
2º 31/01/2018
3º 31/03/2018

Abaixo segue um exemplo funcional.

$(function() {
  $('#form_forn').submit(function() {
    $('.table-result').show();
    $('#result-table tbody tr').remove();
    var vencimento = $('#txtVencimento').val().split("/");
    var qtde_parcelas = $('#txtParcelas').val();
    var x = 1;
    var acc_vlr_total = 0;
    var acc_vlr_pop = 0;

    vencimento = new Date(vencimento[2] + "/" + vencimento[1] + "/" + vencimento[0]);
    var data_sum = 1;

    while (x <= qtde_parcelas) {
      var data = adicionarDiasData(data_sum, vencimento);
        $('#result-table tbody').append("
" + x + " de " + qtde_parcelas + "	" + data + "
");
      x++;
      data_sum += 30;
    }
    return false;
  });
});

function adicionarDiasData(dias, primeiro_ven) {
  //var hoje = new Date();
  var dia = new Date(primeiro_ven.getTime());
  var dataVenc = new Date(primeiro_ven.getTime() + (dias * 24 * 60 * 60 * 1000));
  return dia.getDate() + "/" + ("0" + (dataVenc.getMonth() + 1)).slice(-2) + "/" + dataVenc.getFullYear();
  //console.log(dia.getDate() + "/" + ("0" + (dataVenc.getMonth() + 1)).slice(-2) + "/" + dataVenc.getFullYear());
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<form id="form_forn" class="form-horizontal" name="novolancamento" method="post" action="#" autocomplete="off">
  <fieldset>
    <legend>Cadastrar novo lançamento Fornecedor</legend>

          1º Vencimento:

            <input id="txtVencimento" name="txtVencimento" type="date" class="form-control input-md" required="">

          Quantidade parcelas:

            <input id="txtParcelas" name="txtParcelas" type="number" placeholder="" class="form-control input-md" title="Valor compreendido entre 1 e 12" required="" maxlength="2" min="1" max="12">

              <button type="submit" id="btnSalvar" name="btnSalvar" class="btn btn-warning pull-right">Simular lançamento</button>

  </fieldset>
</form>

        Parcela
        Vencimento

  <button class="btn btn-success" style="float:right; margin-right: 6%;" id="salvar_lancamento">Salvar</button>

Comment: Já tentou modificar sua função para incrementar 1 mês ao invés de 30 dias?
Comment: @CarlosAndrade, então na verdade estou tendo dificuldade para entender a função date, teria algum exemplo para me informar, outra coisa que esqueci de mencionar é que no retorno da datas os dias de 1 a 9 retornam sem o 0 (zero) a esquerda ficando assim `1/01/2018`
Answer: Você pode fazer a soma de dias utilizando a função getDate e setDate do objeto Date
Dessa forma.
var date = new Date(); // Captura a data de hoje: 22/12/2017
var dayOfMonth = date.getDate() //Captura o dia do mês
date.setDate( dayOfMonth + 30 ); //Soma 30 dias.

console.log(date); //Output: 21/01/2017

$(function() {
  $('#form_forn').submit(function() {
    $('.table-result').show();
    $('#result-table tbody tr').remove();
    var qtde_parcelas = $('#txtParcelas').val();

    /* Capture o tempo em milissegundos desde 01/01/1970 */
    var time = Date.parse($('#txtVencimento').val().split("-"));

    /* Instancia o objeto Date e define a data em milissegundos */
    vencimento = new Date();
    vencimento.setTime(time);

    for (i = 1; i <= qtde_parcelas; i++) {
      var data = vencimento;

        $('#result-table tbody').append("
" + i + " de " + qtde_parcelas + "	" + data.toLocaleString("pt-BR") + "
");

      /* Captura o dia do mês e soma mais 30 dias */
      vencimento.setDate( data.getDate() + 30);

    }

    return false;
  });
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<form id="form_forn" class="form-horizontal" name="novolancamento" method="post" action="#" autocomplete="off">
  <fieldset>
    <legend>Cadastrar novo lançamento Fornecedor</legend>

          1º Vencimento:

            <input id="txtVencimento" name="txtVencimento" type="date" class="form-control input-md" required="">

          Quantidade parcelas:

            <input id="txtParcelas" name="txtParcelas" type="number" placeholder="" class="form-control input-md" title="Valor compreendido entre 1 e 12" required="" maxlength="2" min="1" max="12">

              <button type="submit" id="btnSalvar" name="btnSalvar" class="btn btn-warning pull-right">Simular lançamento</button>

  </fieldset>
</form>

        Parcela
        Vencimento

  <button class="btn btn-success" style="float:right; margin-right: 6%;" id="salvar_lancamento">Salvar</button>

Answer: /* Captura o dia do mês e soma mais 30 dias */
  vencimento.setDate( data.getDate() + 30);

sei que é um pouco tarde, mas achei ficaria melhor assim, não acha?
/* Captura o dia do mês e soma mais 1 mês */
            vencimento.setMonth( data.getMonth() +1);

Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Splash page for mobile website

Question: I am working on a mobile website and I need to have a splash page for 3 sec displayed when the client access the website for the first time. Is there any plugin I can use or what solution can I use.
Thanks
Answer: Put a meta refresh tag in the header of your mobile splash page template:
<code><meta http-equiv="refresh" content="3;url=http://WHEREYOUREALLYWANTTOGO">
</code>
This will display the splash page for 3 seconds before moving on to the page you want them to see next.
Comment: Yes that's quite interesting but I have just found [meerkat](http://meerkat.jarodtaylor.com/) which is very easy to setup.

Splash page for mobile website


Compute the Jacobson radical of $R=\mathbb{F}_3[S_3]$ and find all simple $R$-modules.

Question:
Compute the Jacobson radical of $R=\mathbb{F}_3[S_3]$ and find all simple $R$-modules.

I need to find a surjective map and compute its kernel. But I am not sure which map. Any hints?
Comment: What kind of surjective map are you looking for? Anyway, it seems that $(1)(2)(3)+(123)+(321)$ (the sum over elements in $A_3=C_3$) is in the radical. Dunno if there's anything not generated by it though...
Comment: http://web.maths.unsw.edu.au/~danielch/modules12/exam12.pdf Maybe question 4 here helps?
Comment: Related: https://math.stackexchange.com/questions/1594683/compute-the-jacobson-radical-of-the-group-ring-mathbbf-2s-3?rq=1
Comment: Yes it is but the question didn't include simple modules
Answer: The starting idea is that when the characteristic of the field and the order of the group are not coprime, you are going to have a nonzero Jacobson radical. Because the ring is Artinian, the Jacobson radical must be a nilpotent ideal. If we succeed in finding a nilpotent ideal $I$ such that $R/I$ has zero radical, then we can be assured that $J(R)=I$. (You will need to understand and fully justify this strategy for yourself.)
Like the document you referenced, I like to use $\sigma$ for the generator of order $3$ and $\tau$ for the generator of order $2$.
By the Freshman's dream theorem, $(1-\sigma)^3=1-\sigma^3=0$, so $1-\sigma$ is nilpotent. We'd also like to prove that $(1-\sigma)r$ is nilpotent for any other $r\in R$, but since $1-\sigma$ isn't central, this isn't immediately obvious.
But $(1-\sigma)$ does satisfy a weaker property that does the trick, namely that $(1-\sigma)R=R(1-\sigma)$. The rule $(1-\sigma)\tau=\tau(1+\sigma)(1-\sigma)$ allows you to commute $(1-\sigma)$ from the left of the product $(1-\sigma)r$ to the right to get $r'(1-\sigma)$ for some $r'\in R$. Likewise $(1-\sigma)r'=r''(1-\sigma)$. Then $(1-\sigma)R=R(1-\sigma)$ is a two sided ideal and
$$
((1-\sigma)r)^3=(s-\sigma)r(s-\sigma)r(s-\sigma)r\\= (s-\sigma)rr'(s-\sigma)(s-\sigma)r\\=r'r''(s-\sigma)(s-\sigma)(s-\sigma)r=0
$$
This establishes that $(1-\sigma)R$ is a nilpotent ideal, and hence is contained in the Jacobson radical.
Now let's focus on the kernel of the map $F_3[S_3]\to F_3[S_3/\langle\sigma\rangle]$. Of course, everything in $\langle\sigma\rangle$ is mapped to the identity of the quotient, so $1-\sigma$ is in the kernel.
If $\sum r_g g \mapsto 0$, we know that $\sum_{g\in\langle\sigma\rangle}r_g=0$ and $\sum_{g\in G\setminus\langle\sigma\rangle}r_g=0$
Given that, a little reverse engineering (or just plain long division) shows that
$$(\sigma-1)((r_{\sigma^2}+r_\sigma)1+r_{\sigma^2}\sigma+(r_{\sigma\tau}+r_{\sigma^2\tau})\tau+r_{\sigma^2\tau}\sigma\tau=\sum r_gg$$
demonstrates that $\sum r_gg$ is in $(1-\sigma)R$. So the kernel is equal to this ideal.
By Maschke's theorem, the second group ring is semisimple; moreover, it is commutative. The only two possibilities are that it is a $F_9$ or that it is $F_3\times F_3$. It can't be $F_9$ though: $(1-\tau)(1+\tau)=0$ shows there are zero divisors in $F_3[S_3/\langle\sigma\rangle]$.
Thus $R/J(R)$ has two distinct maximal ideals corresponding to two nonisomorphic simple modules. As an exercise you can attempt to describe the maximal right ideals of the original ring that correspond to these.
Comment: @Bob $G=S_3$. The double subscripts were going to get messy
Comment: What is G? Is it S3?
Comment: Just to clarify the simple R-module is F3xF3?
Comment: @Bob no: the original ring shares the same simple modules as F3xF3, of which there are two. F3xF3 is not simple as a module over itself
Comment: So R is isomorphic to F3*F3, but how do I find the simple modules of this?
Comment: @Bob $R$ is *not* isomorphic to F3xF3. You should be abl to work out the simple modules of a product of fields on your own or with help of other questions here
Comment: What do you mean by second group ring? And how do I do I work out Thus R/J(R) has two distinct maximal ideals corresponding to two nonisomorphic simple modules
Comment: @Bob there are only two group rings here: the other one is $F[S_3/\langle\sigma\rangle]$
Comment: So F[S3/] is isomorphic to F3xF3? I'm not sure how you use Maschke Theorem here.
Comment: @Bob I want you to work on the simple submodules of products of fields on your own for a while.
Comment: @Bob the group has order 2, 2 is a unit in $F_3$ so the second ring is a $2$ dimensional semisimple $F_3$ algebra. It is a direct application of maschke
Comment: I understand why I need to calculate the maximal ideal but how do I find them? Could you provide an example
Comment: I have a homomorphism from S3 to {+/- 1} does this help?
Comment: @Bob  see this about ideals http://math.stackexchange.com/a/2048122/29335
Comment: So in our case $R(0,1)(1-\sigma)$ and $R(1,0)(1-\sigma)$?
Comment: @Bob $(0,1)$ and $(1,0)$  have no meaning in $R$. Take a day to think the pieces over carefully. It sounds like you are rushing.
Comment: I get simple modules as F3x0 and 0xF3 is that right?
Comment: @Bob YES, this is correct. Do you understand why $R$ and $R/J(R)$ share the same simple modules? If you do, then we can start working harder on finding them in $R[S_3/\langle\sigma\rangle]$ and lifting them to $R$.
Comment: Yes, I understand why they share the same simple modules.
Comment: How would I find them? and what do you mean by lift?
Comment: @Bob To find some idempotents in any group ring: take any subgroup $H<G$, sum the elements of $H$, then divide that by $|H|$. The result is an idempotent. This will lead you to the idempotents of $F_3[S_3/\langle\sigma\rangle]$ that split it into two simple submodules. Lifting: if you find a maximal right ideal $T$ of $R/I$, then there must be a maximal ideal $T'$ of $R$ such that $T=T'/I$, by correspondence. This gives you the two maximal right ideals in $R$ that you need from the maximal right ideals in $R/I$.
Comment: $A_3$ is a subgroup of $S_3$. $A_3={1,(1,2,3) and (1,3,2)}$. Sum=1+(1,2,3)+(1,3,2). Divide by 3. I don't understand anything after this point.
Comment: @Bob You ought to be working in $S_3/\langle \sigma\rangle\cong \{1,\tau\}$, not $S_3$ itself.  But anyway, the trick works for $\frac13(1+\sigma+\sigma^2)$: $(\frac13(1+\sigma+\sigma^2))^2=\frac19(3+3\sigma+3\sigma^2)=\frac13(1+\sigma+\sigma^2)$.
Comment: I think I can put the simple R-modules are F3x0 and 0xF3 in my question. Don't think I need the rest. Thanks


Controller for Non-holonomic agents

Question: I have designed a certain controller for a group of holonomic agents (I was assuming that they were holonomic and that they were able to move in the 3D space)
Now I want to use the same controller to control a group of non-holonomic agents (unicycle-like robots) which are just capable to move on the plane.
Their model is
$\begin{split}
v_x = v\cdot \cos{\theta}\\
v_y = v\cdot \sin{\theta}\\
\dot{\theta}=\omega
\\
\end{split}$
Where $v_x,v_y,\dot{\theta}$ are respectively the linear velocities along $x,y$ and the angular velocity around $z$.
$v,\omega$ are the only control inputs I have. Respectively linear and angular velocity.
How would you conceptually do it ?
I implemented the previous controller in MATLAB/SIMULINK
Thanks.
Answer: You can extend you state, such that the relative degree from each input to each output becomes the same. This can be done as follows,
$$
v_x = v \cos\theta,
$$
$$
v_y = v \sin\theta,
$$
$$
\dot{v} = a,
$$
$$
\dot{\theta} = \omega.
$$
So,
$$
\dot{v}_x = a \cos\theta - v\, \omega \sin\theta,
$$
$$
\dot{v}_y = a \sin\theta + v\, \omega \cos\theta,
$$
or
$$
\begin{bmatrix}
\dot{v}_x \\ \dot{v}_y
\end{bmatrix} =
\begin{bmatrix}
\cos\theta & -v\sin\theta \\ \sin\theta & v\cos\theta
\end{bmatrix}
\begin{bmatrix}
a \\ \omega
\end{bmatrix}.
$$
As long as $v\neq0$ then this matrix is invertible and you can linearize and decouple this system using,
$$
\begin{bmatrix}
a \\ \omega
\end{bmatrix} =
\begin{bmatrix}
\cos\theta & -v\sin\theta \\ \sin\theta & v\cos\theta
\end{bmatrix}^{-1}
\begin{bmatrix}
u_x \\ u_y
\end{bmatrix},
$$
$$
\begin{bmatrix}
\dot{v}_x \\ \dot{v}_y
\end{bmatrix} =
\begin{bmatrix}
u_x \\ u_y
\end{bmatrix}.
$$
Comment: @minidiable The last two equations basically show a transformation of virtual inputs, to the actual inputs, such that when using the virtual inputs the system is linear and decoupled. So you can apply simple linear control methods in order to design a control law. For example $u_x = -v_x$ and $u_y = -v_y$ would work, maybe you have to add a little more if you also want to control the x and y positions as well, but you can still find a linear control law which makes the system (exponentially) stable. But you are right that you would run into trouble when $v=0$ (constant position).
Comment: Thanks fibonatic for the great reply.

This was more or less what I had in mind while I was thinking to this problem. I didn't understand fully what you want to say with the last set of 2 equations. If I want to reach a set of desired positions it seems that, with your proposed algorithm, I need always to have a certain velocity $v\neq0$.
Another thing is: my control inputs now are 2 accelerations?
Comment: Hi thanks again for the reply. I am trying to understand better what you described. So, as far as I understood we shift from a controller which has as controlling input the linear velocity $v$ and angular velocity $\omega$ to one which has  linear acceleration $a$ and angular velocity $\omega$.

We said that when $v=0$ the controller won't work. This happens also for $\theta=\pm\frac{k\pi}{2}$ with $k\in \mathbb{N}$ . Correct?
Comment: @minidiable No, if $v\neq0$ then this matrix will always be invertible for all $\theta$. For example take $v=1$ then this matrix is just a rotation matrix, whose inverse is equal to its transpose.
Comment: Yeah sorry. I made a mistake :)
Comment: The way proposed by @fibonatic is the way people usually go. Alternatively let me give another hint. You can work in the polar coordinates by considering the submersion $(v_x,v_y,\theta) \mapsto (r,\theta)$ by setting $r:=\sqrt{p_x^2+p_y^2}$. In these coordinates you have $\dot r = v$ and $\dot \theta=\omega$, i.e. a linear system in which you do not need to invert anything.

Controller for Non-holonomic agents


dalekjs clicks on a link that contains text but it doesnt work

Question: What I am trying to do is to get an element out of a list. I want to take the text in a link and click on the link if it contains the right text. this is the html-code:

I need help

Oh hello

Lorem ipsum

I tried this:
 .click('table > td > tr > a:contains("I need help")')

But for some reason it doesn't work.
I can't use this:
.click('table > td > tr:nth-child(1) > a)

because there will be added more tr tags as the site gets bigger.
Any ideas ?
Answer: You did not create table properly, it should be:

I need help

Oh hello

Lorem ipsum

and this js code working properly
$(document).ready(function(){
    $("table tr td a:contains('I need help')").click(function(){

    });
  });

Comment: It still didn't work for me, it won't execute properly.
Comment: You are making mistake, above code working for me, send me your complete code.
Answer: First of all, your HTML code is a bit twisted; a  has to be a child of an
 element, not the way around. I suggest to read the MDN Docs regarding
 elements.
Regarding your problem with Dalek; Dalek uses the CSS selector engine of the browser that it executes. This will change in the future (Replaced by Sizzle as a unified selector engine), but I have no estimation when this future exactly will be.
Regarding the :contains() pseudo selector - As far as I know, this is gone. The current CSS3 spec has removed it & therefor you can't use that in your Dalek selectors.
Comment: thank you for your anwser I already figured it out about the selectors. Thanks anyway


Where is the best place to save temporary files in Windows

Question: I am busy writing an application that runs under windows
Where is the correct place to save temporary files ?
Answer: If you are using .NET, please use Path.GetTempPath().  This will guarantee that you use the temporary directory assigned to the user that runs your application, regardless of where it is stored.
If you browse the file system, you will notice that there are many "temp" directories:

~\Temp
~\Windows\Temp
~\Users\userName\AppData\Local\Temp

... and many more.  Some of these paths are OS-dependent, and won't be present on certain windows flavors.  So, save yourself some time and hassle, and let the .NET framework figure out where the "temp" path is located.
Comment: Better yet, just use Path.GetTempFileName() which will generate the file name as well, and return the full path to it (in the appropriate temp folder).
Comment: That - or use isolated storage, to which a user is always guaranteed to have write access!
Answer: Use GetTempPath and and possibly GetTempFileName to determine where to put your temporary files.  This is the most reliable, enduser-friendly, and future proof way to get a temporary location for files.
Answer: In the temp directory?
Use GetTempPath or in a batch file %TEMP%
Answer: C:\Temp is NOT a good choice.
If you are using .Net use code like this:
<code>           string baseFolder = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);

        string cfgFolder = Path.Combine(baseFolder, "MyAppName");

        try
        {
            if (!Directory.Exists(cfgFolder))
            {
                Directory.CreateDirectory(cfgFolder);
            }
        }
        catch { } // If no access, not much we can do.
</code>
to get a place for medium-term storage of app data, or Path.GetTempPath() for transient storage of data.
Comment: C:\ might be a really small partition, and in many cases, normal (non-admin) users don't have write permissions on C:\ so they can't create C:\temp
Comment: Why is it not a good idea to use `c:\Temp`? I'm not disagreeing with your point, I'm just curious as to your reasoning =)
Comment: Moreover, who's to say that C:\temp even exists on non-English Windows?
Answer: Use the GetTempPath API, or the equivalent for your programming environment.
Answer: It depends on the language you are using:
<code>string tempFolder = System.IO.Path.GetTempPath();
</code>
will return you the appropriate folder in C# for instance.
or, the environment variables TEMP or TMP if you must.
Answer: C:\Documents and Settings\username\Application Data\IsolatedStorage
Comment: Yes - but please use the documented Isolated Storage API and don't hardcode this path! On a system with a German version of Windows, this would be e.g. "C:\Dokumente\....." and if you hardcode this path, your app will break. FOLKS: IF THERE ARE APIs TO DO SOMETHING, **USE THEM**!!


add arbitrary descriptions div in a node edit or add form

Question: the need seems simple but I don't find anything about this.
I'd like to add descriptions (div class="description"), non related to specific cck fields. I though I could use these to compute informations inside it (to sum up some of the choices of tricky content types) or to show up an information when choosing a particular option (like, to show a "cck description" rather than a true cck widget when using conditionnal field).
template.php does not seems to be the right way : I got a lot of ccks, and a lot of content types, I just cant create a hook for each case I need this is not flexible enough. I suppose.
is there any 'dummy' cck field with just a description array and no widget I could use like a normal cck, and locate as any other cck in my forms ?
or : how could I write a 'cck description' module (I'm ok with php and drupal module simple setup)
Im using D6.x
Answer: it sounds like you want a custom div to show for certain form values ... or on some conditional ajaxy thing on the form ...
I would basically use hook_form_alter with a case statement probably, or some use of nested array keys to add #prefix elements into the form.
The simplest example would be:
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'my_content_type_node_add') {
    $form['field_FOO']['#prefix'] = '
a description goes here...
';
  }
}

You said you had a million of these, all over the place ... no big deal. Somewhere in your module as a variable or tucked away in a function:
// A simple array lookup of $form_id => $fields => $descriptions ...
$descriptions_map = array(
  'my_content_type_node_add' => array(
    'field_FOO' => 'a description goes here ....',
     ),
    'field_ANOTHER_BAR' => '...',
  ),
  'some_other_content_type' => array ...,
);

Using this simple lookup table (which could help tidy up your code) ... you then make hook_form_alter use it by looking at the array keys and eventually setting form values ... I'm leaving out an ugly bit of code with for loops and calling like array_keys but ...
$form[$field_key]['#prefix'] = $field_key_description;


Present in a circle

Question: I found the following riddle:
There are 10 persons in a circle. Person $1$ has a present. This person gives it to the right or to the left with equal probability. The next person with the present does the same. They repeat this until only one person didn't have the present. This person gets to keep the present. Where do you place yourself to have the highest chance to get the present?
I guess you should place yourself on the opposite side of the circle to face person $1$. But how to I proof this mathematically? I can't calculate the probability for each position, because there are infinite possibilities to pass the present to a third person, because two persons could just pass the present to each other every turn. Can someone give me a hint or is there an easier solution?
Comment: You can calculate the probabilities recursively, though I don't see a very fast way to do it.  For example, assume you start at slot $1$ and let $P(i,n)$ be the probability that $i$ is last, given $n$ slots.  Then, recursively $P(2,n)=\frac 12\times 0+\frac 12\times P(2,n-1)$ which implies, barring error, that $P(2,10)=2^{-8}$.  Of course this is also $P(10,10)$.  Continue in this way.
Answer: It doesn't matter where you place yourself, because each position has an equal probability of $1/9$ of getting the present.  We show a connection between this problem and the classical Gambler's Ruin Problem.
The Gambler's Ruin Problem goes like this:  there are two players, $A$ and $B$, who flip a fair coin.  Each time the coin comes up heads, $B$ gives $A$ a coin, and each time the coin comes up tails, $A$ gives $B$ a coin.  Player $A$ initially has $a$ coins and $B$ has $b$ coins, and the game continues until one of the players runs out of coins.  It can be shown that the probability that $A$ wins the game is
$$\frac{a}{a+b}$$
This result is well-known, but we sketch a proof below for completeness.  There is also a version of the problem in which the coin is biased, but we will not need that version.
An alternative formulation of the Gambler's Ruin Problem is to consider $A$'s cumulative gain, which may be negative.  His initial gain is zero.  At each coin flip his gain increases by one or decreases by one with equal probability.  He wins if his gain reaches $b$ without ever reaching $-a$.
Now for the problem of $10$ people standing in a circle, with the present initially at person $1$.  Consider a move of the present from $1$ to $2$ as a move to the right, and a move from $1$ to $10$ as a move to the left.  Then person $2$ gets the present if and only if the present reaches $8$ steps to the left without ever reaching $1$ step to the right from its original position.  This is equivalent to the Gambler's Ruin Problem with $a=1$ and $b=8$, so the probability that person $2$ gets the present is $1 /(1+8) = 1/9$.
Suppose the present reaches $7$ steps to the left without ever reaching $1$ step to the right.  This happens if and only if either person $2$ or $3$ gets the present, and is equivalent to the Gambler's Ruin Problem with $a=2$ and $b=7$, so the associated probability is $2/(2+7) = 2/ 9$.  Since we already know the probability that person $2$ gets the present is $1/9$, the probability that person $3$ gets the present is $2/9 - 1/9 = 1/9$.
At this point I think the pattern is clear, and we will leave it to the reader to complete the proof that the probability that any one person gets the present is $1/9$.

Here is a short derivation of the Gambler's Ruin Problem formula. Let $P(a,b)$ be the probability that player $A$ will win the game when he initially has $a$ coins and player $B$ has $b$ coins. The first flip of the coin is heads with probability $1/2$, and tails with probability $1/2$.  If heads, then $A$ now has $a+1$ coins and $B$ has $b-1$ coins; if tails, then $A$ now has $a-1$ coins and $B$ has $b+1$ coins. So
$$P(a,b) = \frac{1}{2} P(a+1, b-1) + \frac{1}{2} P(a-1,b+1)$$
for $a \ge 1$ and $b \ge 1$, with
$P(a,0) = 1$ and $P(0,b) = 0$
for $a>0$ and $b>0$.  It is easy to verify that
$$P(a,b) = \frac{a}{a+b}$$
satisfies this recursion and the boundary conditions.

Edited June 16, 2018: I had the numbers of persons $2$ and $3$ mixed up in the derivation of person $3$'s chance of winning.  (I had written $1$ and $2$ instead of $2$ and $3$.) This has been corrected.
Answer: Placing yourself on the opposite side of the circle is probably the worst position: think about it. After 4 gives there is a 1/16 chance it is 4 steps to the right or left. But it would be in one or the other. The gift has to eventually travel around the circle. The best position would likely be next to the person that starts with the gift. Sure, it could take one step right & then weave a lefterly path: but I think that's the way to bet.
To win from the opposite seat, it must go around one way, then, eventually around the other way: quite unlikely!
Comment: But is it really more likely that the present travels around the circle in only one direction rather than "swinging" from left to right? My idea was that person 1 holds the present most often, the persons adjacent to 1 hold it second most often and so on. I thought about the present like a pendulum.
Comment: You misunderstand: I'm not saying it's not swinging back & forth, just that the result is reaching a certain position. Let's call objective 1 going around & reaching the next person to you sitting opposite the original holder.
Comment: Well I screwed up by accidentally hitting edit. Here's the point. After reaching objective 1 you are in the exact situation I started you with by sitting you next to the original holder. Thus whatever the probability of reaching objective 1, it is exactly that many times more difficult to win sitting opposite than in sitting next to the original holder!
Comment: I just had an idea thanks to your example. Is it possible, that every position has an equal chance to get the present? If you sit right next to person 1, then the present has to travel around the circle in the opposite direction until it reaches the other person next to me. For every postion in the circle at one time one adjacent person holds the present and the other adjacent didn't hold it(objective 1). Now it also has to travel around the circle in the opposite direction. Is this correct?

Present in a circle


C# - get data between dates

Question: The SQL database I am trying to reach has the following columns and their types (as displayed in the "design" window in Microsoft SQL Server Management Studio):
timestamp : Datetime (for example : 2017-05-15 08:53:55.000)
price : Single               ,             etc.
I want to send to select all the prices where their timestamp is between now and yesterday, for example. Even though i would like an example for a month too.
My code looks like this:
string query = "SELECT price FROM table WHERE  timestamp>=@now AND timestamp<=@yes);";
        SqlCommand command = new SqlCommand(query, sqlConnection);
        command.Parameters.AddWithValue("@now", DateTime.Now);
        command.Parameters.AddWithValue("@yesterday", DateTime.Now.AddDays(-1));

But my reader returns empty, what am I doing wrong?
Comment: And `@yes` <> `@yesterday`
Comment: Why don't you use `GETDATE()` instead of passing `@now`?
Comment: Please tag properly.  MySQL is not SQL Server.
Comment: @Eric understand, thanks.
Comment: @TabAlleman thanks
Comment: @CamiloTerevinto can u explain?
Comment: GETDATE is a built-in function that returns you the current datetime of the database server, you can use that instead of passing the now parameter
Answer: You can use BETWEEN, also Yesterday is less than Today:
SELECT price FROM table WHERE timestamp BETWEEN @yesterday AND @now

Answer: You have your dates the wrong way around, try this instead:
SELECT price FROM table WHERE  timestamp >= @yes AND timestamp <= @now;

Comment: You should also add that `@yes != @yesterday`. Otherwise this is just as broken
Comment: @CamiloTerevinto  Was that really worth a downvote?  There are clearly several things wrong with the code in the question, though per the question it is actually running.  This would suggest that this is simply a badly transposed snippet aiming at a minimal example.  My answer shows what the issue is.
Answer: You have the @now and @yes reversed, currently it is saying timestamps greater than now and less than yesterday.

C# - get data between dates


How to tell if data has homgenous variance?

Question: I am checking the assumptions of ANOVA model and I want to see if the condition of homogeneity of variances is met in my model. I made such a plot, but I am not sure what to look at here and what conclusions to draw...
Comment: If you are the person who asked about a [similar `Time~Programme` model](https://stats.stackexchange.com/q/575731/28500), see [this page](https://stats.stackexchange.com/help/merging-accounts) for how to merge your accounts.
Comment: Another highly similar question: https://stats.stackexchange.com/questions/576120/detecting-homogenity-of-variance-from-the-plot
Answer: For an ANOVA model like this, you have 1 mean value estimate for each of 3 groups. The residuals are the differences of each individual observation from its corresponding group mean.
Roughly, the spread of the residuals should be about the same for all groups and not depend on the predicted values. The spread in your data seems to increase somewhat with the predicted values. With an ANOVA model like this, a q-q plot can be more helpful, as it gets around the point-overlap problem in the residuals-vs-fitted plot that you show.
Both the middle- and high-fitted groups seem to have a clumping pattern among the residuals: some very close to the fitted value, some substantially higher, and some substantially lower (residuals of $\pm 20$ around means of about 40 to 50). For the ideal normal distribution of residuals, you should have a less clumped distribution with residuals gradually decreasing in frequency as you move away from 0 on both sides.
A non-normal distribution of residuals doesn't necessarily invalidate ANOVA. This page goes into detail about how you can handle non-normality of residuals and heteroscedasticity in ANOVA.
That distribution of residuals, however, makes me wonder if there's some other variable to consider. For example, might the age or comorbidity status of a patient be contributing to this, with older/sicker patients having high residuals and younger/healthier ones lower? Alternatively, could this represent day-of-the-week issues? If performance tests are only performed on weekdays, then you might have gaps in the observed Time if there aren't observations on weekends.
I'd worry about those potential systematic issues first. Then consult the pages linked above.
Comment: _"That distribution of residuals, however, makes me wonder if there's some other variable to consider"_ - do you mean by that that it is better to consider the model such as: `Time ~Program + Day_of_the_week` and do two-way ANOVA?
Comment: @MaximeTars that model wouldn't do what you need. For the weekend/weekday problem you have what's called "interval censored" time values: you know lower and upper limits to the time, but not the actual time. That can be handled by some types of survival analysis. In general, a 2-way ANOVA includes an interaction between 2 categorical predictors, not just their additive terms as you write. You write `Time ~ factorA * factorB`, not `Time ~ factorA + factorB`


Upload and read CSV file in google app engine

Question: I am uploading a CSV file from a form and would like to retrieve its first line in Python. I am on an App Engine application, and using webapp2 (don't know if it's relevant?).
I tried many answers that I found on forums, but none is working. I tried:
def post(self):
    csv_file = self.request.POST.get('csvFile')
    fileReader = csv.reader(csv_file.file)

But I get: AttributeError: 'unicode' object has no attribute 'file'
I also tried:
def post(self):
    csvFile = self.request.get('csvFile')
    print csvFile

    stringReader = csv.reader(StringIO.StringIO(csvFile))
    for row in stringReader:
        print row

But I get:
C:\fakepath\my_file.csv
['C:\\fakepath\\my_file.csv']
for my print statements (whether I do request.get or request.POST.get).
I also tried:
def post(self):
    content = self.request.POST.multi['csvFile'].file.read()

But I get: AttributeError: 'str' object has no attribute 'file'
I also tried:
def post(self):
    csvFile = self.request.files['csvFile']
    file = open(csvFile, 'r')

But I get: AttributeError: files
I also tried:
def post(self):
    csvFile = self.request.POST['csvFile'].value.decode('utf-8')
    file = csvFile.splitlines()
    data = csv.DictReader(file)

But I get: AttributeError: 'unicode' object has no attribute 'value'
I don't understand these errors since many of these solutions seem to work for other people.
My form looks like this (I am using Polymer):
<form is="iron-form" action="/upload" method="POST" enctype="multipart/form-data"
                          on-iron-form-submit="_formSubmitted" id="form" name="form">

                            <input type="file" name="csvFile" id="file" class="inputfile"
                                   data-multiple-caption="{count} files selected" multiple on-tap="_chooseFile"/>

                                Choose a CSV file...

Do you have suggestions?
Thank you!
Answer: I finally found the problem: It comes from Polymer, the object 'iron-form' does not support enctype="multipart/form-data". I removed is="iron-form" and all worked fine.


About a certain type of polynomial

Question: Let $p$ be a polynomial over the set of positive integers such that $p(n) > n$  for all positive integers $n$. It is also known that for every positive positive integer $m$, there exists a term of the sequence $1,\, p(1),\, p(p(1)),\, p(p(p(1))), \dots$ divisible by $m$. Then it is easy to see that $p(n) = n + 1$ satisfies all the criteria, cause then $p(n) > n$ and the sequence becomes $1, 2, 3, \ldots$ just the sequence of all positive integers.
Does there exist any other polynomial which satisfy all the criteria ?
Comment: You might want to take a look at [this](http://math.stackexchange.com/questions/8101/iterated-polynomial-problem).
Answer: Define $a_i = p^i(1)$. So the $a_i$ are just $1,p(1),...$. Now, remark that as $p(n) > n$ we have for some sufficiently large $L$ that $a_{i+1} > 10a_i$ for all $i > L$ if $\deg f > 1$ (this is simply because $a_i$ is unbounded, and the $10$ is just some big number).
Now, take some $i > L$. Remark that $p(a_i) - a_i > 9a_i$. However, one can easily show using $a-b\mid p(a)-p(b)$ that we have $p(a_{k}) \equiv a_k \bmod{(p(a_i) - a_i)}$ whenever $k \ge i$ by induction. Obviously $(p(a_i) - a_i) \nmid a_i$. Thus we have $(p(a_i) - a_i) \nmid a_k$ for any $k \ge i$. Take $k = p(a_i) - a_i$ to get a desired contradiction, as $k$ does not divide $p(1),..., p(a_{i-1})$ due to $k > p(a_i)$ and the $a_i$ being monotonically increasing.
Thus we are reduced to the degree 1 case, in which Gerry Myerson provides a great proof that $p(n) = n+1$ is the only solution.
BTW, I think this problem is a previous IMO Shortlist Problem or from some country's national olympiad. However, I was unable to determine the source.
Answer: I don't know. Here's how far I got with the linear case. Suppose $p(x)=ax+b$ with $a,b$ integers, $a\ne1$. Then the $n$th term in your sequence is $$a^n+{a^n-1\over a-1}b$$ For this to be a multiple of some prime $q$, we need $$(a+b-1)a^n\equiv b\pmod q\tag1$$ Now for any $a$, there will be primes $q$ such that $a$ has a relatively small order modulo $q$, and modulo such $q$ there will be very few different values of $a^n$, and very unlikely that any $n$ will satisfy (1). So I'm convinced (although I recognize I haven't given a proof) that there are no such linear polynomials with $a\ne1$. And for $a=1$ it's easy to see $b=1$, since any prime dividing $b$ can't divide any term in the sequence.

About a certain type of polynomial


How to install apache tomcat to a custom directory?

Question: When I go to C:\Apache24\bin and install apache using httpd -k install, it installs into C:\Program Files.
I am unable to do anything with the war files when this happens, because I always get the error

java.io.IOException: Unable to create the directory

What must I write in the C:\Apache24\httpd.conf file to make it install to C:\Apache Tomcat instead of C:\Program Files?
Comment: Your question is asking about Apache HTTPD, not Apache Tomcat so please clarify what you actually want. However, you don't have to place your war files in `C:\Program Files` at all.
Answer: First, httpd -k install only installs or registers Apache Httpd (which is not Tomcat) as a Windows service, so it has nothing to do with your problem. You must have installed Tomcat some other way, either using the Windows service installer or by unzipping the installation zip file.
Second, the directory where war files are located is defined in the server.xml:
<Host name="localhost"  appBase="c:\whatever" unpackWARs="true" autoDeploy="true">

The appBase attribute defines where the server will look and unpack its jar files.


why json values converted to string in my code

Question: I have a few values that I want give from Json
what I received from server:
(as you can see values aren't string)
<code> "HP": {
  "BaseValue": 44.0, //float
   "Point": 3.0, //float
   "UpdateFactor": 1.5 //float
   }
</code>
After receiving jason from server
<code>IEnumerator ReceiveJson()
{
    var postScoreURL = Url;
    var postHeader = new Dictionary<string, string>();
    postHeader.Add("Content-Type", "application/json");
    WWW request = new WWW(postScoreURL, null, postHeader);
    yield return request;
    if (request.error != null)
    {
    }
    else
    {
        Receive = JSONNode.Parse(request.text);
        Debug.Log(Receive);
    }
}
</code>
why I received string value?
(but here I have string values!!!)
<code> "HP": {
  "BaseValue": "44.0", //string
   "Point": "3.0", //string
   "UpdateFactor": "1.5" //string
   }
</code>
Comment: Did you try using `.AsFloat` ?
Comment: @MarkC. yeah I used it but I it return 0 !!! I think because it's string it return it
Comment: Is `Receive` a class or some C# representation of JSON?
Comment: @MarkC. `Receive["HP"]["BaseValue"].AsFloat`
Comment: Try `.AsInt`. as a test?
Comment: @MarkC.I need this value of float.
Comment: The point was to see if it would still be a string or not.. hence the words "try" and "test"
Comment: @MarkC. I try Receive["HP"]["BaseValue"].AsInt and return 0!
Comment: Are you tied to this JSON parsing library or can you utilize Newtonsoft or another library?
Comment: I use the SimpleJson library, but tell me if you have a better library
Comment: I would just go with Newtonsoft Json.NET
Comment: use https://app.quicktype.io to create a proper model class and then use Unity's JSONUtility to parse it
Answer: Your json is invalid.
You can check your json at Jsonlint.
Your json needs to look like this:
<code>{
    "HP": {
        "BaseValue": 44.0,
        "Point": 3.0,
        "UpdateFactor": 1.5
    }
}
</code>
Comment: what part of my jason is invalid?
Comment: That is simply not true. Floating point numbers are perfectly valid JSON.
Comment: Yes, floats are perfectly valid, but the JSON is still invalid (it needs to be surrounded with `{...}`
Comment: Floats are perfectly valid, not sure from what spec you got that from.
Comment: Even the link you posted will validate floats successfully.
Comment: OK. I'm wrong, sorry. I've edited my answer. Thanks for the down votes, I deserved them.
Comment: OK, now you have edited, can you say that the floats won't be enclosed inside quotes any more?


taylor expansion of scalar fields

Question: Starting of with electrodynamics I have to compute the taylor expansion around $\vec{r} = 0$ of
$\psi (\vec{r}) = |\vec{r} - \vec{r_0}|^{\frac{3}{2}}$ where $\vec{r_0}$ is a constant vector up to second order and
$\psi(\vec{r}) = e^{i\vec{k}\cdot \vec{r}}$ where $\vec{k}$ is a constant vector up to arbitrary order.
I don't have problems with multidimensional taylor expansions as long as there  are no vectors involved and functions look like $f(x,y,z) = y \cdot \sin(xz) + xz^2$ for example. Therefore, in the cases above I feel lost.
Can someone explain how to solve the exercise?
Answer: I think Taylor series expansion of $\phi(\vec r+\vec l)$ ,where $\vec r$ is variable and $\vec l$ is a constant vector, can be written as $\phi(\vec r+\vec l)=\phi(\vec r)+\vec l.\vec \nabla\phi(\vec r)+....$ in analogy with the general form of taylor series expansion $f(x-a)$=$f(a)+xf'(a)+\frac {x^2}{2!}f''(a)+....$; but not sure about it. I have seen this formula used in solution of a problem in a book, but I'm not sure about it.
Answer: Since you are already OK with multidimensional Taylor expansions, note that if we call $\vec r = \begin{pmatrix}x \\ y \\ z\end{pmatrix}$, $\vec r_0 = \begin{pmatrix}x_0 \\ y_0 \\ z_0\end{pmatrix}$, and $\vec k = \begin{pmatrix}k_x \\ k_y \\ k_z\end{pmatrix}$, then
$$|\vec r - \vec r_0|^{3 \over 2} = |\vec r - \vec r_0|^{2 \cdot \frac{3}{4}} = \left[(x-x_0)^2+(y-y_0)^2+(z-z_0)^2\right]^\frac{3}{4}$$
and
$$e^{i\vec k \cdot \vec r} = e^{i(k_x \cdot x+k_y \cdot y+k_z \cdot z)}$$
Can you proceed from here?

taylor expansion of scalar fields


Is it possible to calculate a p-value from a modified test?

Question: I was asked to fit a distribution to some data and calculate the goodness-of-fit and a corresponding p-value. I've been using Pearsons chi-squared test (chi2gof in matlab) to do this but my advisor told me to used a separate equation to calculate the test statistic. Instead of Pearson's equation, I've been asked to use $\chi^2=\frac{1}{n−m}\sum_{i=1}^n\frac{(Oi−Ei)^2}{σ_i}$, where $m$ are the degrees of freedom and $σ$ is the standard error of each histogram bin. I'm not familiar enough with statistics to know if we can just modify a test like that and get meaningful results. I imaging I would have to make a new test but I don't know how I'd go about doing that. I'd appreciate hearing some others thoughts on this. Thanks!
Answer: The easiest approach to estimate a p-value is to simulate from the null distribution and determine how often the test statistic is as extreme as (or more extreme than) the result from your sample.
Take the distribution that you are checking for goodness-of-fit, simulate data, calculate your (modified) test statistic, repeat.


Place an Auto-sized widgets based on the parent widget's Width and height

Question: Goal: Achieving Auto-size widgets based on the parent widget's constraints

Use Case: Placing two buttons on the same Row but being adaptive to multiple screen sizes (Responsive)
Problem: I have two buttons (each of them wrapped inside a column widget) that is wrapped inside a Row widget.
To sum: (Parent->child): Row > [Column - Column]
As shown in the screenshot below.

Tried-solutions: I tried placing the widgets inside of an Expanded widget, that is placed inside of a Flex Widget
Padding > Flex > Expanded > Row > [Widgets]
The code is as follows:
Padding( //Main Padding
            padding: EdgeInsets.only(top: 14, bottom: 14),
            child: Flex(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              mainAxisSize: MainAxisSize.max,
              direction: Axis.horizontal,
              children: <Widget>[
                Expanded(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    mainAxisSize: MainAxisSize.max,
                    children: <Widget>[
                      ChipButton(text: 'Main Size', withIcon: false),
                      ChipButton(text: 'Others', withIcon: false),
                    ],
                  ),
                ),
              ],
            ),
          ),
          Padding(
            padding: EdgeInsets.only(top: 14, bottom: 14),
            child: Expanded(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                mainAxisSize: MainAxisSize.max,
                children: <Widget>[
                  ChipButton(text: 'trademark', withIcon: false),
                ],
              ),
            ),
          ),
          Padding(
            padding: EdgeInsets.only(top: 14, bottom: 14),
            child: Expanded(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                mainAxisSize: MainAxisSize.max,
                children: <Widget>[
                  ChipButton(text: 'Price', withIcon: false),
                  ChipButton(text: 'Color', withIcon: false),
                ],
              ),
            ),
          ),

Answer: Try modifying the code below to your app:
Padding(
        padding: EdgeInsets.only(top: 14, bottom: 14),
        child: Column(children: <Widget>[
          Row(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                Expanded(
                    child:
                        Container(color: Colors.amberAccent, child: Text("A"))),
                Expanded(
                    child:
                        Container(color: Colors.blueAccent, child: Text("B"))),
              ]),
          Row(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                Expanded(
                  child: Container(color: Colors.grey, child: Text("C")),
                ),
              ]),
          Row(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                Expanded(
                    child:
                        Container(color: Colors.redAccent, child: Text("D"))),
                Expanded(
                    child: Container(
                        color: Colors.orangeAccent, child: Text("E"))),
              ]),
        ]),
      ),

It produces something like this:

You can also view the DartPad code I worked on here, in case you want to check if it works on different widths :D
P.S. I really like the way you've asked your question.
Comment: Thank you so much, your answer is very helpful and it did the job well, This is the result (https://snipboard.io/tH2ojs.jpg) i just added a padding around every container, and it is rocking!


Assigning a concrete Task to a variable of type Task

Question: Consider a class Foo which wholly implements IFoo.
Concurrently, consider a task Task<IFoo>.
Why is it that when the following is called, a compilation error is thrown;
Task<IFoo> task = Task.Factory.StartNew(() => new Foo());

The compiler states that it cannot convert from source type Task<Foo> to Task<IFoo>. While this makes sense because they are essentially two differing types, would it not fall under the same premise as IList<IFoo> list = new List<IFoo>{new Foo(/* construct */)};, or other similar assignments?
At the moment I am forcing a cast to the interface, but this feels unneccesary.
Comment: Your counter-example isn't counter. List cannot be assigned to IList, either.
Comment: Huh, you're right. I guess this falls under the same blanket then.
Comment: I usually return concrete from a mixture of Portland Cement ad water. Perhaps you could edit your title to be more descriptive.
Comment: Daniel, I edited your title to be a bit more precise, in line with the suggestion from @PieterGeerkens.
Answer: That is because this statement Task.Factory.StartNew(() => new Foo()); returns an instance of type Task<Foo>.
And given that the Task<> class is a concrete class, it cannot be covariant, unless it were implementing a covariant interface (i.e. ITask<out T>).
Note that there is a uservoice topic to do just that: "Make Task implement covariant interface ITask".
Also note the following possible explanation on why it is the way is it now, "Lack of Covariance in the Task Class":

Framework guidelines are:

If your framework already includes an interface for other reasons, then by all means make it co+contravariant.
But don't introduce an interface solely for the purposes of enabling co+contravariance.

The justification is that the advantage of covariance is outweighed by the disadvantage of clutter (i.e. everyone would have to make a decision about whether to use Task<T> or ITask<T> in every single place in their code).

For now you will have to do:
Task<IFoo> task = Task.Factory.StartNew<IFoo>(() => new Foo());

Comment: Thanks, for this. What I was really after what a why rather than a how, and this hit the nail on the head.
Comment: @DanielPark If you think this sufficiently addressed your question, you may want to accept it as the answer, so that your question can be removed from the "unanswered questions" list.
Answer: You can use generic version
Task<IFoo> task = Task.Run<IFoo>(() => new Foo());


Pyqt4 to Pyqt5 and python code error

Question: i switch from Pyqt4 to Pyqt5 and from python2.7 to 3.4 and i found a bug in Pyqt5 so i upgrade it to the last version which is not suppoted by python3.4 . than i used python3.5 and it work fine except one module called pymaxwell.
always the app crash and closed and to confirm i go back to python2.7 and i use pyqt5 for python2.7 and the same error ; the app closed immediately and show me an error in a part in the code which is work well with pyqt4.
in the gif a comparaison between Pyqt4/Pyqt5 with python2.7
comparison

the part of the code which have problem:
<code>        self.btnMXSmxm()
        self.mxs_filt.setChecked(True)
        self.show_folder.setChecked(False)
        inPath = self.input_mxs_scene_2.text();
        self.input_mxs_scene.setText(inPath);
        self.mxm_list.clear()
        if len(inPath) == 0:
           self.chosen_material.clear()
        # loop over all mxs
        else:
            mxsList = self.input_mxs_scene.text()
            print mxsList
            if not len(mxsList) == 0:
                scene = Cmaxwell(mwcallback);
                ok = scene.readMXS(mxsList);
                sceneMaterials = scene.getMaterialNames();
                materialcount = int(scene.getMaterialsCount()[0])
                if os.path.isfile(self.input_mxs_scene.text()):
                    for name in sceneMaterials:
                        scenematerial = scene.getMaterial(name)
</code>
Comment: In the image samples that you use `mxsList = self.input_mxs_scene.text().toAscci().data()` instead in the code you place only samples `mxsList = self.input_mxs_scene.text()`, which code are you using?
Comment: both of them give the same result and the same error
Comment: Show only one version since you confuse us, in addition your error is irreproducible since you show an incomplete code, if you want us to help you could publish your project in github or similar and share the link.
Comment: i just want if pyqt5 have a problem with the code; because it work fine with pyqt4; so maybe this is a bug in pyqt5 and the code need pymaxwell and maxwell render installed in the system ; who want download them to try ?
Comment: mmmm, because to blame a bug, Qt5 made many changes, and therefore pyqt5, in addition to that pyqt5 tries to use things native to python, for example in PyQt4 the functions that worked with text used the class QString, this tenie the method toAscci as samples in your code, but in PyQt5 uses the native str data type of python, I recommend you run it from the terminal and observe the error messages, look in the docs if the function has renamed or deleted the functions.
Comment: thanks i also asked pymaxwell developers to know about the problem; and every pyqt5 version give me a different error ; i tried many python version with many pyqt5 versions , what i like in pyqt5 is easier to use in some things and have bettr media player ; i will create simple code and try with it; thanks for informations
Comment: in this line : inPath = self.input_mxs_scene_2.text(); i remove the comma (;) and than the error disappear but now i have other problem with pymaxwell and i wait response of the deveolpers
Comment: problem solved ; python with pyqt5 don't read mxsList so i use str(mxsList) and it work fine
Comment: and big thanks eyllanesc ; you give an idea how to resolve the problem
Comment: with python 2.7 and pyqt5 work fine but the problem still happen with python 3.5 and pyqt5 even i use str()
Answer: problem solved;
i use python 3.5.4 and pyqt 5.9
now even i use read(file) or read(str(file)) don't give any error.
and i find that with pyqt5 it need new arrangement of some lines in the code.
i modify the code and it work :
<code>        mxsList = self.input_mxs_scene.text()
        scene = Cmaxwell(mwcallback)
        materialcount = int(scene.getMaterialsCount()[0])
        if not len(inPath) == 0:
            if os.path.isfile(self.input_mxs_scene.text()):
                ok = scene.readMXS(mxsList)
                sceneMaterials = scene.getMaterialNames()
                if not len(mxsList) == 0:
                    for name in sceneMaterials:
                        scenematerial = scene.getMaterial(name)
                        # #print scenematerial
                        self.mxm_list.addItem(name)
</code>
i also add : from PyQt5.QtCore import *
that solve other problem with reading media files
after many tries with different versions of python and pyqt5 ; the best versions works well together , python 2.7.9 and pyqt5 from github :
PyQt 5.7.1 for Python 2.7

Pyqt4 to Pyqt5 and python code error


What does it mean when an array name is in parentheses with a caret pointer before it?

Question: I have an array of unsigned numbers, called dataArray (actually in the program I am trying to figure out, they are entered as hexadecimal numbers, but I don't think that's important). I have another variable of type unsigned char, called c.
What does this do?
unsigned int dataArray[]={1,2,3,4,5};
unsigned char c;
x=c^ (dataArray)[i];

I have read that the caret is a reference to c, but what does it mean when the array name is in parentheses? It seems that x is just set to the (i-1)th element in dataArray, but under what conditions is that not so?
Thanks.
Comment: Are you not getting any error?? its c XOR dataArray[i]. You dont have value for c and i.
Comment: Is this from a CRC calculation by any chance?
Answer: The parenthesis don't impact the semantics here. x is computed as the bitwise exclusive-or of c (undefined here) and dataArray[i].
Comment: It's the element at index i being XOR'ed with C, not the whole array.
Answer: In some derived language, the caret is used to declare a managed pointer. It's the so-called C++/CLI language made by microsoft and is used in .Net. It doesn't have that meaning in normal C++. In expressions, the caret means, as already explained by others, the bit-wise XOR, anyway.
Answer: The ^ character as it is used here is a bitwise XOR (see wikipedia).  The parentheses don't to anything here, as the operator [] has higher precedence than bitwise-xor.
Answer: If this is really C++, then the '^' is the XOR bitwise operator.  The parentheses are extra and do nothing in this example.
Answer: The ^ is not overloaded, as far as I know.  If it is entered and compiles properly, it is going to attempt a XOR operation, though in this case it's probably going to be messing with data you don't want it to...
Answer: Ok, cool. That makes sense in the program I'm using. I had thought the caret was a pointer, but it's an XOR and then later on in the line there's an & (bitwise AND). The program is for sending and receiving signals from electronics, so bit-level logic is to be expected. Thanks very much for the fast replies.
Comment: It is preferred to edit one's question or write a comment, instead of writing an "answer" which isn't one.  Nothing bad happens, but keep in mind, that those answers are seldom viewed in chronological order, but all of them indeed stay mostly on their own.


function with a given average value, how to create?

Question: I want to create a function f(x) defined on the interval [0..1], which has all of the following properties on the interval:

It is continuous and differentiable throughout the interval, and can be expressed in a closed form without integrals, or through the use of piecewise functions.
$f'(x)$ is never negative for any value of $x \in [0..1]$
$f(0)$ is 0 and $f(1)$ is 1. and $f''(x)$ cannot change sign more than once in the interval.
If one were to select an $x$ randomly from a perfectly uniform distribution on $[0..1]$, the limit on the average $f(x)$ over an infinite number of tries approaches some particular value $c$.

Given some real value for $c \in (0..1)$, what is the simplest way to generate an $f(x)$ that satisfies the criteria?
The first three criteria are fairly easy to achieve...  consider the rational function:
$$g(x) = \frac{xk}{2kx-k-x+1}$$
satisfies the first 3 properties, guaranteeing intersection with the point $\left(\frac{1}{2},k \right)$, and even satisfies the 4th property for special case where $k=c=\frac{1}{2}$.
I do not know, however, how to satisfy the 4th property in general.  I am thinking that it may simply be some kind of modification to the above function, but don't know for sure.
Do I need to find a value of $k$ for the above function $g(x)$ such the closed integral of $g(x)$ for $x=0..1$ = $c$?   This might be possible for me to calculate, I haven't tried yet, but if it doesn't yield a function that satisfies the fourth property, I fear it would ultimately only be a waste of time.  I am hoping there may a more elementary solution.
Answer: Literally just $x^n$ LOL.
For nonnegative $n$, as $n$ increases, the average value is closer to zero, and as $n$ decreases towards zero, the average value is closer to $1$.
All other three criteria are fulfilled too.
Comment: Pretty sure you can't really get c=0 or c=1, but they are APPROACHABLE
Comment: But it might not be differentiable at x=0 hm
Comment: How would you go about calculating 'n' for a given 'c'?
Comment: gah... stupid question.  I figured it out... n=(1-c)/c.   Indeed, that does seem to produce to correct result.
Comment: hey that isn't a stupid question! plus you figured it out. pat on the back
Answer: Yes, you need $c$ to be the integral of the function over the interval. For your function, the integral is
$$\frac{k \left(2 k-2 (k-1) \tanh ^{-1}(1-2 k)-1\right)}{(1-2 k)^2},$$ so solving for $k$ is not trivial.


How to edit image URL in node field?

Question: I am using Media Browser widget for uploading and editing images in nodes. My images are stored using image fields. Is it possible to edit URL of the image after uploading? I would need to achieve:
When I upload file named "foo.png" it has by default the following URL:

/sites/default/files/media/.../foo.png

I would need to edit filename to "bar.png", so resulted path will be:

/sites/default/files/media/.../bar.png

(only filename is changed in URL)
I tried to edit filename, since it is possible using Media browser widget. But editing filename does not have affect on change of URL for me. I also tried to use following hook: hook_file_presave
I tried to programatically change uri parameter using this hook. But nor filename change neither uri change affected URL of the file.
When I look in directory sites/default/files/..  I can see that filename is the same as I uploaded it, not affecting my later changes of filename or uri. When I load php $file object, I can see $file->filename and $file->uri properties changed.
Is it possible to change URL of the file (just last part of the URL - filename) after uploading the file?
//EDIT: I tried to do following changes in my hook_file_presave:
function mymodule_file_presave($file) {
 if ($file->type != 'image') {
  return;
  }
 if (!empty($file->filename)) {
   $uri_parts = explode('/', $file->uri);
   $count = count($uri_parts);
   $uri_parts[$count - 1] = $file->filename;
   $file->uri = implode('/', $uri_parts);
   $file->destination = $file->uri;
   }
 }

Comment: Use hook_insert()
Answer: To rename the file, you'll need to use PHP's rename() function. To do so, you'll want to get the file's full local path using drupal_realpath() like so:
// Fetch the local absolute path of our image
$local_path = drupal_realpath($file->uri);

Once you've renamed the file, you'll need to modify the file URI (and potentially other attributes-- use print_r($file) to check).
The wording in the docs is a little weird to me, it says "when a file has been added to the database" which means to me the file metadata has already been saved to the database. However, the example shown in the docs seems to edit this info (but without using &$file ...?) without having to return the file object. Strange.
Anyway, your code might look something like this:
function mymodule_file_presave($file) {
  if ($file->type != 'image') {
    return;
  }
  if (!empty($file->filename)) {

    // Will likely be 'public://'
    $scheme = file_uri_scheme($file->uri);

    // Get full path of image location
    $local_path = drupal_realpath($file->uri);

    // Create new name using drupal scheme format
    $new_uri = $scheme.'new_name_here.jpg';

    // Actual OS rename of file
    rename($local_path, drupal_realpath($new_uri);

    // Update $file object with new uri
    $file->uri = $new_uri;

    // Not sure if this is still needed...
    $file->destination = $file->uri;
  }
}

How to edit image URL in node field?


Select com YEAR e MONTH juntos

Question: Bom é possível juntos o ano e o mês, e passar um paramento assim 20017-06 para o select?
SELECT SUM(valor) FROM contas where YEAR(data) = '2017' and MONTH(data) = '06'

Answer: Sim é possível, use a função date_format() passando o formato desejado no lugar das duas funções.  Y para o ano com 4 dígitos e m para o mês com dois dígitos.
SELECT SUM(valor) FROM contas where date_format(data, '%Y-%m') = '2017-07'

Comment: Perfeito, era exatamente isso que estava precisando aqui. Vlw brother.
Comment: opa, vlw. isso vai ajudar bastante.

Select com YEAR e MONTH juntos