A resposta HTTP 418 "I'm a Teapot" seria válido?

Question: Uma determinada API está me retornando um status 418 I'm a teapot, vi que faz parte do protocolo HTCPCP.
             ;,'
     _o_    ;:;'
 ,-.'---`.__ ;
((j`=====',-'
 `-\     /
    `-=-'

O uso deste status pode ser considerado como um retorno válido?
Comment: @DanielMendes se eu fizer uma requisição HTCPCP para uma chaleira em ambiente de produção qual deveria usar então?
Comment: Não acho que sua implementação deva ser feita em um servidor de produção, pois o mesmo nasceu de uma piada de primeiro de abril, mas existe até mesmo RFC: https://developer.mozilla.org/pt-BR/docs/Web/HTTP/Status/418
Comment: não seria válido usar esse código quando alguém tenta fazer algo que o servidor não faz?
Answer: O status 418 hoje é reservado ao "I'm a teapot", mas vou contar um pouco de como foi este processo.
Como já foi dito este status é uma brincadeira que surgiu em 01/04/1998, ou seja uma brincadeira de "primeiro de Abril", até mesmo a Google o utilizou em um de seus Easter Eggs:

https://searchengineland.com/new-google-easter-egg-seo-geeks-server-status-418-im-teapot-201739

No entanto o que falta falar é que este status foi proposto para ser removido, Mark Nottingham, presidente do IETF na época, solicitou a remoção desse status de algumas linguagens e bibliotecas, em resposta a isto, Shane Brunswick (um desenvolvedor, por algum motivo frisaram que na época ele tinha apenas 15 anos) criou um site chamado https://save418.com/ ("Save 418 Movement"), na proposta ele citou alguns argumentos em favor de manter o status 418, mas creio que a que mais convenceu as pessoas foi este argumento:

... It's a reminder that the underlying processes of computers are still made by humans.

Traduzido:

... É um lembrete de que os processos subjacentes dos computadores ainda são feitos por seres humanos.

Isto se tornou viral (ao menos entre o publico que é da área de desenvolvimento e participantes do reddit) que ocasionou na hashtag #save418 em mídias sociais.
Com isto as linguagens e bibliotecas HTTP que pretendiam remover o status 418 optaram por mantê-lo, não porque ele é útil ou porque ele é aplicável, foi apenas pelos fatos ocorridos antes.
Estes ocorridos levaram Mark Nottingham a abrir um processo de tornar o 418 um status reservado para que no futuro não fosse substituído no futuro por outro uso, então basicamente é por isso que o status ainda existe.

Respondendo a pergunta:

O uso deste status pode ser considerado como um retorno válido?

Validade é uma questão de contexto, sem contexto algum e falando apenas de HTTP dá pra dizer sim, ele é valido, mas usar por usar não tem nem sentido, assim como usar qualquer outro código sem contexto.
Reforço dizendo que mesmo sendo hoje um código reservado isto não significa que lhe será útil, a não ser que você queira brincar também (e ache isto prudente no momento), por exemplo, no dia primeiro de Abril em qualquer erro(s) HTTP especifico(s) (exemplo 404) você trocaria pelo 418 (desde que não afete quem for usar o serviço).
Resumindo a história, não tem um uso real, tem um apoio das comunidades e pessoas por motivações históricas e algum "apreço" a lembrar que as coisas são criadas por humanos ainda.
Você não precisa se preocupar em resolver este status, mas também se nota-lo em uma requisição de outro servidor que fizer, já sabe, provavelmente é uma brincadeira e provavelmente tem como contornar ou você com certeza caiu no lugar errado ou fez algo errado, para cair na tal brincadeira.
Answer: O código HTTP 418 faz parte de uma especificação (RFC), que foi publicada como piada de 1º de Abril (fonte).
De acordo com a especificação, esse código é válido se você solicitou a uma cafeteira que ela faça café, mas o "servidor" não é uma cafeteira e sim um "tea pot" (chaleira?).
Mesmo não sendo uma especificação séria, várias bibliotecas e frameworks implementaram essa especificação como forma de continuar a piada.
Como a especificação nunca foi reconhecida pela IETF (órgão responsável por endossar as especificações relacionadas ao HTTP) teoricamente ela não é válida para um servidor de verdade. Mas, mesmo assim, nada impede alguns serviços de implementarem esse código.
Answer: Por definição, todos os status codes que começam com 4 são status code de "Client Error". Portanto, você precisa considerar isso como uma falha. Os status de sucesso são os que começam com 2.
418 I'm a teapot é um status code feito como primeiro de abril e não deveria ser usado em produção.
Você vai precisar falar com quem fez o endpoint pra entender o que ele quis dizer com isso.


Mysql InnoDb cluster adding new instance causes exception

Question: I have created Centos 7 VM instance on Google cloud. I installed MySql 8.0 on this. Configured all proper settings. Edited my.cnf. After finalizing my instance I created the snapshot of this instance and created two more instances from this snapshot.
I have to configure the Mysql InnoDB cluster using MySQL shell. Now the issue is there all newly created instance has the same UUID as their master node. When I try to add the new instance in InnoDB cluster it shows me the following error. I am literally stuck here. please anyone guide me how can I change the UUID of newly created machines. So that new noded can be added in MySQL Cluster.
Following is the error for
cluster1.addInstance('root@*******:3306', { memberSslMode: 'REQUIRED', ipWhitelist:'**********************'});

    Cluster.addInstance: Cannot add an instance with the same server UUID (1ddc0de3-8050-11e8-8cc0-42010a8e0003) of an active member of the cluster 'server2:3306'. Please change the server UUID of the instance to add, all members must have a unique server UUID. (RuntimeError)

[root@server3 server3]# ls -ltr /dev/disk/by-uuid/
total 0
lrwxrwxrwx. 1 root root 10 Jul  5 13:19 51a7c7e4-4490-4c13-a7aa-446d8606cef5 -> ../../sda1

[root@server2 ~]# ls -ltr /dev/disk/by-uuid/
total 0
lrwxrwxrwx. 1 root root 10 Jul  5 12:19 51a7c7e4-4490-4c13-a7aa-446d8606cef5 -> ../../sda1

Answer: The server UUID is stored in the file auto.cnf. Your snapshot should not contain this file, so that MySQL in each created instance generates its own unique UUID. Delete it and create a new snapshot.


SQL left Join Error on multiple JOIN

Question: Here is my query

SELECT item.item, item.id as itemID,item.item_sku,O.serial_no,transaction.id, transaction.t_price, transaction.t_unit, transaction.total_amount, transaction.transaction_type, transaction.comment, transaction.created from transaction

LEFT JOIN item ON transaction.item_id = item.id
LEFT JOIN order O  ON transaction.order_no=o.order_no
WHERE transaction_type='buy' ORDER BY transaction.created DESC

But its showing this error .. why ??
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'order  o ON transaction.order_no=o.order_no WHERE transaction_type='buy' ORDER ' at line
Answer: ORDER is a reserved word, so you need to escape it. Check this Stackoverflow answer on how to use back-tick to escape the reserved words in your queries.
Please check this one:
SELECT item.item, item.id as itemID,item.item_sku,O.serial_no,transaction.id, transaction.t_price, transaction.t_unit, transaction.total_amount, transaction.transaction_type, transaction.comment, transaction.created
FROM transaction

LEFT JOIN item ON transaction.item_id = item.id
LEFT JOIN `order` O  ON transaction.order_no = o.order_no
WHERE transaction_type='buy'
ORDER BY transaction.created DESC

Answer: And you can write a shorter form when you use ALIAS.
SELECT
    i.item
    , i.id as itemID
    , i.item_sku
    , o.serial_no
    , t.id
    , t.t_price
    , t.t_unit
    , t.total_amount
    , t.transaction_type
    , t.comment
    , t.created
FROM transaction
LEFT JOIN item i ON t.item_id = i.id
LEFT JOIN `order` o ON t.order_no=o.order_no
WHERE transaction_type='buy'
ORDER BY t.created DESC;

SQL left Join Error on multiple JOIN


How can I add enemies coming from left and right?

Question: I am creating a shooting game in which the player in the bottom middle can shoot enemies coming from the bottom left and bottom right. I have looked at online tutorials and all of the the shooting games had been space shooting which the enemies comes from the top to the bottom. This is the code I have for now:
import pygame
import time
import random

# --- constants --- (UPPER_CASE_NAMES)

DISPLAY_WIDTH = 800
DISPLAY_HEIGHT = 600

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

FPS = 60

# - init -

pygame.init()

gameDisplay = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))
pygame.display.set_caption("The Adventure of the Excorist's Meter")

# - objects -

background_image = pygame.image.load("skyline_background.jpg").convert()
background_position = [0, 0]

player_image_left = pygame.image.load('character_left.png')
player_image_right = pygame.image.load('character_right.png')

player_image = player_image_left

# Load enemy image
zombie_image = pygame.image.load('zombie_image.png')
devil_image = pygame.image.load('devil_image.png')
ghost_image = pygame.image.load('ghost_image.png')

def enemy(enemy_x,enemy_y):
    gameDisplay.blit(zombie_image, (enemy_x, enemy_y))

player_speed = 0
player_x = DISPLAY_WIDTH * 0.45
player_y = DISPLAY_HEIGHT * 0.65
player_x_change = 0

# - mainloop -

clock = pygame.time.Clock()
crashed = False

while not crashed:

    # - events -

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            crashed = True

        if event.type == pygame.KEYDOWN:

            if event.key == pygame.K_LEFT:
               player_x_change = -5
               player_image = player_image_left

            elif event.key == pygame.K_RIGHT:
                player_x_change = 5
                player_image = player_image_right

        if event.type == pygame.KEYUP:
            if event.key in (pygame.K_LEFT, pygame.K_RIGHT):
                player_x_change = 0

    # - updates -

    player_x += player_x_change

    # - draws -

    gameDisplay.blit(background_image, background_position)

    gameDisplay.blit(player_image, (player_x, player_y))

    pygame.display.update()

    clock.tick(FPS)

# - end -

pygame.quit()

Comment: create `pygame.Rect()` for every enemy to keep its size and position, and change enemies positions in `# - updates -`, and draw enemies in `# - draws -`. Briefly you have to do similar to `player`.
Comment: if tutorial shows how to move from top to bottom then it has to change `y`. To move from left to right you have to change `x` instead of `y`.
Answer: Create pygame.Rect() for every enemy to keep its size and position
zombie_rect = zombie_image.get_rect()
zombie_rect.y = 300
zombie_speed = 10

devil_rect = devil_image.get_rect()
devil_rect.right = DISPLAY_WIDTH
devil_rect.y = 200
devil_speed = -10

and change enemies x positions in - updates -
zombie_rect.x += zombie_speed
devil_rect.x += devil_speed

# change direction
if zombie_rect.left <= 0 or zombie_rect.right >= DISPLAY_WIDTH:
    zombie_speed = -zombie_speed
if devil_rect.left <= 0 or devil_rect.right >= DISPLAY_WIDTH:
    devil_speed = -devil_speed

and draw enemies in - draws -.
gameDisplay.blit(zombie_image, zombie_rect)

gameDisplay.blit(devil_image, devil_rect)

Briefly you have to do something similar to player.
If tutorial shows how to move from top to bottom then it has to change y. To move from left to right you have to use x instead of y.
BTW: I use Rect() for player position (player_rect) so I can check if it touchs enemies.
import pygame
import random

# --- constants --- (UPPER_CASE_NAMES)

DISPLAY_WIDTH = 800
DISPLAY_HEIGHT = 600

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

FPS = 60

# --- classes ---

# --- functions ---

# --- main ---

# - init -

pygame.init()

gameDisplay = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))
pygame.display.set_caption("The Adventure of the Excorist's Meter")

# - objects -

background_image = pygame.image.load("skyline_background.jpg").convert()
background_rect = background_image.get_rect()

player_image_left = pygame.image.load('character_left.png').convert()
player_image_right = pygame.image.load('character_right.png').convert()

player_image = player_image_left
player_rect = player_image.get_rect()

player_rect.x = DISPLAY_WIDTH * 0.45
player_rect.y = DISPLAY_HEIGHT * 0.65

player_speed = 0
player_x_change = 0

# Load enemy image
zombie_image = pygame.image.load('zombie_image.png').convert()
devil_image = pygame.image.load('devil_image.png').convert()
ghost_image = pygame.image.load('ghost_image.png').convert()

zombie_rect = zombie_image.get_rect()
zombie_rect.y = 300
zombie_speed = 10

devil_rect = devil_image.get_rect()
devil_rect.right = DISPLAY_WIDTH
devil_rect.y = 200
devil_speed = -10

# - mainloop -

clock = pygame.time.Clock()
crashed = False

while not crashed:

    # - events -

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            crashed = True

        if event.type == pygame.KEYDOWN:

            if event.key == pygame.K_LEFT:
               player_x_change = -5
               player_image = player_image_left

            elif event.key == pygame.K_RIGHT:
                player_x_change = 5
                player_image = player_image_right

        if event.type == pygame.KEYUP:
            if event.key in (pygame.K_LEFT, pygame.K_RIGHT):
                player_x_change = 0

    # - updates -

    player_rect.x += player_x_change

    zombie_rect.x += zombie_speed
    devil_rect.x += devil_speed

    # change direction
    if zombie_rect.left <= 0 or zombie_rect.right >= DISPLAY_WIDTH:
        zombie_speed = -zombie_speed
    if devil_rect.left <= 0 or devil_rect.right >= DISPLAY_WIDTH:
        devil_speed = -devil_speed

    if player_rect.colliderect(zombie_rect):
        print("You touch zombie")
    if player_rect.colliderect(devil_rect):
        print("You touch devil")

    # - draws -

    gameDisplay.blit(background_image, background_rect)

    gameDisplay.blit(player_image, player_rect)

    gameDisplay.blit(zombie_image, zombie_rect)

    gameDisplay.blit(devil_image, devil_rect)

    pygame.display.update()

    clock.tick(FPS)

# - end -

pygame.quit()

Comment: Perhaps you should show the questioner also how to add multiple enemies to a list.


form ajax forget's changes made in previous ajax callback calls

Question: Why do changes don't get saved in $form, or what is it that's overriding it?
I would like to set custom class to multiple fieldsets in an ajax callback function:
if (something) {
  $form['fieldset_01']['#attributes'] = array('class' => array('custom_class'));
  $form['fieldset_02']['#attributes'] = array('class' => array('custom_class'));
}
elseif (somethingelse) {
  $form['fieldset_11']['#attributes'] = array('class' => array('custom_class'));
  $form['fieldset_12']['#attributes'] = array('class' => array('custom_class'));
}

return $form;

When $form is returned, the element that I have set in this call is rendered fine, with a new CSS class but the elements I have rendered in previous calls have lost this new class, as if they were rendered with default values.
EDIT: my form creation function
function mynode_form($form, &$form_state) {

$nid = $form_state['values']['nid'];

$ajax = array(
'callback' => 'mynode_ajax',
'wrapper' => 'mynode_form',
'event' => 'change',
'method' => 'replace',
);

$node = node_load($nid);
$title = $node->field_title['und'][0]['value'];

$form = array();
$form['#prefix'] = '
';
$form['#suffix'] = '
';

$form['nid'] = array(
  '#value' => $nid,
  '#type' => 'hidden',
);

$form['fieldset_0'] = array(
  '#type' => 'fieldset',
  '#collapsible' => true,
  '#title' => 'Fieldset title 0',
  //'#attributes' => array('class' => array('a', 'b')),
  '#weight' => 1,
);

$form['fieldset_0']['textfield_0'] = array(
  '#type' => 'textfield',
  '#title' => t('Title 0?'),
  '#ajax' => $ajax,
);

$form['fieldset_1'] = array(
  '#type' => 'fieldset',
  '#collapsible' => true,
  '#title' => 'Fieldset title 1',
  //'#attributes' => array('class' => array('a', 'b')),
  '#weight' => 1,
);

$form['fieldset_1']['textfield_1'] = array(
  '#type' => 'textfield',
  '#title' => t('Title 1?'),
  '#ajax' => $ajax,
);

if (isset($form_state['triggering_element']['#name'])){
  $key = $form_state['triggering_element']['#name'];
  switch($key){
    case 'textfield_0':
      $form['fieldset_0']['#attributes'] = array('class' => array('a', 'b',   'c'));
      $form['fieldset_1']['#attributes'] = array('class' => array('a',   'b'));
    break;
  }
}
else{
  //only the first time
  $form['fieldset_0']['#attributes'] = array('class' => array('a', 'b'));
  $form['fieldset_1']['#attributes'] = array('class' => array('a', 'b'));
}
return $form;
}

Comment: There's syntax errors in this code.
Comment: I must have done something, while indenting.. i think it is fixed now.
Comment: I can't see anything wrong with that code. I hope you're clearing all cache after you change your functions as form arrays sometimes may get cached. Also I'd wrap anything referencing `$form_state` inside an `isset()` check to avoid warnings and notices.
Answer: AJAX callback function is meant to only tell Drupal what to update. By design all you do in it is for one call only.
Permanent changes needs to be done in main form creation function. I usually see them done in block like that:
if (!empty($form_state['values'])) {
  //here you are supposed to use these values
}

Comment: Your form function is called everytime before an ajax callback is called. So the condition and the modification of `$form` should be inside your form function.
Comment: @Molot I am pretty sure. In the same debug session i reach form_name_form function and in ajax call i reach ajax callback function but not form_name_form function.
Comment: I have checked this, but i couldn't find the style changes - class values for certain element. How can i check this? It is not a value..
Comment: You need to alter $form array, not $form_state. You need $form_state only to know that ajax was actually called and what element triggered your form building function.
Comment: I get form with print drupal_render(drupal_get_form($form_name, $request_id)); and it seems that function for creating that form si getting called only the first time.
Comment: Is there any reason why it wouldn't be called? I set a breakpoint and it was reached only the first time, when form is initially created.
Comment: @gregab are you sure your debugger is actually connected to calls invoked by AJAX? they happen in separate processes, you know.
Comment: To test that the form is being rebuilt, a more hands-on approach would be to use the devel module and put `dpm('Form rebuilt');` at the top of the form function. This will output a message to the message area everytime the function runs. With Ajax calls however, if you're not writing anything to the screen you should open another tab with a different page, and after you trigger the ajax call, switch to the other tab and refresh the page to see the message being output. But thing is, the main problem is your condition and form modification is in callback, should be in form builder.
Comment: i moved everything in function which creates form and now nothing is changed when ajax callback returns $form.
Comment: Can you update your question with the current code?
Comment: i have updated with code


Secondary dropdown menu within a dropdown menu not showing

Question: I'm having trouble getting a secondary dropdown menu to appear to the right of one of the dropdown links I hover over but it does not appear..
I have positioned the secondary dropdown menu accordingly using margins.. If you change the width of the .subDropdown class to a value e.g. 100px, you can see the dropdown is where it should be.. so I'm not sure why it does not change when I code in a 'hover' event..
https://jsfiddle.net/yje82den/
Can't see what I'm missing..
The HTML:

MENU BUTTON

Link 1

Link 2

Link 3 →

Link 4

Link 5

Link 6

The CSS:
.navbtn {
background-color: #009337;
max-width: 250px;
}

.dropdown {
height:0;
overflow: hidden;
transition: height 0.5s;
}

.dropdownitem {
background-color: #00bf48;
border-top: 1px solid rgba(0,0,0,0.4);
padding: 10px;
transition: background-color 0.5s;
}
.dropdownitem:hover {background-color:#43e27f;}

.subDropdown .dropdownitem {
background-color: #23f171;
}

.subDropdown {
position: fixed;
margin: -39px 0 0 250px;
height: 120px;
width: 0;
overflow: hidden;
transition: width 0.5s;
}

.navbtn:hover .dropdown {height:115px;}
#sub:hover .subDropdown {width: 250px;}

Answer: The dropdown .subDropdown is not a descendant of #sub, so selector #sub:hover .subDropdown won't work.
Instead you can use the sibling selector (+), as the sub-dropdown is placed immediately after the #sub div in the DOM.
Also, you can add .subDropdown:hover on the same styles to ensure that as you hover over the child links, the menu remains open.
#sub:hover + .subDropdown,
.subDropdown:hover {
  width: 250px;
}

Here's the updated fiddle: https://jsfiddle.net/yje82den/2/
Comment: Ah thank you Nisarg. Funny the difference 1 symbol can make.. I am yet  to wrap my head around the css selectors so I might go and do that now.
Comment: @SteveyG Yup they can be tricky initially. MDN has some great articles here: https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS/Selectors
Comment: May I ask (as I just noticed) - when I hover over any of the secondary dropdown links, the menu minimises again..

Just wondering if you know what's causing that?
Comment: @SteveyG Yeah, you'd need to add one more rule there which keeps the menu open when `.subDropdown` is hovered upon. I just updated the answer.
Comment: Also, see [this](https://jsfiddle.net/yje82den/3/), if you need to add more links-sublinks, you will need to change `height` to `auto` on rule `.navbtn:hover .dropdown`.


Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.22.2:test

Question: Estou iniciando em programação e esse é meu primeiro projeto. Quando executo o "Maven Install", ocorre o seguinte erro "Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.22.2:test"
Preciso de ajuda para resolver
Pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.2</version>
        <relativePath/>
    </parent>
    <groupId>br.com.seguro</groupId>
    <artifactId>Seguro</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>SeguroVeicular</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.0.0-M7</version>
            <type>maven-plugin</type>
        </dependency>
    </dependencies>

    <build>
        <plugins>
        <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
            <configuration>
                <useSystemClassLoader>false</useSystemClassLoader>
            </configuration>
        </plugin>
        </plugins>
    </build>

</project>

Console
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------
------------------------
[INFO] Building SeguroVeicular 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:3.2.0:resources (default-resources) @ Seguro ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Using 'UTF-8' encoding to copy filtered properties files.
[INFO] Copying 1 resource
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.10.1:compile (default-compile) @ Seguro ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:3.2.0:testResources (default-testResources) @ Seguro ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Using 'UTF-8' encoding to copy filtered properties files.
[INFO] skip non existing resourceDirectory C:\Users\gabriel\Desktop\Seguro-master\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.10.1:testCompile (default-testCompile) @ Seguro ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.22.2:test (default-test) @ Seguro ---
[INFO]
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running br.com.seguro.seguroveicular.SeguroVeicularApplicationTests
19:42:47.011 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
19:42:47.118 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
19:42:47.245 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [br.com.seguro.seguroveicular.SeguroVeicularApplicationTests] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
19:42:47.350 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [br.com.seguro.seguroveicular.SeguroVeicularApplicationTests], using SpringBootContextLoader
19:42:47.377 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [br.com.seguro.seguroveicular.SeguroVeicularApplicationTests]: class path resource [br/com/seguro/seguroveicular/SeguroVeicularApplicationTests-context.xml] does not exist
19:42:47.378 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [br.com.seguro.seguroveicular.SeguroVeicularApplicationTests]: class path resource [br/com/seguro/seguroveicular/SeguroVeicularApplicationTestsContext.groovy] does not exist
19:42:47.379 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [br.com.seguro.seguroveicular.SeguroVeicularApplicationTests]: no resource found for suffixes {-context.xml, Context.groovy}.
19:42:47.379 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [br.com.seguro.seguroveicular.SeguroVeicularApplicationTests]: SeguroVeicularApplicationTests does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
19:42:47.600 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [br.com.seguro.seguroveicular.SeguroVeicularApplicationTests]
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 1.327 s <<< FAILURE! - in br.com.seguro.seguroveicular.SeguroVeicularApplicationTests
[ERROR] br.com.seguro.seguroveicular.SeguroVeicularApplicationTests  Time elapsed: 1.325 s  <<< ERROR!
java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test

[INFO]
[INFO] Results:
[INFO]
[ERROR] Errors:
[ERROR]   SeguroVeicularApplicationTests » IllegalState Unable to find a @SpringBootConf...
[INFO]
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  24.621 s
[INFO] Finished at: 2022-09-10T19:42:48-03:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.22.2:test (default-test) on project Seguro: There are test failures.
[ERROR]
[ERROR] Please refer to C:\Users\gabriel\Desktop\Seguro-master\target\surefire-reports for the individual test results.
[ERROR] Please refer to dump files (if any exist) [date].dump, [date]-jvmRun[N].dump and [date].dumpstream.
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

Answer: Esse erro é apenas na tua classe de teste, ou seja,  tu não implementou quaisquer tipo de teste. A prova disso é no próprio console, onde a mensagem é: There are test failures.
Neste caso, tu pode usar o comando mvn clean install -DskipTests que irá pular os testes ou implementar os testes de fato.


Thread-safely transforming a value in a mutable map

Question: Suppose I want to use a mutable map in Scala to keep track of the number of times I've seen some strings. In a single-threaded context, this is easy:
import scala.collection.mutable.{ Map => MMap }

class Counter {
  val counts = MMap.empty[String, Int].withDefaultValue(0)

  def add(s: String): Unit = counts(s) += 1
}

Unfortunately this isn't thread-safe, since the get and the update don't happen atomically.
Concurrent maps add a few atomic operations to the mutable map API, but not the one I need, which would look something like this:
def replace(k: A, f: B => B): Option[B]

I know I can use ScalaSTM's TMap:
import scala.concurrent.stm._

class Counter {
  val counts =  TMap.empty[String, Int]

  def add(s: String): Unit = atomic { implicit txn =>
    counts(s) = counts.get(s).getOrElse(0) + 1
  }
}

But (for now) that's still an extra dependency. Other options would include actors (another dependency), synchronization (potentially less efficient), or Java's atomic references (less idiomatic).
In general I'd avoid mutable maps in Scala, but I've occasionally needed this kind of thing, and most recently I've used the STM approach (instead of just crossing my fingers and hoping I don't get bitten by the naïve solution).
I know there are a number of trade-offs here (extra dependencies vs. performance vs. clarity, etc.), but is there anything like a "right" answer to this problem in Scala 2.10?
Comment: what about a single Akka actor that writes to the mutable map? `Counter.add` just sends a fire-and-forget message to it. As for reads, depending on your needs they can happen concurrently or go through the actor too.
Answer: How about this one? Assuming you don't really need a general replace method right now, just a counter.
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicInteger

object CountedMap {
  private val counts = new ConcurrentHashMap[String, AtomicInteger]

  def add(key: String): Int = {
    val zero = new AtomicInteger(0)
    val value = Option(counts.putIfAbsent(key, zero)).getOrElse(zero)
    value.incrementAndGet
  }
}

You get better performance than synchronizing on the whole map, and you also get atomic increments.
Comment: I'm curious if there's a reason to reach for ConcurrentHashMap instead of concurrent.TrieMap. I have no opinion, just that the forum is an ad for API.
Comment: Thanks—I am interested in the general case, but it's good to see that this is so easy.
Comment: This is the right solution and leverages the very high performance Java concurrent libraries.
Comment: @som-snytt I was not aware of that class, and I don't have an opinion right now in choosing one or the other.
Answer: The simplest solution is definitely synchronization. If there is not too much contention, performance might not be that bad.
Otherwise, you could try to roll up your own STM-like replace implementation. Something like this might do:
object ConcurrentMapOps {
  private val rng = new util.Random
  private val MaxReplaceRetryCount = 10
  private val MinReplaceBackoffTime: Long = 1
  private val MaxReplaceBackoffTime: Long = 20
}
implicit class ConcurrentMapOps[A, B]( val m: collection.concurrent.Map[A,B] ) {
  import ConcurrentMapOps._
  private def replaceBackoff() {
    Thread.sleep( (MinReplaceBackoffTime + rng.nextFloat * (MaxReplaceBackoffTime - MinReplaceBackoffTime) ).toLong ) // A bit crude, I know
  }

  def replace(k: A, f: B => B): Option[B] = {
    m.get( k ) match {
      case None => return None
      case Some( old ) =>
        var retryCount = 0
        while ( retryCount <= MaxReplaceRetryCount ) {
          val done = m.replace( k, old, f( old ) )
          if ( done ) {
            return Some( old )
          }
          else {
            retryCount += 1
            replaceBackoff()
          }
        }
        sys.error("Could not concurrently modify map")
    }
  }
}

Note that collision issues are localized to a given key. If two threads access the same map but work on distinct keys, you'll have no collisions and the replace operation will always succeed the first time. If a collision is detected, we wait a bit (a random amount of time, so as to minimize the likeliness of threads fighting forever for the same key) and try again.
I cannot guarantee that this is production-ready (I just tossed it right now), but that might do the trick.
UPDATE: Of course (as Ionuț G. Stan pointed out), if all you want is increment/decrement a value, java's ConcurrentHashMap already provides thoses operations in a lock-free manner.
My above solution applies if you need a more general replace method that would take the transformation function as a parameter.
Comment: I noticed in the Map code he switched to ThreadLocalRandom https://github.com/scala/scala/blob/master/src/library/scala/collection/concurrent/TrieMap.scala#L473
Answer: If you are ok to work with future based interface:
trait SingleThreadedExecutionContext {
  val ec = ExecutionContext.fromExecutor(Executors.newSingleThreadExecutor())
}

class Counter extends SingleThreadedExecutionContext {
  private val counts = MMap.empty[String, Int].withDefaultValue(0)

  def get(s: String): Future[Int] = future(counts(s))(ec)

  def add(s: String): Future[Unit] = future(counts(s) += 1)(ec)
}

Test will look like:
class MutableMapSpec extends Specification {

  "thread safe" in {

    import ExecutionContext.Implicits.global

    val c = new Counter
    val testData = Seq.fill(16)("1")
    await(Future.traverse(testData)(c.add))
    await(c.get("1")) mustEqual 16
  }
}

Comment: This is not thread safe at all. While you guarantee a single writer at a time, you can still have threads reading while the map is being modified
Comment: As I understand, all operations - read, write, mixed - that use ec as context will be thread safe. Ops outside that context will not be thread-safe. Will be glad to hear from others if this understanding is correct.
Comment: But the thing is, the reading is done directly: when you access `c.counts` you are not using the `ExecutionContext` at all.
Comment: c.counts is a mutable map so exposing it to the outside world is not a good idea. I updated the code by adding a get method and making map private. The gist is: all read/write to the mutable map must be guarded by ec. If that is not acceptable, use a concurrent data structure.
Comment: Yes, that was my whole point. This is much better now. Actually if OP can indeed adapt his code to use futures, this is the best solution in terms of ease of use and correctness (though not iintterms of speed).
Comment: I'm not sure I'd want to dedicate a thread to one counter, but maybe if it was doing other drudge work; a get could wait in a long queue. But if hourly rates correlate with SO rep, this is a great deal. Also satisfies the no-dependency requirement, if Akka is a dependency.
Comment: Of course if this is literaly just to perform increments, this is overkill. For something more substantial in terms of computation, that is a nice enough solution. A fully generic solution would actually use a fixed set of one-thread pools (a pool of thread pools) and just make sure that each instance of the map always uses the same one-threa pool. This would prevent the thread count from explosing (as the number of maps grow) while still ensuring that there is no thread-unsafe access.
Comment: @RégisJean-Gilles Yes. I +1 this + yours, which I mashed up to some effect below, for some value of some.
Answer: You're asking for trouble if your map is just sitting there as a val.  If it meets your use case, I'd recommend something like
class Counter {
  private[this] myCounts = MMap.empty[String, Int].withDefaultValue(0)
  def counts(s: String) = myCounts.synchronized { myCounts(s) }
  def add(s: String) = myCounts.synchronized { myCounts(s) += 1 }
  def getCounts = myCounts.synchronized { Map[String,Int]() ++ myCounts }
}

for low-contention usage.  For high-contention, you should use a concurrent map designed to support such use (e.g. java.util.concurrent.ConcurrentHashMap) and wrap the values in AtomicWhatever.


What would be a good harmonic progression for this example?

Question: For my advanced theory seminar class this semester, I am being introduced to formal counterpoint writing procedures. For a homework assignment this week, I have to write a good bass line (First Species) to go against this given melody line. The first step is I am supposed to determine the "implied harmonic progression."
We're in C major here. I hear the first group of eighth notes as a I chord and the next group as a IV chord. Is it normal for IV to go to the vi chord? That is not one of the common progressions I was taught.
I'd appreciate any help. Thanks in advance!
Comment: IV-vi and ii-vi are commonplace enough (at least compared to iii) in my experience.
Comment: (It's years since I did this stuff.YEARS!) Yes, C and F in the first bar, I think. Then you could try | G#F#G# A  B C B D | C Bb A G etc, Maybe? The first half bar should be springy, to contrast with the step-wise stuff. Like C(low one) G E C(high one)
Comment: What about this bass line?  c e | f f# | g g, | c
Answer: I hear it as:
C  F | Am Dm | C/E G7 | C
I IV | vi ii | I6  V7 | I
But there are other possible interpretations as well.


Android Curl Rest

Question: I've developed an android app and an external server node js link with a mongodb db . How I manage to link them ? I need to call a CURL function for example during the building of the app
<code>$ curl -X POST -H "Content-Type: application/json" --data '
  {
"email":"email@example.com",
"PreferedBook":[["Harry Potter e la pietra filosofale","J.K.Rowling","26/06/1997"]],
"BooksRead": ["La pietra filosofale"],
"notes":[],
"genre": ["Thriller", "Fantasy"],
"numberorReviews":0
</code>
}
' http://localhost:4002/readers
Answer: I manage to solve the issue through the Retrofit library! In particular I follow that link https://square.github.io/retrofit/ that let me to see how we can interact with my server that makes requests to the non relational database mongodb

Android Curl Rest


How to extract information from a scatterplot matrix when you have large N, discrete data, & many variables?

Question: I'm playing around with the breast cancer dataset and created a scatterplot of all attributes to get an idea for which ones have the most effect on predicting the class malignant (blue) of benign (red).
I understand that the row represents x axis and column represents y axis but I can't see what observations I can make about the data or the attributes from this scatterplot.
I'm looking for some help to interpret/make observations about the data from this scatterplot or if I should be using some other visualization to visualize this data.

R code I used
link   <- "http://www.cs.iastate.edu/~cs573x/labs/lab1/breast-cancer-wisconsin.arff"
breast <- read.arff(link)
cols   <- character(nrow(breast))
cols[] <- "black"
cols[breast$class == 2] <- "red"
cols[breast$class == 4] <- "blue"
pairs(breast, col=cols)

Comment: Your two-colour scatters can make fine sense if you jitter (add noise) your piles of points.
Comment: That is kind of what I thought. I tried plotting a boxed barplot but that wouldnt be useful in seeing which attribute has most effect on the class right...? Looking for help on what type of visualization would give some meaningful information.
Comment: jitter means to edit your plot, so that overlying points are placed beside eachother to not obscure the view of one datapoint over the other. it's often used in R plotting functions.
Comment: You're right: it's hard to see much in this. Since all your variables appear to be discrete, with relatively small numbers of categories, it is impossible to determine how many symbols are piled up to form each distinctly visible symbol. That makes this particular image of little value in assessing anything.
Comment: @ttnphns I don't understand what you mean by "jitter your piles of points"
Comment: see `?jitter` in R.
Comment: Possibly related: [Exploring a scatter-plot matrix for many variables](http://stats.stackexchange.com/q/64789/7290).
Answer: There are a number of issues that make it difficult or impossible to extract any usable information from your scatterplot matrix.
You have too many variables displayed together.  When you have lots of variables in a scatterplot matrix, each plot becomes too small to be useful.  The thing to notice is that many plots are duplicated, which wastes space.  Also, although you do want to see every combination, you don't have to plot them all together.  Notice that you can break a scatterplot matrix into smaller blocks of four or five (a number that is usefully visualizable).  You just need to make multiple plots, one for each block.

Since you have a lot of data at discrete points in the space, they end up stacking on top of each other.  Thus, you cannot see how many points are at each location.  There are several tricks to help you deal with this.

The first is to jitter.  Jittering means adding a small amount of noise to the values in your dataset.  The noise is taken from a uniform distribution centered on your value plus or minus some small amount.  There are algorithms for determining an optimal amount, but since your data come in whole units from one to ten, $.5$ seems like a good choice.
With so much data, even jittering will make the patters hard to discern.  You can use colors that are highly saturated, but largely transparent to account for this.  Where there is a lot of data stacked on top of each other, the color will become darker, and where there is little density, the color will be lighter.
For the transparency to work, you will need solid symbols to display your data, whereas R uses hollow circles by default.

Using these strategies, here is some example R code and the plots made:
# the alpha argument in rgb() lets you set the transparency
cols2 = c(rgb(red=255, green=0, blue=0,   alpha=50, maxColorValue=255),
          rgb(red=0,   green=0, blue=255, alpha=50, maxColorValue=255) )
cols2 = ifelse(breast$class==2, cols2[1], cols2[2])
# here we jitter the data
set.seed(6141)  # this makes the example exactly reproducible
jbreast = apply(breast[,1:9], 2, FUN=function(x){ jitter(x, amount=.5) })
jbreast = cbind(jbreast, class=breast[,10])  # the class variable is not jittered

windows()  # the 1st 5 variables, using pch=16
  pairs(jbreast[,1:5], col=cols2, pch=16)

windows()  # the 2nd 5 variables
  pairs(jbreast[,6:10], col=cols2, pch=16)

windows()  # to match up the 1st & 2nd sets requires more coding
  layout(matrix(1:25, nrow=5, byrow=T))
  par(mar=c(.5,.5,.5,.5), oma=c(2,2,2,2))
  for(i in 1:5){
    for(j in 6:10){
      plot(jbreast[,j], jbreast[,i], col=cols2, pch=16,
           axes=F, main="", xlab="", ylab="")
      box()
      if(j==6 ){ mtext(colnames(jbreast)[i], side=2, cex=.7, line=1) }
      if(i==5 ){ mtext(colnames(jbreast)[j], side=1, cex=.7, line=1) }
      if(j==10){ axis(side=4, seq(2,10,2), cex.axis=.8) }
      if(i==1 ){ axis(side=3, seq(2,10,2), cex.axis=.8) }
    }
  }

Answer: It is difficult to visualize more than 3-4 dimensions in a single plot.  One option would be to use principal components analysis (PCA) to compress the data and then visualize it in the main dimensions.  There are several different packages in R (as well as the base prcomp function) that make this syntactically easy (see CRAN); interpreting the plots, loadings, is another story, but I think easier than a 10 variable ordinal scatterplot matrix.
Comment: Thanks for suggestion on PCA. I did not know about it. How would I interpret the image you posted? Does it mean that all the attributes that are clumped together in a group would be of some importance?
Answer: I'm not sure if this is of any help for you, but for primary EDA I really like the tabplot package. Gives you a good sense of what possible correlations there may be within your data.
install.packages("tabplot")
tableplot(breast) # gives you the unsorted image below
tableplot(breast, sortCol="class") # gives you a sorted image according to class

Comment: how would one interpret this tabplot? From the second tabplot it looks like columns 2, 3, 4, and 7 behave very similar to each other?
Comment: Is this for an assigment/homework of some kind? If so, please refer to the metas for the rules etc on getting help with assigments.
My brief reply: a) I have no clue what all the different values mean in the columns because I have not studied the dataset description, b) if I were simply to describe what I see, I'd say: class 4 seems to be associated with higher values of each column/variable and vice a versa.


Existence of a bounded function satisfying a second order differential equation

Question: This question is a variation version from here.
Let $\phi:\mathbb{R}\mapsto\mathbb{R}$ be the standard normal density, $$\phi(x)=\frac1{\sqrt{2\pi}}e^{-\frac{x^2}{2}}, \forall x\in\mathbb{R}.$$
Given $0<\sigma\le 1$. I am working with the differential equation
$$\alpha''(u) [\phi(u) + \frac 1\sigma \phi(u/\sigma)] - \alpha'(u) [u\phi(u) + \frac 1{\sigma^3} u\phi(u/\sigma)] - \alpha(u)  [\phi(u) + \frac 1{\sigma^3} \phi(u/\sigma)] = \frac 1{\sigma^5} u\phi(u/\sigma).$$
I am looking for a solution of the above equation such that its $3$-rd derivative is bounded.
What I know so far are:

If the boundedness condition of $3$-rd derivative is ignored, then of course the ODE above has a general solution. The question is, how to choose a solution satisfying the boundedness condition.
For $\sigma=1$, I could take $\alpha(u)=-\frac14u$ that satisfies all conditions. I got this function because in this case the general solution for the above ODE is $\alpha(u)= -\frac 14 u + (a + b \Phi(u))/\phi(u)$. So we can choose $a=b=0$. However, for $\sigma<1$, it makes my problem much harder. Any suggestion?
Comment: I am doubtful as to whether there is a solution for $\sigma < 1$ that is not coercive. If you take, say, $\sigma = 1 - \epsilon$ then expand where you can in your ODE for very small $\epsilon$ you get:
$$0=(-e^{u^2 \epsilon } -1-\epsilon)\alpha ''(u)+u \left(e^{u^2 \epsilon }+3 \epsilon +1\right) \alpha '(u)+\alpha (u) \left(e^{u^2 \epsilon }+3 \epsilon +1\right)+u \epsilon +u$$
Comment: I tested a large number of solutions numerically and they all look good near zero but are coercive (apperently exponentially). The problem is that you can't get rid of the exponential with $\epsilon$ not zero. There's probably a theroem somewhere that proves this that I do not know.
Comment: @amcalde: Thanks for your help. Do you mean that the solution behaves like $e$ to power of something? So, is it impossible to have $\alpha'''$ is bounded?
Comment: I can't prove that it's impossible but for all appearances it looks like $\alpha \approx e^{x^2}$. This would make all derivatives unbounded.
Comment: OK, thanks @amcalde for your time and suggestions
Answer: An approach (not yet a full solution):
using my approximation in the comment write
$$\alpha''(x)=\alpha'(x)\left(x\frac{1+3\epsilon+e^{\epsilon x^2}}{1+\epsilon+e^{\epsilon x^2}}\right)+\alpha(x)\left(\frac{1+3\epsilon+e^{\epsilon x^2}}{1+\epsilon+e^{\epsilon x^2}}\right)+x\frac{1+\epsilon}{1+\epsilon+e^{\epsilon x^2}}$$
Since we have the second derivative of $\alpha$ interms of the first two. We can likewise find the third derivative in terms of the first two.
Take one more derivative and substitue for $\alpha''(x)$ where ever it appears. Simplifying, I get
$$\alpha'''(x)=\left(\alpha'(x) (e^{2 x^2 \epsilon} (2 + x^2) + (2 + x^2 + 3 x^2 \epsilon) +
  e^{x^2 \epsilon} (4 + 2 x^2))+ \alpha(x) x \left(e^{2 x^2 \epsilon }+2 e^{x^2 \epsilon }+1\right) + 2 x^2 \epsilon  \left(1-e^{x^2 \epsilon }\right)+\left(x^2+1\right) \left(e^{x^2 \epsilon }+1\right)\right)/\left(e^{x^2 \epsilon }+1\right)^2$$
Now let $x\rightarrow \infty$. The equation simplifies to
$$\alpha'''(x) =\frac{\alpha'(x) x^2 e^{2 x^2 \epsilon}+ \alpha(x) x e^{2 x^2 \epsilon} + x^2 e^{x^2 \epsilon }}{e^{2x^2 \epsilon }} \\ \Rightarrow \alpha'''(x) =\alpha'(x) x^2 + \alpha(x) x + x^2 e^{-x^2 \epsilon } \\ \Rightarrow \alpha'''(x) =\alpha'(x) x^2 + \alpha(x) x $$
It seems that for your $3$rd derivative to be bounded you at least need bounded solutions to the above equation. I haven't worked these out yet (or proved they don't exist).
Comment: Upon inspection, these do not appear to have no bounded solution for $x\rightarrow \infty$.
Comment: Thank a lot for your help. Could you tell me what $\varepsilon$ here?
Comment: Here $\sigma = 1 - \epsilon$. So this shows that you cannot have a bounded $3$rd derivative when $\epsilon$ is non-zero.


Find an example to a function $f$ so $f>0$, $\lim_{x\to\infty} f(x)$ does not exist and $\int\limits_{1}^{\infty} f(x) dx<\infty$

Question: An example I instantly came up with is:
If $x\in \mathbb{Z}$ I say that $f(x)=1$
If $x\notin \mathbb{Z}$ I say that $f(x)=\frac{1}{x^2}$
Now, I am pretty sure that this example is correct. However, first I wondered if there is a simpler example. Second, we were taught that if a function $g$ is different than $f$ in a FINITE number of points, then $\int\limits_{a}^{b} f(x) dx=\int\limits_{a}^{b} g(x) dx$ (So the integral CAN'T be improper).
I was trying to say that $\int\limits_{1}^{\infty} f(x) dx=\lim_{M\to\infty} \int\limits_{1}^{M} f(x) $, and that for all $M\in \mathbb{R}$ we have a finite number of points where we change the value of $g(x)=\frac{1}{x^2}$, which equals $\lfloor M \rfloor -1$.
This way, I am not quite sure that I use the theorem properly, but unsure if there is a problem. I only use it that way for proper integrals, I think, but again not sure.
Any input will be appreciated.
Answer: Yes. By your definition of $f$, $f$ differs from $g$ at finitely many points
on the interval $[1, M]$ whence
$$
\int_1^M f(x)\, dx=\int_1^M g(x)\, dx
$$
for each $M>1$. Now let $M\to \infty$ to deduce the result.
Answer: $$f(x)=\sum_{n\geq 1}\exp\left[-n^4(x-n)^2\right] $$
does the job. For any $m\in\mathbb{N}^+$ we have $f(m)\geq 1$, but
$$ \int_{1}^{+\infty}\exp\left[-n^4(x-n)^2\right]\,dx<\int_{\mathbb{R}}e^{-n^4 x^2}\,dx=\frac{C}{n^2} $$
so $f(x)\in L^1(\mathbb{R}^+)$. In order to prove that $\lim_{x\to +\infty}f(x)$ does not exist it is enough to consider the behaviour of $f(x)$ at the elements of $\frac{1}{2}+\mathbb{N}$, in order to deduce $\lim_{m\to +\infty}f\left(\frac{1}{2}+m\right)=0$.
Answer: If you want a continuous example, imagine a function that's either 0 or has triangular peaks occurring a $x\in\mathbb{Z}$ with width $1/x^2$ and height 1.


Supervised machine learning method to forecast energy demand according to multiple variables

Question: I need the best machine learning method/algorithm/technique to predict energy consumption. The given training dataset consists of 2 years of energy consumption, with entries every 15 minutes. In addition, weather data (radiation, humidity, temperature and wind speed) are given every hour.
Now as input, I have a few entries with exactly the same format as the training dataset, except, the power consumption has to be predicted as accurately as possible.
The dataset contains several variables: time, day of the week, week of the year, radiation, humidity, temperature, wind speed and power demand
The goal is to be give the same variables but to predict power demand
The algorithm must be:

supervised machine learning
interpolated the weather (radiation, humidity, temp and wind speed) before training because they are only given per hour while we need per 15minutes
divide the historic data into two sets, a training set (from which the application can learn) and a test set, on which to test the accuracy of the forecasts.
expect that not only weather but also time of day, day of week and week of the year will play an important role in the forecasting
not expect all the variables will play an equal role, including all possible input variables may even reduce performance

P.S. My apologies guys, I have no experience in machine learning at all, I just need a machine learning method/programming library to forecast the most accurate power comsumption, thanks!!
Comment: Welcome to CrossValidated. You may profit from reading [this page](http://stats.stackexchange.com/help/how-to-ask) on asking a good question. What have you already tried?
Comment: There is no one algorithm to rule them all. The only way to know what works best is to try several approaches. Every other suggestion would be a heuristic at best.
Answer: You may want to start by doing some exploratory analysis before you dive into making a prediction model or put this into a prediction modelling framework.
Try to plot the data to see if you can spot whether some trends appear. It is likely that some of the explanatory variables that you have are completely redundant. Depending on the amount of data that you have, this may cause your prediction model to overfit if you do not ignore them.
Energy consumption is most likely dependent on the weather w.r.t. temperature and humidity, (although wind also plays a part). E.g. people turn on their radiators when it is cold and AC when it is warm. Time of day is also important, since when people are not at home during the day, they might not be using as much energy in their homes etc.
Instead of using the time of the day as a variable you can split it into fewer factors, e.g. night, morning, working day, evening. This will help w.r.t. overfitting.
You might also want to introduce factor variables which tell whether a given day is a national holiday or not, i.e. on Christmas or during the super bowl energy consumption will likely spike. It is hardest to model these big spikes/outliers in your data, you need to insert your expert knowledge on the problem into the equation to account for this.
This is not an easy problem and usually the method that you use is not what is most important. What matters most is how you preprocess your data and how you add in your own assumptions about the situations (e.g. the holidays).
The easiest way to go is to use a linear model or a random forest. Random forests are easy to use in most languages and are rather safe for not to overfit.
You can also get something from the random forest which is called variable importance, it shows you how "important" the variables are for making predictions and may help in interpreting the results.
Hope this helps, just don't dump this into some model head first, think about the problem and what matters for these predictions. Also look at the residuals after you have fitted the model.
Answer: You can try Linear Regression, SVM or MLP. They are good for energy forecasting.
Comment: please try to explain more in detail.


Multi relation classification

Question: I'm ph.d. scholar in statistics. I have given task to learn classification algorithm. I successfully completed feature selection with filter and wrapper methods with weka. But it is for single table like iris or weather.
My question is that how to implement these techniques if I have to work on multiple table where all table are joined with primary and foreign keys.
If I select on table as classification then how to used other tables which are related to main table?
I need ur help to understand this question.
Comment: this is a database question and not a machine-learning/classification question right?
Answer: You can join the tables like so,
TABLES
<code>**APP_BLOG**
BLO_ID BLO_TITLE BLO_CATEGORY BLO_STATUS
1      lorem     1           1

**APP_CATEGORY**
CAT_ID CAT_NAME CAT_STATUS
1      Design   1
</code>
MYSQL
<code>SELECT * FROM app_blog
LEFT JOIN app_categories ON blo_category = cat_id
</code>

Multi relation classification


How do I get the bundle name by route?

Question: I would like to pass variables to twig that depend on certain routes or node types (bundles) (a user page, a comment, a page or a custom content type). I used the name of the route (entity.comment.edit_form, entity.user.canonical) for that purpose.
Now I need to exclude some node types (i.e. I can't use just entity.node.canonical for all cases, I need to create a special condition for certain types of nodes). How do I get node type (bundle?) by route name/object?
My code is in the .theme file in HOOK_preprocess_page(&$variables)
UPD: Okay, I have discovered that there is actually $variables['node'] which contains what I need in $variables['node']->getType()
But let's say I have just the route, how do I get an ID from it and load a node?
Answer: Drupal is providing such a variable for the html template:
/**
 * Implements hook_preprocess_HOOK() for HTML document templates.
 */
function node_preprocess_html(&$variables) {
  // If on an individual node page or node preview page, add the node type to
  // the body classes.
  if (($node = \Drupal::routeMatch()->getParameter('node')) || ($node = \Drupal::routeMatch()->getParameter('node_preview'))) {
    if ($node instanceof NodeInterface) {
      $variables['node_type'] = $node->getType();
    }
  }
}

This code works in your HOOK_preprocess_page(&$variables) as well.
UPD: getParameter('node') gets already a loaded node. So you don't need to get the ID to load the node, but if you need the ID then use getRawParameter('node').

How do I get the bundle name by route?


How do i change the max attachment size in exchange 2007?

Question: I'm confused. i've changed the transport limits in organisation configuration>global settings> transport settings. I've also altered it in the send and receive connectors max message size.
When i attach a file over 10mb in outlook it says attachment size exceeds the allowable limit.
i can't find where i'm supposed to change it. I'm sure it's easy...
Answer: If you're running Exchage 2007 SP1 changes you made with Set-TransportConfig should have copied to the global settings in AD. If you're not running Exchange 2007 SP1, then you're going to need to change these values in AD using something like ADSIEDIT.
First, here's a good overview of the process w/ screenshots: http://exchangepedia.com/blog/2007/09/exchange-server-2007-setting-message-size.html
If you're still ing Exhcange 2007 RTM, here's an article that will describe changing the global size limit: http://technet.microsoft.com/en-us/library/bb310771.aspx
You're best off going to Exchange 2007 SP1 (or SP2) if you're still running RTM.
Edit:
Could you post a link to the output of a "Get-TransportConfig", "Get-SendConnector | fl", "Get-ADSiteLink | fl", and "Get-RoutingGroupConnector | fl" from the Exchange Management Shell?
Comment: i am on sp1 and have followed the instructions and set everything to 50mb but outlook still won't let me attach anything over 10mb.
Comment: Hmm. What's the specific error you're getting back? It's likely there's still a limit set somewhere, but I'm drawing a blank at the present moment.
Comment: outlook it says "attachment size exceeds the allowable limit". before i upgraded to 2007 i could send large files so it must be exchange's doing...
Answer: Its the  MaxSubmitMessageSize property that you need to change, in Exchange 2007 this is read from 3 places, in this order:

Individual Mailbox
Transport Settings container
Organisation Settings container

To change these use the following commands inside the Exchange Management Shell
Transport Container
This will set the value for all users, in this case to 50Mb
set-transportconfig -maxsendsize 50Mb

Individual Mailbox
 set-mailbox 'mailboxName' -maxsendsize 50Mb

Comment: Do remember that if you're running Exchange 2007 RTM the "Set-TransportConfig" applet won't set the organization setting. That's "fixed" in SP1. You'll have to use ADSIEDIT (or some other tool to manipulate arbitrary objects in the AD) for that in an Exchange 2007 RTM environment.
Answer: I'm on:
Exchange Server 2007
Microsoft Corporation
Version: 08.01.0340.000
I used the following in the syntax in the "Exchange Command Shell":
Set-TransportConfig -MaxReceiveSize 50mb
This changed my "MaxReceiveSize" from 10mb to 50mb,  see the Before and After "TransportConfig".
Before:
ClearCategories                : True
DSNConversionMode              : UseExchangeDSNs
GenerateCopyOfDSNFor           : {5.4.8, 5.4.6, 5.4.4, 5.2.4, 5.2.0, 5.1.4}
InternalSMTPServers            : {127.0.0.1}
JournalingReportNdrTo          : <>
MaxDumpsterSizePerStorageGroup : 18MB
MaxDumpsterTime                : 7.00:00:00
MaxReceiveSize                 : 10MB
MaxRecipientEnvelopeLimit      : 5000
MaxSendSize                    : 50MB
TLSReceiveDomainSecureList     : {}
TLSSendDomainSecureList        : {}
VerifySecureSubmitEnabled      : False
VoicemailJournalingEnabled     : True
WritingBrandingInDSNEnabled    : True
Xexch50Enabled                 : True

[PS] C:\Windows\System32>Set-TransportConfig -MaxReceiveSize 50mb

After:
ClearCategories                : True
DSNConversionMode              : UseExchangeDSNs
GenerateCopyOfDSNFor           : {5.4.8, 5.4.6, 5.4.4, 5.2.4, 5.2.0, 5.1.4}
InternalSMTPServers            : {127.0.0.1}
JournalingReportNdrTo          : <>
MaxDumpsterSizePerStorageGroup : 18MB
MaxDumpsterTime                : 7.00:00:00
MaxReceiveSize                 : 50MB
MaxRecipientEnvelopeLimit      : 5000
MaxSendSize                    : 50MB
TLSReceiveDomainSecureList     : {}
TLSSendDomainSecureList        : {}
VerifySecureSubmitEnabled      : False
VoicemailJournalingEnabled     : True
WritingBrandingInDSNEnabled    : True
Xexch50Enabled                 : True

Answer: Answer based on Exchange 2003, but probably valid for 2007 as well: there may be size restriction on the individual account (look up user in active directory users & computers -> exchange general -> delivery restrictions).
Answer: Ok here are some outputs from the manangement shell. I have to put this here since it's too long for a comment...
Get-TransportConfig:
ClearCategories                : True
DSNConversionMode              : UseExchangeDSNs
GenerateCopyOfDSNFor           : {5.4.8, 5.4.6, 5.4.4, 5.2.4, 5.2.0, 5.1.4}
InternalSMTPServers            : {127.0.0.1}
JournalingReportNdrTo          : <>
MaxDumpsterSizePerStorageGroup : 18MB
MaxDumpsterTime                : 7.00:00:00
MaxReceiveSize                 : 50MB
MaxRecipientEnvelopeLimit      : 5000
MaxSendSize                    : 50MB
eceiveDomainSecureList     : {}
TLSSendDomainSecureList        : {}
VerifySecureSubmitEnabled      : False
VoicemailJournalingEnabled     : True
WritingBrandingInDSNEnabled    : True
Xexch50Enabled                 : True

Get-SendConnector | fl
AddressSpaces                : {smtp:*;1}
AuthenticationCredential     :
Comment                      :
ConnectedDomains             : {}
ConnectionInactivityTimeOut  : 00:10:00
DNSRoutingEnabled            : True
DomainSecureEnabled          : False
Enabled                      : True
ForceHELO                    : False
Fqdn                         : [our domain]
HomeMTA                      : Microsoft MTA
HomeMtaServerId              : JUDGES
Identity                     : Windows SBS Internet Send JUDGES
IgnoreSTARTTLS               : False
IsScopedConnector            : False
IsSmtpConnector              : True
LinkedReceiveConnector       :
MaxMessageSize               : 50MB
Name                         : Windows SBS Internet Send JUDGES
Port                         : 25
ProtocolLoggingLevel         : None
RequireTLS                   : False
SmartHostAuthMechanism       : None
SmartHosts                   : {}
SmartHostsString             :
SourceIPAddress              : 0.0.0.0
SourceRoutingGroup           : Exchange Routing Group (DWBGZMFD01QNBJR)
SourceTransportServers       : {JUDGES}
UseExternalDNSServersEnabled : False

Get-ADSiteLink | fl
Cost              : 100
ADCost            : 100
ExchangeCost      :
MaxMessageSize    : unlimited
Sites             : {Default-First-Site-Name}
AdminDisplayName  :
ExchangeVersion   : 0.0 (6.5.6500.0)
Name              : DEFAULTIPSITELINK
DistinguishedName : CN=DEFAULTIPSITELINK,CN=IP,CN=Inter-Site Transports,CN=Site
                s,CN=Configuration,DC=contra,DC=local
Identity          : contra.local/Configuration/Sites/Inter-Site Transports/IP/D
                EFAULTIPSITELINK
Guid              : ca9984b7-5541-471b-9914-be56515bef87
ObjectCategory    : contra.local/Configuration/Schema/Site-Link
ObjectClass       : {top, siteLink}
WhenChanged       : 18/12/2008 14:17:30
WhenCreated       : 18/12/2008 14:17:30
OriginatingServer : JUDGES.contra.local
IsValid           : True

Get-RoutingGroupConnector | fl - returns nothing. just a new command prompt...
Answer: I've found this article useful when it comes to understanding the various message size limits in Exchange 2007.


Is it always true that $f=g+h$ is not convex when $g$ is convex and $h$ is neither convex or concave?

Question: Suppose we have the function $$f=\frac{x^2}{2} + 10y^2 - 10xy$$ where $$g=\frac{x^2}{2} + 10y^2$$ and $$h= - 10xy$$.
In this case $f$ is a sum of a convex function $g$ and a function $h$ which is neither convex or concave. And it turns out that this particular function $f$ is not convex.
Is a function $f$ always not convex when it is written as a sum of a convex function and a function which is neither convex or concave?
Answer: No.
$$
f(x)=x^4, g(x)= x^2, h(x)= x^4-x^2.
$$
Here $f, g$ are convex, $h$ is neither convex nor concave [since $h''=0 \iff 6x^2 = 1$].


Drawing a graph of three nodes such that $\forall x \in V : \forall y \ (x, y) \in E $ (and two variants)

Question: How will these three graphs look like? It's said that each have 3 nodes. If the three graphs fulfill the following rules, how can I draw them? I still cannot interpret what the statements below mean.
$$G_1 : \forall x \in V : \forall y \in V \ (x, y) \in E $$
$$G_2 : \exists x \in V : \forall y \in V \ (x, y) \in E $$
$$G_3 : \exists x \in V : \forall y \in V \ (x, y) \notin E $$
Comment: $G_1$ is like a complete graph, and $G_2$ is like a star graph...
Comment: how did you come up to that conclusion. Can you explain please?
Comment: $G_1$: For each vertex (node) $x$ we know there is an edge $(x, y)$ between it and any other graph vertex $y$.
Comment: $G_2$: There is a vertex $x$ such that there is an edge $(x, y)$ between it and any other graph vertex $y$.
Answer: Case $G_1$: A complete graph is a graph in which each pair of graph vertices is connected by an edge  [Ref]. It seems that your $G_1$ following this definition.


Question about the definition of topological entropy (book: Brin & Stuck)

Question: For a compact metric space $(X,d)$ and a continuous map $f\colon X\to X$, the book Introduction to Dynamical Systems written by M. Brin and G. Stuck uses the expression $$h_{\varepsilon}(f):=\limsup_{n\to\infty}\log(\text{cov}(n,\varepsilon,f))$$ in their definition of topological entropy. Later they prove that you can replace limsup by lim, because apparently the lim of the sequence above converges to a finite number. So why do they use the limsup in their definition? I thought that the limsup may also diverge to infinity.
Comment: What is the meaning of "cov"?
Comment: @FShrike It's the minimum cardinality of an open cover each of whose elements have diameter less than $\epsilon$ with respect to the Bowen metric $d_n^f$ (e.g. as mentioned here: https://math.stackexchange.com/q/4345039/169085).
Comment: See e.g. https://www.math.stonybrook.edu/~jack/DYNOTES/dn7.pdf , p. 7-8 for further details.
Comment: (To be more accurate perhaps I should drop "open".)
Comment: @AlpUzman Thank you for the reference
Answer: Probably because any sequence $x_n$ in $\mathbb R$ (so also $x_n = \log(\operatorname{cov}(n,\varepsilon,f)$) (for some fixed $f$, $\varepsilon$) has a well-defined $\limsup$ (which can be $+\infty$). So first you have a well-defined (extended) number and then you can discuss its other properties, like whether it's always finite etc.
Comment: What is the meaning of "cov"


How to use  tag in views?

Question: I have a site on Drupal 7, where I'm using Views with Multilingual settings.
I have 2 languages, Russian and English.
On the front page, I have created a "Latest News" block with Views.
Each news item has a link to the full article like the following ones:

example.com/en/news/1
example.com/ru/news/1

This block is also shown on some other pages, such "Services - > Service 1"  shown at example.com/en/services/service-1.
The problem is that on my block I use global text to format the output of the latest news; the link is built using the following:

[title]

It works fine on the front page, but when I'm on the Services page, the news link is similar to example.com/en/services/news/1,which is incorrect; Drupal gives me an error about a not existing page.
Is there a way to reference the front page with any tag I can use in the "Global Text" settings?
Answer: You can use php filter, or install Token Filter module and then enable tokens in filter which you use (admin/config/content/formats). Token for front page is [site:url] so you should write your link like follow:

[title]

How to use  tag in views?


Convert single backslash to double backslash

Question: I have a list containing directories: ("..\b\c.txt", "..\b\d.txt").
I was planning to use .split() method to have another list of the directory components separated by "\", but I'm not having success mostly due to "\" usage. Thus, the final result will be something like this ("a", "b, "c.txt") ...
I do understand \ being a escape character and the difficulties reported by this link, but I'm not understanding if it's possible to convert the entire list to raw string. Can anyone help?
files = ('..\..\data\User\level1\level2\sun.png','..\..\data\User\level1\level2\description.txt')

I was testing something like this:
str = files[0].split("\")

Desired output: a list containing:
('data', 'User', 'level1', 'level2', 'sun.jpg')

Comment: Please show us your actual code, so we can fix any mistakes you have have made in it. Note that the [`os.path` module](https://docs.python.org/2/library/os.path.html) can do just about all could want when it comes to path handling, however.
Answer: If files is a literal, use raw literal notation then:
files = (
    r'..\..\data\User\level1\level2\sun.png',
    r'..\..\data\User\level1\level2\description.txt'
)

In this specific example, you managed to evade all of the known character escape sequences, but that was just lucky.
You can use "\\" to define a string with just a backslash:
files[0].split("\\")

Demo:
>>> files = (
...     r'..\..\data\User\level1\level2\sun.png',
...     r'..\..\data\User\level1\level2\description.txt'
... )
>>> files[0].split("\\")
['..', '..', 'data', 'User', 'level1', 'level2', 'sun.png']

If you wanted to split a path into parts, you probably should look at os.path.split() and the other functions in that module. Using such functions helps keep your code platform agnostic.
There is also os.sep and os.altsep, which would also help keep your code indepedendent of the OS.
Comment: Thanks I will look onto that. Regarding your first suggestion the problem is that the "files" list contains over 1000 paths, is there any way to make the raw literal notation to all the list?
Comment: No; string literals are parsed as you produce them; once the object has been created it is really too late to repair the damage.
Comment: Note that raw string literals are *just a notation*. They produce string object values just like regular string literals. Only the details of the notation differ.
Answer: It turns out you're not quite there yet with understanding \ as an escape character. The escape characters are not extra characters in the actual string, they're extra characters in the source code.
To create a string that contains one \ character in Python, you can use \ as an escape character like this:
"\\"

There are 2 characters between the quotes in the source code, but in the actual string, there is only the "escaped character", which is the second \.
Note that "raw strings" are similar: the difference is in the source code, not the actual string. The following are equal:
"abc\\def"
r"abc\def"

What I do when I have doubts about things like this is play around in the interactive mode of the interpreter, and I'd suggest you do the same. For example, if you were unsure of what the real contents of a string like "abc\\def" really are, you could try print-ing it.


Zend_Auth: How to check role in addition to username and password?

Question: I want my 'users' table in my database to contain users of all different levels (members, moderators, admins, etc). So a column in my 'users' table is role. I want to be able to check the role to see if they have permission to log in to special parts of the application. How can I do this? Here is my auth adapter so far:
protected function _getAuthAdapter($formData)
{
    $dbAdapter = Zend_Db_Table::getDefaultAdapter();
    $authAdapter  = new Zend_Auth_Adapter_DbTable($dbAdapter);

    $authAdapter->setTableName('users');
    $authAdapter->setIdentityColumn('username');
    $authAdapter->setCredentialColumn('password');

    $authAdapter->setIdentity($formData['username']);
    $authAdapter->setCredential(md5($formData['password']));

    return $authAdapter;
}

Answer: You may be trying to use Zend_Auth for a purpose it wasn't intended.
Zend_Auth is supposed to tell you whether a user is who he says he is, not whether they have permission to do a particular thing.
You're looking for Zend_ACL: http://zendframework.com/manual/en/zend.acl.html
Comment: I agree that Zend_Acl is probably better for the job, but I just need a temporary solution. I don't need a full fledged ACL just yet.
Answer: If you're not wanting to use Zend_Acl for this yet, try this:
protected function getAuthAdapter()
{
    if (null === $this->_auth)
    {
        $a = new Zend_Auth_Adapter_DbTable(
            Zend_Registry::get('db')
        );

        $a->setTableName('users')
          ->setIdentityColumn('email')
          ->setCredentialColumn('password');

        // Get the select object and
        // modify to check against whatever you want
        $s = $a->getDbSelect();
        $s->where('userType = ?', 'admin'); // Or whatever, you can see what I'm doing

        $this->_auth = $a;
    }

    return $this->_auth;
}

You can see that you can use getDbSelect() to get the actual Zend_Db_Select object that Zend_Auth is using and modify it as needed.
Comment: I haven't verified this yet, but this is exactly what I needed, thanks!


override CSS style or add to it?

Question: I have a template that has a lot of CSS formatting, but now when I try to add my text I cannot add any formatting to it. Within a paragraph, I try to put superscripts, italics, but nothing works. Is there a way around this?
Answer: Here's a little explaination about overiding CSS
I'll take for my example this simple HTML :

If you have, for example, a css like
#home{color : blue;}
.current{color : orange;}

The text will be blue since #home is "stronger"
If we put values to selector: id=10 class=5 node selector (div) = 1
so #home = 10 and is higher than .current wich equal 5, #homestyles will override.
you could use li.current but again, 5+1=6 wich is lower than an id.
But #home.current will equal 15! Wich will overide #home styles!
But if your color style is on the node itself within the attribute style="" you have to remove it with jquery or use !important :
.current{
    color: blue !important;
}

It will override EVERY css but it is not recommended.
Note that the value i am using are not the exact one, so .parentClass .class will maybe not over an id and i can't find the original values... But keep in mind that the more selective you are, the more chance you have to override a style.
At last, if you have 2 selector with the same value, the last one called will be the one overriding.
Use chrome inspector or firebug to see what's overriding what.
Comment: I found that  where not included in my CSS style sheet. I added and that solved the problem.

override CSS style or add to it?


Virtualized firewall under Hyper-V?

Question: We are currently considering installing an instance of pfSense on our Hyper-V R2 based server to act as a content filter, captive portal and general firewall.
Although it is usually bad practice to virtualise a firewall / gateway.. sometimes you gotta work with what you've got! :)
We've got 2 physical NICs.. 1 Facing the internet (WAN) and 1 facing our internal LAN.
How would one go about making sure all internet access goes through the pfSense VM?
Is there a configuration that eliminates any possibility of traffic coming in on the LAN NIC bypassing the pfSense VM?
Sorry if it's a silly question, I'm a developer by day :D
Comment: You're in bad need of a good IT guy/consultant. This stuff isn't difficult at all for someone who knows what they're doing, and it's going to be a world of hurt for someone who doesn't.
Comment: "Although it is usually bad practice to virtualise a firewall / gateway" <-- According to who??
Comment: @DanielUpton - When I started putting firewalls inside VM's I copped a lot of flack for it too. Some people (on Server Fault) were down-right rude to me about it. But what you'll find is that people who know what they're doing and do it properly won't make general hand-waving "all is bad" comments like that :) What you have here are two very high-rep users saying "go for it". I'd listen to them over some anonymous forum people.
Comment: Tends to be the first response i've seen on most forums :P This isn't for the company i work for BTW it's something i'm setting up for my church.. trying to expand my skill set :D
Answer: What Wesley said... Plus a diagram:
<code>              +----------------------------------+
              |    +----------+   +---------+    |     +----+ +----+ +----+
              |    | pfSense  |   | Host OS |    |     |    | |    | |    |
              |    |          |   |         |    |     | PC | | PC | | PC |
              |    +----------+   +---------+    |     |    | |    | |    |
              |         ^   ^          ^         |     +----+ +----+ +----+
              |         |   +------+   |         |        ^      ^      ^
              |         |          |   |         |        |      |      |
              |         V          V   V         |        V      V      V
+--------+    +---+   +-------+  +-------+   +---+      +-----------------+
|Internet|<-->|WAN|<->|WAN NET|  |LAN NET|<->|LAN|<----+|    LAN SWITCH   |
+--------+    +---+   +-------+  +-------+   +---+      +-----------------+
              |          Hyper-V Host            |
              +----------------------------------+
</code>
It's actually possible to use the same NIC on the Hyper-V Host for both WAN and LAN, but you'll need to setup vLANs and need a switch that supports them. It gets messy quickly and NICs are fairly cheap. A note on NIC chips, get a good one, like Intel, Broadcom, etc. Stay away from Realtek, Marvel, and most of the on-board chips on cheaper and DIY motherboards. They're nothing but trouble for virtualized environments.
Also, keep in mind that Hyper-V is a bare-metal Hypervisor. It is NOT a service that runs in Windows. What used to be the Windows installation on the machine becomes a special VM. This will not appear to be the case for simplicity and usability reasons, but comes into play when you do things like setup the Hyper-V Networking.
Comment: The ASCII-fu is strong with this one...
Comment: @WesleyDavid He Cheated.
Answer: Simply setting all PCs, switches, routers and etcetera network infrastructure to use the pfsense virtual machine as their default gateway will make all traffic flow through the content filter.
Certainly, someone could yank network cables out of the server and plug their PC straight into your WAN. You could set some kind of MAC filtering or 802.1x authentication to enact port level security. Of course, someone could just wire around that as well. The point being: There comes a time when you are merely relying on "I've got the passwords and the keys to the server room and you don't."
Simply setting up your gateway as the default gateway / router and not having any other routing options on the network prevents all outlets with the exception of someone storming your server closet and frobbing with cables.
Comment: Thanks! So do I set the default gateway of the Hypervisor to the VM too? what if a user on the LAN manually sets their default gateway to the IP of a router behind the VM (on the WAN)? .. you can probably tell this is all new to me!
Comment: Yes, in this setup the VM will be Hyper-V's gateway. However, I'm ever so slightly confused about your network design now. If done properly, there will be no router "behind" the VM. The VM is well and truly it's own machine. While, yes, the physical host will have a network cable on the WAN, it won't be a router; it won't have the proper routing tables. It won't respond to attempts at getting it to route packets.
Comment: Ah sorry was confusing myself for a moment then, your absolutely right, thanks for your answer!
Comment: @DanielUpton I hang my head in defeat to Chris's ASCII art. When you bestow the green checkmark to him, give him this... my only upvote. *dies dramatically*
Comment: @WesleyDavid My apologies, I didn't mean to steal your thunder, especially since you've got the right answer (too).
Comment: @ChrisS Hush - you're interrupting my dramatic death scene. =)

Virtualized firewall under Hyper-V?


Reporting results from a GLMER

Question: I have conducted a generalized linear mixed model (GLMM). For the output, see below. Normally (when reporting results from an ANOVA), I write something like this: $F(1, 116) = 6.09$, $p = .015$, $η2 = .04$.  But which statistical parameters (e.g. $\beta$, ...) do I use when reporting the results below (according to APA)?
<code>   747.5    788.7   -364.7    729.5      711

Scaled residuals:
    Min      1Q  Median      3Q     Max
-4.4527 -0.4184  0.2273  0.4934  2.0564

Random effects:
 Groups Name        Variance Std.Dev.
 id     (Intercept) 3.006    1.734
Number of obs: 720, groups:  id, 120

Fixed effects:
                                  Estimate Std. Error z value Pr(>|z|)
(Intercept)                     -9.985e-01  5.763e-01  -1.733   0.0832 .
Risikodarstellung                1.351e+00  7.763e-01   1.740   0.0819 .
Icon                            -7.898e-01  7.961e-01  -0.992   0.3211
Position                        -8.368e-07  1.183e-01   0.000   1.0000
Risikodarstellung:Icon          -9.109e-02  1.141e+00  -0.080   0.9364
Risikodarstellung:Position       3.297e-01  1.659e-01   1.987   0.0469 *
Icon:Position                    7.937e-01  1.822e-01   4.357 1.32e-05 ***
Risikodarstellung:Icon:Position -4.527e-01  2.673e-01  -1.694   0.0903 .
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Correlation of Fixed Effects:
            (Intr) Rskdrs Icon   Positn Rskd:I Rskd:P Icn:Ps
Rskdrstllng -0.746
Icon        -0.712  0.529
Position    -0.718  0.533  0.520
Rskdrstll:I  0.502 -0.675 -0.698 -0.363
Rskdrstll:P  0.502 -0.700 -0.371 -0.713  0.480
Icon:Positn  0.446 -0.325 -0.719 -0.649  0.495  0.477
Rskdrst:I:P -0.312  0.435  0.490  0.443 -0.719 -0.620 -0.670 ```

I
</code>
Comment: I don't know that there's a specific APA guideline for mixed models ... https://www.scribbr.com/apa-style/numbers-and-statistics/
Answer: As Ben noted in the comments, there are no APA standards for reporting mixed models. However, there are certainly a good number of important parts about your analysis that should be included if this is for a published manuscript. A useful paper on this subject is Meteyard and Davies, 2020, which notes on Page 16 what you should include:

Software and version used.
What data cleaning/wrangling was involved and whether or not your data meets the assumptions of mixed models.
Fixed and random effects are explicitly noted with important theoretical underpinnings noted for how the model was constructed.
Sample size in terms of units of observations (50 subjects x 10 items = 500 observations for crossed effects models).
Whatever model comparison was employed and the metrics that go with that (such as AIC/BIC).
Convergence issues and how they were handled.
The model equation and output (normally reported in a table), which includes pretty much everything it spits out (point estimates, standard errors, etc) as well as model fit metrics (pseudo R2 values for example).
If possible, the data and code itself.

Here is an example from an article which includes a good number of these things but not all of them. They include the fixed effects on the top and the random effects on the bottom, along with the beta coefficients, the standard errors, and the t-values that go with them (I only include part of it here because its very long:

And another example here, where you can see they included the actual equations, R2 values, and p values:

Reporting of these models varies a lot. More is always better, so include as much as possible and try to follow the guides I have cited here.
Citations
Best Practice Guides

Brown, V. A. (2021). An introduction to linear mixed-effects modeling in R. Advances in Methods and Practices in Psychological Science, 4(1), 1–19. https://doi.org/10.1177/2515245920960351
Harrison, X. A., Donaldson, L., Correa-Cano, M. E., Evans, J., Fisher, D. N., Goodwin, C. E. D., Robinson, B. S., Hodgson, D. J., & Inger, R. (2018). A brief introduction to mixed effects modelling and multi-model inference in ecology. PeerJ, 6, e4794. https://doi.org/10.7717/peerj.4794
Meteyard, L., & Davies, R. A. I. (2020). Best practice guidance for linear mixed-effects models in psychological science. Journal of Memory and Language, 112, 104092. https://doi.org/10.1016/j.jml.2020.104092

Example Studies

Al-Dajani, N., & Czyz, E. K. (2022). Suicidal desire in adolescents: An examination of the interpersonal psychological theory using daily diaries. Journal of Clinical Child & Adolescent Psychology. https://doi.org/10.1080/15374416.2022.2051525

Wang, L., Wang, J., Liu, D., & Lin, D. (2021). The role of metalinguistic awareness and character properties in early Chinese reading. Journal of Experimental Child Psychology, 210, 105185. https://doi.org/10.1016/j.jecp.2021.105185
Comment: Thank you very much!
Comment: One further question: If I have to report an effect size, which would you choose?
Comment: You can consider [pseudo R2 values for the model itself](https://doi.org/10.1098/rsif.2017.0213)
Comment: And [part R2](https://peerj.com/articles/11414) for the predictors.
Comment: Okay thanks. So would it look like this? ß = ___ , p = _____, part R2 = _____ (I know, that these are not the correct characters, but to get an idea). Or do I need a t-value instead of ß (ß stands for the estimates in my output I guess). Alternatively, I thought about reporting it like this: ß, p, Cohens D (ß/SE => which are both in my output)...
Comment: Another question regarding this: How can I report descriptive data? According to my teacher, I have to report things like this (example for ANOVA): The participants in the conditions ARR (M = 4.37, SD = 1.73) and ARR-Icon (M = 4.48, SD = 1.66) achieved a significantly higher total score compared to the individuals in the conditions RRR (M = 2.14, SD = 2.17) and RRR-Icon (M = 3.87, SD = 1.54), F(1, 116) = 20.23, p < .001, η2 = .14.    But I don't know how to apply this to my mixed model output.
Comment: The guides go over that to a degree. Minimum would be some general descriptives about participants but can be defined in any way that its useful to add.

Reporting results from a GLMER


Showing that $f(x) = \frac{1}{\sqrt x \ (|1+lnx|)} \chi_{(0,\infty)}$ is in $L^p_\mu \mathbb{(R)}$ iff $p=2$

Question: Let $f(x) = \frac{1}{\sqrt x \ (|1+lnx|)} \chi_{(0,\infty)}$
Show that $f \in L^p_\mu \mathbb{(R)}$ if and only if $p=2$.
This is an exercise in my Measure Theory course. I believe that I have proven that $f \in L^2_\mu \mathbb{(R)}$, but I cannot figure out a way to prove the other implication.
Comment: Hmmm... what would be a feature preventing $f$ to be in $L^1$, say?
Answer: here is the case for $2<p$:  $$||f||_{L_p}=\int_{(0,\infty)}\frac{1}{|x(1+\log(x))|}^pdx \geq \int_{(1,\infty)}\frac{1}{|x||1+\log(x)|}^pdx \geq \int_{(1,\infty)}\frac{1}{x(1+x)}^pdx \geq \int_{(1,\infty)}\frac{1}{x(x+x)}^pdx=\frac{1}{2^p}\int_{(1,\infty)}x^{p-2}dx = \frac{1}{2^p}\lim_{\alpha \rightarrow \infty}(-\frac{1}{1-p}+\frac{\alpha^{p-1}}{p-1})=\infty$$ since $p-1>1$


What creates this swooshing guitar effect?

Question: Hillel Slovak in Special Secret Song Inside by Red Hot Chili Peppers at 2:33

 creates a quick sound effect with his guitar that sounds like some effect put on feedback being panned rapidly.
How is that sound created? From what I know about making feedback, it takes a second to get started, and it wouldn't fade that nicely either.
I think this might be another example with Jimi Hendrix playing Wild Thing at Monterey: https://vimeo.com/220996511#t=98s, which also resembles one of the many effects on Exp off of Axis: Bold as Love at 1:15 (couldn't find link).
Answer: Sounds like a guitar, bridge pickup, lots of distortion playing high F and C on the 1st and 2nd strings 13th fret being dive bombed with a whammy bar and at the same time panned hard left to right...but hey, I could be wrong.
Comment: @bearacuda13 Great, now turn your head quickly from one side to the other for the panning effect, lol!
Comment: Nice ear! I broke out my Wal-Mart guitar that has a whammy, distorted it as much as possible, and it sounded pretty close!


How to prove the path has minimal length?

Question: Setting:Given an isosceles right triangle AEC,A=90 degree,AE=AC. Given r>0,we draw circle A and circle E with radius r. Let point G=the midpoint of the "quarter circle A". We draw a line L parallel to segment CG and the distance of CG and L is r. Let point M=the intersection of L and segment CE. We draw circle M with radius r.
Goal:We want to find point O on circle M and point P on circle E such that the sum GO+OP or GP+PO has minimal length.
Conjecture:(1)Clearly when r is large such that segment GE and circle M has intersection,then O、P are the intersection of GE and circle M、E,respectively. (see picture 1)
(2) when r is small such that segment GE and circle M has "NO" intersection,then the minimal sum is GO+OP (Not GP+PO),where points O、P satisfy: (a)An ellipse with two foci G、P is tangent to circle M at tangent point O (b)segment OE and circle E intersect at P (see picture 2)
p.s.:The hard part is the order of path can be G->circle M ->circle E  or G->circle E->circle M,and we want to find minimal path among the 2 cases. Hence we must prove:
Given arbitrary 2 points N on circle M and L on circle E,the inequality     GO+OP <GL+LN  is true.
I checked the conjecture (2) by software "Geogebra",it seems right,but I don't how to prove. Please help me,thanks.
Related pictures:
Answer: Once you choose $O$ on circle $M$, then the point $P$ on circle $E$ with the least distance from $O$ is the one on segment $OE$. Note that $OG+OP=OG+OE-r$: as $r$ is fixed, $OG+OP$ is minimum when $OG+OE$ is minimum.
Consider now the ellipse through $O$ with foci $G$ and $E$. If it isn't externally tangent to circle $M$, then some point $O'$ on that circle would be within the ellipse and $O'G+O'E<OG+OE$, that is point $O$ would not give the minimum sum of distances from $G$ and $E$. It follows that $O$ must be chosen so that the ellipse is externally tangent to circle $M$: in that case all other points on circle $M$ are external to the ellipse and $OG+OE$ is minimum.
By the way: I've found here a "simple" geometric construction of the ellipse.
Comment: Thanks for answer. Maybe my poor English confused readers.
The hard part is the order of path can be G->circle M ->circle E  or G->circle E->circle M,and we want to find minimal path among the 2 cases. Hence we must prove:

Given arbitrary 2 points N on circle M and L on circle E,the inequality
GO+OP <GL+LN  is true.

Thanks you.


React after refreshing page with param showing blank on production but works fine on local

Question: Anyone got any idea why is this happening on my local there is no errors everything compiles fine but on production it's just blank (screenshot)?
Comment: Which babel presets are you using? Are you exporting from Webpack in production mode?
Comment: "@babel/core": "^7.0.0-beta.40",
    "@babel/plugin-transform-react-jsx": "^7.0.0-beta.40",
    "babel-eslint": "7" and using docker to build in production
Answer: In the build index.html need to add <base href="/" />


NetBeans Remote Connection

Question: I'm trying to set netBeans remote project and I'm having pretty much trouble with it. I've started a PHP Application from Remote Server and in the last confirmation step it throws error on me.

No files available for download. Try to check Passive mode in the remote configuration.

In the log output it fails there:

> 215 UNIX Type: L8
> PORT 192,168,5,217,196,73
> 500 Illegal PORT command.

Did anyone have same problem with setting up remote connection? Please help.
Answer: To establish an FTP connection, choose either of the options below:

Turn off the Windows firewall.
Configure Windows Firewall for a passive mode FTP server as follows:

Open an Administrator command-prompt.
Click Start > All Programs > Accessories.
Right-click Command Prompt, and then click Run as Administrator.
Run the following command:
netsh advfirewall firewall add rule name=FTPService action=allow service=ftpsvc protocol=TCP dir=in

Disable stateful FTP filtering so that the firewall does not block any FTP traffic:
netsh advfirewall set global StatefulFTP disable

Comment: That was the thing that got me running a few years ago :D. Found it somewhere else.
Comment: Worked for me on Windows 10 using NetBeans 8.2. Thanks. +1.
Comment: This solution worked for me as well on windows 10 .. thanks
Answer: This seems to be the top answer whenever anyone is looking for how to set netbeans into passive mode. Despite the advice always being "set the ftp into passive mode" for those using Mac OS and Netbeans you may never seem to find it.

Right click on the project
Select Properties
Select Run Configurations
Select Manage
Select your_ftp_connection on the left column
Scroll down
Answer: The only way I fixed this was to switch to using SFTP. This obviously requires that you've set up SFTP (FTP over SSH) access to your server.
In the Run Configuration, when it asks you for the Remote Connection:

Click on 'Manage'
Click on 'Add...'
Select SFTP as the connection type
Fill in the rest of the details as if it were a normal FTP connection.
Answer: Turning plain FTP Netbeans connection into passive mode solved the problem for me.
Answer: Please Check Passive Mode; i had faced the same issue; after checking it; resolve this issue.
Answer: There is no way to find the passive mode in a OSX. It's a Netbeans bug... So I won't be able to develop on netbeans using my Mac. Already tried to download last version.
Comment: Really? Have you checked [Kenny West's answer](http://stackoverflow.com/a/28935977/3982001)?
Answer: For me the solution was to check Passive Mode on the client and to do following things on the server side
in /etc/vsftpd.conf
pasv_enable=Yes
pasv_max_port=10100
pasv_min_port=10090

then in terminal
iptables -I INPUT -p tcp --destination-port 10090:10100 -j ACCEPT
service iptables save
service vsftpd restart

NetBeans Remote Connection