Deny access to non-existing sub-paths that bubble up to an existing node

Question: I have a drupal site with a page 'About us' (url: example.com/about-us). So when you type the url it correctly opens up the 'About Us' page. But if you append that url with any garbage value or a sensible word (eg:  example.com/about-us/adfasd OR /home) it still opens up the 'About us' page.
Is there a way to restrict this?
That means the user should get an error (something like 'Page not found') if he enters a url for a page which is not valid or if there is not content for that url on the website.
Any kind of help or guidance is greatly appreciated.
Answer: check admin/config/system/site-information and configure, in my site it's empty and all wrong urls get a drupal msg that the page couldn't be found.
Comment: That page contains quite some textfields. What specifically is empty and what do you recommend setting it to?
Comment: Hey Belba, thanks for your response.But the solution you mentioned does not handle the situation.


Fazer botão 'submit' esperar ação de um alert?

Question: Tenho um formulário HTML com um botão submit. Valido os campos no click do botão,caso estes estejam inválidos, é exibido um alerta, mas este desaparece rapidamente e o formulário já redireciona pra página do action. Só funciona quando mudo o tipo do botão para button.
Alguém sabe como resolver isso?
Comment: Poste o código do seu form pra gente analisar.
Answer: Sem ver seu código fica um pouco complicado de responder com certeza, mas acredito que seja porque o comportamento padrão do submit está sendo disparado.
Você pode usar Event.preventDefault para prevenir a ação default. Após fazer a validação, se estiver tudo correto você pode usar HTMLFormElement.submit() para enviar o formulário.
var input = document.querySelector('input'),
    form = document.querySelector('form');

form.addEventListener('submit', validateAndSubmit, false);

function validateAndSubmit(event) {
  // Prevenindo o comportamento padrão.
  event.preventDefault();

  // Pegando o valor do input.
  var value = input.value;

  // Fazendo a validação e enviando caso esteja OK.
  if (value.length < 5)
    alert('O formulário não será enviado, a palavra não possui 5 caracteres.');

  else {
    alert('O formulário será enviado.');
    form.submit();
  }
}

Não é possível simular o envio do formulário nos snippets do StackOverflow, então coloquei o script nesse fiddle.
Comment: Muito obrigada! Exatamente o que eu queria.
Answer: O ideal é chamar a função de validação no onSubmit do formulário, e caso der algo errado na validação, retornar false, assim o formulário não é enviado.

function valida() {

  if( ! document.getElementById('nome').value ) {

    alert('Preencha o campo "Nome"');
    return false;

  } else {

    return true;

  }

}
<form action="" method="get" onsubmit="return valida();">
  <input id="nome" type="text"/>

  <input type="submit" value="Enviar">
</form>


solr reverse proxy Apache2

Question: I am trying to setup Apache2 as Reverse Proxy for solr. Apache and Solr are on the same machine. Apache is serving other stuff as regular web server, too.
solsearch config file in /etc/apache2/config.d/

# Proxy specific settings
ProxyRequests Off
ProxyPreserveHost Off

<Proxy *>
    AddDefaultCharset off
    Order deny,allow
    Allow from all
</Proxy>

ProxyPass /solrsearch http://localhost:8983/solr/collection1/browse
ProxyPassReverse /solrsearch http://localhost:8983/solr/collection1/browse

Now trying http://localhost/solsearch gives me the first page of http://localhost:8983/solr/collection1/browse, but with broken layout (like css missing).
Result: error.log of apache:
File does not exist: /var/www/solr, referer: [http://192.168.1.150/solrsearch]

Comment: What location are the css files etc trying to load from?
Comment: First make sure you understand the basics: http://www.michael--martinez.com/computers/reverseproxy.html
Comment: @Shane Madden: It should get all files from [localhost:8983/slor], but then it suddenly looks for them in the normal www folder...
Answer: The links from the HTML content page for the CSS and other files are probably absolute paths - so they're linked to /solr/path/to/css instead of path/to/css.
You should be able to solve this by adding another ProxyPass:
ProxyPass /solrsearch http://localhost:8983/solr/collection1/browse
ProxyPassReverse /solrsearch http://localhost:8983/solr/collection1/browse
ProxyPass /solr http://localhost:8983/solr

But, you should be careful that that's not exposing more content than you want exposed if this is a publicly available server.
Answer: just to tag on here. The following proxy configuration permits the default Solr browser to operate (with CSS, javascript, etc) without giving access to the admin functions:
<IfModule mod_proxy.c>
    # Proxy specific settings
    ProxyRequests Off

    <Proxy *>
        AddDefaultCharset off
        Order deny,allow
        Allow from all
    </Proxy>

    # permit:
    #  * queries
    #  * javascript
    #  * css
    #  * term vectors
    # restrict:
    #  * all other traffic (admin, etc)

    ProxyPassMatch "/solr/(.*/browse)" http://localhost:8983/solr/$1
    ProxyPassMatch "/solr/(.*/terms)" http://localhost:8983/solr/$1
    ProxyPassMatch "/solr/(.*/admin/file)" http://localhost:8983/solr/$1
    ProxyPass /solr/js http://localhost:8983/solr/js
    ProxyPassReverse /solr http://localhost:8983/solr
</IfModule>

This is working on my Solr 6.1.0 system.

solr reverse proxy Apache2


Webform mail sender

Question: I'm new to Drupal and i'm working on a website that wasn't made by myself.
How can I change the mail sender from  a form made with the webform module?
Answer: Go back to the WEBFORM tab and look for the E-mails sub-tab. Fill in an address and click Add.
Answer: You can edit by it's edit page, it will be /node/XX/webform/emails where XX is your node number

Webform mail sender


Is it possible to schedule an svn update?

Question: I use eclipse galileo with subversive plugin or Tortoise SVN to do an update.
It is possible to schedule an auto-update (eg. every night)?
If yes, is it possible to configure it to just update the non-conflicting files?
Comment: Primo, this is a superuser.com question, Secundo, it's a question about the OS, not Subversion/Eclipse.
Answer: I use this command via a scheduled task - this assumes you have Silksvn installed (but any svn client will do this)
<code>"C:\Program Files\SlikSvn\bin\svn" update --accept postpone d:\SourceCode >> c:\svn.log
</code>
It will only update files that aren't conflicting also, so no worry about that.
OR even, do it from TortoiseSVN using this command
<code>C:\Program Files\TortoiseSVN\bin\TortoiseProc.exe /command:update /path:d:\sourcecode /closeonend:1
</code>
closeonend can be one of these
<code>/closeonend:0 don't close the dialog automatically

/closeonend:1 auto close if no errors

/closeonend:2 auto close if no errors and conflicts

/closeonend:3 auto close if no errors, conflicts and merges

/closeonend:4 auto close if no errors, conflicts and merges for local operations
</code>
Comment: Anyone have it where the /closeonend param doesn't actually close the dialog? We set it to :1, but there are connection errors about once a day that cause errors, so it ends up hanging all the svn updates to our QA server.
Comment: `/closeonend:0` keeps the dialog open, as the answer says.
Answer: Just schedule a task to run a batch file every night. The batch file just calls an svn update using a Subversion command line client. Simple enough, right?
Answer: I had the same problem with the popup lingering when the connection dropped, so I just installed a command line version of svn and checked the returned ERRORLEVEL using a Windows batch script
Answer: Microsoft Task Scheduler or CRONw


Página não carrega componentes Primefaces

Question: Minha página não está carregando os componentes do Primefaces, no caso um dataTable. O resultado final está assim, tanto no chrome, quanto no próprio navegador do Eclipse:

Segue o meu código:
listaMarcas.xhtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<h:body>
<h:form>

        <h:commandLink value="Deletar" action="#{marcaBean.deletarMarca}">
        <f:setPropertyActionListener target="#{marcaBean.marca}" value="#{m}"></f:setPropertyActionListener>
        </h:commandLink>

</h:form>
</h:body>

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>br.com</groupId>
  <artifactId>tesi2015</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>tesi2015 Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.33</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.3.6.Final</version>
    </dependency>
    <dependency>
        <groupId>com.sun.faces</groupId>
        <artifactId>jsf-api</artifactId>
        <version>2.2.8-02</version>
    </dependency>
    <dependency>
        <groupId>com.sun.faces</groupId>
        <artifactId>jsf-impl</artifactId>
        <version>2.2.8-02</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
    </dependency>
    <dependency>
        <groupId>c3p0</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.1.2</version>
    </dependency>
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.2</version>
    </dependency>

        <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>

        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>5.1</version>
        </dependency>
  </dependencies>
  <build>
    <finalName>tesi2015</finalName>
  </build>
</project>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
  <display-name>tesi2015</display-name>
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.jsf</url-pattern>
  </servlet-mapping>
</web-app>

Não sei se estou errando algo, já tentei de tudo e não consigo carregar a tabela. Como faço pra essa tabela aparecer? O que estou errando? Valeu.
Comment: Ah, acho que lembrei :-) Você precisa de uma tag `head` porque é onde o primefaces adicionará código para referenciar suas bibliotecas. Experimente, antes de abrir a tag ``, adicionar ` Título da página `.
Comment: Acho pertinente você editar sua pergunta e adicionar o conteúdo do seu arquivo `web.xml`.
Comment: Editado @electus
Comment: Tentei adicionar o layout e não funcionou @Caffé
Comment: O que aparentemente ocorre é que tua aplicação está barrando os arquivos CSS que vem junto com o primefaces. Verifique se não implementou um filter, autenticação, algo do tipo...
Answer: Na verdade os componentes Primefaces foram criados, ou você teria outros sintomas. O que ocorreu foi que os estilos não foram aplicados.
O Primefaces adiciona referências às suas bibliotecas de estilos (css) na tag head.
Se ele não encontra esta tag, acaba não adicionando as referências e sua página fica assim, sem estilo nenhum.
Para resolver o problema, simplesmente adicione a tag head. Seu código ficará mais ou menos assim:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <h:head>
        <title>Título da página (seção head necessária ao Primefaces)</title>
    </h:head>
    <h:body>
        <h:form>
            ...
        </h:form>
    </h:body>


Failed to update and now causes module errors

Question: I recently attempted to update a Drupal 8 site from 8.7.7 to 8.9.3 and had a failure due to server not being on the right version of php7 to run the new 8.9 version.
As a result I am now getting issues within /admin/people view with the following errors
The website encountered an unexpected error. Please try again later.

Drupal\Component\Plugin\Exception\PluginNotFoundException: The "webform_submission_delete_action" plugin does not exist. Valid plugin IDs for Drupal\Core\Action\ActionManager are: comment_delete_action, comment_unpublish_by_keyword_action, comment_publish_action, comment_save_action, comment_unpublish_action, node_promote_action, node_delete_action, node_make_unsticky_action, node_assign_owner_action, node_unpromote_action, node_make_sticky_action, node_save_action, node_publish_action, node_unpublish_action, node_unpublish_by_keyword_action, user_remove_role_action, user_unblock_user_action, user_cancel_user_action, user_block_user_action, user_add_role_action, pathauto_update_alias, entity:delete_action:comment, entity:delete_action:media, entity:delete_action:node, entity:publish_action:block_content, entity:publish_action:comment, entity:publish_action:media, entity:publish_action:node, entity:publish_action:taxonomy_term, entity:publish_action:menu_link_content, entity:publish_action:paragraph, action_message_action, entity:unpublish_action:block_content, entity:unpublish_action:comment, entity:unpublish_action:media, entity:unpublish_action:node, entity:unpublish_action:taxonomy_term, entity:unpublish_action:menu_link_content, entity:unpublish_action:paragraph, action_send_email_action, entity:save_action:block_content, entity:save_action:comment, entity:save_action:file, entity:save_action:media, entity:save_action:node, entity:save_action:taxonomy_term, entity:save_action:user, entity:save_action:font, entity:save_action:menu_link_content, action_goto_action in Drupal\Core\Plugin\DefaultPluginManager->doGetDefinition() (line 53 of core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php).

The webform version went from 8.5.4 to 8.5.19
Within my modules admin, currently webform is showing as uninstalled. When I try to re-enable with drush I get a similar error.
php ../drush.phar pm-enable webform

In PreExistingConfigException.php line 65:

  Configuration objects (system.action.webform_submission_delete_action, system.action.webform_submission_make_lock_action, system.action.webform_submission_make
  _sticky_action, system.action.webform_submission_make_unlock_action, system.action.webform_submission_make_unsticky_action, webform.settings, webform.webform.c
  ontact, webform.webform_options.country_codes, webform.webform_options.country_names, webform.webform_options.days, webform.webform_options.education, webform.
  webform_options.employment_status, webform.webform_options.ethnicity, webform.webform_options.gender, webform.webform_options.industry, webform.webform_options
  .languages, webform.webform_options.likert_agreement, webform.webform_options.likert_comparison, webform.webform_options.likert_importance, webform.webform_opt
  ions.likert_quality, webform.webform_options.likert_satisfaction, webform.webform_options.likert_ten_scale, webform.webform_options.likert_would_you, webform.w
  ebform_options.marital_status, webform.webform_options.months, webform.webform_options.phone_types, webform.webform_options.relationship, webform.webform_optio
  ns.size, webform.webform_options.state_codes, webform.webform_options.state_names, webform.webform_options.state_province_codes, webform.webform_options.state_
  province_names, webform.webform_options.time_zones, webform.webform_options.titles, webform.webform_options.yes_no) provided by webform already exist in active
   configuration

Has anyone encountered similar and can point me to how to get webform enabled again and to get rid of the errors?
Comment: It seems like the webform module was not fully uninstalled and there is leftover configuration in the database.
Comment: there was an issue with the version of the module not supporting the current the upgraded version of Drupal. I rolled back the version of Drupal, updated webform and then reapplied the drupal update.
Answer: What seems to the problem
It seems during the failed update Webform was marked as uninstalled but its configuration objects are still present. This is preventing Webform to be enabled again because you can't install an extension that uses configuration objects already in the system.
How to solve it
You can remove all the configuration objects and try to install/enable the module. To remove them, you can use the cdel drush command.
Given the configuration object list, the commands to run would be:
drush cdel system.action.webform_submission_delete_action
drush cdel system.action.webform_submission_make_lock_action
drush cdel system.action.webform_submission_make_sticky_action
drush cdel system.action.webform_submission_make_unlock_action
drush cdel system.action.webform_submission_make_unsticky_action
drush cdel webform.settings
drush cdel webform.webform.contact
drush cdel webform.webform_options.country_codes
drush cdel webform.webform_options.country_names
drush cdel webform.webform_options.days
drush cdel webform.webform_options.education
drush cdel webform.webform_options.employment_status
drush cdel webform.webform_options.ethnicity
drush cdel webform.webform_options.gender
drush cdel webform.webform_options.industry
drush cdel webform.webform_options.languages
drush cdel webform.webform_options.likert_agreement
drush cdel webform.webform_options.likert_comparison
drush cdel webform.webform_options.likert_importance
drush cdel webform.webform_options.likert_quality
drush cdel webform.webform_options.likert_satisfaction
drush cdel webform.webform_options.likert_ten_scale
drush cdel webform.webform_options.likert_would_you
drush cdel webform.webform_options.marital_status
drush cdel webform.webform_options.months
drush cdel webform.webform_options.phone_types
drush cdel webform.webform_options.relationship
drush cdel webform.webform_options.size
drush cdel webform.webform_options.state_codes
drush cdel webform.webform_options.state_names
drush cdel webform.webform_options.state_province_codes
drush cdel webform.webform_options.state_province_names
drush cdel webform.webform_options.time_zones
drush cdel webform.webform_options.titles
drush cdel webform.webform_options.yes_no

Consecuences
Removing configuration objects mean you likely are going to lose any Webform configuration you made. This can be not a problem if you can easily redo the configuration or your configuration was not finished or needed changes. I'm not sure if this includes losing all the created webforms.
However, if you dumped the configuration to files (using Drupal configuration system) you may able to recover the configuration using those files.


Run SKAction that runs a void statement SpriteKit

Question: I'm trying to run a particle node or just a node when an action is called but Im unsure of which action to use or if I'm even doing it right.
I've searched apple's docs with no luck.
This is what I've attempted:
<code>    -(void)setupbabyFireNode{
    NSString *babyFirePath = [[NSBundle mainBundle]pathForResource:@"BabyOnFireParticle" ofType:@"sks"];

    babyFireNode = [NSKeyedUnarchiver unarchiveObjectWithFile:babyFirePath];

    babyFireNode.position = CGPointMake(-30, 40);
    babyFireNode.zPosition = 1;

    [babyNode addChild:babyFireNode];
    }

    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    [babyNode removeActionForKey:@"left"];

     babyNode.position = CGPointMake(700, 280);

     moveLeft = [SKAction moveTo:CGPointMake(100, 280)duration:5.0];

    SKAction *completion = [SKAction runBlock:^{

    SKScene *endScene = [[EndScene alloc]initWithSize:self.size];
    SKTransition *doors = [SKTransition crossFadeWithDuration:5];
    [self.view presentScene:endScene transition:doors];

    }];
    SKAction *fire = [self setupbabyFireNode];

    SKAction *sequence = [SKAction sequence:@[ moveLeft ,fire, completion ]];

    SKAction *sequence = [SKAction sequence:@[ moveLeft ,completion ]];

    [babyNode runAction:sequence withKey:@"left"];

    }
</code>
Comment: Your question is unclear. Please elaborate what you are trying to do, along with what you have tried.
Comment: I would like to add a node, to the scene, within an action sequence. (node appears after it moves left)  I've created the node and it all works fine. I can add the node to the scene using [self setupNode]; .  "What I've tried is" (  SKAction *action = [self setUpFireNode];  )  "LOL", and called it in a sequence with an SKAction *sequence = [SKAction sequence:@[ moveLeft ,[self setUpFireNode... etc..], completion ]];

[Node runAction:sequence];
Answer: I guess, this is what you are trying to do;
<code>SKAction *sequence = [SKAction sequence:@[moveLeft ,[SKAction performSelector:@selector(spawnPipes) onTarget:self]]];

[Node runAction:sequence];
</code>
Comment: You gonna change the selector which takes function name as a parameter, so you need something like; [self runAction:[SKAction performSelector:@selector(setUpBabyFireNode) onTarget:self]];
Comment: Thank you!!  I'll edit my code shortly.  Sorry for deleting old comment.  Realized this is the correct answer.


Feedback problems

Question: bit of an awkward one. I have a American special strat and black star ht5r. Basically the spring that adjusts the pickup height (humbucker in the bridge) fell out so I had a huge ordeal fixing that because it magnetised to the humbucker inside etc... But now when I play I get a terrible high pitch feedback sound. Turning the volume down doesn't make a difference and I don't have a noise gate, this never happened before... Please help :)
Comment: Is it feedback? There are two possibilities - you are getting acoustic feedback through however you fixed the pickup mount, or you broke something.
Comment: Please add some more info – pictures, some recording of the sound, test configuration...
Answer: OK, you need to take the pick guard off and get that spring out.  You need to get it off the humbucker's magnets and back onto the screw-height post that it's supposed to be on.  The spring is probably causing a short in the wiring between the coils of the humbucker and that's why you are getting the high-pitched sound.

Feedback problems


Is this an equivalent definition of cluster point?

Question: My textbook Analysis I by Amann/Escher defines the notions of neighborhood and cluster point as follows:

Then the authors present equivalent definitions of cluster point:

I would like to ask if the below definition of cluster point is equivalent to the one given in my textbook?

$a \in X$ is a cluster point of $(x_{n})$ if, for each $U \in \mathcal{U}(a)$, there is some $m \in \mathbb N$ such that $x_m \in U$ and $x_m \neq a$.

Thank you so much for your help!
Answer: No, take $x_n=a$ for all $n\in \mathbb{N}$. Then, any neighbourhood of $a$ contains every element of the sequence, and so, in particular, infinitely many terms. As such, $a$ is a cluster point of $(x_n)_{n\in \mathbb{N}}$.
In general, we want it to be true that if $(x_n)_{n\in \mathbb{N}}$ is convergent, then it has a unique cluster point: The limit.


How to line up elements after they have been rotated

Question: I've got an issue lining up divs that have been rotated.
For example, if .straight has been rotated 30deg, I want to get the new offset coordinates of the bottom right corner, so that I can set the bottom left corner of .curve to match up with this coordinate exactly.
In order to get the offset coordinates of the bottom right corner of .straight, I'm using the following:
var straight_width = $(".straight").width();
var br_corner_x = straight_width*Math.cos(30*Math.PI/180); //60.62
var br_corner_y = straight_width*Math.sin(30*Math.PI/180); //35

This is all good, but the problem is that if I set the left and top of .curve to these values, as follows:
$(".curve").css({"left": br_corner_x, "top": br_corner_y})

the browser rounds the pixels and positions the left at 61px and leaves a tiny gap between the divs. For what I'm doing, this tiny discrepancy is significant.
Here is a fiddle that shows the issue: https://jsfiddle.net/39q5m71u/2/
Now, I know I can line up both divs in a wrapper and rotate the wrapper, and I know I can line up both divs and then rotate .curve about the the same transform-origin coordinate as .straight, but for reasons involving scaling the project to handle lining up multiple rotated divs with different angle values, these solutions won't work.
I'm wondering if anyone can think of an alternate approach that can line the divs up only after they have been rotated? Thanks!
Answer: What's happening is that the browser is performing pixel rounding on the left property:

If you manually change the value of left to, say, 60.49, that little gap is removed.
I was able to remove the gap by rounding br_corner_x down to the nearest whole number:
var br_corner_x = Math.floor(straight_width*Math.cos(30*Math.PI/180));

To deal with some of the jaggedness going on, I adding a .container div around the two existing divs and added:
.container {
  backface-visibility: hidden;
}

https://jsfiddle.net/ytzw2bzf/2/
Comment: Thanks for your answer. While this eliminates the gap, it does not line the `div`s up perfectly, as now `.curve` is slightly too far left, as you can see in the screenshot. I realize there may be no better way, but I'm just wondering if there is.
Comment: I modified my answer a bit. With `backface-visibility: hidden;` it's better than before, though I'm not sure how much closer I can get.


"chmod / 775 -R" and now our mysql database is down...!

Question:
Possible Duplicate:
How to repair/restore ubuntu 10.04 after 'sudo chmod / 777'

It looks like there are some related issues to my problem.. One of our team members accidentally ran "chmod / 775 -R" and now we've got some issues with our database..
I'm getting stuff that looks like this : Incorrect information in file: '*.frm'
Any help to get us back on our feet would be awesome
Comment: Hopefully you have a good backup?!  Seriously, because the chmod doesn't differentiate between files and directories so the fact the Mysql isn't running is only the tip of the iceberg.  If anything you need something that can restore the original permissions of your entire filesystem.
Answer: I would recommend rebuilding the server but you probably have a problem with your /tmp, try chmodding it to 777.
But you will come across various other issues. Take your backups or what you need and rebuild the system from scratch.
Also, take a look at this: How to repair/restore ubuntu 10.04 after sudo chmod / 777


creating virtual bridge breaks host network

Question: Tried to set up virtual bridge on a Ubuntu machine, and host network broke
<code>#ip link add name br0 type bridge
#ip link set dev eth0 master br0
#ip link set dev br0 up

#ping <gateway_addr> // failed
#ip neigh
<gateway_addr> dev eth0 FAILED

#echo 1 >/proc/sys/net/conf/ipv4/br0/arp_accept
#ping <gateway_addr> // failed
#ip neigh
<gateway_addr> dev eth0 FAILED
<gateway_addr> dev br0 lladdr <mac_addr> REACHABLE
</code>
Ping to gateway doesn't succeed, however it does when I delete the bridge and remove it as a master of eth0. What am I missing. Please advise!
Comment: when you attach a bridge to an interface, do you also make sure the interface has no IP configured and the bridge has the server's IP instead?
Comment: No. And, I understand what you mean, if I do so, it would work. But, bridge is not supposed to have an IP address? Does it? here is where my concept is questioning me. Please advise!
Comment: When you set up a bridge, it is the bridge device that should have an IP address, not the individual interfaces that are part of the bridge.
Comment: That is what I am saying, it a bridge/switch and not a router, theoretically it doesn't have to have an IP assigned to it? Am I missing something.
Comment: Okay, even if I assume virtual bridge is assigned an IP, why do I have to flush the IP of host ethernet interface, isn't it connected to the bridge? Either my concept is wrong or something else is wrong.
Comment: As per my understanding bridge's job is to store and forward packets destined to adjoining LAN, if not reject if destined to source LAN.  Am I missing something? Please advise!
Comment: You understand correctly what the bridge does. But it also becomes the de-facto interface for the host, because the NIC becomes a slave which doesn't do the actual communication any longer, attached to a bridge it is simply another port. If it helps you understand - in a switch you don't assign IPs to ports, but you definitely assign an IP to the switch, if you want to configure and monitor it.
Answer: OK, taking it down here as an answer.
Your bridge is the interface that should have the IP configuration, the NIC (or bond, if you have one) becomes a dummy used by the bridge as a physical port to forward the packets out through, and should not hold an IP.
Comment: So, as the bridge has to send the packets from guest machines out, and if the eth0 is on same LAN it would be not the bridge way to send out via eth0. So, it will keep eth0 as dummy to forward the packets out. Correct me! I still have a follow up question. Are you aware of VMnet0? it is configured by VMware networking. It is a bridge that lets the guest machines NICs connect to host LAN, still it doesn't touch host IP address. Do you know how does that work? https://pubs.vmware.com/workstation-9/index.jsp?topic=%2Fcom.vmware.ws.using.doc%2FGUID-4D35D1FC-5926-45A8-96B1-42C922DA97E9.html
Comment: VMnet0 is the virtual adapter / bridge created by the VMWare hypervisor. If it is configured as a host-only network, then only guest VMs can talk to each other via that, and it is completely separate from other host network adapters.
Comment: And, if it configured to use host LAN?


How to prove every shell is non-overlapping in volume of revolution by "shells"? Does the Riemann sum imply the volume is over-counted?

Question: Why is the shell method not
$$\lim_{n \rightarrow \infty} \sum_{k=1}^n 2\pi\left(\frac{(b-a)}{n}\right)\cdot f\left((k-1)\cdot\frac{(b-a)}{n}\right)\cdot \frac{1}{n} + \pi f\left((k-1)\cdot\frac{(b-a)}{n}\right) \cdot \left(\frac{1}{n}\right)^2.$$?
This means the shells are concentric circles going outward, the subsequent shells after the first are hollow in the center, and the hole increases further towards the end points in increasing order.
I have trouble with the implication that in the "shell method" to calculate volumes of revolution, the left end point of the first piece is $0$, the left end point of the second piece is $\dfrac{(b-a)}{n}$, the left end point of the third piece is $2\dfrac{b-a}{n}.$
Why do you use the left end point of the pieces in the integral rather than
$\int$ (constant "radius" of cylinder) $\cdot 2\pi\cdot$ height of shell $\cdot dx$?
If you're shells radius is not a constant, and the shell radius are in the increasing sequence $a_k=(k-1)\dfrac{b-a}{n}$, then you're are using overlapping shells, you're not partitioning the volume into a bunch of non-overlapping shells centered on the axis, and you're double-counting volume multiple times.

It looks like you're dealing with the case of a cylinder (i.e. the height is always $y$). In general, the height of a shell is a function of $x$, say $f(x)$, so the volume of a shell is
$$\Delta V=2\pi xf(x)\Delta x + \pi f(x) (\Delta x)^2.$$
Now say the range of $x$ values is $[a,b]$. If we partition this into $n$ pieces, the left endpoint of the $k$th piece is $(k-1)\cdot \frac{(b-a)}{n}$. This is the inner radius of the $k$th shell. Now the total volume of the $k$ shells is
$$\sum_{k=1}^n 2\pi\left((k-1)\cdot\frac{(b-a)}{n}\right)\cdot f\left((k-1)\cdot\frac{(b-a)}{n}\right)\cdot \frac{1}{n} + \pi f\left((k-1)\cdot\frac{(b-a)}{n}\right) \cdot \left(\frac{1}{n}\right)^2.$$

If we partition this into $n$ pieces, the left endpoint of the $k$th piece is $(k-1)\cdot \frac{(b-a)}{n}$.

To find the element of volume contained in a shell of inner radius $r = x$ and out radius $R = x + \Delta x$, length $y$, we have:

$$\begin{align*}\Delta V &= \pi(R^2-r^2)y\\ &=\pi y(x^2+2x\Delta x + \Delta x^2 - x^2)\\&=2\pi xy\Delta x + \pi y\Delta x^2\end{align*}$$
As $\Delta x$ is very small, $(\Delta x)^2$ is negligible, hence $$\Delta V = 2\pi xy\Delta x\\\therefore V = 2\pi \int_a^bxy\,dx $$

Derivation of Shell Method
Answer: For the time being, ignore the solid of revolution and go back to the basic Riemann sum of $f(x)$ over the interval $[a,b]$ using an equally spaced partition.
We divide the interval $[a,b]$ into $n$ equal subintervals.  Since the width of the interval is $b-a$, the width of each subinterval is $\frac{b-a}{n}$.  On this matter, surely there can be no disagreement.
The first (leftmost) subinterval has its left endpoint at $a$.  So to determine the right endpoint of the first subinterval, you must add to $a$ the width of the subinterval; i.e., the right endpoint must be
$$a + \frac{b-a}{n}.$$
This is also the left endpoint of the second subinterval.  So the right endpoint of the second subinterval is
$$a + \frac{b-a}{n} + \frac{b-a}{n} = a + 2 \frac{b-a}{n},$$
and so on, creating an arithmetic sequence of endpoints
$$a,\; a + \frac{b-a}{n},\; a + 2 \frac{b-a}{n},\; a + 3 \frac{b-a}{n}, \;\ldots,\; a + k \frac{b-a}{n},\; \ldots,\; a + n \frac{b-a}{n}$$
whose initial term is $a$, with common difference $\frac{b-a}{n}$, and last term is $a + n \frac{b-a}{n} = a + b-a = b$.
Then the (right subinterval endpoint) Riemann sum for this partition is the value of the function evaluated at each of the right endpoints, multiplied by the width of each subinterval:
$$\sum_{k=1}^n f\left(a + k \frac{b-a}{n}\right) \cdot \frac{b-a}{n},$$
and if we take the left subinterval endpoints, it looks like this:
$$\sum_{k=0}^{n-1} f\left(a + k \frac{b-a}{n}\right) \cdot \frac{b-a}{n},$$
or with a shift of the index variable $k$, like this:
$$\sum_{k=1}^n f\left(a + (k-1) \frac{b-a}{n}\right) \cdot \frac{b-a}{n}.$$
But in none of these cases does it look like anything you wrote, because you have
$$f\left((k-1)\frac{b-a}{n}\right).$$
When $k = 1$, my expression correctly gives either $f(a)$ (left endpoint) or $f(a + \frac{b-a}{n})$ (right endpoint), but your expression gives
$$f(0).$$
This immediately disqualifies your result.
The correct way to conceptualize the cylindrical shell is to start from a correct understanding of the Riemann sum's partition structure, then take a representative subinterval and compute its volume as it is swept.  If we assume that the axis of rotation is the $y$-axis and that $0 < a < b$, then a representative subinterval would have the form
$$x \in \left[a + (k-1) \frac{b-a}{n}, a + k \frac{b-a}{n}\right].$$
In fact, this is the $k^{\rm th}$ subinterval for $k \in \{1, 2, \ldots, n\}$.  If we take the left endpoint for the height of the cylindrical shell, this gives us $h = f\left(a + (k-1) \frac{b-a}{n}\right)$.  The outer radius of the shell is the right endpoint $r_1 = a + k \frac{b-a}{n}$, and the inner radius is the left endpoint $r_2 = a + (k-1) \frac{b-a}{n}$.  So its volume is exactly
$$\begin{align}
\pi (r_1^2 - r_2^2) h
&= \pi (r_1 + r_2)(r_1 - r_2) h \\
&= \pi \left(2a + (2k-1)\frac{b-a}{n}\right)\left(\frac{b-a}{n}\right) h \\
&= 2\pi f\left(a + (k-1)\frac{b-a}{n}\right) \left(a + (k-\tfrac{1}{2}) \frac{b-a}{n}\right) \frac{b-a}{n}.
\end{align}$$
However, in the limit as $n \to \infty$, it is unnecessary to take this Riemann sum:  it is better to use the differential volume
$$dV = 2 \pi x f(x) \, dx$$
of a representative shell with radius $x$.  We can argue that its exact volume for a width of $\Delta x = \frac{b-a}{n}$ is
$$\begin{align}
\Delta V &= \pi \left((x + \Delta x)^2 - x^2\right) f(x) \\
&= \pi \left(2x \,\Delta x + (\Delta x)^2\right) f(x) \\
&= 2\pi x \, \Delta x f(x) + \pi f(x) (\Delta x)^2.
\end{align}$$
Informally, as $\Delta x \to 0$, $\Delta x \to dx$ and $(\Delta x)^2 \to 0$; that is to say, the second term $\pi f(x) (\Delta x)^2$ vanishes much faster than the first term, and in doing so, we recover the formula for the differential volume as shown above.
Notably, the second term quantifies the error in approximating the exact volume of the cylindrical shell as an "unrolled" rectangular slab with height $f(x)$, width $2\pi x$ equal to the circumference of the shell, and thickness $\Delta x$.
Comment: How do you know $x=(a+(k-\dfrac{1}{2})(\dfrac{b-a}{n}))$?
Comment: when $n\rightarrow \infty$?
Comment: @jkj For a point  $x \in [a,b]$, the subinterval containing $x$ will have an index $k$ satisfying $$a + (k - 1)\frac{b-a}{n} \le x \le a + k \frac{b-a}{n},$$ or equivalently, $$n \frac{x-a}{b-a} \le k \le n \frac{x-a}{b-a} + 1.$$  As $n \to \infty$, then $k \to \infty$ in such a way that $k/n \to (x-a)/(b-a)$.  For example, if $[a,b] = [2,5]$ and $x = 4$, then $k/n \to (4-2)/(5-2) = 2/3$.  That said, your question is immaterial, because your expression for the Riemann sum is wrong.


Approximate the nonlinear function by piece-wise linear segments

Question: I'm thinking if I can use GEKKO for the following problem. Please feel free to share your comments. Thank you in advance.
Given that I'd like to approximate some nonlinear functions by piece-wise linear(PWL) segments. For instance, I'd like to use N PWL segments to approximate the function of Gaussian. Is it possible to leverage GEKKO for the problem? What available examples do you suggest studying?
Thank you
Answer: The link that Junho sent is good if you have discontinuous functions that are linear or nonlinear with switching conditions. If you have data then there is a PWL function in Gekko that you can use without binary or MPCC switching conditions. Below is a simple PWL example in Python. Instead of the data points I included, you can use PWL segments to approximate the Gaussian function.

import matplotlib.pyplot as plt
from gekko import GEKKO
import numpy as np
m = GEKKO(remote=False)
m.options.SOLVER = 1
x = m.FV(value = 4.5)
y = m.Var()
xp = np.array([1, 2, 3, 3.5,   4, 5])
yp = np.array([1, 0, 2, 2.5, 2.8, 3])
m.pwl(x,y,xp,yp)
m.solve()
plt.plot(xp,yp,'rx-',label='PWL function')
plt.plot(x,y,'bo',label='Data')
plt.show()

If there is a data set with many points, sometimes it is desirable to fit just a few points with a PWL segments. This is another example that shows how to fit a PWL approximation. In this case you can't use the PWL object in Gekko.

from scipy import optimize
import matplotlib.pyplot as plt
from gekko import GEKKO
import numpy as np

m = GEKKO()
m.options.SOLVER = 3
m.options.IMODE = 2

xzd = np.linspace(1,5,100)
yzd = np.sin(xzd)

xz = m.Param(value=xzd)
yz = m.CV(value=yzd)
yz.FSTATUS = 1

xp_val = np.array([1, 2, 3, 3.5,   4, 5])
yp_val = np.array([1, 0, 2, 2.5, 2.8, 3])
xp = [m.FV(value=xp_val[i],lb=xp_val[0],ub=xp_val[-1]) for i in range(6)]
yp = [m.FV(value=yp_val[i]) for i in range(6)]
for i in range(6):
    xp[i].STATUS = 0
    yp[i].STATUS = 1
for i in range(5):
    m.Equation(xp[i+1]>=xp[i]+0.05)

x = [m.Var(lb=xp[i],ub=xp[i+1]) for i in range(5)]
x[0].lower = -1e20
x[-1].upper = 1e20

# Variables
slk_u = [m.Var(value=1,lb=0) for i in range(4)]
slk_l = [m.Var(value=1,lb=0) for i in range(4)]

# Intermediates
slope = []
for i in range(5):
    slope.append(m.Intermediate((yp[i+1]-yp[i]) / (xp[i+1]-xp[i])))

y = []
for i in range(5):
    y.append(m.Intermediate((x[i]-xp[i])*slope[i]))

for i in range(4):
    m.Obj(1000*(slk_u[i] + slk_l[i]))

m.Equation(xz == x[0]   + slk_u[0])
for i in range(3):
    m.Equation(xz == x[i+1] + slk_u[i+1] - slk_l[i])
m.Equation(xz == x[4] - slk_l[3])

m.Equation(yz == yp[0] + y[0] + y[1] + y[2] + y[3] + y[4])

m.solve()
#y_val = yz.value
#print(y_val)

import matplotlib.pyplot as plt
plt.plot(xp,yp,'rx-',label='PWL function')
plt.plot(xzd,yzd,'b.',label='Data')
plt.show()

Comment: Thank you for the detailed explanation. I'll give it a try.
Answer: Please check out the link below for examples of PWL using binary decision variables.
Logical conditions in Optimization


In baseball, what is the "inside corner"?

Question: When I listen to baseball games, announcers will mention that pitches are on the inside corner. Presumably, the inside corner of the strike zone.
What I don't understand is that the strike zone, to my knowledge, is a rectangle so wouldn't it have two inside corners (inside being the vertical side closest to the batter)? Or does inside corner mean something else?
Answer: The "home plate" is an unusual construct, that is rectangular in front (two corners), and becomes a triangle in back (one corner). Here, "corner" refers to the two front ones.
"Inside" is in relation to the batter. A right handed batter will stand to the left of the plate, so that his "inside" corner is the (left) corner closer to him, and the "outside" (right) corner is the one further from him. The reverse is true for a left handed batter.
If the pitched ball stayed "totally" inside, it would be between the plate and the batter, and be a "ball." Hitting the "inside corner" means part of the baseball barely "covered" the "inside corner" of the plate for a called strike. The baseball has to go over the plate between the batter's shoulders and knees, for a "called" strike but the rule is any part of the ball over any part of the plate over the appropriate height.


Upload de 2 arquivos através de ashx

Question: Tenho a tela abaixo:

Preciso que o usuário selecione uma música e uma capa, porém não estou achando uma maneira de enviar os dois arquivos de uma só vez e ainda validar se foi selecionado a Música e a Capa.
Até então segui o exemplo abaixo, porém o JS pega apenas o conteúdo do input de Foto (upFoto), entretanto criei o mesmo trecho com nomes diferentes para pegar o input de Música (upMusica), porém o JS não envia arquivo MP3, ocorre erro no click do botão enviar (lbtEnviar).
Alguém teria uma sugestão para este caso?
$(function () {
        $('#lbtEnviar').click(function () {
            var fileUpload = $("#upFoto").get(0);
            var files = fileUpload.files;
            var test = new FormData();
            for (var i = 0; i < files.length; i++) {
                test.append(files[i].name, files[i]);
            }
            $.ajax({
                url: "UploadArquivo.ashx",
                type: "POST",
                contentType: false,
                processData: false,
                data: test,
                // dataType: "json",
                success: function (result) {
                    alert(result);
                },
                error: function (err) {
                    alert(err.statusText);
                }
            });
        });
    })

Trecho em C# que recebe o arquivo:
public void ProcessRequest(HttpContext context)
        {
            try
            {
                if (context.Request.Files.Count > 0)
                {
                    HttpFileCollection files = context.Request.Files;
                    for (int i = 0; i < files.Count; i++)
                    {
                        HttpPostedFile file = files[i];
                        string fname;
                        if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE" || HttpContext.Current.Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
                        {
                            string[] testfiles = file.FileName.Split(new char[] { '\\' });
                            fname = testfiles[testfiles.Length - 1];
                        }
                        else
                        {
                            fname = file.FileName;
                        }

                        string pathToSave = "D:\\Msik_Arquivos" + "\\" + fname;
                        file.SaveAs(pathToSave);
                    }
                }
                context.Response.ContentType = "text/plain";
                context.Response.Write("File Uploaded Successfully!");
            }

Answer: Optei por outra solução sem o uso do JavaScript, estou utilizando um componente FileUpload e configurei o click do botão para enviar o arquivo a pasta que precisava:

<asp:FileUpload ID="fupFoto" runat="server"/>

<asp:LinkButton ID="lbtEnviar" type="submit" runat="server" OnClick="lbtEnviar_Click">Enviar</asp:LinkButton>

No eventro click do botão enviar configurei o trecho abaixo:

if (fupMusica.HasFile)
{
  string extensaoMusica = Path.GetExtension(fupMusica.FileName);
  if (extensaoMusica == ".mp3")
  {
    try
    {
      string nomeMusica = fupMusica.FileName;
      string pathToSave = "D:\\Musicas_Arquivos" + "\\" + nomeMusica;
      fupMusica.SaveAs(pathToSave);
    }
    catch (Exception)
    { // ERRO AO SALVAR }
  }
  else
  { // ESCOLHA UM ARQUIVO MP3 }
}
else
{ // NÃO FOI SELECIONADO NENHUM ARQUIVO }

Por padrão só é possível fazer 4MB de upload, sendo assim tive que alterar no Web.config as propriedades maxAllowedContentLength, executionTimeout, maxRequestLength.

Upload de 2 arquivos através de ashx


Border with title in Android

Question: I would like to create a component in Android. The component should be a border with title similar to the TextInputLayout with the possibility to include any layout inside.

I have found one solution in here, but I would like to know if someone could share a different solution. I think that one is hacky.
The layout includes two linear layouts, the first one is the top border line with the title, and the second is the content with a left-, right- and bottom-border.
What do you think?
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="20dp">
        <LinearLayout
            android:id="@+id/main"
            android:layout_width="match_parent"
            android:layout_height="20dp"
            android:orientation="horizontal"
            android:gravity="center_vertical"
            android:weightSum="2">
            <View
                android:layout_width="fill_parent"
                android:layout_height="2dp"
                android:layout_weight="1"
                android:background="#2ebadc"/>
            <TextView
                android:gravity="bottom"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="20sp"
                android:text="Hello World" />
            <View
                android:layout_width="wrap_content"
                android:layout_height="2dp"
                android:layout_marginRight="5dp"
                android:background="#2ebadc"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_marginTop="10dp"
            android:padding="10dp"
            android:background="@drawable/topless_border">
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="This is a border with title"/>
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:text="The top inset of the border is set to -3 to make it disappear and then it's covered with a line with text in the middle by using LinearLayout with two Views and one TextView"/>
        </LinearLayout>
    </RelativeLayout>

</LinearLayout>

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:top="-3dp">
        <shape>
            <solid android:color="@android:color/transparent" />
            <stroke android:width="2dp" android:color="#2ebadc" />
            <corners android:radius="1dp" />
        </shape>
    </item>
</layer-list>

Thanks in advance.
Answer: I took a look into how it is implemented in the Material Components library. And they use the CutoutDrawable for this. Sadly it can not be used directly as the constructor is package private. But one could just "directly" import this class into the project.
To get the desired effect, I would add two views to a ConstraintLayout, one for the label and one for the content. The solution would also work with any other parent layout to position the views, but with ConstraintLayout it is easy to position the views as required:
    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="200dp"
        android:layout_height="200dp">

        <View
            android:id="@+id/content"
            android:layout_margin="8dp"
            android:layout_height="0dp"
            android:layout_width="0dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <com.google.android.material.textview.MaterialTextView
            android:id="@+id/label"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"
            android:text="Test"
            app:layout_constraintBottom_toTopOf="@+id/content"
            app:layout_constraintLeft_toLeftOf="@+id/content"
            app:layout_constraintTop_toTopOf="@+id/content" />
    </androidx.constraintlayout.widget.ConstraintLayout>

The content view is the one that will get the CutoutDrawable. Besides setting the background, we also need to add some mechanism that updates the position were to "cut out" - depending on the position of the label view. I solved this with a OnLayoutChangeListener:
        // configuration of the shape for the outline
        val shape = ShapeAppearanceModel.Builder()
            .setAllCorners(RoundedCornerTreatment())
            .setAllCornerSizes(16f)
            .build()

        // configuration of the CutOutDrawable - replace with themed values instead of hard coded colors
        val drawable = CutoutDrawable(shape).apply {
            setStroke(4f, Color.BLACK)
            fillColor = ColorStateList.valueOf(Color.WHITE)
        }
        // content is the view with @+id/content
        content.background = drawable
        // label is the view with @+id/label
        label.addOnLayoutChangeListener { _, left, top, right, bottom, _, _, _, _ ->
            // offset the position by the margin of the content view
            val realLeft = left - content.left
            val realTop = top - content.top
            val realRigth = right - content.left
            val realBottom = bottom - content.top
            // update the cutout part of the drawable
            drawable.setCutout(
                realLeft.toFloat(),
                realTop.toFloat(),
                realRigth.toFloat(),
                realBottom.toFloat()
            )
        }

It should be also possible to put this strategy into a custom view that configures a CutoutDrawable as background and registers a listener for the position of another view to update the cut out position.
This is the result:

It is also possible to adjust the spacing between text and line by adjusting the padding of the label TextView
Comment: Can we design this with `android:layout_height="wrap_content"`

Border with title in Android


Sphinx: list of functions in a module

Question: I have some python modules containing mostly functions and a few classes.  Each one is documented using sphinx-autodoc in a separate rst.  What I want to do is to create a table or list of the module's contents at the top of each page, so for example, of mymodule.py is
def first():
    'First function'

def second():
    'Second function'

And mymodule.rst is
Page Contents
-------------

:create_page_contents_list:

Members
-------

.. automodule:: mymodule
    :members:

Then the output should look something like this:
Page Contents
-------------

first
second

Members
-------

first()
    First function

second()
    Second function

The question how to do :create_page_contents_list:.  I've have a look at using a TOC, but it seems that I would need to manually create an entry for each item.  I've also looked at autosummary, but I still need to list the members.  Any suggestions for automating this?  I'd rather avoid third-party extensions.
Answer: You probably want something like the autosummary extension.  The actual autosummary extension will not quite do what you want, though.
An example of how you might extend autosummary to auto-detect the contents of the module is given in this answer
Comment: Can you provide an example of its use in this case?
Comment: How does this extension solve the problem? Using `autosummary` you still have to manually specify every single function/method/attribute in a list. A `:members:` option for modules, like `autodoc` has, is not available. The only solutions I found to automatically do this are based on javascript.
It really annoys me that most Python documentations don't have a concise table overview over all module members (glancing at you _matplotlib_).
Comment: Exactly, autosummary is not solving the problem. There is a related question here with some code-snippet for extending Sphinx: https://stackoverflow.com/questions/20569011/python-sphinx-autosummary-automated-listing-of-member-functions
Comment: Currently that link seems to be broken. Something about a redirect loop.

Sphinx: list of functions in a module


Open form to record seleced from double click on same record in datasheet form

Question: I've got a pair of forms that are both based on the same data table.  One is a single form with a better layout of all the onfo, the other is a datasheet.  I want to be able to double click on the project number in the datasheet form to open the details single form to that same record.
I've done it on a simplified practice db, but when I try it in my current db it opens the second form, but to a new record entry.  This form is one that was a template that someone else downloaded and modified for our purpose, so maybe there is something stored somewhere else that is interrupting the filtering.
I deleted a couple of macros that I thought might be interfering, made sure that the form properties are cycling all records and that on form load it isn't directed to a new record.  I can't figure out where else there is something preventing the form from being filtered for the selected record.  Here's the code I've used in the datasheet form:
<code>Private Sub combined_DblClick(Cancel As Integer)

    DoCmd.OpenForm "frmTaskDetailsExisting", acNormal, , "SLRtaskID = " & Me.SLRtaskID

End Sub
</code>
Anyone have an idea what I'm missing here.
Answer: Have you considered doing this with a split Form? You will have the Detailed view per record and the dataseet.
If you really want two independent forms due to your needs, your code looks ok. But two things may be happening:

The value in Me.SLRtaskID is not correct. Put a breakpoint in the code and check it.
There is code in frmTaskDetailsExisting that moves it to a new record when it is opened, regardless to the filter.
Comment: Yeah I considered the split form, but the details take up too much space which would block out most of the items in the datasheet list view.  I'll dig around more in the settings on the details form, though i've tried to do that and haven't found anything yet.
Comment: I tried creating a new form and copying all the objects into that in case there was something in the form properties messing this up.  When I redirect the on double click to this form it still opens to a blank record.  But if I view the properties it tells me that it is filtered on the record I want.  Is it possible something in the first form is affecting this?


How to solve $\int_0^\infty\frac1{(ti+1)^2(e^{2\pi t}-1)}-\frac1{(-ti+1)^2(e^{2\pi t}-1)}dt$

Question: Happy New Year! Using the Abel-Plana formula on the Basel sum, I found that $$-i\frac{\pi^2-9}6=\int_0^\infty\frac1{(ti+1)^2(e^{2\pi t}-1)}-\frac1{(-ti+1)^2(e^{2\pi t}-1)}dt$$ How do I solve this integral without the knowledge of the Abel Plana summation formula?
Comment: Are you sure about your result ? Could it be $-i \frac{\pi ^2-9}{6} $
Comment: @ClaudeLeibovici +1. I agree with your statement and have derived the same in my answer.
Comment: @ScipioAemilianus Yes that is what I intended. Thanks
Comment: Going from Scipio's first equality, a possible related question can be seen [here](https://math.stackexchange.com/questions/3072149/explicit-calculation-of-int-0-infty-frac-sin2-arctan-x1x2-exp2?noredirect=1). If you want, I can make up an answer that's different than those solutions from the link.
Comment: @Accelerator Yes please :)
Answer: Taking the common denominator of the expression in RHS, we get:
$$I = \int_0^{\infty} \frac{1}{e^{2\pi t}-1} \cdot \frac{-4it}{(1+t^2)^2} dt = -i\cdot \int_0^{\infty} \frac{4tdt}{(1+t^2)^2\cdot (e^{2\pi t} -1)}$$
Now, from Binet's second formula for the digamma function, we have:
$$\psi(z)=\log(z)-\frac{1}{2z}-2\int_0^\infty \frac{x}{(x^2+z^2)(e^{2\pi x}-1)}dx$$
Differentiating the equation once with respect to $z$, we get
$$\psi^1(z) = \frac{1}{z} + \frac{1}{2z^2} + z\cdot \int_0^{\infty} \frac{4x}{(x^2+z^2)^2\cdot (e^{2\pi x} -1)} dx$$
For $z=1$, we get
$$\psi^1(1) = \frac{\pi^2}{6} = \frac{3}{2} + \int_0^{\infty} \frac{4xdx}{(1+x^2)^2\cdot (e^{2\pi x} -1)}$$
Thus we get
$$\int_0^{\infty} \frac{4xdx}{(1+x^2)^2\cdot (e^{2\pi x}-1)} = \frac{\pi^2-9}{6}$$
And thus we arrive at the result:
$$ I = -i\cdot \frac{\pi^2-9}{6}$$
Comment: Well done and (+1)
Comment: Thanks for the praise
Answer: Without using the Abel-Plana Formula, we will prove the following equality.
$$
\bbox[15px,#FFFAFD,border:6px groove#60007C]{\int_0^\infty\left(\frac1{(ti+1)^2(e^{2\pi t}-1)}-\frac1{(-ti+1)^2(e^{2\pi t}-1)}\right)dt = i\frac{9-\pi^{2}}{6}}
$$
Proof. Let $\mathcal{I}$ be the integral in question. Using the Laplace Transform,
$$
\frac{1}{2}\int_{0}^{\infty}ye^{-y}\sin\left(xy\right)dy=\frac{x}{\left(1+x^{2}\right)^{2}}\,,
$$
we get
$$
\begin{align}
\mathcal{I} &:= \int_0^\infty\left(\frac1{(ti+1)^2(e^{2\pi t}-1)}-\frac1{(-ti+1)^2(e^{2\pi t}-1)}\right)dt \\
&= -4i\int_{0}^{\infty}\frac{x}{\left(e^{2\pi x}-1\right)\left(1+x^{2}\right)^{2}}dx \\
&= -4i\int_{0}^{\infty}\int_{0}^{\infty}\frac{ye^{-y}\sin\left(xy\right)}{2e^{2\pi x}-2}dydx \\
&= -4i\overbrace{\int_{0}^{\infty}\int_{0}^{\infty}\frac{ye^{-y}\sin\left(xy\right)}{2e^{2\pi x}-2}dxdy}^\text{Fubini's Theorem} \\
&= -2i\int_{0}^{\infty}ye^{-y}\int_{0}^{\infty}\frac{\sin\left(yx\right)}{e^{2\pi x}-1}dxdy\,. \\
\end{align}
$$
We write the inner integral as
$$
\int_{0}^{\infty}\frac{\sin\left(yx\right)}{e^{2\pi x}-1}dx = \lim_{L\,\to\,\infty}\lim_{r\,\to\,0^{+}}\Im\int_{r}^{L}\frac{e^{iyx}}{e^{2\pi x}-1}dx\,.
$$
In the next section, we will use contour integration to prove
$$
\bbox[10px,#F7FFDF]{\int_{0}^{\infty}\frac{\sin\left(yx\right)}{e^{2\pi x}-1}dx = \frac{1}{4}\coth\left(\frac{y}{2}\right)-\frac{1}{2y}\,.}
$$

Define a holomorphic function
$$
f: \mathbb{C}\,\backslash\left\{n \in \mathbb{Z}\,:\,in\right\}
$$
$$
z\mapsto \frac{e^{iyz}}{e^{2\pi z}-1}
$$
and a contour $C$ that travels counterclockwise through the union of sets, in order,
$$
\begin{align}
\color{#9E0000}{\lambda_1} &:= [r,L] \\
\color{#9E9300}{\lambda_2} &:= \left\{L+it\,:\,t\in[0,1]\right\}\\
\color{#3F9E00}{\lambda_3} &:= \left\{i-t\,:\,t\in[-L,-r]\right\}\\
\color{#00989E}{\gamma_1} &:= \left\{re^{-it}+1\,:\,t\in\left[0,\frac{\pi}{2}\right]\right\}\\
\color{#0062C3}{\lambda_4} &:= \left\{-it\,:\,t\in[r-1,-r]\right\}\\
\color{#68009E}{\gamma_2} &:= \left\{-re^{-it}\,:\,t\in\left[\frac{\pi}{2},\pi\right]\right\}\,.\\
\end{align}
$$
Here, we let $\displaystyle 0<r<\frac{1}{2}\ll L$. I've provided a visual down below that matches exactly what the union of sets is, down to the exact RGB/hexadecimal colors.

(I accidentally used $R$ instead of $L$. Oops :P...)
Integrating over these sets, we have
$$
\oint_{C}f = \int_{\color{#9E0000}{\lambda_1}}f + \int_{\color{#9E9300}{\lambda_2}}f + \int_{\color{#3F9E00}{\lambda_3}}f + \int_{\color{#00989E}{\gamma_1}}f + \int_{\color{#0062C3}{\lambda_4}}f + \int_{\color{#68009E}{\gamma_2}}f\,.
$$
Because $f$ is holomorphic on the simply connected open domain $\mathbb{C}\,\backslash\left\{n \in \mathbb{Z}\,:\,in\right\}$, $C$ is homologous to $0$, and $C$ is a piecewise, smooth, and closed loop, we use Cauchy's Integral Theorem to get
$$
\oint_{C}f = 0\,.
$$
Applying $\displaystyle \lim_{\substack{L\,\to\,\infty \\ r\,\to\,0^+}}\Im$ on both sides, we get
$$
0 = \int_{0}^{\infty}\frac{\sin\left(yx\right)}{e^{2\pi x}-1}dx + \lim_{L\,\to\,\infty}\Im\int_{\color{#9E9300}{\lambda_2}}f + \lim_{\substack{L\,\to\,\infty \\ r\,\to\,0^+}}\Im\int_{\color{#3F9E00}{\lambda_3}}f + \lim_{r\,\to\,0^+}\Im\int_{\color{#00989E}{\gamma_1}}f + \lim_{L\,\to\,\infty}\Im\int_{\color{#0062C3}{\lambda_4}}f + \lim_{r\,\to\,0^+}\Im\int_{\color{#68009E}{\gamma_2}}f\,.
$$
Now we evaluate each of these contour integrals.
For $\displaystyle \lim_{L\,\to\,\infty}\Im\int_{\color{#9E9300}{\lambda_2}}f$, I'll leave that as an exercise for your practice (and because I'm lazy). You can see similar examples here and here. As the vertical line segment gets farther away, we see that the behavior of the contour integral is

 $$\lim_{L\,\to\,\infty}\Im\int_{\color{#9E9300}{\lambda_2}}f = 0\,.$$

Letting $z \in \color{#3F9E00}{\lambda_3}$, we evaluate $\displaystyle \lim_{\substack{L\,\to\,\infty \\ r\,\to\,0^+}}\Im\int_{\color{#3F9E00}{\lambda_3}}f$ as
$$
\begin{align}
\lim_{\substack{L\,\to\,\infty \\ r\,\to\,0^+}}\Im\int_{\color{#3F9E00}{\lambda_3}}f &= \lim_{\substack{L\,\to\,\infty \\ r\,\to\,0^+}}\Im \int_{-L}^{-r}f(i-t)d(i-t) \\
&= \lim_{\substack{L\,\to\,\infty \\ r\,\to\,0^+}}\Im \int_{-L}^{-r}\frac{e^{iy\left(i-t\right)}}{e^{2\pi\left(i-t\right)}-1}d\left(i-t\right) \\
&= -e^{-y}\lim_{\substack{L\,\to\,\infty \\ r\,\to\,0^+}}\int_{-L}^{-r}\frac{\Im\left(e^{-iyt}\right)}{e^{-2\pi t}-1}dt \\
&\overset{-t\,\mapsto\,t}= -e^{-y}\lim_{\substack{L\,\to\,\infty \\ r\,\to\,0^+}}\int_{r}^{L}\frac{\sin\left(yt\right)}{e^{2\pi t}-1}dt \\
&= -e^{-y}\int_{0}^{\infty}\frac{\sin\left(yt\right)}{e^{2\pi t}-1}dt\,.
\end{align}
$$
As the top quarter-circle shrinks towards the simple pole at $z = i$, we evaluate $\displaystyle \lim_{r\,\to\,0^+}\Im\int_{\color{#00989E}{\gamma_1}}f$ as
$$
\begin{align}
 \lim_{r\,\to\,0^+}\Im\int_{\color{#00989E}{\gamma_1}}f &= \Im\left(-\frac{i\pi}{2}\mathop{\mathrm{Res}}_{z\,=\,i}\frac{e^{iyz}}{e^{2\pi z}-1}\right) \\
&= -\frac{\pi}{2}\lim_{z\,\to\,i}\frac{e^{iyz}}{\frac{d}{dz}\left(e^{2\pi z}-1\right)} \\
&= -\frac{1}{4e^{y}}\,. \\
\end{align}
$$
We can use a similar procedure to prove that

$$\lim_{r\,\to\,0^+}\Im\int_{\color{#68009E}{\gamma_2}}f = -\frac{1}{4}\,.$$

Evaluating $\displaystyle \lim_{r\,\to\,0^+}\Im\int_{\color{#68009E}{\gamma_2}}f$, we get
$$
\begin{align}
\lim_{r\,\to\,0^+}\Im\int_{\color{#68009E}{\gamma_2}}f &= \int_{r-1}^{-r}f(-it)d(-it) \\
&= \lim_{r\,\to\,0^+}\Im\int_{r-1}^{-r}\frac{e^{iy\left(-it\right)}}{e^{2\pi\left(-it\right)}-1}d\left(-it\right) \\
&= -\lim_{r\,\to\,0^+}\Re \int_{r-1}^{-r}\frac{e^{yt}}{e^{-2\pi it}-1}dt \\
&= \lim_{r\,\to\,0^+}\Re \int_{r-1}^{-r}e^{yt}\Re\left(\frac{1}{1-e^{-2\pi it}}\right)dt \\
&= \lim_{r\,\to\,0^+}\int_{r-1}^{-r}e^{yt}\Re\left(\frac{1}{2}-\frac{i}{2}\cot\left(\pi t\right)\right)dt \\
&= \lim_{r\,\to\,0^+}\int_{r-1}^{-r}\frac{e^{yt}}{2}dt \\
&= \frac{1}{2y}\left(1-\frac{1}{e^{y}}\right)\,. \\
\end{align}
$$
Collecting our results together, we have
$$
\require{cancel}{0 = \int_{0}^{\infty}\frac{\sin\left(yx\right)}{e^{2\pi x}-1}dx + \cancelto{0}{\lim_{L\,\to\,\infty}\Im\int_{\color{#9E9300}{\lambda_2}}f}}-e^{-y}\int_{0}^{\infty}\frac{\sin\left(yt\right)}{e^{2\pi t}-1}dt-\frac{1}{4e^{y}}+\frac{1}{2y}\left(1-\frac{1}{e^{y}}\right)-\frac{1}{4} \\
$$
$$
\implies \bbox[10px,#F4FEFF]{\int_{0}^{\infty}\frac{\sin\left(yx\right)}{e^{2\pi x}-1}dx = \frac{1}{4}\coth\left(\frac{y}{2}\right)-\frac{1}{2y}\,.}
$$

Going back to the double integral, $\mathcal{I}$ becomes
$$
\begin{align}
\mathcal{I} &= -2i\int_{0}^{\infty}\frac{y}{e^{y}}\cdot\frac{1}{4}\left(\coth\left(\frac{y}{2}\right)-\frac{2}{y}\right)dy \\
&= i-\frac{i}{2}\int_{0}^{\infty}\frac{y}{e^{y}}\coth\left(\frac{y}{2}\right)dy\,.
\end{align}
$$
I'll leave it as an exercise (again) to prove that the remaining integral equals

$$\frac{\pi^{2}}{3}-1\,.$$

Other than that, we conclude with
$$
\bbox[15px,#FDFFF4,border:6px groove#9BB400]{\int_0^\infty\left(\frac1{(ti+1)^2(e^{2\pi t}-1)}-\frac1{(-ti+1)^2(e^{2\pi t}-1)}\right)dt = i\frac{9-\pi^{2}}{6}}
$$
and we're done! $\blacksquare$


parameter in function even not isset ,still work

Question: Is it possible call a function, whatever the parameter isset or not,
how to do it?
select();
select($response_message);

function select($response_message) {
  ....
}

Answer: For PHP, when you declare the function, put in a default value
function select($response_message = 'whatever') {
    ....
}

At this point, select() and select('whatever') run the same thing.
for more information on PHP
As for javascript, that process is a little more involved
Comment: Thanks for reply, in php what if the $response_message sometime is an array,  can I define it before function like,  $response_message = array(...);  function select($response_message = $response_message') {
Comment: If you need to pass in an array, you can just run it like you'd expect `select(array('foo', 'bar'))`. 'whatever' is only assigned if you leave out the argument when you call it.
Comment: As for attempting to assign a default value like that, you'll need to do all that inside the function declaration itself, cant do `function select($this = $that) {}`.
Comment: so is it means  I set function select($a = 'default') {}   and other side I can call function like select()  or   $a = 'custom' select($a)


Word-frequency and statistics

Question: I am new to statistics and am wondering how I can apply it in linguistics. There is a conjunction in a corpus that 902 times (.91) conjoins sub-clausal units, and 91 (.09) times clausal units. How would I go about using statistical methods to argue that this distribution did not arise by chance? Do I need data from another conjunction that would show how conjunctions are "normally distributed"? What test would I use in this case?
Comment: It is very difficult to answer this question without some additional information (for instance, defining the basic terms you are using); you should also edit your question so the title reflects the specific content of the question.
Comment: That is the problem: I don't know what additional information I should be providing. What do you mean the basic terms? There is a word that occurs in total 993 times. In 902 cases (or .91) that word occurs before something smaller than a clause. In 91 times (or .09) it occurs before a clause. What other terms should I include?
Comment: Your phrase, did not arise by chance, leads to hypothesis testing. Which is a method to show that a particular assertion, hypothesis, is unlikely to have happened by chance. The data you give us, in isolation, can not be used to infer very much. You might have to analyse other conjunctions and compare and contrast them, in an attempt to understand the general behaviour of conjunctions. Then you might be able to infer something about this particular conjunction, or it's use in this particular corpus as opposed to other conjunctions in this and other corpuses. More information needed :)
Comment: Exactly what question are you trying to answer?  What difference are you looking for?  What are you trying to prove?  It is not clear from the original question.
Comment: As the other commenters have said, there isn't enough information to give a strong answer to your question. That said, years ago I worked in a lab studying neurolinguistics and had to do some similar analyses (related to frequency counts in a corpus). Essentially, the literature at the time had no consistent recommendations as to what to do. Based on my own experience doing that research and consulting with other researchers, I found the best thing to do is to use a bootstrap method to construct hypothesis tests.
Answer: If you would like to be able to say that the unbalanced split is not due to chance, you could do a z test to compare the proportion .91 to the null hypothesis of .5  (Alternatively, you could do the test on the .09 proportion; it is the same mathematically.)  The details on conducting such a statistical test are in most elementary statistics books (under one-sample test of proportions) and on-line (e.g. http://isites.harvard.edu/fs/docs/icb.topic116457.files/Review_Session_Slides_-_Part_2_-_Yves.pdf).

Word-frequency and statistics


angularFire route resolution

Question: I'd like to have my angularFire collection resolve on route loading. Something like:
App.config ($routeProvider, angularFireProvider) ->
  $routeProvider.when '/test',
    templateUrl: 'views/test.html'
    controller: 'TestCtrl'
    resolve: angularFireProvider.resolve 'testItems'

Is it possible to do this?
Answer: I'm not exactly sure why you want the collection to resolve on route loading, as opposed to in the controller - could you elaborate? For example, the following would work too:
App.config ($routeProvider, angularFireProvider) ->
  $routeProvider.when '/test',
  controller: 'TestCtrl'

function TestCtrl($scope, angularFire) {
  angularFire("https://<example>.firebaseio.com", $scope, "collection").
    then(function() {
      // The collection has been resolved and available in $scope.collection
    });
}

Is it mainly a matter syntactic convenience or am I missing functionality you want in the above?
Update: For the value to be resolved before the $routeChangeSuccess event is fired:
 App.config(['$routeProvider', 'angularFire', function($routeProvider, angularFire) {
   $routeProvider.when("/test", {
     templateUrl: 'views/test.html'
     controller: 'TestCtrl',
     resolve: {collection: angularFire("https://<example>.firebaseio.com")}
   });
 }]);

 function TestCtrl(collection) {
   // collection has already been resolved to its value.
 }

Comment: In this method `$routeChangeSuccess` will be emitted before the `angularFire` resources are resolved, right?
Comment: You're right - if you want the value to be resolved before the event Fires, you can just simply move the call to `angularFire` into your resolve property, since it returns a promise. I'll edit the answer to provide a code snippet.
Comment: Anant, on the off chance you may see this, I'm trying to use the resolve functionality but it states that angularFire is an unknown provider (on a related note is angularFireCollection not more appropriate in this instance owing to not requiring a scope?). aF and aFC work fine elsewhere in my code but is there perhaps something I'm missing in using it with config and resolve?

angularFire route resolution


Profinite completion of integers

Question: Can someone help me in this exercise?
Show that $Z_{p}=\varprojlim_{n\in \mathbb{N}}\mathbb{Z}/p^{n}\mathbb{Z}$ can also be identified with the set of power series
$$Z_{p}= \{ b=\sum_{n=0}^{\infty}b_{n}p^{n} \ | \ b_{n}\in \mathbb{N}, \ 0\leq b_{n}\leq p \}$$
Explain how the addition and multiplication of series is carried out under
this identification. How is $\mathbb{Z}$ embedded in $Z_{p}$ under this identification?
Thank you!
Answer: This is a classical exercise on inverse limits. Recall that $\varprojlim \mathbb{Z}/p^n\mathbb{Z}$ is a subgroup of the product $\prod_{n\in \mathbb{N}}\mathbb{Z}/p^n \mathbb{Z}$. Specifically,
$$
\varprojlim \mathbb{Z}/p^n\mathbb{Z} = \{(a_n)_n \mid a_n \equiv a_m (\text{mod }p^n) \text{ for } n\geq m \}
$$
(check this using the UMP of the inverse limit)
Thus, for every sequence $(a_n)_n$ in $\varprojlim \mathbb{Z}/p^n\mathbb{Z}$ we have: $a_1 \in \mathbb{Z}/p\mathbb{Z}$, then $a_1 \equiv a_2 (\text{ mod }p)$; thus, $a_2 = a_1 + k_1p$ for $k \in \mathbb{Z}/p\mathbb{Z}$. Analogously, $a_3 = a_1 + k_1p + k_2p^2$. We have then, $a_n = a_1 + k_1p + \ldots + k_{n-1}p^{n-1}$. Therefore, the sequence $(a_n)_n$ is just sequence of partial sums of elements in $Z_p$. This is the identification you're looking for.

Profinite completion of integers


Adding Social Authentication to Django

Question: I am using Django 3.0.5 and python 3.6. I want to add social authentication for my blog. Related files Settings.py, urls.py and login.html are:
Settings.py:
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATES_DIR=os.path.join(BASE_DIR,'templates')
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog',
    'social_django',
]

AUTHENTICATION_BACKENDS = [
    'social_core.backends.github.GithubOAuth2',
    'social_core.backends.google.GoogleOAuth2',
    'django.contrib.auth.backends.ModelBackend',

]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'social_django.middleware.SocialAuthExceptionMiddleware',

]

ROOT_URLCONF = 'mysite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATES_DIR],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'social_django.context_processors.backends',
                'social_django.context_processors.login_redirect',
            ],
        },
    },
]

WSGI_APPLICATION = 'mysite.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR,'static'),
)

STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles')

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

urls.py:
from django.contrib import admin
from django.urls import path

from django.conf.urls import url,include
from blog import views
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/',views.index, name='index'),
    path('datetime/',views.current_datetime,name='datetime'),
    path('',views.post_list,name='post_list'),
    url(r'^blog/(?P<id>\d+)/(?P<slug>[\w-]+)/$',views.post_detail,name="post_detail"),
    url('post_create/',views.post_create,name = "post_create"),
    url('login/', views.user_login,name="user_login"),
    url('logout/', views.user_logout,name="user_logout"),
    url('register/',views.register,name="register"),

    url('',include('django.contrib.auth.urls')),
    url(r'^oauth/', include('social_django.urls', namespace="social")),

]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

login.html:
{% extends 'blog/base.html' %}
{% block content %}
   <form method = "post">
       {% csrf_token %}
       {{form.as_p}}

       <input type="submit" value="Login" class="btn btn-outline-success">

 -- OR --

        <button type="button" name="button" class="btn btn-primary"> Github </button>

        <button type="button" name="button" class="btn btn-danger"> Google+ </button>

    </form>
{% endblock %}

In browser, when I click on Google+ button, I get the url "http://127.0.0.1:8000/oauth/login/google-oauth2/" from "http://127.0.0.1:8000/login/" but I supposed to get "401 error as invalid_client - The OAuth client was not found" because from this page's url, I get the value of uri which I need while doind setup django app on google developer console. Can anyone please help me how to get this error page ? Any help would be appreciated.
Answer: If you are using email login see settings you may have duplicated
AUTHENTICATION_BACKENDS
Review Settings Good and make sure you only use it once and include all of the backends

Adding Social Authentication to Django


Cor do ícone - Toolbar Android

Question: Como faço para deixar a cor do ícone, em API's menores que a 21, também da cor branca? Na 21 funciona ok, porém abaixo como por exemplo a 16, fica preto.
Fiz dessa forma:
Toolbar

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

Style

Cor do ícone - Toolbar Android


"Dual basis" generalizes to perfect pairing?

Question: Let $V, W$ be finite dimensional vector spaces over a field $F$ with a nondegenerate pairing $V \times W \rightarrow F$ on them.  Then $w \mapsto \langle-,w \rangle$ is an isomorphism $\Phi$ of $W$ with the dual of $V$, and in particular, $V, W$ have the same dimension.
Given a basis $v_1, ... , v_n$ for $V$, there then exists a basis $w_1, ... , w_n$ of $W$ such that $\langle v_i, w_j \rangle = \delta_{ij}$.  Namely one defines $w_i = \Phi^{-1}(v_i^{\ast})$, where $v_i^{\ast}$ is the dual element of $v_i$ in $V^{\ast}$.
Now, assume we are working with free abelian groups rather than vector spaces.  Let $X, Y$ be finite rank free abelian groups with a perfect pairing $X \times Y \rightarrow \mathbb{Z}$.  This means that $y \mapsto \langle -, y \rangle$ defines an isomorphism of $Y$ onto $\textrm{Hom}_{\mathbb{Z}}(X,\mathbb{Z})$, and the same with $X$ and $Y$ reversed.
I assume we can say the same thing? To any basis $x_1, ... , x_n$ of $X$, there exists a basis $y_1, ... , y_n$ of $Y$ such that $\langle x_i, y_j \rangle = \delta_{ij}$.  The same argument as above seems to carry over.  I just wanted to make sure I wasn't making a mistake somewhere.
Answer: The answer is yes. The crucial thing is the question whether the $y_i$ really generate $Y$. Because in the vector space case, you often use an dimension argument for this, which you cannot use over $\mathbb Z$. But we can help ourselves:
Let $y \in Y$ be arbitrary. Clearly $y_1, \dotsc, y_n$ is a $\mathbb Q$-basis of $Y \otimes \mathbb Q$, thus we have $y = \sum \lambda_i y_i$ with $\lambda_i \in \mathbb Q$.
For an $j$ we obtain
$$\langle x_j, y \rangle = \sum \lambda_i \langle x_j,y_i \rangle = \lambda _j$$
, hence $\lambda_j \in \mathbb Z$ and we are done.


Probability of agreeing to do some work depending on the payment

Question: I am looking for several options of modeling the probability of people agreeing to do some work depending on the price/payment. The payment can only range between p1 and p2 (p1 < p2). I looked at normal distribution and not sure if I can use it to model my case because the higher the payment, the higher probability that people will do it, intuitively, therefore it's monotonic. Is there anyway to only use the left side of the normal distribution to preserve the monotonicity?
Any other suggestions would be appreciated.
THanks.
Comment: What about using the cumulative distribution function of a Gaussian whose mean is $(p1 + p2)/2$ and standard deviation $(p2-p1)/2$?
Comment: David, can you elaborate more? Can that still preserve the monotonicity of the probability depending on the payment?
Answer: Here is the cumulative distribution function (CDF) of a Gaussian with mean $\mu = (p1+p2)/2$ and variance $\sigma = (p2-p1)/6$, which is of course monotonic in price (as all CDFs must be):
Comment: Great. Just a quick check: mu = (p1+p2)/2, right? not (1+p2)/2.
Comment: @Simo.  Yes.  (A typo.)
Answer: Because you have a bounded pay scale, and you do not know the shape of the function that maps probability of acceptance against pay, this is an excellent use case for a  generalized additive model, in particular a generalized additive logistic regression model. For this, I recommend the gam function from the R package mgcv. If you have multiple responses from the same individuals, you can use the gamm function, which allows you to specify random intercepts. You can then use the predict function to compute the fitted probabilities of acceptance for a grid of values on the pay scale. Then you can look at the plot of the curve and decide whether you could describe the relationship using some parametric function with interpretable parameters. If so, you could use one of the many R packages for nonlinear regression modeling to estimate the values of the parameters of that function.


How can i see my flutter app output in both Android and IOS simulator simultaneously?

Question: I am using the android studio to develop flutter application, I want to know is there any way I can see my app output in both android and ios simulator also I can perform hot reload on both simulator?
Answer: To debug multiple devices concurrently you should set up a launch config for each device that has the deviceId fieldset (this is the same ID you'd pass to flutter run -d xxx). Open the launch config by clicking Debug -> Open Configurations. Add a compound config at the bottom that will launch both (or more) configurations at the same time:
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Current Device",
            "request": "launch",
            "type": "dart"
        },
        {
            "name": "Android",
            "request": "launch",
            "type": "dart",
            "deviceId": "android"
        },
        {
            "name": "iPhone",
            "request": "launch",
            "type": "dart",
            "deviceId": "iphone"
        },
    ],
    "compounds": [
        {
            "name": "All Devices",
            "configurations": ["Android", "iPhone"],
        }
    ]
}

Selecting the compound config on the Debug side bar and clicking Debug -> Start Debugging (or Start Without Debugging) will launched debug sessions for each device at the same time.
Comment: More about this setup for multi-target debugging in VSCode in the [Flutter wiki](https://github.com/flutter/flutter/wiki/Multi-device-debugging-in-VS-Code)
Answer: Yes, there is a way to do that First install android and ios simulator and one by one Flutter run after that when both simulators are running. you can Hot reload from here.

and if you are looking for running both simultaneously then just then select all available devices and run your command. flutter run
Answer: Finally, I found a command to run an app in both Ios and Android simulator.
write below command in a terminal where your app is located
flutter run -d all

You can press r keyword in terminal to do hot reload.


Cannot use LogisticRegression for multilabel classification

Question: I'm using LogisticRegression from the sklearn library along with MultiOutputClassifier in order to use LR for multilabel classification. Unfortunately I'm getting an error when running this code:
res = MultiOutputClassifier(estimator=LogisticRegression()).fit(x_train, y_train)

Error:
ValueError: This solver needs samples of at least 2 classes in the data,
but the data contains only one class: 0

This does not make sense to me because x_train has shape (2210, 2000) while y_train has shape (2210, 58), which means it has 58 classes.
y_train = array([[0, 0, 1, ..., 0, 0, 0],
   [0, 0, 0, ..., 0, 0, 0],
   [0, 0, 0, ..., 0, 0, 0],
   ...,
   [0, 0, 0, ..., 1, 0, 1],
   [0, 0, 0, ..., 0, 0, 0],
   [0, 0, 0, ..., 0, 0, 0]])

x_train represents an array containing embeddings using Bag of Words term frequency inverse document frequency:
x_train = array([[0.        , 0.        , 0.02571182, ..., 0.        , 0.        ,
    0.        ],
   [0.        , 0.        , 0.        , ..., 0.        , 0.        ,
    0.        ],
   [0.        , 0.11247333, 0.        , ..., 0.09392727, 0.        ,
    0.        ],
   ...,
   [0.        , 0.        , 0.        , ..., 0.        , 0.        ,
    0.        ],
   [0.        , 0.07308953, 0.        , ..., 0.09155637, 0.        ,
    0.        ],
   [0.        , 0.07492016, 0.        , ..., 0.        , 0.        ,
    0.        ]])

Comment: Careful... you have 58 **targets**, not 58 **classes** (unless `y` has been encoded with one-hot encoding?). The number of classes you have corresponds to the number of unique values in `y`. It would probably help to see some of your data.
Comment: Hi @kwinkunks yes it is one-hot encoded
Comment: In general, I'd stick to one-hot encoding for **features**, not the target. Why not leave the labels unencoded (`sklearn` is okay with this now) and pass in a 1D array for the target? Then it's an ordinary multiclass problem and you can use classifiers directly.
Comment: @kwinkunks But if it is an ordinary multiclass problem stops being a multilabel problem? correct me if I'm wrong
Comment: Correct, if there's only one set of related classes (dog, cat, horse), it's a multiclass problem. If you have another set of classes (brown, black, grey) then you would have a multilabel problem. (Most problems are not expressed as mutilabel problems.)
Comment: @kwinkunks in this case I must express the problem as a multilabel one, I was able to apply logistic regression, by using OnevsRestClassifier instead of MultiOutputClassifier
Answer: Your MultiOutputClassifier is training a new Logistic Regression for each class, in such a way that the i-th logistic regressor is trained on y_train[:,i] (a column vector). The error
ValueError: This solver needs samples of at least 2 classes in the data,
but the data contains only one class: 0

is given by Logistic Regression and is indicating that one of these column vectors (y_train[:,i]) has only zeroes (i.e, only the class 0). Logistic Regression (and many other binary classifiers) can't be trained on a dataset where only exists a single class.
You can check the class distribution of each class by running
np.mean(y_train,axis=0)

and, consequently, check which class has only zeroes.
Approach 1
In supervised learning, if a class has only negative samples (only zeroes), it is reasonable to only output zero, since there is nothing that can be learned from the positive class.
In scikit-learn, some algorithms from supervised learning will always output zero for this class that only has zeroes. Some examples are: KNeighborsClassifier and DecisionTreeClassifier.
Or you can just discard this column vector that has only zeroes:
new_y = y_train[:,y_train.sum(axis=0)!=0]

Approach 2
But if your testing data actually has zeroes and ones for all classes, you may want to reconsider regenerating your training data in such a way that all classes have negative and positive samples in the training data. Search for stratification for multi-label data, such as iterative-stratification.
Approach 3
If this training data is not possible for some reason, you may want to take a look at one-class classification algorithms or novelty detection. These algorithms can learn from training data that only has "normal" samples, that is, all samples belong to the same class.


Reinforcement Learning: Afterstate and Afterstate value functions

Question: While reading the book: Reinforcement Learning, An Introduction by Rich Sutton, I came across a doubt regarding afterstates and afterstates value functions and I am afraid I don't understand the concept well.

A conventional state-value function evaluates states in which
  the agent has the option of selecting an action, but the state-value function used in tic-tac-toe evaluates board positions after the agent has made its move. Let us call these
  afterstates, and value functions over these, afterstate value functions.

Now, I understand what afterstates are, but I am unable to understand, how to use these afterstate value functions to learn the action values?

A conventional action-value function would have to
  separately assess both pairs, whereas an afterstate value function would immediately assess
  both equally. Any learning about the position–move pair on the left would immediately
  transfer to the pair on the right.

How do we make sure that the learning is transferred from one state-action pair to the other provided both the state-action pair results in the same afterstate?
Answer:
I am unable to understand, how to use these afterstate value functions to learn the action values?

If you use afterstates, you don't learn action values. You learn afterstate values.
It might help to think of it like this:

$v_{\pi}(s)$ state value of being in state $s$ and following policy $\pi$
$q_{\pi}(s,a)$ action value of being in state $s$, taking action $a$ and thereafter following policy $\pi$
$w_{\pi}(s')$ afterstate value of changing to state $s'$ (regardless of current state) and thereafter following policy $\pi$

Sorry to use the letter $w$ - that's because $a$ already taken - but I want to make it clear that this is a different, but related function. Most of the literature appears to use $v$ or $q$ with some annotation to explain that it is an afterstate value function.

How do we make sure that the learning is transferred from one state-action pair to the other provided both the state-action pair results in the same afterstate?

With afterstate values, it is impossible to not do this. There is nowhere else for any new value estimate to go, but to the value of the (shared) afterstate.
What you are possibly missing is that you need to use the environment model to look up either:

Which actions lead to which afterstates. In which case you might use same notation as action value $Q(s,a)$ but use $(s,a)$ to look up $s'$ and store a table (or approximate a function) of estimated values indexed by $s'$.

OR

Which afterstates are possible/valid given the current state. In which case you might use the same notation as state value $V(s)$ but actually use $s'$ in place of $s$ and remember to include immediate reward for arriving in the state in the value.

Both of these effectively define action selection (your "action" is to select a desired afterstate), and this is something you must do in order to use afterstate representation.
One other possible "gotcha" for using afterstates: In general as I've used $s'$ above, $s' \neq s_{t+1}$ for afterstates. That is, the agent may select a state $s'$, then the environment (or other player) could alter the state further resulting in the next state $s_{t+1}$ seen by the agent.
Comment: What confused me is that how to use *afterstates* to define a VI/PI. In Powell's book, *afterstates* is called *post-decision states*, and the $s_{t+1}$ is generated via two steps, that is the first is $s^{a}_t = s^{M, a}(s_t, a_t)$ and  the second step is $s_{t+1}=s^{M, W}(s^{a}_{t}, W_{t+1})$. For me, the two steps are not that novel, with deep learning, we can simply input $s_t$ and $W_{t+1}$ into the network. So, what makes *afterstates* new? And there are few works on how to use it with DRL.
Comment: **For me, the two steps are not that novel**, I mean the beauty of *afterstates* is not fully presented.


Quadratic residue modulo odd power of $2$

Question: If $x$ and $n$ both are odd positive integers, such that, $$x^2 \equiv -1\mod2^n$$  what can we say about $x$ and $n$ ?
Comment: An immediate observation: $n$ cannot be even because that would make $2^n$ a perfect square (and no consecutive numbers except for $0$ and $1$ are perfect squares). In addition, $x$ cannot be even as well.
Comment: Second thought, doesn't Catalan's conjecture (which was proved some time ago) imply that no such values of $x$ and $n$ exist?
Comment: @barakmanos It is amusing that you state the already given info. in the question as your first claim.
Comment: @Broly: It is now that you've mentioned it (didn't notice that).
Comment: Does the first comment mean to say that $x^2\cong -1$ $(mod y)$ has no solution if $y$ is a perfect square? This is false, take $x=7$ and $y=25$
Answer: Hint: Note that if $x$ is odd, then $x^2+1\equiv 2\pmod{4}$.
Answer: Since odd square  $ \equiv 1 \pmod 8$ we infer that if $n \geq 3$, $x^2+1 \equiv 2 \neq -1 \pmod 8$. Thus $n=1$.