Como excluir um registro de uma tabela na view sem deletar do banco de dados

Question: Estou desenvolvendo um sistema a nível de didático e na minha view eu tenho uma tabela que exibe os dados de um funcionário cadastrado pelo usuário.
Na view tem os botões editar e deletar, só que o deletar está apagando também os
o registro no banco de dados. Para manter a integridade dos dados eu preciso apagar somente o funcionário na view para o usuário e manter o registro salvo no banco.
Alguém pode me ajudar em como eu posso fazer isso?
Estou usando o Laravel 5.6 / PHP 7.2.3 / MySQL
Comment: Uma dica, crie um campo, exp: `hidden` como boolean, ai se quiser excluir da view é so setar como true, e listar na sua view mais ou menos assim: `$books->isHidden(false);`
Answer: O Laravel tem uma feature chamada Soft Deleting (exclusão lógica) que permite que se exclua um registro logicamente sem apagá-lo do banco de dados.
Para o Laravel reconhecer um registro como excluído é necessário que:

a tabela contenha o campo deleted_at (do tipo TIMESTAMP);
o Model use a trait Illuminate\Database\Eloquent\SoftDeletes
se adicione na propriedade $dates do Model o valor 'deleted_at'

Dessa maneira os registros que tiverem o campo 'deleted_at' IS NOT NULL. Serão considerados registros excluídos e não serão inclusos nos resultados do Eloquent.
Caso seja necessário mostrar todos os registros, incluindo os "excluídos", pode-se usar o seguinte método:
<?php

// Todos Models
App\Model::withTrashed()->all();

// Apenas excluídos
App\Model::onlyTrashed()->all();

Veja os Docs para mais informações.

Exemplo de classe:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Exemplo extends Model
{
    use SoftDeletes;

    protected $dates = ['deleted_at'];
}

Exemplo de migration:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateExemploTable extends Migration
{
    public function up()
    {
        Schema::create('exemplo', function (Blueprint $table) {
            $table->primary('id');
            // ...
            $table->softDeletes();
        });
    }

    public function down()
    {
    }
}

Comment: Fernando, muito obrigado mesmo. No caso eu iria colocar o atributo deleted_at como boolen correto?
Comment: Na verdade é um `TIMESTAMP` onde o Laravel testa se for `NULL` é porque não foi excluído, e se não for `NULL` o campo tem a data da exclusão.
Se tu olhar o [código do migrations](https://github.com/laravel/framework/blob/ad52d1cc1fd314b4f617a5941bbb543f9f05e2e7/src/Illuminate/Database/Schema/Blueprint.php#L988) tu vai ver que quando se chama `$table->softDeletes()` o schema builder cria um `TIMESTAMP` mesmo.
Comment: Valeu mais uma vez, conseguir entender e irei aplicar aqui. Abraço.


How do I create a "More like this" block?

Question: Is there a way to create a "More like this" block with the Views, and the Search API Solr modules?
I saw this, but it doesn't work.
Answer: Here is the recipe for search_api_solr as per the OP. Note: both apachesolr and search_api_solr leverage Solr's builtin more like this feature. It is, therefore, not available to normal search.

Enable some modules: search_api, search_api_solr, search_api_views
Create a Search server of the Solr class.
Create a Search index (or use the Default node index) and point your Solr search engine at it.
Create a new view on your search index NOT on Search index.
eg:
Show *Default node index* sorted by *unsorted*
Continue and edit.
Reveal Advanced and Add a Contextual filter.
Filter on Search or scroll down to find Search: More like this.
Under When the filter is not available select Provide default argument: Content ID from URL.
Configure by selecting the Fields for Similarity that you want to determine likeness on.

http://drupal.org/node/1250304#comment-4870278
Comment: "9.Configure by selecting the Fields for Similarity that you want to determine likeness on."
I am interested in Taxonomy term likeness.How can I do that?thanks
Comment: @sokratis - If they are in the indexed in the search index (e.g. `default node index`), you can select them.
Comment: Also, note that the `search_api_views` module is bundled with the `search_api` module itself, not a separate contrib module.
Answer: You don't need anything to create the 'more like this block', just go to admin/structure/block/manage/apachesolr_search/mlt-001/configure.
However, you can follow this tutorial on how to create it with the Views module, but it's based on taxonomy terms.
Comment: Note: He is talking about using the Search API Solr module, not the Apache Solr module.
Comment: I not sure about the normal search module.  The only modules I know that provide that is the http://drupal.org/project/apachesolr and http://drupal.org/project/search_api_solr modules.
Comment: And for the normal seach module ?


Need to export multiple fields collections via views data export in XML

Question: I have my site set up to import CSVs and manual entry and exporting the key information into an XML feed/File using views data export.
I have a problem when I need to add a group of fields. The user can add as many of these groups of fields as they need and they should appear in the output in a single row as nested items.
When I use field collections the output produces invalid XML or is stripped of all wrappers so that it is just plain text. I have tried custom template files in my theme but views data export strips out the tags.
Desired output
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<file_information xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<asset_data>
    <upn>GBHIS3473610HD30P001</upn>
    <title>My Title</title>
    <version>Sunday 26th January</version>
    <duration>00:00:30:00</duration>
    <tc_in>10:00:00:00</tc_in>
    <tc_out>10:00:30:00</tc_out>
    <aspect_ratio>16:9</aspect_ratio>
    <segment>
        <sequence>1</sequence>
        <tc_in>10.00.00.00</tc_in>
        <tc_out>10.00.30.00</tc_out>
    </segment>
    <segment>
        <sequence>2</sequence>
        <tc_in>DMC</tc_in>
        <tc_out>DMC</tc_out>
    </segment>
    <segment>
        <sequence>3</sequence>
        <tc_in>DMC</tc_in>
        <tc_out>DMC</tc_out>
    </segment>
    <segment>
        <sequence>4</sequence>
        <tc_in>DMC</tc_in>
        <tc_out>DMC</tc_out>
    </segment>
</asset_data>
</file_information>

Actual output
(rest of XML is fine)
<segment>
  <sequence>

sequence:&nbsp;

1

  </sequence>
  <tc_in>

tc_in:&nbsp;

         0:00:00

  </tc_in>
  <tc_out>

tc_out:&nbsp;

       0:00:30

  </tc_out>
  <sequence>

sequence:&nbsp;

2

   </sequence>
   <tc_in>

tc_in:&nbsp;

        0:00:00

   </tc_in>
   <tc_out>

tc_out:&nbsp;

        0:00:20

  </tc_out>
 </segment>

So how can I customise the output or should I use something other than field collections?
contents of my field-collection-item.tpl.php
<sequence><?php print render($content['field_sequence']); ?></sequence>
<tc_in><?php print render($content['field_tc_in']); ?></tc_in>
<tc_out><?php print render($content['field_tc_out']); ?></tc_out>

contents of my views-data-export-xml-body.tpl.php
<?php
   $item_item = 'asset_data';
?>
<?php foreach ($themed_rows as $count => $row): ?>
  <<?php print $item_item; ?>>
<?php foreach ($row as $field => $content): ?>
  <?php if($content != NULL){ ?>
    <?php $content = str_replace("<","<",$content);
     $content = str_replace(">",">",$content); ?>
     <<?php print $xml_tag[$field]; ?>><?php print_r $content; ?></<?php print $xml_tag[$field]; ?>>
    <?php } ?>
 <?php endforeach; ?>
   </<?php print $item_item; ?>>
 <?php endforeach; ?>

Comment: @Mołot was right - I had cleaned fields tpl file but had a typo in the filename so it wasn't picking it up. Initial test looks good.
Comment: Looks like you haven't cleaned tpl for rows and fields.
Comment: As far as I know, Field Collection's Views integration is poor, to say the least. @user24312 You might have better luck in the module issue queue.
Comment: @user24312 feel free to post that as self-answer (if 8h limit for self-answers was lifted already).
Comment: G'dam typos always get you!
Comment: Still have a few hours to wait before I can self answer but have had time to test and needed to do another tweak to make it perfect so will include that when I reply.
Answer: As suggested by @Molot I needed to clean fields.tpl.php which I had done but had a typo in the name which is why I was puzzled.
In addition to this I needed to add some logic into views-data-export-xml-body.tpl.php to wrap each set of field items seperately.
(used str_replace to find the closing tag of the last element and insert the closing and opening wrapper tag)
$content = str_replace("/tc_out> <sequence>","/tc_out> </segment>
    <segment> <sequence>",$content);


Distributed wifi for medium-sized office

Question: We're soon to be moving into office of 400m² that's an odd U shape. We'd like wireless coverage across the whole thing. It seems to me that distributed wi-fi is the answer (a controller managing two dumb APs). I can't for the life of me find any vendor that has a solution in the price range a medium-sized business. Perhaps I'm searching for the wrong thing? Any advice is appreciated.
Comment: Shopping Questions are Off-Topic on any of the [se] sites. See [Q and A is hard, lets go Shopping](http://blog.stackoverflow.com/2010/11/qa-is-hard-lets-go-shopping) and the [FAQ] for more details.
Answer: Give Juniper a look.  They have a small controller (supports 4 AP's) for $900 full retail, you can find it as low as $650 if you look around.  I am a fan of the Cisco line, worked with them for 4 years and they are a dream to manage, lots of online reference material.
Answer: Meru runs some good bundle pricing on their smaller controllers.  I think you need to call the reseller in your area to get pricing.  I have 5 of their radios in a 10,000 square foot office and they work great.
Answer: Mikrotik. You get a lot more, but this is also something they support and their prices are - very interesting.


Set input value in custom search module

Question: I'm using custom search module in my site. What I want to do is set a value for the input (text box) in the username and password field.
How can I do that?
Answer: The Form API is your friend. Take a look in the Form API Quickstart Guide, how to change a form for your needs.
Comment: I just stumbled over http://mustardseedmedia.com/podcast/episode53.

Set input value in custom search module


Find the range of $xy$ under the conditions: $x^2-xy+y^2=9$ and $|x^2-y^2|<9$

Question: Assume $x,y \in \mathbb{R}^+$, and satisfied the following expression:
$$x^2-xy+y^2=9$$
$$\left|x^2-y^2\right| < 9$$
find the range of $xy$

My approach:  $x^2-xy+y^2=9$ $\Rightarrow$ $xy+9=x^2+y^2 \geq 2xy$ $\Rightarrow$ $xy \leq 9$
But I don't know  how to find the lower bound. please help me..thanks very much.
Answer: For the lower bound you can use the follwing facts:

$x^2-xy+y^2 = (x-y)^2 +xy \Rightarrow 9-xy = (x-y)^2$
$x^2-xy+y^2 = (x+y)^2 -3xy \Rightarrow 9+3xy = (x+y)^2$
$\left|x^2-y^2\right| < 9 \Leftrightarrow (x+y)^2(x-y)^2 < 81$

Plugging 1. and 2. into 3. you get:
$$(x+y)^2(x-y)^2 < 81 \Leftrightarrow (9-xy)(9+3xy) < 81 \Leftrightarrow xy(6-xy) < 0 \stackrel{x,y >0}{\Leftrightarrow} \boxed{xy>6}$$
Together with your upper bound $\boxed{xy \leq 9}$ you get
$$\boxed{6 < xy \leq 9}$$


Limitar tamanho de uma String?

Question: Declarei
char pl1[10], pl2[10];

E fiz o seguinte:
printf("Nome do Player1: ");
scanf("%10s", &pl1);
printf("Nome do Player2: ");
scanf("%10s", &pl2);

Pensando que ele ia ler só os 10 primeiros caracteres que o usuário digitasse. Porém assim, quando eu digito um  nome com mais de 10 caracteres o programa lê errado, exemplo, é digitado "dinamicamente", ele associa "dinamicame" á pl1 e "nte" á pl2. Já tentei também sem o 10 no scanf daí ele armazena o que ultrapassou o escopo no pl1, exemplo (usando "dinamicamente") ele ignora o primeiro nome digitado (caso o segundo seja com mais de 10 caracteres), e atribui os 10 primeiros caracteres digitados quando pede o Nome do Player 2 á pl2 e o restante em pl1. Caso o digitado em pl2 seja menor que 10 caracteres ele armazena o dinamicamente no pl1 e o nome que foi digitado em pl2.
Answer: Precisas de espaço para o '\0' e não podes por o & operador
scanf("%9s", pl1); // p1 = "dinamicam\x00"

mas o resto da string fica no buffer // ente<ENTER> e vai ser apanhado no scanf() seguinte
scanf("%9s", pl2); // pl2 = "ente\x00" e fica o <ENTER> pendurado no buffer

EDIT
Se quiseres cortar o input nos primeiros 9 caracteres e ignorar o resto, usa fgets()
fgets(p1, sizeof p1, stdin);
lenp1 = strlen(p1);
if (p1[lenp1 - 1] == '\n') {
    /* nome completo, com ENTER incluido */
    p1[--lenp1] = 0; // apagar o ENTER
} else {
    /* ENTER e possivelmente outros caracteres ficaram no buffer */
    int ch;
    do ch = getchar(); while (ch != '\n'); // limpa caracteres extra
}

fgets a correr no ideone
Comment: Acho que seria melhor mudar o tamanho do vetor pra 11 ao invés de diminuir o número de caracteres lidos
Comment: Não consegui reproduzir aqui, ficou igual
Comment: No ideone passa-se o que eu descrevi: https://ideone.com/OlzRmU
Comment: Sim, esse é o erro que vem ocorrendo comigo, p1 tem "dinamicam"
p2 tem "ente" igual no seu exemplo
Comment: Mas se `p1` tem espaço para 9 caracteres mais o terminador ... não dá para lá meter `"dinamicamente"`!
Comment: Sim eu sei, só que ele não deveria atribuir o restante no outro vetor, e sim só ignorar esse restante, pois assim nao da pra informar o nome de p2, entende o problema agora? Tipo, é limitar o quento o usuário pode digitar
Comment: Para limitar o que o utilizador pode digitar enquanto o programa corre vais ter que usar funções especificas to teu Sistema Operativo. Ou usas uma biblioteca que torna isso mais ou menos fácil, por exemplo a [ncurses](https://pt.wikipedia.org/wiki/Ncurses) ou [pdcurses](https://en.wikipedia.org/wiki/PDCurses) (em inglês).
Comment: Está dando certo quando eu coloco diretamente como a primeira coisa do programa, quando eu coloco dentro do case do menu ou if ele não funciona, ele pula a parte de p1
Comment: Misturar `fgets()` com `scanf()` é má ideia. Aparentemente o menu usa `scanf()` e deixa coisas penduradas no buffer. Muda esses `scanf()` para `fgets()` seguido de `sscanf()`.
Comment: Ele atrapalha o fgets() mesmo sendo número inteiro? Não sabia rs vou tentar aqui
Answer: O problema é justamente o fato de que a função scanf não verifica se o tamanho da string lida "cabe" dentro da área reservada. Por isso, ao ler mais do que o alocado, a função continua escrevendo na memória. Como você declarou as duas variáveis uma seguida da outra, ocorre que ele acaba gravando na área da variável seguinte. Poderia ser bem pior, poderia invadir uma área de memória que não está reservada para o seu programa, causando erros de execução.
Se o seu compilador for da Microsoft*, há a função scanf_s que permite que você informe o número máximo de caracteres a ser lido (mais detalhes nesta outra questão do SOEN). Caso contrário, você precisa tomar o devido cuidado. Uma boa solução foi proposta nesta resposta do SOEN:
int scanner(const char *data, char *buffer, size_t buflen)
{
    char format[32];
    if (buflen == 0)
        return 0;
    snprintf(format, sizeof(format), "%%%ds", (int)(buflen-1));
    return sscanf(data, format, buffer);
}

Basicamente, você cria uma função própria (scanner) que recebe um parâmetro (buflen) com o tamanho máximo (e seguro) do seu buffer de leitura, e ela usa a função snprintf para criar a máscara com o tamanho desejado para o buffer e garantir que erros não ocorram.
* É importante observar o comentário do colega @pmg sobre o scanf_s ser uma função opcional para compiladores C, e não apenas algo exclusivo de compiladores da Microsoft.
Comment: o `scanf_s()` está descrito no [C Standard mais recente](http://port70.net/~nsz/c/c11/n1570.html#K.126.96.36.199) mas faz parte do anexo K que é opcional para os compiladores.
Comment: @pmg Obrigado, não sabia. Sempre achei que era algo específico dos compiladores da Microsoft.
Answer: Pensei um pouco, tentei mas dava errado, mas hoje durante a aula me veio a ideia, cheguei em cada, tentei e deu certo. Primeiramente devemos alterar o valor dos vetores para um número que o usuário provavelmente nunca irá colocar como 100. Após isso demos o scanf, e se o vetor tiver comprimento maior que 10 ele então em um while que apaga os caracteres até o elemento 10 do vetor:
int i;
char p1[100], p2[100];
printf("\nNome do Player1: ");
scanf("%s", &p1);
printf("Nome do Player2: ");
scanf("%s", &p2);

//Redefine tamanho do Nome do player1
i = strlen(p1);
if (i > 10){
    while(i != 9){
         p1[i] = 0;
         i --;
    }
}

//Redefine tamanho do Nome do player2
i = strlen(p2);
if (i > 10){
    while(i != 9){
         p2[i] = 0;
         i --;
    }
}

Essa foi a forma mais simples que achei sem ter de alterar o restante do programa.
Comment: "Primeiramente devemos alterar o valor dos vetores para um número que o usuário provavelmente nunca irá colocar como `100`." Uhoh! É assim que nascem os *buffer overflow*.

Limitar tamanho de uma String?


Upper semicontinuity in real analysis

Question: Exercise from book:
Let $\left(f_{k}\right)_{k=1}^{\infty}$ be a sequence of functions and suppose that they are all upper semi-continuous at $x_{0}$. Define the function $g$ by $g(x)=\inf _{1 \leq k<\infty} f_{k}(x)$. Show that $g$ is upper semi-continuous at $x_{0}$.
My attempt: By definition of upper semi continuity we have
$\lvert x-x_0\rvert \Longrightarrow f_{k}(x) < f_{k}(x_0)+\varepsilon$
$ \inf f_{k}(x) < f_{k}(x_0)+\varepsilon$
I think it completes the proof.
Is it right or I missing something?????
I am not familiar with topology. so I am interested in only real analysis terms
Comment: To show the upper semi-continuity of $g$ at $x_0$ you have to show that $\forall \varepsilon > 0$, there exists $\delta > 0$ such that $|x - x_0| < \delta$ implies $g(x) < g(x_0) + \varepsilon$. It seems to me that your proof is not complete.
Comment: You have the main idea but some details are missing.
Comment: @Falcon thank you. I will try
Answer: Let $\varepsilon > 0$ and $g(x) = \inf_{k \in \mathbb N} f_k(x)$. Therefore, there exists $k_0 \in \mathbb N$ with
$$f_{k_0}(x_0) - g(x_0) < \frac{\varepsilon}{2}.$$
Moreover, for such a $k_0$, there is $\delta_{k_0}> 0$ with the property that
$$|x - x_0| < \delta_{k_{0}} \quad \Rightarrow \quad f_{k_0}(x) < f_{k_0}(x_0) + \frac{\varepsilon}{2}.$$
We deduce that, if $|x - x_0| < \delta_{k_0}$,
$$g(x) \le f_{k_0}(x) < f_{k_0}(x_0) + \frac{\varepsilon}{2} < g(x_0) + \varepsilon.$$
Comment: You are welcome.
Comment: Thank you Sir for the complete solution.

Upper semicontinuity in real analysis


How can I force a CSS animation of an element to start from the same location as the previous animation finished?

Question: I have an image that I want to move a certain distance (always the same) and a certain direction (specified in an array) on each mouse-click.  The first click moves it in the direction specified in the first array element, the second in the second and so on.
This works fine unless I ask it to move in the same direction twice in a row.  In that case it moves instantly to the finishing position with no animation, as if it had started the animation there, although the debugger shows the location, as defined by unitElement.style.left as corresponding correctly to its appearance on-screen.
The HTML, with four transformations and an image to move:

The function that is called on the click event:
function nextPulseAnimate() {
    pulse++;
    for(var index = 0; index < units.length; index++) {

        var unit = units[index];
        var direction = unit.moves[pulse-1]

        var unitElement = document.getElementById(unit.name);

        //ensure that the image is starting from the right place
        unitElement.style.left = unit.start.x;
        unitElement.style.top = unit.start.y;

        unitElement.style.animation = direction + " 2s ease-in-out forwards";
    }

    //then re-set the locations ready for next pulse
    //If this is not done, each animation will start from the unit's original location
    for(var index = 0; index < units.length; index++) {
        var unit = units[index];
        var direction = unit.moves[pulse-1]

        switch (direction){
         case "N":
             unit.start.y -= 60;
             break;
         case "E":
             unit.start.x += 60;
             break;
         case "S":
             unit.start.y += 60;
             break;
         case "W":
             unit.start.x -= 60;
             break;
         }
    }
}

The "unit" referred to in the function is derived from a global array of objects that looks like this (in practice it will have  a couple of dozen elements):
units = [
    {name: "F1", start: {x: 0, y: 0}, moves: ["S", "E", "E", "E"]}
];

For completeness, there is one other global variabe defined (and used above):
pulse = 0
Comment: The twice in a row problem: when you set the same animation name the system won't animate because it thinks it's already done it. You need to clear it and reset in some way.
Comment: provide css `.unit` rule definition. How. your img is positioned static, relative, absolute, or fixed? A minimal reproducible code would be really nice.
Comment: Sure.  Here is the css definition for .unit:
.unit {
width: 60px;
height: 60px;
position: absolute;
}
Comment: I mean the entire css rule like `.unit{ position: absolute; height:20px}`. update your opening post/question
Comment: In second for loop you are setting units to fixed coordinates they are not actually their last locations. There is a DOM event `onAnimationEnd` you can use that to update last coordinates. https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/animationend_event
Comment: That was the entire .css definition for .unit I posted.  I have updated the OP at your request.  Thank you - I will look into onAnimationEnd, but is there a reason you think that will work better than iterating through the animated elements to re-set their starting co-ordinates?  Bear in mind that the code above works perfectly unless the same direction  is called for twice in a row.
Comment: I tried using the onAnimationEnd event, calling the following function to re-set the stye:
function setLocation() {
 this.style.left = this.offsetLeft
 this.style.top = this.offsetTop
}
As I expected, this sets to the original (pre-animation) location rather than the final one.  But perhaps you meant I should derive the final location in some other way??

This, in fact, is why I introduced the second for-loop in the first place.  It works fine, remember, except when the same direction appears twice in a row.
Answer: Here is what I mean:

units = [{name: "F1", start: { x: '0px', y: '0px'},
    moves: ["S", "E", "E", "N", "W", "W"]
  },
  { name: "F2", start: { x: '120px', y: '60px' },
    moves: ["N", "W", "W", "S", "E", "E"]
  }
];

var pulse = 0;

function init() {
  document.body.addEventListener("click", nextPulseAnimate);

  for (var index = 0; index < units.length; index++) {
    var unit = units[index];
    var unitElement = document.getElementById(unit.name);
    unitElement.style.left = unit.start.x;
    unitElement.style.top = unit.start.y;

    unitElement.addEventListener('animationend', (event) => {
      document.body.addEventListener("click", nextPulseAnimate);
      var e = event.target;
      /* get position relative to viewport */
      var r = e.getBoundingClientRect();
      e.style.left = r.left + 'px';
      e.style.top = r.top + 'px';
      /* remove animation so that you can use it again */
      e.style.animation = 'none';
    });
  }
}

function nextPulseAnimate() {
  pulse++;
  if (pulse < 7) {
    document.getElementById('stats').innerText = 'Moves: ' + pulse + '/6';
    //don't let user click while animation is going on
    document.body.removeEventListener('click', nextPulseAnimate);
  }

  for (var index = 0; index < units.length; index++) {
    var unit = units[index];
    var direction = unit.moves[pulse - 1]
    var unitElement = document.getElementById(unit.name);
    unitElement.style.animation = direction + " 2s ease-in-out forwards";
  }
}
body {
  width: 90vw;
  height: 90vh
}

p {
  position: fixed;
  top: 40vh;
}

.unit { width: 60px; height: 60px; position: absolute; }

@keyframes N {100% {transform: translate(0px, -60px);}}
@keyframes E {100% {transform: translate(60px, 0px);}}
@keyframes S {100% {transform: translate(0px, 60px);}}
@keyframes W {100% {transform: translate(-60px, 0px);}}
<!DOCTYPE html>

Click anywhere to trigger moves


Is something happening with the ISP market in UK?

Question: We're being forced to look at rather expensive leased lines due to our distance from the exchange. Even on the new ADSL2+, we can't get much more than 3MBit/s but more importantly, we need to improve our upload speed.
Several vendors have offered us special deals if we sign up for three years before the end of October.
Call us cynical, but is something about to be launched in the UK that means leased lines will either be much lower price or under threat from other technologies. I assume that it could be ADSL2+ itself - if that's the case, we're still stuck :-(
Thanks, Rob.
Answer: October is a half-year for a lot of corporations, so it might just be salesmen trying to hit targets.
Comment: Could be you've got it in one. ;)
Answer: BT is in the process of rolling out its "21st Century Network" - it might be the case that the wholesale price is expected to drop imminently in your area; as others hav said, it should also just be a case of sales targets.
Comment: As long as it's not come new leased-line competitor technology just about to be rolled out.
Comment: From what little I know, 21CN offers products that effectively make leased lines obsolete. Things like Ethernet extenders, which for us were cheaper than a leased line.
Answer: Virgin/(NTL cough!) are talking about 100mBits to the door over their fibre optic network? not sure what the upload speed is.
Comment: ....if only I could receive their service, even thought they send me fliers saying I can...
Comment: VM is one of these companies offering a very good deal at the moment.


Countdown won't work

Question: I have a script in which I have tried to make a countdown, which counts down for 30 days and then resets to 30 days and starts over again. But my problem is that when I open it in my browser(safari), the page is blank with nothing on it, although if I remove the function I am using to reset the countdown it works but I need it to reset.
if (seconds_left <= 0){
    target_date = target_date + 30 days;
}

Full code:
 <!DOCTYPE html>

Comment: `target_date = target_date + 30 days` makes no sense in javascript. (the `+ 30 days` part)
Comment: `LANGUAGE="Javascript"` - why do people still use this?!
Answer: <!DOCTYPE html>

Countdown won't work


javascript create multiple files zip them up and send to server

Question: So a docx file is actually a bunch of meta data files + some other bits and bobs compressed. I am looking to create a online text editor which will create a format similar to docx.
In my head the end result will be: after the user writes his content  in the web browser and hits save the client will get together all the meta data files and zip them up. They will then send it to the server which will store the files.
The trouble is I have no idea where to get started on the client side of creating the files and zipping them up. Idealy I would want the client to be in charge of all of that to reduce overhead on the server. Would anyone be able to point me in the right direction on were to begin with this?
Comment: http://stuk.github.io/jszip/ or http://gildas-lormeau.github.io/zip.js/
Comment: If you're doing the zipping to save bandwidth then you're betting off making sure gzip compression is enabled. This will achieve the same reduction.
Comment: @FritsvanCampen - not for uploads
Comment: http://stuk.github.io/jszip/ is great. (oops, echo in here...)
Comment: you can simply deflate it, that's less work on both ends...
Answer: I wouldn't advise doing it client side. You don't know what the client might be sending back in a zip file. Do this securely on the server. If you can't afford the overheads then you might want to create a different service.
Comment: Beware of the zip bombs. Compressing a 20GB file with just characters `a` in it will give you a ridiculously small filesize, not so much when you unzip it.
Comment: ok after reading this, I think I'll do it server side. I'll let the client send the content of the file to the server and I'll just construct it all server side


Python Seleniume Multiple Buttons with same name

Question: For the below HTML code, I want to select the button in the DIV for 2022 November

                                        2022 November

                                        <button class="myButton" ng-show="!gridFile.monthOpen" ng-click="toggleMonthReport(gridFile)">Open</button>

                                        <button class="myButton ng-hide" ng-show="gridFile.monthOpen" ng-click="toggleMonthReport(gridFile)">Close</button>

However the same is repeated for all the months.
Below is the link to the larger HTML Code for reference. Any help is appreciated:
https://workdrive.zohoexternal.com/external/ecd06139063100a07635e16e74cb43a21504e8cb0b2c3bd57d6f3d7e317724d5
I have tried the following:
driver.find_element_by_xpath('//*[@id="reportHeaderCol4NonMobile"]/div[2]/div[3]/div[3]/fieldset/div1/div1/div').click()
driver.find_element_by_link_text('Open')1.click()
driver.find_element_by_class_name('button.myButton')1.click()
driver.find_element_by_class_name('myButton')1.click()
and a bunch more but none of them seem to work and I end up with error Message: no such element: Unable to locate element
---- Edit / Addition---
I even tried the suggestion from @AbiSaran with Xpath as (.//*[@class='reportTitleAreaNonMobile'])1//button1 but got the same error.
I feel the Xpath's are correct since I am able to find them in Chrome > Inspect screen. But my python code fails.

-----------Solution---
The solution below was pointing to accurate Xpath but was not working since the website was opening a new tab and the code continued to look for the element in the previous tab. I has the switch the active tab using the doe below and it worked fine.
driver.switch_to.window(driver.window_handles[1])

Answer: You can use the below XPath:
For the 'Open' button in '2022 November':
(.//*[@class='reportTitleAreaNonMobile'])[1]//button[1]

For the 'Close' button in '2022 November':
(.//*[@class='reportTitleAreaNonMobile'])[1]//button[2]

Comment: Thank you for the quick response but it didn't work.. got the same errors
...
driver.find_element_by_xpath("(.//*[@class='reportTitleAreaNonMobile'])[1]//button[1]").click()
...
NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"(.//*[@class='reportTitleAreaNonMobile'])[1]//button[1]"}
Comment: From the html source you've posted, it is working. If its not working, post the URL, it will be helpful to debug.
Comment: Thank you @AbiSaran , You providing the correct Xpath helped me explore other options to fix the issue.


JNI UnsatisfiedLinkError: (Class).(Method)()V

Question: I'm using JNI in my final project for my Intro to CS class. I'm almost able to get it working, but have an error that's stumped me the entire last weekend. I've looked around in many places, but haven't been able to fix.
The error I'm getting: java.lang.UnsatisfiedLinkError: JNI_Functions.dllHello()V
My code:
////////////////////////
// JNI_Functions.c

    #include "JNI_Functions.h"
    #include <jni.h>
    #include <stdio.h>

    JNIEXPORT void JNICALL Java_JNI_1Functions_dllHello(JNIEnv *env, jobject obj) {
        printf("This was sent from the DLL\n");
        return;
    }

///////////////////////
// JNI_Functions.h

    /* DO NOT EDIT THIS FILE - it is machine generated */
    #include <jni.h>
    /* Header for class JNI_Functions */

    #ifndef _Included_JNI_Functions
    #define _Included_JNI_Functions
    #ifdef __cplusplus
    extern "C" {
    #endif

    /*
     * Class:     JNI_Functions
     * Method:    dllHello
     * Signature: ()V
     */

    JNIEXPORT void JNICALL Java_JNI_1Functions_dllHello
      (JNIEnv *, jobject);

    #ifdef __cplusplus
    }
    #endif
    #endif

//////////////////// JAVA ///////////////////
// Entry.java
    public class Entry {
        public static void main(String[] args) {
            try {
    //          JNI_Functions jni = new JNI_Functions();
    //          jni.dllHello();
                new JNI_Functions().dllHello();
            } catch (UnsatisfiedLinkError e) {
                System.out.println("Couldn't call native function.\n" + e);
            }
        }
    }

///////////////////////
// JNI_Functions.java

public class JNI_Functions {
    public JNI_Functions() {
        System.loadLibrary("JNI_Functions");
        System.out.println("Loaded JNI_Functions.dll");
    }

    // Prints out a simple hello world from the dll
    public native void dllHello();
}

I'm using Code::Blocks to compile, here's the output if needed:
-------------- Build: Release in JNI_Functions (compiler: GNU GCC Compiler)---------------

mingw32-gcc.exe -Wall -O2 -D_JNI_IMPLEMENTATION_ -Wl,--kill-at -ID:\JNITest -c D:\JNI_Functions\JNI_Functions.c -o obj\Release\JNI_Functions.o
mingw32-g++.exe -shared -Wl,--output-def=bin\Release\libJNI_Functions.def -Wl,--out-implib=bin\Release\libJNI_Functions.a -Wl,--dll  obj\Release\JNI_Functions.o  -o bin\Release\JNI_Functions.dll -s
Output file is bin\Release\JNI_Functions.dll with size 9.00 KB
Process terminated with status 0 (0 minute(s), 9 second(s))
0 error(s), 0 warning(s) (0 minute(s), 9 second(s))

Answer: If your class or method name contains an underscore, it becomes _1 in C, not _. This is so that JNI_Functions.method and JNI.Functions_method don't have the same C names.
See Table 2-1 in http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/design.html.
In your case, the C function should be called Java_JNI_1Functions_dllHello.
Comment: It was that originally, but I had seen someone who had fixed their issue by doing that. I forgot to change it back I guess. Still doesn't work however.


on the sum of an infinite series

Question: Got stuck with this series:
$$
\sum_{k=0}^\infty \frac{1}{(\theta+2+k)(\theta+1)^{k+1}}
$$
which should be equal to
$$
\int_0^1 \frac{t^{\theta+1}}{\theta+1-t}\textrm{d}t
$$
But why? Which is the missing passage?
Comment: $$\frac{1}{\theta+2+k}=\int_{0}^{1} t^{\theta+1+k}\,dt, $$ hence to compute your series you just need to integrate the sum of a geometric series.
Answer: Differentiation and integration will help, you have to somehow construct a geometric series and choosing a function, that upon differentiation, will eliminate the extra term, you will succeed.
Consider a function
$$f(t)=\frac{t^{\theta+1+k+1}}{(\theta+1+k+1)(\theta+1)^{k+1}}$$
Differentiate
$$f'(t)=\frac{t^{\theta+k+1}}{(\theta+1)^{k+1}}=t^\theta \left(\frac{t}{\theta+1}\right)^{k+1}$$
Sum
$$\sum_{k=0}^\infty f'(t)=t^{\theta}\frac{t/(\theta+1)}{1-t/(\theta+1)}=\frac{t^{\theta+1}}{\theta+1-t}$$
Integrate back and take into account that the original sum was $\sum_{k=0}^\infty f(1)$.
This is a very general trick regarding the generating functions. All sums that differ from geometric sum by polynomial factors in $k$, can be solved with this method.

on the sum of an infinite series


Expressing boundary conditions in vector notation

Question: I have a second-order (Sturm-Liouville) differential equation for $u$ and want to express the boundary condition at (say) a, $k_1u(a)-k_2u'(a)=0$, in the form Y(a) = C where Y and C are column vectors and $Y=[y, y']^T$. I would appreciate your advice on the best method to do this, providing it is possible.
Answer: I'll assume that you meant $Y=[u, u']^T$ (since you didn't introduce $y$ and $y'$).
Note that you can write your boundary condition as a dot product:
$$\left(k_1\atop -k_2\right) \cdot Y(a)=0\;.$$
So $Y(a)$ must lie on the line orthogonal to $\left(k_1\atop -k_2\right)$, and that line can be parametrized as
$$Y(a)=\lambda\left(k_2\atop k_1\right)\;.$$


Pyspark : incremental ETL in cloud storage from multiple files

Question: I have about 500-700 csv files for logs to be loaded weekly. The file names are randomly generated each week. Those files are stored on google cloud storage, and the pyspark is running on google dataproc with several worker nodes.
I've created a pyspark file which basically just iterate the files and load them as is into bigquery.
I thought I willl see incremental load on bigquery table, but it seems pyspark takes the whole gz input files, merge them into dataframe, then process it at once. So I got the result after 90 minutes or so.
How can I write the pyspark code so that everytime the file read, it will be written to bigquery. The overall time might not be changed a lot, but at least how can I see data partially written to bigquery?
Below is my code.
<code>import pyspark
from pyspark.sql.types import StructType, StructField, StringType, DateType
from pyspark.sql import SparkSession

spark = SparkSession.builder.appName("Node Log ETL").getOrCreate()

log_dir = "gs://some-bucket/*.csv.gz"
log_spark = spark.read.csv(log_dir, header=True)

# Write to bigquery
log_spark.write\
    .format("bigquery")\
    .option("temporaryGcsBucket", "some-bucket/node-logs-temp-bq")\
    .option("dataset", "somedataset")\
    .mode("overwrite")\
    .save("node_weekly_logs")
</code>
Thanks
Comment: Against the spirit of spark.
Comment: You could read files one by one and loop through the write function call. I never tried to do something like that, but it may work for your case.
Comment: What do you mean against the spirit of spark? @thebluephantom
Comment: 2nd comment: I never tried to do something like that...should make you think
Comment: if there is no transform during the Spark job, why not just using bq command to run a load job and load all csv.gz files to BigQuery?
Answer: The BigQuery connector does not support streaming writes to BigQuery. To write results one file at a time, you would have to read and write each file separately instead of globbing them into a single DataFrame.


HLSL/XNA Ambient light texture mixed up with multi pass lighting

Question: I've been having some troubles lately with lighting. I have found a source on google which is working pretty good on the example. However, when I try to implement it to my current project, I am getting some very weird bugs. The main one is that my textures are "mixed up" when I only activate the ambient light, which means that a model gets the texture of another one .
I am using the same effect for every meshes of my models. I guess this could be the problem, but I don't really know how to "reset" an effect for a new model. Is it possible?
Here is my shader:
float4x4 WVP;
float4x4 WVP;
float3x3 World;

float3 Ke;
float3 Ka;
float3 Kd;
float3 Ks;
float specularPower;

float3 globalAmbient;
float3 lightColor;

float3 eyePosition;
float3 lightDirection;
float3 lightPosition;
float spotPower;

texture2D Texture;
sampler2D texSampler = sampler_state
{
    Texture = <Texture>;
    MinFilter = anisotropic;
    MagFilter = anisotropic;
    MipFilter = linear;
    MaxAnisotropy = 16;
};

struct VertexShaderInput
{
    float4 Position : POSITION0;
    float2 Texture  : TEXCOORD0;
    float3 Normal   : NORMAL0;
};

struct VertexShaderOutput
{
    float4 Position : POSITION0;
    float2 Texture  : TEXCOORD0;
    float3 PositionO: TEXCOORD1;
    float3 Normal   : NORMAL0;
};

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output;

    output.Position = mul(input.Position, WVP);

    output.Normal = input.Normal;

    output.PositionO = input.Position.xyz;

    output.Texture = input.Texture;

    return output;
}

float4 PSAmbient(VertexShaderOutput input) : COLOR0
{
    return float4(Ka*globalAmbient + Ke,1) * tex2D(texSampler,input.Texture);
}

float4 PSDirectionalLight(VertexShaderOutput input) : COLOR0
{
    //Difuze
    float3 L = normalize(-lightDirection);
    float diffuseLight = max(dot(input.Normal,L), 0);
    float3 diffuse = Kd*lightColor*diffuseLight;

    //Specular
    float3 V = normalize(eyePosition - input.PositionO);
    float3 H = normalize(L + V);
    float specularLight = pow(max(dot(input.Normal,H),0),specularPower);
    if(diffuseLight<=0) specularLight=0;
    float3 specular = Ks * lightColor * specularLight;

    //sum all light components
    float3 light = diffuse + specular;

    return float4(light,1) * tex2D(texSampler,input.Texture);
}

technique MultiPassLight
{
    pass Ambient
    {
        VertexShader = compile vs_3_0 VertexShaderFunction();
        PixelShader = compile ps_3_0 PSAmbient();
    }
    pass Directional
    {
        PixelShader = compile ps_3_0 PSDirectionalLight();
    }
}

And here is how I actually apply my effects:
public void ApplyLights(ModelMesh mesh, Matrix world,
    Texture2D modelTexture, Camera camera, Effect effect,
    GraphicsDevice graphicsDevice)
{
    graphicsDevice.BlendState = BlendState.Opaque;

    effect.CurrentTechnique.Passes["Ambient"].Apply();

    foreach (ModelMeshPart part in mesh.MeshParts)
    {
        graphicsDevice.SetVertexBuffer(part.VertexBuffer);
        graphicsDevice.Indices = part.IndexBuffer;

        // Texturing
        graphicsDevice.BlendState = BlendState.AlphaBlend;
        if (modelTexture != null)
        {
            effect.Parameters["Texture"].SetValue(
                modelTexture
            );
        }

        graphicsDevice.DrawIndexedPrimitives(
            PrimitiveType.TriangleList,
            part.VertexOffset,
            0,
            part.NumVertices,
            part.StartIndex,
            part.PrimitiveCount
        );

        // Applying our shader to all the mesh parts
        effect.Parameters["WVP"].SetValue(
            world *
            camera.View *
            camera.Projection
        );
        effect.Parameters["World"].SetValue(world);
        effect.Parameters["eyePosition"].SetValue(
            camera.Position
        );

        graphicsDevice.BlendState = BlendState.Additive;

        // Drawing lights
        foreach (DirectionalLight light in DirectionalLights)
        {
            effect.Parameters["lightColor"].SetValue(light.Color.ToVector3());
            effect.Parameters["lightDirection"].SetValue(light.Direction);

            // Applying changes and drawing them
            effect.CurrentTechnique.Passes["Directional"].Apply();
            graphicsDevice.DrawIndexedPrimitives(
                PrimitiveType.TriangleList,
                part.VertexOffset,
                0,
                part.NumVertices,
                part.StartIndex,
                part.PrimitiveCount
            );
        }
    }

I am also applying this when loading the effect:
effect.Parameters["lightColor"].SetValue(Color.White.ToVector3());
effect.Parameters["globalAmbient"].SetValue(Color.White.ToVector3());
effect.Parameters["Ke"].SetValue(0.0f);
effect.Parameters["Ka"].SetValue(0.01f);
effect.Parameters["Kd"].SetValue(1.0f);
effect.Parameters["Ks"].SetValue(0.3f);
effect.Parameters["specularPower"].SetValue(100);

Thank you very much
UPDATE:
I tried to load an effect for each model when drawing, but it doesn't seem to have changed anything. I suppose it is because XNA detects that the effect has already been loaded before and doesn't want to load a new one. Any idea why?
Answer: Alright so the problem was pretty stupid actually. I was applying the same effect to every meshes. I simply added a Effect.Clone() when loading the model and it worked!


Autocomplete em input dinâmico

Question: Bom dia pessoal.
Estou tentando implementar autocomplete no input dinamico mas não funciona. Já teste chamando class ou id e nada.
segue o código para que possam me dar uma luz mostrando onde estou errando.
Função Jquery que adiciono linha numa tabela dinamicamente. e a função autocomplete no campo descri (descricao do produto)
        $(document).ready(function(){

                //Atribui o evento click a classe .btn-insert-field
                $('.btn-insert-field').click(function(e){
                    //Remove ação padrão do link para não atualiza a página
                    e.preventDefault();

                    //Define o elemento onde será inserido os campos
                    var target  = $("#target");
                    //total de linhas criadas dinamicamente
                    //Será utilizado com indices pra serem removidos mais facilmente
                    var total = $("#target tr").length;
                    //Cria estrutura que será inserida
                    var html   = '
';
                            html   += '<input type="number" id="qtt" name="qtt[]" />	';
                            html   += '<input type="text" class="descri" id="descri" name="descri[]" style="text-transform:uppercase"  />	';
                            html   += 'X	';
                        html   += '
';

                    //Adiciona no final do elemento que foi selecionado anteriormente
                    target.append(html);
                });

                //Atribui a classe .btn-delete-row o evento click
                //É usado on porque o elemento será criado dinamicamente
                $(document).on('click', '.btn-delete-row', function(e){
                    //Remove ação padrão do link para não atualiza a página
                    e.preventDefault();
                    //pega o valor do data-id
                    var id  = $(this).data('id');
                    //Remove a linha
                    $('.row-field-'+id).detach();

                });

                $(document).on('DOMNodeInserted','.descri', function(){
                    $(this).autocomplete({
                        source:'pesquisa_produto.php'
                    });
                });

            });

Dentro do meu html eu mostro numa div ->

                                                                Quantidade
                                                                Descrição
                                                                Adicionar

Quando chamo a função autocomplete fora do input dinâmico funciona perfeitamente.
Answer: Troque DOMNodeInserted por focus. Quando o campo, seja criado dinamicamente ou não, receber o foco, irá ganhar o autocomplete:
$(document).on('focus','.descri', function(){
   // este if verifica se o campo já tem autocomplete
   if( !$(this).hasClass("ui-autocomplete-input") ){
      $(this).autocomplete({
         source:'pesquisa_produto.php'
      });
   }
});

Veja um exemplo:

$(function(){
   var availableTags = [
   "ActionScript",
   "AppleScript",
   "Asp",
   "BASIC",
   "C",
   "C++",
   "Clojure",
   "COBOL",
   "ColdFusion",
   "Erlang",
   "Fortran",
   "Groovy",
   "Haskell",
   "Java",
   "JavaScript",
   "Lisp",
   "Perl",
   "PHP",
   "Python",
   "Ruby",
   "Scala",
   "Scheme"
   ];

   $(document).on('focus','.descri', function(){
      // este if verifica se o campo já tem autocomplete
      if( !$(this).hasClass("ui-autocomplete-input") ){
         $(this).autocomplete({
            source: availableTags
       });
      }
   });

   $("#addicionar").on("click", function(){

      $("#box").append('<input class="descri">');

   });

});

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">

Digite "basic": <input class="descri">

<button id="addicionar">Adicionar input</button>
Comment: Assim como sugerido também não funcionou. Estou utilizando a versão https://ajax.googleapis.com/ajax/libs/jquery/jqueryui/1.12.1/jquery-ui.min.js  e
 http://code.jquery.com/ui/1.10.3/jquery-ui.js  e https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js
Comment: Estranho. Adicionei um exemplo funcional na resposta. Veja que funciona normal.
Comment: Aqui comigo não funciona... porque será? E esta linkado corretamente.
Comment: Funciona em campos que não foram adicionados de forma dinâmica?
Comment: Estou testando aqui... parou de funcionar também! na função eu chamo a página pesquisa_produto.php que está assim:           prepare($sql);
$result ->execute();

while($row = $result->fetch(PDO::FETCH_ASSOC)){
$data[] = $row['descric'];

}
echo json_encode($data);

?>
Comment: Tá vendo esse IF que coloquei: `if( !$(this).hasClass("ui-autocomplete-input") ){`? Faz um `else` nele e coloque: `console.log("já tem");`.  Aí vc vai clicando nos inputs mais de 1 vez e veja se aparece a mensagem no console. Se aparecer, o código está funcionando corretamente e o problema é no retorno do PHP.
Comment: Qdo eu depuro... olho no console nem entra no if... está dando erro na linha           $(document).on('focus','.descri', function(){
Comment: O que é mais estranho ainda. Vc usa outros eventos e não dá erro, só nesse que tá dando? Mt estranho.
Comment: Voltou a funcionar no input normal mas no input criado dinamicamente está dando erro quando chamo o $(this).autocomplete({ .....
Comment: Resolvido... criei um novo arquivo .php copiei os dados do antigo colei e voltou a funcionar... agora não me pergunte pq rs.. Vlw a força Sam.

Autocomplete em input dinâmico


Using Spring Aspects with Jetty

Question: I have an application that uses Aspects with Spring 3.1. It runs perfectly with Tomcat 7. The advised methods get called as expected.
I want it to work with Jetty. I've previously used Aspects with Spring 2.0 and Jetty with no major problems apart from adding a JVM agent. However I've had no luck with Jetty 6.22 and my Spring 3.1 application. I start Jetty with the javaagent thus
-javaagent:./spring-instrument-3.1.3.RELEASE.jar
where the  Spring Instrument jar is in my CWD.
There is a similar question on StackOverFlow but no-one was able to come up with a working answer.
Answer: First of all, I'd highly recommend to use jetty 9 instead of jetty 6. Jetty 6 is End of Lifetime since a while now and it's missing lots of features and bugfixes!
Besides that, are you using the --exec option somewhere in your configs? That will start a second jvm and probably that second jvm is not started with the javaagent setting place. You could verify that with "ps -ef | grep jetty" on *nix systems.
Comment: Ok thanks for this advice. I will try using a later Jetty. It did work with Spring 2.5 but maybe the move to Spring 3.0 has broken something.

Using Spring Aspects with Jetty


How to assign ViewData value as div id in asp.net mvc

Question: hi friends help me to get out of this..
//controller
{
ViewData["idvalue"]="id"+1;
return View();
}
// Viewpage

 id has to set as id1..

help me, how i can set div id as id1..?
thanks in advance.
regards,
Answer: Use
//controller
{
  ViewData["idvalue"] ="id1";
  return View();
}
// Viewpage

However, I would recommend to use ViewBag instead of ViewData
Answer: {
ViewBag.idvalue ="id1";
return View();
}
// Viewpage

I recommend using ViewBag instead. It's just a nicer wrapper for ViewData


A metric for a big/medium/small ML classification

Question: I am working on an ML classification task which is similar to the following:
Apples have to be classified to three classes: Big, Medium and Small.
I need a metric which I can use to assess the system. I consider using mean F1 score for the three classes (Big, Medium and Small).
However it looks like there is a problem with F1 score here: it will equally penalize the system for a big-to-medium apple confusion and for big-to-small confusion. And, from my intuition, system should be penalized more for making a bigger mistake (confusing a big apple with a small one is a bigger mistake than confusing a big apple with a medium one).
What metric could I use instead of F1 score here?
Answer: The F1 score is an evaluation metric for binary classifiers, so it is not very appropriate here (although it could be adapted).
However, more important is that your problem is not a genuine classification problem. In classification, there is no order of the classes, and you cannot say "that class is nearer to this class than another". They are all "equally far apart".
So you already have to choose a more appropriate model, to begin with, one that knows how to deal with response variables that have ordered differences. This is always the case in regression when the response is a real number. But you don't really have a continuous real response, you have just three discrete values with "different distances between them". Thus, your problem is more appropriately handled by ordinal regression models.
Comment: Thank you for bringing up the term "ordinal regression". It helped with further googling ) Here is an answer which addresses my question about choosing an evaluation metric for ordinal regression: https://stats.stackexchange.com/a/557563/319972


Quality of review process

Question: I'm just curious if anyone actually over looks the quality of the "review" tab. I recently started to contribute and have noticed that there are others that regularly contribute, but are doing so at a lightning fast pace.
I have a doubt that it is actually being done properly, in fact I've come across a few "new posts" that had spelling mistakes or formatting issues, while they were minor it makes me wonder.
Also, having been a victim of a question being incorrectly closed myself - the same people appear to be blindly voting. When I raised the fact it shouldn't have been closed here, it was voted to be re-opened. I've voted to keep some questions opened that were borderline, even went as far to edit them to salvage it but they were ultimately closed and my edit rejected?
I'm thinking that the review section has created a culture of blindly reviewing posts, edits, votes in efforts to just rack up points without merit.
I don't think I'm completely wrong on this, I've seen it a few times already.  I don't believe everyone is to blame here, but you cannot tell me that with the speed the queues are being cleared that there is actually any quality to the work being put in.
After having witnessed yet another closing to a question that I voted to keep opened (new user, the post could have been edited and there was an answer) I am proposing the following:

Limits per MONTH on how many times a person can vote

Note: This will force people to read more carefully and fully consider the questions they vote to close.

Lower the current limit of how many times a person can vote per DAY

Note: Again will prevent blind voting and allow questions to stay open long enough for someone to answer or properly edit the question.

Set a time delay after 3 consecutive reviews by the same person with "No Action Needed"

Note: This will address the many "new user" posts or "first answer" posts that I've seen that require obvious adjustments that are just not implemented.
I think the above is a good start to a) allow more members to contribute b) allowing questions to remain open for a reasonable amount of time c) prevent people from blindly clearing the queues.

Can a moderator please have a look at the user Keyul Shah
He is not reviewing new posts properly - most of them are "No Action Needed" but clearly need editing. Some have been subsequently edited, some posts have obvious formatting issues example: Magento. Extremely low First Byte and load time
Comment: There's definitely patterns. I recently posted about this because it's still happening: https://magento.meta.stackexchange.com/questions/2688/reviewers-please-stop-pressing-looks-ok-when-its-not
Answer: I personally are tired of stupid questions. If I don't understand a question, because I invest more time in reviewing it, than the OP to ask it, I close it. At least it feels like it. Normally I leave a comment, because I don't understand the question.
And I can tell at least for me, that I'm wondered from time to time, which questions are closed. So I understand your point.
Comment: I agree that questions without any thought or work done are frustrating and should be closed. I'm happy that you agree and understand my point.
Comment: I just skip the questions Iam not able to understand, usually there is someone who will be able to understand it or help to make it understandable.
I remember questions I edited to make them better understandable, when others already voted for close.
Answer: I am one of the people who only have a light view ower the questions,
 I participate there from time to time as I think we dont have enough reviewers anyway.
Iam not perfect in grammar, and not good in spelling.
I usually care about if the question makes sense and is answerable and then also give an upvote.
Comment: Maybe spelling and grammar is a bit over the top - I don't agree that we don't have enough reviewers, they aren't given a chance because the same person/people have made it a mission to clear them out within seconds of them arriving in the queue.  You are not one of the offenders, what you are doing is exactly what the review process should be.

Quality of review process


Analysis- subspaces from $\mathbb{R}^{n}$

Question:
Let $E\subset \mathbb{R}^n$ a vector subspace such that $E\neq \mathbb{R}^n$. Show that $\text{int}(E)=\emptyset$, where $E$ is a closed and connected set.

I don't know how to solve, someone can help me, any tips?
Comment: What kind of subspace?  Topological?  Vector?  Topological-vector?
Comment: @Randall Probably just vector.
Comment: @Randall Vector subspace
Answer: $0\notin Int(E)$ because if there exists a open ball $B(0,\epsilon) $ such that it is contained in $E$ then $E=\mathbb{R}^n$ because  for each $v\in \mathbb{R}^n$  then $\frac{\epsilon}{||v||}v$ is in $B(0,\epsilon)\subseteq E$ but $E$ is a subspace so $\frac{||v||}{\epsilon} (\frac{\epsilon}{||v||}v)=v\in E$.
Each point of $E$ can be mapped in $0$ with a translation so each point it is in $int(E)$ if and only if $0\in \phi(E)=E$ but it is not possibile
Answer: I am considering that you talk about vector subspace and the topology on $\mathbb{R}^n$ is induced by the usual (Euclidean) norm $\left| \left| \cdot \right| \right|$.
Now, since $E$ is a subspace of a finite dimensional vector space, it must be finite dimensional. Say $\left\lbrace v_1, v_2, \cdots, v_m \right\rbrace$ is a basis for $E$. We can extend this basis to $\left\lbrace v_1, v_2, \cdots, v_m, v_{m + 1}, \cdots, v_n \right\rbrace$ to be a basis for $\mathbb{R}^n$. Since $E \neq \mathbb{R}^n$, clearly $m \neq n$ and in particular $v_n \notin \left\lbrace v_1, v_2, \cdots, v_m \right\rbrace$.
We shall assume that these bases are normalised, i.e., $\left| \left| v_i \right| \right|
= 1$ for every $i = 1, 2, \cdots, n$.
Now, let $x \in E$ be any vector. Construct an open ball $B \left( x, \epsilon \right)$. The vector $x + \dfrac{\epsilon}{2} v_n \in B \left( x, \epsilon \right)$ since $\left| \left| x - \left( x + \dfrac{\epsilon}{2} v_n \right) \right| \right| = \dfrac{\epsilon}{2} < \epsilon$ however, $x + \dfrac{\epsilon}{2} v_n \notin E$ since it cannot be written as a linear combination of elements $\left\lbrace v_1, v_2, \cdots, v_m \right\rbrace$. This is because of the linear independence of a basis.
Therefore, taken any point in $E$ and constructing any open ball around it, that open ball is not contained in $E$. Hence, no point of $E$ can be interior point, i.e., $\text{int} \left( E \right) = \emptyset$.


Product of a principal proper ideal by itself

Question: Let $P$ be a principal proper ideal in an integral domain.

Is it $P^2 \subset P$ in general? If yes, how to prove it?

For example, if you look at the ideal $(3)=3\mathbb{Z}$ in $\mathbb{Z}$, it is quite simple to show that $3$ is not in $(3)^2$, but how to prove a similar property in a more general context?
Now suppose that we have a Dedekind domain.

If $P$ is a principal prime ideal, does $P^2 \neq P$ (and so $P^2 \subset P$) follow from the fact that there is a sort of unique factorization of proper ideals in terms of prime ideals?
Comment: By $\subset$ you mean $\subsetneq$ (gotten from `\subsetneq`). It is usually a good idea to be emphatic about this in notation.
Comment: Hint: contains = divides for principal ideals and ideals in Dedekind domains.
Comment: @Oo3: http://math.stackexchange.com/questions/348789 could be related
Answer: If $P=(x)$, then $P^2=(x^2)$. If $P\subseteq P^2$, there is an $a$ such that $x=ax^2$, so $x(1-ax)=0$. If $x\neq0$, then $1-ax=0$ and $x$ is a unit.
Therefore $P=P^2$ implies either $P=0$ or $P=A$, the whole ring.
Comment: Nice one. And if we replace "principal" with "prime", does the property still hold?


Munkres Lemma 54.1 (Unique lifting)

Question: For the uniqueness part of the proof, I am having some trouble understanding why the set $\overline{\overline{f}}([s_{i},s_{i+1}])$ has to be connected in $E$. It is clear $\overline{f}([s_{i}, s_{i+1}])$ is connected in $E$, since it is a continuous image of an interval, but there is no reason why $\overline{\overline{f}}$ has to be continuous on the interval $[s_{i}, s_{i+1}]$. Are liftings automatically assumed to be continuous?
Comment: I am going through this proof right now. In the text is not clear to me if there's a distinction between $\bar{f}$ and $\tilde{f}$. Maybe you can clarify?
Answer: Let's prove lifts are continuous. Let $\overline{f}:[0, 1] \rightarrow E$ be a lift of a path $f:[0, 1]\rightarrow B$. Let $s\in [0, 1]$ and let $U \subseteq E$ be an open neighbourhood of $\overline{f}(s)$ such that $p|_U : U \rightarrow B$ is a homeomorphism. Let $V=f^{-1}(p(U))$ such that $\overline{f}|_V = (p_U)^{-1} \circ f$. Note that $\overline{f}|_V$ is continuous as the composition of continuous maps. Since $V$ is an open neighbourhood of $s$, this implies $\overline{f}$ is continuous at $s$ (a map of topological spaces is continuous at a point iff its restriction to some open neighbourhood of that point is continuous).
This really works for any lift, not just a lift of a path.
Comment: After some more reflection, I realize that this argument is not actually sound. It is not automatic that $\overline{f}$ is continuous. In fact, lifts are typically continuous by definition.
Answer: No, we do not assume liftings to be continuous. But the statement of Lemma 54.1 states
'a unique lifting to a path $\overline{f}$ in $E$ beginning at $e_0$'. Paths are continuous, so $\overline{\overline{f}}$ is assumed to be in the second half of the proof.

Munkres Lemma 54.1 (Unique lifting)


How to implement async instant messaging chat with ZeroMq

Question: Approach
I'm building an asynchronous IM/chat application with ZeroMq, just as a learning exercise, using the following approach.
The server uses two ROUTER sockets, similar to lbbroker.java, reading from incoming and writing to outgoing, while manipulating the envelope for delivery to the intended receiver.
Clients set a unique identity with socket.setIdentity(), and use PULL and PUSH sockets, instead of REQ/REP, for sending and receiving chat messages asynchronously. I've built and tested the code, everything appears to work fine.

Questions

Is the use of PUSH/PULL with ROUTER a valid approach?

Why do chat clients become unreachable when dropping off then reconnecting?

Sally becomes unreachable if she disconnects then reconnects, she can no longer receives chat messages. After debugging the server, I confirmed it's definitely sending messages with the correct envelope to sally. I also used outgoing.setRouterMandatory(true) to ensure unaddressable messages weren't being dropped by the server, but no errors got raised.
Answer: After further research, while PUSH and PULL sockets work with ROUTER, they are not valid socket combinations as per the ZeroMq spec.
A DEALER socket on the client side is a better approach. DEALER supports bidirectional message transfer, basically doing the job of PUSH and PULL but with a single socket.
I started a thread on Github discussing the issue, it includes some sample code for agent-based pattern using DEALER.
https://github.com/zeromq/jeromq/issues/81


ggplot2 legend when each layer has a single variable

Question: Sorry for this basic question but I'm new to ggplot2 and am probably not using correct terminology in my search for an answer. I have a scatterplot with two layers. The base is individual observations at various times and the overlay is the mean of those observations at the same times. All data is in long format. Sample code below produces the correct plot but I can't figure out how to create the legend that links + to individual observations and circles to the means of those observations. Thanks for helping a newbie.
x <- c(1, 2, 3)
x <- rep(x, each = 3)
y <- c(3, 2, 5, 5, 6, 3, 8, 9, 6)
df1 <- data.frame(x, y)
df2 <- aggregate(y ~ x, df1, mean)
p1 <- ggplot(data = df1, aes(x = x, y = y)) +
  geom_point(pch = 3, size =2) + # Individual observations
  geom_point(data = df2, aes(x = x, y = y)) + # Means
  geom_line(data = df2, aes(x = x, y =y)) # Connect means

Comment: Thanks. Nothing like missing the obvious.
Answer: That is because to display a legend you have to specify a shape argument in the aes() function that maps data to visual parameters.
The easiest way would be to combine your two dataframes and add a third column specifying the type...
df3 <- as.data.frame(rbind(df1, df2))
df3$type <- rep(c("Ind. Obs.", "Means"), c(nrow(df1), nrow(df2)))

Then you need to specify the shape parameter to correspond to df3$type. Also to get the shapes that you want you will need to call scale_shape_manual().
p1 <- ggplot() +
  geom_point(data = df3, aes(x = x, y = y, shape = type)) +
  scale_shape_manual(values = c(3, 19)) +
  geom_line(data = df2, aes(x = x, y =y)) # Connect means
p1


Infinite Series $a_k=\frac{(-1)^{k+1}}{2k-1}$

Question: Let $$a_k=\frac{(-1)^{k+1}}{2k-1}.$$
Compute the sum $\sum_{k=1}^{\infty} {a_k}$.
Then compute $\lim _ { n \to \infty}\left(\sum_{k=n}^{2n}|a_k|\right)$.
The sum I want to compute is $1-\frac{1}{3}+\frac{1}{5}-\frac{1}{7}. . .$. I know the sum should come out to be $\frac{\pi}{4}$, but I don't know how to get to that point. I don't know where to start on computing the limit.
Answer: For the first one, recall that
$$\arctan(x)=\int_0^x\frac1{1+t^2}\ dt$$
Then use the geometric series to see that for $t\in(-1,1)$,
$$\frac1{1+t^2}=\sum_{k=1}^\infty(-1)^{k+1}t^{2k-2}$$
Then rigorously show that when $x=1$, we can interchange the integral and series to get
$$\frac\pi4=\arctan(1)=\int_0^1\frac1{1+t^2}\ dt=\sum_{k=1}^\infty\int_0^1(-1)^{k+1}t^{2k-2}\ dt=\sum_{k=1}^\infty\frac{(-1)^{k+1}}{2k-1}$$

One may then note that $|a_k|=\frac1{2k-1}$, thus, we want to compute the following limit:
$$L=\lim_{n\to\infty}\sum_{k=n}^{2n}\frac1{2k-1}$$
This may easily be done by noticing that
$$0\le\sum_{k=n}^{2n}\frac1{2k-1}-\int_n^{2n}\frac1{2x-1}\ dx\le\frac1{2n-1}+\frac1{4n-1}$$
And by seeing that
$$\int_n^{2n}\frac1{2x-1}\ dx=\frac12\ln\left(\frac{4n-1}{2n-1}\right)\stackrel{n\to\infty}\longrightarrow\frac12\ln(2)$$
We conclude by the squeeze theorem that
$$L=\frac12\ln(2)$$
Comment: Sorry, my bad @Dr.MV.  Thanks for the catch!
Comment: You're welcome.  My pleasure.
Answer: HINT:
Let $f(x)=\arctan(x)$.  Then $f'(x)=\frac{1}{1+x^2}=\sum_{k=0}^{\infty} (-x^2)^k$.
Now integrate term by term and set $x=1$

$$\begin{align}
\sum_{k=n}^{2n}\frac{1}{2k-1}&=\sum_{k=0}^{n}\frac1{2n+2k-1}\\\\
&=\frac1{2n}\sum_{k=0}^n\frac{1}{1+\frac{k-1/2}{n}}\tag 1
\end{align}$$
Now note that $(1)$ is the Riemann Sum for $\frac12\int_0^1 \frac{1}{1+x}\,dx$
Answer: $\newcommand{\bbx}[1]{\,\bbox[8px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$

\begin{align}
\sum_{k = 1}^{\infty}{\pars{-1}^{k + 1} \over 2k - 1} & =
\sum_{k = 1}^{\infty}{\ic^{\pars{2k - 1} + 3} \over 2k - 1} =
-\ic\sum_{k = 1}^{\infty}{\ic^{2k - 1} \over 2k - 1} =
-\ic\sum_{k = 1}^{\infty}{\ic^{k} \over k} +
\ic\sum_{k = 1}^{\infty}{\ic^{2k} \over 2k}
\\[5mm] & =
\ic\ln\pars{1 - \ic} - {1 \over 2}\,\ic\ln\pars{1 - \ic^{2}} =
\ic\bracks{{1 \over 2}\,\ln\pars{2} - {\pi \over 4}\ic} -
{1 \over 2}\,\ic\ln\pars{2} = \bbx{\ds{\pi \over 4}}
\end{align}

\begin{align}
\lim_{n \to \infty}\sum_{k = n}^{2n}{1 \over 2k - 1} & =
{1 \over 2}\,\lim_{n \to \infty}\pars{%
\sum_{k = 1}^{2n}{1 \over k - 1/2} - \sum_{k = 1}^{n - 1}{1 \over k - 1/2}}
\end{align}

Note that

\begin{align}
\sum_{k = 1}^{N}{1 \over k - 1/2} & = \sum_{k = 0}^{N - 1}{1 \over k + 1/2} =
\sum_{k = 0}^{\infty}\pars{{1 \over k + 1/2} - {1 \over k + N + 1/2}} =
\Psi\pars{N + {1 \over 2}} - \Psi\pars{1 \over 2}
\\[5mm] & \sim
-\Psi\pars{1 \over 2} + \ln\pars{N + {1 \over 2}}\quad \mbox{as}
\quad N \to \infty
\end{align}

\begin{align}
\mbox{Then,}\quad \lim_{n \to \infty}\sum_{k = n}^{2n}{1 \over 2k - 1} & =
{1 \over 2}\,\lim_{n \to \infty}\bracks{%
\ln\pars{2n + {1 \over 2}} - \ln\pars{n - {1 \over 2}}} =
\bbx{\ds{{1 \over 2}\,\ln\pars{2}}}
\end{align}
Answer: Let $\varphi , \psi : [- \pi , \pi] \to \mathbb{R}$ given by $\varphi = \frac{1}{2} Id_{[- \pi , \pi]}$ and $\psi = {\chi}_{[- \pi , 0]} - {\chi}_{(0 , \pi)}$. Let's expand $\varphi$ and $\psi$ to $\mathbb{R}$ such that $\varphi$ and $\psi$ are both $2 \pi$-periodic functions. Two of a lot of forms to compute these sum are computing Fourier series of $\varphi$ and $\psi$.


Can't get foreign key to work in Propel2

Question: I am trying to use Propel2 for my web-application. I just can't figure out why my foreign-key connection does not work. It is very similar to the Book-example and that works fine.
My schema.xml:
<database name="default" defaultIdMethod="native"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:noNamespaceSchemaLocation="http://xsd.propelorm.org/1.6/database.xsd">

        <column name="game_id" type="INTEGER" required="true" sqlType="int(11) unsigned" primaryKey="true" autoIncrement="true"/>
        <column name="game_name" type="VARCHAR" size="150" required="true"/>
        <unique name="UNIQUE_game_name">
            <unique-column name="game_name" size="150" />
        </unique>

        <column name="team_game" type="INTEGER" required="true" sqlType="int(11) unsigned"/>
        <column name="team_id" type="INTEGER" required="true" sqlType="int(11) unsigned" primaryKey="true" autoIncrement="true"/>
        <column name="team_name" type="VARCHAR" size="150" required="true"/>
        <index name="KEY_teams_for_constraints">
            <index-column name="team_game" size="11" />
            <index-column name="team_id" size="11" />
        </index>
        <index name="KEY_teams_name_check">
            <index-column name="team_game" size="11" />
            <index-column name="team_name" size="150" />
        </index>
        <foreign-key name="FK_team_game" foreignTable="games" phpName="Game" refPhpName="Team">
            <reference local="team_game" foreign="game_id"/>
        </foreign-key>

</database>

My PHP test-code:
echo "----- ----- -----  PROPEL TEST (START) ----- ----- -----

";

echo "--1--
";
$game = new Game();
$game->setGameName('PropelTestGame10');
echo "--2--
";
$team = new Team();
$team->setTeamName('Propel Test Team10');
$team->setTeamGame($game);
echo "--3--
";
$team->save();
echo "--4--
";
var_dump($team->toArray());
echo "
";
echo "--5--
";

echo "----- ----- -----  PROPEL TEST (END) ----- ----- -----

";

The PHP code generates this output:
----- ----- ----- PROPEL TEST (START) ----- ----- -----
--1--
--2--
Notice: Object of class Game could not be converted to int in E:\MyApp\Model\Base\Team.php on line 351
--3--
--4--
array(3) { ["TeamGame"]=> int(1) ["TeamId"]=> int(10) ["TeamName"]=> string(18) "Propel Test Team10" }
--5--
----- ----- ----- PROPEL TEST (END) ----- ----- -----

If the game-table is empty, nothing is stored in the database. In this case there is an old row with in the game-table and inserted team is associated with that game (TeamGame=1). Nothing new is saved to the game-table.
What am I doing wrong?
I can't see why my structure should not work when the book-example does (Propel 2 - Book-example).
Answer: Here is your mistake:
$team->setTeamGame($game);

You are trying to set team_game column to object value. You wrote in your schema that this will be integer so this auto-generated function in base class expects integer value. You should use:
$team->setGame($game);

if you want to set related object or you can use:
$game->save();
$team-setTeamGame($game->getPrimaryKey());

Here is your working example


java.util.NoSuchElementException reading user input

Question: I'm getting an error message (java.util.NoSuchElementException) in thread main when attempting to compile the following code with the input 3, then 4, 5, and 7. I've tried to tweak the code, but there's something I'm missing. I was thinking it may be due to my use of arrays since I am just learning how to use those, but I've tried to look closely at them and I didn't see anything I did wrong, but I definitely missed something. Any help would be appreciated. Thanks!
import java.util.Scanner;
public class ArrayMethods2 {
    public static int[] findMinAndMax(int[] x) {
        int i;
        int min = x[0];
        int max = x[0];
        for (i = 0; i < x.length; i++) {
            if (x[i] < min) {
                min = x[i];
            }
            if (x[i] > max) {
                max = x[i];
            }
        }
        int [] minAndMax = new int[2];
        minAndMax[0] = min;
        minAndMax [1] = max;
        return minAndMax;
    }
    public static double averageWithDrop(int[] x) {
        int i;
        int min = x[0];
        int minIndex1 = 0;
        int minIndex2 = 0;
        int sum = 0;
        for (i = 0; i < x.length; i++) {
            if (x[i] < min) {
                minIndex1 = i;
            }
        }
        for (i = 0; i < x.length; i++) {
            if (x[i] < min) {
                if (i != minIndex1)
                minIndex2 = i;
            }
        }
        for (i = 0; i < x.length; i++) {
            if (i == minIndex1) {
                sum = sum + 0;
            }
            else if (i == minIndex2) {
                sum = sum + 0;
            }
            else {
                sum = sum + x[i];
            }
        }
        double average = sum / (x.length - 2);
        return average;
    }
    public static void main (String[] args) {
        Scanner scnr = new Scanner(System.in);
        System.out.print("How many numbers would you like to enter? (must be at least 3) ");
        int userValue = scnr.nextInt();
        System.out.println(userValue);
        while (userValue < 3) {
            System.out.println("Invalid value, must be at least 3. Please try again ");
            userValue = scnr.nextInt();
            System.out.println(userValue);
        }
        int x = 0;
        int indexVal;
        int [] userArray = new int [userValue];
        while (x <= userValue) {
            System.out.print("Enter value for index " + x + ": ");
            indexVal = scnr.nextInt();
            System.out.println(indexVal);
            userArray[x] = indexVal;
            x++;
        }
        int [] minAndMaxVal = new int [2];
        minAndMaxVal = findMinAndMax(userArray);
        System.out.println("Min value: " + minAndMaxVal[1] + ", Max value: " + minAndMaxVal[2]);
        double avg = averageWithDrop(userArray);
        System.out.println("Average excluding two lowest values: " + avg);
    }
}

Answer: Running your code, I did not get any NoSuchElementException, however I got IndexOutOfBoundsException. Check the class your are running.
Please remember arrays are 0 based.
In the main method change while (x <= userValue)to while (x < userValue)
Again, arrays are 0 based, change:
System.out.println("Min value: " + minAndMaxVal[1] + ", Max value: " + minAndMaxVal[2]);

to
System.out.println("Min value: " + minAndMaxVal[0] + ", Max value: " + minAndMaxVal[1]);

Answer: There are few problems in the code :

Update this (x <= userValue) to (x<userValue) , else it will give array index out of bounds exception

Start the for loop in minMaxFunction from 1 , since you have already stored the value of arr[0] to min and max like below . This is just an optimization in the code.
     for (i = 1; i < x.length; i++) {
         if (x[i] < min) {
             min = x[i];
         }
         if (x[i] > max) {
             max = x[i];
         }
     }

This line in main method should have index 0 and index 1 . There is no index 2 since you have declared the array of length 2 , else it will give array index out of bounds exception
  minAndMaxVal = findMinAndMax(userArray);
  System.out.println("Min value: " + minAndMaxVal[0] + ", Max value: " + minAndMaxVal[1]);

Comment: @maha i think the issue is with the editor in that online tool. You need to pass the console input beforehand in the STDIN tab, then it works. Otherwise, it is working perfectly fine in standard IDEs
Comment: If you run the code there is no such exception . I am pretty sure .
Comment: i got the error he talked about.. check here http://tpcg.io/xk5pCJNO


PHP, JSON - Receive just fields with exact value

Question: with the following code i get values from a json-list
$data = json_decode($result, true);
foreach ($data['items'] as $key => $value) {
echo $value['classification_id'].','.$value['classification_name'];

Result is
5,Standorte (Leihgeber)6,Objekttypen9,Museen/Sammlungen
(Webgate)10,Vervielfältigungen von11,Vorlagen-Format 112,Vorlagen-Typ
115,Maßangaben16,Geografischer Bezug17,Vorlagen-Status
118,Vorlagen-Status 219,Vorlagen-Status 320,Vorlagen-Status
421,Vorlagen-Format 222,Vorlagen-Format 323,Vorlagen-Format
424,Vorlagen-Typ 225,Vorlagen-Typ 326,Vorlagen-Typ
429,Künstler30,Fotografen31,Personen32,Stichworte/Keywords36,39,Copyright_Zusaetze
(Standort-Zusatz)42,Test_PHP

Now I want to get only the fields for "classification_id" and "classification_name" where the field ""classification_id" has the value "42" (42,Test_PHP). How can I do this?
Json example
23
classification_id   39
classification_name "Copyright_Zusaetze (Standort-Zusatz)"
classification_dtcreate "2016-02-10T14:00:12+01:00"
classification_dtupdate "2016-09-15T17:44:35+02:00"
24
classification_id   42
classification_name "Test_PHP"
classification_dtcreate "2018-10-10T16:06:57+02:00"
classification_dtupdate "2018-10-18T11:09:51+02:00"

echo $result
{"request":{"date":"2018-11-15T12:00:42+01:00",
            "uid":"20181115-120042-66b3dfab25a8a11180a46313ac401b3c"
            },
"offset":0,
"limit":5000,
"totalCount":25,
"items":[
            {"classification_id":5,
            "classification_name":"Standorte (Leihgeber)",
            "classification_dtcreate":"2013-09-17T13:58:58+02:00",
            "classification_dtupdate":"2015-02-13T15:12:51+01:00"
            },
            {"classification_id":6,
            "classification_name":"Objekttypen",
            "classification_dtcreate":"2013-09-19T15:18:26+02:00",
            "classification_dtupdate":"2013-09-19T15:30:38+02:00"
            },
            {"classification_id":9,
            "classification_name":"Museen\/Sammlungen (Webgate)",
            "classification_dtcreate":"2013-10-21T17:31:12+02:00",
            "classification_dtupdate":"2017-08-15T07:55:02+02:00"
            },
            {"classification_id":10,
            "classification_name":"Vervielf\u00e4ltigungen von",
            "classification_dtcreate":"2014-01-08T14:32:55+01:00",
            "classification_dtupdate":"2014-05-14T10:50:12+02:00"
            },{"classification_id":11,"classification_name":"Vorlagen-Format 1","classification_dtcreate":"2014-01-08T15:01:10+01:00","classification_dtupdate":"2014-06-11T15:41:31+02:00"},{"classification_id":12,"classification_name":"Vorlagen-Typ 1","classification_dtcreate":"2014-01-08T15:23:40+01:00","classification_dtupdate":"2014-05-14T11:02:39+02:00"},{"classification_id":15,"classification_name":"Ma\u00dfangaben","classification_dtcreate":"2014-04-10T09:42:12+02:00","classification_dtupdate":"2014-04-10T09:42:12+02:00"},{"classification_id":16,"classification_name":"Geografischer Bezug","classification_dtcreate":"2014-04-30T13:35:10+02:00","classification_dtupdate":"2014-04-30T13:35:10+02:00"},{"classification_id":17,"classification_name":"Vorlagen-Status 1","classification_dtcreate":"2014-05-14T10:39:27+02:00","classification_dtupdate":"2014-06-11T15:42:23+02:00"},{"classification_id":18,"classification_name":"Vorlagen-Status 2","classification_dtcreate":"2014-05-14T10:41:17+02:00","classification_dtupdate":"2014-06-11T15:42:30+02:00"},{"classification_id":19,"classification_name":"Vorlagen-Status 3","classification_dtcreate":"2014-05-14T10:41:55+02:00","classification_dtupdate":"2014-06-11T15:42:38+02:00"},{"classification_id":20,"classification_name":"Vorlagen-Status 4","classification_dtcreate":"2014-05-14T10:42:16+02:00","classification_dtupdate":"2014-06-11T15:42:47+02:00"},{"classification_id":21,"classification_name":"Vorlagen-Format 2","classification_dtcreate":"2014-05-14T10:50:25+02:00","classification_dtupdate":"2014-06-11T15:41:40+02:00"},{"classification_id":22,"classification_name":"Vorlagen-Format 3","classification_dtcreate":"2014-05-14T10:50:47+02:00","classification_dtupdate":"2014-06-11T15:41:48+02:00"},{"classification_id":23,"classification_name":"Vorlagen-Format 4","classification_dtcreate":"2014-05-14T10:51:21+02:00","classification_dtupdate":"2014-06-11T15:42:07+02:00"},{"classification_id":24,"classification_name":"Vorlagen-Typ 2","classification_dtcreate":"2014-05-14T11:02:44+02:00","classification_dtupdate":"2014-05-14T11:02:50+02:00"},{"classification_id":25,"classification_name":"Vorlagen-Typ 3","classification_dtcreate":"2014-05-14T11:03:17+02:00","classification_dtupdate":"2014-05-14T11:03:23+02:00"},{"classification_id":26,"classification_name":"Vorlagen-Typ 4","classification_dtcreate":"2014-05-14T11:03:50+02:00","classification_dtupdate":"2014-05-14T11:03:58+02:00"},{"classification_id":29,"classification_name":"K\u00fcnstler","classification_dtcreate":"2014-11-18T15:20:51+01:00","classification_dtupdate":"2018-11-05T11:09:42+01:00"},{"classification_id":30,"classification_name":"Fotografen","classification_dtcreate":"2015-01-15T13:28:57+01:00","classification_dtupdate":"2017-11-07T10:59:19+01:00"},{"classification_id":31,"classification_name":"Personen","classification_dtcreate":"2015-01-15T13:42:26+01:00","classification_dtupdate":"2015-12-16T11:22:20+01:00"},{"classification_id":32,"classification_name":"Stichworte\/Keywords","classification_dtcreate":"2015-01-22T15:29:00+01:00","classification_dtupdate":"2016-05-10T12:05:17+02:00"},{"classification_id":36,"classification_name":"","classification_dtcreate":"2015-05-06T09:32:20+02:00","classification_dtupdate":"2015-05-06T09:32:20+02:00"},{"classification_id":39,"classification_name":"Copyright_Zusaetze (Standort-Zusatz)","classification_dtcreate":"2016-02-10T14:00:12+01:00","classification_dtupdate":"2016-09-15T17:44:35+02:00"},{"classification_id":42,"classification_name":"Test_PHP","classification_dtcreate":"2018-10-10T16:06:57+02:00","classification_dtupdate":"2018-10-18T11:09:51+02:00"}]}

Thank you
Comment: using array_search() with array_column(). Smth like `$itemKey = array_search(42, array_column($data, 'classification_id'));`
Comment: Its not a json string, please see above comment
Comment: And if you try and format it so it is easily readable it really helps people bother to stay on a question rather thna do something more interesting
Comment: @RiggsFolly *something more interesting* - not sure what that means :-/
Comment: @NigelRen my man, you need to get out more :)
Comment: Can you just show us an `echo $result`
Comment: But it is JSON. Only a part of the whole
Comment: Updated my post with echo $result = json string
Comment: Sorry @RiggsFolly
Answer: If classification_id is a unique value, then you can use array_column() to re-index the array with this value.  You can then access the array directly with the key your after...
$data = array_column($data['items'],null,'classification_id');

echo $data[42]['classification_name'];

gives...
Test_PHP


In Neural network prediction(not classification), What Cost function shall i use?

Question: Would you please provide me with some cost function that i can use in Neural Network back propagation prediction.
I have a prediction to be done in backpropagation, but i dont know if i can use any cost function.
Are cost function dependent on the activation function that we use?
If i use sin(x) as activation function then what will be the cost function?
Answer: 1) In the course Machine Learning on Cursera, Andrew Ng provides this cost function: J(theta) = -1/m*( y*log(h(X*theta)) + (1-y)*log(1-h(X*theta)) ),
where log is a natural logarithm, h(X*theta) is output from NN. Apparently, this comes from Kullback–Leibler divergence and Cross-entropy.
2) The general idea is that your cost function is convex and classifier via optimization function finds one global minimum. If you use the above equation for classification such that your ys are 0 or 1, this function will be convex.
As a side note, the cost function J(theta) = 1/2*( h(x) - y )^2 is not convex when you use NN for classification.
3) Yes, especially for gradient calculation whose form is different depending on an activation function.
4) First of all why would you invent the wheel if it's already invented?
It's tricky question but I can give some clues. Your Cost function has to

give ideally 0 when output is exactly as it supposed to be:

h(x)=1 given x and y is 1
h(x)=0 given x and y is 0

The cost function has to give you any huge number otherwise, e.g. h(x)=0 when y=1 etc.
The cost function has to be convex.

Taking into account this features, you would have to work out the Cost Function. Besides, it looks like if you used sin(x), you would probably have to limit your argument X*theta to -pi ... pi.
Comment: I think that the first one is a cost function for classification problem (it assumes that y matrix consists of only zeros and ones).
Answer: Actually, ZikO, you should check the coursera materials again.  The first cost function is still non-convex.  Perhaps you are confusing neural networks with logistic regression.  In the latter, using the entropic cost-function does indeed make the problem convex, whereas ordinary least squares does not.  In neural networks, both cost functions are non-convex.  According to Prof. Ng, however, this is not a big problem for neural networks.


How to make all menu links without www? (shortened menu links)

Question: I've seen a few sites, not necissarily Drupal sites, in which the menu links, are without www. (that is the Cname DNS record).
Drupal 7 shortens links from http://www.barackobama.com to be www.barackobama.com
I am asking if it is possible to create links without the Cname even, I.E that the final result would be:
barackobama.com

Can be done from inside the Drupal GUI? If not, please at least example how will you do so from the .htaccess file?
Answer: No, this is something that is been handle at the server or DNS level. From the GUI, you do not have control of where you application (Drupal) can will run.
If you are running Apache you can add this code to your .htaccess
RewriteEngine On
RewriteCond %{HTTP_HOST} ^your-site.com [NC]
RewriteRule ^(.*)$ http://www.your-site.com/$1 [L,R=301]

Source: Force drupal 7 to place "www" in front of urls
Comment: Benia, I have added the information on how to do it from the .htaccess.
Comment: How will you do so from the .htaccess (Hope it's okay by you, that I ask here to expand your answer with that data)...


Content Pane on Landing Page not getting Context

Question: I thought that would be fairly easy: I am working with Panopoly and I have multiple Landing Pages, a Vocabulary, Content Items and a View with a Content Pane.
The user can select one term per Landing Page (term reference) on creating the lp. Also the content items have one of the terms from the vocabulary attached (as well via term reference).
The View lists all the content items with a contextual filter by term. By default the content pane is part of a newly created Landing Page. So, in this simple case, I want the user to pick a term from the vocabulary and subsequently let the content tagged with this term appear on that landing page via the content pane.
What I get working is the contextual filter "Has taxonomy term ID" with "Argument Input: Input on pane config" Now I can pick a term through the IPE.
However for more complex applications I would like to hand the term selected by the user on creation of the Landing Page (in the edit form) to the content pane, so that the user doesn't have to set it on each content pane seperatly.
Any ideas?
Comment: I try to rephrase the important part:
Comment: On creation of a Landing Page the user selects a term from a vocabulary via term reference. This term shall be used as an argument in a content pane which is part of the Landing Page.
When I switch the argument input to "Input on pane" and add the argument into the pane via the IPE it works. However, I would like to hand over the argument by context. That's what doesn't work for me.
Comment: I' using the Panopoly distribution on pantheon.io with drupal 7.43, panels 7.x 3.5 and views 7.x 3.11
Answer: Ok, the solution is pretty easy, but due to Views complexity it took my some time to figure it out. In my setup, there is no filter available. My mistake was, that I thought there IS a fitler available which is why I did not fill in the upper section. Since my filter is not in the url, I had to select "Load default filter from node page, that's good for related taxonomy terms".
That's all the magic ;)