AES em PHP é seguro?

Question: Estou pretendendo implementar AES em uma área de uma intranet que está em desenvolvimento com a finalidade de que o usuário possa guardar dados importantes como senhas de contas e senhas de acesso a servidores, além de transferência de dados através de uma API para servidores externos, porém estou preocupado com a segurança pois estou utilizando uma classe já pronta: Link.
Poderiam me tirar a dúvida se esta classe é segura o suficiente para este tipo de implementação?
Answer: Não. De um modo geral, somente é seguro utilizar bibliotecas que tenham passado por bastante escrutínio de especialistas nessa área. Não só a implementação precisa ser correta, mas ela precisa levar em conta coisas como side-channel attacks (i.e. ataques que exploram falhas na implementação do algoritmo, não na sua lógica). Isso é algo que desenvolvedores "comuns" não estão qualificados a avaliar.
Entretanto, nesse caso nem é preciso ir tão longe: uma passada de olho no código-fonte revelou que ele opera segundo o modo de operação ECB:
public function encrypt($text)
{
    $t = ""; // 16-byte bloco
    $y = ""; // Para retorno do bloco cifrado.

    $xsize = strlen($text);
    for ($i = 0; $i < $xsize; $i += 16){
        for ($j = 0; $j < 16; $j++){
            if (($i+$j) < $xsize){
                $t[$j] = $text[$i+$j];
            }else{
                $t[$j] = chr(0);
            }
        }

        $y .= $this->encryptBlock($t);
    }

    return $y;
}

O ECB é uma implementação "ingênua" da criptografia, o modo que uma pessoa que só estudou seu básico a implementaria. E é totalmente insegura. A imagem abaixo foi criptografada usando ECB, você consegue adivinhar do que ela se trata?

Quanto a uma alternativa segura, infelizmente conheço pouco de PHP para indicar algo. As funções mcrypt_generic e mdecrypt_generic devem ser boas o bastante, mas não sei como usá-las corretamente. Essa resposta no SOen também dá algumas sugestões que à primeira vista parecem boas (mas de novo, não sei avaliar). E se você tiver acesso ao OpenSSL, talvez exista alguma opção de criptografia AES que você possa usar (embora o foco dessa biblioteca seja criptografia de chave pública).
Seja qual solução você escolha, lembre-se de escolher um modo de operação seguro e, de preferência, autenticado (ex.: CCM, GCM, EAX ou OCB). AES é só uma primitiva criptográfica, não um protocolo completo, é preciso ter isso em mente.
Comment: +1 pela resposta

AES em PHP é seguro?


Active Admin form: has_many inputs in separate panels by condition

Question: I am trying to use active admin and formtastic to create a form where reviews of a specific type is edited on a separate panel, currently I render the panels through a .html.erb partial like this:

Admin Reviews

      <% f.has_many :reviews, heading: false, new_record: true, allow_destroy: false do |review| %>
        <% next unless review.object.reviewer_type === "Admin" %>
        <%= render partial: "admin/admin_reviews", locals: { r: review } %>
        <% review.input :_destroy, :as => :boolean, :label => "Delete" %>
      <% end %>

Reviews

    <% f.has_many :reviews, heading: false, new_record: true, allow_destroy: false do |review| %>
       <% next if review.object.reviewer_type === "Admin" %>
       <%= render partial: "admin/form_reviews", locals: { r: review } %>
       <% review.input :_destroy, :as => :boolean, :label => "Delete" %>
    <% end %>

but I would much rather do something like to get rid of the blank div that is generated for each review being iterated through that belongs in the other panel (blank div):

Admin Reviews

      <% admin_reviews = Review.where(reviewer_type: "Admin") %>
      <% f.has_many admin_reviews, heading: false, new_record: true, allow_destroy: true do |review| %>
        <%= render partial: "admin/admin_reviews", locals: { r: review } %>
      <% end %>

Reviews

    <% reviews = Review.where.not(reviewer_type: "Admin") %>
    <% f.has_many reviews, heading: false, new_record: true, allow_destroy: true do |review| %>
       <%= render partial: "admin/form_reviews", locals: { r: review } %>
    <% end %>

The above does not work, but I hope it communicates my need for a neater solution that does not have blank divs that I am considering hiding with javascript.
Answer:

Reviews

        <% f.has_many :reviews, for: [:reviews, f.object.non_admin_reviews], heading: false, new_record: true, allow_destroy: true do |review| %>
          <%= render partial: "admin/tutors/form_tutor_reviews", locals: { r: review } %>
        <% end %>


sqlite tutorial

Question: Is there any good tutorials/books on how to use sqlite with C??
Answer: Yes, right at their website:  http://www.sqlite.org/cintro.html
Answer: I recommend the book: The Definitive Guide to SQLite (1st Edn, 2006) by Mike Owens.  It is a very good book.
There is also a second edition available from multiple sources, including Amazon: The Definitive Guide to SQLite (Expert's Voice in Open Source) (2nd Edn, 2010) by
Grant Allen and Mike Owens.
Comment: I prefer "Using SQLite" (O'Reilly, 2010). It's a great resource for C developers and database designers.

sqlite tutorial


Gerar lista de divisores de um determinado número n

Question: guru = function (n){

  if (n>0){
    x = (n%%(1:n) == 0)

    cat(x)
  }
}

Então, eu preciso criar um vetor que contenha todos os divisores de n, mas quando eu testo, com algum valor de n, ele me diz de forma lógica se tal número na divisão dá resto 0 ou não dá, queria saber como faço para saber quais números e como faço para armazenar tais números num vetor.
Ex: guru (3)
TRUE FALSE TRUE

Answer: Para resolver esse problema basta usar which(vetor lógico).
Note que fiz duas outras modificações. Incluí o newline a terminar o cat e agora a função não se limita a printar qualquer coisa, retorna um valor.
guru <- function(n){
  if (n > 0){
    x <- which(n%%(1:n) == 0)
    cat(x, "\n")
    x
  }
}

guru(3)        # Número primo
guru(8)        # Número composto

No entanto, creio que o seguinte é melhor.
guru2 <- function(n) if (n > 0) which(n%%(1:n) == 0)

guru2(3)        # Número primo
guru2(8)        # Número composto
guru2(12)       # Número composto
guru2(33331)    # Número primo


Find The eigen value of P

Question: Let P,M,N be n$\times$n matrices such that M and N are non singular.If
x is an eigenvector of P corresponding to eigen value $\lambda$,then
an eigenvector of N$^{-1}M$PM$^{-1}N$ corresponding to eigenvalue
$\lambda$is
(a) MN$^{-1}$x (b) M$^{-1}Nx$ (c) NM$^{-1}x$ (d) N$^{-1}Mx$
One more thing that worries me is P and N$^{-1}MPM^{-1}N$ having
same eigen value .What makes it necessary?
My Approach : The only thing i know is since M and N are non-singular
N$^{-1}M$ and M$^{-1}N$ they will have same set of eigenvalues.I
don't know if it has anything to do with question.
Answer: Hint: let $Px=\lambda x$ and $B\equiv APA^{-1}$ for some non-singular matrix $A$. Then
$$
B\color{red}{Ax}=APA^{-1}Ax=\lambda \color{red}{Ax}
$$
Answer: As already said $Px=\lambda x$.
$$N^{-1}MPM^{-1}N=K \rightarrow N^{-1}MP=KN^{-1}M \rightarrow N^{-1}MPx=K(N^{-1}Mx) \rightarrow \lambda (N^{-1}Mx)=K(N^{-1}Mx) $$ and so, $K$ has eigenvalue $\lambda$ and eigenvector $N^{-1}Mx$

Find The eigen value of P


Unknown option `--tail` when running `drush ws --tail`

Question: I am using Drush version 9.0-dev-dev.
When I run drush ws --tail, I get the following error:
[error]  Unknown option: --tail.  See `drush help watchdog-show` for available options. To suppress this error, add the option --strict=0.

I've used this with all other versions of drush with no issues.
Comment: I'm voting to close this question as off-topic because it's a known issue tracked and answered on [GitHub](https://github.com/drush-ops/drush/issues/3414).
Comment: Same Problem here ...

-> see https://github.com/drush-ops/drush/issues/3414
Comment: I have drush 9.0-dev and the sentence works fine
Answer: It's all in the linked issue.

Some existing Drush commands were simplified in Drush 9. I think that
  --tail would still be a welcome addition, if someone wanted to submit a PR.

But as of today the pull request is still unmerged. Maybe you can reanimate it and provide some help.
Comment: As a dirty and quick workaround you can use: `watch -n2 drush ws`. This runs the drush command each 2 seconds, displaying the result. The effect is seeing the updated list of last entries on the watchdog.
Comment: For anyone arriving here much later, the command is now `drush wt` instead.


Apache: Send pre-packed gzip'ed files

Question: I want Apache to send static files gzip'ed over the wire, but also want Apache to not always gzip them over and over again. So I thought if it wouldn't be possible to deliver an .gz file if it exists. This set-up:
File structure:
static/
|
|--- style.css
|
\--- style.css.gz

And the following in an .htaccess:
mod_rewrite rule:
RewriteCond %{REQUEST_FILENAME}.gz -s
RewriteRule ^(.+) $1.gz [L]

And this setting:
AddEncoding x-gzip .gz

Actually, this works insofar as the .gz file is sent instead of the .css, if the request goes to /static/style.css. The problem is only, that the file is delivered as "application/x-gzip" and not as "text/css". Using mod_rewrite's T flag doesn't alter this. Neither does an explicit
AddType text/css .css

Has anyone an idea, how I could achieve the desired behaviour? Or is it unnecessary for some reason I didn't reckon?
EDIT: There is an additional difficulty: Sending the original file to clients without gzip support. Has anyone an idea how this could work?
Comment: I'm amazed this isn't way more obvious, as it seems crazy to have a web server that doesn't do this. I think IIS has a system to cache gzipped copies of static files on first access. mod_deflate doesn't mention such a feature.
Comment: apache's mod_deflate docs have their own example now: http://httpd.apache.org/docs/2.4/mod/mod_deflate.html#precompressed
Answer: A solution for sending the correct version to browsers that don't accept gzip would be something along the lines of:
RewriteCond %{HTTP:Accept-Encoding} !gzip
...your rules here...

Also, there is another way to change the type, namely:
<FilesMatch .*\.css.gz>
    ForceType text/css
</FilesMatch>

<FilesMatch .*\.js.gz>
    ForceType text/javascript
</FilesMatch>

HTH.
Comment: This isn't a huge problem, but reading that config, if someone manually fetched the .css.gz file, they would get the text/css, when they should get the application/x-gzip type.
Comment: Why the ! before gzip on the Accept-Encoding line? Surely that's the opposite of what you need?
Comment: Cool, thanks! Are there docs for the %{HTTP:...} thingy? I didn't see any mentioning of it in the RewriteCond section of Apache 2.2. The FilesMatch was another idea I had but I thought it more verbose. Since both rules need to fire up the regexp engine, there should be no real difference.
Comment: OK, found the docs. http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html I just skipped the interesting part.
Comment: I was thinking the same, it makes sense to have the `RewriteCond` only match when the client _does_ accept gzip encoding.
Answer: Ah, it seems I found a solution: The T flag does not work if set on the same rule, but it sure does, if you spend it a rule of its own:
RewriteCond %{REQUEST_FILENAME}.gz -s
RewriteRule ^(.+) $1.gz

RewriteRule \.css\.gz$ - [T=text/css]
RewriteRule \.js\.gz$ - [T=text/javascript]

Still I would like to hear others' solutions and opinions.

Apache: Send pre-packed gzip'ed files


Probability and range partition

Question: in this question we have a fixed partition and we want to partition the range to obtain a three subsets with the condition below.
Answer: The simplest approach is for person $1$ to produce three parts which have equal probability measure under $\rho_1$.
Person $2$ then takes those two parts with largest and second largest probability measure under $\rho_2$ and moves a bit from the former to the latter so they then have equal probability measure under $\rho_2$, each at least a third of the total.
Person $3$ can then choose one of the three parts with probability measure under $\rho_3$ of at least a third of the total. If this is one of those constructed by person $2$ then the other constructed by person $2$ has probability measure under $\rho_2$ at least a third of the total and the remaining third part has probability measure under $\rho_1$ equal to a third of the total; if person $3$ chooses the part untouched by person $2$, then one of the parts adjusted by person $2$ has has probability measure under $\rho_1$ at least a third of the total and the remaining part has probability measure under $\rho_2$ at least a third of the total.
This works but can create envy, in the sense that, although everyone gets parts which they  measure as at least a third of the total, some might think others have done even better than them.  The Selfridge–Conway discrete procedure provides an envy-free solution.  The question is usually posed as being about cakes, but the key point is that the cake is continuously divisible - hence the probability density functions used here.
Comment: Thanks a lot for your answer and I appreciate your help

Probability and range partition


Write a java file using JavaPoet in annotation processor

Question: I am trying to use processingEnv.getFiler() to create a source file. But I don't see any source file getting created. Below is the code that I am using:
public void javaPoetEg() {
  Filer filer = super.processingEnv.getFiler();
  MethodSpec main = MethodSpec.methodBuilder("testFiler")
    .addModifiers(Modifier.PUBLIC)
    .returns(void.class)
    .addParameter(String[].class, "args")
    .addStatement("$T.out.println($S)", System.class, "Hello, JavaPoet!")
    .build();

  TypeSpec helloWorld = TypeSpec.classBuilder("HelloWorld")
    .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
    .addMethod(main)
    .build();

  JavaFile javaFile = JavaFile.builder("com.ankit.annotation", helloWorld)
    .build();

  try{
    javaFile.writeTo(filer);
  } catch (IOException e) {
    e.printStackTrace();
  }
}

And then calling the function javaPoetEg in the overridden function process() of Annotation processor. What am I doing wrong here?
Answer: I suggest you take a look at how Filer is supposed to work. Javadoc
The location of the source files might depends on parameters you specify via command line, or, you have to check the default generated directory.
Answer: This part: javaFile.writeTo writes to a File, or a PrintStream. So you can do something like this:
File file = new File("/target/directory");
javaFile.writeTo(file); // this will make a new File with all the data you added

Or:
javaFile.writeTo(System.out) // this will print the file representation in the console

Hope this helps. Cheers.


How can I set up filesharing on two servers

Question: I have two servers in my network, both running Windows Server 2008 R2. Server One is the firewall (with local IP 192.168.2.1), and server Two is the web server (with local IP 192.168.2.2) which connects to the web through server One (See image: https://i.stack.imgur.com/9vhpH.png). This means that server One has two network cards.
I have one shared folder on server One (folder A), and one shared folder on server Two (folder B) (regular windows sharing). I would like to be able to connect to both folders from a workstation at another location, for instance by specifying a port or something similar, but I don't how to do this.
When I connect to \\IP-address I get access to folder A (after specifying username/password).
If I go into the Routing and remote access configuration on server One, I can set up the following rule (See image: https://i.stack.imgur.com/UVFWZ.png) on port 445. After I have set this rule, I can with \\IP-address access folder B from the remote location, but at the same time I can no longer access folder A. How can I set this up so that I by specifying a port or something similar from the remote location can access both folders, without having to change the settings in server One all the time (adding or removing the routing rule)?
I am not using Active Directory.
Answer: You want to make folders on two servers visible over the same IP?  Windows doesn't support this type of scenario in any way I know.  I assume you are trying to access the folder from some remote site and you might be better off setting up a PPTP or better,  L2TP or SSTP VPN on your firewall.  When you connect to the VPN, you will appear on the local LAN and be able to access both servers normally.


Custom validator for checking if fields match

Question: I have two fields, value and copy that I'm trying to do some custom validation on to make sure they roughly match each other.
So far in my module I have this:
function HOOK_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle)
{
    if(!empty($fields['field_value']) && !empty($fields['field_copy']))
    {
        $fields['field_copy']->addConstraint('CopyMatchesValue');
        $fields['field_value']->addConstraint('CopyMatchesValue');
    }
}

A constraint
<?php

namespace Drupal\MODULE\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;

/**
 * Checks that value matches copy
 *
 * @Constraint(
 *   id = "CopyMatchesValue",
 *   label = @Translation("Copy Matches Value", context = "Validation"),
 * )
 */
class CopyMatchesValue extends Constraint
{
    // The message that will be shown if the format is incorrect.
    public $copyValueMismatch = 'The value does not look like it matches the copy.';
}

And a validator
<?php

namespace Drupal\MODULE\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Validates the CopyMatchesValue constraint.
 */
class CopyMatchesValueValidator extends ConstraintValidator
{
  /**
   * {@inheritdoc}
   */
  public function validate($items, Constraint $constraint)
  {

      foreach ($items as $key => $item) {
          var_dump($item->value);
      }
      exit;

      // do some processing to make sure they match

      $this->context->addViolation();
    }
  }
}

I was expecting $items to have both fields I added the constraint to, but that doesn't seem to be the case.
How can I pass two fields to one validator so that I can validate them against each other?
Answer: In your case, in validate() you should get an entity before.
So your code should be like this:
<?php

namespace Drupal\MODULE\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Validates the CopyMatchesValue constraint.
 */
class CopyMatchesValueValidator extends ConstraintValidator {

  /**
   * {@inheritdoc}
   */
  public function validate($entity, Constraint $constraint) {
    $entity = $entity->getEntity();
    $field_first = $entity->get('field_first')->getString();
    $field_second = $entity->get('field_second')->getString();
    if ($some_logic) {
      $this->context->addViolation($constraint->message);
    }
  }
}

This one example how I made a similar custom validator for checking the field depending on the value of another field.
Comment: This answer should be marked as the accepted.
Answer: I'm not sure if constraints is the best way to go when you need access to two fields. In your form alter, could you add a custom validation method? That way you would have access to array &$form, FormStateInterface $form_state giving you access to all fields.
$form['#validate'][] = 'my_test_validate';

And then your validation function...
/**
 * {@inheritdoc}
 */
function my_test_validate(array &$form, FormStateInterface $form_state) {
  // Do what you need to do here...
}

Comment: I was originally going to do is this way, but then everything I could find said that you should't do it that way and to use constraints instead. If I go this route, how can I then set the errors on the fields with the equivalent of `$this->context->addViolation`?
Comment: Interesting. I haven't heard that this is no longer the route to go. If you have any backup material for that, I would be curious to give it a look.

That said, you can set the error like this...

    `$form_state->setErrorByName('website', $this->t('Invalid URL.'));`
Comment: I framed my code around [this example](https://drupal.stackexchange.com/a/233053/27797) which mentions it, but I found that same sentiment in a few other places as well.
Comment: Ah I see. For an entity, yes that does make sense. I was answering from a custom form approach which is not quite what you intended.
Comment: I'm using this validator on a node_create form, I'm not sure if that matters or not. Is there different validation for entity vs form?
Comment: Well, if you add a custom form validation method, it will only work when that actual altered form is submitted. So if the node is created through an API or programmatically then your validation will be missed. That would be the only concern.
Comment: Gotcha. I think I'd ultimately rather do entity validation if possible, then. But for now I'll do it with forms. Thanks!
Comment: It is totaly possible to add a constraint to the entity level rather than the field level, in that way you can compare two fields during validation.
Answer: In order to compare and validate two fields of an entity you need to add the validation to the entity itself instead of validating individual fields.
If you have a custom entity you built yourself, add the constraint to the annotation:
/**
 *[...]
 * @MyEntityType(
 *  id = "myentity",
 *  [...]
 *  constraints = {
 *    "MyConstraintName" = {},
 *  },
 * )
 */

If you are altering an entity that you haven't created, you can still add the constraint using hook_entity_type_alter or to alter only one bundle of the entity use hook_entity_bundle_info_alter
Once you have the constraint set up, you can compare and validate the fields in your constraint validator class "validate" method:
  public function validate(array $value, Constraint $constraint) {
   $entity = $this->context->getRoot()->getValue();
   // Do your comparisons here.
   if ($entity->get('yourFirstField')->value !== $entity->get('yourSecondField')->value)) {
     $this->context->addViolation($constraint->fieldsDontMatchMessage);
   }
  }


Some nodes served headless Drupal and some nodes served with Drupal

Question: We are building a site that will be built and served via Drupal.  We want to have microsites that we want to share SOME of the content between the main site and the microsite.  We are thinking to build the microsites via Headless Drupal and use API from the main site.
The problems I see:
For example, node/2 should only be accessible on the microsite.  How would the main site which is not headless know that it can't access node/2?  Basically, some nodes will be served headless and some will be regular Drupal.
Would it make things easier to just have the main site be headless as well?
Comment: Brother, simply create a view or a controller that fetches certain nodes based on whatever logic you want and outputs them as JSON to some URL you can call from outside to populate your microsites with content. That's all. Don't overcomplicate things ;)
Answer: Take a look at the Permissions by Term module.  You can add a term field that defines the site(s) the node is accessible by and limit access to content authors on the main site.
Your API for the microsites can use this to limit access by site as well.
If that one doesn't work, it's description lists another module that might work.


Polyphonic singing techniques (singing multiple notes at once)

Question: I'm basically looking for the possessed oracle sound with my voice. I want 2 distinct notes and I want to be able to speak it. I've tried a bit of stuff already with no success:

Subharmonics (relaxed, low larynx vocal fry; drops the voice an octave): not 2 distinct notes
Ingress phonation (inhale singing that has a head voice, chest voice, and something similar to subharmonics at the bottom): again, not 2 distinct notes
Overtone (producing a high whistle pitch over a sung note by moving the tongue): I am yet to get it spoken, but this has 2 notes
Kargyraa (popular throat singing technique): I'm still learning, but I'm having trouble getting 2 distinct notes right now
Throat bass (I believe this is false chords + vocalization): I haven't started learning it. From what I've heard of it, it may not have 2 distinct notes

If anybody could give me any heads ups on any techniques that have 2 distinct notes with a hope for speaking in it, I would love to know. Also, I would love to hear about any and all polyphonic techniques you know of.
[edit]: I added some "definitions" to the techniques to hopefully explain them better
Comment: I learned a lot just from your question—the only kind of multi-pitched vocal technique I as aware of was kargyraa, and I didn't even know it by that name. You might get better results if you edit to explain the other techniques you reference, since I'm not sure how they differ. Also, we try to keep questions from being too broad: If you settle on one of these techniques, it might be more useful to ask specific help with it.
Answer: I can't say it's provably impossible to do, but it seems like the tongue and throat positions required for any of the overtone singing styles would make it rather difficult to articulate speech.
I'm mostly familiar with the Tuvan styles of overtone singing.  Kargyraa seems most likely to be "speakable".  I have a baritone voice and I'm able to manage a Xöömei, which is probably a second choice.  Although I can't do either, it seems Sygyt and Borbangnadyr would be impossible to speak, especially when you consider that they are rarely used with lyrics the way Kargyraa and Xöömei are.
Comment: Ok, so it sounds like the answer isn't going to be overtones because of the precision required to get the overtone in the first place. Thank you!
Answer: In my opinion, the (western contemporary) experts on the subject of polyphonic voice are in the beatboxing community! There's a very common technique that beatboxers use to create a true polyphonic voice effect; I am not sure of the exact anatomy of how to do it, but I've heard it described in loose terms and it seems to involve careful manipulation of the traditionally "ugly" break between the falsetto voice and the voice; somehow abusing this break is able to force the vocal cords to vibrate at two unrelated frequencies?
It is certainly possible to control this, even to the degree of harmonizing with oneself. However, it's difficult and learning may be confusing with the typical beatboxing non-agreement on exact precise terminology. Here's a great example:

Happy researching! There are also other people who can do this same technique in other variations, but beatboxing seems to me to be where it's most well-known.
Comment: I've been looking for that person for a while now! Thank you for this, I will definitely try this out
Answer: I found something from Beatbox international

I'll need to find out how he makes that sound, but it definitely has 2 notes, and can be spoken. It doesn't sound as clear as user45266's answer, but it's something that can work for this sound.
[edit] : I'm looking into this specific sound and there are rumors that one line was edited (the line I'm interested in). I haven't been able to confirm yet, but it's not looking hopeful.


How to import an object list from a javascript file to dynamic slug component in Next Js

Question: I have started using Next JS in my project. I have a list of projects in a separate js file. Projects are listed in my main page and when clicked on a project, I am navigating to the project details page. I have created /pages/projects/[slug].js to dynamically create pages and use project id in Link. I use router.query.slug to get the project id in the slug. I want to import the project list in the slug and choose the project. I am unable to reference the project's details from the imported projects list. I tried to console.log the project variable. In the browser console I get the project details, but in VS code terminal i get undefined. If I try to access project properties I get TypeError: Cannot read properties of undefined (reading 'name').
My Slug:

import { useRouter } from 'next/router';
import ProjectDetail from '../../components/projectdetails';
import '../../styles/globals.css'

const ProjectPage = () => {
  const router = useRouter();
  const projectid=(parseInt(router.query.slug,10));
  return (
    <>
    <ProjectDetail projectid={projectid} />
    </>
  );
};

export default ProjectPage;

My ProjectDetail component

'use client';
import { Box, Paper, Typography } from '@mui/material';
import projectlist from '../utility/projectlist';

const ProjectDetail = ({projectid}=props) => {
  const project=projectlist[projectid];
  console.log(project.name);
  // const images = [...project.screenshot];

  return (

      <Box>

      </Box>

  );
};

export default ProjectDetail;
Comment: Can you show the `projectlist`?
Comment: This is weired: `{projectid}=props`. Try just with `{projectid}`.
Comment: Hi, thank you for your time. Seems the problem was using `app` directory in my project. I had my main page in that directory when the app was created. I got `undefined` value for project id all the time. I disabled it in `next.config.js` and created an `index.js` in `pages` directory and used `Link` query to pass the value and got the value in the slug
Answer: thank you for your time. Seems the problem was using app directory in my project. I had my main page in that directory when the app was created. I got undefined value for projectid all the time. I disabled it in next.config.js and created an index.js in pages directory and used Link query to pass the value and got the value in the slug


How do you fix wget from comingling download data when running multiple concurrent instances?

Question: I am running a script that in turn calls another script multiple times in the background with different sets of parameters.
The secondary script first does a wget on an ftp url to get a listing of files at that url.  It outputs that to a unique filename.
Simplified example:
Each of these is being called by a separate instance of the secondary script running in the background.
wget --no-verbose 'ftp://foo.com/' -O '/downloads/foo/foo_listing.html' >foo.log

wget --no-verbose 'ftp://bar.com/' -O '/downloads/bar/bar_listing.html' >bar.log

When I run the secondary script once at a time, everything behaves as expected.  I get an html file with a list of files, links to them, and information about the files the same way I would when viewing an ftp url through a browser.
Continued simplified one at a time (and expected) example results:
foo_listing.html:
...
foo1.xml ...
foo2.xml ...
...

bar_listing.html:
...
bar3.xml ...
bar4.xml ...
...

When I run the secondary script many times in the background, some of the resulting files, although they have the base urls correct (the one that was passed in) the files listed are from a different run of wget.
Continued simplified multiprocessing (and actual) example results:
foo_listing.html:
...
bar3.xml ...
bar4.xml ...
...

bar_listing.html
correct, as above
Oddly enough, all other files I download seem to work just fine.  It's only these listing files that get jumbled up.
The current workaround is to put in a 5 second delay between backgrounded processes.  With only that one change everything works perfectly.

Does anybody know how to fix this?
Please don't recommend using some other method of getting the listing files or not running concurrently.  I'd like to actually know how to fix this when using wget in many backgrounded processes if possible.
EDIT:
Note:
I am not referring to the status output that wget spews to the screen.  I don't care at all about that (that is actually also being stored in separate log files and is working correctly).  I'm referring to the data wget is downloading from the web.
Also, I cannot show the exact code that I am using as it is proprietary for my company.  There is nothing "wrong" with my code as it works perfectly when putting in a 5 second delay between backgrounded instances.
Comment: Are you sure you've got the filename generating code right? Does everything work as expected when you're running one `wget` at a time?
Comment: Yep, the current workaround is putting in a 5 second delay.  With only that one change everything works as expected.
Comment: Just in case that wasn't clear.  All the filename generation is happening correctly.  Even if it wasn't that would mean that each line would be correct as it output to the file.  Instead on each line of the file some parts are consistently for one instance of wget and other parts, consistently, are from another instance.
Comment: The examples above are as close as I can give.  As I've said, everything works so long as I put in a delay between putting in processes.  I can't show the exact code as it has proprietary information in it belonging to my company.
Answer: Log bug with Gnu, use something else for now whenever possible, put in time delays between concurrent runs.  Possibly create a wrapper for getting ftp directory listings that only allows one at a time to be retrieved.
:-/


Use Unicode text or Unicode for string?

Question: I got a problem when save string character.
Example, I create property file for multi language or define a const in .java file. I have 2 options to do it:
label.country=Việt Nam

(public static final int COUNTRY = "Việt Nam";)

or
label.country=\u0056\u0069\u1ec7\u0074 \u004e\u0061\u006d

(public static final int COUNTRY = "\u0056\u0069\u1ec7\u0074 \u004e\u0061\u006d";)

I think the first option is no problem, but some people recommend me use second option. I don't know what is the different of that. Please let me know what is the best option and the different between 2 options.
Note: All files are encoded in UTF-8.
Answer: In short, the first option is recommended.
As long as the file is truly encoded in UTF-8 you are fine. I don't recommend using Unicode escape sequences. The key is that you must tell your java reader that you are reading a UTF-8 file so it can be encoded into UTF-16 Java strings. Something like this:
BufferedReader in = new BufferedReader(
           new InputStreamReader(
                      new FileInputStream(fileDir), "UTF8"));

If you are writing files to disk and want UTF-8 be sure to set the encoding to UTF8. That is key.
Comment: Thank you. Can you tell me when the second option is better?
Comment: The second option, that is escape sequences, are typically used in files which can't themselves be in unicode for whatever reason. For example I have had ASCII source files in java that (long story) could not be saved as UTF-8 or even UTF-16. So within java strings we used Unicode escape characters for foreign language scripts.    It also comes in handy if you wish to encode a Unicode character that cannot be produced via the keyboard such as Unicode Emojis.  I am sure there are plenty of other cases I haven't thought of. Think of escape sequences as a last resort.
Comment: @LinhNguyen ResourceBundles expect property files to be in the ISO-8859-1 encoding.  You can change that, but it requires creating your own ResourceBundle.Control class and implementing a fair amount of logic.

Use Unicode text or Unicode for string?


How do stochastic simulations work?

Question: Is there any simple (or simplified) explanation for how stochastic simulation work? How those methods could provide the information about the underlying processes that almost impossible to be achieved with non-stochastic models? How stochastic (random) model could link with unknown property of the system?
For example, in the evaluation of mineral distribution in an area (2D or 3D) it is always recommended that to use simulations (specially conditional simulations) instead of estimations (such as kriging, idw etc) since the resulting maps based on simulations could preserve local variations where in almost all estimation methods the smoothing effect exists.
Now the above questions have some physical sense.
Comment: It would be best to be slightly more specific.  Surely your question arises from some specific case you're thinking about.  Say at least a little bit about that specific case.
Comment: I added some information.
Answer: Probably the best idea is just to quote Ulam:

The first thoughts and attempts I made to practice [the Monte Carlo Method] were suggested by a question which occurred to me in 1946 as I was convalescing from an illness and playing solitaires. The question was what are the chances that a Canfield solitaire laid out with 52 cards will come out successfully? After spending a lot of time trying to estimate them by pure combinatorial calculations, I wondered whether a more practical method than "abstract thinking" might not be to lay it out say one hundred times and simply observe and count the number of successful plays. This was already possible to envisage with the beginning of the new era of fast computers, and I immediately thought of problems of neutron diffusion and other questions of mathematical physics, and more generally how to change processes described by certain differential equations into an equivalent form interpretable as a succession of random operations. Later [in 1946], I described the idea to John von Neumann, and we began to plan actual calculations.
Comment: +1 It's always nice to see such useful historical material.  Although it's only implicit in this quotation, the appeal for Ulam, von Neumann, and others is that this technique promises to reveal *complex* behaviors of systems, such as their dynamics and their natural variation, which goes far beyond mere estimations of expectation as in the Canfield game.
Comment: I also liked it.
Answer: At its core, the use of simulation is exploiting the idea that if you repeatedly simulate a process, you can - with a sufficiently large sample size - start to get results that resemble an analytical solution even when that analytical solution is unknown. There are all kinds of questions that can be answered with that - Monte Carlo methods are a pretty sprawling topic, so you might want to consider a more specific question. However, I'll give two examples of techniques where they could be used:

You're trying to calculate the power for a proposed study. Either due to the planned statistical analysis, a very sophisticated study design, or wanting to build in some more complexity, there aren't simple power formulas you can use. You can simulate a population with a true value, and see how many times your analysis technique correctly identifies said true value. That percentage is your power.
You'd like to explore the impact of a study design choice. For example, in a case-control study, its common to sample cases perfectly (from a registry for example), and then recruit controls though some less perfect method, like random-digit dialing. What happens if there are underlying differences in those populations that are related to your outcome? For complex versions of these questions, there aren't clean, closed form solutions. But you can get the answer by simulating thousands upon thousands of studies recruiting from a population with a known value.

If you provide more details about what exactly you're interested in doing, people might be able to point you toward where simulation might help.
Comment: (+1) The power analysis example is a good one. In almost every situation I'm interested in knowing power (or sample size for a particular power) under a particular parameter value, simulation is the only practical way I can get a handle on it.
Comment: I added some points. My question is how random (stochastic) sampling could target the underlying process? What is behind stochastic methods that makes links between us as observers and underlying unknown processes?
Comment: @Developer What links us is coding the simulation. You cannot simulate a purely unknown process. Well, I suppose you could, but it would be pretty useless. What links it is the question you ask, and how you answer it. "If this is uniformly distributed, what happens? What if its not?" - those questions are reflected in the underlying simulation code.
Comment: This answer together with comments looks satisfactory to me. Thanks
Answer: Simulations generally concern estimation of the expected value of some function $f(x)$ of a random variable that has some distribution $\Pr(x)$.
Non-stochastic calculation would be to compute the sum $\text{E}[f(X)] = \sum_x f(x) \Pr(x)$ exhaustively.
The simulation approach is to sample $x_1, \dots, x_n$ from $\Pr(x)$ and then estimate $\text{E}[f(X)]$ by $\sum_i f(x_i) / n$.

How do stochastic simulations work?


How to map Feed Importer with my content type?

Question: Here's my problem:
I'm using the "Feeds" module to import data from different RSS feeds. One of the feeds is:
http://www.happynews.com/rss/.aspx

As you can see, one of the elements is the "link" of each article.
How do I map that link with my content type? (note it's NOT the feed's link)
I've updated my content type "Feed item", adding a new text field to it called "Article link", attached it to the importer item and definitely can see the new field in the "target" options, however, it seems that in the "source" options there is no link field.
Is there a way to add "source" options to map them up with our targets?
Big thanks in advance for any help! I really appreciate it.
So far I found this article that might help to my problem above:

http://www.zivtech.com/blog/feed-feeds-importing-referenced-rss-data#comment-1378
Answer:
How do I map that link with my content type? (note it's NOT the feed's link)

You're right your feed link is NOT a feed link. The URL is simply incorrect and this issue has nothing to do with Feeds module.
http://www.happynews.com/rss/.aspx returns 404 but when you dig a little you can quickly find that http://www.happynews.com/rss/ returns directories and other resources containing XML feeds.
For example https://www.happynews.com/rss/environment.aspx is a correct RSS channel titled "HappyNews - Environment" where you can see <item> XML nodes and each nested <title><description><link><pubDate> data.
To import such single channel you need:

create importer with HTTP Fetcher
and as a parser check Common syndication parser option
in fetcher settings you should provide RSS source channel link, so in Automatically add scheme input simply paste link to the channel you want to import like https://www.happynews.com/rss/environment.aspx
if right address is given Feeds fetcher will be able to"recognize" the scheme and all accessible fields should be visible on mapping tab in "Select a source" select field.

After all steps inluding RSS -> node fields mapping definitions you will be able to import data periodically (when CRON configured) or manually by running http://you-site-address/import
You can also attach importer to specific content type, this way source is imported by creating a node of that content type.
  .


random effect variance increases with the inclusion of predictor

Question: What does it mean when the inclusion of a fixed effect (sex) increases variance of the random effect?
dat <- data.frame(ID=rep(1:12), sex=c(0,1,1,1,0,0,1,0,1,1,0,1), region=rep(c("A","B"),each=6), y=c(12,13,15,7,8,4,8,8,9,3,4,5))

m <- lmer(y~1+(1|region),data=dat)
VarCorr(m)
 Groups   Name        Std.Dev.
 region   (Intercept) 2.1820

m = lmer(y~sex+(1|region),data=dat)
VarCorr(m)
 Groups   Name        Std.Dev.
 region   (Intercept) 2.4544

I thought including an independent variable could only decrease random effect variance, but I am obviously wrong. Is it a good idea to include sex in the model even though it increases random effect variance?
Answer: In this case, the expected behaviour is that the variance of the random intercepts will be unchanged after adding the predictor. In reality, it will change, but the expected change is still zero. If we modify your simulation slightly, we can see that it can decrease slightly:
> dat$region <- rep(c("A","B","C"),each=4)

> lmer(y~1+(1|region),data=dat) %>% VarCorr()
## Groups   Name        Std.Dev.
## region   (Intercept) 3.0721
## Residual             2.7386

> lmer(y~sex+(1|region),data=dat) %>% VarCorr()
## Groups   Name        Std.Dev.
## region   (Intercept) 3.0236
## Residual             2.8577

If we were to repeat this, with different data, we would find that, on average the difference will be zero.  We can do a simple simulation to show this:
> N <- 100
> n.sim <- 200
> rints_dif <- as.numeric(n.sim)
> for(i in 1:n.sim) {
+   set.seed(i)
+
+   X <- rnorm(N)
+   G <- rbinom(N, 10, 0.5)
+   Y <- G + rnorm(N)
+
+   m0 <- lmer(Y ~ 1 + (1|G))
+
+   m1 <- lmer(Y ~ 1 + X + (1|G))
+
+   rints_dif[i] <- as.data.frame(VarCorr(m0))$sdcor[1] - as.data.frame(VarCorr(m1))$sdcor[1]
+ }
> hist(rints_dif)
> mean(rints_dif)
[1] -0.0002529647

Comment: +1 Great post, Rob. Question for you. You say that we would expect the random effect variance to be unchanged with the inclusion of the predictor. Is this because there was no attempt in the simulation to ensure that the predictor and outcome were associated with one another?
Comment: Yes, I am also wondering about that statement. Is it always the case that we should expect no change in random intercepts variance with the inclusion of a predictor?
Comment: @ErikRuzek & locus, Yes this is correct. If `X` is associated with the outcome then things are a bit more complicated. It will depend on whether `X` varies within or between groups, and probably whether there is between *and* within variation ! If it varies only within then I would expect the random intercepts variance to increase, but I think the ICC would also increase. If it varies only between then I think it would decrease, but the ICC would remain unchanged. I'm not completely sure about this, it's probably worthy of asking another question about these scenarios.
Comment: Hey @RobertLong - Years later, I ended up playing with some simulation code in Stata to show how between cluster variance in a predictor has the effect of increasing between cluster variance in the outcome in a mixed effect model. A predictor with little to no between-cluster variance has almost no effect on between-cluster variance of y in the mixed model. I added a new answer just so others would see it in the future.
Answer: As a quick update to the excellent answer by @RobertLong, I simulated some data in Stata to demonstrate how a predictor that itself has sizable between-cluster variance increases the between-cluster variance in the outcome.
Here are the TLDR results. I simulated x1 so that it has almost no between-school variability whereas x2 was simulated to have a fair bit of it. Notice how in column 2 the sd(school) remains almost the same as in column 1. Contrastingly, in columns 3 and 4, the sd(school) increases substantially relative to column1.
----------------------------------------------------------------
                      (1)          (2)          (3)          (4)
                        y            y            y            y
----------------------------------------------------------------
x2                               1.592                     0.976
                              (0.0685)                  (0.0740)

x1                                            2.342        1.480
                                           (0.0904)      (0.100)

_cons               15.44        11.14        7.478        7.769
                  (0.167)      (0.237)      (0.537)      (0.414)
----------------------------------------------------------------
sd(school)          0.763        0.758        3.034        2.045
                  (0.185)      (0.146)      (0.338)      (0.260)
----------------------------------------------------------------
sd(residual)        4.041        3.242        3.054        2.876
                 (0.0927)     (0.0744)     (0.0703)     (0.0666)
----------------------------------------------------------------
N                    1000         1000         1000         1000
----------------------------------------------------------------
Standard errors in parentheses

Simulation code is below:
version 16.1
clear *
set seed 683728

* create scalar to be multplied by rnormal() when creating random intercept
scalar sd_sch_id = .5 // ICC = .5/4+.5 = .11
*scalar sd_residual = 4

* Schools
set obs 50
gen schid = _n
gen re_sch_id = sd_sch_id*rnormal() // random intercept, school level

* Students
expand 20
by schid, sort: gen stuid = _n

* create a vector that contains the equivalent of a lower triangular correlation matrix for x1, x2, and y
matrix c = (1, 0.5968, 1, 0.6623, 0.6174, 1)
* create a vector that contains the means of the variables
matrix m = (3.23,2.775,15.645)
* create a vector that contains the standard deviations
matrix sd = (1.05,1.47,4)
* draw a sample of 1000 cases from a normal distribution with specified correlation structure and specified means and standard deviations
drawnorm x1 x2 y, n(1000) corr(c) cstorage(lower) means(m) sds(sd)
corr y x1 x2 // looks good

*gen residual = sd_res*rnormal() // not needed b/c resiudal baked into drawnorm

* Add random effects to x1, x2, and y
egen pick1sch = tag(schid)
*x1 and x2
scalar sd_x1_sch = 1.2
scalar sd_x2_sch = .01
foreach v of varlist x1 x2 {
    gen re_`v'_sch = sd_`v'_sch*rnormal() if pick1sch==1
    bysort schid: replace re_`v'_sch = re_`v'_sch[_n-1] if missing(re_`v'_sch)
    replace `v' = `v' + re_`v'_sch
}

*y
replace y = y + re_sch_id

foreach v of varlist x1 x2 y {
    bysort schid: egen sch_mn_`v' = mean(`v')
    gen cws_`v' = `v' - sch_mn_`v'
}

mixed y || schid: , stddev // sd = 0.76
eststo empty
mixed y x2 || schid:, stddev // sd = 0.76
eststo x2
mixed y x1 || schid:, stddev // sd = 3.30
eststo x1
mixed y x1 sch_mn_x1 || schid:, stddev // sd = 0.96

mixed y x1 x2 || schid:, stddev // sd = 2.04
eststo x1_x2


Why do TSLint and JSLint report empty blocks?

Question: From time to time, I get TSLint errors "block is empty". This happens e.g. when I pass a no-op callback to a function:
doSomething(() => {});

From what I read, JSLint apparently does the same, but I didn't verify that.
I find these usages completely valid, so I tried to find a reason why empty blocks are considered bad at all. But the only thing I'm able to find (e.g. in this answer) are instructions to add a return; to avoid the error. This is not what I want to do in every empty callback.
Why does TSLint report above empty block as problem? Is there any reason why I shouldn't disable the check?
Comment: @TripeHound No, TSLint complains even when I specify an explicit type of `(() => void)` for the callback. Regarding the noop: I just found out that lodash already defines one: `_.noop`. This is so far the cleanest solution...
Comment: Never used either; just thinking aloud: could it be that the times that TSLint complains is when it thinks the function _should_ return a value and your no-op function isn't doing so?  You could perhaps define an explicit no-op function and just pass its name in this sort of call.
Comment: @danwellman yes but that changes the return type from `void` to an empty object.
Comment: Go to the following page for the empty function errors: https://stackoverflow.com/a/70746269/7680511
Comment: Go to the following page for the empty function errors: https://stackoverflow.com/a/70746269/7680511
Answer:
Why does TSLint report above empty block as problem

To prevent mistakes. Perhaps the function was forgotten to be filled out. Recommend () => undefined as a noop.
More
If you want to disable it simply add "no-empty": false, to your tslint.json (globally disable) or disable it inline using a /* tslint:disable:no-empty */ comment.
Comment: I guess I don't want TSLint to tell me I missed filling out a function body, that's what I have tests for. So if there is really nothing else that this check is useful for, I rather disable it than using `() => undefined` in every single callback. But that's a matter of taste I suppose.
Comment: Like basarat said, a mistake might be you forgot to implement something, although conventionally every function you want yo implement someday should throw `NotImplemented` when used.
Comment: Using `() => undefined` breaks the [no-undefined](https://eslint.org/docs/latest/rules/no-undefined) rule, so no this is not recommended. The recommended fix is to [write a clear comment](https://eslint.org/docs/latest/rules/no-empty-function): `() => {\n// Do nothing.\n}`.
Comment: Just to clarify, could you specify what you mean by "mistakes" exactly? Is it just the empty function body?
Comment: FYI it's been updated to:
 "no-empty": 0,
Comment: @GéryOgam thanks a lot bro, I was just at the docs and literally missed the first topic.
Answer: If you feel you dont want to use callback during certain scenarios
you can modify the code
from
doSomething(() => {});

to
doSomething(() => undefined);

Substituting () => {} to this implies you dont care about this callback. and explicit typecasting will avoid implications.
Good luck.
Answer: A way to suppress the error and designate that empty block was intentionally is to disable the rule temporary:
// tslint:disable-next-line:no-empty
doSomething(() => {});

Or make it non-empty:
doSomething(() => {/**/});

Comment: The second advise seems very inappropriate.
Answer: As with all checks, you have the ultimate judgement on whether they are helping you or not. You can switch off this TSLint check using one of the following options.
Disable the rule in tslint.json
//...
"no-empty": false,
//...

Disable the rule in the file:
/* tslint:disable:no-empty */

You can always switch it back on again if sometime in the future you find an empty block that has caused you a problem.
Comment: @angellica.araujo you should absolutely build your own ruleset with your team. Don't follow lint rules blindly. I would keep this particular rule, but in general, you should _think_ about each rule and take a team decision.
Comment: Avoid disabling lint rules.
Comment: I understand your point. The thing is that ideally, the decision to build the ruleset usually occurs when the project starts. You may help me to understand why investing time to choose a ruleset that can be easily bypassed or ignored (as the first option to solve issues like the one mentioned) while a project grows.
Answer: tslint v5.10.0 introduced "allow-empty-functions" option to "no-empty" just for this case;
also "allow-empty-catch" (introduced in v5.5.0) may be useful:
"no-empty": [true, "allow-empty-functions", "allow-empty-catch"]

Answer: if it doesn't work the comment inline to disable try this
// eslint-disable-next-line @typescript-eslint/no-empty-function
handler: () => { }, // here you empty function


Factorise the following p(x) as the product of a linear term and a quadratic polynomial with no real roots.

Question: Factorise the following p(x) functions as the product of a linear term and a quadratic polynomial with no real roots (or if there are real roots, factorise to irreducible form and find them):
 1. $$p(x)=x^3+x$$
 2. $$p(x)=x^4+x^2$$
 3. $$p(x)=x^3-x$$
Comment: What have you tried? Where are you confused?
Answer: Really, these polynomials target a single skill: taking out a common factor. For example, with $x^2+x$, both terms have $x$ as a factor, so you can divide it out (inverse distributive property of sorts) and get $x(x+1)$.
$$$$

$$x^3+x = x(x^2+1)$$
Roots are $0$, $i$, and $-i$.
$$x^4+x^2 = x^2(x^2+1)$$
Roots are $0$, $i$, and $-i$.
$$x^3-x = x(x^2-1) = x(x+1)(x-1)$$
Roots are $0$, $1$, and $-1$.
Comment: Ah, see this is exactly what I thought to do at first, but then the wording of the question threw me. What do they mean by "product of a linear term"?
Isn't 0 a real root? Is it possible to take 1 and 2 further so that the terms only give complex roots and no real roots? Or is that impossible?
Comment: @KaylaMartin if p(x) has a real root, it will be there however further you take it. Linear term will obviously give you a real root. So, it is impossible.
Comment: Okay, thank you!
Answer: I think it's important you understand this idea for more difficult cases than you ask about, so my answer will touch on a more general method for solving these problems, and show you how it works for slightly more difficult cases.
We have that if for some polynomial  $p(x)$, $p(a)=0$, then:
$$p(x)=(x-a)\cdot q(x)$$
Where $q(x)$ is a polynomial one degree smaller than $p(x)$ (the degree of a polynomial just means the largest power of $x$ in it).
If you can find any point where a polynomial $p(x) $ has a zero, you can take out the factor in this way and find the smaller polynomial $q(x)$, which can either be solved or reduced again.
Let me demonstrate first on (b)
We have that $p(x)=x^4-x^2$
I like to test values $0,1,-1,2,-2$ etc... Here, it's plain that $p (0)=0$, so we take out $(x-0)$, or just $x$. We now have that:
$$x^4-x^2=x\cdot q(x)$$
From which we get that $q(x)=x^3-x$. But $q(0)=0$, so we can take out another factor $x$, giving $$x^4-x^2=x^2\cdot r (x)$$ It follows that $r(x)=x^2+1$, a quadratic we can solve by the Quadratic Formula.
This is a rather bland example, so I'll demonstrate the procedure on a better example.
Suppose we have $$f(x)=x^3+4x^2+7x+4$$
Plugging in values for $x$, we get that $f(-1)=0$
So we have that:
$$x^3+4x^2+7x+4=(x+1)\cdot g(x)$$
Or rather,
$$x^3+4x^2+7x+4=(x+1)(x^2+px+q)$$ for some real $p,q$.
Expanding this out we get:
$$x^3+4x^2+7x+4=x^3+(p+1)x^2+(p+q)x+q$$
From which it follows that $p=3, q=4$.
So: $$f(x)=(x+1)(x^2+3x+4)$$, which is a quadratic we can solve (even if the solutions aren't real)


SQLSTATE[40001]: Serialization failure: 1213 Deadlock issue caused by INSERT trigger on concurrent access

Question: I found a SQL deadlock issue which occurs when the function is executed concurrently by two users. I have a PHP function which executes several database insert queries which enclose in a transaction. And one of the inserts fires a trigger as well. See my table schema and code sample below.
main_table
CREATE TABLE `main_table` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `action_time` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

history_table
CREATE TABLE `history_table` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `action_time` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  `audit_id` INT,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

audit_table
CREATE TABLE `audit_table` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `action_time` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

I have a trigger on main_table, defined as follows. What it does is that selecting the max id from audit_table and insert a record to the history_table.
CREATE TRIGGER watch_insert_main_table
AFTER INSERT ON main_table
FOR EACH ROW BEGIN
    DECLARE max_id INT;
    SET max_id = (SELECT MAX(`id`) FROM `audit_table`) + 1;
    INSERT INTO `history_table` SET audit_id=max_id;
END;

Following is the function which is executed by two users concurrently. insertRecord funtion simply inserts a record to the given table.
try {
    $dbConnection->beginTransaction();
    $this->insertRecord('main_table');
    $this->insertRecord('audit_table');
    $dbConnection->commit();
} catch (Exception $e) {
    $dbConnection->rollback();
}

I get the following dead lock error when the function is called for the second time (concurrently).
40001 - SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock; try restarting transaction

If I do either of the following changes, this issue won't occur.

Remove the enclosed transaction in the PHP code
Remove $this->insertRecord('audit_table'); line from the PHP code
Modify the trigger so that it doesn't have a select statement from the audit_table

I want to know the root cause of this issue. Is another transaction being starting from the MySQL trigger when it is fired? How are the transactions and locks working inside a trigger?
I found that the following two questions are also related to a similar issue.

MySQL Deadlock with an an insert that raises a trigger
Deadlock caused by INSERT trigger - thread looking for lock it already has?
Answer: See if this simplification helps:
CREATE TRIGGER watch_insert_main_table
AFTER INSERT ON main_table
FOR EACH ROW BEGIN
    INSERT INTO `history_table` (audit_id)
        SELECT MAX(`id`)+1 FROM `audit_table`;
END;

Notice how it combines your two statements into a single statement.  This may avoid letting another connection get in there and grab the same id (or something to that effect).
The following may be related (provided by OP):  This happens due to a known issue in MySQL. Setting a variable from a select acquires a lock when using read uncommitted isolation level. This thread has more information.
Are you using isolation mode Read Uncommitted?  If so, why?
Comment: Yes! This solves the problem. What I wanted to know is that the root cause for this issue. I found that the issue happens due to a known issue in mysql. I will edit your answer and add more information.
Comment: @PathumHarshana - I provided my rationale for suggesting the code and I rescued your comment, but... Are you using isolation mode Read Uncommitted? If so, why?


Retrieving project version from csproj in Azure Pipeline .NET Core CLI task

Question: I have the following tasks in my yaml file in Azure DevOps
It publishes my console application and zip it in a file
- task: DotNetCoreCLI@2
  inputs:
    command: 'publish'
    publishWebProjects: false
    projects: '**/MyApp.csproj'
    arguments: '-r win-x64 -p:PublishSingleFile=True --self-contained true -o $(Build.ArtifactStagingDirectory)'

- task: PublishBuildArtifacts@1
  inputs:
    PathtoPublish: '$(Build.ArtifactStagingDirectory)'
    ArtifactName: 'drop'
    publishLocation: 'Container'

I set the project version directly on the project file in Visual Studio when I make any changes.
Now I'm trying to get that version when I am publishing the project in AzureDevOps and customise the file name, lets say for a project version 1.2.1 the archived file output of the publish in azure should be MyApp-v1.2.1.zip
Currently it only output file as MyApp.zip
Not sure if even my approach towards versioning is correct, so appreciate any input!
Updated:
Unfortunately the provided answer didn't work for me, I can get the version but I cannot rename the file, even copying the exact script below results in the same zip file, not renamed! The folder will be renamed but the zip file stays as MyApp.zip.
I have the following script now, trying to rename using PowerShell at the end but that successfully finish executing and again results in exact the same MyApp.zip file in the drop folder

- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: |
         $xml = [Xml] (Get-Content .\MyApp\MyApp.csproj)
         $version = $xml.Project.PropertyGroup.Version
         echo $version
         echo "##vso[task.setvariable variable=version]$version"

- task: DotNetCoreCLI@2
  inputs:
    command: 'publish'
    publishWebProjects: false
    projects: '**/MyApp.csproj'
    arguments: '-r win-x64 -p:PublishSingleFile=True --self-contained true -o $(Build.ArtifactStagingDirectory)'

- task: PublishBuildArtifacts@1
  displayName: 'Publish Artifact'
  inputs:
    PathtoPublish: '$(build.artifactstagingdirectory)'
  condition: succeededOrFailed()

- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: 'Rename-Item -Path "$(Build.ArtifactStagingDirectory)\MyApp.zip" -NewName "$(Build.ArtifactStagingDirectory)\MyApp-Win-x64-v$(version).zip"'

However the above script doesn't work either, as if we don't have permission to change that zip file, no matter what I cannot rename it.
Fixed - Solution
I had to move the rename power shell script to before Publish Artifact

- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: |
         $xml = [Xml] (Get-Content .\MyApp\MyApp.csproj)
         $version = $xml.Project.PropertyGroup.Version
         echo $version
         echo "##vso[task.setvariable variable=version]$version"

- task: DotNetCoreCLI@2
  inputs:
    command: 'publish'
    publishWebProjects: false
    projects: '**/MyApp.csproj'
    arguments: '-r win-x64 -p:PublishSingleFile=True --self-contained true -o $(Build.ArtifactStagingDirectory)'

- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: 'Rename-Item -Path "$(Build.ArtifactStagingDirectory)\MyApp.zip" -NewName "$(Build.ArtifactStagingDirectory)\MyApp-Win-x64-v$(version).zip"'

- task: PublishBuildArtifacts@1
  displayName: 'Publish Artifact'
  inputs:
    PathtoPublish: '$(build.artifactstagingdirectory)'
  condition: succeededOrFailed()

Answer: To set the name of the output file(zip file), you need to set the corresponding format in dotnet build argument.
--configuration $(BuildConfiguration) --output $(build.artifactstagingdirectory)/MyApp-$(version)

In order to get the Version value in csproj file, you can add a powershell task before the Dotnet Publish task. Then you could retrieve project version from csproj
Here is my example:
- powershell: |
   $xml = [Xml] (Get-Content .\MyApp.csproj)
   $version = $xml.Project.PropertyGroup.Version

   echo $version

   echo "##vso[task.setvariable variable=version]$version"
  displayName: 'PowerShell Script'

- task: DotNetCoreCLI@2
  displayName: Publish
  inputs:
    command: publish
    publishWebProjects: false
    projects: '**/*.csproj'
    arguments: '--configuration $(BuildConfiguration) --output $(build.artifactstagingdirectory)/MyApp-$(version)'

- task: PublishBuildArtifacts@1
  displayName: 'Publish Artifact'
  inputs:
    PathtoPublish: '$(build.artifactstagingdirectory)'
  condition: succeededOrFailed()

Result:

You can also try to set the name as $(build.artifactstagingdirectory)/MyApp-v$(version)
The output name will be MyApp-v1.0.0.zip
Update:
I have tested your sample in Yaml Pipeline and I could reproduce this issue.
To solve this issue, you could add the parameter: modifyOutputPath: false in Dotnet Publish task.
Here is the yaml sample:
- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: |
         $xml = [Xml] (Get-Content .\MyApp\MyApp.csproj)
         $version = $xml.Project.PropertyGroup.Version
         echo $version
         echo "##vso[task.setvariable variable=version]$version"

- task: DotNetCoreCLI@2
  displayName: Publish
  inputs:
    command: publish
    publishWebProjects: false
    projects: '**/*.csproj'
    arguments: '--configuration $(BuildConfiguration) --output $(build.artifactstagingdirectory)/MyApp-v$(version)'
    modifyOutputPath: false

- task: PublishBuildArtifacts@1
  displayName: 'Publish Artifact'
  inputs:
    PathtoPublish: '$(build.artifactstagingdirectory)'
  condition: succeededOrFailed()

Comment: oh wow mate, thanks very much I did it the hard way and edited it in an azure function! But your method is the right way of doing it!
Comment: arguments: '-r win-x64 -p:PublishSingleFile=True --self-contained true -o $(Build.ArtifactStagingDirectory)/MyApp-Win-x64-v$(version)'
Comment: Actually never mind I fixed it, I had to move the PowerShell script to before publish artifact
Comment: Hi @user65248. Please refer to my update. You just need to add the parameter: modifyOutputPath: false in dotnet publish task. Then it will work fine . This could be an easier method to solve this issue.
Comment: Ah great, thanks very much for the update!
Comment: But this answer is not completely correct. You are not changing assembly file version. To do that you need to add following argument: -p:Version=$(version)


Value of expression involving coefficients of an equation and its complex roots.

Question: It is given that $\cos\alpha + i \sin\alpha$ is the solution of the equation
$$x^n + P_1x^{n-1}+ \cdots +P_n=0$$ where all the coefficients are real.
Then what is the value of $$P_1\sin\alpha+P_2\sin2\alpha+ \cdots + P_n \sin n\alpha$$
By substituting $n=1$ and $P_n$ an arbitrary real value, it is easily seen that $\alpha=n\pi$ and hence the value is $0$.
But how can this be proved for any values of $n$ and the other co-efficients in the equation?
Comment: Is it supposed to be $P_1x^2$ or $P_1x^{n-1}$?
Comment: Oops! I've changed it. Thanks for suggesting the edit.@kingW3
Comment: $P(e^{i\alpha}) = 0 \implies \Im\left(e^{-in\alpha}P(e^{i\alpha})\right) = 0$. Now express RHS using $\sin\alpha, \sin(2\alpha),\ldots$.
Answer: Once we have:
$$x^n + P_1x^{n-1}+ \cdots +P_n=0 \quad (1)$$
divide everything by $x^n$ and get:
$$1 + P_1x+ P_2x^{-2}\cdots +P_nx^{-n}=0 \quad (2)$$
If $\cos \alpha + i\sin \alpha$ is root of $(1)$ then $(\cos \alpha + i\sin \alpha)^{-1}=\cos \alpha - i\sin \alpha$ is root of $(2)$.
Use that $(\cos \alpha - i\sin \alpha)^m=\cos (m\alpha) - i\sin (m\alpha)$, so:
$$1 + P_1x+ P_2x^{-2}\cdots +P_nx^{-n}=\\
=1+P_1[\cos (\alpha) - i\sin (\alpha)]+P_2(\cos (2\alpha) - i\sin (2\alpha))+...+P_n(\cos (n\alpha) - i\sin (n\alpha))=0$$
so,
$$P_n\cos (n\alpha)+P_{n-1}\cos ((n-1)\alpha)+...+P_{1}\cos (\alpha)+1=0$$
$$-i[P_n\sin (n\alpha)+P_{n-1}\sin ((n-1)\alpha)+...+P_{1}\sin (\alpha)]=0$$
and
$$P_n\sin (n\alpha)+P_{n-1}\sin ((n-1)\alpha)+...+P_{1}\sin (\alpha)=0$$
Comment: Will the same be true if these equations involved complex coefficients?
Comment: @AnanthKamath: Nope! I can write $$-i[P_n\sin (n\alpha)+P_{n-1}\sin ((n-1)\alpha)+...+P_{1}\sin (\alpha)]=0$$ only if $P_i\in \Bbb R$.
Comment: Okay.  Thanks for sharing your knowledge @Arnaldo.


Duplicated copy using file.makeCopy() function (Google Apps Script)

Question: I'm having a problem with a file.makeCopy(name, destination) function. I have a form and a spreadsheet template in a folder. I want to copy them to another directory. Here it is my code:
  // Create the destination folder
  var newFolder = parentFolder.createFolder(institute + " - a.s. " + schoolYear + " - " + school + " - Classe " + classroom + section);

  // Create a copy of the template form in the created folder and name it "questionario"
  var formFile = formTemplate.makeCopy('questionario', newFolder);
  var form = FormApp.openById(formFile.getId());

  // Create a spreadsheet for answers in the new folder and name it "risposte"
  var repliesFile = responseTemplate.makeCopy('risposte', newFolder);
  var replies = SpreadsheetApp.openById(repliesFile.getId());

  // Connect the form to the spreadsheet
  form.setDestination(FormApp.DestinationType.SPREADSHEET, replies.getId());

Both files, form and spresdsheet, are correctly copied to the new folder. The problem is another copy of the form is created in the source directory (template directory). That is not happening to the spreadsheet: the script create a copy in directory I want and no copies are created in the template folder. I can't figure it out, any idea? Some images are attached.
Template folder

Destination folder
Answer: Whenever you make a copy of a Spreadsheet that has a linked Form, a copy of that Form is automatically made and linked to the new Spreadsheet (you can test this by manually making a copy of the Spreadsheet in Google Drive).  So when your script makes a copy of the form and links it to the Spreadsheet, this is extra work because it's already been done.
You might be better off to just rename and move the copy of the form that is automatically generated:
// Create the destination folder
var newFolder = parentFolder.createFolder(institute + " - a.s. " + schoolYear + " - " + school + " - Classe " + classroom + section);

// Create a spreadsheet for answers in the new folder and name it "risposte"
var repliesFile = responseTemplate.makeCopy('risposte', newFolder);
var replies = SpreadsheetApp.openById(repliesFile.getId());

// Get the URL of the linked form
var formUrl = replies.getSheetByName('NameOfTheRepliesSheet').getFormUrl();
var formId = FormApp.openById(formUrl).getId();

// Get the Form as a Drive File object so we can change its parent folder.
var formFile = DriveApp.getFileById(formId);

// Rename the file.
formFile.setName('questionario');

// You can't 'move' a file in Drive: you add it to one folder and remove it from the other.
var oldFolder = formFile.getParents().next();
newFolder.addFile(formFile);
oldFolder.removeFile(formFile);

Note that now there is no need to call form.setDestination(), because the form was already linked when the Spreadsheet copy was made.
Comment: Thanks a lot Aaron, that explains everything!


como eu posso pegar o texto de uma página html usando python?

Question: estava tentando pegar um texto de uma página html em um localhost usando a biblioteca requests do python, quando eu rodava o código, ele só mostrava se o status era 200 ou 404.
Alguém pode me ajudar?
Código:
<code>import requests

texto = requests.get("(link do localhost)")
print(texto)

</code>
Comment: Tenta [`print(texto.text)`](https://docs.python-requests.org/en/latest/api/#requests.Response). Veja também [HTTP Status 200](https://developer.mozilla.org/pt-BR/docs/Web/HTTP/Status/200) e [HTTP Status 404](https://developer.mozilla.org/pt-BR/docs/Web/HTTP/Status/404)
Comment: @Augusto Vasques Muito obrigado!! Funcionou perfeitamente
Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Answer: isso por que voce deve tratar o resultado e dizer ao requests.
No caso após voce fazer va requisicao deve fazer print(texto.json()) se caso for um json print(texto.text) no caso de texto e assim por diante, leia a documentacao Documentacao requests
Comment: Corrigi aqui, ajudou muito mesmo


Print result of $body

Question: on D7 and I've made this:
function project() {
  global $user;
  $uid = $user->uid;
  $name = $user->name;

  $teaser = 0;
  $page = 1;
  $type = 'page';
  $status = 1;
  $format = 3;

  $body = " ".
                "

Projects from user ".$name."

";
}
?>

And I need to print the result on the main content of my theme, how can I do it?
If I do echo "$body";I view the result not in the main content but as a single page. Thanks a lot.
Answer: <?php print $node->body['und'][0]['value'];?>

Comment: Hi and thanks for the response.
Added the line but I've blank page. why?
Comment: Notice: Undefined variable: node in ..
Notice: Trying to get property of non-object in ....
Answer: I suppose that project() is a page callback, a function that is associated to a path used from the module, and that needs to output what contained in $body. In that case, you need to returns its content, and your code should be like the following one.
function project() {
  global $user;
  $uid = $user->uid;
  $name = $user->name;

  // The rest of your code.

  return '' . "

Projects from user $name

";
}

The reason is that drupal_deliver_html_page() (indirectly called from index.php) contains the following code.
  if (is_int($page_callback_result)) {
    // The page callback returned an integer.

    // …

  elseif (isset($page_callback_result)) {
    // The page callback returned a string or an array.
    // Print anything besides a menu constant, assuming it's not NULL or
    // undefined.
    print drupal_render_page($page_callback_result);
  }

If your page callback doesn't return anything, but it just prints its own output, drupal_render_page() will not be called, and the output of your page callback will be all the content you see in the page.
Comment: Solved with:
return $body;
Thanks a lot for your help!

Print result of $body


How to make custom Op in TensorFlow importable in Python?

Question: I have implemented a kernel for my custom Op, and put it into /tensorflow/core/user_ops as custom_op.cc. Inside the Op I do all the registering stuff, like REGISTER_OP and REGISTER_KERNEL_BUILDER.
Then I implemented gradient for this Op in Python, and I put it in the same folder as custom_op_grad.py. I did all the registering here as well (@ops.RegisterGradient).
I have created the BUILD file, with the following content:
load("//tensorflow:tensorflow.bzl", "tf_custom_op_library")
tf_custom_op_library(
        name = "custom_op.so",
        srcs = ["custom_op.cc"],
)

py_library(
        name = "custom_op_grad",
        srcs = ["custom_op_grad.py"],
        srcs_version = "PY2",
        deps = [
        ":custom_op_grad",
        "//tensorflow:tensorflow_py",
        ],
)

After that, I rebuild Tensorflow:
pip uninstall tensorflow
bazel clean
bazel build -c opt //tensorflow/tools/pip_package:build_pip_package
cp -r bazel-bin/tensorflow/tools/pip_package/build_pip_package.runfiles/__main__/* bazel-bin/tensorflow/tools/pip_package/build_pip_package.runfiles/
bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg
pip install /tmp/tensorflow_pkg/tensorflow-0.8.0-py2-none-any.whl

When I try to use my Op after all this, by calling tf.user_ops.custom_op it tells me that module doesn't have it.
Maybe there are some additional steps I have to do? Or I am doing something wrong with the BUILD file?
Answer: Ok, I found the solution. I just removed the BUILD file, and my custom Op was successfully built and was importable in Python using tensorflow.user_ops.custom_op().
To use the gradient I had to put it's code directly inside the tensorflow/python/user_ops/user_ops.py. Not the most elegant solution, but working for now.


Server 2003 List AD Objects in OU

Question: I need to list via command line objects within an OU. I know I can use "Export List" in the GUI, but I'd rather be able to do it via CLI as well. I can use a combination of dsquery piped into dsget for groups to get members,
# dsquery group -name "standardDistGroup"
"CN=standardDistGroup,OU=templateOU,DC=employees,DC=MyOrganization,DC=com"

# dsquery group -name "standardDistGroup"  | dsget group -members

"CN=John Doe,OU=templateOU,DC=employees,DC=MyOrganization,DC=com"
"CN=Otto Normalverbraucher,OU=templateOU,DC=employees,DC=MyOrganization,DC=com"

but the same syntax doesn't appear to work for getting OU container objects.
# dsquery OU -name "ByeBye"
"OU=ByeBye,DC=employees,DC=MyOrganization,DC=com"

# dsquery OU -name "ByeBye"  | dsget ou -members

dsget failed:`-members' is an unknown parameter.
type dsget /? for help.
# dsquery OU -name "ByeBye"  | dsget group -members
dsget failed:OU=ByeBye,DC=employees,DC=MyOrganization,DC=com:The object class of the target does not match the one specified on the command line.
type dsget /? for help.

Does anyone know how to accomplish this via CLI? Powershell isn't available on this server.
Comment: I just want to make sure you know Powershell can be installed on Server 2003 and would probably be much simpler for you. https://blogs.technet.microsoft.com/danstolts/2011/03/how-to-install-powershell-on-windows-server-2003-and-enable-remote-powershell-managementall-servers-should-have-this-done/
Answer: Groups have members, OU's do not have members. OU's contain other objects.
You will need a slightly different command for each object type you want to list at a given path.
dsquery user OU=ByeBye,DC=employees,DC=MyOrganization,DC=com

dsquery computer OU=ByeBye,DC=employees,DC=MyOrganization,DC=com

dsquery ou OU=ByeBye,DC=employees,DC=MyOrganization,DC=com

Using powershell would be the better way to do this. You can query objects with get-adobject, get-aduser, get-adcomputer and also navigate AD like a filesystem with the AD: drive after you import-module activeDirectory.

Server 2003 List AD Objects in OU


JSF 2.3: "Array index out of range" when rendering a form with Url containing ''&&"

Question: Given a url with params such that:
page.xhtml?param1=value&&param2=value

It appears that after submitting a form on that page, the following exception and stack trace occurs:
java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 0
    at org.apache.myfaces.context.servlet.ServletExternalContextImpl.encodeURL(ServletExternalContextImpl.java:906)
    at org.apache.myfaces.context.servlet.ServletExternalContextImpl.encodeActionURL(ServletExternalContextImpl.java:364)
    at javax.faces.context.ExternalContextWrapper.encodeActionURL(ExternalContextWrapper.java:80)
    at org.apache.myfaces.shared.renderkit.html.HtmlFormRendererBase.encodeBegin(HtmlFormRendererBase.java:88)
    at javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:597)
    at javax.faces.component.UIComponentBase.encodeAll(UIComponentBase.java:527)
    at javax.faces.component.UIComponentBase.encodeAll(UIComponentBase.java:551)
    at javax.faces.component.UIComponentBase.encodeAll(UIComponentBase.java:551)
    at org.apache.myfaces.view.facelets.FaceletViewDeclarationLanguage.renderView(FaceletViewDeclarationLanguage.java:1897)

It appears that this will happen when the form is being re-rendered.
Using ajax to narrow what is being re-rendered allows me to side step the issue.
With that said, I'm wondering if there are more options to fixing this issue?
Using IBM's Liberty 188.8.131.52, IBM's JSF 2.3 [1.0.0]
Comment: I can't reproduce this error. Can you provide a small app?
Answer: It appears this issue is unique to my project's configurations.  After some selective removals and additions it was discovered that a view-handler responsible for re-attaching request params back onto the url was the culprit.
The param string
param1=value&&param2=value

Would be reattached as
=&param1=value&param2=value

Which in turn caused the encoding exception.
Thank you and Apologies.
Answer: That version of WebSphere Liberty is almost 3 years old, so I would first recommend moving up to a recent version of WebSphere Liberty (or Open Liberty) and checking if the issue has since been resolved.
With Liberty's zero migration architecture, the move to the latest version should be pretty seamless.... and not only will you get ~3 years worth of bug & security fixes but also performance and development enhancements.


What is the purpose of running nginx infront of your app servers on Amazon EC2?

Question: I've been doing a lot of research into back-end architecture. I'm currently running a django app server and a postgresql database server on Amazon's Web Services. All of my content is served through Gunicorn. I would like to know why nginx servers are place in front of the the django app servers. What is their purpose? Here is a diagram:
https://d36cz9buwru1tt.cloudfront.net/architecture_diagram_praekelt-1.jpg
Answer: In many stacks, nginx is often placed in front of unicorn or gunicorn for buffering responses to slow clients.
See the nginx documentation for more information:
http://wiki.nginx.org/HttpProxyModule#proxy_buffering
The ELB doesn't do buffering, so having nginx in place can save your bacon.
Answer: Generally you put a reverse proxy in front of backend servers like gunicorn (or tomcat in the java world) because they have more features and are more resilient.
E.g., with nginx you can add fine-grained access control, terminate SSL, and not be as susceptible to DOS attacks (which is what gunicorn specifically mentions in their docs ( http://docs.gunicorn.org/en/latest/deploy.html ).
In EC2 you could replace nginx and haproxy with an ELB if there are no special features of nginx or haproxy you are using. See http://harish11g.blogspot.com/2012/11/amazon-elb-vs-haproxy-ec2-analysis.html for a comparison of ELBs and haproxy.
Comment: I've look into back end setups of many other companies on AWS and some of them have the ELB in front and then NGINX behind them, why is that?


Asio4all: Simultaneous output on two devices possible?

Question: I am not sure I understood the point of asio4all correctly. I have two USB Audio interfaces (Yamaha AG06 and Line6 Pod X3) that I am using in Cubase AI 8. I use the POD to record the guitar, and the AG06 as a mixer and for a keyboard.
If I switch on two devices in asio4all and I added the corresponding busses in Cubase , shouldn't the sound be redirected to both ?
How can I use one device for recording and the other one for playing (except switching from one driver to the other) ? If this is not possible with asio4all, what is the point of the ability to turn on more than one device at the same time ?
Cheers
Answer: No. Unfortunately Asio4All in cubase does not support using more than one device . Whichever device is switched on first gets control of the driver. ASIO officially does not support more device per driver although there are workarounds for other DAWS.
The only exception is FL Studio.
Comment: Can you elaborate on how FL Studio is different? Is it able to somehow use ASIO4All drivers for more than one interface at a time?
Comment: Yes it is. I had it set up that way for a while.https://www.image-line.com/support/FLHelp/html/envsettings_asio4all.htm


Probability of eighth best reaching the semifinals

Question: $16$ players $P_1, P_2, ..... P_{16}$ take part in a tennis knockout tournament. The order of the matches is chosen in random. Lower suffix player is better than higher suffix, the better wins. What is the probability that the eighth best reaches the semifinals?
Basically I think that we just have to keep selecting only those players who are below $P_8$. For the first round the probability of choosing a player below $P_8$ would be $\frac{8}{15}$. But then I find it difficult to arrange the players who got selected in the next round.
Answer: In order for a particular player to reach the semifinals, where there are $4$ players, they must be in a group of $\frac{16}{4}=4$ players wherein they are the best: our chosen player will play in a first-round match, then in a second-round game against the winner of another first-round match.
So the question is, how many ways are there to pick four players such that the best player is $P_8$?  We must then compare this to the number of ways to pick four players where $P_8$ is included but not necessarily best.
Obviously, one of the four must be $P_8$; this leaves $3$ players to choose from.  There are $8$ players worse than $P_8$, so we have $\binom{8}{3} = 56$ ways to choose the remaining three so that $P_8$ is best.
Similarly, there are $15$ players other than $P_8$, so there are $\binom{15}{3} = 455$ ways for $P_8$ to contend for a semifinal slot at all.
So the final probability is $\frac{56}{455} = \frac{8}{65}$ that $P_8$ will reach the semifinals.
Comment: Can we calculate the number of ways in which $P_8$ reaches semi-finals
Comment: That's $56 \times 3$ - you need the $3$ to determine who $P_8$ is going to play against in the first round.  For instance, one of the $56$ is that in $P_8$'s section of the bracket, there are $P_{10}$, $P_{13}$, and $P_{14}$; $P_8$ could face any one of them in the first round, and the other two will face each other.  Note that this doesn't do anything at all with the rest of the bracket.  If you want to know *those*, I think it's $12!/2^{12}$ but that's just me fiddling with it in my head
Answer: Thinking about it round-by-round is not the easiest way to think about the problem. Instead, think about it this way: the semifinals are between the four players who were best in their quarter of the bracket. What's the probability that $P_8$'s quarter of the bracket doesn't have any of the players better than $P_8$ in it?

 There are $\binom{15}{3}$ ways to choose who else is in the same quarter of the bracket as $P_8$, and $\binom{8}{3}$ ways to choose only players from $\{P_9, P_{10}, \dots, P_{16}\}$. So the probability is $\binom{8}{3}/\binom{15}{3} = \frac{8\cdot 7\cdot 6}{15\cdot 14 \cdot 13} = \frac{8}{65}.$


In survey sampling, have calibration margins to be known (estimated with 0 variance)?

Question: Calibration estimators in survey sampling (as defined by Deville and Särndal, and implemented for example in the SAS macro "Calmar") generalize many other calibration estimators, including post-stratification, when calibration is done using totals of dummies indicating whether each unit belongs to the given post-stratum.
An interesting property about post-stratification estimators is that they are (strictly) unbiased, except when calibration is done using totals not known with certainty, but estimated with a slight error $e = \hat{T(X)} - T(X)$. In this case, bias of the post-stratification estimator is a function of $e$, and does not decrease with sample size (i.e. you can't say the post-stratification estimator is "asymptotically unbiased")
By inference, one could imagine that calibration could only be done using totals known without variance, i.e. computed using the sample frame or a census.
However, it seems that very often calibration estimators are used even when only estimated margins are known. People seem rather happy with it, as long as sample size for the estimation of the margin is significantly higher than sample size of the survey they're trying to calibrate. Pascal Ardilly, in his book Les techniques de sondage (in French, Technip, 2006), says that "you can show that calibration estimation is still asymptotically unbiased when margin is not known, but estimated", but does not explain how this can be done.
Has anyone got ideas on how to prove this result ? Am I the only one the be bugged by the apparent paradox with the bias of the post-stratification estimator ? Maybe the proof brings out a term that cannot be simplified if all variables are categorical and totals for each modality are known (although this would still bug me...) ?
Answer: The behavior of estimators calibrated to estimated control totals has been studied already, see Dever and Valliant 2010 (which is the most technical part of Jill Dever's dissertation). They derive the bias explicitly, discuss the (somewhat weird) conditions under which the bias is small, and provide additional variance terms necessary to account for uncertainty in the control totals.
Comment: A related paper, though not about calibration: Little, Roderick J. A., and Mei-Miau Wu. 1991. Models for Contingency Tables with Known Margins when Target and Sampled Populations Differ. Journal of the American Statistical Association 86, no. 413: 87-95.  See the abstract at: http://amstat.tandfonline.com/doi/citedby/10.1080/01621459.1991.10475007
Comment: Very interesting article ! Though I'm surprised the authors don't insist on the formula : $Bias \approx t_y \dfrac{N_b}{N}$ ($N_b$ being the the estimated margin and $N$ the true margin, assuming there's no coverage bias). After all, it means using estimated margins leads to biased calibrated estimators. And in practice, it is impossible to compute $\dfrac{N_b}{N}$, as surveys are only done once.
Answer: I'd guess that a proof of asymptotic unbiasedness applies only to the double process: 1) estimate margins, with bias going to zero asymptotically; and 2) calibrate to these estimates.
Comment: It's probably what Ardilly meant indeed ! I'm still a little confused, because even if the process you describe truly is unbiased, it seems to me that MSEs can add up dramatically in this case. For what I've seen so far, people working with calibrated estimators just assume unbiasedness (from Deville and Särndal's theorem, i.e. _not_ the 2-step process you describe) and move on...


Next() em CSV Reader com Python 3

Question: Olá, eu estou fazendo um curso de Machine Learning/Classificação e bem ele utiliza um arquivo CSV no qual deve-se ignorar a primeira linha do arquivo. Então fiz o seguinte código:
import csv

def carregar_acessos():

    X = []
    Y = []

    arquivo = open('acesso_pagina.csv', 'rb')
    leitor = csv.reader(arquivo)
    leitor.next()

    for home,como_funciona,contato,comprou in leitor:

        dado = [int(home),int(como_funciona),int(contato)]
        X.append(dado)
        Y.append([int(comprou)])

Porém quando o executo informa que o "leitor" não possuí atributo NEXT. Alguém poderia me ajudar?
Retorno do Terminal:
Traceback (most recent call last):
  File "classifica_acesso.py", line 3, in <module>
    X,Y = carregar_acessos()
  File "/Users/josecarlosferreira/Desktop/machine-learning/dados.py", line 11, in carregar_acessos
    leitor.next()
AttributeError: '_csv.reader' object has no attribute 'next'

Segundo o que é mostrado na aula o código está correto e deveria funcionar. Mas tentei procurar sobre a mudança no Next, e testei outros códigos que encontrei e bem continuava dando erro.
Obs: A primeira linha do Arquivo CSV é um Texto e todas as outras são números inteiros.
Answer: Você precisa usar a função next() em vez de um método com esse nome.
Assim:
    leitor = csv.reader(arquivo)
    next(leitor)

Na biblioteca padrão de Python os iteradores implementados em C suportam diretamente a função next(). Classes implementadas em Python podem implementar um método chamado __next__ para suportar a função next().
Seja seja como for implementado o iterador, o jeito recomendado para acessar o próximo item é chamar next(meu_iterador).
Comment: Perdão, mas não acho que tenha entendido muito bem o que quis dizer.
Se o meu código não está implementando o next() quer dizer que preciso implementar o __next__ ? Mas onde seria implementado isto?

Desculpa, estou descobrindo o mundo da programação e tem muitas coisas que ainda me deixam um pouco confuso.
Answer: import csv

def carregar_acessos():
    X = []
    Y = []

    arquivo = open('acesso.csv', 'rb')
    leitor = csv.reader(arquivo)

    next(leitor)

    for home,como_funciona,contato, comprou in leitor:

        dado = [int(home),int(como_funciona)
            ,int(contato)]
        X.append(dado)
        Y.append(int(comprou))

    return X, Y

Comment: Bem, eu tentei desta forma e ele continuou não aceitando. Dizendo que havia algo de errado com o Iterador.
Comment: http://carlosmaniero.blogspot.com.br/ cara da uma olhada neste blog, pode ser que ajude
Answer: Eu uso a versão 3.61 aqui, coloquei o código desta forma e funcionou 100% , o que deve ser observado é atenção para detalhes, pois vc colocou a leitura de um arquivo csv(txt) como "rb" read binary ? apenas coloquei "r" e pronto tudo certo!
import csv
def carregar_acessos():
    X = []
    Y = []
arquivo = open('csvpy.txt', 'r')
leitor = csv.reader(arquivo)

next(leitor)

for home,como_funciona,contato, comprou in leitor:

    dado = [int(home),int(como_funciona)
        ,int(contato)]
    X.append(dado)
    Y.append(int(comprou))
    print(X)
    print(Y)

return X, Y

carregar_acessos()

Next() em CSV Reader com Python 3


SearchView sem retorno algum no Android

Question: Implementei uma SearchView e coloquei um Toast para ver se estava funcionando assim que eu digitasse algo na busca. Porém o Toast não é exibido, não aparece nenhum erro no Logcat. A busca está em uma ActionBar. Quando clico no ícone de busca, ela expande para poder digitar porém assim que e aperto "enter" / "confirmar" o Toast não aparece.
Essa é a parte onde eu estou chamando a Search
public void pesquisar(MenuItem item){

        searchView = (SearchView) item.getActionView();

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                Toast.makeText(MainActivity.this, "ola", Toast.LENGTH_SHORT).show();
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                            return false;
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.menu_main, menu);

        return true;

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()){
            case R.id.sair:
                this.finish();

            case R.id.sobre:
                return true;

            case R.id.cadastrar:
                Intent telaCadastro = new Intent(MainActivity.this, CadastroMaterias.class);
                startActivity(telaCadastro);

            case R.id.pesquisar:
                pesquisar(item);

            default:
                return super.onOptionsItemSelected(item);

        }
    }

XML
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    >

    <item android:id="@+id/sobre"
        android:title="Sobre"
        android:orderInCategory="100"
        app:showAsAction="never"/>

    <item android:id="@+id/sair"
        android:title="Sair"
        android:orderInCategory="150"
        app:showAsAction="never"/>

    <item android:id="@+id/cadastrar"
        android:title="Adicionar Materia"
        android:orderInCategory="100"
        android:icon="@drawable/ic_action_add"
        app:showAsAction="ifRoom"/>

    <item android:id="@+id/pesquisar"
        android:title="Pesquisar"
        android:orderInCategory="150"
        android:icon="@drawable/ic_search"
        app:showAsAction="always"
        app:actionViewClass="android.widget.SearchView"/>

    <item android:id="@+id/excluir"
        android:title="Excluir todos os registros"
        android:orderInCategory="200"
        android:icon="@drawable/ic_delete"
        app:showAsAction="ifRoom"/>

</menu>

Comment: Consegui aqui, no XML, no item do campo busca troquei para
`app:actionViewClass="android.support.v7.widget.SearchView"/>`
 e coloquei também um
`return true`
no metódo
`public boolean onOptionsItemSelected(MenuItem item)`
da classe onde está o ícone da busca.
Comment: Voce esta chamando o setOnQueryTextListener dentro da funcao pesquisar, mas voce lembrou de chamar essa funcao pesquisar() no seu metodo onCreate para que o listener seja de fato setado na searchView? Ou em algum outro momento esta chamando o pesquisar()? Tenta botar o listener direto na onCreate e ve o que acontecesse, nao tem todo seu codigo ai mas pode ser isso ;)
Answer: Chame o pesquisar ou mude a implementação do mesmo para dentro do onCreateOptionsMenu e deixe o retorno do onQueryTextSubmit para true.
Comment: Consegui aqui, no XML, no item do campo busca troquei para
 `app:actionViewClass="android.support.v7.widget.SearchView"/>`
 e coloquei também um `return true` no metódo
`public boolean onOptionsItemSelected(MenuItem item)` da classe onde está o ícone da busca.

SearchView sem retorno algum no Android