Another domain is pointing to my server, and Google is indexing that one rather than mine

Question: So I own www.example.com.
I have an A record pointing to my IP, and also have a CNAME for www.
Clearly my IP is shared, because if I access it, I get taken to www.domain.com
Anyway, last week, I googled for www.example.com, and it's been indexed under www.domain.com which is pointing to my IP. I assume some type of nasty SEO scrapping site?
This led me to this post on the webmaster exchange, where I implemented the Perl script shown. Now, when I google my domain, the blackhat one still shows up, even though if you click on it, the page shows a 404 like this: 404.
This site has now been responding with a 404 when accessed, yet it's still indexed instead of my real website. How can I actually stop google from indexing this website, and I guess, further block it? My VHosts and .htaccess is pretty simple.
Comment: What happens if you visit domain.com rather than www.domain.com?  Does your site load? Where does domain.com point to? You cannot have a cname at the root level.
Answer: Create a virtualhost for your domain. Send all other traffic to another directory on your web server containing an index.html file.
Then, in that index.html, include a noindex meta tag in the page's HTML code. When Googlebot next crawls that page and see the tag or header, Googlebot will drop that page entirely from Google Search results, regardless of whether other sites link to it.
Then, use Google's URL Inspection Tool to reset the search results for both domains.
Answer: You need to ask Google to re-crawl your website. Sadly it can take up time.

Crawling can take anywhere from a few days to a few weeks. Be patient
  and monitor progress using either the Index Status report or the URL
  Inspection tool.

Please see that link for submission to a re-crawl; https://support.google.com/webmasters/answer/6065812?hl=en


Get the name of a running Java program from C# (like the process name for .NET apps)

Question: I need to get the name of the Java program thats being executed by Java, from a C# program. I have no access to the Java program (aka I'm not the one who wrote it, so I can't make it communicate with my C# program.) Is it possible to do this?
Answer: There is a command line tool that comes with the JDK called 'jps'. jps -v shows all the arguments you have passed to java.
You can call jps from c# and then read the output.
Hope this helps.
Answer: I don't know for sure, but I don't believe so and let me explain why:
on your root machine, if you use a process explorer you will just see the JVM (java virtual machine) and not what is happening inside it. the herarchy would actually be Root > Java VM > Java VM process.  hope that logic helps you find your solution if there is one.
Comment: the only way I think its possible is if you detect whenever a .jar is launched and then record it that way, but you still wont know which process is running which jar if there are more than 1 jars running..


Geode transaction to generate ID and insert object

Question: Let's say I have 3 PARTITIONED_REDUNDANT regions:

/Orders - keys are Longs (an ID allocated from /Sequences) and values are instances of Order
/OrderLineItems - keys are Longs (an ID allocated from /Sequences) and values are instances of OrderLineItem
/Sequences - keys are Strings (name of a sequence), values are Longs

The /Sequences region will have many entries, each of which is the ID sequence for some persistent type of that is stored in another region (e.g., /Orders, /OrderLineItems, /Products, etc.)
I want to run a Geode transaction that persists one Order and a collection of OrderLineItems together.
And, I want to allocate IDs for the Order and OrderLineItems from the entries in the /Sequences region whose keys are "Orders" and "OrderLineItems", respectively. This operates like an "auto increment" column would in a relational database - the ID is allocated/assigned at insertion time as part of the transaction.
The insertion of Orders and OrderLineItems and the allocation of IDs from the /Sequences region need to be transactionally consistent - they all succeed or fail together.
I understand that Geode requires data being operated on in transaction to be co-located if the region is partitioned.
The obvious thing is to co-locate OrderLineItems with the owning Order, which can be done with a PartitionResolver that returns the Order's ID as the routing object.
However, there's still the /Sequences region that is involved in the transaction, and I'm not clear on how to co-locate that data with the Order and OrderLineItems.
The "Orders" entry of the /Sequences reqion would need to be co-located with every Order for which an ID is generated...wouldn't it? Obviously that's not possible.
Or is there another / better way to do this (e.g., change region type for /Sequences)?
Thanks for any suggestions.
Answer: Depending on how much data is in your /Sequences region - you could make that region a replicated region. A replicated region is considered co-located with all other regions because it's available on all members.
https://geode.apache.org/docs/guide/15/developing/transactions/data_location_cache_transactions.html
This pattern is potentially expensive though if you are creating a lot of entries concurrently. Every create will go through these shared global sequences. You may end up with a lot of transaction conflicts, especially if you are getting the next sequence number by incrementing the last used sequence number.
As an alternative you might want to consider UUIDs as the keys for your Orders and OrderLineItems, etc. A UUID takes twice as much space as a long, but you can allocate a random UUID without needing any coordination between concurrent creates.
Comment: I switched the refid for the /Sequences region in my cache.xml from PARTITION_REDUNDANT to REPLICATE. After doing so, I am seeing the following error:

Exception in thread "main" org.apache.geode.cache.TransactionDataRebalancedException: Transactional data moved, due to rebalancing.

Do I retry the transaction in a loop? Or what is the way to handle this error?
Comment: There is a little bit of trickiness that you have to handle when mixing replicated and partitioned regions in a transaction. The first operation in the transaction needs to got to the partitioned region, to set the transaction host. I suspect maybe your first operation was to the replicated region, which is why you got that error. The link I put above mentions this, although I feel it's not particularly clear about that point.


Inequality based on triangle: $\frac{3}{2}\le\frac{a}{b+c}+\frac{b}{c+a}+\frac{c}{a+b}<2$

Question:
If $a,b,c$ are sides of a triangle, prove that ${3\over2 }\le {{a\over b+c}} + {{b\over c+a}}+{{c\over a+b}} \lt 2$ .
Comment: use the Ravi substitution
Comment: Have a look at [Nesbitt's inequality](https://en.wikipedia.org/wiki/Nesbitt%27s_inequality) and http://math.stackexchange.com/questions/54627/inequality-involving-sides-of-a-triangle
Answer: Variational Approach
Without loss of generality, assume that $a+b+c=1$. Then
$$
\frac{a}{1-a}+\frac{b}{1-b}+\frac{c}{1-c}\tag{1}
$$
has an interior extreme when
$$
\frac{\delta a}{(1-a)^2}+\frac{\delta b}{(1-b)^2}+\frac{\delta c}{(1-c)^2}=0\tag{2}
$$
for any variation so that
$$
\delta a +\delta b+\delta c=0\tag{3}
$$
Linearity says that we need $a=b=c=\frac13$, so that
$$
\bbox[5px,border:2px solid #C0A000]{\frac{a}{1-a}+\frac{b}{1-b}+\frac{c}{1-c}=\frac32}\tag{4}
$$

Due to symmetry and the triangle inequality, an edge extreme occurs only when $c=a+b=\frac12$ or when $c=0$, in which case $a+b=1$. In either case, we are finding an extreme of
$$
\frac{a}{1-a}+\frac{b}{1-b}\tag{5}
$$
An interior extreme of $(5)$ occurs when
$$
\frac{\delta a}{(1-a)^2}+\frac{\delta b}{(1-b)^2}=0\tag{6}
$$
for any variation so that
$$
\delta a +\delta b=0\tag{7}
$$
Linearity says that we need $a=b$, so that if $c=\frac12$, then $a=b=\frac14$ and
$$
\bbox[5px,border:2px solid #C0A000]{\frac{a}{1-a}+\frac{b}{1-b}+\frac{c}{1-c}=\frac53}\tag{8}
$$
or if $c=0$, then $a=b=\frac12$ and
$$
\bbox[5px,border:2px solid #C0A000]{\frac{a}{1-a}+\frac{b}{1-b}+\frac{c}{1-c}=2}\tag{9}
$$

We don't need to worry about the edge edge case where $a=0$ or $b=0$ since those cases are covered by $(9)$. Therefore, the possible extremes are  given in $(4)$, $(8)$, and $(9)$. Thus,
$$
\bbox[5px,border:2px solid #C0A000]{\frac32\le\frac{a}{1-a}+\frac{b}{1-b}+\frac{c}{1-c}\le2}\tag{10}
$$
Answer: The left inequality.
$\sum\limits_{cyc}\frac{a}{b+c}-\frac{3}{2}=\sum\limits_{cyc}\left(\frac{a}{b+c}-\frac{1}{2}\right)=\sum\limits_{cyc}\frac{a-b-(c-a)}{2(b+c)}=\sum\limits_{cyc}\frac{(a-b)^2}{2(a+c)(b+c)}\geq0$.
The right inequality.
$\sum\limits_{cyc}\frac{a}{b+c}<\sum\limits_{cyc}\frac{a+a}{a+b+c}=2$
Answer: The left inecuality:
Use Titu's Lemma and $a^2+b^2+c^2\ge ab+bc+ca$
$$\frac a{b+c}+\frac b{c+a}+\frac c{a+b}=\frac {a^2}{ab+ac}+\frac {b^2}{bc+ba}+\frac {c^2}{ca+bc}\ge$$
$$\ge\frac{(a+b+c)^2}{2(ab+bc+ca)}=\frac{a^2+b^2+c^2}{2(ab+bc+ca)}+1\ge\frac12+1=\frac32$$
The left inecuality is Nesbitt's inequality
Answer: We show the right side of the inequality, that is,
\begin{align*}
\frac{a}{b+c}+\frac{b}{c+a}+\frac{c}{a+b} < 2,
\end{align*}
which is equivalent to
\begin{align*}
\frac{b+c-a}{b+c}+\frac{c+a-b}{c+a}+\frac{a+b-c}{a+b} > 1.
\end{align*}
Let $x=b+c-a$, $y=c+a-b$, and $z=a+b-c$. Then $x>0$, $y>0$, and $z>0$. Moreover,
\begin{align*}
\frac{b+c-a}{b+c}+\frac{c+a-b}{c+a}+\frac{a+b-c}{a+b} &= \frac{x}{x+\frac{y+z}{2}}+\frac{y}{y+\frac{x+z}{2}}+\frac{z}{z+\frac{x+y}{2}}\\
&=\frac{x^2}{x^2+x\frac{y+z}{2}}+\frac{y^2}{y^2+y\frac{x+z}{2}}+\frac{z^2}{z^2+z\frac{x+y}{2}}\\
&\ge\frac{(x+y+z)^2}{x^2+y^2+z^2+xy+xz+yz} > 1.
\end{align*}
We are done.


Como editar a scrollbar no Firefox e Google Chrone

Question: Ola tenho esse código de CSS que configura a barra de rolagem no site com tudo não funciona no Firefox e nem no Google Chrone alguém poderia me ajudar segue abaixo o código.
::-webkit-scrollbar {
    width:2px;
    height:10px;
}
::-webkit-scrollbar-thumb:vertical {
    background:#000000;
}
::-webkit-scrollbar-thumb:horizontal {
    background:#000000;

}

Esse codigo CSS funcionou perfeitamente no no Navegador Opera.
Answer: Estilizar a barra de rolagem não é um recurso especificado nas CSS, não é um padrão. Ainda assim muitos usuários e desenvolvedores solicitam que esta (e outras) feature seja implementada nos demais navegadores por meio dos canais de comunicação de cada um.
Navegadores com motor webkit já permitem essa estilização da scrollbar, bem como o Internet Explorer a partir da versão 9. Já o Firefox... bem... existe um tópico no BugZilla sobre o assunto há 14 anos.
Como este ainda não é um recurso cross-browser a melhor opção é optar por utilizar algum plugin que permita a estilização e trate a diferença entre navegadores.

Nesta página há uma seleção com alguns, como:

Perfect Scrollbar - DEMO
Scroller - DEMO
SlimScroll - DEMO
jScrollPane - DEMO

Formas de alterar o scroll padrão do navegador utilizando o Perfect Scrollbar (que dos listados acima foi o que achei mais interessante):
Exemplo [aplicando scroll na página toda]

$(function() {
  $('body').perfectScrollbar();
});
* {
  margin: 0;
  padding: 0;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

html,
body {
  position: relative;
  overflow: hidden;
  height: 100%;
  width: 100%;
}

.classQueForcaOScroll {
  height: 800px;
}

<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/jquery.perfect-scrollbar/0.5.9/perfect-scrollbar.min.css'>

Exemplo [aplicando scroll em um elemento específico]

$(function(){
  $('.foo').perfectScrollbar();
});
.foo {
  position: relative;
  border: 2px solid #ccc;
  overflow: hidden;
  height: 60px;
  width: 250px;
}

<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/jquery.perfect-scrollbar/0.5.9/perfect-scrollbar.min.css'>

  scroll scroll scroll scroll

  scroll scroll scroll scroll

  scroll scroll scroll scroll

  scroll scroll scroll scroll

  scroll scroll scroll scroll

Comment: Muito obrigado pelos esclarecimentos.
Comment: Grato pela ajuda era isso mesmo que eu queria.
Comment: @Rodrigo De textarea eu não sei, só lendo a documentação para saber. Em div é possível sim, acabei de incluir um segundo exemplo aplicando o scroll nele.


Webform Create node, send email when webform is submitted

Question: I'm creating a node when a webform is submitted and adding the webform submission id to an int field on the node so the node is linked to the webform submission. I'm also sending an email when the webform is submitted.
Here's the node creation handler code.
<?php

namespace Drupal\my_module\Plugin\WebformHandler;

use Drupal;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\Entity\Node;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;

/**
 * Create Award Nominee nodes from a webform submission.
 *
 * @WebformHandler(
 *   id = "award_nominee_from_webform",
 *   label = @Translation("Award Nominee node"),
 *   category = @Translation("Webform"),
 *   description = @Translation("Creates an Award Nominee node."),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_REQUIRED,
 * )
 */

class AwardNomineeWebformHandler extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
    $webform = $webform_submission->getWebform();
    // Get an array of form field values.
    $submission_array = $webform_submission->getData();
    // Todo: Prevent this save from sending emails.
    $webform_submission->save();

    $sid = $webform_submission->id();

    $term = \Drupal::entityTypeManager()
      ->getStorage('taxonomy_term')
      ->load($submission_array['nomination_award']);
    $award_name = $term->getName();

    if (empty($submission_array['member_information'])) {
      $nominee_middle_name = !empty($submission_array['nominee_middle_name']) ? ' ' . $submission_array['nominee_middle_name'] . ' ' : ' ';
      $title = $submission_array['nominee_first_name'] . $nominee_middle_name . $submission_array['nominee_last_name'];
      $nominee_accomplishments = $submission_array['nominee_accomplishments'];

      $this->getNode($title, $award_name, $nominee_accomplishments, $sid);
    }
  }

  /**
   * Creates the node when it's a new webform submission.
   *
   * @param string $title
   * @param string $award_name
   * @param mixed $nominee_accomplishments
   * @param int $sid
   *
   * @return void
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  protected function getNode(string $title, string $award_name, mixed $nominee_accomplishments, int $sid): void {
    $node = Node::create([
      'type' => 'award_nominee',
      'status' => FALSE,
      'title' => $title,
      'field_award_nominee_plaque_name' => '',
      'field_award_nominee_award_name' => $award_name,
      'field_award_nominee_organization' => '',
      'field_award_nominee_members' => '',
      'body' => [
        'value' => $nominee_accomplishments,
        'format' => 'bold_italic',
      ],
      'field_webform_submission_id' => $sid,
      'field_award_nominee_city' => '',
      'field_award_nominee_state' => '',
    ]);
    $node->save();
  }

}

There's even a hook to delete the nodes when the submission is deleted. Here's the hook:
/**
 * Implements hook_webform_submission_delete().
 */
function my_module_webform_submission_delete(WebformSubmissionInterface $webform_submission) {
  $entity_ids = Drupal::entityQuery('node')
    ->condition('type', 'award_nominee')
    ->condition('field_webform_submission_id.value', $webform_submission->id())
    ->execute();
  $nodes = Node::loadMultiple($entity_ids);
  foreach ($nodes as $node) {
    $node->delete();
  }
}

Although I think another webform handler could "handle" the deletions too.
The problem is the emails are being sent: one from the configured email handler, and one from the webform_submission->save() in the node creation handler. How can I prevent an email being sent from the node creation handler?
$webform_submission->resave() seems to solve the problem like this.
$sid = '';
if ($webform_submission->id()) {
  $webform_submission->resave();
  $sid = $webform_submission->id();
}

Answer: Use \Drupal\webform\Entity\WebformSubmission::resave instead of \Drupal\webform\Entity\WebformSubmission::save
Comment: Thanks @Vanish. That helps a lot. I'll update the code with your suggestion and approve your comment.


hook_form_alter Add wrapping div around label and input

Question: Using hook_form_alter, for each field I want to wrap a div around the label and the input, leaving the help text (description) separate. Can hook_form_alter do this? Seemingly I can only add prefix and suffix to the wrapping div.
Comment: No, You have to implement hook_theme for this.
Comment: ok - can you point me in the right direction for this case?
Answer: You have to implement theme_form_element to achieve desired goal.
It returns HTML for a form element.
Each form element is wrapped in a DIV container
Comment: Thanks, looks close. But I can't see how the html is formed with this hook?


Covert Razor delegate syntax to WebForms

Question: I am trying to write this style of code from cassette using WebForms. Is this possible?
@{
var message = "Hello World!";
Bundles.AddInlineScript(
  @);
}

I haven't managed to find an example of using methods with the Func<Object, Object> parameter in WebForms. Or is this because this only allowed by the Razor view engine?
Answer: <% Bundles.AddInlineScript("if (someTest) { ...") %>

Comment: That's a code nugget. It will execute when the aspx is rendered. See http://msdn.microsoft.com/en-us/library/ms178135(v=vs.90).aspx
Comment: Using the string overload is really painful when the inline script is more than a single line, and needs to mix with variables as the aspx is rendered. This is why I am asking if there is another way.


Não colorir data atual com FullCalendar

Question: Tenho uma agenda em fullcalendar, e estou tentando não colorir o dia de hoje..

note que ele está em amarelo claro (seg 1/4)
Alguma dica?
Answer: Você pode usar o código CSS abaixo para sobrescrever essa configuração:
<code>.fc-today {
    background: #FFF !important;
    border: none !important;
    border-top: 1px solid #ddd !important;
    font-weight: bold;
}
</code>
Lembrando que o código deve ficar abaixo da chamada do arquivo CSS do FullCalendar.
Comment: Tinha achado no CSS  .fc td.fc-today { background-color: #ffffff !important;} mas assim dá certo tb! Obrigado

Não colorir data atual com FullCalendar


How to change value of multiple fields onchange

Question: I want to change the value of Ordered Qty (product_uom_qty) and prix unitaire (price_unit) when changing the Ligne Contrat. But my onchange functions only work for the Ordered Qty, although both functions are called correctly.

Here is my code :
from datetime import datetime, timedelta
from odoo import api, fields, models, _

# Contrat model
class Contrat(models.Model):
    _name = 'contrat.contrat'
    _rec_name = 'contrat_name'
    contrat_name = fields.Char(string='Nom')
    contrat_number = fields.Integer(string="Numero")
    date_start = fields.Date(string='Date Debut')
    date_end = fields.Date(string="Date Fin")
    date_deadline = fields.Date(string="date echeance")
    ligne_id = fields.One2many('contrat.lignes','ligne_ids',"mylignes")
    # notebook_ids = fields.Many2one('contrat.lignes','ligne_id',string='Notebook')
    client_name = fields.Many2one('res.partner',string="Client")
    bons_ligne_ids = fields.One2many('sale.order.line', 'contrat_name_id', String='Contrat bons')

class ContratOrder(models.Model):
    _name = 'contrat.lignes'
    _rec_name = 'ligne_name'
    ligne_ids = fields.Many2one('contrat.contrat',string="Contrat")
    ligne_name = fields.Char(string="Nom de Ligne")
    unit_price = fields.Float(string='Prix Unitaire')
    article_name = fields.Many2one('product.template', string="Article")
    quantity = fields.Float(string='Quantite')

# modifier les lignes des bons de commands
class bons_lignes(models.Model):
    _inherit="sale.order.line"
    bons_po = fields.Integer('PO')
    contrat_name_id = fields.Many2one('contrat.contrat', string='Contrat')
    contrat_lignes_id = fields.Many2one('contrat.lignes', string='Ligne contrat')
    product_uom_qty = fields.Float('qtt', related='contrat_lignes_id.quantity')
    price_unit = fields.Float(string='Prix Unitaire')

    @api.onchange('contrat_lignes_id')
    def onchange_conrat_lignes_id(self):
        self.price_unit = self.contrat_lignes_id.unit_price

How is it possible to change both fields with one or more onchange functions.
EDIT: Odoo already has a onchange trigger on field product_uom_qty which is changing the field price_unit after calling my onchange methods. How is it possible to get my onchange functions get called later, or just forbid Odoo to call its other functions?
Comment: please delete the images with code and add inline code. If you don't know how, read the f****** manual ;-)
Comment: @CZoellner he is a new member he will learn about this in time
Comment: I know, the RTFM was just a well known little hint for him ;-)
Comment: @CZoellner I add the inline code , thanks
Answer: Just use a single onchange method to change both fields.
@api.onchange('contrat_lignes_id')
def onchange_conrat_lignes_id(self):
    self.product_uom_qty = self.contrat_lignes_id.quantity
    self.price_unit = self.contrat_lignes_id.unit_price

Comment: @mahmoud You should be more clear about what you want mahmoud the man answered your question if there is an error in computing you can post another question with more detail about it.
Comment: It takes by default the unit price from the products not from my custom module
Comment: @Cherif oke bro i will
Comment: @Cherif but he is right, the solution won't work, because a quantity change will trigger an onchange method which will again change the price. So this is not the correct solution.
Comment: @CZoellner if you understood what he want you can edit he's question for us. I dind't understand what he want at all
Comment: @CZoellner, you're right . I didn't consider that product_uom_qty already has an onchange method. A quick and dirty solution to this would be to create an empty method called product_uom_change to override the onchange. I wouldn't normally advise doing that but I won't be able to test another method until later tonight.
Comment: @djames take your time :-)


Subtrair valor usando JS

Question: Até o momento meu código estava usando uma soma dos valores
Exemplo:

const inputs = [...document.querySelectorAll("input[class='serv']")];
const res = document.getElementById("resultado");
const total = res.querySelector('[name="total"]');
const serv = res.querySelector('[name="serv"]');

inputs.forEach(x => x.addEventListener("change", () => {
    total.value = inputs.filter(el => el.checked).reduce((sum, el) => sum + Number(el.value), 0);
    serv.value = inputs.filter(el => el.checked).map(el => el.name).join(',');
}));

            Serviços

        <input type="text" class="input-group-text" placeholder="0,00" name="total" value="" readonly="readonly">
        <input type="hidden" name="serv" value="">

    Desconto:
    <select class="form-control form-control-sm" name="desconto">
        <option value=""></option>
        <option value="5%">Desconto Pai e Filho</option>
        <option value="10%">Amigo da Hora</option>
        <option value="15%">Familia</option>
    </select>

                <input type=checkbox class='serv' name="" value="10"> Serviço
                10

                <input type=checkbox class='serv' name="" value="15"> outro Serviço
                15

eu gostaria de saber como incluir um desconto quando for selecionado.
Answer: Primeiro eu aconselharia usar os valores de desconto em decimais, exemplo 5% = 0.05, 10% = 0.1, 15% = 0.15... etc...
const desconto = res.querySelector('[name="desconto"]');

desconto.addEventListener("change", () => {
    var total = serv.value;         // Pega o total
    total = total + total*desconto; // Calcula o Desconto
    total = total.toFixed(2);       // Coloca em formato de decimal com 2 casas
    campo.value = total;            // Preenche o campo que você quer preencher com o valor
})

Depois seria necessário colocar um campo pra exibir o valor final que está na variável total...
Answer: Tente fazer da seguinte forma
-

const inputs = [...document.querySelectorAll("input[class='serv']")];
const res = document.getElementById("resultado");
const total = res.querySelector('[name="total"]');
const serv = res.querySelector('[name="serv"]');
const combo = document.getElementById("desconto");
inputs.forEach(x => x.addEventListener("change", () => {
    total.value = inputs.filter(el => el.checked).reduce((sum, el) => sum + Number(el.value), 0);
    serv.value = inputs.filter(el => el.checked).map(el => el.name).join(',');
 if (combo.value > 0){
  if (total.value > 0){
   total.value = total.value - (total.value * combo.value);
  }
 }

}));

combo.addEventListener("change", () => {
  if (total.value > 0){
    var desconto = (serv.value * combo.value);
 total.value = total.value - (total.value * combo.value);
  }
});

            Serviços

        <input type="text" class="input-group-text" placeholder="0,00" name="total" value="" readonly="readonly">
        <input type="hidden" name="serv" value="0">

    Desconto:
    <select class="form-control form-control-sm" name="desconto" id="desconto">
        <option value="0"></option>
        <option value="0.05">Desconto Pai e Filho</option>
        <option value="0.010">Amigo da Hora</option>
        <option value="0.015">Familia</option>
    </select>

                <input type=checkbox class='serv' name="" value="10"> Serviço
                10

                <input type=checkbox class='serv' name="" value="15"> outro Serviço
                15

Comment: era exatamente essa situação, porém dessa forma não funciona precisamente... após selecionar um desconto quando seleciono outro, ele desconta no valor já descontado e não no valor real e também não consegui voltar ao valor real quando selecionei a opção em branco.

Subtrair valor usando JS


How can I tell if a certain Active Directory login has been used today?

Question: How can I tell if a somebody used the login 'Accounts' today to log into a pc in my Active Directory domain?  It seems to be causing errors if 2 people are logged in using the same username and I don't know if this is the case or not.
Answer: To see the last time a particular account has logged in to your domain, you can run the net user command via a command prompt. Syntax is as follows (without the brackets):
net user [username] [/domain]
That will return several pieces of information, including Last logon time.
Comment: so i would put net user accounts /myersclark  ans sorry is there a way it would tell me what computer it was logged into?
Comment: No, you would put:

net user accounts /domain
Comment: it will not let me vote up i will do when i get enough points
Answer: With Active Directory a user can be logged into different workstations without causing problems.  What are the issues you are seeing?  If you have the proper auditing on your DCs you could search through the event logs for login events for that user.
A more accurate answer could be given if you provide more information on what OS you are running on your DCs and what Domain & Forest Function level you are running.
You could also use the Lockout Tool to search the username if your problem is related to the account getting locked out.  It will search the event logs for bad logon attempts on the DCs and show you the most recent attempt.
Comment: sorry i dont no what a forest function is. my domain in called myersclark and it is run on a server 2003. i have software that runs on my printers so when u scan a document it sends it to the computer where the person is logged in. i have a tempory account called Accounts and when i scan something half of the document appears and the other disappers which makes me think that there are 2 users logged in useing this so i was wondering if there is say a log of when users have logged in
Comment: You would need to look through the Security event log on the DC of your domain for login events.  However, to test you could reset the password of that account so only you know it, or create a new temp account and test with that one.
Comment: it will not let me vote up i will do when i get enough points


Basketball and rebound

Question: In basketball, why is a rebound simply not just called a bounce, ball bounce, or re-bounce? What exactly is a rebound? Also, why is a date with someone used to forget another date simply also called a rebound? What is the connection?
Comment: This may be better suited for English SE, as we're getting into word etymology rather than anything directly sports specific?
Comment: There ate at least two different questions here, and at least one of them is blatantly off-topic for Sports SE.
Answer: Bounce refers to dribbling a basketball.  Re-bounce would mean to dribble again but it is not English so it would have no meaning.
Rebound is actually a word used when a ball or anything hits a hard object and deflects somewhere else.  This isn't just a basketball term.
The connection with the date, is using a sports analogy.  It is a rebound date because you missed on your other date/relationship but got another date quickly, just like if you missed your shot and got a rebound.

Basketball and rebound


unexpected error with php fileinfo extension usage (windows wamp)

Question: I am using current wamp of wampserver.com under windows7 (Apache : 2.4.9, PHP : 5.5.12 ). file upload script was having troubles with file info functions. Troubles that i dont have with linux lamp and professinal hosting companies. Finfo class not found was the error. I added this statement into php.ini to use finfo under win7 wamp
extension=php_fileinfo.dll

I am able to use file info objects and functions. But a weird error shows up when i try to destroy finfo object.
Error:
Warning: finfo_close() expects parameter 1 to be resource

Script:
...
$finfo = new finfo(FILEINFO_MIME_TYPE);
$semamime = $finfo->file($_FILES['filedata']['tmp_name']);
if (false === $ext = array_search(
      $finfo->file($_FILES['filedata']['tmp_name']),
      array(
          'pdf' => 'application/pdf',
      ),
      true
)) {
throw new RuntimeException('Invalid file format.');
}
!!!! finfo_close($finfo); !!!
...

file exists. i am seing the ANSI form of the file content on the screen. i gave the legitimate parameter to the finfo_close but no luck. Is this error about my syntax or the wamp that im using?
EDIT
Complete script: http://pastebin.com/x8Bbv5S4
php.ini file   : http://pastebin.com/9KjVjThU (extension activated at the last line)
Comment: The [examples for `finfo_open` in the manual](http://php.net/manual/en/function.finfo-open.php#refsect1-function.finfo-open-examples) only show `finfo_close` being used when the procedural style with `finfo_open` is used – in the first example for the object-oriented style (`new finfo(…)`) you'll notice that there is no call to `finfo_close` there … so I'd assume that it is simply not needed in this case.
Comment: are you sure extension=php_fileinfo.dll has no semicolon?
Comment: positive. Before erasing semicolon, first line was giving error. Now its the finfo_close()
Comment: @kimbarcelona i posted the file
Comment: you are right. its weird that i copied this from my other script which works flawlessly at remote lamp. I think hosting company omitting php errors.
Comment: @CBroe feel free to post former answer
Answer: The examples for finfo_open in the manual only show finfo_close being used when the procedural style with finfo_open is used – in the first example for the object-oriented style (new finfo(…)) you'll notice that there is no call to finfo_close there … so I'd assume that it is simply not needed in this case.


question related with half angle from a given equation

Question: If $\sec x + \tan x = 3$ , then what is the value of $\tan \frac x2?$
i squared both sides and then converted the $\tan x $ into $\sec x$ and then $\sec  x $ into $\cos x$ which gave me value $\sqrt\frac15$. Kinda confused after this step.. help is appreciated
Comment: Could You write down those steps?
Answer: As $\sec^2x-\tan^2x=1,$
$\sec x+\tan x=a\iff\sec x-\tan x=\dfrac1a$ for finite non-zero $a$
$\implies2\sec x=\dfrac{a^2+1}a,2\tan x=\dfrac{a^2-1}a$
$\implies\sin x=\dfrac{\tan x}{\sec x}=\cdots$
Now $\tan\dfrac x2=\dfrac{1-\cos x}{\sin x}=?$
Answer: HINT:
$$\sec(x)+\tan(x)=3\Longleftrightarrow$$
$$-3+\sec(x)+\tan(x)=0\Longleftrightarrow$$

Substitute $y=\tan\left(\frac{x}{2}\right)$. Than $\sin(x)=\frac{2y}{y^2+1}$ and $\cos(x)=\frac{1-y^2}{y^2+1}$:

$$\frac{2}{y-1}-\frac{4y}{y-1}=0\Longleftrightarrow$$
$$-\frac{2(2y-1)}{y-1}=0\Longleftrightarrow$$
$$\frac{2y-1}{y-1}=0\Longleftrightarrow$$
$$2y=1\Longleftrightarrow$$
$$y=\frac{1}{2}\Longleftrightarrow$$
$$\tan\left(\frac{x}{2}\right)=\frac{1}{2}\Longleftrightarrow$$
$$\frac{x}{2}=\tan^{-1}\left(\frac{1}{2}\right)+\pi n\Longleftrightarrow$$
$$x=2\tan^{-1}\left(\frac{1}{2}\right)+2\pi n$$
With $n\in\mathbb{Z}$

So it if you take $n=0$:
$$x=2\tan^{-1}\left(\frac{1}{2}\right)+2\pi n \Longrightarrow$$
$$x=2\tan^{-1}\left(\frac{1}{2}\right)+2\pi \cdot 0 =2\tan^{-1}\left(\frac{1}{2}\right) $$
Than $\tan\left(\frac{x}{2}\right)$ is:
$$\tan\left(\frac{x}{2}\right) \Longrightarrow$$
$$\tan\left(\frac{2\tan^{-1}\left(\frac{1}{2}\right)}{2}\right)=\tan\left(\tan^{-1}\left(\frac{1}{2}\right)\right)=\frac{1}{2}$$
Answer: Let $2y=\dfrac\pi2-x$
$3=\sec x+\tan x=\csc2y+\cot2y=\dfrac{1+\cos2y}{\sin2y}=\cot y$
$\tan\dfrac x2=\tan\left(\dfrac\pi4-y\right)=\dfrac{1-\tan y}{1+\tan y}=\dfrac{\cot y-1}{\cot +1}=?$


Canceling the SpaceBar Click/Tap on uwp controls throughout the app

Question: When a UI element ( control ) is focused in a uwp app it can be triggered with Spacebar or the Enter keys, this is not limited to Desktop but also helps in Xbox so user can navigate through the controls and press on any focused control to active its Command.
Use case
But in My use case I want only Enter key to trigger that behaviour and Spacebar should not do anything at all no matter which control is pressed on the screen.
The reason to this requirement is that I am building a MediaPlayer application and no matter which control or button is focused within the app when I press Spacebar I want to simply link it to the Play/Pause Behaviour of my media element.
Not a Duplicate
This question is not a duplicate of : UWP - Don't fire Click event when pressing space (like in Movies & TV app)
Because in the question linked above, the answer was only relevant if any of the AppBarButtons were focused so they will not do anything on pressing Space but only will be invoked with Enter. But in my use case I want to apply the same behavior even outside the MediaPlayerElement control. I have a NavigationView and MediaPlayerElement resides in one of the pages, so I want this behavior to work even when a NavigationViewItem is focused or any other control which can be focused and invoked should only be invoked with Enter and not Space.
Is there a app level solution where I can apply this behaviour at the very root control and it descends to all of its children i.e : whole app?
What I have tried
I have tried with the already answered question (linked above) and that works fine for its limited scenario. And I have also tried setting AllowFocusOnInteraction=false to every app bar button and also other extra controls I have in the style of my CustomMediaTransportControls. But this is also limited to MediaPlayerElement only and also it prevents tab navigation which is not good for accessibility.
Answer: You can do this by handling the PreviewKeyDown event higher in the visual tree hierarchy, for example in the Page.
Subscribe to the event in the Page constructor:
public MainPage()
{
    this.InitializeComponent();
    this.PreviewKeyDown += MainPage_PreviewKeyDown;
}

Or in XAML:
<Page ... PreviewKeyDown="MainPage_PreviewKeyDown">

And in the event handler set the KeyRoutedEventArgs to handled when the Space key was pressed:
private void MainPage_PreviewKeyDown(object sender, KeyRoutedEventArgs e)
{
    if (e.Key == VirtualKey.Space)
    {
        e.Handled = true;
    }
}

This way the key down event will never reach any control below in the hierarchy because the PreviewKeyDown event propagates the tree before the event takes place.
Answer: There are many ways could approach, You could listen the current Content PreviewKeyDown event to detect Space press.
public Scenario1()
{
    this.InitializeComponent();
    Window.Current.Content.PreviewKeyDown += Content_PreviewKeyDown;
}

private void Content_PreviewKeyDown(object sender, KeyRoutedEventArgs e)
{
    e.Handled = e.Key == VirtualKey.Space ? true : false;
}

You could also GLOBAL HOTKEY for your uwp app that could be used when your app's window not in foreground. For more derail you could check this blog .


How to edit a profile field from the node add form

Question: My client has a user field field_geolocation of type  Geofield.
And he has a content type issue, he allows people to create new issues (kinda like in drupal.org but private).
What he wants is: When someone is creating a new issue, he should be able to to set/edit the field in his profile identified by field_geolocation.
My guess: create a custom module which does the following

Inject a widget for the user field field_geolocation inside the node add/edit form, prbably with FAPI
Use Node API to save the data collected previously into the actual user.

Did I guess right? Or any better solutions?
Thank you.
Answer: You're on the right track.  It should be a pretty straight forward thing to implement.
I would add a custom submit handler to the node form for your issue content type.  Grab the submitted values for the geolocation field.  Load the user using user_load(), if the value has changed, the update it and call user_save().


On $X = C(0,1)$ define $T:X \to X$ by $T(f)(x) = \int_0^x f(t) \, dt$ for all $f$ in $X$. Is $T$ invertible$?$

Question: On $X = C(0,1)$ define $T:X \to X$ by $T(f)(x) = \int_0^x f(t)\,dt$ for all $f$ in $X$.
Is $T$ invertible$?$
Clearly, $T$ is one one (injective) , since only zero functions will be mapped to zero function, $T$ is one one (injective).
How can I check surjectivity $?$
Comment: It seems to me that $T$ is not surjective. Surjectivity here would mean that every function is $X$ has corresponding function integral of which he represents. However any function represented by operator $T$ is necessarily (continuously) differentiable. However not all function in $X$ has to be differentiable.
Comment: I'd say $T$ is not well-defined. What's $T(x^{-1})$ supposed to be?
Comment: Better notation: $T(f)(x)=\int_0^x f(t)dt$, as $T(f)$ should be in $X$ hence be a function of $x \in (0,1)$.
Comment: So you can take any non-differentiable but continuous function, and can easily state that it can't be represented as an integral of given form.
Answer: Let $r(x)=\left|x-\frac 12\right|$, now $r\in X$ ,but not exists a $t(x)\in X,s.t.r=T(t)$


Where to begin my Math journey

Question: I apologize if this is not the correct forum for this, but I felt it appropriate.
I want to start getting into more mathematics and learning all I can to step up my programming career.  I know plenty of programming languages but I feel like if I can understand more math concepts I can really make some amazing things.
I didn't do well in High School because I slacked off and didn't care (which I regret now).  Now that I have found programming (my passion) I just want to learn more and more and more.
I know addition, subtraction, multiplication & division.  I even remember some basic Geometry and Algebra, but that's about it, I may even need to refresh those.
I see things that are explained in a more mathematical way and I would love to know more about the complicated parts of math, I just have no clue where to begin.  I want to start with the basic and work my way up.
I am interested in 3D math, big data analysis, physics, and statistics.
So, my question has a few parts:

Where do I start?  Where is the best place for someone like me to pick back up and build off of that knowledge into more complicated things?   What books or resources could I start with??
Are there certain parts of math I don't need to know?  Should I just focus on the things I am interested in?
What math is pertinent for 3D math, physics, statistics and data analysis?
What is calculus? (I have always been interested in what this is, an easy to understand explanation would be great)

Thanks in advance!
Comment: Good for you!  I find that I use trig/geometry more than anything when I code.  Also number theory and set theory are always popping up in computer science.  Depending on what you're working on, you probably don't need much calculus, although knowing basics will shed light on certain things.
Comment: @Jedediyah Thank you for your words of wisdom and encouragement.
Comment: Does this answer your question? [Learning mathematics as if an absolute beginner?](https://math.stackexchange.com/questions/22513/learning-mathematics-as-if-an-absolute-beginner)
Answer: It seems like you are a non-traditional student (left High school, some years passed and now want to go back and learn). I do not know about your financial situation, but I would go visit a community college first. They are the cheapest and you can take plenty of math courses there, including 18 credits of calculus. If that's not enough, you can transfer to a 4 year institution and get a bachelors in a computer related field that suits your desires. This track also answers your fourth question in my view
Comment: Sethen: Khan Academy is excellent, especially for brushing up on your math, and studying trig, calculus, etc. There's also Paul's Notes for calc...(I think also linear algebra, which will step up your programming.) You might want to consider looking at online (free) offerings on Coursera...
Comment: @SethenMaleno  Ok, then this is another approach: First get a precalculus book from an online site and then get a calculus book. Stewart or something comparable. You have a good set of brains, allocate time and do self study. You may AUDIT a course if you wish. I did that once (not in a math course but in a course where math was used) and learned a lot. Time and devotion should do it when I read your comment above. And of course, if you need help, mathstackexchange is here to help.
Comment: I can appreciate that you're a great self-learner, and if it's not an option then it's not an option, but @imranfat make a great point.  I'm sure you don't *need* school, but it gives you all sorts of good shortcuts in learning that make it more efficient, and it can be very helpful when looking for a job doing what you're passionate about.
Comment: @Jedediyah This is true.  I think my particular learning style is all about figuring it out on my own and I know I can do that.  I feel like I retain information better when I am given a book and paper/text editor.
Comment: Going back to college for me is not an option.  I've learned HTML, CSS, JavaScript, PHP, Ruby, Python, C# and SQL all by reading books.  In fact, I am senior software engineer currently and I am very good at what I do.  I know I am very capable to learn on my own, I don't need a college course to teach me.
Comment: @imranfat Thank you for that!  I will look into it.
Comment: @imranfat I found this with a quick Google search: https://www.khanacademy.org/math/precalculus ... Any thoughts here?
Comment: Even without actually attending lessons in a school you can still follow the courses that some universities post online, MIT has some really well made videos (I'm not sure about which topics or how advanced are them exactly) and there are other universities doing that too

Where to begin my Math journey


Can I use z-scores to compare data measured in different units?

Question: I am trying to compare the accuracy of two different methods of estimating biomass. This data is in the form of percentage cover (and is arcsine transformed). I also have the real biomass values, measured in grams, so three different measurements of the same thing, one of which (for the purpose of the study) I'm assuming provides the correct values, the other two are of unknown accuracy. What's the best way to approach this?
I've tried two separate correlation analyses, and then used Fisher's r-to-z transformation to compare the correlation coefficients.
I was wondering if it's possible to calculate an 'accuracy' value by standardising all the scores, then taking the absolute value of the difference between my (standardised) % cover data points and the (standardised) biomass value in grams. This would be useful because then I could see whether the accuracy changes over time, for example. But does it make sense?
I'm a statistics novice and could really do with some tips! I'm using SPSS.
Answer: If I understand this correctly, you have
$B$. Measured values of biomass in grams, which you regard as your best measurement.
$C_1$ and $C_2$. Two measures of percent cover, which you regard as proxies for biomass.
The main question is surely the relationships between $B$ on the one hand and $C_1$ and $C_2$ on the other. As $B$ and $C_1$, $C_2$ are in quite different units of measurement, you can only assess accuracy by establishing what functions best approximate $B$ as predicted from $C_1$ and $C_2$ respectively.
Calculating a correlation is pertinent to the extent that the relationships are approximately linear, and my guess would be to doubt that, especially as $B$ is unbounded (no mathematical limit on its upper values) whereas the $C$s are bounded. I'd expect some kind of nonlinear relation here.
Transforming percents or correlations are secondary details; it may be that arcsine transformations (by which you may well mean "arcsine of square root" as that is a common transformation here) help with nonlinearity, or it may not be. Nor is it clear that any standardisation will help at all: standardisation of each variable separately makes sense if there are linear relationships of the form $\hat B = a + bC$,  but if so you are better off working directly with those relationships.
To give good advice we need to see plots of $B$ vs $C_1$ and $B$ vs $C_2$; there is, in my view, no correct method for this problem that can be given in abstraction. Listings of the data would be most helpful if they can be provided easily.
Comment: Thanks for this. Yes, you've correctly understood my data and the question I'm trying to answer. I'm posting scatter graphs for the relationships between B (weight) and the untransformed C1 and C2. As far as I can tell there is a linear relationship (although there seems to be heteroscedasity?)
Comment: I'd fit power functions here of the form $B = aC^b$ which have the right limiting behaviour $C = 0 \Rightarrow B = 0$. What you have shown suggests that the bounds on cover don't bite as it is not more than $0.3$.
Comment: Sorry, can you explain that a bit more fully? I don't understand what you're suggesting- how do i find the appropriate a and b values?
Comment: Usually people take logarithms and fit a regression, as $\log B = \log a + b \log C$. As I guess you're a biologist of some kind, a search term is "allometry".
Comment: http://stats.stackexchange.com/questions/59784/regression-for-a-model-of-form-y-axk is one place to start.


IIS install failed because "the server that you specified requires a restart" constant loop

Question: I have a machine running Windows Server 2012 Datacentre and have been having problems re-installing IIS.  It had been installed previously but could not properly locate the .NET central configuration so I tried a re-install.  The uninstall went fine although when re-installing (after a reboot) I was presented with the error:
<code>The operation cannot be completed because the server that you specified requires a restart
</code>
At first I tried a restart but I still got this error afterwards.  I searched the Internet and have tried several options including:

Add NT SERVICE\ALL SERVICES to the Log on as a service privilege in Group Policy - this was already set on my machine
Explicitly add MSSQL$MICROSOFT##WID to the Log on as a service privilege in Group Policy - this user/service could not be found and could therefore not be added
Install Windows Internal Database - the install failed alongside IIS

What is odd is IIS is not installed but it still appears as a snap-in in the Computer Management MMC but not in Server Manager.
Is there anything else I can try other than a full Windows re-install and reset?  I can run IIS on a VM on top of this server but the fact I have problems configuring server roles and features concerns me as it is effectively a faulty instance at present.
The server has the Hyper-V role enabled and Visual Studio 2015 Community and SQL Server 2014 Enterprise installed.
Answer: Are there any files in c:\windows\system32\inetsrv? If so, try moving them to another temp folder during the reinstall. It should be empty if IIS isn't installed.
Also, can you install other applications? You mentioned that Windows Internal Database wouldn't install, so this suggests that the issue may be with the Windows installer rather than IIS itself.
Does Event Viewer have any clues, with either a timestamp right after the last reboot or during the attempted install?
Comment: Many thanks for your response, however, I had performed a full server reinstall by the time you wrote this.  :(  I am reorganising application distribution and will be moving IIS onto a Hyper-V VM (it's not a critical instance).  If the issue ever comes up again I shall try this method though.
Comment: @BWHazel That sounds good. Thanks for the update. All the best with it.


Why my simple tableview app won't work?

Question: Iv'e made a code for a simple tableview app and with textfield and a button.
When I click on the button it adds to the array but do not show it on the table view.
What can I do to see it?
Here is the code:
import UIKit

class ViewController: UIViewController, UITableViewDelegate {
    @IBOutlet weak var textfieldd: UITextField!
    @IBOutlet var tasksTable:UITableView!
    var toDoList:[String] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {

        return toDoList.count

    }

    @IBAction func Add(sender: AnyObject) {

        toDoList.append(textfieldd.text)
        println(toDoList)
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {

        var cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
        cell.textLabel?.text = toDoList[indexPath.row]
        return cell

    }

}

Answer: You've updated your data source (the array), but not the actual display (the table view). You should call the reloadData() function whenever you want to update your table view:
tasksTable.reloadData()
Comment: Thank you! i did it but it didn't work.
So i added it to the button func and now it works
Comment: @Eliko If this answer helped you, please upvote it by clicking the up-facing arrow/triangle to the left and click the checkmark.
Answer: You need to reload the TableView after you've added the new element to the list.
You can do so with the reloadData method.
tasksTable.reloadData()

Answer: You are not applying the UITableviewDataSource protocol to your class, just the delegate.
Add it and set the datasource for the table to the class?

Why my simple tableview app won't work?


Test-ComputerSecureChannel - Logon failure: unknown user name or bad password

Question: I restored a Win7 image that I know will be out of date.   I then run as administrator powershell from an account that is a member of the local machine administrator group.
All I get is:
Test-ComputerSecureChannel : Logon failure: unknown user name or bad password.
At line:1 char:27
+ Test-ComputerSecureChannel <<<<  -verbose
    + CategoryInfo          : NotSpecified: (:) [Test-ComputerSecureChannel], AuthenticationException
    + FullyQualifiedErrorId : System.Security.Authentication.AuthenticationException,Microsoft.PowerShell.Commands.TestComputerSecureChannelCommand

Or if I provide Credential:
PS C:\Windows\system32> Test-ComputerSecureChannel -Credential domain\administrator
Test-ComputerSecureChannel : A parameter cannot be found that matches parameter name 'Credential'.
At line:1 char:39
+ Test-ComputerSecureChannel -Credential <<<<  domain\administrator
    + CategoryInfo          : InvalidArgument: (:) [Test-ComputerSecureChannel], ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.TestComputerSecureChannelCommand

I even tried using psexec -sid to run powershell under the system account but that gives same unknown user or bad password issue.
How is this supposed to work?
Comment: I rejoined the domain and using `nltest` works without access denied (it had said that before rejoining the domain), but the `Test-ComputerSecureChannel` still gives the same logon failure message.
Answer: Please make sure to remove the computer account from Active Directory. Then rejoin the computer in domain. It will reset the password of the computer account in AD.
Please let me know if this helps.
Answer: Try this
$cred = Get-Credential
Test-ComputerSecureChannel -Credential $cred

When running $cred = Get-Credential make sure to enter a domain account that permissions to read computer accounts. Best thing is to be logged on with a domain account.
This cmdlet works much like NetDom.exe. Both NetDom and Test-ComputerSecureChannel use the NetLogon service to perform the actions.


Como mostrar dados do banco em Textboxes?

Question: Olá! Meu cenário é o seguinte:
Estou desenvolvendo uma aplicação Web em C# ASP.NET, e estou tendo algumas dificuldades para trazer os dados do banco (via LINQ to SQL) para os controles da página.
Abaixo um dos controles do meu arquivo .aspx onde desejo trazer uma determinada informação do banco
 <asp:TextBox
    ID="txtCodigo"
    ClientIDMode="Static"
    CssClass="form-control"
    MaxLength="4"
    Enabled="false"
    runat="server">
 </asp:TextBox>

E abaixo o meu .aspx.cs.
protected void Page_Load(object sender, EventArgs e)
    {
            int idCliente;
            TB_CLIENTE_CLI cliente = new TB_CLIENTE_CLI();
            if (Int32.TryParse(Request.QueryString["ID"], out idCliente))
            {
                ClienteBusiness.ListarCliente(idCliente);

                txtCodigo.Text = cliente.ID_CLIENTE_CLI.ToString();
                txtRazaoSocial.Text = cliente.TXT_RAZAOSOCIAL_CLI;
                txtNomeFantasia.Text = cliente.TXT_NOMEFANTASIA_CLI;
                txtCNPJ.Text = cliente.TXT_CNPJ_CLI;
                txtCEP.Text = cliente.TXT_CEP_CLI;
                txtLogradouro.Text = cliente.TXT_LOGRADOURO_CLI;
            }

}

Minha aplicação está dividida em camadas. O método ClienteBusiness.ListarCliente(idCliente) chama outro método que, por sua vez, faz a consulta ao banco, conforme mostra o código abaixo:
public static List<TB_CLIENTE_CLI> ListarCliente(int idCliente)
    {
        List<TB_CLIENTE_CLI> cliente = null;
        using (PlanoTesteDataContext context = new PlanoTesteDataContext())
        {
            cliente = (from clientes in context.TB_CLIENTE_CLIs
                       where clientes.ID_CLIENTE_CLI == idCliente
                       select clientes).ToList();
        }
        return cliente;
    }

Comment: Está passando por qual dificuldade especificamente? O método está retornando alguma exceção em algum ponto?
Comment: Olá Pedro! Os dados simplesmente não são exibidos. Não recebo nenhuma exception ou erro.
Comment: "Debugando" o código você verificou se está entrando no if e valores estão sendo exibidos? Se sim, você pode ir "debugando" colocando na janela Watch do Visual Studio para ver se em algum momento do fluxo da requisição esse valor é apagado.
Comment: Pedro, haviam alguns erros nos meus métodos, que o Eduardo listou e assim consegui resolver o problema. Mesmo assim, muito obrigado pela ajuda!
Answer: Existem alguns problemas no seu códdigo:

No Page_Load o comando ClienteBusiness.ListarCliente(idCliente); não popula o objeto cliente, já que nada recebe o retorno do métood listarCliente(...).
O método public static List<TB_CLIENTE_CLI> ListarCliente(int idCliente) retorna uma lista ao passo que deveria retornar apenas um objeto cliente, para que seu código no Page_Loadfaça sentido.

A linha ClienteBusiness.ListarCliente(idCliente); no método Page_Load deveria ser: cliente = ClienteBusiness.ListarCliente(idCliente);.
O método public static List<TB_CLIENTE_CLI> ListarCliente(int idCliente) deveria ser implementado da seguinte maneira:
public static List<TB_CLIENTE_CLI> ListarCliente(int idCliente)
{
    List<TB_CLIENTE_CLI> cliente = null;
    using (PlanoTesteDataContext context = new PlanoTesteDataContext())
    {
        cliente = (from clientes in context.TB_CLIENTE_CLIs
                   where clientes.ID_CLIENTE_CLI == idCliente
                   select clientes).ToList();
    }
    return cliente.First();
}

Comment: Obrigado pelas correções, Eduardo! Consegui resolver o problema de acordo com as suas recomendações.


Merge two postgres outputs into a single output

Question: I have  two tables in postgres
regions
'Passenger transportation'
regions:
code_id, region
'Passenger transportation':
"Total thousands of people", "Unit of measure",
"Date of report", "transport",
"Railway transport", "Air transport",
"sea transport", "Inland sea transport"
I have two query in postgres:
1:
SELECT json_build_object('Passenger transportation',
json_agg(
json_build_object ('Total thousands of people', "Total thousands of people", 'Unit of measure', "Unit of measure",
'Date of report', "Date of report", 'transport', "transport",
'Railway transport', "Railway transport", 'Air transport', "Air transport",
'sea transport', "sea transport", 'Inland sea transport', "Inland sea transport"
)
)
)
FROM "1.0"

and 2:
SELECT json_build_object('List of regions',
                            json_agg(
                               json_build_object ('Region name', region, 'region code', kod_id)
                            )
                        )
FROM regions;

Their's outputs what I have
1:
{
  "Passenger transportation": [
    {
      "Total thousands of people": 17565,
      "Unit of measure": "Thousands of people",
      "Date of report": "2023-06-01",
      "transport": 2423,
      "Railway transport": 421,
      "Air transport": 234,
      "sea transport": 54,
      "Inland sea transport": 23
    }
 ]
}

2:
[
{
   "List of regions":[
      {
         "Region name":"Moscow region",
         "region code":77
      },
      {
         "Region name":"Belgorod Oblast",
         "region code":31
      },
      {
         "Region name":"Bryansk Oblast",
         "region code":32
      }
   ]
}

I need to get a json response like this:
{
   "List of regions":[
      {
         "Region name":"Moscow region",
         "region code":77
      },
      {
         "Region name":"Belgorod Oblast",
         "region code":31
      }
   ]
,
{
  "Passenger transportation": [
    {
      "Total thousands of people": 17565,
      "Unit of measure": "Thousands of people",
      "Date of report": "2023-06-01",
      "transport": 2423,
      "Railway transport": 423,
      "Air transport": 234,
      "sea transport": 54,
      "Inland sea transport": 23
    }
}

{
   "List of regions":[
      {
         "Region name":"Moscow region",
         "region code":77
      },
      {
         "Region name":"Belgorod Oblast",
         "region code":31
      }
   ]
,
{
  "Passenger transportation": [
    {
      "Total thousands of people": 17566,
      "Unit of measure": "Thousands of people",
      "Date of report": "2023-06-02",
      "transport": 2425,
      "Railway transport": 423,
      "Air transport": 554,
      "sea transport": 55,
      "Inland sea transport": 13
    }
}

Can you please tell me how to get the output I want?
Maybe who's know where I can see sample queries in postgres for json output?
Comment: Is there any column linking those two tables ?
Comment: There is no such column.
Answer: We can use the operator || to concatenate two jsonb values into a new jsonb value :
WITH regions_cte as (
  SELECT json_build_object('List of regions',
                         json_agg(
                             json_build_object ('Region name', region, 'region code', kod_id)
                         )
                        ) as regions
  FROM regions
),
passengers_cte as (
  SELECT json_build_object('Passenger transportation',
                           json_agg(
                              json_build_object ('Total thousands of people', "Total thousands of people", 'Unit of measure', "Unit of measure",
                                'Date of report', "Date of report", 'transport', "transport",
                                'Railway transport', "Railway transport", 'Air transport', "Air transport",
                                'sea transport', "sea transport", 'Inland sea transport', "Inland sea transport"
                              )
                           )
        ) as passengers
  FROM Passenger_transportation
)
select regions::jsonb || passengers::jsonb
from regions_cte, passengers_cte;

If we take this data :
create table regions (
  region varchar(20),
  kod_id int
);

insert into regions values
('Moscow region', 77), ('Belgorod Oblast', 31), ('Bryansk Oblast', 32), ('Vladimir Oblast', 33);

create table Passenger_transportation (
      "Total thousands of people" int,
      "Unit of measure" varchar(20),
      "Date of report" date,
      "transport" int,
      "Railway transport" int,
      "Air transport" int,
      "sea transport" int,
      "Inland sea transport" int
);

insert into Passenger_transportation values
(17565, 'Thousands of people', '2023-06-01', 2423, 421, 234, 54, 23);

We will get as result :
{
   "List of regions":[
      {
         "Region name":"Moscow region",
         "region code":77
      },
      {
         "Region name":"Belgorod Oblast",
         "region code":31
      },
      {
         "Region name":"Bryansk Oblast",
         "region code":32
      },
      {
         "Region name":"Vladimir Oblast",
         "region code":33
      }
   ],
   "Passenger transportation":[
      {
         "transport":2423,
         "Air transport":234,
         "sea transport":54,
         "Date of report":"2023-06-01",
         "Unit of measure":"Thousands of people",
         "Railway transport":421,
         "Inland sea transport":23,
         "Total thousands of people":17565
      }
   ]
}

Demo here
This question is a follow-up of this one : PostgreSQL to JSON object
Comment: Big thanks for answer! But if I have several rows filled in the table "Passenger_transportation",
I get this output
 {
   "List of regions":[
      {
         "Region name":"Moscow region",
         "region code":77
      },
      {
         "Region name":"Belgorod Oblast",
         "region code":31
      }
   ]
 "Passenger transportation":[
      {
         "transport":2423,
         "Air transport":234,
         "sea transport":54,
},
     {
         "transport":2424,
         "Air transport":235,
         "sea transport":56,
      }
   ]
}
Comment: There should be a link between those tables !, you can have a column in table **Passenger_transportation** reference table **regions**  Exemple https://dbfiddle.uk/ZLyjhgft


R - Random Forest and more than 53 categories

Question: I know. RandomForest is not able to handle more than 53 categories. Sadly I have to analyze data and one column has 165 levels. Therefor I want to use RandomForest for a classification.
My problem is I cannot remove this columns since this predictor is really important and known as a valuable predictor.
This predictor has 165 levels and is a factor.
Are there any tips how I can handle this? Since we are talking about film genre I have no idea.
Are there alternative packages for big data? A special workaround? Something like this..
Switching to Python is no option. We have too many R scripts here.
Thanks a lot and all the best
The str(data) looks like this:
'data.frame':   481696 obs. of  18 variables:
 $ SENDERNR          : int  432 1612 735 721 436 436 1321 721 721 434 ...
 $ SENDER            : Factor w/ 14 levels "ARD Das Erste",..: 6 3 4 9 12 12 10 9 9 7 ...
 $ GEPLANTE_SENDUNG_N: Factor w/ 12563 levels "-- nicht bekannt --",..: 7070 808 5579 9584 4922 4922 12492 1933 9584 4533 ...
 $ U_N_PROGRAMMCODE  : Factor w/ 14 levels "Bühne/Aufführung",..: 9 4 8 4 8 8 12 8 4 2 ...
 $ U_N_PROGRAMMSPARTE: Factor w/ 6 levels "Anderes","Fiction",..: 5 3 2 3 2 2 5 2 3 3 ...
 $ U_N_SENDUNGSFORMAT: Factor w/ 29 levels "Bühne / Aufführung",..: 20 9 19 4 19 19 24 19 4 16 ...
 $ U_N_GENRE         : Factor w/ 163 levels "Action / Abenteuer",..: 119 147 115 4 158 158 163 61 4 84 ...
 $ U_N_PRODUKTIONSART: Factor w/ 5 levels "Eigen-, Co-, Auftragsproduktion, Cofinanzierung",..: 1 1 3 1 3 3 1 3 1 1 ...
 $ U_N_HERKUNFTSLAND : Factor w/ 25 levels "afrikanische Länder",..: 16 16 25 16 15 15 16 25 16 16 ...
 $ GEPLANTE_SENDUNG_V: Factor w/ 12191 levels "-- nicht bekannt --",..: 6932 800 5470 9382 1518 9318 12119 1829 9382 4432 ...
 $ U_V_PROGRAMMCODE  : Factor w/ 13 levels "Bühne/Aufführung",..: 9 4 8 4 8 8 12 8 4 2 ...
 $ U_V_PROGRAMMSPARTE: Factor w/ 6 levels "Anderes","Fiction",..: 5 3 2 3 2 2 5 2 3 3 ...
 $ U_V_SENDUNGSFORMAT: Factor w/ 28 levels "Bühne / Aufführung",..: 20 9 19 4 19 19 24 19 4 16 ...
 $ U_V_GENRE         : Factor w/ 165 levels "Action / Abenteuer",..: 119 148 115 4 160 19 165 61 4 84 ...
 $ U_V_PRODUKTIONSART: Factor w/ 5 levels "Eigen-, Co-, Auftragsproduktion, Cofinanzierung",..: 1 1 3 1 3 3 1 3 1 1 ...
 $ U_V_HERKUNFTSLAND : Factor w/ 25 levels "afrikanische Länder",..: 16 16 25 16 15 9 16 25 16 16 ...
 $ ABGELEHNT         : int  0 0 0 0 0 0 0 0 0 0 ...
 $ AKZEPTIERT        : Factor w/ 2 levels "0","1": 2 1 2 2 2 2 1 2 2 2 ...

Comment: you might find answers to [R's randomForest can not handle more than 32 levels. What is workaround?](https://stats.stackexchange.com/questions/49243/rs-randomforest-can-not-handle-more-than-32-levels-what-is-workaround) useful.
Comment: Hey @ImranAli I checked this page a few days ago. Sadly this workaround ist not helpful.
Answer: Having faced the same issue, here are some tips I can list.

Switch to another algorithm, for instance gradient boosting from
gbm package. You can handle up to 1024 categorical levels. If your predictor has quite discriminant parameters, you should also consider probabilistic approaches such as naiveBayes.
Transform your predictor into dummy variables, which can be done by using matrix.model. You can then perform a random forest over this matrix.
Reduce the number of levels in your factor. Ok, that may sound like a silly advice, but is it really relevant to look at factors with such "thinness" ? Is it possible for you to aggregate some modalities at a broader level ?

EDIT TO ADD MODEL.MATRIX EXAMPLE
As mentioned, here is an example on how to use model.matrix to transform your column into dummy variables.
mydf <- data.frame(var1 = factor(c("A", "A", "A", "B", "B", "C")),
                   var2 = factor(c("X", "Y", "X", "Y", "X", "Z")),
                   target = c(1,1,1,2,2,2))
dummyMat <- model.matrix(target ~ var1 + var2, mydf, # set contrasts.arg to keep all levels
                         contrasts.arg = list(var1 = contrasts(mydf$var1, contrasts = F),
                                             var2 = contrasts(mydf$var2, contrasts = F)))
mydf2 <- cbind(mydf, dummyMat[,c(2:ncol(dummyMat)]) # just removing intercept column

Comment: Once you have transformed your factor column into dummy variables, you just need to combine its columns to your initial data frame (you will keep the same number of rows if using `model.matrix`). I will edit my post to show you an example on how to use it.
Comment: Thanks @AshOfFire Point 3 is sadly not possible. Tip 2: I checked the model.matrix method but I guess I am to stupid for this. At the moment we ware talking about a data.frame and one column with more than 53 levels. When I extract this column and transform the values to a matrix, how can I use this new generated matrix in combination with the initial data? I will check out the gbm package.
Comment: Ah, I got the point. As shown in your example I will get a data.frame called mydf2 with some additional columns. So I can use this new generated data.frame and extract the columns I need. In this case just remove the columns called "var1" and "var2". Makes sense. But do you think RandomForest is helpful for so many factors regarding the run-time? Do you have experiences? You mentioned the package GBM... THANKS A LOT!
Comment: You may indeed face run time issues (considering the volume you're treating). Depending on the purpose of your classification, you may have to drop RF and consider alternatives. In my case, I had 5 predictors, including one with ~800 factors and one with ~60 factors (couldn't reduce them) + 100k observations. I used `gbm` on a single-core laptop and the script took roughly 10-15 minutes. It happened, though, that `naiveBayes` gave much quicker (and nicer) results since in a couple of seconds (ironically, the combination of those two predictors was very discriminant), so I stuck to this method.
Comment: @AshOfFire : will the code you provided in the answer work for continuous and categorical variables together?
Comment: @Noob no this is oriented towards categorical variable. If you have continuous variables, I suggest you perform bucketing beforehand.
Answer: Use the caret package :
random_forest <- train("***dependent variable name***" ~ .,
                 data = "***your training data set***",
                 method = "ranger")
 This can handle 53 + categories.


Alinhar divs á esquerda com css, separando-as em grupos, sem quebra de linha

Question: Estou procurando uma forma de alinhar divs á esquerda, porém, mante-las divididas em grupos, sem que um grupo quebre a linha. O código abaixo chega perto, mas gostaria de obter o resultado da imagem.

.group {
    border-width: 1px;
    border-style: solid;
    border-color: #008040;
    overflow: inherit;
    padding:5px;
    float:left;
    margin-left: 5px;
    margin-top:5px;
}

.machine {
    float: left;
    border-color: red;
    height: 75px;
    width: 50px;
    border-width: 1px;
    border-style: solid;
    box-sizing:border-box;
}

1

2

3

4

1

2

3

4

1

2

3

4

O código acima me dá este resultado (ATUAL):

Mas eu gostaria de obter este outro resultado (DESEJADO):

É possível?
Comment: Complicado de fazer isso, eu particularmente não consigo imaginar um jeito simples de fazer ou algo pronto que faça, teria que identificar o "group" que excede a largura da tela e modificá-lo, por ai vai...Surgiram algumas ideia, mas nenhuma de simples implementação, caso eu encontre algo, posto aqui.
Comment: Este código chega muito próximo ao resultado esperado

[link]https://stackoverflow.com/a/44293889/1872936
Answer: Acho que assim chega bem perto do que você procura. Mas fica bem difícil alinhar.

.group {
  display: inline;
  border-width: 1px;
  border-style: solid;
  border-color: #008040;
  padding: 35px 5px;
  margin-left: 5px;
  margin-bottom: 15px;
  line-height: 75px;
}

.machine {
  display: inline-block;
  border-color: red;
  height: 75px;
  width: 50px;
  border-width: 1px;
  border-style: solid;
  box-sizing: border-box;
  text-align: center;
  margin-bottom: 20px;
}

1

2

3

4

1

2

3

4

1

2

3

4

EDIT
Se você não fizer questão dos espaços entre os grupos... Ele é o que efetivamente desalinha tudo:

.group {
  display: inline;
  border-width: 1px;
  border-style: solid;
  border-color: #008040;
  padding: 35px 0px;
  margin-bottom: 15px;
  line-height: 75px;
}

.machine {
  display: inline-block;
  border-color: red;
  height: 75px;
  width: 50px;
  border-width: 1px;
  border-style: solid;
  box-sizing: border-box;
  text-align: center;
  margin: 0 3px 25px;
}

1

2

3

4

1

2

3

4

1

2

3

4

Comment: Ficou excelente. Obrigado! Agora surgiu mais uma demanda: Preciso colocar um `header` no topo de cada grupo (acima das máquinas), por exemplo: Grupo 1, Grupo 2, etc...
Comment: Este seria o resultado final que preciso: https://i.stack.imgur.com/8VG3N.png
Comment: @pires E como você imagina isso dando certo quando se quebrasse no final da página?
Comment: Ainda não faço idéia, mas, talvez repedir o `header`.


$lub(a, b)$ and $glb(a, b)$ of non- comparable lattice elements

Question: In an algebraic lattice $(L, \vee, \wedge, 0, 1)$, the binary operations $\vee$ and $\wedge$ are commutative and associative, satisfying absorption laws. The elements $0$ and $1$ are top and bottom elements, respectively. In other words $0$ is additive identity and $1$ is multiplicative identity.
In general, elements $a,b\in L$ are comparable if $a\leq b$ and in that case, least upper bound ($lub$)of $a$ and $b$= $ a\vee b=b$ and greatest  lower bound ($glb$) of $a$ and $b$=$ a\wedge b=a$
However, if $a$ and $b$ are not comparable, then presumably $lub(a, b)$ =$ a\vee b=1$ and $glb(a, b)$=$ a\wedge b=0$.

Can we find an example of lattice in which $lub(a, b)$ =$ a\vee b\neq 1$ and $glb(a, b)$=$ a\wedge b\neq 0$ when $a\nleq b$?
Comment: Also, $a\wedge b$ is not usually called the "infimum"; it's called the greatest lower bound of $a$ and $b$; and $a\vee b$ is the least upper bound of $a$ and $b$.
Comment: @ArturoMagidin you are right. I will  correct it. In your example, $ a$ and $ b$ are not comparable, so getting whole set as the $lub$ and $\emptyset $ as the $glb$, But apparently, whole set is identity elements with respect to set intersection and $\emptyset$ is identity with respect to set union. I am looking for $glb$ and $lub$ to be other than identity elements.
Comment: No, they aren't "identity elements". The $0$ element is the *least* element, which in this case is $\varnothing$. The $1$ is the *greatest* element, which in this case is the whole set. The example I gave **is** an example of what you want: the join is not the whole set, the meet is not the empty set. Or else, what you claim you want is not what you *actually* want.
Comment: "lub" by itself doesn't mean anything. It's "least upper bound **of** $a$ and $b$", etc. Just saying "lub" is like saying "give me the name", and never specifying the name of *what*.
Answer: Your nomenclature is off: $a\wedge b$ is called the greatest lower bound of $a$ and $b$, or the "meet of $a$ and $b$", not the infimum of $a\wedge b$; $a\vee b$ is called the least upper bound of $a$ and $b$ or the "join of $a$ and $b$", not the supremum of $a\vee b$. For complete lattices, if $S$ is a subset, then $\bigvee S$ is the supremum of $S$, $\bigwedge S$ the infimum of $S$. You could say $a\vee b$ is "the supremum of $a$ and $b$", but not "the supremum of $a\vee b$".
Finally, note that "algebraic lattice" is actually a term of art: it means a complete lattice in which every element is a join of compact elements. I think what you mean is "a lattice viewed as an algebra (in the sense of universal algebra)".
As to the rest, you are somewhat confused. If $a$ and $b$ are comparable, then $a\wedge b = \min\{a,b\}$ and $a\vee b= \max\{a,b\}$. So if, for example, $a\leq b$, then $a\vee b = b$ and $a\wedge b = a$. In particular, if you took $a=0$ and $b=1$, you would have $a\wedge b =0$ and $a\vee b = 1$; your assertion that if they are comparable then $a\wedge b\neq 0$ and $a\vee b\neq 1$ is false.
As to examples: let $L$ be the lattice of subsets of $\{1,2,3,4\}$ ordered by inclusion. Here, $A\wedge B = A\cap B$, $A\vee B = A\cup B$, $\mathbf{0}=\varnothing$, and $\mathbf{1}=\{1,2,3,4\}$.
Let $a=\{1,2\}$, $b=\{2,3\}$. These two elements are incomparable, since neither is contained in the other. Here, $a\wedge b = a\cap b = \{2\}\neq\varnothing$, and $a\vee b = a\cup b = \{1,2,3\}\neq\{1,2,3,4\}$.
In a $01$-lattice, two elements $a$ and $b$ such that $a\wedge b = 0$ and $a\vee b=1$ are said to be "complementary".
Comment: We can still say that $a \wedge b$ is the infimum of $\{a,b\}$; I'm not sure the OP will get that from your answer and the example with the set $S$.
Comment: @amrsa: But that's the infimum of $\{a,b\}$, not "infimum of $a\wedge b$".
Comment: Yes, I understand. I'm just not sure the difference is explicit enough for the OP


How to insert last element using myStringList

Question: I'm having issues with myStringList.insertLast(name)
I'm unsure if I need to change .insertLast to something else. The error says the name cannot be resolved to a variable.
public class TestLinkedList
{
  public static void main(String [] args)
  {

  // define an Integer linked list MyIntList
  LinkedListClass<Integer> MyIntegerList = new LinkedListClass<Integer>();

  // intitialize the list
  MyIntegerList.initializeList();

  // insert a last element 5, then 6, and 7
  MyIntegerList.insertLast(5);
  MyIntegerList.insertLast(6);
  MyIntegerList.insertLast(7);

  // print the list
  MyIntegerList.print();

   // insert first element 8
   MyIntegerList.insertFirst(11);

   // print the list
   MyIntegerList.print();

  // define a String linked list MyStringList
  LinkedListClass<String> MyStringList = new LinkedListClass<String>();

  // initialize the list
  MyStringList.initializeList();

  // insert last element Chris ,then Tom, and Bo
  MyStringList.insertLast(Chris);
  MyStringList.insertLast(Tom);
  MyStringList.insertLast(Bo);

  // print the list
  MyStringList.print();

  // insert first element Bo
  MyStringList.insertFirst(Anna);

  // print the list
  MyStringList.print();

  }
}

The actual errors Im receiving say the following:
4 errors found:
File: C:\Users\GreatOne\Desktop\Master Folder\LinkedList\LinkedList\TestLinkedList.java  [line: 36]
Error: Chris cannot be resolved to a variable
File: C:\Users\GreatOne\Desktop\Master Folder\LinkedList\LinkedList\TestLinkedList.java  [line: 37]
Error: Tom cannot be resolved to a variable
File: C:\Users\GreatOne\Desktop\Master Folder\LinkedList\LinkedList\TestLinkedList.java  [line: 38]
Error: Bo cannot be resolved to a variable
File: C:\Users\GreatOne\Desktop\Master Folder\LinkedList\LinkedList\TestLinkedList.java  [line: 44]
Error: Bo cannot be resolved to a variable

Comment: A string literal in java must be enclosed in " otherwise it will be treated as a variable. "Chris", "Tom" and "Bo".
Comment: ah, I should have known that. thanks @ arynaq
Answer: String must b enclosed between double-quotes ("). Solution of your compilation problems would be here:
  MyStringList.insertLast("Chris");
  MyStringList.insertLast("Tom");
  MyStringList.insertLast("Bo");

  ...

  // insert first element Bo
  MyStringList.insertFirst("Anna");

Answer: Name are String, In java you have to use " ".
   MyStringList.insertLast("Chris");
   MyStringList.insertLast("Tom");
   MyStringList.insertLast("Bo");
   MyStringList.insertFirst("Anna");


How to config Scss and purgeCss in Next js custom postCSS config

Question: I am using Scss and Bootstrap for designing my project. In order to remove unused Css with purgeCss , I have customized my postcss.config.js file like this:

module.exports = {
  plugins: [
    "postcss-flexbugs-fixes",
    [
      "postcss-preset-env",
      {
        autoprefixer: {
          flexbox: "no-2009",
        },
        stage: 3,
        features: {
          "custom-properties": false,
        },
      },
    ],
    [
      "@fullhuman/postcss-purgecss",
      {
        content: [
          "./pages/**/*.{js,jsx,ts,tsx}",
          "./components/**/*.{js,jsx,ts,tsx}",
        ],
        defaultExtractor: (content) => content.match(/[\w-/:]+(?<!:)/g) || [],
        safelist: ["html", "body"],
      },
    ],
  ],
};

The problem is that postCss is ignoring my Scss files and not showing styles.
How can I add Scss to postcss.config.js file?
Answer: The Problem come from @fullhuman/postcss-purgecss.
You can delete it.
 [
      "@fullhuman/postcss-purgecss",
      {
        content: [
          "./pages/**/*.{js,jsx,ts,tsx}",
          "./components/**/*.{js,jsx,ts,tsx}",
        ],
        defaultExtractor: (content) => content.match(/[\w-/:]+(?<!:)/g) || [],
        safelist: ["html", "body"],
      },
    ],

And then work scss again. Or you can change setting about content.


wp_schedule_event não está funcionando

Question: Tenho a seguinte função criada no meu functions.php.  Estou alterando o tema para agendar, e eu consigo ver que está agendado pela função do next_schedule.
add_action( 'after_switch_theme', 'prefix_setup_schedule' );

function prefix_setup_schedule() {
    if ( ! wp_next_scheduled( 'sendemail' ) ) {
        $timeschedule = strtotime(date("Y-m-d 18:00:00"));
        wp_schedule_event( $timeschedule, 'daily', 'sendemail');
    }
}

function sendemail()
{
    update_option('envioemail','feito');
}

Porém, esse código não está sendo executado, alguém tem alguma ideia?
Answer: Consegui resolver da seguinte maneira, primeiro o  wp_schedule_event ficou assim:
wp_schedule_event( $timeschedule, 'daily', 'my_daily_event');

Depois criei uma action assim:
add_action( 'my_daily_event',  'sendemail' );

e a função ficou normal, assim o meu problema foi resolvido.
Resposta baseada em comentário do autor da pergunta.
Comment: Caio, se quiser publicar uma resposta em seu próprio nome, me avise e removo esta.

wp_schedule_event não está funcionando


ng2-charts bar charts displaying values at the end of the bar

Question: I am using ng2-charts to display very basic charts. I am using horizontal bar charts and I need to display values at the end of bars. I couldn't figure out how to do that?
See image
Following is my html and options:
<code> <canvas height="500" width="1000" baseChart
            [data]="barChartData"
            [labels]="statusNames"
            [options]="barChartOptions"
            [colors]="chartColors"
            [legend]=false
            [chartType]="barChartType"
            (chartHover)="chartHovered($event)"
            (chartClick)="chartClicked($event)">
</canvas>

    public barChartOptions: any = {
    title: {
        display: true, text: 'Current Subject Status',
        fontSize: 20,
        color: "black"
    },
    scales: {
        xAxes: [{
             gridLines: {
                          borderDash: [5],
                          lineWidth: 1.4
                         },
             ticks: { beginAtZero: true}
             }],
        yAxes: [{
                  barThickness: 20,
                  gridLines: { display: false }
                }]
    },
    maintainAspectRatio: true,
    responsive: false
    };

    public barChartType: string = 'horizontalBar';
    public chartColors: any = [{ backgroundColor: "#005CA9" }];
    public barChartData: number[] = [3, 97 ,15, 13,63 ];
</code>
Comment: I found a solution here: https://github.com/valor-software/ng2-charts/issues/662
Answer: Found the solution Here on GitHub


Edit method for EmployeeStore (HashMap)

Question: Hey my edit method is not running correctly.  I'll tell you step by step how it isn't supposed to work.
Step 1:  The user inputs a name such as Luis Suarez and then the searchByName method will search for this name in the Employee Store.
Step 2:The User will again input employee details and this time it will overwrite the employee they wish to edit.
I will now show you my code:
MainApp
//---------------------------------------------------------------------------------------
//              Name:        Case 4: Edit.
//              Description: Choice 4 gives the user an option to edit the employee's in the store.
//                           This consists of changing the employee's name,id and e-mail address.
//---------------------------------------------------------------------------------------
            case 5:
                System.out.println("Edit");
                Employee employeeEdit = MenuMethods.userInputByName();
                Store.searchByName(employeeEdit.getEmployeeName());
                if (employeeEdit != null)
                {
                    employeeEdit.setEmployeeName("Joe");
                    employeeEdit.setEmployeeId(1);
                    employeeEdit.setEmployeeEmail("webmail.com");
                    Store.edit(employeeEdit);
                }
                break;

UserInputByName
//---------------------------------------------------------------------------------------
//  Name:        userInputByName.
//  Description: This method is used in the MainApp to give the user capability to search by name.
//---------------------------------------------------------------------------------------
    public static Employee userInputByName()
    {
        // String temp is for some reason needed. If it is not included
        // The code will not execute properly.
        String temp = keyboard.nextLine();
        Employee e = null;
        System.out.println("Please enter the Employee Name:");
        String employeeName = keyboard.nextLine();

        return e = new Employee(employeeName);

    }

Edit
// ---------------------------------------------------------------------------------------
    // Name: Edit.
    // ---------------------------------------------------------------------------------------
    public void edit(Employee employee)
    {
        map.put(employee.getEmployeeName(), employee);
    }

Employee
//---------------------------------------------------------------------------------------
//  Employee class.
//---------------------------------------------------------------------------------------
public class Employee
{
//---------------------------------------------------------------------------------------
//  Variables to be used in the employee store.
//---------------------------------------------------------------------------------------
    private String employeeName;
    private int employeeId;
    private String employeeEmail;
//---------------------------------------------------------------------------------------
//  Name:        Constructors.
//  Description:
//---------------------------------------------------------------------------------------
    public Employee(String employeeName, int employeeId, String employeeEmail)
    {
        this.employeeName = employeeName;
        this.employeeId = employeeId;
        this.employeeEmail = employeeEmail;
    }
//---------------------------------------------------------------------------------------
//  Overloading the constructor for the use with userInputByName method.
//---------------------------------------------------------------------------------------
    public Employee(String employeeName)
    {
        this.employeeName = employeeName;
    }
//---------------------------------------------------------------------------------------
//  Name:   Getters.
//---------------------------------------------------------------------------------------
    public String getEmployeeEmail()
    {
        return employeeEmail;
    }

    public String getEmployeeName()
    {
        return employeeName;
    }
    public int getEmployeeId()
    {
        return employeeId;
    }
//---------------------------------------------------------------------------------------
//  Name:   Setters.
//---------------------------------------------------------------------------------------
    public void setEmployeeEmail(String employeeEmail)
    {
        this.employeeEmail = employeeEmail;
    }
    public void setEmployeeName(String employeeName)
    {
        this.employeeName = employeeName;
    }
    public void setEmployeeId(int employeeId)
    {
        this.employeeId = employeeId;
    }

//---------------------------------------------------------------------------------------
//  Name:   toString.
//---------------------------------------------------------------------------------------
    public String toString()
    {
        return "\t\t\tEmployee\n" +
                "********************************************************************\n"+
                "Employee Name: "+ employeeName +"\n"+
                "Employee Id: " + employeeId +"\n"+
                "Employee Email: " + employeeEmail;
    }
//---------------------------------------------------------------------------------------
}

SearchByName
// ---------------------------------------------------------------------------------------
    // Name: Search by Name.
    // ---------------------------------------------------------------------------------------
    public Employee searchByName(String employeeName)
    {
        Employee employee = map.get(employeeName);
        System.out.println(employee);
        return employee;
    }

Comment: What is the exact error you're getting?
Comment: Could you post the implementation of `searchByName` method? Moreover if this method finds the object why are you hardcoding values before editing?
Comment: I edited my code with the searchByName method.  The values where hardcoded because i was testing the individual methods to work with the edit.
Comment: it seems that the value set in `employeeEdit.setEmployeeName();` forces the map not to find the `Employee` object and insert a new one. Printout the contents of this value before setting it
Answer: have a look at this small demo :
HashMap<String, Employee> map = new HashMap<>();
map.put("Pendo826", new Employee("Pendo826", 1, "firstname.lastname@example.com"));

Employee e = map.get("Pendo826"); // get emp instance by name
e.setEmployeeName("Pendo"); // emp name of that instance edited
System.out.println(map.get("Pendo826").getEmployeeName()); // name is changed within map

so simply your case 5 :
System.out.println("Edit");
Employee employeeEdit = MenuMethods.userInputByName();
Employee e = Store.searchByName(employeeEdit.getEmployeeName());
if (e != null)
{
  e.setEmployeeName("Joe");
  e.setEmployeeId(1);
  e.setEmployeeEmail("webmail.com");
  // Store.edit(employeeEdit); // no need as you already have made changes to reference e
}
break;

after that if you view all you will have the changes
Comment: lol sorry i had no internet yesterday.  So i came into the library now.
Answer: Since the Store operates the employees by their name you should not change employee's name when you call edit.

If you call edit providing an employee with the name which is not stored yet - the new employee is inserted.
If you call edit providing an employee with name already stored - the emplyee with this name is being updated.

Edit method for EmployeeStore (HashMap)


Patrial Fraction definite integral with non-real part

Question: I have a question to find the area bounded by $y = \dfrac{x^2-4x-4}{x^2-4x-5}$ and the x-axis.  First I found the bounds by solving where the numerator would equal zero.  My result is $2\pm2\sqrt2$ so I wrote the integral as follows:
$$\int_{2-2\sqrt2}^{2+2\sqrt2}\dfrac{x^2-4x-4}{(x-5)(x+1)}$$
Then I used partial fractions to split the integral.  The final result I got prior to evaluation at the bounds to find the area is:
$$x + \dfrac{\ln(x-5)}{6}-\dfrac{\ln(x+1)}{6}\bigg|_{2-2\sqrt2}^{2+2\sqrt2}$$
My question is, when I go to plug in the bounds, I get a negative answer inside the first log ($\ln(2+2\sqrt2-5) = \ln(-0.171))$, so that part is not real.  I checked over my integral a couple times and I get the same result, although it's possible I'm missing something somewhere.  If the result above is correct, how do you deal with the non-real portion after evaluating the bounds?
Comment: Doesn't $\int \frac{1}{x}=\ln|x|$? (Note the absolute value signs)
Comment: Oh my gosh, I feel so dumb...yes, I guess I've been working on this for too long and I'm starting to make stupid mistakes...  Thanks!
Answer: As @JChau mentioned in his comment to my question, my mistake was forgetting to include the absolute value when taking the integral.  Silly mistake!  Thank you.
Answer: I am going to start at the partial fractions bit (this isn't necessarily for the OP because he already knows how to do it. Rather, it is for other people who may come across a similar problem).
$$\frac{x^2-4x-4}{x^2-4x-5}=1-\frac{1}{x^2-4x-5}$$
I will ignore the $1$ for now. Just remember that the $1$ is still there.
$$\frac{9}{(x-5)(x+1)}$$
$$=\frac{A}{x-5}+\frac{B}{x+1}$$
$$A(x+1)+B(x-5)=1$$
$$Ax+Bx+A-5B=1$$
Now we have a linear system of equations, where $A+B=0$ (this deals with the $x$ term) and $A-5B=1$ (this deals with the constant)
$$\begin{cases} A+B=0 \\ A-5B=1 \\ \end{cases}$$
We can solve by elimination.
$$\begin{array}{align} & A & + & B & = & 0 \\ - & (A & - & 5B) & = & 1 \\ \hline & & & 6B & = & -1 \\ & & & B & = & -\frac{1}{6} \end{array}$$
Plugging back into either equation:
$$A-\frac{1}{6}=0$$
$$A=\frac{1}{6}$$
$$\frac{9}{x^2-4x-5}=\frac{\frac{1}{6}}{x-5}+\frac{-\frac{1}{6}}{x+1}$$
$$=\frac{1}{6(x-5)}-\frac{1}{6(x+1)}$$
Don't forget that $1$! Now we solve for the indefinite integral
$$\int \frac{x^2-4x-4}{x^2-4x-5} \ dx$$
Using our partial fractions:
$$\int 1+\frac{1}{6(x-5)}-\frac{1}{6(x+1)} \ dx$$
$$=\int 1 \ dx + \int \frac{1}{6(x-5)} \ dx - \int \frac{1}{6(x+1)} \ dx$$
The integral of $1$ is $x$.
$$x+\int \frac{1}{6(x-5)} \ dx -\int \frac{1}{6(x+1} \ dx$$
Apply constant rule
$$x+\frac{1}{6} \int \frac{1}{x-5} \ dx -\frac{1}{6}\int \frac{1}{x+1} \ dx$$
Let's work on each integral one by one. Let's start with the first one.
$$\int \frac{1}{x-5} \ dx$$
Let:
$$u=x-5, \ du=dx$$
$$\int \frac{1}{u} \ du$$
$$=\ln|u|$$
$$=\ln|x-5|$$
The second integral can be solved in the same way. Let:
$$u=x+1, \ du=dx$$
$$\int \frac{1}{u} \ du$$
$$=\ln|u|$$
$$=\ln|x+1|$$
$$\int \frac{x^2-4x-4}{x^2-4x-5}=x+\frac{1}{6}\ln|x-5| -\frac{1}{6}\ln |x+1| + C$$
$$=x+\frac{\ln|x-5|}{6}-\frac{\ln|x+1|}{6}+C$$
Now we solve for the definite integral. We can ignore the $+C$ because it is only going to get canceled out.
$$\left.x+\frac{\ln|x-5|}{6}-\frac{\ln|x+1|}{6}\right|_{2-\sqrt{2}}^{2+\sqrt{2}}$$
$$=\left(2+\sqrt{2}+\frac{\ln\left|2+\sqrt{2}-5\right|}{6}-\frac{\ln\left|2+\sqrt{2}+1\right|}{6}\right)-\left(2-\sqrt{2}+\frac{\ln\left|2-\sqrt{2}-5\right|}{6}-\frac{\ln\left|2-\sqrt{2}+1\right|}{6}\right)$$
$$=2+\sqrt{2}+\frac{\ln\left|2+\sqrt{2}-5\right|}{6}-\frac{\ln\left|2+\sqrt{2}+1\right|}{6}-2+\sqrt{2}-\frac{\ln\left|2-\sqrt{2}-5\right|}{6}+\frac{\ln\left|2-\sqrt{2}+1\right|}{6}$$
$$=2\sqrt{2}+\frac{\ln\left|\sqrt{2}-3\right|-\ln\left|\sqrt{2}+3\right|}{6}+\frac{\ln\left|3-\sqrt{2}\right|-\ln\left|-\sqrt{2}-3\right|}{6}$$
$$=\frac{12\sqrt{2}+\ln\left|\sqrt{2}-3\right|-\ln\left|\sqrt{2}+3\right|+\ln\left|3-\sqrt{2}\right|-\ln\left|-\sqrt{2}-3\right|}{6}$$
We can simplify the $\left|-\sqrt{2}-3\right|$ in the numerator to $\sqrt{2}+3$. We can also get rid of the absolute value bars in $\left|\sqrt{2}+3\right|$.
$$\frac{12\sqrt{2}+\ln\left|\sqrt{2}-3\right|-\ln\left(\sqrt{2}+3\right)+\ln\left|3-\sqrt{2}\right|-\ln\left(\sqrt{2}+3\right)}{6}$$
$$=\frac{12\sqrt{2}+\ln\left|\sqrt{2}-3\right|-2\ln\left(\sqrt{2}+3\right)+\ln\left|3-\sqrt{2}\right|}{6}$$
$$\color{green}{\therefore \int_{2-\sqrt{2}}^{2+\sqrt{2}} \frac{x^2-4x-4}{x^2-4x+5} \ dx=\frac{12\sqrt{2}+\ln\left|\sqrt{2}-3\right|-2\ln\left(\sqrt{2}+3\right)+\ln\left|3-\sqrt{2}\right|}{6}}$$
If you want a decimal approximation, just plug in that whole entire string of $\ln$s and whatnot into your calculator, or just use an online definite integral calculator. I hope I helped you.