autocomplete not ful complete

Question: I have written an autocomplete function.
When I click on #input3 it starts to generate what I have typed.
Example: "apple" I type "app" and I click to select "apple". What I select should be sent to the src and updated in #input2.
Problem: What is sent to the src is what I have typed and not what I have selected. Why?
<code>.autocomplete({
    source: function(request, response) {
        $.ajax({
            url: src,
            fillin:true,
            dataType: "json",
            data: {
                term : request.term,
                c3 : $("#input3").val()
                },
            success: function(data){
                response(data)
                }
            });
        },
    minLength: 0,
    delay: 300
    })
.change(function(request2, response) {
    $.ajax({
        url: src,
        dataType: "json",
        data: {
            term : request2.term,
            c1 : "search",
            c3: $("#input3").val()
            },
        success: function(data){
            $("#input2").val(data);
            }
        });
    })
</code>
Comment: bind custom event on the input2, then trigger it by select: and change event of autocomplete.
Comment: How do I trigger it by select?
Comment: Before asking another question, go back and select an answer to one of the _7_ open questions you have.
Comment: Opps sorry, didn't know I had to Answer them.
Comment: Arhh now I get it, I have to click on the tick!
Comment: execute select: as Kyokasuigetsu show for change, trigger event by trigger method of jquery;
Answer: I have solve it. I add the cod after .autocomplete
<code>        focus: function(event, ui) {
            $("#txtBufferTwo").val(ui.item.value);
            event.preventDefault();
            },
</code>
Follow by a hidden field.

What I did was once selection was click, the value is assign to the hidden field and submit the value of the hidden field.
If there is any better methods feel free to post here
Answer: You can use the change event in jquery ui autocomplete:
<code> $("#your_input_id").autocomplete({
            source: availableTags,
            change: function(){
            console.log($(this).val());//selected value
            }
 });
</code>
Comment: I added the code right before 'minLength: 0,' It doesn't respond.

autocomplete not ful complete


Paginação de produtos com PDO

Question: Preciso criar uma paginação para o meu banco de dados com 180 produtos, só que as imagens sem paginação aparecem todas as 180 uma do lado da outra, como posso fazer para limitar as imagens 10 por pagina lado a lado?
Eis o meu código:
<?php
echo'

';
$conn = new PDO("mysql:host=localhost;dbname=loja", "root", "");
$stmt = $conn->prepare("SELECT * FROM `produtos` ORDER BY `id` ASC ");
$stmt->execute( );
$linha = $stmt->fetch(PDO::FETCH_ASSOC);
while($linha = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo'
';
    echo'

'.$linha['nome'].'

';
    echo "

";
    echo '<button type="button" name="" value="" class="quero">Eu Quero!</button>';
}
echo "

";
?>

Comment: Relacionado: [Como limitar a quantidade de páginas mostradas numa paginação?](http://pt.stackoverflow.com/a/34854/91)
Answer: Para limitar a quantidade de registros duma consulta, utilize a cláusula LIMIT.
SELECT * FROM `produtos` ORDER BY `id` ASC LIMIT 10

Comment: pois eu gostaria de criar uma paginação com os links para a pagina tipo anterior e proximo.
Comment: Dê uma lida no link que o rray comentou na sua pergunta.
Comment: vou testar aqui rray, vlw pela ajuda.
Comment: Agradeço a ajuda , consegui! muito obrigado!

Paginação de produtos com PDO


Changing text by clicking an image

Question: I am a javascript noob.
I want clicking on the images to change the text in a span
What I have so far:
Image:

Span:
    My Initial Text

I dont know what should follow "document." and I assume i need javascript in the header or something?
I was referencing this post: click on image and change a text
I have no idea what I'm doing here. I don't understand js,  I'm a designer!
Comment: I was also having problems because I realized the text I wanted to change it to had an apostrophe, so it was screwing up the code- so I used ' instead
Answer: Span's do not have value properties.  You need to use innerHTML in this case, like so:

This will change the text of the first element with name videoTitle on your page.
Fiddle: http://jsfiddle.net/duffmaster33/7j59H/
Answer: I think you are looking for this:-
 document.getElementsByName('videoTitle')[0] // assuming this is the first element with
                                             //the name `videoTitle`
.getElementsByTagName('strong')[0]
 .innerHTML = 'My Text'

SO it will be
My Initial Text

This is native old way and is supported in all browsers.

Demo
Answer: I recommend do something like this:

or

I also advice to give the span an id and select it by ID

Changing text by clicking an image


Does Promise.resolve wait for the passed promise to fulfill?

Question: If I was to have an active promise and I wanted to start a new promise but wait until that one was fulfilled would
var newPromise = Promise.resolve(stillActivePromise);

mean any chains on newPromise onwards would wait until stillActivePromise had fulfilled?
(lets pretend someActivePromise has a setTimeout(..., 10000); or something so you may want to start chaining new stuff but waiting for existing stuff to fully fullfil, be it a rejection or a resolution)
Comment: yes it does, and will also fulfill to rejected state if `stillActivePromise` rejects
Comment: yeah thats what I had hoped, can you put this as an answer so I can give you the points.
Answer: if Promise.resolve is given a "pending" promise as it's argument, it will "wait" for that promise to resolve (fulfill or reject) and will take on the state and value of the passed in promise


Alinhamento de div

Question: Eu possuo uma tabela que é construída dinamicamente com as informações de um diretor de filme. E preciso mudar a estrutura para uma div, principalmente pela questão de responsabilidade, hoje ao reduzir o tamanho do componente que armazena essa table, o texto acaba se sobrepondo;
Hoje ela é assim:

.label{
  font-weight: bold;
  text-align: right;
}

.blue-box{
  background-color: green
}

  Nome:
  Del Toro
  Data de cadastro:
  19/05/2017
  Data de atualizacao:
  19/05/2017

  Categoria de produto:
  Diverso
  Ultimo Prêmio:
  Leão De Ouro
  Filme Indicado
  Shape of Water

Com div eu consegui fazer boa parte do trabalho, entretanto algumas coisas como o alinhamento presente nos labels eu não consegui fazer de jeito nenhum:

.label{
  font-weight: bold;
  float: left;
  text-align: right;
  display: inline;
  margin-right: 5px
}

.blue-box{
  background-color: aquamarine;
  overflow: hidden;
}

.father{
  float: left;
  margin: 0px 5px 0px 5px ;
}

.content{
  float: left;
  display: inline;
}

  Nome:

    Del Toro

  Data de cadastro:

    19/05/2017

  Data de atualizacao:

    19/05/2017

  Categoria de produto:

    Diverso

  Ultimo Prêmio:

    Leão de Ouro

  Filme indicado:

    Shape of water

Tem alguma forma de preservar esse alinhamento dos labels como se fosse na table apenas com HTML?
Ou vou ter que trabalhar com JS para tentar verificar a largura dos labels e setar como o maior elemento?
Answer: Acrescente no .father
width:30%;

Veja se resolve o seu problema

.label{
  font-weight: bold;
  float: left;
  text-align: right;
  display: inline;
  margin-right: 5px
}

.blue-box{
  background-color: aquamarine;
  overflow: hidden;
}

.father{
  float: left;
  margin: 0px 5px 0px 5px ;
  width:30%;
}

.content{
  float: left;
  display: inline;
}

  Nome:

    Del Toro

  Data de cadastro:

    19/05/2017

  Data de atualizacao:

    19/05/2017

  Categoria de produto:

    Diverso

  Ultimo Prêmio:

    Leão de Ouro

  Filme indicado:

    Shape of water

Answer: Se deseja manter as dimensões das células como aconteceria com tables, trabalhar com o atributo CSS display pode resolver o seu problema.
Atributos display correspondentes aos elementos da tabela:
table { display : table}
tr { display : table-row}
thead { display : table-header-group }
tbody { display : table-row-group}
tfoot { display : table-footer-group }
col { display : table-column}
colgroup { display : table-column-group }
td, th { display :  table-cell }
caption { display : table-caption }

Fonte: maujor.com
Aplicado ao seu código ficaria assim:

.label{
  font-weight: bold;
  text-align: right;
  display: table-cell;
  margin-right: 5px
}

.blue-box{
  background-color: aquamarine;
  overflow: hidden;
  display: table;
}

.father{
  margin: 0px 5px 0px 5px ;
  display: table-row
}

.content{
  padding-left: 10px;
  display: table-cell;
}

      Nome:

      Del Toro

      Data de cadastro:

      19/05/2017

      Data de atualizacao:

      19/05/2017

      Categoria de produto:

      Diverso

      Ultimo Prêmio:

      Leão de Ouro

      Filme indicado:

      Shape of water

Alinhamento de div


Maximizing the volume of the convex hull of $N$ points in the unit ball

Question: Suppose we are given an integer $N\ge4$, and we have to pick $N$ points in a unit ball in $\mathbb R^3$ to maximize the volume of their convex hull. Are those points necessarily on the surface of the ball? Can we generalize the result to $\mathbb R^n$?
For the similar problem in $\mathbb R^2$ the answer seems obvious: we always have to pick the vertices of a regular $N$-gon inscribed in the disk, so they always lie on the disk boundary.
Comment: Perhaps I am not understanding the question, but if one of the points $P$ is interior to the ball can it not be extended along the radius containing it to the point $P^\prime$ on the surface of the ball to form a convex hull with greater volume?
Comment: Or perhaps the difficulty arises in showing that the new convex hull contains the old as a subset?
Comment: Note that by increasing all pairwise distances in a set of points it is actually possible to decrease the volume of their convex hull.
Comment: I see, obviously I am out of my level here. But it is an interesting problem, I will continue to think about and try to see why my suggested solution does not work.
Answer: Take a point $Q$ in the interior of the convex hull of points $P_1,\cdots,P_N$ and extend the rays $QP_k$ to the points $P_k^\prime$ on the surface of the ball to get a convex hull containing the old yet with volume not less than the old.
Comment: Note that if point $A$ is in Conv$\{P_i\}$ then there are $P_j,P_k$ such that $A$ lies on the segment $P_jP_k$, thus $A$ also must lie in the convex hull of segments $P_jP_j^\prime$ and $P_kP_k^\prime$ therefore $A$ is also in Conv$\{P_i^\prime\}$. So Conv$\{P_i\}\subseteq$Conv$\{P_i^\prime\}$.
Comment: "not less" only means the points can be picked on the surface, not that they are necessarily on the surface. Note that, for example, without the requirement $N\ge4$ the answer to my question would be "no".


BorderLayout SOUTHEAST?

Question: My question is:
How to add a JPanel to a BorderLayout in the South - East?
This is my group of buttons:
buttonsPanel = new JPanel();
buttonsPanel.setLayout(new GridBagLayout());
buttonsPanel.add(cancel);
buttonsPanel.add(previous);
buttonsPanel.add(next);

And the cancel, previous and next buttons are JButtons-s, and buttonsPanel is a JPanel. Declarations:
JPanel buttonsPanel;
JButton cancel;
JButton previous;
JButton next;

And my JFrame:
JFrame mainWindow; - the declaration. The rest of code:
mainWindow.setJMenuBar(menubar);
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.getContentPane().setLayout(new BorderLayout());
mainWindow.setSize(new Dimension(screenW / 3 + 200, screenH - 200));
mainWindow.setMinimumSize(new Dimension(screenW / 4, screenH - 500));
//mainWindow.getContentPane().add(BorderLayout.EAST, BorderLayout.SOUTH, buttonsPanel);
int w = mainWindow.getWidth();
int h = mainWindow.getHeight();
x = (screenW - w)/2;
y = (screenH - h)/2;
mainWindow.setLocation(x, y);
mainWindow.setVisible(true);

So what can I do to move the buttonsPanel in the South - East of the main window?
Please help me.
Thanks in advance,
Mateiaru
Answer: Create a JPanel with a BorderLayout, add this panel to SOUTH position of the main panel.
Create another JPanel, add your buttons to this panel (using what ever layout manager you need.
Now add the "button" panel to the south panel at the EAST position
Answer: If I understand correctly, you would like to have your button panel at the south of your frame, and your buttons to be at the right of the button panel.
To do that, I would use a horizontal BoxLayout, containing a glue as its first element, to layout the buttons inside their button panel. Then I would add this button panel at the south of the content pane.
Read how to use those two layout managers in the swing tutorial, because you're confused about how a BorderLayour works: you can't add something at the south and at the east of such a layout.
Note that the tutorial page about the BoxLayout has an example that does exactly what you want.
Answer: buttonsPanel = new JPanel( new FlowLayout(FlowLayout.RIGHT) );
mainPanel.add(buttonsPanel, BorderLayout.SOUTH);

BorderLayout SOUTHEAST?


Wrong results due to NaN (package InfoTrad)

Question: I'm trying to use a package called InfoTrad.
I tried to compute an example given, but it doesn't produce the same results for me. Could the computing capacity be a reason for this? I get a bunch of NaNs, which are probably the reason for the wrong results. The code is as follows:
<code>library(InfoTrad)
Buy <- c(350,250,500,552,163,345,847,923,123,349)
Sell <- c(382,500,463,550,200,323,456,342,578,455)
data = cbind(Buy,Sell)
#par0 = (al,del,mu,eps_b,eps_s)
par0 = c(0.5, 0.5, 300, 400, 500)

EHO_out = EHO(data)
model = optim(par0, EHO_out, gr = NULL, method = c("Nelder-Mead") , hessian = FALSE)
print(model)

#output
$par
[1] -216494.389  631863.422     380.386     307.447     435.555

$value
[1] -44532.65
</code>
The real result (from the example) should look like this:
<code>$par
[1] 0.9111102  0.0001231429     417.1497     336.075     466.2539
</code>
Here's the link to the paper, where they explain the package: https://www.semanticscholar.org/paper/InfoTrad%3A-An-R-package-for-estimating-the-of-%C3%87elik-Tini%C3%A7/9efb3f9de4781bed286e16e9f4e2a87653bea693
Is there any way to change the limit values, so that I do not produce any NaNs or at least less?
Thank you in advance.
I'd appreciate it, if you could run the code once and tell me, if your results differ from mine. (I just want to know, if it's my computer's fault)
Answer: Apparently the problem lies within the package (I've tested the code on multiple computers with different computing capacities). Sadly I don't know where exactly it lies, but I've found another package called pinbasic which works better and has more output options:
https://cran.rstudio.com/web/packages/pinbasic/vignettes/pinbasicVignette.html


hook_context_default_contexts() ?

Question: I used Bulk Export to export all my Context definitions into my module in a function that implements hook_context_default_contexts().  However, my default context definitions do not appear if I delete the ones in the database.
Does this hook no longer work in Drupal 7?
Answer: Here's the piece I was missing:
<code>/**
 * Implementation hook_ctools_plugin_api().
 *
 * Makes module compatible with context 3.
 */
function MY_MODULE_ctools_plugin_api($module, $api) {
  if ($module == 'context' && ($api == 'plugins' || $api == 'context')) {
    return array('version' => 3);
  }
}
</code>
Answer: It does work in Drupal 7, here you can see an example of a valid code from export created by Features module:
<code><?php
/**
 * @file
 * vw_product_search.context.inc
 */

/**
 * Implements hook_context_default_contexts().
 */
function vw_product_search_context_default_contexts() {
  $export = array();

  $context = new stdClass();
  $context->disabled = FALSE; /* Edit this to true to make a default context disabled initially */
  $context->api_version = 3;
  $context->name = 'shop';
  $context->description = '';
  $context->tag = '';
  $context->conditions = array(
    'path' => array(
      'values' => array(
        'shop' => 'shop',
        'search' => 'search',
      ),
    ),
  );
  $context->reactions = array(
    'block' => array(
      'blocks' => array(
        'facetapi-WVeJBMTHZn1PCfPfrIPnjg1v8m19Gkqd' => array(
          'module' => 'facetapi',
          'delta' => 'WVeJBMTHZn1PCfPfrIPnjg1v8m19Gkqd',
          'region' => 'sidemenu_left',
          'weight' => '-10',
        ),
        'facetapi-H24ObDRB0Wq0KpRW1qalIgb7TvlKP7aj' => array(
          'module' => 'facetapi',
          'delta' => 'H24ObDRB0Wq0KpRW1qalIgb7TvlKP7aj',
          'region' => 'sidemenu_left',
          'weight' => '-9',
        ),
        'facetapi-GxgmQn2y5194O1hZ7qJIROIO63v5BKtG' => array(
          'module' => 'facetapi',
          'delta' => 'GxgmQn2y5194O1hZ7qJIROIO63v5BKtG',
          'region' => 'sidemenu_left',
          'weight' => '-8',
        ),
        'facetapi-zNmFD0ELaD0hTUYX9jyfnhkzHkz5GVvQ' => array(
          'module' => 'facetapi',
          'delta' => 'zNmFD0ELaD0hTUYX9jyfnhkzHkz5GVvQ',
          'region' => 'sidemenu_left',
          'weight' => '-7',
        ),
        'facetapi-kSPIS0vKCobobG533MMOWru8Q42SmByu' => array(
          'module' => 'facetapi',
          'delta' => 'kSPIS0vKCobobG533MMOWru8Q42SmByu',
          'region' => 'sidemenu_left',
          'weight' => '-6',
        ),
        'quicktabs-shop_facets' => array(
          'module' => 'quicktabs',
          'delta' => 'shop_facets',
          'region' => 'sidemenu_right',
          'weight' => '-8',
        ),
      ),
    ),
  );
  $context->condition_mode = 0;
  $export['shop'] = $context;

  return $export;
}
</code>
Make sure that your module is enabled, that the hook implementation is correct and your caches flushed.

hook_context_default_contexts() ?


Update somar produto de uma tabela para outra tabela

Question: A query abaixo ela pega o produto da tabela VENDAS onde for igual o produto da tabela ESTOQUE e soma a quantidade, ocorre que essa query só funciona se tiver 1 linha de venda/produto, gostaria de fazer ela percorrer quantas linhas a VENDA tiver e não só uma, não sei se precisa usar while ou for.
UPDATE PRODUTOS  SET ESTOQUE = ESTOQUE +  ( SELECT QUANTIDADE FROM VENDAS WHERE CODIGO=' " + Convert.ToInt32(codigoTextBox.Text) + " ' ) WHERE  Codigo = ( SELECT CodigoProduto FROM VENDAS WHERE CODIGO= ' " + Convert.ToInt32(codigoTextBox.Text) + "' )";

Poderiam me ajudar? Obrigado.
Comment: Bem vindo ao StackOverflow. Edite o seu código de modo a colocar o código todo no formato de código. Pode selecionar o código e clicar na opção { }
Comment: o problema de "só funciona com uma linha" poderia resolver colocando um sum na sub-consulta: `SELECT sum(QUANTIDADE) FROM VENDAS WHERE CODIGO...` porém tem que ver  o que significa cada "codigo" desse aí, a segunda sub-query pode ser melhorada, mas tem que saber qual a lógica
Answer: Por favor, tente dessa forma e veja se resolve pra você:
UPDATE PRODUTOS
SET ESTOQUE = ESTOQUE + V.QUANTIDADE
FROM PRODUTOS P
INNER JOIN (
    SELECT CodigoProduto, SUM(QUANTIDADE) AS QUANTIDADE
    FROM VENDAS GROUP BY CodigoProduto) as V ON V.CodigoProduto = P.CodigoProduto
WHERE V.CodigoProduto = ' " + Convert.ToInt32(codigoTextBox.Text) + " ';

Comment: Obrigado @NDelavi, deu certo só fiz umas alterações abaixo e funcionou. `UPDATE PRODUTOS
SET ESTOQUE = ESTOQUE + V.QUANTIDADE
FROM PRODUTOS P
INNER JOIN (
    SELECT CODIGO,CodigoProduto, SUM(QUANTIDADE) AS QUANTIDADE
    FROM VENDAS   GROUP BY CODIGO,CodigoProduto) as V ON V.CodigoProduto = P.Codigo
WHERE V.CODIGO = 382`


Multiple Registration forms (with unique roles)?

Question: I have a scenario where I want users to be able to register via the standard registration form and be assigned a role of "tenant". I also need the ability for site administrators to be able to create either "tenant" roles (with unique fields) or "landlord" roles (with their own unique fields and roles).
I've looked at profile2, user role field, and field permissions as possible modules, but I'm unable to see a way of getting this to work. How can I make certain fields required for one role, but hidden for another?
Comment: Do you want to hide the fields in registration forms ?
Comment: That would be great, but even that's not necessary. I'm stuck now because if I make a field required for one role it's required for both roles.
Answer: Sounds like profile2_regpath will help you.
Answer: Multiple registration should help you.


'meteor run android-device' takes forever installing the Cordova plugins

Question: Is this just a mistake on my system here, but it takes at least 15 minutes or even longer to "meteor run android-device". It hangs at 90% of installing the cordova plugins.
In detail I have 2 cordova-packages mdg:camera and mdg:geolocation but that doesn't seem to be the problem.
It is getting slow when I add the plugin email@example.com which is a native map.
I switched to developing on the browser, and also the google chrome browser developer tools, but sometimes I need to see how it looks on an actual device, and if it runs there for that matters.
Also once it runs it doesn't update any changes or only very slowly.
On the browser everything is ok, loading times, "hot code push".
I thought it would get better with the latest update of meteor announcing the very same thing, but I am already running email@example.com.
Cannot be my internet connection either, it's 100mbit.
It really seems to be the maps plugin, also as others suggested, it helps (but only a little) to
rm -rf .meteor/local/cordova-build/
rm -rf .meteor/local/build/
Is there another way to minimize loading times?
Answer: Turns out it was really the google maps plugin. Since I removed it the deployment is faster now, don't know if it is only in case of this special plugin or a general problem with meteor/cordova.
Answer: It's a general problem with the meteor version you are using. It's fixed in Meteor version 1.2.1 and above.
Comment: Nope, problem still persists at 1.4 and above


Why won't this update in hook_update_n() run in batches correctly?

Question: I am working on this issue in the Feeds issue queue: https://www.drupal.org/node/2341407
I am trying to make the updates to the importers run in batches. I can't figure out why this won't run in multiple batches when there are multiple importers. What happens is instead of seeing a progress bar reload a few times when running update.php, it loads once and processes all importers in a single batch.
The code works well except for batching. Below is the code. Thanks in advance!
<?php

/**
 * Fix importer mappings for file and image fields to use :uri convention.
 */
function feeds_update_7210(&$sandbox) {
  // If this is the first pass through this update function then set some variables.
  if (!isset($sandbox['total'])) {
    // Load all importers.
    $importers = feeds_importer_load_all(TRUE);
    $sandbox['total'] = count($importers);
    $sandbox['current'] = 0;
  }

  foreach ($importers as $importer) {
    $processor = $importer->processor;
    $config = $processor->getConfig();
    foreach ($config['mappings'] as $id=>$mapping) {
      // Act on mappings that do not contain a colon.
      if (!strpos($mapping['target'], ':')) {
        // Get field data. Check if $info is empty to weed out non-field mappings like temporary targets.
        $info = field_info_field($mapping['target']);
        if (!empty($info)) {
          // Act on file or image fields.
          if (in_array($info['type'], array('file', 'image'))) {
            // Add ':uri' to fix the mapping.
            $config['mappings'][$id]['target'] = $mapping['target'] . ':uri';
          }
        }
      }
    }
    // Add the updated config and save the importer.
    $processor->addConfig(array('mappings' => $config['mappings']));
    $importer->save();

    drupal_set_message(t('@importer fields have been updated.', array('@importer' => $importer->id)));
    $sandbox['current']++;
  }

  // Set the value for finished. If current == total then finished will be 1, signifying we are done.
  $sandbox['#finished'] = ($sandbox['current'] / $sandbox['total']);

  if ($sandbox['#finished'] === 1) {
    drupal_set_message(t('@importers importers processed.', array('@importers' => $sandbox['total'])));
  }
}

Answer: Why are you expecting it to work as a batch, it's doing exactly what you're asking it to do and processing all the importers in the foreach loop!  foreach ($importers as $importer)  It's not magic, it can't assume that's what you want to batch  :o)
Try this instead (obviously I haven't tested it, I've just typed it straight into the text editor here - but it's essentially your code so it should be fine);

/**
 * Fix importer mappings for file and image fields to use :uri convention.
 */
function feeds_update_7210(&$sandbox) {
  // If this is the first pass through this update function then set some variables.
  if (!isset($sandbox['progress'])) {
    $sandbox['importers'] = feeds_importer_load_all(TRUE);
    $sandbox['progress'] = 0;
    $sandbox['max'] = count($sandbox['importers']);
  }

  $importer = array_pop($sandbox['importers']);
  $processor = $importer->processor;
  $config = $processor->getConfig();
  foreach ($config['mappings'] as $id => $mapping) {
    // Act on mappings that do not contain a colon.
    if (!strpos($mapping['target'], ':')) {
      // Get field data. Check if $info is empty to weed out non-field mappings like temporary targets.
      $info = field_info_field($mapping['target']);
      if (!empty($info)) {
        // Act on file or image fields.
        if (in_array($info['type'], array('file', 'image'))) {
          // Add ':uri' to fix the mapping.
          $config['mappings'][$id]['target'] = $mapping['target'] . ':uri';
        }
      }
    }
  }
  // Add the updated config and save the importer.
  $processor->addConfig(array('mappings' => $config['mappings']));
  $importer->save();

  $sandbox['progress']++;

  // Set the value for finished. If progress == max then finished will be 1, signifying we are done.
  $sandbox['#finished'] = ($sandbox['progress'] / $sandbox['max']);

  if (empty($sandbox['importers'])) {
    return t('@importers importers processed.', array('@importers' => $sandbox['max']));
  }
}

For hints about my alterations see the API documentation - note that the naming convention changes don't alter anything, I just made them for Drupal core consistency.  The most important thing to note is that all I've really done, is to remove the foreach loop so one importer gets used at a time.
NOTE: For clarification (as it's really not obvious) the percentage shown relates to the number of batch operations run - not the amount of passes through one batch operation.  See _batch_process():
// Total progress is the number of operations that have fully run plus the
// completion level of the current operation.
$current    = $total - $remaining + $finished;
$percentage = _batch_api_percentage($total, $current);

On a normal batch operation you'd pass in several separate operations like this;
$batch = array(
  'operations' => array(
    array('batch_example_one_process', array($options1, $options2)),
    array('batch_example_two_process', array($options3, $options4)),
  ),

And you'd see 50% completion only after batch_example_one_process has completed.  I guess you can see that your code is working correctly though, as it clearly only processes one processor per pass - as long as they all get processed, you can confirm that batch api is working correctly.
Comment: Aha, I missed the part about only returning one value. I changed your code to use `array_pop()`, but when I run the update from update.php, it still seems to run as a single batch (the progress bar just completes in one shot and doesn't break up to run multiple times). If I output `$sandbox['progress']`, I see it outputting multiple times and incrementing correctly when the update completes. Any ideas why this happens? Here is the current code: https://gist.github.com/vinmassaro/049109c69d59aa2d33c0
Comment: Try the updated code - apologies, the API documentation was a little vague around the return for a successful completion message.
Comment: Still seems to complete in one batch operation. The progress bar goes immediately to 100%. I still can't figure out why it's not getting the number of items, then running the batch that many times and showing a correctly segmented progress bar.
Comment: Ah sorry I should have pointed this out before, the percentage is based on operations not batches.  It would have saved your confusion.  As you can't put code blocks in comments, I've edited my reply post.
Comment: This was not clear at all from the API docs! Thanks!


Conflito em Requisição

Question: Estou com dificuldade para fazer a pagina carro.php funcionar abrindo na DIV visual através do link ao acessar o endereço provisório "https://www.pbfjacarepagua.com.br/teste/index.php"
Mas quando entro com o endereço "https://www.pbfjacarepagua.com.br/teste/carro.php" os efeitos funcionam.
Deixo abaixo os códigos usados.
Pagina index.php:
<!DOCTYPE html>

    <meta charset="UTF-8"/>

Script da Requisição "rotinas.js"
//Tratamento dos Status
function tratarEventos(e){
    if (e.target.readyState == 4){
        if (e.target.status == 200){
            document.getElementById('visual').innerHTML = e.target.responseText;
        } else if (e.target.status == 404){
            document.getElementById('visual').innerHTML = "
Arquivo não encontrado.
";
        }
    }
}

//Ir para a pagina carro.php
function consultarCarro(){
    var req = new XMLHttpRequest();
    req.open('GET','carro.php',true);
    req.onreadystatechange = tratarEventos;
    req.send();
    //aborta o request
xhr.abort();
}

Pagina carro.php:
<!doctype html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="stylesheet" type="text/css" href="css/xzoom.css" media="all" />

Se os amigos puderem me dizer onde estou errando, ficarei agradecido.
Comment: OK dvd, inclui os .js na index.php, mas também não funcionou. Dê uma olhada, e veja o que esta acontecendo.
Comment: tem uma variável `xhr`que não existe e está dando erro nesta linha: `xhr.abort();`
Comment: Mas não creio que seja esse o problema. É que eu não sei dizer agora com certeza se carregando .js via Ajax irão funcionar. Vc pode tirar essa dúvida colocando um `alert("teste");` em um dos .js para ver se o alerta aparece. Volta como estava antes pra testar.
Comment: Acho que resolvi trocando o script da requisição. Acabei de postar com a alteração no endereço provisório para você poder dar uma olhada e me dizer o que acha, se pode ficar desse jeito.  Vou responder a minha pergunta com as alterações que fiz...
Comment: Abri a index e só apareceu uma imagem do carro. Ao clicar nela nada acontece.
Comment: Tenta agora, pois estava transferindo os arquivos com as alterações, OK?
Comment: Agora funcionou..
Answer: Consegui resolver trocando o script da Requisição e inserindo o , e ficou assim os código funcionando:
Pagina index.php:
<!DOCTYPE html>

    <meta charset="UTF-8"/>
    <title></title>

Script da Requisição - rotina.js:
////// Para visualizar o item selecionado //////
$(document).ready(function(){
    $('#carro').click(function(){
       $.ajax({
           url:'carro.php',
           success:function(data){
           $('.visual').html(data);
           }
       });
    });
});

Pagina carro.php:

<link rel="stylesheet" type="text/css" href="css/xzoom.css" media="all" />

Espero que possa vir ajudar alguém no futuro.

Conflito em Requisição


Partial start date with end date output views

Question: I'm using views to output a list of nodes with dates. Some node dates have both a start and end date inserted.
If both a start and end date exists, i would like the date to be outputted only taking the day from the start date.
Current: 9 January 2018 - 10 January 2018
Desired: 9 - 10 January 2018
I've tried using a custom field and rewriting the results in views, but this doesn't work. I've also looked in the pre_render and preprocess functions and only see the start date.
Any ideas?
Comment: Are the start and end dates separate fields, or is this a single daterange field?
Comment: It's a single date range field
Answer: I have resolved this issue using the compact daterange module, and using one of the committed patches.
https://www.drupal.org/project/daterange_compact
Answer: There is a possibility to do it without an extra module

Add a field in views for the start date and use the custom formatter with j as the custom format. This will output the date without month or year.
Add a field for end date and format this date as you wish.
Rewrite Results of end date field (or add a custom field) and put the appropriate token replacements

{{ field_start_date }} - {{ field_end_date }}

Note: this solution cannot handle properly dates spanning 2 or more months


Confidence bound for a family of lines

Question: I have a family of lines $y_i= a_ix+b_i$ where the pairs $(a_i,b_i)$ are generated by a random process.
I can fix $x$ and generate a family of points $y_i$ for which I can estimate the mean and the confidence bound. If I repeat this for all $x$, I can generate a function $\bar{y} = f(x)$ describing the mean value for each $x$, and another function $\delta_{y,c} = g(x)$ where $c$ is a confidence bound (e.g. 95%), so that for any value of $x$ I have a probability equal to $c$ that $a_ix+b_i$ falls within $\bar{y}(x) \pm \delta_{y,c}(x)$.
As an engineer, I'm solving this problem computing the mean and the confidence interval for a large enough set of $x$ values and then interpolationg between them.
However, is there a way to compute the functions $f(x)$ and $g(x)$ analytically without having to iterate over all possible values of $x$ (that in theory are infinite)?
For the sake of simplicity, let's assume $a_i$ and $b_i$ are normally distributed (but not uncorrelated).
Comment: Certainly. Just use the fact that in the jointly Gaussian case, for any fixed $x$, the corresponding $y$ is normal with the mean $x\,E[a]+E[b]$ and the variance $x^2\,V[a]+V[b]+2x\,Cov[a,b]$ and the standard table of z-values to determine the confidence interval for $y$.
Comment: @fedja would you like to write this into an Answer so that I can accept it? PS: does your conclusion change if $a$ and/or $b$ are not normally distributed?
Answer: I'm posting here the answer that was provided by @fedja in a comment above.
Just use the fact that in the jointly Gaussian case, for any fixed $x$, the corresponding $y$ is normal with the mean $xE[a]+E[b]$ and the variance $x2V[a]+V[b]+2xCov[a,b]$ and the standard table of z-values to determine the confidence interval for $y$.

Confidence bound for a family of lines


Trim transparent background of an image drawn in Canvas with PHP or javascript

Question: I have created an image in my Canvas with HTML5 and I saved it.  My code looks like the one here, in this example:
http://www.worldofwebcraft.com/page.php?id=101&t=HTML5_use_php_and_ajax_to_save_canvas_as_png_on_your_server
My problem is that when I save my image, the whole canvas it is saved and not only the part of it that has a draw on it. So I get an image with a big, transparent background, behind my image, and the image instead of be 50x50 for example, becomes 100x100.
Is there a way to trim this transparent background, either in the JavaScript site, before send the data to the php file, or in the PHP file, after save the image?
Thanks in advance
Answer: If you know what part of the canvas you want. You can create a new canvas element and make it the right size for you and then draw bit of the image you want onto the new canvas and then just do the same thing you are doing but for the second smaller canvas.
<code>var smallCanvas = document.createElement('canvas');
smallCanvas.width = somewidth
smallCanvas.height = someheight
var smCtx = smallCanvas.getContext('2d');
smCtxdrawImage(oldCanvas, sx, sy, sw, sh, dx, dy, dw, dh)
</code>
takes an oldCanvas, clips it to the rectangle(sx, sy, sw, sh), scales it to dimensions (dw, dh), and draws it on the smallCanvas at coordinates (dx, dy).
EDIT:
As per my comment here is a Jquery plugin that does what I have been suggesting.
Here
Comment: Yes you are right, this is what I should use. I found this link https://gist.github.com/784508 which makes exactly what I wanted. Just in case someone has the same problem. Thanks
Comment: the size of the image is not always the same. I have an image that I can change, make it bigger and smaller so every time is different. But maybe there is an html5 function that allows me to get only the part of canvas that has something on it?
Comment: You could use getImageData function, which returns an array of pixels data that you could search through and find where the min and max points are of the image by looking for the first pixels with data in.


Conformal mappings of multiply-connected regions

Question: I'm reading about conformal mappings in Ahlfors' text, and I got to this section:

In the following $\Omega$ denotes a plane region of connectivity $n > 1$. The components of the complement are denoted by $E_1, E_2, \dots, E_n$,  and we take $E_n$ to be the unbounded component. Without loss of generality we can and will assume that no $E_k$ reduces to a point, for it is clear that a point component is a removable singularity of any mapping function, and consequently the mappings remain the same if this isolated boundary point is added to the region.

I think this statement is false. For example, consider the region $\Omega=\{0<|z|<1 \} $ which has connectivity 2, with components $E_1=\{0\}$ and $E_2=\{|z| \geq 1\} \cup \{ \infty \}$.
The function $f(z)=\frac{1}{z}$ maps $\Omega$ conformally onto its exterior $\{|z|>1\}$, and although $E_1$ reduces to point, the singularity of $f$ there is of a pole type (which is not removable).
Am I right here? If so, what do you think the author meant to say?
Thanks!
Comment: View the mappings as holomorphic mappings to the sphere. A pole is a removable singularity then.
Comment: @DanielFischer But introduing $\infty$, what happens to the notions of holomorphicity and conformality?
Comment: Not much. If you know the notion of a manifold, the sphere is one, and maps to/from the sphere are holomorphic/conformal when they are such as expressed in the coordinate charts. We have the two charts $\operatorname{id} \colon \widehat{\mathbb{C}}\setminus \{\infty\} \to \mathbb{C};\; z \mapsto z$, and $\psi \colon \widehat{\mathbb{C}}\setminus \{0\} \to \mathbb{C}; z \mapsto \frac1z\;(\infty \mapsto 0)$. So $f$ is holomorphic/conformal in $\infty$ iff $f\circ \psi$ is holomorphic/conformal in $0$ (supposing $f(\infty)\neq \infty$), $\psi\circ f\circ\psi$ if $f(\infty)=\infty$.
Comment: @DanielFischer Thank you. Correct me if I'm wrong, but Ahlfors never discussed this(?). In that case I'll take it as a definition.
Comment: Looks indeed like Ahlfors never discusses that. But without it, you must have special restrictions on the domains resp. mapping functions that would make the entire theory cumbersome.
Comment: @DanielFischer If you will make your comment into an answer I will accept it.
Answer: Apparently Ahlfors wrote that with mappings between regions of the Riemann sphere in mind.
If you consider only plane regions, as you noticed, an isolated singularity can be a pole, and thus is not a removable singularity of a holomorphic function $f \colon \Omega \to \mathbb{C}$. When considering regions in the sphere, the mappings are viewed as holomorphic mappings $\Omega \to \widehat{\mathbb{C}}$, and then an isolated singularity of a conformal map is necessarily removable - viewed as a holomorphic function, if the isolated singularity is not removable in that sense, it must be a simple pole (by injectivity; a holomorphic function cannot be injective in a punctured neighbourhood of an essential singularity or multiple pole), and extending $f$ by $f(z_0) = \infty$ into the isolated singularity then produces a conformal mapping between regions in the sphere.


Redirecting webapps in nginx content folders

Question: I have setup an nginx + php + wordpress site at www.example.com
When I go to example.com on my browseer I see my wordpress blog as I expect and can work with it flawlessly, no problem there.
But now I wanted to keep using nginx for other webapps without losing the blog.
Ningx content root is at /srv/www/html
Wordpress root is at /srv/www/wordpress/public_html
I wanted to for example create /srv/www/newsite and drop some webapp in there and be able to access it through example.com/newsite, is that possible?
I tried creating the equivalent in sites-available with the following content:
server {
    server_name example.com/newsite www.example.com/newsite;
    access_log /srv/www/newsite/logs/access.log;
    error_log /srv/www/newsite/logs/error.log;
    root /srv/www/newsite;

but it gives me a wordpress page-not-found.
Just to be clear, I want to keep wordpress the way it is now, I want example.com to show me worpdress by default. I just want example.com/newsite to be able to serve its own files.
Answer: Instead of declaring a separate server block, within your example.com server block for wordpress, you can open a new location block, like so:
location ~ /newsite/ {
  root /srv/www/;
}

Comment: you mean to modify the sites-available file for wordpress? I think that would be against good practices. This wouldnt be an app related to worpress but something completely unrelated.
Comment: I'm referring to the nginx configuration file for your domain example.com. The fact that it's wordpress is less relevant than the fact that it's what is managing the domain. Nginx doesn't support URL's in the `server_name` directive, and you can only have one `server {}` code block per `server_name`.
Comment: I tried your advice but same issue remains. I added the new location block on the wordpress config file for nginx. Whe I try to access newsite it still shows me the 404 of wordpress.
Comment: Have you tried moving up the location block higher in the wordpress configuration? What errors are provided in the error log? On CentOS it's located at: /var/log/nginx/error_log


Find the volume of the solid enclosed by the surface $\rho=1+\cos\phi$

Question: Find the volume of the solid enclosed by the surface $\rho=1+\cos\phi$.
How do I set up the triple integral for this? I know that $1+\cos\theta$ is a cardioid but how would it look like as a surface?
Comment: It is the surface of revolution formed by rotating the cardioid.
Answer: The volume is found by integrating $\iiint 1\cdot dV$. The real trick is in finding the bounds. The easiest way to do this would be to set up the integral order with the angle first:
$$V = \int_0^{2\pi}\int_0^2 \int_0^{\cos^{-1}(\rho-1)} \rho^2\sin\phi \:d\phi d\rho d\theta $$
Comment: " The real trick is in finding the bounds. The easiest way to do this would be to set up the integral order with the angle first:".. why?
Comment: @Buraian just as we ask posters to put effort into their questions, we should put effort into quality comments. Would you care to explain your question further? I'm afraid I don't understand what you are asking.
Comment: Maybe this is what the other comment was getting at - why not$$\int_0^{2\pi}\int_0^\pi\int_0^{1+\cos\phi}\rho^2\sin\phi\,d\rho\,d\phi\,d\theta\,?$$


Special character from FTP directory

Question: i´m using the black raccoon class for ftp sessions. getting the content of a FTP directory  like this
arrayHelper.FTPFileName = [file objectForKey:(id)kCFFTPResourceName]

and writing into nsmutablearray
i have some folders with special character like this on the ftp share:
"Heino - Mit Freundlichen Gr\U00b8ssen (Deluxe Edition) (2013) - 320"
How can i convert the string?
i´ve try´ed the following:
NSString *uncodedName = [file objectForKey:(id)kCFFTPResourceName];
        NSLog(@"Uncoded Name is %@",uncodedName);
        arrayHelper.FTPFileName = [NSString stringWithCString:[uncodedName cStringUsingEncoding:NSUTF8StringEncoding]
                                                     encoding:NSNonLossyASCIIStringEncoding];
        NSLog(@"Coded Name is %@",arrayHelper.FTPFileName);

but returns nil...
NSLog:
[7344:c07] Uncoded Name is Heino - Mit Freundlichen Gr¸ssen (Deluxe Edition) (2013) - 320
[7344:c07] Coded Name is (null)
Answer: One can see in the source code of CFFTPStream.c
that CFFTPStream interprets all file names on the FTP server in the "Mac OS Roman" encoding. Your FTP server seems to use Windows encoded file names, which are therefore wrongly converted to Unicode in CFFTPStream.
But you can reverse the process with
NSString *uncodedName = [file objectForKey:(id)kCFFTPResourceName];
NSData *data = [uncodedName dataUsingEncoding:NSMacOSRomanStringEncoding];
arrayHelper.FTPFileName = [[NSString alloc] initWithData:data encoding:NSWindowsCP1252StringEncoding];

Comment: I answered the question even if I can't stand Heino music :-)
Comment: THX a lot! works perfect! ...but my next problem is writing back the string to a nsmutablearray (used for browsing the ftp share) returns me a "Heino - Mit Freundlichen Gr\U00fcssen (Deluxe Edition) (2013) - 320"   ..... me too with the heino music, but he´s covering rock bands in the new album :-)
Comment: @HugoBoss: The NSLog or debugger output often prints special characters using escape sequences, `\U00fc` *is* "ü".
Comment: yes, you´re right! logging just the filename is ok. I need to convert the string back for a ftp request? get an error with the ü in the name..
Comment: @HugoBoss: Yes probably. (I know a bit about encodings, but nothing about the BlackRaccoon project.) You can swap the encodings in the above code to convert back to the encoding needed for the FTP request. Or you can remember both strings and use the converted string only for display, and the original string for requests.
Comment: tried both methods without luck :-( can´t even use the original string to browse, and the back converted also not.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/26300/discussion-between-martin-r-and-hugoboss)
Comment: changing the kCFStringEncodingUTF8 in the brrequest.m to kcFStringEncodingWindowsLatin1 was my solution! of course in combination with martin´s reverse process. Martin thank you very much for your help!!

Special character from FTP directory


How do I destructure this given code into an HTML table and display it?

Question: My instructor has given us this code and asked me to destructure the given code creating and displaying an HTML table. I can destructure it using loops displaying it in the console, but thats as far as I've gotten. How can I display the data into a table using destructuring??

<!DOCTYPE html>

    <title></title>

        Name	Date of Birth	Spoken Languages

Comment: `console.table(userList.people);` ;)  but in all seriousness, use a template engine or view framework...
Comment: Loop through the array, creating elements as you go.
Answer: I don't see that destructuring each person object adds a lot of benefit here, however, I will assume it's meant to be a learning exercise.
You will need to use a loop to iterate over the users.people array. This could be a forEach, for, for in, or I have chosen a for of loop.
You can then destructure the person object on each iteration, and use the separate variables to create and append new DOM elements to the table#table DOM element.

const table = document.getElementById('table');
const users = {
  people: [
    {
      firstName: "Fred",
      lastName: "Smith",
      dateOfBirth: 1980,
      spokenLanguages: {
        native: "English",
        fluent: "Spanish",
        intermediate: "Chinese"
      }
    },

    {
      firstName: "Monica",
      lastName: "Taylor",
      dateOfBirth: 1975,
      spokenLanguages: {
        native: "Spanish",
        fluent: "English",
        intermediate: "French"
      }
    },

    {
      firstName: "Maurice",
      lastName: "Edelson",
      dateOfBirth: 1992,
      spokenLanguages: {
        native: "English",
        fluent: "Spanish",
      }
    },

    {
      firstName: "Kelly",
      lastName: "Lang",
      dateOfBirth: 1982,
      spokenLanguages: {
        native: "English",
        fluent: "German",
        intermediate: "Dutch"
      }
    }
  ]
};

for (const { firstName, lastName, dateOfBirth, spokenLanguages } of users.people) {
    const row = document.createElement('tr')
    table.appendChild(row);

    const nameTd = document.createElement('td');
    nameTd.appendChild(document.createTextNode(`${firstName} ${lastName}`));
    row.appendChild(nameTd);

    const dobTd = document.createElement('td');
    dobTd.appendChild(document.createTextNode(dateOfBirth));
    row.appendChild(dobTd);

    const spokenLanguagesTd = document.createElement('td');
    spokenLanguagesTd.appendChild(document.createTextNode(Object.values(spokenLanguages).join(', ')));
    row.appendChild(spokenLanguagesTd);
}
<!DOCTYPE html>

    <title></title>

        Name	Date of Birth	Spoken Languages

Below are links to the documentation for the functions used in the example:

Document.createElement
Node.appendChild
Document.createTextNode
Object.values
for...of


Override default node form submit handler

Question: I retrieve a node form and replace it's submit callback like this:
<code>$node = entity_create('node', array('type' => 'my_type', 'title' => ''));
$node = entity_metadata_wrapper('node', $node);
$node = my_node_handler($node, 'some_operation') // It's an object factory
  ->ekran()
  ->getEntity() // It returns a DrupalEntityWrapper
  ->value() // Node's stdClass from wrapper;

form_load_include($form_state, 'inc', 'node', 'node.pages');
$form_state = array();
$form_state['build_info']['args'] = array($node);
$form = drupal_build_form('my_type_node_form', $form_state);

// Remove save, preview, delete, ....
remove_default_actions_from_form($form);
$form['actions']['send'] = array(
  '#type' => 'button',
  '#value' => t('My Button'),
  '#submit' => array('my_callback'),
  '#executes_submit_callback' => FALSE,
  '#name' => 'name_here',
);
</code>
But Form API does not care what my submit callback is or even, #executes_submit_callback, It always sends the node form to node_form_submit and the node is saved.
Even changing the callback like this:
<code>$form['actions']['send'] = array(
  '#type' => 'button',
  '#value' => t('My Button'),
  '#submit' => array('some_non_existing_function_hahaha_hohoho'),
  '#executes_submit_callback' => FALSE,
  '#name' => 'name_here',
);
</code>
Will not produce an error. What's wrong here? I used entity_form(args...) for retrieving the form and this thing happened, And changed it to drupal_build_form, Still the same thing.
Also along all these, I have added:
<code>  $form['#submit'] = 'die';
</code>
Which wont happen (not even an error about die not being callable from call_user_func...);
Answer: Wow, The magic was using form alter along side the menu callback which created and handled the node like this:
<code>function my_module_form_node_form_alter(&$f, &$fs) {
  $f['actions']['my_action'] = array(
    '#type' => 'submit',
    '#value' => t('My Button'),
    '#submit' => array('the_submit_func_here'),
  );

dpm($f);
}
</code>
Notice it's not a button type but is of type "submit". I have no idea how Form API handles submits, I thought I was having issues because of FORM_ID_submit but now I have no idea what is happening?
Comment: Remember: $form['#usbmit'] is only executed when default #submit button is pressed; if another button is pressed and have its own #submit the main form #submit function will not be fired, except when de button #submit fucntin call it (I think node submit form buttons do it, calling the main submit function from the button submit function). This may be related to your problem.
Comment: @tunic The problem is always default ['#submit'] is called, and by default I mean what node module put there, doesn't matter if I change it later. But thanks for the tip it's good to know


How to get the last work day in SQL Server date dimension?

Question: We are using a dimension table for dates based on this blog post.
There is a view which gives for each date if it is a week day/ weekend or if that date is a holiday.

TheDate
IsWeekend
IsHoliday

2022-04-13
0
0

2022-04-14
0
0

2022-04-15
0
1

2022-04-16
1
0

2022-04-17
1
1

2022-04-18
0
1

2022-04-19
0
0

2022-04-20
0
0

We are using a window function with with LAG() to get the last workday on weekends:
SELECT [TheDate]
    ,[TheDayName]
    ,CASE
        WHEN [TheDayOfWeek] = 1
            THEN LAG([TheDate], 2) OVER (
                    ORDER BY [TheDate]
                    )
        WHEN [TheDayOfWeek] = 2
            THEN LAG([TheDate], 3) OVER (
                    ORDER BY [TheDate]
                    )
        ELSE LAG([TheDate], 1) OVER (
                ORDER BY [TheDate]
                )
        END AS LastWorkDay
FROM [dbo].[TheCalendar]

The result is as expected:

TheDate
TheDayName
LastWorkDay

2022-04-13
Wednesday
2022-04-12

2022-04-14
Thursday
2022-04-13

2022-04-15
Friday
2022-04-14

2022-04-16
Saturday
2022-04-15

2022-04-17
Sunday
2022-04-15

2022-04-18
Monday
2022-04-15

2022-04-19
Tuesday
2022-04-18

I am looking now how the window function can include holidays, so the Workday before Tuesday, April 19 is actually Thursday, April 15 because Monday (4/16) and Friday (4/15) are holidays and Sunday (4/17) and Saturday (4/16) are Weekend (Well Sunday in fact is both).
I tried to use a cursor to iterate dates down to the next work day but it is everything than performant. I am thinking now to materialize the last workday for weekends and then again doing the same exercise for holidays.
What could be a more intelligent approach?
Answer: As @lptr commented, you can use max...over query to acheive the requirement. Made few changes in that query to work for all use cases. Below is the query.
Query:
select *, case when IsWeekend=0 and IsHoliday=0 then lag(TheDate,1) over (order by TheDate) else
  max(case when IsWeekend=0 and IsHoliday=0 then theDate end)
  over(order by TheDate rows between 10 preceding and 1 preceding) end
  from [dbo].[TheCalendar]

This query selects all columns from the table TheCalendar and uses a CASE statement to check if the current date is a weekend or holiday. If it is not, then it uses the LAG function to get the previous non-holiday and non-weekend date. If it is a weekend or holiday, then it uses a window function to get the maximum date for the previous 10 non-holiday and non-weekend days. The query you provided is correct.
Input:

TheDate
IsWeekend
IsHoliday

2022-04-13
False
False

2022-04-14
False
False

2022-04-15
False
True

2022-04-16
True
False

2022-04-17
True
True

2022-04-18
False
True

2022-04-19
False
False

2022-04-20
False
False

Output:

TheDate
IsWeekend
IsHoliday
PrevDay

2022-04-13
False
False
null

2022-04-14
False
False
2022-04-13

2022-04-15
False
True
2022-04-14

2022-04-16
True
False
2022-04-14

2022-04-17
True
True
2022-04-14

2022-04-18
False
True
2022-04-14

2022-04-19
False
False
2022-04-18

2022-04-20
False
False
2022-04-19

db<>fiddle
Comment: Lag is not required at all.
Comment: The right hint came from @lptr, but since this was a comment and you build it into your answer, I check this as the right answer. Thanks all


I am trying to make an aside menu with

Question: I am making a little page as a project for school (don't mind content, it's in Polish). I have tried deleting CSS and it worked, but the look of it was just awful.

body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
}

header {
  background-color: #333;
  color: #fff;
  padding: 20px;
  text-align: center;
}

header img {
  width: 350px;
  /* Zmienić odpowiednio */
  height: auto;
}

content {
  margin-left: 500px;
  position: relative;
  height: 100%;
  font-family: Arial, Helvetica, sans-serif;
}

aside {
  min-height: 110vh;
  background-color: #666;
  color: #fff;
  width: 2;
  float: left;
  padding: 30px;
}

aside ul {
  list-style-type: none;
  padding: 0;
}

aside ul li {
  text-align: center;
  margin-bottom: 30px;
}

content {
  flex-grow: 1;
  padding: 20px;
  margin-left: 230px;
  flex-direction: column;
}

footer {
  background-color: #333;
  color: #fff;
  padding: 10px;
  text-align: center;
  clear: both;
}

a {
  text-decoration: none;
  color: white;
}

p {
  text-align: justify;
}

h3 {
  font-size: x-large;
}

Pow

Powrót do strony głównej

Powrótony głównej

I tried making  as a button but still nothing. I just want to open second page linked to a specific . The link to the page is valid; it worked without CSS.
Comment: Can you please edit your question to explain the problem more clearly. Is the problem that your links don't **look** as you want them to, or that they don't **work** as you want them to?
Answer: My initial assumption is the reason you're having issues with your links is due to an invalid URI path. If you double check that the page you're trying to go to is being linked to properly since the CSS you have here shouldn't interfere with the link.
As an example, I've recreated your code and added completely different links to illustrate my point.

body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
}

header {
  background-color: #333;
  color: #fff;
  padding: 20px;
  text-align: center;
}

header img {
  width: 350px; /* Zmienić odpowiednio */
  height: auto;
}

content {
  margin-left: 500px;
  position: relative;
  height: 100%;
  font-family: Arial, Helvetica, sans-serif;
}

aside {
  min-height: 110vh;
  background-color: #666;
  color: #fff;
  width: 2;
  float: left;
  padding: 30px;
}

aside ul {
  list-style-type: none;
  padding: 0;
}

aside ul li {
  text-align: center;
  margin-bottom: 30px;
}

content {
  flex-grow: 1;
  padding: 20px;
  margin-left: 230px;
  flex-direction: column;
}

footer {
  background-color: #333;
  color: #fff;
  padding: 10px;
  text-align: center;
  clear: both;
}

a {
  text-decoration: none;
  color: white;
}

p {
  text-align: justify;
}

h3 {
  font-size: x-large;
}

Pow

Powrót do strony głównej

Powrótony głównej

Answer: you can use bootstrap for this type of nav.
between html head tags

<link href="https://firstname.lastname@example.com/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">

    enter code here
body

  <button type="button" class="btn btn-secondary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
    Right-aligned menu example
  </button>

<button class="dropdown-item" type="button">Action</button>

<button class="dropdown-item" type="button">Another action</button>

<button class="dropdown-item" type="button">Something else here</button>

   body

For more options check out https://getbootstrap.com/

I am trying to make an aside menu with


Find all right-angled triangles whose hypotenuse is $2^{2015.5}$

Question: Find all right-angled triangles whose hypotenuse has length $2^{2015.5}$ and whose other two sides have integral lengths.

My attempt:
  As $2^{2015.5}=2^{2015} \sqrt2$, the other lengths of the triangle can be $(2^{2015},2^{2015})$. Are there any other possible cases?
Comment: *Hint:* You want to solve $x^2+y^2=2^{4031}$ for $x,y \in \mathbb N$. Look at the Gaussian integers.
Comment: Please tell me how to solve that equation sir because I don't know how to solve it
Answer: A natural attempt is to work in the ring $ \mathbf Z[i] $ in order to exploit its factoriality. $ 2 $ factors as $ (1+i)(1-i) $ in this ring, and our equality becomes
$$ (x + yi)(x - yi) = (1 + i)^n (1 - i)^n = i^n (1 - i)^{2n}$$
where $ n = 4031 $. The right hand side is a prime factorization in the factorial ring $ \mathbf Z[i] $, and the quantities on the left hand side are conjugates. This tells us that the solutions are of the form
$$ x + yi = \varepsilon (1 - i)^{n} $$
where $ \varepsilon = \pm 1, \pm i $. Accounting for the signs, there is only one solution such that both $ x $ and $ y $ are positive. Since $ x = y = 2^{2015} $ is clearly a solution, we are done.

An alternative approach: We proceed by induction.
Claim: Let $ n = 2k + 1 $ be odd. Then, the equation $ x^2 + y^2 = 2^n $ has a unique solution in the positive integers, given by $ x = y = 2^k $.
Proof. The claim is certainly true for $ k = 0 $. Assume that it is true for $ k $, and let $ m = k+1 $. We want to show that the equation $ x^2 + y^2 = 2^{2m+1} $ has a unique solution in the positive integers. Since $ m > 0 $, the right hand side is divisible by $ 4 $, therefore so is the left hand side. Looking at the congruence $ x^2 + y^2 \equiv 0 \pmod{4} $, we deduce that both $ x $ and $ y $ must be even. But then,
$$ \left(\frac{x}{2}\right)^2 + \left(\frac{y}{2}\right)^2 = 2^{2k+1} $$
and by the inductive hypothesis we know that the positive integer solutions to this equation are unique, given by $ x/2 = y/2 = 2^k $. Multiplying through by $ 2 $ then gives the desired result.
Now, apply this claim to your specific problem, with $ k = 2015 $.
Comment: That second method is very good!  " x^2+y^2≡0(mod4), we deduce that both x and y must be even" This might not be universally known $(2k)^2 \equiv 0 \mod 4$ and $(2k + 1)^2 \equiv 1 \mod 4$.  $x^2 \not \equiv 3 \mod 4$ so $x^2 + y^2 = 0,1,2 \mod 4$ if i)both are even ii) one odd and one even iii) both odd respectively.
Comment: I don't know that concept so please tell me in an alternate method.
Comment: I added another approach.
Comment: There might not be a better method.  However maybe we can work this into a more introductory approach.  I'll try and see what I can do.
Comment: In the final step of the second method, you multiply through by $2$. This clearly gives a solution, but how does it prove uniqueness?
Comment: $ (x/2, y/2) $ is unique, so $ (x, y) $ must also be unique.


ToListAsync() - SqlNullValueException: Data is Null. This method or property cannot be called on Null values

Question: Estou recebendo o seguinte erro ao tentar listar todos os registros de um modelo:

SqlNullValueException: Data is Null. This method or property cannot be
  called on Null values.
  System.Data.SqlClient.SqlBuffer.get_Int32()

Meu método:
//GET: api/empresa
[HttpGet]
public async Task<ActionResult<IEnumerable<Empresa>>> getEmpresas()
{
    return await _context.Empresas.ToListAsync();
}

Meu modelo:
public class Empresa
{
    public int Id { get; set; }
    public string Nome { get; set; }
    public string Cep { get; set; }
    public string Logradouro { get; set; }
    public string Complemento { get; set; }
    public int Numero { get; set; }
    public string Bairro { get; set; }
    public string Localidade { get; set; }
    public string UF { get; set; }
    public int Unidade { get; set; }
    public int IBGE { get; set; }
    public int GIA { get; set; }
    public string Telefone{get;set;}
}

No meu bd esta são as colunas e o resultado da seleção de todos os registros:
Pelo que pesquisei esse erro acontece quando tem uma coluna não nulo no bd, porém nesse caso apenas o Id (chave primária) é não-nulo, porém ela já é auto-incrementada.
Answer: O erro que está ocorrendo de get_Int32 deve ser por que um campo int na tabela Empresa é null e na classe Empresa nenhuma propriedade int está como null.
Tente colocar int? Numero, int? Unidade e assim por diante.
Comment: o miserável é um gênio


Selecting a Tab activity two ways

Question: My app has three tabs, A, B, C that have three distinct activities.
Tab A includes a list view. User can either select Tab B or scroll the list view in A, selecting a row will take him to Tab B with the position of the selected row.
How can I detect in Tab B that the user has selected a row or clicked on Tab B. Clicking on Tab B selects a default,
whereas selecting a row in A makes B do something special with the data. I could create a separate activity that is launched when a row is selected, but that is code duplication and I prefer trying to find out if B can detect how it was launched.
Answer: Use the Extras attribute of the Intent you use to launch tab B's Activity.
eg.
When you launch Tab B from a list click:
Intent tabBIntent = new Intent(this, TabB.class);
tabBIntent.putExtra("fromList", true);
startActivity(tabBIntent);

in TabB's onCreate (or somewhere similar):
if (getIntent().getBooleanExtra("fromList", false))
    ....

Selecting a Tab activity two ways


Properly Defining DAG Schedule Interval

Question: Problem: We're having difficulties having a DAG fire off given a defined interval. It's also preventing manual DAG executions as well. We've added catchup=False as well to the DAG definition.
Context: We're planning to have a DAG execute on a 4HR interval from M-F. We've defined this behavior using the following CRON expression:
0 0 0/4 ? * MON,TUE,WED,THU,FRI *

We're unsure at this time whether the interval has been defined properly or if there are extra parameters we're ignoring.
Any help would be appreciated.
Answer: I think you are looking for is 0 0/4 * * 1-5 which will run on 4th hour from 0 through 23 on every day-of-week from Monday through Friday.
Your DAG object can be:
from airflow import DAG

with DAG(
    dag_id="my_dag",
    start_date=datetime(2022, 2, 22),
    catchup=False,
    schedule_interval="0 0/4 * * 1-5",
) as dag:
    # add your operators here

Comment: Yep, that did the trick. Thank you!

Properly Defining DAG Schedule Interval


NSUserDefault and Switches

Question: I use NSUserDefaults to save a switch on/off and so far it is good. It remembers the switch position in next session.
Now to the thing which I do not understand.
I use the same switch (with the same name)in another view, let´s say a flip view which is pushed in from the first view. If I change the switch in the first view it is automatically changed in the flip view.
But the other way round, if I change it in the flip view it is not changed in the first view when I go back. Only if I restart the application the first view is also changed.
How can I solve this to be changed at the same time? Or kind of refresh the first view without need to restart.
Answer: Your first view is not refreshed, as it is not initialized again. If you using ViewControllers you could update your switch in viewWillAppear (if isViewLoaded).
Comment: I used a UIBarButtonItem and @selector(refresh) and then              - (void)refresh and put inside the BOOL savedState for the switches involved. So pushing the button it runs thru the savedStates again and they are updated. It works.
Answer: You should observe NSUserDefaults changes in views that are interested in the changes.
You can use the following code to observe the changes:
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self
           selector:@selector(defaultsChanged:)
               name:NSUserDefaultsDidChangeNotification
             object:nil];

And implement the defaultsChanged method:
- (void)defaultsChanged:(NSNotification *)notification
{
    NSUserDefaults *defaults = (NSUserDefaults *)[notification object];
    id value = [defaults objectForKey:@"keyOfDefaultThatChanged"];
    self.something = [(NSNumber *)value intValue];    // For example.
}

Don't forget the remove the observer when your view closes (perhaps in dealloc):
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center removeObserver:self];

Comment: Thanks, it works to check. I have many views which are interested in the change.

NSUserDefault and Switches


How to fix progress resetting when i switch my tabs

Question: Im making a game with tabs and as it stands progress between tabs resets when I change tabs  http://prntscr.com/ns2jvg http://prntscr.com/ns2k31 http://prntscr.com/ns2k74     I know eventually i'll make a last tab called options that you can use to reset. but i would like for development to be able to debug and be able to switch tabs with no reset
Im not sure how this is done im new to html
This is my Home Tab in html:

    <title> Basic Clicker</title>
    <link rel="stylesheet" href="css/style.css" />

Home

SkillTree

Equipment

Pets

Skills

Quests

                <link rel="stylesheet" type="text/css"
href="interface.css" />

            <title> Basic Clicker</title>

This is the next tab in html:

        <title> Basic Clicker</title>
    <link rel="stylesheet" href="css/style.css" />

Home

SkillTree

Equipment

Pets

Skills

Quests

                <link rel="stylesheet" type="text/css"
href="interface.css" />

            <title> Basic Clicker</title>

I expect the tabs to switch and for the player to not lose any data/ it not to reset. right now things reset when you click a different tab.
Answer: You can make use of localStorage.
On page one you can add an item into localStorage with:
localStorage.setItem('pet', 'Cat'); // name, value

And on page two you can retrieve the value with:
var pet = localStorage.getItem('pet');

You can also overwrite the value later on, or remove it with:
localStorage.removeItem('pet'); // remove an individual item
localStorage.clear(); // remove all items

Note that localStorage persists across browser sessions. If you want to restrict the storage to an individual session, you should instead make use of sessionStorage.
Comment: thanks ive never used this before can u give me a example on where to put that in my code to make it functioning? for example my skill points carrying over to the skill tree tab ( it adds one to a counter when u rebirth) or the other way around hp up going to home tab


STL map to find the first non repeatable character

Question: I have written a small C++ program to keep a count of the alphabets.
I am using stl map for the same,
Interestingly, i am not getting the list as it appeared in the input.
For example for the word TESTER, my program should give
T  2
E  2
S  1
R  1

But its giving,
E       2
R       1
S       1
T       2

change in the position of the alphabets,
I want the o/p of the alphabets as it appeared in the input. Please help me if i am missing anything.Here is my code
#include<iostream>
#include<map>

using namespace std;

int main()
{
    char *str = "TESTER";
    map<char,int> checkmap;
    map<char,int>::iterator p;
    int i;
    while( *str != '\0' )
    {
        p = checkmap.find(*str);
        i = p->second;
        if(p == checkmap.end())
        {
            checkmap.insert(std::make_pair(*str,++i));
        }
        else
        {
            p->second = ++(p->second);
        }
    str++;
    }
    for(p=checkmap.begin(); p!=checkmap.end(); p++)
    {
        /*if(p->second == 1)
        {
            cout<<(*p).first<<endl;
        }*/
        cout<
first<<"\t"<
second<<endl;
    }

    return 0;
}

Comment: possible duplicate of [A std::map that keep track of the order of insertion?](http://stackoverflow.com/questions/1098175/a-stdmap-that-keep-track-of-the-order-of-insertion)
Comment: You can use an array instead of a map since characters are considered as integers.
Answer: Here is shown an approach how it can be done
#include <iostream>
#include <map>
#include <cstring>

int main()
{
    const char *str = "TESTER";

    auto order = [&]( char c1, char c2 )
    {
        return ( std::strchr( str, c1 ) < std::strchr( str, c2 ) );
    };

    std::map<char, int, decltype( order )> m( order );

    for ( const char *p = str; *p; ++p ) ++m[*p];

    for ( const auto &p : m ) std::cout << p.first << ' ' << p.second << std::endl;
    std::cout << std::endl;

    return 0;
}

The program output is
T 2
E 2
S 1
R 1

Comment: @juanchopanza  I simply repeated my old answer to some other similar question. The only difference is that there was used an std:;string object instead of the string literal. So instead of standard function strchr I used member function find.:)
Comment: It's somewhat of a pity that the `order` lambda is so expensive (O(N) per invocation).
Comment: @MSalters  What can you suggest?
Comment: `std::strchr(str,c)` can be memoized. If I would have had a simple suggestion how to do that, I'd offer it. But I'm afraid you're going to need a `size_t[UCHAR_MAX]` and that in turn means your lambda has to become a stateful functor.
Answer: You're missing that std::map has its own internal ordering, which is completely independent of the order in which elements are added. As you can see from your example, it is ordered alphabetically. This is in increasing order of the value of the char key.
Also note that your map manipulations are overly complex. All you need to do is
char *str = "TESTER";
map<char,int> checkmap;

while( *str != '\0' )
{
    checkmap[*str]++;
    ++str;
}

The while can be collapsed further if you're into that kind of thing:
while( *str != '\0' ) checkmap[*str++]++;

For the general problem of mapping values while maintaining insertion order, see A std::map that keep track of the order of insertion?
Comment: @Rndp13 Not trivially. You could push elements into a vector of `pair`, and only push new elements if the pair's first element does not already exist.
Comment: Thanks @juanchopanza                                                                               Is there any way i can get the alphabets as it appeared in the input?
Answer: There is no way to keep track of the order in which elements are added to map. To get the same order it would be advisable to use std::vector<std::char, int> and then update the same.


How do I find which file contains a function?

Question: How do I find where a Drupal function is defined? For example, in which Drupal file is db_query() defined?
Answer: You can find it at includes/database/database.inc, line 2342.
Your editor may be providing a similar feature like the one implemented in Zend studio: When you press control while you click on the function name, it will take you to the file containing the implementation of that function.
Comment: no, cause im using notepadd++. :D
Comment: You can try eclipse also..It also provide the same features..
Comment: @Belmark If you continue to use NPP, you can also search for function definition in drupal root folders. But as suggested by mohit, it s good to use an IDE, saves you time.
Answer: Drupal.org API shows which file contains a Drupal function, class, or method for which you are looking the documentation. In the case of db_query(), this is what the site shows.

That is also a link that takes you to a page showing the content of that file.
Notice that the documentation for Drupal 8 is not actually complete. For some reason, Drupal 8 files are not completely parsed, and it can happen you don't find on Drupal.org API a class or method Drupal 8 defines.
Answer: For anyone reasonably comfortable with a CLI.
Find function:
grep -rn "on db_query" *
Find class:
grep -rn "ss Node" *


Desejo fazer uma função se(if) junto de uma função muliplicação

Question: Desejo fazer uma função se(if) junto de uma função multiplicação, de modo que, se for escolhido a "modeloescolha" 2(Para noooossa alegria), e a quantidade que a cliente desejar for apenas 1, então na caixa "Preço Total" terá o valor desta compra. O valor de apenas uma roupa desta(Para noooossa alegria) será R$ 15,00.
Seguem abaixo o que eu já fiz:

 <fieldset id="pedido"><legend>Quero uma Camiseta Feminina</legend>

Modelo:
<select name="modeloescolha">
    <option value="1">
    <option value="2">Para noooossa alegria
    <option value="3">Caveira de óculos pink
    <option value="4">Não toque no meu cabelo
 <option value="5">Bacon estilo de vida
 <option value="6">Hakuna Matata do Timão e Pumba
 <option value="7">Princesa Peach
</select>

Cor:
<select name="utilização">
    <option value="1">
    <option value="2">Azul
    <option value="3">Vermelho
    <option value="4">Branco
</select>

Quantidade:
  <input type="number" name="tNum" id="cNum" min="1" max="99999"

Preço Total: R$

 </fieldset>
Comment: E o código de javascript? Ficou perdido pelo TPC? =P
Answer: você pode usar o evento "input" nos inputs e/ou o "change" nos selects para monitorar qual quer mudança de valor nos mesmos, então você pode calcular o valor do item.

/* definindo a "classe" Produto */
var Produto = function (elem) {
  var self = this;
  this.inputs = {};

  /* buscando os objetos DOM na linha atual */
  this.inputs.modeloescolha = elem.querySelector("[name='modeloescolha']");
  this.inputs.cores = elem.querySelector("[name='cores']");;
  this.inputs.quantidade = elem.querySelector("[name='quantidade']");;
  this.inputs.valor = elem.querySelector("[name='valor']");;

  /* definindo os valores iniciais */
  this.modeloescolha = 0;
  this.cores = 0;
  this.quantidade = 0;

  this.ModeloId = 0;
  this.CorId = 0;

  var onInput = function (event) {
    self.onInput(event);
  }

  this.inputs.modeloescolha.addEventListener("input", onInput);
  this.inputs.cores.addEventListener("input", onInput);
  this.inputs.quantidade.addEventListener("input", onInput);

  /* atualizando spans com valores */
  this.atualizarValor();
}

/* criando uma propriedade calculada para a "classe" Produto. */
Object.defineProperty(Produto.prototype, "total", {
  get: function () {
    return (this.modeloescolha + this.cores) * this.quantidade;
  }
});

/* atualizando valores ao modificar o campo value de um input */
Produto.prototype.onInput = function (event) {
  var modeloescolha = Produto.modeloescolha.querySelector("option[value='" + this.inputs.modeloescolha.value + "']");
  var cores = Produto.cores.querySelector("option[value='" + this.inputs.cores.value + "']");

  this.modeloescolha = modeloescolha ? parseFloat(modeloescolha.dataset.value) : 0;
  this.cores = cores ? parseFloat(cores.dataset.value) : 0;
  this.quantidade = this.inputs.quantidade.value ? parseFloat(this.inputs.quantidade.value) : 0;

  this.ModeloId = modeloescolha ? parseInt(modeloescolha.dataset.id) : 0;
  this.CorId = cores ? parseInt(cores.dataset.id) : 0;

  this.atualizarValor();
}

/* consultandos os objetos DOM iniciais/compatilhados. */
Produto.template = document.getElementById("tmplLinha").content;
Produto.modeloescolha = document.getElementById("modeloescolha");
Produto.cores = document.getElementById("cores");
Produto.addItem = document.getElementById("addItem");
Produto.total = document.getElementById("total");
Produto.tabela = document.querySelector("#produtos tbody");
Produto.lista = [];

/* definindo o "método" atualizarValor para a "classe" Produto */
Produto.prototype.atualizarValor = function () {
  var total = 0
  Produto.lista.forEach(function (produto, indice) {
    total += produto.total;
  });

  this.inputs.valor.textContent = this.total.toLocaleString("pt-BR", {
    style: "currency",
    currency: "BRL"
  });

  Produto.total.textContent = total.toLocaleString("pt-BR", {
    style: "currency",
    currency: "BRL"
  });
}

Produto.addItem.addEventListener("click", function () {
  var item = document.importNode(Produto.template, true);
  var produto = new Produto(item);
  Produto.lista.push(produto);
  Produto.tabela.appendChild(item);
});

      Modelo
      Cor
      Quantidade
      Valor

      <button id="addItem">Adicionar Item</button>
      Total:

<template id="tmplLinha">

    <input type="text" name="modeloescolha" list="modeloescolha" />
    <input type="text" name="cores" list="cores" />
    <input type="number" name="quantidade" min="1" max="99999" />

</template>

<datalist id="modeloescolha">
  <option data-id="2" data-value="15.00" value="Para noooossa alegria"></option>
  <option data-id="3" data-value="1.00" value="Caveira de óculos pink"></option>
  <option data-id="4" data-value="2.00" value="Não toque no meu cabelo"></option>
  <option data-id="5" data-value="3.00" value="Bacon estilo de vida"></option>
  <option data-id="6" data-value="4.00" value="Hakuna Matata do Timão e Pumba"></option>
  <option data-id="7" data-value="5.00" value="Princesa Peach"></option>
</datalist>

<datalist id="cores">
  <option data-id="2" data-value="1.00" value="Azul"></option>
  <option data-id="3" data-value="1.00" value="Vermelho"></option>
  <option data-id="4" data-value="0.00" value="Branco"></option>
</datalist>

utilizei o datalist no lugar no select, para não tornar o markup do HTMl muito extenso, isto pode lhe ajudar caso queira inspecionar os elementos da pagina.
caso prefira usar um select no lugar, você pode faze-lo sem nenhum problema.
Comment: Eu usei este código mas ele não pegou, se puder me ajudar eu agradeço, sou novato nisso, tenho que fazer um site para o meu trabalho do curso mas não estou conseguindo fazer isso... Obrigado desde já pela ajuda.


iterate through a list and get user response to each item using tkinter GUI

Question: I am being particularly obtuse. I am iterating through a list of technical italian words and wanting to insert a translation using a tkinter interface. There is no problem doing this without the GUI: My problem is that I cannot figure out how to do an iteration, load a word into a ttk.Label and wait for a user entry in a ttk.Entry field. I have searched and found explanations, but I am at a loss how to apply the suggestions. This is my code using a trivial list of words:
from tkinter import ttk
import tkinter as tk

def formd():

    list_of_terms = ['aardvark', 'ant','zombie', 'cat', 'dog', 'buffalo','eagle', 'owl','caterpiller', 'zebra',  'orchid','arum lily' ]
    discard_list = []
    temp_dict={}
    list_of_terms.sort()

    for item in list_of_terms:
        listKey.set(item)

    # need to wait and get user input
        translation =dictValue.get()
        temp_dict[item]=translation
        discard_list.append(item)
    # check if it has worked
    for key, value in temp_dict.items():
        print(key, value)
# GUI for dict from list
LARGE_FONT= ("Comic sans MS", 12)

root = tk.Tk()
root.title('Nautical Term Bilingual Dictionary')
ttk.Style().configure("mybtn.TButton", font = ('Comic sans MS','12'), padding = 1,  foreground = 'DodgerBlue4')
ttk.Style().configure('red.TButton', foreground='red', padding=6, font=('Comic sans MS',' 10'))
ttk.Style().configure('action.TLabelframe', foreground = 'dodger blue3')
#.......contents frames.....................
nb = ttk.Notebook(root)
page5 = ttk.Frame(nb)
# declare variables
listKey= tk.StringVar()
dictValue = tk.StringVar()
# widgets
keyLabel =ttk.Label( page5, text = "key from list", font=LARGE_FONT).grid(row=3, column = 0)
Keyfromlist =ttk.Label(page5, width = 10, textvariable = listKey).grid(row = 3, column = 1)

valueLabel =ttk.Label( page5, text = "enter translation", font=LARGE_FONT).grid(row=3, column = 2)
listValue =ttk.Entry(page5, textvariable =dictValue, width = 15).grid(row = 3, column = 3)
#listValue.delete(0,'end')
#listValue.focus_set()

# add buttons
b1 = ttk.Button(page5, text="add to dictionary",style = "mybtn.TButton", command = formd)
b1.grid(row = 5, column = 0)
b5 = ttk.Button(page5, text="clear entry", style ="mybtn.TButton")
b5.grid(row = 5, column = 2)
nb.add(page5, text='From List')

nb.pack(expand=1, fill="both")

for child in root.winfo_children():
    child.grid_configure(padx =5, pady=5)

if __name__ == "__main__":
    root.mainloop()

I wonder whether someone could take the time to suggest a solution, please. How to stop a while loop to get input from user using Tkinter? was the one suggestion that I cannot figure how to use in my example
Answer: tkinter doesn't "play nice" with while loops.
Fortunately for you, you don't need to use one.
You can do something like the below:
from tkinter import *

class App:
    def __init__(self, root):
        self.root = root
        self.list = ['aardvark', 'ant','zombie', 'cat', 'dog', 'buffalo','eagle', 'owl','caterpiller', 'zebra',  'orchid','arum lily' ]
        self.text = Label(self.root, text="aardvark")
        self.entry = Entry(self.root)
        self.button = Button(self.root, text="Ok", command=self.command)
        self.text.pack()
        self.entry.pack()
        self.button.pack()
    def command(self):
        print(self.text.cget("text")+" - "+self.entry.get())
        try:
            self.text.configure(text = self.list[self.list.index(self.text.cget("text"))+1])
        except IndexError:
            self.entry.destroy()
            self.button.destroy()
            self.text.configure(text = "You have completed the test")

root = Tk()
App(root)
root.mainloop()

This essentially uses the Button widget to iterate to the next text and get the next input.


SELinux blocks tomcat web application to load Java native library (JNI) - how to configure SELinux on Centos 7?

Question: I have a Centos 7 with Tomcat installed and tomcat user
ls -l /var/lib/tomcat
total 0
drwxrwxrwx. 5 root tomcat 84 Jul  3 13:18 webapps

SELinux is enforcing and a Java web application which tries to load Java native library (JNI) from shared object files .so in /tmp/ folder cannot work.
 java.lang.UnsatisfiedLinkError: /tmp/app/gdal_java/2018.07.03.14.52.59/libosrjni.so:
/tmp/app/gdal_java/2018.07.03.14.52.59/libosrjni.so: failed to map segment from shared object: Permission denied

If I disable SELinux, there is no problem to load these files in the Java web application. The permission of this file is:
ls -lZ /tmp/app/gdal_java/2018.07.03.14.52.59/libosrjni.so
-rwxrwxrwx. tomcat tomcat system_u:object_r:tomcat_tmp_t:s0 /tmp/app/gdal_java/2018.07.03.14.52.59/libosrjni.so

How can I configure SELinux to allow tomcat user to load these files from /tmp/app/ folder?
I have tried with this command and restart tomcat but it still has same error
sudo semanage fcontext -a -t tomcat_tmp_t '/tmp/app_*/(.*)?'

Comment: Look in `/var/log/audit.log` for the deny message and use `audit2allow` to generate an updated policy.
Answer: I use audit2allow tool from @jordanm's comment  to allow tomcat can have multiple permission (read, execute) on this /tmp/app folder.
https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/6/html/security-enhanced_linux/sect-security-enhanced_linux-fixing_problems-allowing_access_audit2allow
cat /var/log/audit/audit.log  | audit2allow -a


Remove Linked Master Account Of Mailbox Exchange 2013

Question: I am trying to remove a linked master account of a mailbox user in Exchange 2013 and having trouble doing so. Does anyone know the command in power shell to make this happen?
Thank you,
Comment: Which error & which problems? What did you see in the eventlog? We are missing a lot of details here to help you.
Comment: So I went to associate a user with a different users linked account and got the below message saying it could not due to it already having a linked master account.
Answer: For the below, "firstname.lastname@example.com" should be the mail address on the mailbox you're trying to remove the master from. If this is the command that isn't working for you, you will need to provide error information.
<code>Set-User -identity "firstname.lastname@example.com" -linkedmasteraccount $null
</code>


Adicionando tag na foto

Question: Estou tentando adicionar tags numa foto (como o sistema de identificação do facebook), o erro que estou a ter é o seguinte:
Quando clico numa imagem para colocar as tags o formulário primeiro surge no canto do meu computador, não nas coordenadas da imagem. já trabalhei com estas funções e mesmo assim não funciona
  $('body .jcontent').on('click', '.imgpost', function(e){
       var imgvalue = $(this).parent();
       valueX = e.pageX //- $(imgvalue).offset().left;
       valueY = e.pageY //- $(imgvalue).offset().top;
       var idimg = this.id;
       $('#tagit').css({top:valueY,left:valueX})
       $(imgvalue).append('

<input type="text" name="txtname" class="w3-input" id="tagname" placeholder="Comente..." /><input type="button" name="w3-btn" value="Save" id="btnsave" /><input type="button" name="btncancel" value="Cancel" id="btncancel" />

');
       $('#tagname').focus(); //puts the cursor inside text-field

})

Comment: tenta fazer o teu DIV em que a imagem está inserida como position relative, se isso não funcionar seria bom ter o teu código no Plunker pra podermos ajudar a solucionar
Comment: Você já atribuiu `$(this).parent()` à variável, então ao invés de `$(imgvalue).append('...');` veja se `imgvalue.append('...');` pode resolver o problema.
Answer: Você pode fazer com uma div relative e a da tag fica absolute, assim ela pode ser flutuante dentro da div relative, que no caso seria a imagem.
No seu código está informando o top e o left antes do elemento existir, você tem que adicionar o elemento html primeiro e depois informar qual é a posição.
Aqui com base no seu código:
https://jsfiddle.net/0888bdev/2/

Adicionando tag na foto


Way of writing this direct proof

Question: In Richard Hammack's Book of Proof, he writes:

For the text I highlighted, wouldn't it be more accurate to say:

Then $x=2a+1$ for all $a\in \mathbb{Z}$
Comment: imo, NO. Here, *some* implies that a is only one integer whereas *all* would imply that x is not a number but a set of numbers
Comment: No.  By definition: $x$ is odd $\iff \exists a\in\mathbb Z:x=2a+1$.
Answer: No, $x$ is a fixed odd integer, hence there is unique integer $a\in\mathbb{Z}$ such that: $x=2a+1$.
The claim "Then $x=2a+1$ for all $a\in \mathbb{Z}$" means that if you choose $a=5$ and $a=89$, then $x=11$ and $179$, those are odd numbers but then $x$ is not a fixed odd number.
The right way to say it is: $A:\{x\in \mathbb{Z}\mid \exists a\in\mathbb{Z}: x=2a+1\}$ is the set of odd numbers.
Answer: No. No number is equal to $2a+1$ for all $a\in\Bbb Z$. How could that be, since $2\times1+1\ne2\times2+1$?
Answer: No. To say that $x = 2a + 1$ for all $a \in \Bbb{Z}$ would be to say that $x = 2a + 1$ is simultaneously true for every possible integer you substitute into $a$. For example, it would be true that $x = 2(1) + 1$, and it would also be true that $x = 2(100) + 1$. But, together, this implies
$$201 = 2(100) + 1 = x = 2(1) + 1 = 3,$$
a blatant contradiction!
Answer: In the context of that highlighted sentence, we have been introduced to some fixed odd integer $x$. We do not know its value, but we know that it is odd, so we know that it has to be $2a+1$ for some integer $a$, i.e. we can find an integer $a$ such that $x = 2a+1$.
For example, if $x=3$, then $x = 2a+1$ for $a = 1$.

Way of writing this direct proof


Laplce transform solution to this system of Nonlinear ODEs

Question: I want to solve this system of advective-diffusive-reactive equations analytically:
$$\left(\alpha - k_0c_B\right)c_A+v\frac{dc_A}{dx}-D\frac{d^2c_A}{dx^2} = f_A $$
$$\left(\alpha - k_0c_A\right)c_B+v\frac{dc_B}{dx}-D\frac{d^2c_B}{dx^2} = f_B $$
$$k_0c_Ac_B+\alpha c_C+v\frac{dc_C}{dx}-D\frac{d^2c_C}{dx^2} = f_C $$
Where $\alpha$, $k_0$, $v$, $D$, and $f_{A/B/C}$ are nonzero constants. Here are the boundary conditions:
$$c_A(x=0)=0,\;c_A(x=1)=0$$
$$c_B(x=0)=1,\;c_B(x=1)=0$$
$$c_C(x=0)=0,\;c_C(x=1)=0$$
if $k_0$ were zero, this becomes a system of independent and linear ODEs which I could solve using for example the Laplace Transform. I heard that for nonlinear ODEs, one cannot necessarily use Laplace Transforms without some modification to the original system (like linearization).
If there is a better way to solve the above system, I would like to know how, thanks!
Comment: Is the third equation right, or did you mean to use $dc_C/dx$ and $d^2 c_C/dx^2$?
Comment: Ah yes you're right, my bad. Fixed
Answer: One thing you can try is expand each of $c_A$, $c_B$, $c_C$ in a series in powers of $k_0$.  The equations for each power of $k_0$ will be linear in the coefficients of that power in $c_A$, $c_B$, $c_C$ given the lower-order coefficients.
EDIT:  To reduce the number of subscripts, I'll write $k_0 = \epsilon$, $c_A = A$, $c_B = B$, $c_C = C$.
Thus  $$\eqalign{A &= A_0 + A_1 \epsilon + A_2 \epsilon^2 + \ldots\cr
B &= B_0 + B_1 \epsilon + B_2 \epsilon^2 + \ldots\cr
C &= C_0 + C_1 \epsilon + C_2 \epsilon^2 + \ldots\cr
A_0(0) &= A_1(0) = A_2(0) = 0,\ A_0(1) = A_1(1) = A_2(1) = 0\cr
B_0(0) &=1, B_1(0) = B_2(0) = 0,\ B_0(1) = B_1(1) = B_2(1) = 0\cr
C_0(0) &= C_1(0) = C_2(0) = 0,\ C_0(1) = 1,\ C_1(1) = C_2(1) = 0\cr
}$$
and the differential equations become
$$ \eqalign{
\alpha\,A_{{0}} \left( x \right) &+v{\frac {\rm d}{{\rm d}x}}A_{{0}}
 \left( x \right) -  D  {\frac {{\rm d}^{2}}{{\rm d}{x}^{
2}}}A_{{0}} \left( x \right) -f_{{A}} = 0\cr
\alpha\,B_{{0}} \left( x \right) &+v{\frac {\rm d}{{\rm d}x}}B_{{0}}
 \left( x \right) -  D {\frac {{\rm d}^{2}}{{\rm d}{x}^{
2}}}B_{{0}} \left( x \right) -f_{{B}}=0\cr
v{\frac {\rm d}{{\rm d}x}}C_{{0}} \left( x \right) &-  D
{\frac {{\rm d}^{2}}{{\rm d}{x}^{2}}}C_{{0}} \left( x \right) -f_{{C}} = 0\cr
\alpha\,A_{{1}} \left( x \right) &-B_{{0}} \left( x \right) A_{{0}}
 \left( x \right) +v{\frac {\rm d}{{\rm d}x}}A_{{1}} \left( x \right)
-  D  {\frac {{\rm d}^{2}}{{\rm d}{x}^{2}}}A_{{1}}
 \left( x \right)=0\cr
\alpha\,B_{{1}} \left( x \right) &-B_{{0}} \left( x \right) A_{{0}}
 \left( x \right) +v{\frac {\rm d}{{\rm d}x}}B_{{1}} \left( x \right)
-  D  {\frac {{\rm d}^{2}}{{\rm d}{x}^{2}}}B_{{1}}
 \left( x \right)=0\cr
B_{{0}} \left( x \right) A_{{0}} \left( x \right) &+v{\frac {\rm d}{
{\rm d}x}}C_{{1}} \left( x \right) - D  {\frac {{\rm d}^
{2}}{{\rm d}{x}^{2}}}C_{{1}} \left( x \right) =0\cr
\alpha\,A_{{2}} \left( x \right) &-B_{{0}} \left( x \right) A_{{1}}
 \left( x \right) -B_{{1}} \left( x \right) A_{{0}} \left( x \right) +
v{\frac {\rm d}{{\rm d}x}}A_{{2}} \left( x \right) -  D
{\frac {{\rm d}^{2}}{{\rm d}{x}^{2}}}A_{{2}} \left( x \right)=0 \cr
\alpha\,B_{{2}} \left( x \right) &-B_{{1}} \left( x \right) A_{{0}}
 \left( x \right) -B_{{0}} \left( x \right) A_{{1}} \left( x \right) +
v{\frac {\rm d}{{\rm d}x}}B_{{2}} \left( x \right) -  D
{\frac {{\rm d}^{2}}{{\rm d}{x}^{2}}}B_{{2}} \left( x \right) =0\cr
B_{{1}} \left( x \right) A_{{0}} \left( x \right) &+B_{{0}} \left( x
 \right) A_{{1}} \left( x \right) +v{\frac {\rm d}{{\rm d}x}}C_{{2}}
 \left( x \right) -  D  {\frac {{\rm d}^{2}}{{\rm d}{x}^{
2}}}C_{{2}} \left( x \right)=0
\cr}$$
etc.  Each of these equations involves only one differentiated variable, occurring linearly and with constant coefficients, the other $A_i$, $B_i$ and $C_i$ occurring in the "inhomogeneous terms" being already known from the previous equations.  Thus they may be solved one by one.
Comment: What do you mean by this? Can you show me how this is done?
Answer: There are a few things to notice about your system:

By shifting $c_{A/B/C}$, i.e. introducing $\hat{c}_A = c_A + \delta_A$ and similarly for $c_{B,C}$, you can get rid of the constant source terms $f_{A/B/C}$.
The first two equations are decoupled from the third one, so you can first focus on solving $c_{A}$ and $c_B$, and use that as input in the third equation.
You can remove all the nonlinear terms by a change of variables. Consider $u = c_A - c_B$; when you substract the second model equation from the first, you see that the resulting equation for $c_A - c_B = u$ is linear. The same holds for $v = c_A + c_C$ and for $w = c_B + c_C$. Using these new variables, you will end up with three decoupled, linear equations for $u,v,w$. Moreover, the equations for $u,v,w$ are identical up to the source term $f$. Since there is a linear relation between $u,v,w$ (in this case, $u = v - w$), this procedure does not solve the system completely. However, it will get you started.


Sum of infinite cosine series

Question: I'm sure this has been asked before, but I'm not sure how to search for this.

Evaluate the sum $$\sum_{k=1}^{\infty} \frac{\cos(k)}{2^k}.$$

I thought about expanding $\cos(x)$ as a Taylor series, but that didn't go anywhere. Any hints?
Comment: Express $\cos(k)$ in terms of $e^{ik}$ and $e^{-ik}$. We get two geometric series.
Comment: You are welcome. One can also get it using trig identities, but it is messy, while the $\frac{e^{ik}+e^{-ik}}{2}$ way is structurally quite natural.
Comment: @AndréNicolas Even more efficient is to write $\cos (k)=\text{Re}(e^{ik})$
Answer: HINT:
$$\cos x =\text{Re}\left(e^{ix}\right)$$
Then, the series of interest is
$$\text{Re}\left(\sum_{k=1}^{\infty}\left(\frac{e^{i}}{2}\right)^k\right)$$
Answer: Amusement Time
Firstly I thought about a joke, namely: let's take the series, and white it like:
$$S = \frac{e^i}{2} + \frac{e^{2i}}{4} + \frac{e^{3i}}{8} + \frac{e^{4i}}{16} + \ldots $$
Now:
$$S = \frac{e^i}{2}\cdot\left[1 + \frac{e^i}{2} + \frac{e^{2i}}{4} + \frac{e^{3i}}{8} + \frac{e^{4i}}{16} + \ldots \right] = \frac{e^i}{2}\cdot (1 + S)$$
Then re-arranging the terms to get S:
$$S = \frac{e^i}{2-e^i}$$
Now we have to take the Real part:
$$\Re \frac{e^i}{2 - e^i} = \Re \frac{i\sin(1) + \cos(1)}{2 - i\sin(1) -\cos(1)} = \frac{\cos(1)}{2-\cos(1)} $$
Unfortunately this is not the sum of that series.
But I guess that a similar road shall be undertaken because the sum of that series is (thanks to Mathematica)
$$S = \frac{1 - 2\cos(1)}{4\cos(1) - 5}$$

Sum of infinite cosine series