How to set type of update "In App Update" when I update the app in google play console?

Question: I can't find out where should I set the update type of "In App Update" feature in google play console.
Otherwise tell me how to use AppUpdateType.IMMEDIATE and AppUpdateType.FLEXIBLE?
Answer: Edit:
The Play Core API now supports checking for the priority of updates. See https://developer.android.com/guide/playcore/in-app-updates#check-priority

I think you are misunderstanding the use of this feature. For each newer version available, you can update it in the app both ways.
"Flexible" means that the update will happen in the background and the user can continue using the app while the download happens and you get to let the user choose when to install it.
"Immediate" means that the update happens in the foreground, blocking the user to use the app while the download and install happens (to be used for critical updates).
You can learn more about this in this recent video of a talk at the Android Dev Summit 2019: https://youtu.be/_o_q6hatcIs
Comment: I think the OP meant where to set the priority when a new release is uploaded through Play developer console. But it looks like this can only be achieved through Play developer API https://developers.google.com/android-publisher/tracks
Comment: @Pierre How to define that this new version is Immediate or flexible update ? How to set it from console ?
Comment: As pointed out by @hitmaneidos, this can be set using the Play Developer API. It is explained in the documentation that I linked to. See https://developer.android.com/guide/playcore/in-app-updates/kotlin-java#update-priority


Replacing values in formated file with python

Question: I have a string see attached file like that and i would like to modify it using a function
Giving section name  parameter name and value to set
Also in case i want to modify several parameters for a same section how can i have position
in file to avoid scanning x time for a same section :
<code>&NAM_WRITE_COVER_TEX CLANG='FR'
/
&NAM_FRAC LECOCLIMAP = T
/
&NAM_PGD_GRID PGRID = 'CONF PROJ '
/
&NAM_CONF_PROJ_GRID
XLATCEN=43.,
XLONCEN=0.
NIMAX=12,
NJMAX=8,
XDX=60000.,
XDY=60000. /
&NAM_CONF_PROJ
XLAT0=43., XLON0=0., XRPK=1.0, XBETA=0. /
/
&NAM_PGD_SCHEMES CNATURE = 'ISBA' ,
CSEA = 'SEAFLX' ,
CTOWN = 'TEB' ,
CWATER = 'WATFLX' ,
LGARDEN = F
/
</code>
Comment: Is this a documented format, if so there may already be a module to do what you want. Otherwise I would say that this format looks a lot like the `ini` file format for which [there is already a module](http://docs.python.org/2/library/configparser.html).
Comment: Is there a reason you can't use XML or a formatted Excel file? Python has plenty of libraries to edit these types of files directly
Comment: yes this is namelist file ( kind of ini file) used by a fortran program. i haven't choice to use other format.
Answer: I could suggest using python regular expressions. http://docs.python.org/2/library/re.html. The regular expression will only use one pass.
<code>def replace_value(matchobj):
    new_repl_dict = {'XLATCEN': 54, 'XDX': 7000, 'CTOWN': "'NEW_VAL'"}
    if matchobj.group(1) in new_repl_dict:
        return matchobj.group(1) + matchobj.group(2) + new_repl_dict[matchobj.group(1)]

file = "&NAM_WRITE_COVER_TEX CLANG='FR'\n..."
re.sub('(XLATCEN|XDX|CTOWN)(\s*=\s*)([^\n]*)', replace_value, file)
</code>
Comment: @ johnthexii,Python ConfigParser looks interesting do you think i can add specific structure like '&' as begin section tag '/' as end of section
Comment: @ Victor, do you think it is possible to filter replace to specify which section is concerned by change because a same parameter name could exist in differents sections
Comment: thanks to one who give (-1) my question is not a simple search and replace this no needs a post, what i want to do is a little bit more complicated , but this needs to really understand the problem !!!


input placeholder to be written over

Question: I have an input field for credit card number and I want to achieve a different behaviour from the default place holder.
My place holder is more of a pattern: "xxxx-xxxx-xxxx-xxxx" and I want that in every number entered only the specific x's will be written over and the rest of the placeholder will remain intact(each preserves its own color).
I have seen this post which suggests the use of mask and jQuery but I prefer solutions that combines html, css and angular instead.
If it helps there is an illustration:
Comment: Have you considered that not all credit cards follow the 4-4-4-4 format?
Comment: Show us your code - we can't know what you mean by default place holder / different behaviour (different from what).
Comment: See also https://stackoverflow.com/questions/72856713/keep-placeholder-partially-while-typing-in-input-type-text/72856960#72856960
Comment: @OMGDrAcula I did, but the main problem for me is what i have asked.. i believe i can figure out a solution for this problem when needed, but thanks for the suggestion
Comment: @AndrewAllen the code is a basic input field with an placeholder on it, nothing special

I cant really understand what is it that make you that upset about my question I clarified it in the post, added a link to a post with similar problem(which have more clarification)  and attached a photo... no need to be so toxic
Comment: @daviddavidson asking for code and details is a standard request on this site, not sure why you think I'm upset or how that's toxic. As answer below, an input mask is one option, another is using the control value accessor to create a custom control e.g. 4 input boxes with auto tab after 4 number inputs.
Answer: What you are looking for is called an input mask. It is unfortunately not a feature of HTML, but you'll find plenty of libraries and questions on Stackoverflow (:
What is difficult is finding a good one that is

working with copy & paste or autocomplete
using number-optimized on-screen keyboards
not messing up the number when correcting a character in the middle
works well with assistive technology, which users with disabilities rely on

That's why credit card inputs that work really well do not use input masks on the web.
Usually their implementation follows this principles:

The original input is broken apart into inputs and static text (the placeholder)
Styling is removed from the inputs
Everything gets wrapped in an element that then is styled like an input
Text is styled in a way to align flow of static text and input text
Write a lot of JavaScript to implement behaviour like a single input
Comment: Also, having a different color between the mask and the input might prove to be impossible when working with a single input field. Perhaps some contentEditable magicks might do the trick, but I highly doubt any _existing_ input mask implementations support that level of nitpickery.
Comment: Usually implementations of input masks use several inputs wrapped in something that's styled as the input.
Comment: @Andy ok I see its not that trivial, I will try to find some mask that suits my case good enough

thanks for the detailed explanation

input placeholder to be written over


Como trazer informações do banco e inserir em uma tabela(bootstrap)

Question: Boa tarde! Tenho tentado trazer informações do ´usuario´ do banco de dados e inserir em uma tabela que segue a sintaxe do bootstrap. Mas devido a complexidade de tags acabo me enrolando toda :(

O objetivo é: > Selecionar um professor ´usuario´. E quando ele for selecionado, traga do bancos as disciplinas ´usuario_disciplina´ as quais ele já tinha se cadastrado.

<form class="form-horizontal" method="POST"  action="php/CadastrarDisciplina.php" style="margin-top:20px;">
<fieldset>

    Professor:

        <select id="idusuario" name="idusuario" class="form-control">
          <option> Selecione o professor...</option>
          <?php
          //Seleciona todos os professores e lista no form
          include 'php/Conexao.php';
          $stmt = $conexao->prepare("SELECT * FROM usuario ");
          $stmt->execute();

         if($stmt->rowCount()>0){
           $resultado = $stmt->fetchAll();
           foreach($resultado as $linha){
         ?>
           <option value="<?php echo $linha['idusuario']; ?>"><?php echo ($linha['nomeusuario']); ?></option>
        <?php
           }
        }
        ?>
        </select>

</fieldset>

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css" rel='stylesheet' type='text/css'>

Lista de Disciplinas

    <?php
     include 'php/Conexao.php';
     $stmt = $conexao->prepare("select * from disciplina");
     $stmt->execute();
     if($stmt->rowCount() >0){
    ?>

        ID
        Nome

      <?php
        }
        $resultado = $stmt->fetchAll();

        foreach($resultado as $linha){
          $stmt2 = $conexao->prepare("SELECT * FROM usuario_disciplina WHERE usuario_idusuario=? and disciplina_iddisciplina=?;");
          $stmt2 -> bindParam(1,$idusuario);
          $stmt2 -> bindParam(2,$linha['iddisciplina']);
          $stmt2->execute();
          $resultado2 = $stmt2->fetchAll();
      ?>

          <input type="checkbox" class="form-check-input"  <?php if($stmt2->rowCount()>0){echo "checked='checked'"; }?>  value=<?php echo $linha["iddisciplina"]; ?>>

         <?php echo $linha["iddisciplina"]; ?>
         <?php echo ($linha["descricaodisciplina"]); ?>

      <?php
        }
        ?>

  <button type="submit"  method="POST" name="singlebutton"  style="margin-left:35%;"    class="btn btn-success">Salvar disciplinas</button>

</form>

Comment: Olá, Mikeli. Bem-vinda ao StackOverflow. Algumas partes da  pergunta não estão formatadas devidamente, isso dificulta a leitura e entendimento. Quando à questão, sabe mexer com Ajax JQuery? Seria a melhor e mais limpa solução (minha opinião)
Comment: Olá, Eu recomendo  você colocar o foreach dentro do  tbody, não entendi  muito a sua pergunta, mas acho que você precisa de um requisição ajax,
com javascript  puro http://blog.matheuscastiglioni.com.br/requisicoes-ajax-com-javascript

ou com jquery
Answer: O seu laço de repetição com as informações vindas do banco de dados precisa englobar cada linha () para adicionar as informações nas colunas ()

<?php
    foreach($resultado as $linha){
        $stmt2 = $conexao->prepare("SELECT * FROM usuario_disciplina WHERE usuario_idusuario=? and disciplina_iddisciplina=?;");
        $stmt2 -> bindParam(1,$idusuario);
        $stmt2 -> bindParam(2,$linha['iddisciplina']);
        $stmt2->execute();
        $resultado2 = $stmt2->fetchAll();
?>

                <input type="checkbox" class="form-check-input"  <?php if($stmt2->rowCount()>0){echo "checked='checked'"; }?>  value=<?php echo $linha["iddisciplina"]; ?>>

            <?php echo $linha["iddisciplina"]; ?>
            <?php echo ($linha["descricaodisciplina"]); ?>

<?php
    }
?>


Proving G/N is simple if N is a normal subgroup of G

Question: Suppose that G is a group and N < G a normal subgroup. Assume that there is no normal subgroup M < G with N < M. Prove that G/N is simple.
I am not really 100% sure where to start here. I feel like I may be missing something obvious but I'm not really sure. I know based off the information that N is the smallest normal subgroup of G, and that simple groups' normal subgroups are only the identity and themselves, so I can see the connection, I just can't see HOW to actually connect them
Comment: It isn't saying that $N$ is small.  It is saying that there are no normal subgroups that contain it.  In a sense, $N$ is big.
Comment: I meant that N was the smallest normal subgroup, is that incorrect?
Comment: Since no normal subgroup contains $N$, it is maximal.  That's kind of like being a largest normal subgroup.
Answer: Let $p:G\rightarrow G/N$ the projection map and $L$ be a normal subgroup of $G/N$ different of $G/N$, $p^{-1}(L)$ is a normal subgroup of $G$ which contains $N$, the hypothesis implies  that $p^{-1}(L)=N$ and $L$ is the trivial group. This is equivalent to saying that $G/N$ is simple.
Comment: Because $p^{-1}(L)$ contains $N$ since it contains $p^{-1}(e)=N$ and it is normal, the results follows from the fact that there is not a normal subgroup which contains $N$ and which is different from $N$ and $G$.
Comment: I think I am confused by what a quotient group actually does then. Does G/N then make all elements of N the identity? since p^(-1)((e))=N
Comment: yes, it makes all elements the identity. Since $p(x)=p(y)$ .e $xy^{-1}\in N$ in particular take $x=n\in N, y=e$, $p(n)=p(e)$.
Comment: I think you had a formatting error with the .e part


absolutely irreducible module

Question: If L be lie algebra over F ( F is a field), I want to know what is the definition of absolutely irreducible FL-module? I have confused of several key words related to irreducible modules!? Is there any difference between completely irreducible and absolutely irreducible?
Comment: Is L something special? Like a group or semi group?
Comment: Later it seems like FL might be the enveloping algebra.
Answer: When I google "absolutely irreducible module" the second hit I get is a passage in Lam's Exercises in classical ring theory which explains that an irreducible module $M$ over a $k$ algebra $R$ ($k$ a field) is called absolutely irreducible if $M\otimes_k K$ is irreducible over $R\otimes_k K$ for every extension field K of k.
I would guess the FL part is a semigroup algebra... Hard to tell without more context.
It is commonplace for definitions of modules for associative rings are re-used (where applicable) for modules over Lie algebras. For example, "irreducible module" is used here to mean a module with only trivial modules no matter if the algebra is associative or if it is Lie.  So it seems it would use the same definition for Lie modules.
Comment: what is R in your explanation? you mean M as an R-module?
Comment: @user118746 oops! I dropped it, apparently. Now it's there :)

absolutely irreducible module


Método excluir não é chamado quando clico em um commandButton

Question: Tenho um botão excluir que fica dentro de uma coluna do dataTable e quando clico no mesmo o método que é responsável pela exclusão do usuário não é chamado.
dataTable:

Botão Excluir:

Método excluir no MB:
public void excluir(Usuario usuario) {
        System.err.println("Metodo Excluir");

        try {
            UsuarioDAO usuarioDAO = new UsuarioDAO();
            usuarioDAO.excluir(usuario);

            FacesUtil.adicionarMsgInfo("Usuario excluido com sucesso");
            usuario = new Usuario();
            listarUsuarios();
        } catch (RuntimeException e) {
            FacesUtil.adicionarMsgErro("Erro ao excluir usuário");
            e.printStackTrace();
        }
    }

Método Excluir no DAO:
public void excluir(Usuario usuario) {
        System.out.println("<METODO EXCLUIR CHAMADO");
        Session sessao = HibernateUtil.getSessionFactory().openSession();
        Transaction transacao = null;
        try {
            transacao = sessao.beginTransaction();
            sessao.delete(usuario);
            transacao.commit();
        } catch (RuntimeException ex) {

            throw ex;
        } finally {
            sessao.close();
        }
    }

O escopo do MB é @SessionScoped
Comment: Coloca no commandButton o ajax=false.
Comment: `actionListener="#{usuarioBean.excluir(usuario}` está faltando um ) , coloque e testa novamente.
Comment: Foi um erro na pergunta só, no código estava certo e mesmo assim o método não está sendo chamado
Comment: tentou adicionar o process="@this" no botão?
Comment: Eu estou usando `BootsFaces` não tem o process pra colocar nos botões
Comment: Este componente está dentro do mesmo form?
Comment: Está sim, eu tentei de tudo e não consegui resolver acho que é um problema com o BootsFaces
Comment: Pois quando uso o Primefaces funciona
Comment: @DiegoAugusto, já tentou usar só action?
Comment: @Douglas Se você quiser responder, essa é uma solução. Eu tinha me esquecido de responder essa pergunta após solucionar o erro
Answer: No seu commandButton mude o ajax:
ajax="false"


Confusion in understanding of Steinitz Exchange Lemma by an example

Question: I am trying to understand Steinitz Exchange Lemma from Kurosh's Group Theory:

Suppose in a group $G$, two finite systems of elements are given:
$$
u', u'', \ldots, u^{(k)} \hskip5mm (I) \hskip1cm \mbox{ and } \hskip5mm v', v'', \ldots, v^{(l)} \hskip5mm (II)
$$
the first of which is linearly independent system, each of whose elements is linearly dependent on the second system. Then $k\le l$ and from $(II)$, $k$ elements can be omitted such that the remaining elements with the elements of $(I)$ form a system equivalent to $(II)$.

My question is simple, but I am not getting my fault in understanding.
Suppose we have group $G=\mathbb{Z}\oplus \mathbb{Z}$, with following systems of elements.
$$
(2,0), (0,2) \hskip5mm (I) \hskip1cm \mbox{ and } \hskip1cm (1,0), (0,1)\hskip5mm (II).
$$
It is clear that

$(I)$ is linearly independent (their $\mathbb{Z}$-linear combination is zero only when coefficients are zero).

Members of $(I)$ are linearly dependent on $(II)$ (obvious).

$k\le l$ (they are equal to two both).

As per assertion, we can omit two elements from $(II)$ and replacing them two elements from $(I)$, we get a system equivalent to $(II)$; it means that $(I)$ and $(II)$ should be equivalent. But this is not the case - members of $(II)$ are not $\mathbb{Z}$-combinations of members of $(I)$.
Can anybody point out my misunderstanding?
Comment: The key here is what they exactly mean by 'equivalent systems' of elements of $G$?
Answer: According to Kurosh, systems (I) and (II) are equivalent.
Note the definition given by Kourosh:
An element $u$ of $G$ linearly dependent on the
system of elements $u_1,u_2,\ldots,u_l$ of $G$ if
$$
\alpha u=\beta_1 u_1+\beta_2 u_2+\ldots+\beta_lu_l,\ \alpha,\beta_i\in\mathbb{Z}.
$$
And perhaps $\alpha\neq1$.


Github Wiki as a subfolder of the main project

Question: We have a project self-hosted on our Phabricator instance. I made a mirror of the project on GitHub.
The project has a subfolder called docs that contains the documentation in Markdown.
If the project was hosted on Github, I would add the wiki as a submodule of the main project -- however, the project is hosted on Phabricator and I do not want anything on the Phabricator repo to link to GitHub.
How can I tell Github to use the docs/ folder for the wiki, without any modification needed to the Phabricator repo?
Answer: This link from GitHub's documentation would indicate that GitHub wiki's are stored in a separate repository which I would think means this is not possible.


Vertical Margin Separation in SVM

Question: In a Support Vector Machine, the margins are defined as
$$\vec{w}\cdot\vec{x_i}+b\ge1\text{ for }x_i \text{ in class }+1$$
$$\vec{w}\cdot\vec{x_i}+b\le-1\text{ for }x_i \text{ in class }-1$$
I understand that maximizing $\Vert w \Vert$ will maximize the distance between the margins given the constraints, however I'm having a hard time with the following:
The margins are set in such a way that their y-intercepts (in 2D space) will always be 2 units apart. It's easy to see how, with this constraint, the distance between the margins will depend only on their angle, but why would we limit the vertical separation of the margins? Is there no situation in which the optimal margins would have greater vertical separation?
Edit: Horizontal margin lines come to mind. If the ideal margin lines (again, in 2D space) have a slope of zero, then the distance between them might need to be greater than (or perhaps less than) 2. Am I missing something fundamental?
Answer: Answered at https://stats.stackexchange.com/questions/264645/vertical-separation-of-margins-in-svm/
The one is a result of scaling and does not limit the vertical space between the margins.

Vertical Margin Separation in SVM


Metric modulation, ordering of the notes around the equals sign

Question: I could find some references stating that the old note value is placed on the left while the new one is placed on the right.
For example: "dotted eigth = quarter" means that the tempo just got faster.
However, I think that I recall learning the contrary long ago.
Is there an unique standard?
Is this standard well fulfilled or is it a common mistake to invert the order?
Answer: I can't recall a time I've seen the opposite in print (not to say I haven't forgotten), but what I prefer to read (and what I would write myself) would be old on the left, new on the right for the following reason:
The equals sign should be placed above the double barline between the two measures in question. As a result, the value to the left of the equals sign will then appear above the old meter, and the value to the right of the equals sign will be placed above the new meter. This allows one to easily read "okay, the value of the dotted quarter in 6/8 is now going to be equal in time to a quarter note in our new meter of 2/2."
If there are publishers out there doing it the opposite way, the only way I can think of to decipher it would be if the value on the right CLEARLY matched with the meter on the left and vice versa--like if the left meter was 3/16 and the right was 2/2 and the two values being compared were a dotted eighth and a half note, I don't care which side of the equals side they're on--I'm going to be matching the dotted eighth to the 3/16 and the half note to the 2/2.


Stop overriding for the development snapshot module

Question: I have a development snapshot for a module (ABC-8.x-1.x-dev). I added 4 Patches. Now the developer does commit updates to the module.
By running composer update, I will loose all my patches.
When I remove the module name from composer.json, the module gets deleted. I have read that I should remove the composer.json file within the module.
Is there some kind of sub-version that defines the commit or so, for example "drupal/abc": "~1.0-dev-FD1512" or "drupal/abc": "~1.0-dev-221"?
Answer: Instead of trying to tie yourself to a specific commit, you might consider using composer patches instead:
{
  ...
  "require": {
    "cweagans/composer-patches": "^1.0",
    "drupal/abc": "~1.0-dev"
  },
  "extra": {
    "patches": {
      "drupal/abc": {
        "Fix for foo": "https://url/to/foo-patch",
        "Fix for bar": "https://url/to/bar-patch"
      }
    }
  }
  ...
}

Patches will be applied on install/update of the relevant packages.
Comment: @mogio, I suppose composer will give you an error stating that it failed to apply the patch, from there it is a look in the issue queue and see if it was rolled in. You can also follow issues on drupal.org and you will get a mail once something happens in the issue. You will be notified when a patch is applied. If you must use a specific commit, have a look here: https://stackoverflow.com/questions/21314381/how-to-correctly-require-a-specific-commit-in-composer-so-that-it-would-be-avail
Comment: If you have multiple of your own patches going, then yes, you can specify a sha to lock into so the patches always apply until said issues are resolved. But you'll almost always want to get it rolled in and work with contrib.
Comment: An automatic patching mechanism? What is if the patch was already included in the last DEV? What is if a new patch must be created first?

There must be a way to stop composer from getting a library just by sticking to the already downloaded one?


Listando dados de uma tabela com PHP

Question: Olá, estou tentando fazer uma listagem com dados em uma tabela com o código abaixo, mas não estou conseguindo. Já fiz de várias maneiras, vi tutoriais na internet e tudo mais, porém, não dá em nada. No servidor tanto local quanto o externo não aparece nada, fica tudo branco. Alguém poderia me informar se tem algum erro nesse código?
    <?php
    require_once("Conn.php");
    $conexao = conectar();

    $query = "SELECT * FROM tab_final";
        try{
            $selecionar = $conexao->prepare($query);
            $selecionar->execute();
            $select = $selecionar->fetchAll(PDO::FETCH_OBJ);
          foreach($select as $listar){
            echo "Times: ".$listar->Nome."
";
          }
        }catch(PDOException $e){
            echo $e->getMessage();

     }
    ?>

Usei até o FETCH_ASSOC e mudei o echo para ficar de acordo com o mesmo e nada. Não sei mais o que fazer. Se alguém puder testar e conseguir, me ajuda, por favor! Desde já agradeço!
Answer: É muito simples fazer uma simples listagem usando PHP + MySQL. Se é iniciante, aconselho você primeiro fazer tudo numa página, depois você pode ir organizando de acordo o padrão que quiser. Veja abaixo um exemplo bem simples:
Exemplo de conexão:
<?php
// Instancia o objeto PDO
$pdo = new PDO('mysql:host=localhost;dbname=db', 'root', '');
// define para que o PDO lance exceções caso ocorra erros
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>

A forma mais simples de ser executada uma consulta seria utilizando query conforme o exemplo:
<?php
// executa a instrução SQL
$consulta = $pdo->query("SELECT fullname, email FROM user;");
?>

Para obter os dados pode ser utilizado um while percorrendo assim cada linha retornada do banco de dados:
<?php
while ($linha = $consulta->fetch(PDO::FETCH_ASSOC)) {
    // aqui eu mostro os valores de minha consulta
    echo "Fullname: {$linha['fullname']} - email: {$linha['E-mail']}
";
}
?>

Coloquei o código completo no GitHub como ConsultaPDO.php para ficar registrado.
Você pode ver mais detalhes em PHP Data Objects(en) e PDO:Query(en).
Comment: Muito obrigado, Ack. Estudei seu código e consegui, agora está listando os dados da tabela.

Listando dados de uma tabela com PHP


Show original price and discounted price?

Question: I'm using this module: Commerce Discount to create products discounts. In the products list view I'd like to show both prices: the original price and price with the discount. How can I do this?
I found this module:   https://drupal.org/project/commerce_price_savings_formatter but it doesn't seem to work with the Commerce Discount module.
Answer: It does work with the discount module. In fact the moudle was built with that one in mind. Install Commerce Price Savings Formatter and go to your product types's display settings and change it as per the screenshot.
Comment: I am aware that this is not the only module that does discounts. I am not an idiot. However it was used as the primary source when developing the savings formatter. Anything that affects the price via rules is refelected in the savings formatted.
Comment: What you suggest was the firt I tried. I selected the option shown in your capture, but it didn't work (the price was not visible).  Keep in mind that the Commerce Discount is not the only module that provides price discounts.
Comment: Just be sure: Did you created the discount at admin/commerce/store/discounts?
Comment: You were right. I just try it again and it works. Thanks


Trying to prove uniform continuity for a function

Question: I have been trying to prove that the following function is not uniformly continuous:
Consider $A=(0,\infty), B=(-\infty,0),$ and $f: A \cup B \rightarrow \mathbb{R}$ given by
$$
f(x)=\left\{\begin{array}{ll}
x+1 & x>0 \\
x-1 & x<0
\end{array}\right.
$$
What have i tried so far?
To show that $f$ is not Uniformly continuos, I am going to show that there exists $\epsilon > 0$ such that, $\forall \delta > 0$ there exists $x, y \in A \cup B$ such that $$|x-y|<\delta$$ but $$|f(x)-f(y)| \geq \epsilon$$
Choose $\epsilon = 1$ and consider $\delta > 0$ given. By taking $y = x + \frac{\delta}{2}$ and $x > 0$ from which we get that: $$|x-y|<\delta$$
Now, $$|f(x) - f(y)| = |(x+1) - (x - \frac{\delta}{2})| $$
which equals $$1 + \frac{\delta}{2}$$
Now i am stuck. I want the last quantity to be greater than $\epsilon = 1$ but i cant assure that, since i have no control over the value of $\delta$.
Can someone help me? Something is just not right. I would appreciate feedback followed by a detailed solution, i am really struggling to prove a function is not uniformly continuous in general.
Thanks in advance, Lucas
Comment: Your expression for $f(y)$ is slightly off, $f(y)=y+1=x+1+\delta/2$. The problem with your approach is that $g(x)=x$ is actually uniformly continuous on $\mathbb R$, so you should restrict your attention to the area around $x=0$, which is where Things Fall Apart.
Answer: Your computation looks wrong. Your $x$ and $y$ are both positive, so $f(x)=x+1$, and $f(y)=(x+\frac{\delta}{2})+1$. Thus $|f(x)-f(y)|=|(x+1)-(x+1+\frac{\delta}{2})|=\frac{\delta}{2}$. If $\delta$ is small then this will not be bigger than $1$.
Anyway, your choice of $x$ and $y$ will not work, because the function is uniformly continuous in both $A$ and $B$. What ruins uniform continuity in the union is when $x\in A$ and $y\in B$ or vice versa. So let $\delta>0$ and choose $x=\frac{\delta}{3}, y=-\frac{\delta}{3}$. Then $|x-y|<\delta$. However:
$|f(x)-f(y)|=|(\frac{\delta}{3}+1)-(-\frac{\delta}{3}-1)|=2+\frac{2\delta}{3}\geq 1=\epsilon$
Answer: Take $\delta>0$. Now, take numbers $x$ and $y$ such that

$-\frac\delta2<x<0$;
$f(x)<-\frac12$;
$0<y<\frac\delta2$;
$f(y)>\frac12$.

Then $|x-y|<\delta$, and, since $f(x)<-\frac12$ and $\frac12<f(y)$,  $\bigl|f(x)-f(y)\bigr|>1$. So, $f$ is not uniformly continuous: there is some $\varepsilon>0$ (namely, $\varepsilon=1$) such that, for every $\delta>0$, there are numbers $x$ and $y$ in the domain of $f$ such that$$|x-y|<\delta\quad\text{and}\quad\bigl|f(x)-f(y)\bigr|\geqslant1.$$


Convert row into column like pivot

Question: Table is:
  +----+------+
  | Id | Name |
  +----+------+
  | 1  | aaa  |
  | 1  | bbb  |
  | 2  | ccc  |
  | 2  | ddd  |
  | 3  | eee  |
  +----+------+

Required output:
+----+---------------------++---------------------+
| Id |        colum1       |   column2            |
+----+---------------------+ +--------------------+
|  1 | aaa                 | |   bbb              |
+----+---------------------++---------------------+
+----+---------------------+ +--------------------+
|  2 | ccc                | |   ddd               |
+----+---------------------++---------------------+
+----+---------------------+ +--------------------+
|  3 | eee                 | |   null             |
+----+---------------------++---------------------+

I've been trying on  'with' a and pivot but it seems not in the right way I want a column if I have more than one id
like the image
Answer: You can use row_number() & do aggregation if you have a some limited amount of names else you would need to use dynamic SQL for this:
select id,
       max(case when seq = 1 then name end) as col1,
       max(case when seq = 2 then name end) as col2,
       max(case when seq = 3 then name end) as col3,
       . . .
from (select t.*, row_number() over (partition by id order by name) as seq
      from table t
     ) t
group by id;

Comment: thanks you that query helped me a lot.
 the image was the result of i inner join that i was using but applied you formula to  a single table  and it work
Answer: You can use PIVOT for making this.
DECLARE @Tbl  TABLE ( Id INT, Name VARCHAR(10))
INSERT INTO @Tbl VALUES
(1, 'aaa'),
(1, 'bbb'),
(2, 'ccc'),
(2, 'ddd'),
(3, 'eee')

SELECT Id, [1] column1, [2] column2 FROM (
    SELECT *,
        ROW_NUMBER() OVER(PARTITION BY Id ORDER BY Name) RN
    FROM @Tbl ) AS SRC PIVOT (MAX(Name) FOR RN IN ([1], [2])) PVT

Result:
Id          column1    column2
----------- ---------- ----------
1           aaa        bbb
2           ccc        ddd
3           eee        NULL

Answer: Using row_number() build a dynamic query to execute()
--example table
create table #t (Id int, Name varchar(100))
insert into #t values (1,'aaa'),(1,'bbb'),(2,'ccc'),(2,'ddd'),(3,'eee')

-- number of columns to create
declare @columns int
select top 1 @columns = count(*) from #t group by id order by COUNT(*) desc

--build a query
declare @i int = 2, @qry varchar(max) = 'select Id, column1 = max(case when ord = 1 then name end)'

while @i<=@columns begin
    select @qry = @qry + ', column'+cast(@i as varchar(5))+' = max(case when ord = '+cast(@i as varchar(5))+' then name end)'
    set @i = @i + 1
end

select @qry = @qry + '  from (select *, ord = row_number() over (partition by id order by name)
                              from #t
                             ) t
                        group by id'

--execute the query
execute (@qry)

drop table #t

Convert row into column like pivot


Mean of quasi-geometric distribution

Question: How can I obtain a closed form for the mean of the following discreet distribution?
$$
 \Pr(X=k) =
  \begin{cases}
      p\,(1 - p)^k & \text{, if $k < n$} \\
      p\,(1 - p)^n\,(1 - q)^{(k-n)}&, \text{ if $k \ge n$} \\
  \end{cases},
$$
where $p$, $q$ and $n$ are parameters of the discreet distribution. Note that, if $p=q$ or $n = 0$ or $n\rightarrow\infty$, then the distribution becomes the geometric distribution.
Answer: This appears to be a computational exercise.
Let $$G(x)=\sum_{k=0}^{n-1}x^kp(1-p)^k+\sum_{k=n}^\infty x^kp(1-p)^n(1-q)^{k-n}$$
be the probability generating function.
Both parts are computable in closed form using geometric series, and then you can differentiate it to get the mean.

Mean of quasi-geometric distribution


How to get rows by a list of ids including repeated ids?

Question: I have a list of ids as
1,1,2,3,3,3,1

and want to calculate the sum of a column for the above rows. If I use IN as
SELECT SUM(score) FROM table1 WHERE id IN(1,1,2,3,3,3,1)

it will be the sum of three rows (unique ids), but I need to include repeated rows too (7 rows of 1,1,2,3,3,3,1).
EDIT: The table structure is simple. Something like
CREATE TABLE table1
(
id int(11) unsigned NOT NULL AUTO_INCREMENT,
score int(11),
PRIMARY KEY (id)
) ENGINE=InnoDB

Comment: Can we have a look at the table1 definition GoogleBot? Please
Comment: @zip I added the table structure to the question.
Comment: result for the `WHERE id IN(1,2,3)` and `WHERE id IN(1,1,2,3,3,3,1)` will be same for SUM().
Comment: @DevsiOdedra I know that. This is my question, what should I do instead of `IN` to get `1,1,2,3,3,3,1`.
Answer: You need to create a derived table containing those id values and then JOIN that to your table1 to generate rows for each instance of a value in your list. Those rows can then be summed:
SELECT SUM(score)
FROM (SELECT 1 AS id UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3
                     UNION ALL SELECT 3 UNION ALL SELECT 3 UNION ALL SELECT 1) ids
JOIN table1 t1 ON t1.id = ids.id

Demo on dbfiddle
Answer: You cannot do this using the IN condition, because IN treats your items as a set (i.e. ensures uniqueness).
You can produce the desired result by joining to a UNION ALL, like this:

1,1,2,3,3,3,1

SELECT SUM(Score)
FROM Table_1 t
JOIN ( SELECT 1 AS ID
       UNION ALL SELECT 1 AS ID
       UNION ALL SELECT 2 AS ID
       UNION ALL SELECT 3 AS ID
       UNION ALL SELECT 3 AS ID
       UNION ALL SELECT 3 AS ID
       UNION ALL SELECT 1 AS ID
 ) x ON x.ID = t.ID

Or
CREATE TABLE #TempIDs
(
   ID int
)
INSERT INTO #TempIDs (1)
INSERT INTO #TempIDs (1)
INSERT INTO #TempIDs (2)
INSERT INTO #TempIDs (3)
INSERT INTO #TempIDs (3)
INSERT INTO #TempIDs (3)
INSERT INTO #TempIDs (1)

Select SUM(Score) From Table_1
INNER JOIN #TempIDs t n Table_1.ID = t.ID;


Workflow Tools Comparison?

Question: There is a pretty strong need for us to design some workflows around various processes.  The problem is none of us actually know any workflow technology yet, and finding good data to compare the available options has been tedious and not entirely fruitful.
So I figured I'd ask you guys.
The main technologies we are looking at are Windows Workflow Foundation and eDocs Workflow.  What other options are there?  Sharepoint 2007 has workflow functionality too, right?  Is that just based on WF?
What are the pros and cons of the various technologies?  How do they compare?
EDIT: Also, one feature the administrative types like with eDocs Workflow is that it provides a method for them to edit it themselves.  I believe Sharepoint '07 does as well.  Is there some other way to allow that with a straight WWF implementation?
Comment: I believe that Sharepoint 2007 Workflow is based on WWF.
Answer: Sharepoint and WF more like complementary technologies, designed as two different workflow authoring tools in the same ecosystem. There's a Sharepoint workflow designer, and a WF (Windows Workflow Foundation) workflow designer.
The Sharepoint designer is meant to be an Office-like workflow editing experience, easier to get started with, geared for non-technical types, and generates all the web forms automatically.
The 'WF' workflow designer on the other hand is actually a component of Visual Studio (by default - as Bernie says you can rehost it), and designed to allow programmers to be able to fully customize workflow, and integrate it with any other code/systems desired. Building and deploying sharepoint sites this way is still possible, through the use of 'Sharepoint Activities', but more complex.
If you take the former route, you can hopefully let the administrative types do their own basic customizations (up to the limits of that environment) without causing total chaos.
Comment: Hrm... we're running Sharepoint 2007 in our Rochester office... if I had the manager guy who's bugging me about this develop the workflow in sharepoint, is there a way to grab what's generated and plug it into VS for me to work with after?  Or is it permanently tied to sharepoint?
Answer: It is possible to 'rehost' the WF designer (the one from Visual Studio) in your own application, so that users can author workflows. There are a number of code examples on the web, the most important one from MS itself: http://msdn.microsoft.com/en-us/library/aa480213.aspx).
At some point, when evaluating WF, I implemented a demo application that did this and added some features and found that although it works, not everybody can understand and use the more difficult activities (like the policy activity) that require understanding of how the rules engine works.

Workflow Tools Comparison?


What may be an inefficient estimator of the population mean?

Question: If the sample mean is an efficient estimator of the population mean, what may be an example of an inefficient such estimator?
Comment: It is not that simple. For example sample mean is an efficient estimator for population mean for data coming from Gaussian, but not from Laplace distribution. Similarly sample median will be efficient to estimate population mean for Laplace but will be inefficient to estimate population mean for Gaussian.
Comment: Pick one element of the sample randomly as your estimator.
Comment: OK, let's be more explicit.  Your setting is a sample of values $x_1, x_2, \ldots, x_n.$  Roll an n-sided die.  Call its outcome $i.$  Let $x_i$ estimate the mean.  I hope it's obvious that for $n\gt 1$ this is an inefficient procedure.
Comment: What @whuber is telling you is not using your entire data also leads to an inefficient estimator. Estimator is a function of your data such as $f(x_1,x_2,...,x_n)$. This function doesn't have to be in the form of adding elements or doing symmetric/commutative operations. It can be anything. And if this function doesn't use some of its input arguments that will (always, I think) lead to inefficiency.
Comment: Lars, since my comments aren't making sense to you, we had better back up a bit: could you explain what you understand an "estimator" to be and what your definition of "efficiency" is?
Comment: Those might be good heuristics but they're ultimately worthless for reasoning through questions like yours.  You need to refer to some clear, quantitative definitions.  In so doing, I think my comments might become more understandable, because they assume a conventional understanding of these terms as expressed in statistical literature and textbooks. Here's a search that might take you to some useful posts on our site: https://stats.stackexchange.com/search?q=efficient+estimator+score%3A1
Comment: Well, ok, but I mean the "vanilla case", so I guess Gaussian. Would the median of the sample be an example of an inefficient estimator in this case?
Comment: I don´t understand.
Comment: Nope. It´s all jibberish to me.
Comment: Ok, estimator = a entity used for estimation of another entity. Efficiency = Measures with more accuracy/validity-ish?
Comment: Is there anyway of explaining this (e.g. why median is efficient for Laplace and mean is efficient for Gaussian) in a way that a layman or schoolkid could understand?
Answer: Consider a sample of size $N$ drawn from a normal distribution. The sample median $\tilde{X}$ is an unbiased and consistent estimator for $\mu$. For large
$N$ the sample median is approximately normally distributed with mean $\mu$ and variance
$\pi/2N$. The efficiency for large $N$ is thus $2/\pi \approx 0.64$. This is the asymptotic efficiency, that is the efficiency in the limit as sample size $N$ tends to infinity.
Edit: The sample mean is a better (more efficient) estimator for the population mean as opposed to the sample median, because the sample median will miss the population mean by more (on average) than the sample mean.
That is, the sample medians (talking asymptotically - as the sample size N reaches infinity) will have a wider distribution compared to the sample means. And since both estimators are unbiased, meaning they will estimate the true population mean - meaning they wont under/overestimate the population mean, all that remains is to look at the variance of these estimators. And as written above, the sample median distribution will have a higher variance compared to the sample mean, which means the sample median is a less efficient estimator for the population mean.
Comment: @LarsAhnland In this case the median is inefficient because the efficiency is roughly 0.64. The efficiency of the mean is 1.
Comment: @LarsAhnland Yes, in this case the sample median is more variable.
Comment: @Lars user2974951 was not "using circular logic". When they said "the sample mean is more variable" they were just reframing the statement of your question to a more correct usage of the terminology than what you had in your question. Their response was simply "Yes." and then simply a clarification of what they were saying *yes* to. If you have looked up the definition of [efficiency](https://en.wikipedia.org/wiki/Efficiency_(statistics)#Estimators) of estimators, then it should be clear that a comparison of variances (given both estimators are unbiased here) is simply following ... ctd
Comment: ctd... the definition of efficiency - to be precise, their *relative efficiency* will be the ratio of the reciprocals of their variances, so the more efficient has a smaller variance.the definition of efficiency - to be precise, their *relative efficiency* will be the ratio of the reciprocals of their variances, so the more efficient has a smaller variance.
Comment: That doesn´t answer my question. I was asking for an example of an INEFFICIENT estimator.
Comment: Ok thanks. Sorry, I don´t understand much of that. But in short: I the normal case, the sample mean is more efficient than the sample median for estimating the population mean?
Comment: @LarsAhnland Yes.
Comment: Thanks! And this is because - normally - the median produces more variance?
Comment: Wait... the median produces more variance when it is more variable? That is just circular logic. Can it be explained in a simple/layman way?
Comment: Thanks for clarification! Is there any inherent logic that makes a median having higher variance than a mean ?
Comment: @LarsAhnland (For a normal distribution) If you want to estimate the population mean then you should use the estimator best suited for the job, the closest thing to it, the sample mean. The median also works but is not as efficient. You would use a hammer to hammer a nail, you could use a shovel but it wouldn't be as easy - it would take longer on average compared to a hammer. I can't make it any simpler than this.
Comment: I understand this, but why is the variance higher for the sample median?


Linear algebra use case

Question: I learning some machine learning course, and I would like to know in which case we use linea algebra and Matrix Algebra?
Thank you
Kind regards
Comment: Maybe the list will be shorter if you ask which machine learning algorithms don't use linear algebra and matrix algebra.
Comment: Ok so, I change my question like you said  :)
Comment: Have any suggestion for a title ?
Answer: I agree with Mark L. Stone's comment: too many examples, linear algebra is the foundation of statistics and machine learning, because your data is organized in columns and rows, and most widely used operations are multiplication and addition.
I will use linear regression as an example.
Suppose you are doing multiple linear regression, where you want to build a model for data $x^{(i)}$ (the $i$th data in your data set, and assume your data as $m$ features.)
$$
f(x^{(i)})=\beta_0+\beta_1x_1^{(i)}+\beta_2x_2^{(i)}+\beta_3x_3^{(i)}+\cdots+\beta_mx_m^{(i)}
$$
And you want to minimize the squared error
$$
\sum_i (y^{(i)}-f(x^{(i)}))^2
$$
Such problem can be written in a very concise notation
$$
\min \|X\beta-y\|^2
$$
Where $X$ is data matrix, every row is a data instance, and every column is a "feature". $\beta$ is a vector and $y$ is the response vector. $\|\cdot\|$ is $L_2$ norm of a vector.
Here is where the matrix algebra comes in: take the derivative respect to $\beta$ of $\|X\beta-y\|^2$, you get $2X^T(X^T-y)$. You can set it to $0$ and solve it, which is the "normal equation" for linear regression, where
$$
\beta=(X^TX)^{-1}X^Ty
$$
Note that, using matrix inverse is not a good solution from numerical analysis point of view. In real world, such as in R, QR decomposition is used. And that is more matrix algebra.
Check this post, you will see matrix operations are everywhere
What algorithm is used in linear regression?
Comment: thank you very much,  to make it simple here : http://stats.stackexchange.com/questions/230974/diagnosis-analytics     my collegue suggest to me to use lean algebra to resolve this problem. Are you agree with that? Kind regards
Comment: it depends how far you want to go. if you want to build some "model" that somehow "works", and you do not want to totally understand the model. you can skip the math. Otherwise, it is good to know the math.
Comment: Yes, but Are you Ok with this idea to detect the equipement if you have read the post please? Thank you

Linear algebra use case


Rselenium remove div element

Question: I want to remove a div element from a webpage using RSelenium.  Here is a MWE where I want to remove the
.  I can find the element.  How can I make it disappear?
MWE
library(RSelenium)

url <- 'https://ropensci.org'

## These two lines will pull the latest docker image of firefox and run it
system("docker pull selenium/standalone-firefox:latest")
system("docker run -d -p 4445:4444 selenium/standalone-firefox:latest")

drvr <- RSelenium::remoteDriver(port = 4445L)
drvr$open()
drvr$navigate(url)
drvr$screenshot(display = TRUE)

drvr$findElement("xpath", '//div[@id="header"]')

More Context
I have a webpage where a div header floats around (rather than staying fixed at the top) as I'm expanding collapsed checkboxes and then clicking on the checkboxes.  That div header gets in the way of clicking other elements.
Answer: If you want to do this to the active session you can remove (actually makes it hidden) the element but you have to use JavaScript. RSelenium has an executeScript() method as part of the driver class (docs).
Something like this should do it, you might have to tinker as I do not have access to your particular webpage/instance:
drvr$executeScript("return document.getElementById('header').remove();")

EDIT: You can also remove it with regex on the static page source HTML if you just want to remove it for parsing static content. But it seemed like that was not your use case. Let me know if an example there would be of interest to you as well.
Comment: That's terrific.  Works well.  Thank you.
Comment: For future searchers, I actually had a class tag so I had to adapt this terrific solution slightly. I used @GeoffreyGrimm's approach with a jQuery removal solution found here: stackoverflow.com/a/4777105/1000343

Rselenium remove div element


how to make a small search engine in java

Question: I want to make a small search engine.consider that I have 5 text files and I want to find the word "book" in whole files.How should i start? I am a senior and I have a little information about trees and iterators and I have to use these concepts.could anyone help me with the code?
Comment: @faridamyaie This question isn't appropriate then. This site is for specific questions.
Comment: Can you post the code you've written so far and explain where it failed? You might want to read [How to ask...](http://stackoverflow.com/help/how-to-ask) while waiting for an answer.
Comment: The problem is that I do not know  from where and how should I start.
Comment: http://lucene.apache.org/solr/features.html
Answer: You do not need any knowledge about trees and iterators. It is all about recursive calls, no more.
Here is the pure Java code with no dependencies or frameworks used:
just pass directory or file name and word you'd like to search as parameters when call it.
<code>package com.mytests;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

public class Sometest {

public static void main(String[] args) {

    if (null == args || args.length < 2) {
        System.err.println("Not enough parameters. Please provide searchPath and searchWord.");
        return;
    }

    String pathToSearch = args[0];
    String wordToSearch = args[1];

    System.out.println("Start search word " + wordToSearch + " in " + pathToSearch);

    File searchFile = new File(pathToSearch);

    if (!searchFile.exists()) {
        System.err.println("Cannot find given file or directory to search :" + pathToSearch + ": ");
    }

    int matchesCount = 0;
    matchesCount = searchWord(searchFile, wordToSearch, matchesCount);

    System.out.println("Search completed. Matches found : " + matchesCount);

}

private static int searchWord(File sourceFile, String wordToSearch, int matchesCount) {

    int count = matchesCount;
    if (sourceFile.isDirectory()) {
        String[] sourceFilesArray = sourceFile.list();

        for (String nextFileName : sourceFilesArray) {
            File nextFile = new File(sourceFile.getAbsolutePath() + System.getProperty("file.separator")
                    + nextFileName);
            count = searchWord(nextFile, wordToSearch, count);
        }
    } else {
        try {
            BufferedReader sourceFileReader = new BufferedReader(new FileReader(sourceFile));
            String nextLine = "";
            while (true) {
                nextLine = sourceFileReader.readLine();
                if (null == nextLine) {
                    break;
                }

                if (nextLine.contains(wordToSearch)) {
                    System.out.println("found in -> " + sourceFile.getCanonicalPath());
                    count++;
                }

            }
            sourceFileReader.close();
        } catch (Exception e) {
            System.err.println("Error while reading file " + sourceFile.getAbsolutePath() + " : " + e.getMessage());
        }
    }

    return count;
}

}
</code>
I'm just wondering what is a purpose? personal education?
Comment: First of all, I appreciate you.It was really helpful.And my purpose is both educational and practicing different features of data structure.


NHibernate 3: is it worth migrating?

Question: We are using Nhibernate 1.2 on a big .NET 3.5 C# project and we are considering upgrading to Nhibernate 3.1. But I'm a little puzzled as I don't find over the Internet much articles dealing with

improvements of the new versions (2.0 -> 3.1)
benchmarks between 1.2, 2.x, 3.x

Most of the time people are just saying: NHibernate X.Y is out, it's great, it's wonderful, you have to upgrade, and linking to the ChangeLog.
By far I just have heard of Linq2Nhibernate & MultiCriteria, nothing on performance benchmarks.
Comment: possible duplicate of [What do you gain from upgrading NHibernate 1.2?](http://stackoverflow.com/questions/4150387/what-do-you-gain-from-upgrading-nhibernate-1-2)
Answer: If you don't encounter any issue and do not need to upgrade your application, the "if it's not broken, do not fix it" rule applies.
Otherwise : What do you gain from upgrading NHibernate 1.2?

NHibernate 3: is it worth migrating?


AWS CLI DynamoDB with shell variable

Question: I am trying to put a variable in the AWS CLI DynamoDB command for add a row in a table:
aws dynamodb put-item --table-name table_name --item '{"id_proceso": {"N": "1"}, "fecha_proceso": {"S": "20210707170486"}, "status": {"S": "OK"}, "fecha_termino": {"S": "fecha_termino_var"  } }' --region us-east-1

Where fecha_termino_var it should be a variable. example: fecha_termino_var=(date +'%Y/%m/%d %H:%M:%S')
but I have tried various ways but I have not managed to do it, is there any way to enter a variable in a aws cli command line?
The goal it is to add a row, which will contain a variable of the date in real time.
I've tried various ways but it just adds the variable type, in this case "date", or just the variable name in text plain "fecha_termino_var".
I'm working in a shell (.sh) to do this.
Failed image adds:
Comment: " without success" its not specific. Exactly what is happening? Why do you have space in `$ {date}`? Why do you use single quotes?
Comment: what `date=(date +'%Y/%m/%d %H:%M:%S')` is supposed to do? Can you explain? You are overwriting date with date?
Comment: without success I mean that sometimes it inserts the row but only the text or it gives syntax error
Comment: "date" is just an example to save the date inside that column, it doesn't necessarily have to have the same variable name. the goal is to save a variable within the command line
Comment: This is `date=(date +'%Y/%m/%d %H:%M:%S')` wrong. Is this bash? What do you think it does?
Comment: https://prnt.sc/19n0j8n there I just put the variable intro ", and it appear error parsing parameter
Comment: I have tried with backslashes like: "\${variable}\" but happened the same
Answer: Your screenshot shows that you are missng " infront of fecha_termino. So it should be:
, "fecha_termino":

not:
, fecha_termino":

Update:
The full correct command is:
aws dynamodb put-item --table-name mcp_control_proceso --item '{"id_proceso": {"N": "1"}, "fecha_proceso": {"S": "20210707170487"}, "status": {"S": "OK"}, "fecha_termino": {"S": "'"${fecha_termino_var}"'"} }' --region us-east-1

Comment: thanks for the answer, after this fix it adds the row, but in another way like "$fecha_termino" https://prnt.sc/19n297b
Comment: @Sebastián This is due to single quotes. Check my first comment "Why do you use single quotes? " Don't use single quotes to wrap your string. It does not resolve veriables.
Comment: How it should be? The code I added last one it's:  "fecha_termino": {"S": "$fecha_termino"  }
Comment: @Sebastián Sorry, I don't know. Your real code is different than in the question. Its difficult to speculate what actually you are actually using.
Comment: sorry, already fixed, I just want to insert a variable inside variable, "data": {"S": "$variable"} but it seems to be very difficult
Comment: @Sebastián  `'{"id": {"N": "1"}, "data": {"S": "'${fecha_termino}'"}}'` should work.
Comment: https://prnt.sc/19n5om2 I did your advice, but the row added just appears 'date', I tried with an echo with the row added was 'echo date'
Comment: @Sebastián Sorry, but unless you provide exact details of your code, this can go for ever. Please edit your question with exactly what you are doing. Not some partial screenshots that do not relate to your question.
Comment: thanks for yours advices, please see new details
Comment: @Sebastián It should be `fecha_termino_var=$(date +'%Y/%m/%d %H:%M:%S')`
Comment: and then like this?: aws dynamodb put-item --table-name mcp_control_proceso --item         '{"id_proceso": {"N": "1"}, "fecha_proceso": {"S": "20210707170487"}, "status": {"S": "OK"}, "fecha_termino": {"S": "'${fecha_termino_var}'"} }' --region us-east-1
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/234680/discussion-between-sebastian-and-marcin).

AWS CLI DynamoDB with shell variable


Is $f$ a non zero divisor?

Question:
Consider the ring $R=\dfrac {k[x,y,z,t]}{(y(xt-yz))}$. Consider the polynomial $f=t(yz-xt)$. Is $f$ a non zero divisor of $R$?

I think the answer is yes, because if $f$ is zero divisor then $fh=y(yz-xt)k$ for some polynomials $h$ and $k$. How to proceed from here?
Answer: $f$ is a zero divisor of $R$, since $-yf = (y(xt-yz))t = 0t = 0$.
Comment: @Arthur,@McFry, Thanks but what about the polynomial $t(y^3-x^2z)$ ?
Comment: However, something is missing: $-y\ne0$ in the factor ring.

Is $f$ a non zero divisor?


Edits to my code do not show up when running in Eclipse

Question: I am working on a project which was assigned to me,
they gave me a folder with a ton of classes, docs, and other project related files I'm not too familiar with, and I've been given a separate jar for everything else the project needs.
I have imported the project into eclipse, and can even get a provided test .java I was provided to run correctly, but for some reason any changes I make to the test's code fail to show up when I run it.
I've added code, even commented out lines that would make a big difference in the display, but everything stays the same when I run it.
I have build automatically turned on, and I have even played with it off, turning it back on again, etc.
I fixed all the build path errors by correctly pointing to the external jar, but this still happens.
Has anyone encountered this before and/or do you know how to fix it?
Comment: Could it be that the test class is also contained in the 'everything-else' JAR? In this case they would be twice on the class path, and Eclipse might just use the 'wrong' class.
Comment: Wow, you were pretty spot on there. For some reason I was told to add that jar as an external jar, and that's what was keeping it behind. I had almost given up and moved back to jgrasp for this one.
Comment: Maybe they don't want you to change the test code. :-P But better check whether the code you are _supposed_ to edit is not also contained in the JAR. So, can I put this as an answer, then?
Comment: Yes, you can put that as an answer.

They definitely wanted that file edited. The jar was being used to update libraries and add more documentation, but also contained the source and class of the file I was working on.
Answer: One possible reason for such behaviour is that the classes you are editing in your project are also contained in some JAR you are using. Thus, those classes are on the class path twice, and Eclipse/Java will load only one of them and ignore the other.
So I suppose that the test classes you are editing (and maybe even the other classes you are supposed to work with!) are contained in the separate JAR for 'everything else' you mentioned.


Dynamically changing windows saving directory?

Question: Is there a system property in windows that tells programs where their save location is?
My goal is to create a program which, on startup changes the default file path save location.
When the program shuts down, the default file location would go back to normal.
Comment: Err ... no, there isn't.  Furthermore, changing environment variables for other programs is a bad idea, even if you can implement it reliably.
Comment: Why is it a bad idea. The only issue I see is if my program crashes somehow and doesn't revert the old file path.
Answer: IMO, as stated, this question is an XY problem.
Your real problem is that you want to control where your program's state is saved.
The real solution is to change your program so that it saves its state to a >>specified<< directory ... rather than relying on a "default save directory" (which is not a well defined concept on Windows or any other OS) and changing that to something else, temporarily.
Comment: You are right, and thanks for linking the XY problem. So this is more of somehow accessing each program's respective state save directory and modifying that?
Comment: Well, in Unix systems, there is very well a "well defined" path where to save program configuration, etc., called home-directory.
Comment: *"So this is more of somehow accessing each program's respective state save directory and modifying that?"* - The solution is to >>tell<< each program where to save its state.  That may involve setting a property or environment variable or changing a registry setting, or passing it a command line parameter ... or changing the program so that you can so one of the above.
Comment: @Olaf.  No there isn't.  That is a >>convention<<.  And actually, there are other conventions too ... depending on the nature of the program.
Comment: Not on Linux desktop systems at least and for environments which follow FreeDesktop standard, which includes Gnome and KDE for instance.
Comment: Erm ... if Tomcat ever saves stuff in its home directory, I'm going to start looking for my shotgun!
Comment: For system, there are /etc` and `/var`, of course! We were talking about desktop applications I presumed.
Comment: So yes.  What I said in my Answer is correct :-).  You are making assumptions that are not warranted.


Help with content structure of a typical art gallery website

Question: As a way of learning a bit more about how Drupal 7 works, I'm trying to replicate the features of a local art gallery website. I'm having a few problems setting up the content types so I was hoping someone could point me in the right direction. I want to get all the content correctly configured and stored so I can then play around with Views and different ways of presenting that content. Here's what I've come up with having broken down the different types of data:

ARTIST will have one name, a bio and a website
ARTWORK will be associated with one artist only, will have a title, may or may not belong to a SERIES, will also have dimensions, an image, a year of creation, and will have the material used to create the artwork (term reference to a taxonomy vocabulary with terms such as "oil on canvas", "photograph", "mixed media" etc)
SERIES will be associated with one artist only.

So I've set up my content types. Well, the Artist and Artwork ones anyway, but how do I link them? I think I'm supposed to set up Artist as a taxonomy vocabulary, and list the Artist names as terms, and then when creating the content type Artwork have a term reference to it. This is OK but I don't want to have to manually add the term to the vocabulary each time a new content type Artist is created. So I guess what I'm asking is two questions:

Is my approach completely wrong? If so, please guide me in the correct direction!
If it's not wrong, is there some way to automatically generate the terms of the vocabulary Artist based on the Artist name? So when new Artist content is created, the term is automatically added?
Answer: This problem is often solved using the Node Reference URL Widget. Here is a video podcast on Node References and another on how to create a gallery.
You should use taxonomy to categorize the different series. Use Views to show the series will take a node reference relationship as an argument as well as the taxonomy id of the series.
Comment: Thanks Adam S: Node References was what I needed. Once I created the node reference from artwork to an artist I managed to create a View which displayed each artwork image alongside the artist's short bio, really just as a way of testing out if the View had connected the two entities.


Intersection of a vector in the interpolation line between two vectors? Reverse Linear Interpolation?

Question: Check the image
Basically I have a vector direction (c) that sits between two vectors (a and b) and I want to find P the point of intersection of the direction of c with the line defined by a and b.
So I have all three vectors in a plane, and want to find P.
Thanks!
Comment: Have you looked up intersection of two lines?
Comment: Yes I do sir, but it's visual programing... nodes.
as in this image: http://prntscr.com/6reyfc

My failed attempt consisted of having the angle between A and C be divided by the angle between A and B so I could have a factor for linear interpolation. But it's not working as you can see. I guess it's not the same as calculating the difference between angles, but something else I should be using to get the factor for the LERP between A and B to get the intersection. Cheers
Comment: I'm voting to close this question as off-topic because it is about mathematics, not programming.
Comment: It's solved.... close it at will. And it is about programming... I wanted a step of instructions to feed my 3D software to solve this. Cheers
Answer: The vector OP is P = (1-t)*A+t*B and you need to find P such that C×P=0 where × is the vector cross product. In the end I get
t = (ax*cy-ay*cx)/(ax*cy-ay*cx-bx*cy+by*cx)
px = cx*(ax*by-ay*bx)/(ax*cy-ay*cx-bx*cy+by*cx)
py = cy*(ax*by-ay*bx)/(ax*cy-ay*cx-bx*cy+by*cx)

Example, A=(1,6), B=(5,2), C=(0.5,0.8)
t = 11/26
px = 35/13
py = 56/13

Check results with GeoGebra:
Comment: yeah, my problem is definitely finding t. I would like to know if the t, px and py formulas are a deconstruction of commonly known operations, since I operate with nodes and instead of have each calculus step, maybe I have a construct that does sections of it. To me looks like if random, meaning, I'm not understanding its meaning from a higher position but I can definitely apply those steps. Thanks
Comment: basically I want to find t so I can interpolate 3D space vectors.
Answer: Ok, solved this one in a way that was computable to my brain.
Image description, as I'm a visual person: https://i.stack.imgur.com/L0qWX.png
projected one of the vector to the edge and subtracted the projection to that one of the vector, that' gives me p, a perpendicular vector to the edge.
Then projected c onto p and whatever was the factor of that projection length with the length of p I multiplied c with, giving me the point of intersection.
Sorry if this a very wonky implementation, but the output on my end is just what I needed.


PHP/MySQL - Imprimir valores com relação entre tabelas

Question: Em um sistema eu preciso imprimir latas de tinta e cada uma tem suas próprias cores. Fiz de uma forma que funciona, porém repete diversas vezes os requests no banco de dados.
Fiz duas tabelas(Exemplo):
latas
______________
id | nome
1  | uso geral
2  | teste 1
3  | teste 2

cores
__________________________
id | nome | hexa | id_lata
1  | azul | #0495| 1
2  | preto | #000| 1

Meu código está mais ou menos assim no momento:
<?php
$sql_latas = mysqli_query($conn, 'SELECT * FROM latas');
while($row_latas = mysqli_fetch_array($sql_latas)){
?>

      <?php echo $row_latas['nome']; ?>

      <?php
      $sql_cores = mysqli_query($conn, 'SELECT * FROM cores WHERE id_lata = '.$row_latas['id']);
      while($row_cores = mysqli_fetch_array($sql_cores)){
      ?>

<?php echo $row_cores['nome']; ?>

      <?php
      }
      ?>

<?php
}
?>

Como posso fazer isso?
Answer: Você pode elaborar apenas um SQL, usando o JOIN para unir as tabelas com base no id_lata, neste caso, você conseguirá obter os resultados de cada uma das tabelas, e também para distinguir uma coluna da outra, você pode no SELECT, setar qual é a coluna e qual será o nome dela representada, como o exemplo abaixo:
SELECT
    latas.nome as nome_lata,
    cores.nome as cor_lata,
FROM latas
JOIN cores ON(cores.id_lata=latas.id)

while($row=mysqli_fetch_assoc($sql)){
    echo $row['nome_lata'];
    echo $row['cor_lata']."

";
}


Codeigniter 3 composer and vendor directory

Question: I have installed codeigniter 3.1.8 and installed this library https://github.com/php-amqplib/php-amqplib using composer:
composer require php-amqplib/php-amqplib
This has created a directory vendor
I have looked the accepted answer on how to use the library here How to use composer packages in codeigniter?
but this is my directory structure in vendor.

second
and inside php-amqplib

and inside php-amqplib

If i look at index.php i find that fcpath has already been defined
// Path to the front controller (this file) directory
define('FCPATH', dirname(__FILE__).DIRECTORY_SEPARATOR);

require_once BASEPATH.'core/CodeIgniter.php';

and defining it again will result in an error.How can i get to use php-amqplib inside my controller methods?.
Comment: have you tried :  require_once APPPATH.'vendor/autoload.php';
Comment: Nope, but i can do that. In that answer, i have to put vendor iside application. Does it mean the application folder that codeigniter creates or should it remain where it is in my screenshot and how can i now access it in my controller?.
Answer: IF your question is - How can i get to use php-amqplib inside my controller methods ?

STEP - 1 :

Allow or require the autoload.php file on very beginning, but on codeigniter you cannot do that in general.So change one line on config file that will automatically require autoload.php file.
CodeIgniter/application/config/config.php find :
$config['composer_autoload'] = FALSE; to $config['composer_autoload'] = TRUE;

STEP - 2 :

On your controller class like this :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

class Welcome extends CI_Controller {
   public function index()
   {
        // your business logic like this
        $msg = new AMQPMessage($msg_body);
        $ch->batch_basic_publish($msg, $exchange);
   }
}

STEP - 3 :

Now you can call it via URL
http://example.com/Welcome

Now more ref: PhpAmqpLib
Comment: @Gandalf If you have additional questions, please post them separately - this site is designed to have one question and its answers on each page, rather than threads of discussion, so that it's easier for future readers to find the answer they need.
Comment: vendor must be in the codeigniter application directory.
Comment: How can i close the connection at the end of the controller function?.
Answer: Change composer_autoload config in /application/config/config.php like below
$config['composer_autoload'] = 'vendor/autoload.php';
Answer: This will open and close the connection
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Connection\AMQPStreamConnection;

class Welcome extends CI_Controller {

    public function index()
    {
        $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
        $channel = $connection->channel();
        $channel->queue_declare('hello', false, false, false, false);

        $msg = new AMQPMessage('Yur message goes here....');
        $channel->basic_publish($msg, '', 'hello');

        $channel->close();
        $connection->close();

        $this->load->view('welcome_message');
    }
}


polyfit with multi-dimensional x coordinate

Question: Suppose that I have a (400,10) array called x and a (400,10) array called y. Is that possible to do a polyfit of each row in y to the corresponding row in x without iteration? If with for loop it will be something like
import numpy as np

coe = np.zeros((400,3))
for i in np.arange(y.shape[0]):
    coe[i,:] = np.polyfit(x[i,:], y[i,:], 2)

Because the 400 rows in x is totally different, I cannot just apply np.polyfit with the same x coordinate to a multi-dimensional array y.
Comment: sorry for my typing mistake. It is numpy not bumpy
Answer: Have you tried a comprehension?

coe = [tuple(np.polyfit(x[i,:], y[i,:], 2)) for i in range(400)]

The range(400) emits the values 0 to 399 into i
For each i, you compute the polyfit for x[i,:] vs y[i,:].  I believe the results are a tuple (p, v)
The resulting list-of-tuples is assigned to coe

At the innermost levels, this is an iteration - but in Python 3, such comprehensions are optimized for performance at the C level, so you will probably see a nice performance boost doing it this way over using a for: loop.


Pattern Match Text And Extract Data in C++

Question: I am trying to figure out how I would go about extracting text from a text file if it matches the same pattern as a second text file and putting the extracted values into another text file.
I have never done anything like this before so I don't even know where to start.
So as an example, In file 1 we might have something like this:
else
        {
            if (func_133212(13))
            {
                if (unk_0x44334545("test"))
                {
                    if (!0x22224334545("test"))
                    {
                        0x44444237945("test", true);
                    }
                }
                if (Global_2398334.f_502.f_11 >= 2)
                {
                    if (unk_0x44334545("test2"))
                    {
                        if (!0x22224334545("test2"))
                        {
                            0x44444237945("test2", true);
                        }
                    }
                }
}

And then in file 2 we have something like:
else
        {
            if (func_12312(13))
            {
                if (unk_0x433877545("test"))
                {
                    if (!unk_0x3434344("test"))
                    {
                        unk_0x42224442111("test", true);
                    }
                }
                if (Global_23445454.f_502.f_11 >= 2)
                {
                    if (unk_0x433877545("test2"))
                    {
                        if (!unk_0x3434344("test2"))
                        {
                            unk_0x42224442111("test2", true);
                        }
                    }
                }
}

The program would recognize they have the same pattern and extract the unk_ 's into a list with the unk_ from file 1 on the left and the unk_ from file 2 on the right like so:
unk_0x44334545, unk_0x433877545
etc. etc.
I know this is quite complicated so any help is really really appreciated, Let me know if you need more info or anything like that. Just trying to get an idea of how to go about doing this.
Thanks :)
Answer: How do you define "same pattern". Does whitespace matter, for example? And do you want to do this for any language or just for one?
One quick algorithm for one specific language could be:

Load each file in memory as a single string.
Tokenize these strings on the special separator characters (such as: {}()>=.;), but keep those tokens in your sequences. This transforms your input strings into lists of tokens.
Trim all tokens of whitespace. This allows you to ignore whitespace differences. For example, your goal is to get a sequence like this from the first file: else, {, if, (, func_133212, (, 13, ), ...
Now you can compare the two lists linearly and you can output the pairs that don't match. You can also add some logic that says that for outputting a pair, you need a match of both the element before and after - thus, two successive mismatches would stop your comparison.

Something like this would work for the example you showed and could also be adjusted to work for more complicated examples. Also, if you need to handle larger files, you could stream in their contents and compare them gradually, but that would require more coding.
Comment: Whitespace does not matter. As I said before I really have no idea how to do any of this, in saying that could you give a small example to give me a starting point if you have time? I would really appreciate it. Thank you for your contribution already though, it has given me a lot more understanding of what I need to do.
Comment: All of these steps are about straightforward file reading and string processing. You can find sample code for such operations online or if you have a very specific aspect that you find tricky, then you can ask for an answer here, in a different question.


How to translate/implement a multiobjective binary classifier optimization (multiclass) from matlab to python (using pymoo)?

Question: I'm currently working with two student colleagues with the optimization package pymoo. We have searched in the documentation but we are still strugling to solve some issues.
The main challenge is to define and implement our problem. This problem consist on an optimization of a protein based classifier.
Our aim is to minimize the number of proteins and maximize the accuracy of the classifier(objective function). We already implemented the optimization in matlab, but we are whiling to replicate it on Python.
In matlab we have:
X is a mxn feature matrix(m=samples, n=features)
Y is a multiclass vector(classes: 1,2,3,4)
[m,n]=size(X);
folds=5;
Indices=k_fold(folds,m);

first, we defined the option parameters for the problem which are: multiobjective approach, population size of 50 and 5 generations. This problem is unconstrained.
options = optimoptions('gamultiobj','PopulationType','bitstring','PopulationSize',50,'PlotFcn',@gaplotpareto,'UseParallel',true,'Display','iter','MaxGenerations',5);

fcn is the Objective function which receives the normalized feature matrix Xn and Y (indices is related to the Kfold-cross validation)
fcn=@(Sol)ObjFunc(Sol,Xn,Y,Indices);

In this way we can get this ouput of the optimization including:
BestSol is a vector with the Best solution found.
Fval is a 2 column vector matching the best solution according to the number of features used to classify.
[BestSol,Fval] = gamultiobj(fcn,n,[],[],[],[],[],[],options);

The aim is to get a binary vector (0 and 1) indicating the best features (for the optimized classifier)
The whole first part of the code is:
[m,n]=size(X);
folds=5;
Indices=k_fold(folds,m);
options = optimoptions('gamultiobj','PopulationType','bitstring','PopulationSize',50,'PlotFcn',@gaplotpareto,'UseParallel',true,'Display','iter','MaxGenerations',5);
fcn=@(Sol)ObjFunc(Sol,Xn,Y,Indices);
[BestSol,Fval] = gamultiobj(fcn,n,[],[],[],[],[],[],options);

In python

We don't fully understand how to define our problem class properly.
We have tried to follow some of the examples, but we don't see very clear how to define the objective function according to our case.

this is the example from pymoo docs https://pymoo.org/problems/index.html#
class SphereWithConstraint(Problem):

    def __init__(self):
        super().__init__(n_var=10, n_obj=1, n_constr=1, xl=0, xu=1)

    def _evaluate(self, x, out, *args, **kwargs):
        out["F"] = np.sum((x - 0.5) ** 2, axis=1)
        out["G"] = 0.1 - out["F"]

in our case would be somethin like this:
import numpy as np
from pymoo.model.problem import Problem

class ProteinClassifier(Problem):

    def __init__(self):
        super().__init__(n_var= *columns of X* , n_obj=2, n_constr=0)

    def _evaluate(self, x, out, *args, **kwargs):
        out["F"] = ??????????
        out["G"] = ??????????

in this example they created a binary single objective optimization https://pymoo.org/customization/binary_problem.html:
import numpy as np
from pymoo.algorithms.so_genetic_algorithm import GA
from pymoo.factory import get_crossover, get_mutation, get_sampling
from pymoo.optimize import minimize
from pymoo.problems.single.knapsack import create_random_knapsack_problem

problem = create_random_knapsack_problem(30)

algorithm = GA(
    pop_size=200,
    sampling=get_sampling("bin_random"),
    crossover=get_crossover("bin_hux"),
    mutation=get_mutation("bin_bitflip"),
    eliminate_duplicates=True)

res = minimize(problem,
               algorithm,
               ('n_gen', 100),
               verbose=False)

print("Best solution found: %s" % res.X.astype(int))
print("Function value: %s" % res.F)
print("Constraint violation: %s" % res.CV)

we want to make somethin similar to this, but for multiobjective:
Best solution found: [1 0 0 0 1 0 1 1 0 0 1 0 0 0 0 0 0 1 0 1 0 0 1 0 1 0 0 1 0 0]

Function value: [-686]
Constraint violation: [0.]

Having a look in the github source code we found this, and it is not clear where they defined the x the code is supposing to receive as argument in _evaluate (is supposed to be a decorator in the problem class):
def _evaluate(self, x, out, *args, **kwargs):
    out["F"] = -anp.sum(self.P * x, axis=1)
    out["G"] = (anp.sum(self.W * x, axis=1) - self.C)

the problem source code works like this:
def evaluate(self,
             X,
             *args,
             return_values_of="auto",
             return_as_dictionary=False,
             **kwargs):

    """
    Evaluate the given problem.
    The function values set as defined in the function.
    The constraint values are meant to be positive if infeasible. A higher positive values means "more" infeasible".
    If they are 0 or negative, they will be considered as feasible what ever their value is.

but a decorator is then defined:
@abstractmethod
def _evaluate(self, x, out, *args, **kwargs):
    pass

The method def _evaluate(self, x, out, *args, **kwargs): receives the argument x, but we haven't found where is defined and called. For this reason, we can't execute our objective function, or even put the feature matrix as the input.
-How and where can we define the objective function?
-How does the x is called and handle in the examples?

How to choose the best parameters for the GA object?

We've been stucked in this point for last two weeks. We really appreciate your help
Comment: we also read this [Answer](https://stackoverflow.com/questions/59444909/pymoo-run-multiobjective-function/62175387#62175387) from the main developer. but still isn't clear to us the _evaluate method paradigm.
Answer: I have found some implementation in their official page. Just scroll down to the end to find out more about params and return in the page.
import numpy as np
import autograd.numpy as anp

from pymoo.model.problem import Problem

class MyProblem(Problem):

    def __init__(self, const_1=5, const_2=0.1):

        # define lower and upper bounds -  1d array with length equal to number of variable
        xl = -5 * anp.ones(10)
        xu = 5 * anp.ones(10)

        super().__init__(n_var=10, n_obj=1, n_constr=2, xl=xl, xu=xu, evaluation_of="auto")

        # store custom variables needed for evaluation
        self.const_1 = const_1
        self.const_2 = const_2

    def _evaluate(self, x, out, *args, **kwargs):
        f = anp.sum(anp.power(x, 2) - self.const_1 * anp.cos(2 * anp.pi * x), axis=1)
        g1 = (x[:, 0] + x[:, 1]) - self.const_2
        g2 = self.const_2 - (x[:, 2] + x[:, 3])

        out["F"] = f
        out["G"] = anp.column_stack([g1, g2])

Basically, you initiate the instance of MyProblem class and then call evaluate method.
problem = MyProblem()
dict = problem.evaluate(self, x, out, return_as_dictionary=True)

Returns dict if `return_as_dictionary` is set True or you specify a values of list of strings to be exited

a, b, c, d, e = problem.evaluate(x, return_values_of=[a, b, c, d, e])

Allowed values are ["F", "CV", "G", "dF", "dG", "dCV", "feasible"] for the this argument.

I am not really sure what you meant by GA object but I guess it is g1 and g2 objects which is being defined by passing x argument and then implementing abovementioned formula on it.
Comment: Maybe we weren't clear.  We already have optimized the classifier in matlab (is flawlessly working). In the other hand, our main goal is to achieve a right translation of what we have in the codes in matlab that we showed. To clarify, we don't have constrains, so `n_constr=0`. then, we don't need to define xl and xu. The deal is to declare the objective function in this problem as in matlab. Where we have `fcn=@(Sol)ObjFunc(Sol,Xn,Y,Indices);` How are we supposed to define this Obj Fn in the pymoo problem? let me know if i'm a bit more clear


Why is the graph of 2logx different from log(x^2)?

Question: According to Logarithmic exponent rules:
log(x^y) = y ∙ log(x)
For example:
2 log x = log x^2
However take the following graphs:
y=2logx

y=logx^2

The graphs seems to display something that should not be the case, what am I missing or misunderstanding? I am quite confused.
Comment: That's because $\log x^2$ is defined for $x\ne$, whereas $2\log x$ is defined for $x>0$.
Comment: hint: try the graph of $2\log |x|$...
Comment: Got it, I inputted y=logx^2 {x>0} and received the same as y=2logx.
Comment: I don't think referencing the question "Question about bilinear form on Hilbert space" as saying this is already answered is helpful because if like me you're asking this question, you need a very long explanation to understand how "Question about bilinear form on Hilbert space" is even the same question...
Answer: The domain of $\log x$ and $\log x^2$ is different in the sense that you can plug in negative numbers into $\log x^2$ but not $2\log x$
Answer: $\log$ is only defined for positive inputs. Therefore taking $2\log x$ is bad when $x$ is negative, but $\log x^2$ is fine as $x^2$ is positive. Therefore the graphs are the same for positive $x$, but different for negative $x$.
Answer: In general, the "laws" of exponents and logarithms that you know and love are OK for powers and logarithms of positive numbers, but things are more complicated when negative or complex numbers are involved.  For example, $(a^b)^c = a^{bc}$: but not when
$a = -1$, $b = 2$, $c = 1/2$.  To make sense of this, you have to consider multivalued functions in complex analysis.
Comment: I am speechless, I plugged in values and it does not work. Why? Can you point me to readings or an explanation, even to other similar scenarios?
I do not recall learning this exception, or maybe I did and I forgot. Now I am skeptical of the grounding that these "laws" have and where they do and do not work.
Comment: I just looked some more and everywhere that I see power to a power rule for exponents I find no qualification for when a=1,b=2,c=1/2. You'd think that would be important to include, no?


Projeto Java com Oracle e MySQL ao mesmo tempo?

Question: Tendo em vista um BD Oracle e um BD MySQL, e a impossibilidade de integração de ambas as bases:
Seria possível, por exemplo, uma classe de minha aplicação 'olhar' para a tabela mysql e atualizar uma tabela oracle?
Comment: Sim, seria possível.
Comment: O comentário acima já responderia sua dúvida. Tente especificar melhor qual seu problema. Leia [ask].
Answer: Pelo que pesquisei você pode abrir duas conexões com bancos de dados diferentes e então inserir os dados lidos de um banco de dados no outro mais ou menos assim:
<code>String urlMySql = "jdbc:mysql://localhost:3306/seu_database_mysql";
String urlDb2 = "jdbc:db2://localhost:50000/seu_database_db2";

Connection connMySql = DriverManager.getConnection(urlMySql);
Connection connDb2 = DriverManager.getConnection(urlDb2);

PreparedStatement selectDb2 = connDb2.prepareStatement("SELECT * FROM TABELA");
ResultSet rsDb2 = selectDb2.executeQuery();

while (rsDb2.next()) {
 PreparedStatement insertMySql = connMySql.prepareStatement("INSERT INTO OUTRA_TABELA VALUES...");
insertMySql.setXXX(rsDb2.getXXX(...));
insertMySql.executeUpdate();
}
</code>
Daí, tudo o que você tem que fazer é gerenciar os Connections, PreparedStatements e ResultSets como de costume (inclusive fechando-os em um bloco finally ou usando o try-with-resources).
Também é válido encapsular os Connections em DAOs, colocar as conexões em pools ou separar qualquer operação com o banco de dados em várias classes e/ou vários métodos. Apenas tenha em mente que poderá haver mais do que uma conexão com o banco de dados ativa ao mesmo tempo (juntamente com os respectivos PreparedStatements e ResultSets).
Comment: Muito bom! a minha duvida era justamente "Apenas tenha em mente que poderá haver mais do que uma conexão com o banco de dados ativa ao mesmo tempo". Obrigado!


Metric for nearest neighbor method

Question: Is there a requirement that the measure used in Nearest Neighbor methods be a proper metric distance? What will happen if I use an arbitrary function (e.g., one that does not satisfy the triangle inequality)?
How can you convert an arbitrary function to a valid metric distance?
Comment: In principle, you can use any non-negative real-valued function to evaluate distances. Obviously not all of them are useful though (take for instance the constant null function.)
Comment: I though it must satisfy the triangle inequality d(A,B)<d(A,C)+d(C,B). I think some NN algorithms such as KdTree based on that assumption.
Answer: Replacing the euclidean distance in kNN with another distance function is equivalent to "kernelizing it." A valid Mercer kernel is any function taking two observations that is continuous, symmetric and has a positive definite covariance matrix $\forall x \in D$. Many interesting properties such as stationarity can be imbued in a kernel that make it an attractive option for things like, time-series and geospatial statistics. There exists kernels for structured input that otherwise could not be represented as fixed length vectors. There exists kernels in the literature that are not valid Mercer kernels and still empirically perform well.
If you would like to know more about kernels, I'd recommend reviewing the literature on Gaussian Processes and SVMs.

Metric for nearest neighbor method


Após @JoinColumn JPA nao encontra atributo do entity

Question: Eu tenho duas entidades que estão diretamente relacionadas @Entity Estado e @Entity Cidade e meu intuito era renomear a chave estrangeira presente na entitidade cliente, alterando por exemplo, de 'cidade.estado_idEstado' para 'cidade.idEstado'. Para isto utilizei a annotation @JoinColumn ,entretanto, parece que após esta alteração o Hibernate procura um atributo com o nome que atribui à propriedade NAME da annotation em questão, porém, na entidade Estado eu ja especifiquei o atributo 'estado' como valor do mappedBy.
@Entity Estado
@Entity
public class Estado {

    @Id
    private int idEstado;
    @Column(length=2)
    private String sigla;
    @OneToMany(mappedBy="estado",targetEntity=Cidade.class,cascade=CascadeType.ALL)
    private List<Cidade> cidades;
    public int getIdEstado() {
        return idEstado;
    }
    public void setIdEstado(int idEstado) {
        this.idEstado = idEstado;
    }
    public String getSigla() {
        return sigla;
    }
    public void setSigla(String sigla) {
        this.sigla = sigla;
    }
    public List<Cidade> getCidades() {
        return cidades;
    }
    public void setCidades(List<Cidade> cidades) {
        this.cidades = cidades;
    }
}

@Entity Cidade
@Entity
public class Cidade {
    @Id
    private int idCidade;
    @Column(length=30)
    private String nomeCidade;
    @ManyToOne
    @JoinColumn(name="idEstado")
    private Estado estado;
    public int getIdCidade() {
        return idCidade;
    }
    public void setIdCidade(int idCidade) {
        this.idCidade = idCidade;
    }
    public String getNomeCidade() {
        return nomeCidade;
    }
    public void setNomeCidade(String nomeCidade) {
        this.nomeCidade = nomeCidade;
    }
    public Estado getEstado() {
        return estado;
    }
    public void setEstado(Estado estado) {
        this.estado = estado;
    }
    public Estado getIdEstado() {
        return estado;
    }
    public void setIdEstado(Estado estado) {
        this.estado = estado;
    }
}

Consulta
TypedQuery<Cidade> queryCidades = em.createQuery("select c from Cidade c where c.estado =:codigoEstado",Cidade.class);
queryCidades.setParameter("codigoEstado", 1);
List<Cidade> cidades = queryCidades.getResultList();

Erro
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private int br.com.biblioteca.model.Estado.idEstado] by reflection for persistent property [br.com.biblioteca.model.Estado#idEstado] : 1
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:147)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:155)
    at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1407)
    at org.hibernate.Query.getResultList(Query.java:427)
    at br.com.biblioteca.model.Principal.main(Principal.java:26)
Caused by: org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private int br.com.biblioteca.model.Estado.idEstado] by reflection for persistent property [br.com.biblioteca.model.Estado#idEstado] : 1
    at org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:71)
    at org.hibernate.tuple.entity.AbstractEntityTuplizer.getIdentifier(AbstractEntityTuplizer.java:224)
    at org.hibernate.persister.entity.AbstractEntityPersister.getIdentifier(AbstractEntityPersister.java:4662)
    at org.hibernate.persister.entity.AbstractEntityPersister.isTransient(AbstractEntityPersister.java:4373)
    at org.hibernate.engine.internal.ForeignKeys.isTransient(ForeignKeys.java:226)
    at org.hibernate.engine.internal.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:276)
    at org.hibernate.type.EntityType.getIdentifier(EntityType.java:462)
    at org.hibernate.type.ManyToOneType.nullSafeSet(ManyToOneType.java:161)
    at org.hibernate.param.NamedParameterSpecification.bind(NamedParameterSpecification.java:53)
    at org.hibernate.loader.hql.QueryLoader.bindParameterValues(QueryLoader.java:628)
    at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1956)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1909)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1887)
    at org.hibernate.loader.Loader.doQuery(Loader.java:932)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:349)
    at org.hibernate.loader.Loader.doList(Loader.java:2615)
    at org.hibernate.loader.Loader.doList(Loader.java:2598)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2430)
    at org.hibernate.loader.Loader.list(Loader.java:2425)
    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:502)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:371)
    at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:216)
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1473)
    at org.hibernate.query.internal.AbstractProducedQuery.doList(AbstractProducedQuery.java:1426)
    at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1398)
    ... 2 more
Caused by: java.lang.IllegalArgumentException: Can not set int field br.com.biblioteca.model.Estado.idEstado to java.lang.Integer
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
    at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58)
    at sun.reflect.UnsafeIntegerFieldAccessorImpl.getInt(UnsafeIntegerFieldAccessorImpl.java:56)
    at java.lang.reflect.Field.getInt(Field.java:574)
    at org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:58)
    ... 26 more

Comment: Posso propor testar usando Integer nos atributos idEstado e idCidade? Não como resposta mesmo, mas teste. É disso que o stack trace reclama como erro raiz
Comment: Deu certo! Coloque como resposta.
Comment: irei tentar assim que chegar em casa.
Answer: Chamou-me a atenção a causa raíz dos problemas:
Caused by: java.lang.IllegalArgumentException: Can not set int field br.com.biblioteca.model.Estado.idEstado to java.lang.Integer

Sugeri então trocar os campos declarados como primitivo int para Integer, na esperança do framework não se perder. No caso, os atributos idEstado e idCidade.
O resultado final foi positivo, tendo resolvido a questão atual.
Answer: Opa, você está utilizando a query do TypedQuery, o esperado neste cenário de passagem de parâmetro é você utilizar o próprio objeto estado da cidade, que o hibernate irá se resolver. Ficando:
TypedQuery<Cidade> queryCidades = em.createQuery("select c from Cidade c where c.estado =:estado",Cidade.class);
queryCidades.setParameter("estado", objetoEstado);
List<Cidade> cidades = queryCidades.getResultList();

espero que funcione.
Att