What is the max possible value of $2i-2^{\lceil{\log{i}}\rceil}$  when the base of log is 2?

Question: I have an expression of the form $2i-2^{\lceil{\log{i}}\rceil}$ . I want to know the maximum value of $2i-2^{\lceil{\log{i}}\rceil}$ .
Please consider the base of the logarithm as 2.
Comment: Of course, since $\log i$ can become arbitrary large, so can $2^{\lceil\log i\rceil}$. However, I guess you meant something different. Maybe you want the maximal value of $2^{\lceil\log i\rceil}/i$?
Comment: @celtschk I corrected yet . thanks for pointing out.
Comment: @Geek Originally you wanted a lower bound on $2i-2^{\lceil{\log{i}}\rceil}$.  Are you sure you don't want the minimum possible value now?
Answer: If $i$ is $2^k+1$, $\lceil \log i \rceil = k+1$, so $2^{\lceil \log i \rceil} =2^{ k+1}$ and $2i-2^{\lceil \log i \rceil}=2i-2(i+1)=2$.  If $i$ is further from a power of $2$, the expression will decline.
Comment: The definition of $\log$ gives you that $k = \log 2^k$ whether k is integral or real.  If you take $\log (2^k+1)$ for $k$ integral, it will be a little higher than $k$, so will round up to $k+1$
Comment: @RossMillikan You have an extra factor of $2$ in $2(2i-2)$.  The expression should always be positive since $\lceil \log i \rceil < \log i + 1$.
Comment: Can you explain why If $i$ is $2^k+1$, $\lceil \log i \rceil = k+1$
Comment: @ErickWong:  right.  fixed.  Thanks
Comment: @Geek:  Please see the correctiion
Comment: @RossMillikan When $i=2^k+1$ the value of the expression is the constant $2$.
Comment: @ErickWong:  I lost two factors of 2, not one.
Answer: Let $\log i=I+f\implies i=2^I.2^f$.
If $f\neq0$, then, $\lceil\log i\rceil=I+1\implies 2i-2^{\lceil\log i\rceil}=2^{I+1}2^f-2^{I+1}=2^{I+1}(2^f-1)$
Since $f\gt 0$ and $I$ can go arbitrarily large(depending on $i$), so this difference is unbounded.
If $f=0$, then, $\lceil\log i\rceil=I\implies 2i-2^{\lceil\log i\rceil}=2^{I+1}-2^{I}=2^{I}$ which is unbounded too (depending on $i$)
Answer: Let $u(x)=2x-2^{\lceil\log_2 x\rceil}$, then $x=2^n\sqrt2$ with $n$ integer yields $\lceil\log_2 x\rceil=n+1$ hence $u(x)=2^{n+1}(\sqrt2-1)\to+\infty$ when $n\to+\infty$.
To deal with $u(i)$ for $i$ integer, define $i_n$ as the unique integer such that $i_n\leqslant2^n\sqrt2\lt i_n+1$. Then $2i_n\gt2^{n+1}\sqrt2-2$ and $\lceil\log_2 i_n\rceil\leqslant n+1$ hence $u(i_n)\geqslant2^{n+1}(\sqrt2-1)-2$.
In particular, $u(i_n)\to+\infty$ when $n\to+\infty$, hence the family $\{u(i)\mid i\in\mathbb N\}$ is unbounded.
Likewise, for every real number $a\gt1$, the family $\{ai-a^{\lceil\log_ai\rceil}\mid i\in\mathbb N\}$ is unbounded.


How to have some element of a custom form rendered outside

Question: I have a form based on FormBase. All the form is wrapped by form.html.twig. I want to render $form['charts'] outside the <form>. I was able to do this, but {{ children }} still render all the form with the charts (charts it's duplicated).
Is their a better approach? I was wondering if I should use a normal controller and embed the form.
All this has to do with #theme_wrapper (that wrap the all content with the form template, but with everything already pre-render in #childrens). I must admit I don't really understand the #theme_wrapper logic.
<?php

namespace Drupal\mymodule\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a CDR Dashboard form.
 */
class SurveyQuestionsChartsForm extends FormBase {

  private AccountInterface $account;

  /**
   * @param \Drupal\Core\Session\AccountInterface $current_user
   */
  public function __construct(AccountInterface $account) {
    $this->account = $account;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    // Instantiates this form class.
    return new static(
      // Load services required to construct this class.
      $container->get('current_user')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'mymodule_myform';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $section = '') {

    $form['charts'] = $charts->build();
    $form['charts']['#weight'] = 50;

    $sections = $analysis->getSections();

    $form['section'] = [
      '#type' => 'select',
      '#title' => $this->t('Thématique'),
      '#options' => $sections,
      '#default_value' => $section,
    ];

    $form['actions'] = [
      '#type' => 'actions',
      '#weight' => 10,
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Afficher'),
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {

  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $section = $form_state->getValue('section');
    $form_state->setRedirect($this->getRequest()->get('_route'), [
      'section' => $section,
    ]);
  }

}

mymodule.module
function mymodule_preprocess_form(&$variables) {
  $variables['charts'] = $variables['element']['charts'];
}

form.html.twig
{{ charts }}

<form{{ attributes.addClass(classes) }}>
  {{ children }}
</form>

Comment: Does this answer your question? [Exclude fields from printing in Twig](https://drupal.stackexchange.com/questions/227133/exclude-fields-from-printing-in-twig)
Comment: For people curious about the history of keeping _form https://www.drupal.org/project/drupal/issues/2092647 (not that I think it was a good decision to have keep _form)
Answer: Yes, a clean solution would be a controller to render the chart. The problem with the <form> wrapper template, you are too late in the render pipeline. In a wrapper template the variable {{ children }} is already rendered. But still there should be some things you can try from within the form. You could hide the element so that it is not rendered inside the form and then unhide it to render it outside. Or use #prefix/#suffix:
$form['#prefix'] = $charts->build();

Comment: With #prefix/#suffix I have to render the array in the form controller has #prefix/#suffix only accept string, this feel like a hack.
Using a normal controller, how I access the $form_state in the controller to access the form value?
Comment: Did you try the other option? Hide the chart element by setting #printed = TRUE and later remove #printed to render it outside of the form tag.
Comment: I will try the #printed = TRUE options ASAP. This should works.


Changing MySQL data directory in Ubuntu Server 10.04

Question: I was getting the following error when trying to change the data directory in ubuntu server 10.04.
<code>100809 19:33:00 [Note] Plugin 'FEDERATED' is disabled.
/usr/sbin/mysqld: Can't find file: './mysql/plugin.frm' (errno: 13)
100809 19:33:00 [ERROR] Can't open the mysql.plugin table. Please run mysql_upgrade to create it.
100809 19:33:00  InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
InnoDB: File name ./ibdata1
InnoDB: File operation call: 'create'.
InnoDB: Cannot continue operation.
</code>
Comment: ...and your question is? Note that if you only move the contents of folders, and no files, you will lose all InnoDB table content.
Comment: If you want to ask and answer your own question that is fine, but take the time to actually ask a question and provide your answer as an answer.
Comment: there is no question/spoon. Just figured this might be interesting to people around here. Good point about the InnoDB table content!
Answer: After some general confusion about permissions the OP realized that the problem wasn't that he didn't have permissions and paths rights but that AppArmor was preventing MySQL from reading and writing to the new location.
This is his solution:
First stop MySQL so nothing weird happens while you're fiddling:
<code>$ sudo stop mysql
</code>
Then move all the database directories to their new home:
<code>$ sudo mv /var/lib/mysql/<all folders> /new-mysql-dir/
</code>
Don't move the files, they will be generated by mysql, just move the folders (which are the databases).
Then politely ask AppArmor to allow mysql to use the new folder:
<code>$ sudo vim /etc/apparmor.d/usr.sbin.mysqld
  >> add lines
     /new-mysql-dir/ r,
     /new-mysql-dir/** rwk,
</code>
Then tell mysql that the datadir has moved:
<code>$ sudo vim /etc/mysql/my.cnf
  >> change the line
     datadir=/var/lib/mysql
  >> to
     datadir=/my-new-db-dir/
</code>
NOTE: Depending on your database setup you might need to change innodb-data-home-dir etc. as well.
Then restart AppArmor to read the new settings:
<code>$ sudo /etc/init.d/apparmor restart
</code>
And start up MySQL again using the new datadir:
<code>$ sudo start mysql
</code>
Comment: you could keep the database up and running by linking the files to their new location, instead of moving them... unless of course the two datadir locations are on separate partitions.
Comment: The instruction to move only directories is not accurate in the case you're using innodb. In that case you'll have to move the innodb data and log files aswell (ibdata*, ib_logfile*).
Comment: A note for others as careless as me. You have to have the trailing slashes in the path in the AppArmor config `/new-mysql-dir/ r` or else it will still be denied. Basic Linux stuff but I can never get the trailing slashes correct.
Comment: I was still getting denied by AppArmor. [This thread](https://askubuntu.com/questions/916009/mysql-wont-start-because-of-apparmor) helped make it over that final hurdle.


CKEditor crashes when switching text format for specific content types

Question: drupal 7.38
wysiwyg 7.x-2.2+63-dev
CKEditor 4.5.1.a513a92
If I create an article, switch text formats, everything is fine.
If I create a basic page, switch text formats, the ckeditor toolbar crashes and none of the buttons are clickable.
The crash also occurs if I create a new content type.
Here is a copy of the console log:

Uncaught TypeError: Cannot read property 'sas' of undefined
  js_ALIKtebL-PsIulJhUegpZmaxTRnPdAyakIc8kMeoL-4.js:382 Uncaught
  TypeError: Cannot read property 'sas' of
  undefinedDrupal.wysiwyg.plugins.sas.attach @
  js_ALIKtebL-PsIulJhUegpZmaxTRnPdAyakIc8kMeoL-4.js:382(anonymous
  function) @
  js_ALIKtebL-PsIulJhUegpZmaxTRnPdAyakIc8kMeoL-4.js:103CKEDITOR.tools.createClass.proto.setData
  @ ckeditor.js?nstvdm:780(anonymous function) @ ckeditor.js?nstvdm:349j
  @ ckeditor.js?nstvdm:10CKEDITOR.event.CKEDITOR.event.fire @
  ckeditor.js?nstvdm:12CKEDITOR.editor.CKEDITOR.editor.fire @
  ckeditor.js?nstvdm:13CKEDITOR.tools.extend.setData @
  ckeditor.js?nstvdm:251b @ ckeditor.js?nstvdm:775(anonymous function) @
  ckeditor.js?nstvdm:777CKEDITOR.editor.setMode @
  ckeditor.js?nstvdm:328(anonymous function) @ ckeditor.js?nstvdm:323j @
  ckeditor.js?nstvdm:10CKEDITOR.event.CKEDITOR.event.fire @
  ckeditor.js?nstvdm:12CKEDITOR.editor.CKEDITOR.editor.fire @
  ckeditor.js?nstvdm:13CKEDITOR.event.CKEDITOR.event.fireOnce @
  ckeditor.js?nstvdm:12CKEDITOR.editor.CKEDITOR.editor.fireOnce @
  ckeditor.js?nstvdm:13(anonymous function) @
  ckeditor.js?nstvdm:246CKEDITOR.scriptLoader.load.g @
  ckeditor.js?nstvdm:226CKEDITOR.scriptLoader.load @
  ckeditor.js?nstvdm:226(anonymous function) @
  ckeditor.js?nstvdm:245(anonymous function) @
  ckeditor.js?nstvdm:233(anonymous function) @
  ckeditor.js?nstvdm:231CKEDITOR.scriptLoader.load.g @
  ckeditor.js?nstvdm:226CKEDITOR.scriptLoader.load.B @
  ckeditor.js?nstvdm:226CKEDITOR.scriptLoader.load.s @
  ckeditor.js?nstvdm:226(anonymous function) @ ckeditor.js?nstvdm:227
Comment: I'm voting to close this question as off-topic because it's a bug report for a contributed module. Please report all bugs to the module's issue queue
Answer: I would "downgrade" to the stable WYSIWYG 7.x-2.2 version of the WYSIWYG module, and to the 3.6.x version of CKEditor (such as CKEditor version 22.214.171.124.7696), since the WYSIWYG module does not support the 4.x version yet ...).
Another option is to switch to the CKeditor module (which is in core in D8 now ...), and no longer use the WYSIWYG module in combination with the CKEditor library.


Como alterar a cor apenas do elemento clicado?

Question: Essa pergunta é semelhante ao mudar cor so de elemento clicado a diferença é que é usado Jquery e eu preciso de JS puro, eu tenho alguns elementos  e quando eu clicar no elemento  atual ele mude de cor no caso vermelho quando eu clicar em outro elemento  (ou seja deixar de clicar no elemento  atual) o anterior (que era o atual) volte com a cor original (preta):

const summary = document.querySelectorAll('summary');

for (let i = 0; i  {
        summary[i].style.color = 'red';
    }
}

        Title 1

Content 1

Content 2

Content 3

        Title 2

Content 1

Content 2

Content 3

Os elementos  até muda de cor só que se clicar em todos ambos vão ter a cor e eu não sei como verificar o elemento  que foi clicado anteriormente para que ele mude para a cor original ou seja no caso para mim verificar os elementos que foram clicados foi fácil, mas e os que não foram?.
Answer: Podes fazer isso com classes. Adicionando e removendo com el.classList.add( e .remove(. Mas já que estás a fazer diretamente na propriedade do elemento o que te falta é, dentro de um loop, repor valores a cada click.
A idea é criar uma variável que se lembre do elemento que recebe o onclick e depois correr um for com todos os elementos dentro da callback do click. Dentro desse for verificas quando o sumary[j] é o mesmo que o el que foi clicado e dás-lhe a cor certa.
Exemplo:

const summary = document.querySelectorAll('summary');

for (let i = 0; i  {
    for (let j = 0; j < summary.length; j++) {
      const color = summary[j] === el ? 'red' : 'inherit';
      summary[j].style.color = color;
    }
  }
}

    Title 1

Content 1

Content 2

Content 3

    Title 2

Content 1

Content 2

Content 3

Comment: Perfeito amigo! era justamente isso, obrigado ajudou muito.
Comment: Só que está sendo comparado todos os elementos ou um em específico?
Comment: @felipecardozo a cada clique o código percorre todos os elementos e muda a cor de cada um. Dentro do loop ele verifica se o item iterado é o que foi clicado e a esse específico dá a cor `red`
Answer: Uma alternativa (com limitações, já veremos a seguir) é, sempre que clicar em um summary, procure se já existe um vermelho (e caso exista, mude a cor de volta para a original), e depois mude a cor do elemento clicado para vermelho:

document.querySelectorAll('summary')
    .forEach(s => s.addEventListener('click', function(event) {
        const vermelhoAtual = document.querySelector('summary[style="color: red;"]');
        if (vermelhoAtual) vermelhoAtual.style.color = 'inherit';
        s.style.color = 'red';
    })
);

        Title 1

Content 1

        Title 2

Content 2

        Title 3

Content 3

        Title 4

Content 4

Como a ideia é que somente um summary por vez pode ser vermelho, não precisaria fazer um loop por todos, como sugeriu a outra resposta (que é uma alternativa mais geral, caso tivesse a possibilidade de ter mais de um elemento vermelho, aí faria mais sentido percorrer todos e mudar a cor um a um - se bem que bastaria trocar querySelector por querySelectorAll no código acima, para buscar somente os elementos vermelhos).
Enfim, se é garantido que somente um elemento será vermelho por vez, basta buscar por ele, usando o seletor 'summary[style="color: red;"]', e mudar a cor caso ele exista.

Mas como já dito no início, esta solução é um pouco limitada.
A limitação é que isso só funciona se o elemento não tiver outros estilos inline. Por exemplo, se tiver style="font-weight: bold; color: red;, ou até mesmo se tiver style="color: red" (sem o ponto-e-vírgula), o seletor já não pega mais o elemento.
Daria até para contornar com document.querySelectorAll('summary[style*="color: red"]') (repare no *= em vez de apenas =, veja aqui alguns exemplos e a documentação para mais detalhes), mas aí talvez seja melhor usar classes e buscar pelos elementos que possuem aquela classe, por exemplo.
Uma outra alternativa é guardar o elemento vermelho, assim não precisamos buscá-lo toda hora (novamente, assumindo que não pode ter mais de um vermelho ao mesmo tempo):

var vermelhoAtual = undefined;

document.querySelectorAll('summary')
    .forEach(s => s.addEventListener('click', function(event) {
        if (s == vermelhoAtual) return; // cliquei no mesmo elemento, não precisa fazer nada
        if (vermelhoAtual) vermelhoAtual.style.color = 'inherit';
        s.style.color = 'red';
        vermelhoAtual = s;
    })
);

        Title 1

Content 1

        Title 2

Content 2

        Title 3

Content 3

        Title 4

Content 4

Comment: Boa, resposta! gostei da primeira possibilidade.


URL is being terminated on browser

Question: This is my link in that im sending query string but while clicking that url
&uid=a49ce59f-7606-4d22-a8b0-53d4696c1784

this part is not coming in url bar
original link
This is my code where im creating hyperlink
http://demo.check.in/Login.aspx?ipAddress=22.214.171.124&uid=a49ce59f-7606-4d22-a8b0-53d4696c1784

in url bar im getting this
http://demo.check.in/Login.aspx?ipAddress=188.8.131.52

why the half part is not going in url bar from & symbol

<a href="http://demo.check.in/Login.aspx?ipAddress=<%VisitorsIPAddr%>">http://demo.check.in/Login.aspx?ipAddress=<%VisitorsIPAddr%>&uid=<%guid%>

Comment: Show the code from where this is generated.
Comment: That is what we are asking. Show the code for "im sending full link to mail"
Comment: i just want to send ip address and one guid to url bar for confirmation. im sending full link to mail . but while clicking on that ljnk in the mail . only half part is not coming and saying "Conversion failed when converting from a character string to uniqueidentifier."@MairajAhmad
Comment: may be you're creating proper link as string, but not in the anchor tag's `href`
Answer: Your  tag is missing the "&uid=<%guid%>" portion.
Before

<a href="http://demo.check.in/Login.aspx?ipAddress=<%VisitorsIPAddr%>">http://demo.check.in/Login.aspx?ipAddress=<%VisitorsIPAddr%>&uid=<%guid%>

After

<a href="http://demo.check.in/Login.aspx?ipAddress=<%VisitorsIPAddr%>&uid=<%guid%>">http://demo.check.in/Login.aspx?ipAddress=<%VisitorsIPAddr%>&uid=<%guid%>

Comment: Thats what I commented earlier that he's creating only `innerHtml` not the `href`

URL is being terminated on browser


Magento 2 API shows wrong stockid

Question: I ran the Magento Rest API to get the stock id for a particular product but it's showing me wrong stock id.
We have three websites and each website has a separate stock, but when we call Magento API for these three websites, the stock is shown the same for every product which is wrong.
Please find below the result for the Magento RestAPI
<code>GET https://stage.secure.kindsnacks.co.uk/rest/kind_uk_en/V1/products/KIN30137 HTTP/1.1
</code>
<code>{

    "stock_item": {
      "item_id": 1822,
      "product_id": 193,
      "stock_id": 1,
      "qty": 15,
      "is_in_stock": true,
      "is_qty_decimal": false,
      "show_default_notification_message": false,
      "use_config_min_qty": true,
      "min_qty": 1,
      "use_config_min_sale_qty": 1,
      "min_sale_qty": 1,
      "use_config_max_sale_qty": true,
      "max_sale_qty": 10000,
      "use_config_backorders": true,
      "backorders": 0,
      "use_config_notify_stock_qty": true,
      "notify_stock_qty": 1,
      "use_config_qty_increments": true,
      "qty_increments": 0,
      "use_config_enable_qty_inc": true,
      "enable_qty_increments": false,
      "use_config_manage_stock": false,
      "manage_stock": true,
      "low_stock_date": null,
      "is_decimal_divided": false,
      "stock_status_changed_auto": 0
    }

}
</code>
Answer: You can get product stock status from here :
/V1/stockItems/:productSku

Magento 2 API shows wrong stockid


How can I log webdriver calls, proxy is not working

Question: I'm attempting to write a proxy for RemoteWebDriver to add custom logging for methods such as findElement etc. As an experiment I found a TimingHandler that just provides a start/stop time stamp for methods - it works fine outside of selenium. However, I can't get it to work with RemoteWebDriver.
Questions:
   Is there something about RemoteWebDriver which prevents the use of a proxy?
   Am I implementing this incorrectly?
   Is there a different/better way to do this?
public class TimingDynamicInvocationHandler implements InvocationHandler {

  private static final Logger logger = LogManager.getLogger(TimingDynamicInvocationHandler.class.getName());

  private final Map<String, Method> methods = new HashMap<>();

  private Object target;

  public TimingDynamicInvocationHandler(Object target) {
      this.target = target;

      for(Method method: target.getClass().getDeclaredMethods()) {
        System.out.println("TDIHandler method: " + method.getName());
          this.methods.put(method.getName(), method);
      }
  }

  @Override
  public Object invoke(Object proxy, Method method, Object[] args)
    throws Throwable {
      System.out.println("invoke method: " + method.getName());
      long start = System.nanoTime();
      Object result = methods.get(method.getName()).invoke(target, args);
      long elapsed = System.nanoTime() - start;

      logger.info("Executing {} finished in {} ns", method.getName(),
        elapsed);

      return result;
  }
}

I am using TestNG and I have a BaseTest class, all tests extend from this. I use a beforeMethod which creates the driver. Without the proxy I do the following and it works as expected:
 driver = new RemoteWebDriver(new URL(HUB_URL), caps);
 driver.get(APP_URL);
 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

However when I change to use the proxy it hangs:
    RemoteWebDriver rrDriver = new RemoteWebDriver(new URL(HUB_URL), caps);
    TimingDynamicInvocationHandler handler = new TimingDynamicInvocationHandler(rrDriver);
    Class<?> proxyClass = Proxy.getProxyClass(WebDriver.class.getClassLoader(), WebDriver.class);
    driver = (WebDriver) proxyClass.getConstructor(TimingDynamicInvocationHandler.class).newInstance(handler);

I get the following output:
12:06:06.941 [main] ERROR BaseTest 175 beforeMethod - java.lang.NoSuchMethodException: com.sun.proxy.$Proxy22.<init>(com.timr.utils.aop.TimingDynamicInvocationHandler)

Answer: It believe RemoteWebDriver is not a good candidate for dynamic proxy as it is already part of the CompoundHandler found in the selenium client org.openqa.selenium.remote.Augmenter.java, see : CompoundHandler implements InvocationHandler.
In its place I have opted for a simpler solution extending each of the Driver classes, RemoteWebDriver, ChromeDriver, FirefoxDriver.
public class ChromeLoggingDriver extends ChromeDriver {
  private static final Logger log = LogManager.getLogger(ChromeLoggingDriver.class.getName());

  public ChromeLoggingDriver(ChromeOptions options) {
    super(options);
  }

  @Override
  public void get(String url) {
    log.info("url: " + url);
    super.get(url);
  }

  @Override
  public String getCurrentUrl() {
    String url = super.getCurrentUrl();
    log.info(url);
    return url;
  }

  @Override
  public String getTitle() {
    String title = super.getTitle();
    log.info(title);
    return title;
  }

  @Override
  public List<WebElement> findElements(By by) {
    log.info(by.toString());
    return super.findElements(by);
  }

  @Override
  public WebElement findElement(By by) {
    log.info(by.toString());
    return super.findElement(by);
  }

  // ...

  @Override
  public void close() {
    log.info("");
    super.close();
  }

  @Override
  public void quit() {
    log.info("");
    super.quit();
  }
}

Comment: This is not the correct answer. As it turns out drivers such as FirefoxDriver, ChromeDriver extend from RemoteWebDriver which in turn implements WebDriver along with lots of other Interfaces: WebDriver, JavascriptExecutor,
 etc. Typical use is WebDriver driver = new FirefoxDriver(...), this works because at some point the driver is upcast back to a RemoteWebDriver. I found this out when trying to cast my WebDriverLogger to a JavaScriptExecutor - which fails. so I am still looking for a way to provide custom logging.
Comment: I modified the above code to create 3 separate logging drivers, they extend FirefoxDriver, ChromeDriver, RemoteDriver respectively. There is a lot of repeat code in this solution, if someone has a better idea please let me know.


Java system.getProperty("user.dir") gives wrong result in ubuntu

Question: I develop a Java application which is able to run cross-platform with condition in JRE version at least 18.104.22.168. Everything is work fine on a Windows machine (JRE184.108.40.206) but unwanted result in Ubuntu 8.04 with JRE220.127.116.11.
I found the errors here:
Document doc = docBuilder.parse (new File("webservices.xml"));

On the Windows machine, everything works ok, the docBuilder will refer the file at which my application located at.
Example: if my application located at C:\myApp\start.jar , it will refer webservives.xml at C:\myApp\webservices.xml (this mean it will always refer correct directory no matter where i move my application folder)
But in Ubuntu 8.04 it doesnt work.
I am able to figure out the problem by using this in application:
String curDir = System.getProperty("user.dir");
System.out.println(curDir);

No matter where I place my application folder, the curDir always return "/home/user". Document doc = docBuilder.parse (new File("webservices.xml")) doesn't work until I place the webservices.xml in directory /home/user/webservices.xml.
Running my application using Netbean 6.5.1 in Ubuntu return correct curDir but running my application standalone return wrong curDir (i am using JDK220.127.116.11 and JRE126.96.36.199 same as window machine)
Why Document doc = docBuilder.parse (new File("webservices.xml")) cant work properly in ubuntu JRE126.96.36.199?
Any idea to make my application work standalone in Ubuntu 8.04 just like in window machine?
Comment: Why isn't webservices.xml inside the jar file in the first place? Do you need to change it?
Answer: Do not rely on the current directory to read files that come with the application. Instead, use ClassLoader.getResource() (to access file relative to the classpath) or Class.getResouce() to access files inside packages.
Edit: The above is only good for readonly access. Files that will be modified should be stored in the user's home directory (System property user.home), not the application directory, because the latter causes many problems:

multiple users running the application at the same time might overwrite each other's changes
Users cannot backup or migrate their data easily
It is incompatible with a properly secure system of user privileges, where normal users do not have write access to application directories to prevent viruses from infecting applications.

For small amounts of data, you can use the Java preferences API.
Edit2:
For that particular requirement, this should work (needs the file to be in the classpath):
Document doc = docBuilder.parse (
    new File(getClass().getClassLoader().getResource("webservices.xml").toURI()););

Comment: I am confused using the ClassLoader.getResource(). i need to modify the contents of webservices.xml which store server ip from time to time, am i able to modify it inside packages?
Comment: My application folder concept is similar to portable browser folder, you can execute my application as long as you copy the entire application folder. Which mean no matter where you place the folder (even in portable drive), the program still can access the file webservices.xml, that's why i need access the file which same directory with the application. Everything work fine in window machine but not ubuntu 8.04...
Answer: System.getProperty("user.dir") returns the current directory the user is executing the program, rather than where the program is located.
Comment: I dint use System.getProperty("user.dir") in my application. I add that line just to debug my application due to these line cant work in ubuntu: Document doc = docBuilder.parse (new File("webservices.xml"));
Comment: @winston: that doesn't matter. If you provide a relative file name (such as "webservices.xml") then it will be searched in the current directory which is returned by that system property.
Answer: user.dir is the current working directory of your shell so you cd to it first Sun Java tutorial definition of user.dir
Answer: Try
Document doc = docBuilder.parse(new File("./webservices.xml"));


In how many ways can one yellow, two red and four green beads be placed on a bracelet if the beads are identical apart from colour?

Question: Struggling with this permutations question:
In how many ways can one yellow, two red and four green beads be placed on a bracelet if the beads are identical apart from colour?
Apparently you need to consider cases but I'm not quite sure how to go about doing that. Also, is there a way to do it without cases (i.e. a general formula)?
Comment: Relevant link https://math.stackexchange.com/questions/600/circular-permutations-with-indistinguishable-objects
Answer: Since there is a single yellow bead, we can use it as a reference point.  As we proceed clockwise around the bracelet from the yellow bead, we must choose which two of the remaining six positions will be filled with red beads. There are $$\binom{6}{2} = 15$$ ways to do this.
However, a bracelet can be removed from the wrist, twisted, and placed back on the wrist.  Consequently, clockwise and counterclockwise (anticlockwise) arrangements are equivalent.  Of these $15$ arrangements, the three in which both red beads are equidistant from the yellow bead are the same when the bracelet is reversed.  The other $12$ are not.  They can be placed in $6$ matching pairs, so there are $3 + 6 = 9$ distinguishable bracelets that can be formed.
Comment: Can a bracelet be turned over?  And if so, does this affect the answer? https://en.wikipedia.org/wiki/Necklace_(combinatorics)
Comment: @awkward A bracelet can be removed, twisted $180^\circ$, and placed back on the wrist.  Yes, that does affect my answer, which I have corrected.  Thank you.
Answer: The finished nonoriented bracelet is an adorned cyclic graph with $7$ vertices, up to isomorphy. The two red beads have distance $1$, $2$, or $3$ in this graph. For any choice of this distance, up to isomorphy there are three places left for the yellow bead, one of them in symmetric position with respect to the red beads. It follows that one can make $3\cdot3=9$ such bracelets out of the given beads.
Comment: What do you mean by distance when you say: "The two read beads have distance 1, 2, or 3, and may be placed at conjugate sites" (I assume you mean red).
Comment: @Isaac Greene: See my edit.


How is the Weighted Gini Criterion defined?

Question: I am interested in trying out and/or implementing the Weighted Random Forest (WRF) algorithm described in Chen, Liaw, Breiman. How is the Weighted Gini impurity actually defined? What implementations of the algorithm exist?
My best guess would be that the weighted Gini impurity is defined by
$$\sum_i w_i * f_i * (1-f_i)$$
where $i$ is the class index, $w_i$ is the class weight, and $f_i$ is the fraction of elements in the group of class $i$. And that splits at each node are chosen by minimizing the weighted average sum of these impurities.
Answer: The implementation available at Breiman's website  uses the weighted random forest method described in the paper. It's in Fortran 77 though, which may be off-putting to you. I also found the method that they use to calculate the impurity to be more unclear and complicated than needs be, but that's just my opinion (and probably an artifact of the method that they use to grow their trees).
For any potential split, the weight of all the observations in a potential child node, $c$, is
$$t_c = \sum_i w_i * n_i$$
where $n_i$ is the number of observations of class $i$ in $c$, and $w_i$ is the weight assigned to class $i$. The impurity of child node $c$ is then
$$i_c = 1 - \sum_i (w_i * n_i / t_c)^2$$
where $n_i$ is again the number of observations of class $i$ in the node, $w_i$ is the weight assigned to the class and $t_c$ is as calculated previously.
The impurity of the entire potential split is then
$$\sum_c(t_c / t_p) * i_c$$
where $t_c$ and $i_c$ are as calculated previously, and $t_p$ is the total weight of all observations in the parent node that is being split. Basically the fraction of the parent node's total weight that is in each child node $c$ multiplied by $c$'s impurity. You then choose the potential split that has the lowest impurity over all potential splits.
Comment: Shouldn't $i_c$ be $1 - \sum_i (w_i n_i / t_c)^2$? if you increase the weights too much the impurity goes to 1.
Comment: You're right. I seem to always make typos when converting code into mathematical expressions. I've fixed it now.
Answer: Just a follow-up on Simon's answer.
The Gini index (impurity index) for a node $c$ can be defined as:
$$ i_c = \sum_i f_i \cdot ( 1- f_i) = 1 - \sum_i f_i^2$$
where $f_i$ is the fraction of records which belong to class $i$.
If we have a two class problem we can plot the Gini index varying the relative number of records of the first class $f$. That is $f_1 = f$ and $f_2 = f - f_1$.

We have very high impurity when the class distribution is uniform.
If we assign a weight to each class we are actually rebalancing the impurity index - a high weight for one class (say $\bar{i}$) leads to a stronger decrease of impurity when the number of records for that class increases. We will not have the maximum impurity when the class distribution is uniform anymore. Just a small amount of records in $\bar{i}$ will be enough to decrease the node impurity.
We can still sketch a two class problem example. In Simon's formulas our $f_i$s are
$$f_i = \frac{w_i \cdot n_i}{\sum_i w_i \cdot n_i}$$
We can see that the formula does not change if $\sum_i n_i = 1$ and $\sum_i w_i = 1$ (it is enough to multiply numerator and denominator by the total number of records and total weight). Let $f$ be
$$f = \frac{w \cdot n}{w \cdot n + (1-w)(1-n)}$$
where $n$ is the relative number of records for the first class and $w$ their weight. Now we could compute the Gini when we vary the relative number of records for the first class $n$.

For example if we choose a weight of $0.9$ we have maximum impurity when $n \approx 0.1$. If $n$ increases the impurity steeply decreases as well.
If we define the weigthed Gini index as the OP did we would for example have a strange behaviour in a two class problem:
$$\sum_i w_i \cdot f_i \cdot (1 - f_i) = w \cdot f \cdot (1 - f) + (1 - w) \cdot (1-f) \cdot f = f \cdot ( 1- f)$$
However, I found a paper that uses that index here but I didn't read it, so I might be wrong.
Breiman's weighted index makes actually sense - we are trying to reweight the classes in a cost-sensitive way. The same approach is used in the MetaCost classifier implemented in WEKA.
In case anyone is interested, this is the R code I used to plot the figures:
<code>require(ggplot2)

# two class probability distribution
f <- seq(0,1,0.01)

# Standard Gini impurity
# f1 = f and f2 = 1 - f
Gini <- f*(1-f) + (1-f)*f
qplot(f,Gini, geom = "path")

# Weighted Gini impurity
w <- seq(0,1,0.1)
w_ <- as.vector( sapply(w, function(x) rep(x,length(f))))
n <- rep(f,length(w))

f <- w_*n / ( w_*n + (1-w_)*(1-n) )
WeightedGini <- f*(1-f) + (1-f)*f

Weight <- as.factor(w_)
qplot(n, WeightedGini, colour = Weight, geom = "path")
</code>


How to verify Kalman filter performance without true data

Question: I am implementing a Kalman filter for GPS/INS data, but I do not have data that can be considered "true" (i.e. a deterministic state).  The only data I have for the problem is the collection of measurements available to me, which are naturally corrupted.  I wish to test that my filter error is zero mean and passes the consistency, containment, and NEES tests from Bar-Shalom et al.  However, these tests require a deterministic truth, from which one computes the error based on the difference between estimated state and true state, leaving (ideally) a white process.
How can I test the efficacy of my filter without a deterministic truth?
Comment: Usually, if you need to test your model and need "true" state and noisy data that represents it, you simulate it by yourself by creating the true state data and adding noise to it. How you do it depends on what exactly are the properties of the model & simulation you want to achieve.
Comment: This may have been a dumb question...my apologies if so. https://en.wikipedia.org/wiki/Sum_of_normally_distributed_random_variables
Comment: @Tim thank you for the reply.  I totally thought about the filter the wrong way and this helped.  Thanks.
Answer: To my understanding you can use the Normalized Innovation Error Squared (NIS) Metric which is similar to NEES, but instead of using P it uses S which is the innovation covariance. And instead of using the ground truth, NIS uses the residuals (measured - predicted). These two sources helped me.
Weak in the NEES?: Auto-tuning Kalman Filters with Bayesian Optimization
Wikipedia for Kalman Filters
Comment: Much appreciated!  This will be an interesting paper for me to read this weekend.


Display Second Largest no in Array in Java

Question: Hi all I want to find out second Largest no in Array accept negative numbers. I have used following code and this display second largest no of only positive no.So please suggest me how to do this.
class ArrayExample {
    public static void main(String[] args) {
        int secondlargest = 0;
        int largest = 0;
        Scanner input = new Scanner(System.in);
        System.out.println("Enter array values: ");
        int arr[] = new int[5];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = input.nextInt();
            if (largest < arr[i]) {
                secondlargest = largest;
                largest = arr[i];
            }
            if (secondlargest < arr[i] && largest != arr[i])
                secondlargest = arr[i];
        }
        System.out.println("Second Largest number is: " + secondlargest);
    }
}

Comment: What about using a good sorting algorithm and taking the second element?
Comment: @Salman: In the general case, that's unnecessarily expensive (`O (n logn)` rather than `O(n)`). Of course, if the input is always of length five, the choice of algorithm is moot.
Comment: similar thread http://stackoverflow.com/questions/2615712/finding-the-second-highest-number-in-array
Comment: I'd assume that "no" is short for "number"
Answer: The problem comes from the fact that you initialize your two variables to 0 in the lines:
int secondlargest = 0;
int largest = 0;

You should instead initialize them to Integer.MIN_VALUE and then it will also work for negative values.
Answer: Initialize largest and secondLargest to Integer.MIN_VALUE instead of zero.
Answer: Initialize the variables secondlargest and largest with the smallest negative values.
Use this code:
class ArrayExample {
        public static void main(String[] args) {
            int secondlargest = Integer.MIN_VALUE;
            int largest = Integer.MIN_VALUE;
            Scanner input = new Scanner(System.in);
            System.out.println("Enter array values: ");
            int arr[] = new int[5];
            for (int i = 0; i < arr.length; i++) {
                arr[i] = input.nextInt();
                if (largest < arr[i]) {
                    secondlargest = largest;
                    largest = arr[i];
                }
                if (secondlargest < arr[i] && largest != arr[i])
                    secondlargest = arr[i];
            }
            System.out.println("Second Largest number is: " + secondlargest);
        }
    }

Comment: Thank you so much I got it now
Answer: This works for me, for both positive and negative values. Before the loop, you need to initialize the largest and secondlargest variables with very small values, by doing this you can be (almost) sure that all the other values in the array will be greater than them:
int largest = Integer.MIN_VALUE;
int secondlargest = Integer.MIN_VALUE;

Inside the loop:
if (arr[i] > largest) {
    secondlargest = largest;
    largest = arr[i];
}

else if (arr[i] != largest && arr[i] > secondlargest) {
    secondlargest = arr[i];
}

After the loop:
if (secondlargest != Integer.MIN_VALUE)
    System.out.println("Second Largest number is: " + secondlargest);

Notice that the last check is required for the (rather unlikely) case where all the elements in the array happen to be Integer.MIN_VALUE.
Answer: I think this method may be useful it takes around n+log(n)-2 comparisons
 import java.util.ArrayList;

 public class SecondLargest {
 static ArrayList<ArrayList<Integer>> level = new ArrayList<ArrayList<Integer>>();

public static void main(String[] args) {
    int input[]={9,8,7,4,5,6,1,2,3,1,1,21,33,32,1,2,3,12,3,2,1};
    ArrayList<Integer> arr= new ArrayList<Integer>();

    for(int i=0;i<input.length;i++){
        arr.add(input[i]);
    }
    level.add(arr);
    seconLarger(arr);
    System.out.println(SecondLarge(level));
}

private static ArrayList<Integer> seconLarger(ArrayList<Integer> arr) {
    ArrayList<Integer> tmp= new ArrayList<Integer>();
    if (arr.size()==1)
    {
        return arr;
    }

if(arr.size()%2==0)
    {
        for(int i=0;i<arr.size();i=i+2)
        {
            if(arr.get(i)>arr.get(i+1))
            {
                tmp.add(arr.get(i));
            }
            else
            {
                tmp.add(arr.get(i+1));
            }
        }

    }
else
    {
        for(int i=0;i<arr.size()-1;i=i+2)
        {
            if(arr.get(i)>arr.get(i+1))
            {
                tmp.add(arr.get(i));
            }
            else
            {
                tmp.add(arr.get(i+1));
            }
        }
        tmp.add(arr.get(arr.size()-1));
    }
level.add(tmp);
return seconLarger(tmp);
}

private static int SecondLarge(ArrayList<ArrayList<Integer>> li)
{
    int li_size=li.size();
    int large=li.get(li_size-1).get(0);
    int secondlarge=0;
    int tmp=0;
    for(int i=li_size-2;i>=0;i--)
    {
        ArrayList<Integer> arr = li.get(i);
        if(large==arr.get(tmp))
        {
            if(tmp+1<arr.size())
            {
                if(secondlarge<arr.get(tmp+1))
                {
                    secondlarge=arr.get(tmp+1);
                }
            }
        }
        else
        {
            if(secondlarge<arr.get(tmp))
            {
                secondlarge=arr.get(tmp);
            }
            tmp=tmp+1;

        }

        tmp=tmp*2;
    }
    return secondlarge;
}}

Answer: package com.demo.mum;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author cyruses
 *
 */
public class SecondLargest {
    public static int largest = Integer.MIN_VALUE;
    public static int secondLargest = Integer.MIN_VALUE;

    public static void main(String args[]) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the Size of Array:");
        int n = Integer.parseInt(br.readLine());
        int a[] = new int[n];
        System.out.println("Enter the elements on array:");
        for (int i = 0; i < a.length; i++) {
            a[i] = Integer.parseInt(br.readLine());
        }
        System.out.println("Elements you entered are:");
        for (int i = 0; i < a.length; i++) {
            System.out.println("a[" + i + "]" + "=" + a[i]);
        }
        if (a.length <= 2) {
            if (a[0] == a[1]) {
                System.out.println("Theres no second largest number in your array");
            } else {
                System.out.println("SecondLargest:" + secondLargest(a));
            }
        } else {
            System.out.println("SecondLargest:" + secondLargest(a));
        }
    }

    private static int secondLargest(int[] a) {

        for (int i = 0; i  largest) {
                    secondLargest = largest;
                    largest = a[i];
                } else if (a[i] > secondLargest) {
                    secondLargest = a[i];
                }
            }
        return secondLargest;
    }
}

Answer: Or here is a gimmicky Java implementation which doesn't rely on Integer.MIN_VALUE
int findSecondHighest(int[] arr){
    if(arr == null || arr.length < 2){
        throw new IllegalArgumentException();
    }

    int fh,sh;

    if(arr[0]>=arr[1]){
        fh = arr[0];
        sh = arr[1];
    }else{
        fh = arr[1];
        sh = arr[0];
    }

    for (int i = 2; i < arr.length; i++) {
        if(fh < arr[i]){
            sh = fh;
            fh = arr[i];
        }else if(sh < arr[i]){
            sh = arr[i];
        }
    }

    return sh;
}

Answer: Instead of initializing the second largest number to min value or zero. You can follow below code to get second largest number.
import java.util.Scanner;

public class SecondLargestNumber {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int[] a;
        int n;
        System.out.println("Enter number of elements");
        n = scanner.nextInt();
        a = new int[n];
        for(int i=0; i<n; i++) {
            a[i] = scanner.nextInt();
        }
        int secondLargestNumber = a[0];
        int largestNumber = a[0];
        int count = 1;
        for(int i=1; i= largestNumber) {
                if(a[i] == largestNumber) {
                    count++;
                } else {
                    count = 1;
                }
                secondLargestNumber = largestNumber;
                largestNumber = a[i];
            } else {
                if(secondLargestNumber == largestNumber && count == 1) {
                    secondLargestNumber = a[i];
                } else if(a[i] > secondLargestNumber) {
                    secondLargestNumber = a[i];
                }
            }
        }
        System.out.println("Second Largest Number: " + secondLargestNumber);
    }
}

Answer: public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    System.out.println("Enter array size = ");
    int size=in.nextInt();
    int[] n = new int[size];
    System.out.println("Enter "+ size +" values ");

    for(int i=0;i<n.length;i++)
        n[i] = in.nextInt();
    int big=n[0],sbig=n[0];

    // finding big, second big
    for(int i=0;i<n.length;i++){
        if(big<n[i]){
            sbig=big;
            big=n[i];
            }else if(sbig<n[i])
                sbig=n[i];
    }
    // finding second big if first element itself big
    if(big==n[0]){
        sbig=n[1];
        for(int i=1;i<n.length;i++){
            if(sbig<n[i]){
                sbig=n[i];
                }
        }
    }

    System.out.println("Big "+ big+" sBig "+ sbig);

    in.close();
}


How to rotate axis labels when using a matplotlib histogram?

Question: I have a plot that looks like this, and I am trying to make the x axis labels more readable:

This is what I tried and the error I got:
Answer: The problem is that you are setting plt from the call to hist(), which is not what you want. It is common to import matplotlib as plt, assuming that is what was intended here:
import matplotlib.pyplot as plt

data = [1, 2, 3, 4]

p = plt.hist(data)
plt.xticks(rotation='vertical')

plt.show()


What is the best way to automatically switch between node versions?

Question: When you work with two projects and one project depends on node v 8 and another one project depends on node v 10 you have to somehow switch between them.

Not convenient way:
This is not convenient because i have to always remember to type nvm use when i've just entered into root of project dir or when i've just opened new terminal session.
So when you are working on some project you can go in to root dir and run nvm use and it'll pick up node version from your .nvmrc and you can work on this project in this terminal session.
The same thing with another project - nvm use and work in this terminal session.
Convenient but not reliable way:
This is not way reliable because not all of devs have nvm exactly here $HOME/.nvm/nvm.sh and i don't like this hardcoding of nvm path because it's looks like some dirty hack.
Follow answers in this thread and get some working way. This means that just for my personal local developing it will work(i've tried this thread and it's not working because of this error and i don't know what it means)

$  source $HOME/.nvm/nvm.sh && nvm use && nodemon ts-node -r
  tsconfig-paths/register src/main.ts nvm is not compatible with the
  "PREFIX" environment variable: currently set to "/usr/local" Run
  unset PREFIX to unset it.

Engines in package.json way

I've tried write "engines": {"node" : "10.14.1"}, in to my package.json but when i've started yarn - node haven't changed to 10.14.1(it's already installed on my laptop)
I don't know any more ways to conveniently and reliably change my node version just running yarn start. Do you know some way? Or may be you know some best practices?
Answer: After some time i've reinstalled my OS and i've tried to use ZSH terminal. There is zsh-nvm plugin which check .nvmrc every time you do cd. Convenient. So good so far.


UWP Storyboard not executing animation correctly

Question: I have a small button that should adjust vertically and horizontally. I Would like to use Storyboard and manipulate the X and Y under transform.
And I would like to do it code-behind.
The button moves to the correct position, but no animation is active.
private void AnimatePlayerMovement(Player player)
{
    //This will hold hour animation
    Piece.RenderTransform = new CompositeTransform();

    //New storyboard
    Storyboard storyboard = new Storyboard();

    //New DoubleAnimation - Y
    DoubleAnimation translateYAnimation = new DoubleAnimation();
    translateYAnimation.From = this.Path[player.from, 1];
    translateYAnimation.To = this.Path[player.to, 1];

    translateYAnimation.EasingFunction = new ExponentialEase();
    translateYAnimation.EasingFunction.EasingMode = EasingMode.EaseOut;

    translateYAnimation.Duration = new Duration(TimeSpan.FromMilliseconds(500));

    Storyboard.SetTarget(translateYAnimation, Piece);
    Storyboard.SetTargetProperty(translateYAnimation,
           "(UIElement.RenderTransform).(CompositeTransform.TranslateY)");

    storyboard.Children.Add(translateYAnimation);

    //New DoubleAnimation - X
    DoubleAnimation translateXAnimation = new DoubleAnimation();
    translateXAnimation.From = this.Path[player.from, 0];
    translateXAnimation.To = this.Path[player.to, 0];
    translateXAnimation.Duration = new Duration(TimeSpan.FromMilliseconds(500));

    Storyboard.SetTarget(translateXAnimation, Piece);
    Storyboard.SetTargetProperty(translateXAnimation,
          "(UIElement.RenderTransform).(CompositeTransform.TranslateX)");

    storyboard.Children.Add(translateXAnimation);

    storyboard.Begin();

}

And the button in xaml
<Button x:Name="Piece" Height="50" Width="50" HorizontalAlignment="Left"
        Margin="115,400,0,0" VerticalAlignment="Top" Click="Button_Click"
        RenderTransformOrigin="0.5,0.5">
    <Button.Template>
        <ControlTemplate>
            <Image Source="Assets/piece.png"/>
        </ControlTemplate>
    </Button.Template>
</Button>

Comment: I have tried out your code exactly (except for replacing image with a simple `Rectangle`) and the animation does work. You can find my example repo on Github - https://github.com/MartinZikmund/so-55271281
Comment: Are you sure the `this.Path[player.from, 0]` and `this.Path[player.to, 0]` values are different?
Answer: I have tested your code and the animation works properly. You can find the working repo on GitHub. As the code is almost 1:1 copy of your sample, except I hardcoded the From and To property values of the animations. Thus I think the problem you are seeing is that this.Path[player.from, 0] and this.Path[player.to, 0] values are the same (or very similar). This way the button jumps to the this.Path[player.from, 0] location and stays there, not moving further.


Propositional Logic - Formal Proofs using natural deduction

Question: I have a question I have come across in an old exam paper which I am trying to work through.
It states that a formal proof must be given using the rules of natural deduction

Now generally what I do is I work backwards to see how I could derive the conclusion then I start working forward.
Two problems I am having:
1) For C → D ∨ E this does not look well formed to me as it is lacking parentheses so it seems ambiguous to me. I have chosen to rewrite this as follows (C → D) ∨ E.
2) Working backward initially I use conditional introduction in my sub-proof before my conclusion.
See below:

I have chosen to reiterate B line 7 as I want to be able to derive by elsewhere in my proof.
I am not sure how to proceed next. I thought of perhaps using contradiction elimination by finally deriving a contradiction and ultimately asserting C → D.
Some advice on how to proceed would be greatly appreciated.
Thanks
Answer: The usual convention for the omission of parentheses is that :
1) the negation symbol applies to as little as possible
2) $\land$ and $\lor$ apply to as little as possible, given the above convention.
Thus, $C \to D \lor E$ must be :

$C \to (D \lor E)$.
Comment: @ Mauro ALLEGRANZA Thanks for the input let me try this.
Answer: As @Mauro ALLEGRANZA points out, the convention is that $\vee$ and $\wedge$ bind more tightly than $\to$, so the formula is $C \to (D \vee E)$. Here's a sketch of how the deduction proceeds:

$\neg A \to B$
$C \to D \vee E$
$D \to \neg C$
$A \to \neg E$
$C \to \neg D \quad$ from 3.
$C \to E \quad$ from 2. and 5.
$E \to \neg A \quad$ from 4.
$C \to \neg A \quad$ from 6. and 7.
$C \to B \quad$ from 8. and 1.
Comment: @Metastasis - you have to follow BrianO's answer, using ND rules. 1) assume $C$ and by $\to$-elim derive $D \lor E$. Here $\lor$-elim is needed : 1a) assume $D$, derive $\lnot C$ and from the contradiction, by $\bot \vdash \varphi$ conclude with $B$ and then $C \to B$. 1b) assume $E$, assume $A$, derive $\lnot E$ and, fron the contradiction, derive $\lnot A$ by $\lnot$-intro. Thus derive $B$ by $\to$-elim and then $C \to B$. Now, both 1a) and 1b) have $C \to B$: thus, conclude $C \to B$ by $\lor$-elim.
Comment: True -- I did say "sketch". Not to be coy, though, in all but one case (line 6.) I'm using $\vdash (p \to q) \wedge (q \to r) \to (p \to r)$. Line 6. is really a sub-deduction: assume $C$; then $D \vee E$ by 2., and $\neg D$ by 5., soo.. $E$; so discharging the assumption proves $C \to E$.
Comment: @Metastasis - if you are using Natural Deduction, "usually" there are no rules like HS or Transitivity (as primitive rules) ... And yes, you have to use $\lor$-elimination (i.e.proof by cases).
Comment: Thanks for your input here. Is this a proof by cases? Also, when citing the lines, you haven't referred to the rule of inference you have used?
Comment: Thanks true, you did say sketch... Rule is Hypothetical Syllogism yes? Where it has the same feel as transitivity. I need to try cite this in the program I'm using. Will post an update once I get it right.
Comment: "same form as transitivity" -- exactly. Because it is: $p \to q$ is true $\iff$ truth_value($p$) $\le$ truth_value($q$). And also true (just checked) that "Hypothetical Syllogism" is the appropriate name.
Comment: What I said a few comments up isn't the entire story. The lines that are "from" only one earlier line (lines 5. and 7.) both infer the contrapositive. That's to say, they use ⊢(p→q)→(¬q→¬p) -- plus ⊢p→¬¬p and then Hypothetical Syllogism.
Comment: @MauroALLEGRANZA True, that. I intend the terms to be thought of, in a natural deduction context, as something like *macros*: each expands into a sub-deduction.
Comment: @MauroALLEGRANZA Thanks for this. I understand the use of V elim and that if I had say a→c and b→c and say a V b I could use this to ultimately deduce c. I am somehow still battling to get my head around how to break this proof into cases. I am new to formal proofs and logic so I am not going to select an answer as yet. I will keep trying and post feedback once I have worked this out.


What is the equivalence relation on the Set $A=\{1,2,3,4,5\}$

Question: I have a set $A=\{1,2,3,4,5\}$, where its partition set is $E=\{\{1,5\}, \{2,3,4\}\}$
I am not sure what kind of equivalence relation gives a rise to above partition.
Comment: Do you know the relation between a partition of a set and an equivalence relation on the set?
Answer: Whenever you have a partition $P$ on a set $S$, you can define the binary relation $\sim$ by $x\sim y$ if and only if $x$ and $y$ belong to the same element of $P$. Then:

$\sim$ is an equivalence relation;
the partition that $\sim$ induces is $P$.
Answer: $x \sim y $ if $x\in \{1,5\} \wedge y\in \{1,5\}$ and $x \sim y $ if $x\in \{2,3,4\} \wedge y\in \{2,3,4\}$ will work. It doesn't have to be a nice natural relation.
Answer: Simply define $x\sim y$ iff $x$ and $y$ lie in the same element of the partition.
Comment: I am not required to refer to the name of partiton
Answer: The equivalence relation on A, is given, explicitly, by $$R = \{(1, 1), (5, 5), (1,5), (5, 1), (2, 2), (2, 3),(2, 4), (3, 2), (3, 3), (3, 4),  (4, 2), (4, 3), (4, 4),\}.$$  You'll see that the sets comprising the equivalence classes ($E$) of the partition are indeed $\;\{1, 5\}, \;\;\{2, 3, 4\}$
The ordered pairs $(a, b) \in R$ indicate $a\,R\,b$, that is "$a$ is related to $b$ under $R$"  Here we have that the elements in each equivalence class are mutually related in $R$, but no element from $\{1, 5\}$ is related to any element in $\{2, 3, 4\}$, and vice versa.
The relation $R$ on $A$ is given by

reflexive: for every element $a \in A,\; (a, a) \in R$,
symmetric: For every element $a, b$ in $A,\;$ if $(a, b) \in R$ then $(b,a) \in R$
transitive: For every element $a, b, c \in A,\;$ if $(a, b)\in R$ and $(b, c)\in R,$ then $\;(a, c) \in R$.

It might be a good idea for you to confirm the properties above, just to be assured that the relation is indeed an equivalence relation.


Testing and conidence interval in a clinical trial

Question: In a clinical trial, let's say I want to test
$$H_0: \mu_1 \leq \mu_2$$
$$H_1: \mu_1 > \mu_2$$
$\mu_1$ belongs to the placebo group and $\mu_2$ belongs to the trt group. I used an independent two-sample t-test to compare the two means. I wonder how to express the confidence interval here. And should the point estimate by $\bar{X}_1-\bar{X}_2$? I'm not familiar with statistics and clinical trials so I need some help.
Comment: If you define $d=\mu_1-\mu_2$ then the null hypothesis becomes $d \le 0$ and the alternative $d>0$, with $\bar X_1-\bar X_2$ being the natural estimator of $d$. You are trying to find a confidence interval for $d$.
Comment: Notice that you ask about a _one-sided_ 2-sample t test, but about a _two_sided_ confidence interval. See my Answer. Also, you do not say whether you are suing the pooled 2-sample t test or the Welch 2-sample t test. Unless you have solid advance evidence that the two populations have the same variance, you should use the Welch test.
Answer: If you use statistical software to test the hypothesis $H_0: \mu_1 \le \mu_2$ against $H_a: \mu_1 > m_2$ you will typically get a 95% confidence interval
for $\mu_1 - \mu_2$ as part of the output.
Suppose you have data similar to the fictitious data, simulated using R
statistical software below:
set.seed(2022)
x1 = rnorm(1000, 50, 7)
x2 = rnorm(1000, 55, 8)

summary(x1)
  Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  25.67   45.28   49.65   50.01   54.79   76.36
length(x1);  sd(x1)
[1] 1000              # sample size
[1] 6.987677          # sample standard deviation

summary(x2)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  25.86   49.61   54.99   54.97   60.66   79.58
length(x2);  sd(x2)
[1] 1000
[1] 8.190649

boxplot(x1, x2, horizontal=T, col="skyblue2")

Then a Welch two-sample t test, which does not assume that treatment
and control populations have the same variance, goes as shown below.
Because the P-value is near $0,$ we reject $H_0$ in favor of the
one-sided alternative $H_0.$ The 95% one-sided 95% confidence
interval is $(-\infty, -4.40)$ so that $\mu_1 - \mu_2,$ estimated
by $\bar X_1 - \bar X_2 = 50.00961 - 54.97116 =  -4.96155$ is likely
less than the upper bound $-4.40128 \approx -4.40.$
        Welch Two Sample t-test

data:  x1 and x2
t = -14.573, df = 1949.6, p-value < 2.2e-16
alternative hypothesis: true difference in means is less than 0
95 percent confidence interval:
 -Inf -4.40128
sample estimates:
mean of x mean of y
 50.00961  54.97116

If you want a 2-sided 95% CI, then you can get it as part of the
output for a 2-tailed (or 2-sided) test, specifically
$(-5.63, -4.29),$ which is centered at $\bar X_1 - \bar X_2 = 50.00961 - 54.97116 =  -4.96155 \approx -4.96.$
t.test(x1,x2)$conf.int
[1] -5.629265 -4.293849
attr(,"conf.level")
[1] 0.95

Output from Minitab statistical software for summarized data above, is shown below, where 0.000 means $< 0.0005:$
Two-Sample T-Test and CI

Sample     N   Mean  StDev  SE Mean
1       1000  50.01   6.99     0.22
2       1000  54.97   8.19     0.26

Difference = μ (1) - μ (2)
Estimate for difference:  -4.960
95% upper bound for difference:  -4.400
T-Test of difference = 0 (vs <):
 T-Value = -14.57  P-Value = 0.000  DF = 1949

Again here, the two-sided 95% CI $(-5.628, -4.292)$ accompanies the two-sided test.
Two-Sample T-Test and CI

Sample     N   Mean  StDev  SE Mean
1       1000  50.01   6.99     0.22
2       1000  54.97   8.19     0.26

Difference = μ (1) - μ (2)
Estimate for difference:  -4.960
95% CI for difference:  (-5.628, -4.292)
T-Test of difference = 0 (vs ≠): T-Value = -14.57  P-Value = 0.000  DF = 1949

Both programs use the following formula for the 2-sided 95% confidence
interval of $\mu_1-\mu_2:$
$$\bar X_1 - \bar X_2 \pm t^*\sqrt{\frac{S_1^2}{n_1}+\frac{S_2^2}{n_2}},$$
where $n_i, \bar X_i, S^2_i$ are the sample size, mean, and variance, respectively, of the $i$th sample, and $t^*$ cuts probability $0.025$
from the upper tail of Student's t distribution with the appropriate
degrees of freedom. In my example $t^*=1.96.$
Comment: Is one-sided test CI is different from the formula you provided?
Comment: Thank you for your detailed answer! It is a one-sided test so I was pretty confused.
Comment: Yes, a one-sided CI is usually used along with a one-sided test. The formula for the one-sided interval is different: No $\pm,$ just $+$ to get an upper bound, in this problem (and $t^*$ cuts 5% of the area from the upper tail of the standard normal density curve.
Comment: I guess my case is a one-sided test then. There is not much information about a one-sided CI in a clinical trial so I was very confused. Thank you.


Notepad++ Regex Find Semicolon Second Last From Newline

Question: I am trying to figure out how to do a find and replace on Notepad++ using regex, what I have is a bunch of lines with the following format
1 ; 2 ; 3 ; 4 ; AA ; AA BB
5 ; 6 ; 7 ; 8 ; AA ; BB CC
2 ; 4 ; 6 ; 0 ; AA ; DD EE

What I'd like to do is add a semicolon in between every instance of the last section like this:
1 ; 2 ; 3 ; 4 ; AA ; AA ; BB
5 ; 6 ; 7 ; 8 ; AA ; BB ; CC
2 ; 4 ; 6 ; 0 ; AA ; DD ; EE

Any ideas?
Thanks!
Answer: Find what: ([A-Z]+)\s+([A-Z]+)$
Replace with: $1 ; $2

Answer: Search for: (\w+)\s+(\w+)$
Replace with: \1 ; \2

Answer: Try this regex in find:
 (\S+)$

(read as 'space', then the characters (\S+)$)
And this replace:
 ; $1

(read as 'space', semicolon, 'space' and 'dollar 1')
Make sure that you checked "Regular expression" and that ". matches newline" is unchecked!
\S matches non-spaces (non-newlines, non-carriage returns non-formfeeds) and the brackets stores the match in a variable $1 in this case.
$ matches the end of the line.
In the replace, we're putting space, semicolon, space then the stuff we earlier stored in $1.
Answer: So this is the regex to match last two characters with a space:
(\s\w\w)$

Remember to add multiline flag to your regex.
Replace matched elements with ; $1. $1 stays for first capturing group.
Demo: regexr.com


MongoDB query with lt and gt operators

Question: Please can anybody help with this MongoDB query?
I wrote this query:
db.getCollection('epg').find({
'programs.start':{'$lte': new ISODate('2015-07-30 19:10:00.000Z')},
'programs.end':{'$gte': new ISODate('2015-07-30 19:10:00.000Z')}},
{'programs.$':1, 'name':1, 'id':1, 'broadcastDay':1})

MongoDB returns me this document:
{
    "_id" : ObjectId("55ba36cb68057b06d80f766a"),
    "id" : "2",
    "broadcastDay" : "2015-07-30",
    "name" : "Prima COOL",
    "programs" : [
        {
            "serialNumber" : "11/340/00039/0024",
            "start" : ISODate("2015-07-30T19:25:00.000Z"),
            "end" : ISODate("2015-07-30T19:44:00.000Z")
        }
    ]
}

Start and end in returned document don't match the query. Does anybody know, why MongoDB returns this document? I expect, that result will be empty (there is no matching document in my collection "epg").
Comment: Is that really the only entry of the `programs` array? When there are more entries, you will have to use `$elemMatch` or each criteria will be tested separately against a match in any entry.
Comment: I don't know how you got this document back. But the result should be empty and is empty when I tested it.
Comment: possible duplicate of [Retrieve only the queried element in an object array in MongoDB collection](http://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection)
Answer: Your query will match any document where some item in the programs array matches the start condition, and some element matches the end condition. As per @Philipp's comment above, you should use $elemMatch to do the query if you want to match documents where some item in programs matches both conditions.
You are using the positional $ operator to return only the first element of the array that matches the query. The element returned matches the end condition but if you pull back the whole document by ID, you'll see there are more entries in programs and one of those other entries matches the start condition.

MongoDB query with lt and gt operators


Definition of derivative with integrals

Question: Can we say that $$\int_0^t u_t(x,t,s) \, ds = \lim_{h \to 0} \frac{\int_0^{t+h} u(x,t+h,s)-u(x,t,s) \, ds}{h}$$
Answer: Your statement is true if both $u(x,t,s)$ and $u_t(x,t,s)$ are continuous for $t$ and $s$. That is if both $u(x,t,s)$ and $u_t(x,t,s)$ are continuous then $$g(t)=\int_{0}^{t}u(x,t,s)~ds$$ is differentiable and $$g'(t)=\int_{0}^{t}u_t(x,t,s)~ds.$$
So, $$\int_{0}^{t}u_t(x,t,s)~ds=\lim \limits_{h\to 0}\dfrac{\int_{0}^{t}u(x,t+h,s)~ds -\int_{0}^{t}u(x,t,s)~ds}{h}\\=\lim \limits_{h\to 0}\dfrac{\int_{0}^{t}\left( u(x,t+h,s)~ds -u(x,t,s)\right) ~ds}{h}.$$

Definition of derivative with integrals


Como fazer um "insert" com Dapper usando uma classe?

Question: Estou testando o Dapper e quando tento usar uma classe encontrei o erro:

Must declare the scalar variable

Segue o código:
public class Teste
{
    public int id;
    public string nome;
    public int idade;
}

        using (IDbConnection db = new SqlConnection(conexao))
        {
            Teste t = new Teste();
            t.nome = "Iago";
            t.idade = 20;

            var newTeste = db.Execute("Insert Into Teste (nome, idade) Values(@nome, @idade)", t);

            var teste = db.Query("Select * From Teste");
        }

Tabela:
Create Table Teste (

 id int identity(1,1),
 nome varchar(50),
 idade int
)

Answer: Precisa ter propriedades na classe, então mude sua classe para:
public class Teste {
    public int Id { get; set; }
    public string Nome { get; set; }
    public int Idade { get; set; }
}

E mude:
var newTeste = db.Execute("Insert Into Teste (nome, idade) Values(@Nome, @Idade)", t);

Coloquei no GitHub para referência futura.
Eu mudaria os nomes das colunas da tabela também.
Comment: Maniero, muito obrigado não tinha reparado a falta do get/set na classe. Funcionou muito bem.
Answer: Tente usar o DynamicParameter

public class Teste
{
    public int id;
    public string nome;
    public int idade;
}

//Necessário referenciar o Dapper na sua classe que faz o insert...
using Dapper;

//No seu método para salvar no banco de dados...
var parametros = new DynamicParameters();
parametros.Add("Nome", teste.nome, DbType.AnsiString);
parametros.Add("Idade", teste.idade , DbType.Int32);

db.Execute("Insert into Teste (nome, idade) Values(@Nome, @Idade)", parametros);

Comment: Esse modo acho melhor quando tem vários parâmetros. Melhora na visualização.
Answer: Eu utilizo via procedure.
public class Teste
{
    public int id;
    public string nome;
    public int idade;
}

using (IDbConnection Connection = GetConnection())
{
    try
    {
        Connection.Execute("nome_da_sua_procedure",
            new {
                id = classeTeste.Data,
                nome = logChamadaoEntity.Entrada,
                idade = logChamadaoEntity.Saida
            },
            commandType: CommandType.StoredProcedure);
    }
    catch (System.Exception)
    {

        throw;
    }
    finally
    {
        Connection.Close();
    }
}


Como acessar e alterar objetos dentro de um arquivo XML pela activity?

Question: boa noite, estou com dificuldade para alterar os componentes de um arquivo XML, quando eu abro o menu Drawer eu clico no botao "acompanhamento" ele abre o xml fragment_acompanhamento.xml, porém nao consigo acessar os componentes deste XML,
Segue codigo do meu fragment_acompanhamento
 `

<Button
    android:id="@+id/buttonteste"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/textViewteste" />

<TextView
    android:id="@+id/textViewteste"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="32dp"
    android:text="TextView"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

`
Segue abaixo o codigo da activity criado através do Navigation Drawer Activity
private AppBarConfiguration mAppBarConfiguration;
private FirebaseAuth autenticacao;
public TextView textoemail, textViewNome, textViewTeste;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_menu);

    autenticacao = ConfiguracaoFirebase.getFirebaseAutenticacao();

    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    FloatingActionButton fab = findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
    DrawerLayout drawer = findViewById(R.id.drawer_layout);
    NavigationView navigationView = findViewById(R.id.nav_view);
    // Passing each menu ID as a set of Ids because each
    // menu should be considered as top level destinations.
    mAppBarConfiguration = new AppBarConfiguration.Builder(
            R.id.nav_visita, R.id.nav_acompanhamento
    )
            .setDrawerLayout(drawer)
            .build();
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
    NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
    NavigationUI.setupWithNavController(navigationView, navController);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu, menu);
    return true;
}

@Override
public boolean onSupportNavigateUp() {
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
    return NavigationUI.navigateUp(navController, mAppBarConfiguration)
            || super.onSupportNavigateUp();
}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()){
        case R.id.action_sair:
            deslogarUsuario();
            finish();
            break;
    }
    return super.onOptionsItemSelected(item);
}
public void deslogarUsuario(){
    try {
        autenticacao.signOut();
    }catch (Exception e){
        e.printStackTrace();
    }
}

}
e agora o codigo do AcompanhamentoFragment.java
private Button btnteste;
private TextView txtteste;

public AcompanhamentoFragment() {
    // Required empty public constructor

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_acompanhamento, container, false);

}

oque eu preciso é modificar os componetes da tela fragment_acompanhamento.xml como por exemplo um textView, mas nao sei como inflar essa tela no arquivo AcompanhamentoFragment.java, pois não consigo acessar esses objetos, e se eu tento acessar esses elementos pelo MenuActivity.java ele acusa erro de NullPoint.
Comment: Se eu entendi qual é esse trecho de código, faltou você retornar o xml inflado `return acompanhamento;`
Comment: Mas eu preciso criar método para inflar um objeto? ou apenas instanciando o objeto View eu já consigo modificar os componentes da minha tela?
Comment: Ah, agora que vi que isso é uma `Activity`... Pra exibir o layout numa  `Activity` é melhor criar um [`Fragment`](https://developer.android.com/guide/components/fragments), que vai ter toda a lógica dessa "tela" e a interface (layout) também
Comment: Sim sim eu vi, o problema é que não consigo usar o findViewbyId, ele não permite quando é usado um fragmento, sem isso não consigo acessar os componentes do layout da minha tela. pois a activity faz extends de appCompatActivity, e um fragmento faz extends de fragment
Comment: No `Fragment` você precisa usar `findViewById` em alguma view. Em geral, seria na `view` que o `Fragment` está inflando: `view.findViewById`
Comment: eu editei a minha publicação, dentro do fragmento_acompanhamento.xml tenho um button e um textView igual na imagem anterior, como eu vou acessar eles pelo meu arquivo acompanhamentoFragmento.java?
Comment: Poste código ao invés de imagem, por favor. Fica mais fácil de eu (ou outra pessoa) responder
Comment: agora postei o código, resumindo, eu criei um menu do tipo Navigation Dreawer activity, e criei dois fragmentos que corresponde a dois itens do menu, visita e acompanhamento, no momento que eu clico em acompanhamento ele abre a tela fragment_acompanhamento.xml, até ai beleza, mas eu preciso acessar os compontentes dessa tela e alterar o texto de um textView com um clique, mas como eu acesso os componentes dessa tela? é por qual arquivo? o MenuActivity.java ou pelo Acompanhamento.java? e como eu faço isso? eu vejo varios exemplos de como inflar um xml mas nao funciona
Answer: Por qual arquivo acessar os elementos?
Para acessar os componentes de um layout.xml, você deve acessar por quem inflou o .xml, que no seu caso está sendo o AcompanhamentoFragment.java.
Como acessar os elementos?
Para acessar um elemento partir de uma Activity é só usar o findViewById (o elemento será procurado no Layout que você usou setContentView), como você já faz na sua Activity:
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_menu);

    // Procurar pelo elemento no layout R.layout.activity_menu
    Toolbar toolbar = findViewById(R.id.toolbar);
}

No Fragment é bem similar, você precisa indicar em qual View você está querendo procurar por esse elemento. Segue exemplo:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_acompanhamento, container, false);

    // Procurar pelo elemento no "view", que é o R.layout.fragment_acompanhamento
    Button meuBotao = view.findViewById(R.id.buttonteste);
    TextView meuTextView = view.findViewById(R.id.textViewteste);

    return view;
}

A partir desse momento você já consegue realizar as alterações na interface que deseja, colocar um listener no botão etc.
Comment: Show, muito obrigado, agora deu certo!


iPhone - UIImage mask and CopyImageAndAddAlphaChannel function

Question: I am trying to create a jigsaw puzzle and I need to mask the UIImages to obtain the puzzle pieces.
I don't understand how can I mask a JPG picture because as I understand it doesn't have an alpha channel. Can anyone help me with this?
The JPGs are on an online server and there is no way to download them as PNG.
And one more thing, I can't find this function anywhere on the Apple documentation:
"CopyImageAndAddAlphaChannel". Does it even exist. I found a few references on some forums but nothing strait forward.
Thanks a lot,
Andrei
Answer: Found the answer. Here is the function, it works for JPG and PNG without alpha channel (I have tested it :)):
<code>CGImageRef imageRef = self.CGImage;
size_t width = CGImageGetWidth(imageRef);
size_t height = CGImageGetHeight(imageRef);

CGContextRef offscreenContext = CGBitmapContextCreate(NULL,
                                                      width,
                                                      height,
                                                      8,
                                                      0,
                                                      CGImageGetColorSpace(imageRef),
                                                      kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst);

CGContextDrawImage(offscreenContext, CGRectMake(0, 0, width, height), imageRef);
CGImageRef imageRefWithAlpha = CGBitmapContextCreateImage(offscreenContext);
UIImage *imageWithAlpha = [UIImage imageWithCGImage:imageRefWithAlpha];

CGContextRelease(offscreenContext);
CGImageRelease(imageRefWithAlpha);

return imageWithAlpha;
</code>
Comment: Thanks for sharing the code, but does this just add a blank alpha channel? Looking for something that will take separate image and an alpha and combine them. Maybe I need to look at CGImageMaskCreate?


Building a Visual Basic script that uses a batch file

Question: I've written a batch file script that takes an image sequence from a certain folder, converts it to quicktime using ffmpeg and then it moves the file to a certain folder.
I used variables at the beginning of the batch script for user input on which folder to take the files from.
And now for my question: The batch I've written works just fine but I want to make it into a simple visual basic script so it looks nice and clean instead of a command prompt interface.
Can anyone provide me with tips for the VB code?
How do I pass variables from VB to the batch file?
Any help on this would be much appriciated.
Comment: To clarify, you want a Visual Basic GUI program to take the users input and then feed that input into your batch script. correct?
Comment: Yes. That's exactly what I want.
Answer: Use a HTML Application to program the GUI to gather the info needed from the user. Use WScript.Shell's .Run or .Exec method to start an external process (either the .bat or ffmpeg directly) and pass those info via the command line.


Multi-site sharing content

Question: Is it possible to share content/nodes in a drupal multisite environment.
For example:
Content type "Story"

Site 1- Use this content
Site 2- Don't use this content
Site 3- Use this content

It seems the drupal multisite environment suggests using table prefixes for different sites.
Answer: I think this is what the domain access module is for.
Comment: Yes, that is exactly what Domain Access is for, but it isn't a true multisite environment.  It is for multiple sites running from a single database sharing some content.  It works very well, though, but can be a little bit of a pain to retroactively fit to a site.
Comment: This is perfect for what I need
Comment: And what if i would have not one database. It seems to me domain module would not help. Am i right?
Answer: You could also use the deploy module to push content to specified sites
Comment: I haven't used in a while. If I recall correctly it required a bit to set up, had some challenges when using login redirect modules, like login toboggan. But it worked as expected once it was setup. I cannot comment on the state of the d& version, but I do see there are over 600 sites currently using it, so it must be working. Sorry, I cannot provide you with more info.
Comment: How well does this work?

Multi-site sharing content


Build a covariance matrix for GAM

Question: I am using a GAM in R to compare time series data from 3 countries. The data sets are of hourly measurements for one year. The main aim here is to show when at which time of the day and day of the year are the data well matched to the mean series. The script below shows my attempt:
## Ozone measurements for three countries in Europe
## Find similarities between time series
require(plyr)
require(lattice)
require(mgcv)

TopFolder <- list("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat"
,"http://www.nilu.no/projects/ccc/onlinedata/ozone/CY02_2009.dat"
,"http://www.nilu.no/projects/ccc/onlinedata/ozone/BE35_2009.dat"
)

## create variable for the data
data = ldply(TopFolder, header = TRUE, read.table, sep = "", skip = 3)

## define Ozone levels
Ozone <- data$Value
Ozone[Ozone==-999] <- NA
Ozone <- data.frame(Ozone)

## define Datetime -  need to concatenate arrays
DateTime <- paste(data$Date,data$Hour, sep = " ")
Date <- as.POSIXct(DateTime, format = "%d.%m.%Y %H:%M")

## define countries
Countries <- c("Czech","Cyprus","Belgium")
Country <- data.frame(Country = rep(Countries, each = 8760))

## bind together
Dat <- cbind(Ozone, Country = Country)
Dat <- transform(Dat, Doy = as.numeric(format(Date,format = "%j")),
                     Tod = as.numeric(format(Date,format = "%H")),
               DecTime = rep(seq(1,365, length = 8760),by = 3))

## plot the Ozone data
xyplot(Ozone~DecTime | Country, data = Dat, type  = "l", col = 1,
       strip = function(bg = 'white',...)strip.default(bg = 'white',...))

## generalised additive model
mod1 <- gam(Ozone ~ Country + s(Doy,bs = "cc", k = 20) + s(Doy, by = Country, bs = "cc", k = 20) +
  s(Tod,bs = "cc", k=7) + s(Tod,by = Country,bs = "cr", k=7),
             data = Dat, method = "ML")

plot(mod1,pages=1,scale=0,shade=TRUE)

xyplot(resid(mod1) ~ Doy | Country, data = Dat, type = c("l","smooth"))

mod2 <- gamm(Ozone ~ Country + s(Doy,bs = "cc", k = 20) + s(Doy, by = Country, bs = "cc", k = 20) +
  s(Tod,bs = "cc", k=7) + s(Tod,by = Country,bs = "cr", k=7),
             data = Dat, method = "ML",correlation = corAR1(form = ~ DecTime | Country))

One problem of this is that I am using an additive model with correlated errors i.e. in each time series of hourly measurements, a high concentration is followed by another high concentration. This can be addressed by adding a correlation matrix into the GAM:
However, R throws out an error as it is unable to get any more RAM from the OS. So, to tackle this I need to:
(1) from mod1 - fit a time series model (mod3) to the residuals
(2) obtain the acf(1) from mod3
(2) use the acf(1) to build a covariance matrix that we can then pass into mod2 thus simplifying the correlation matrix.
Any advice on how to to complete some or all of the three steps above would be highly appreciated. Although I think the first point that I an unsure of is how to extract the residuals for the different countries in mod1?
Comment: I would like to run mod2 in order to see how much RAM is actually needed. But if I define `DecTime=(as.numeric(Date)-min(as.numeric(Date)))/3600` there is a `Covariate must have unique values within groups for corAR1 objects` error. Also, are you familiar with `residuals` and its method `residuals.gam`?
Comment: When trying to run mod2 R says 'Error: cannot allocate vector of size 530.2 Mb'. I am fairly familiar with residuals, e.g. I can plot the residuals for each country with 'xyplot(resid(mod1) ~ Doy | Country, data = Dat, type = c("l","smooth"))' but I don't know how I would go about fitting a model to the residuals of each country
Comment: note from the plot of the residuals, there still appears to be some patterns present, hence the need for fitting the correlation matrix in gamm
Comment: I know that you don't have enough memory, but maybe the 16 GB in total on my machine would suffice. But you didn't include how you defined DecTime in your code and my attempt to define it myself gave me an error that there are sometime more than one value per date/hour/country. You can subset the residuals to fit models per country, but I don't know if that would help you ultimately.
Comment: DecTime is now added to the data.frame.
Comment: It looks like I would be able to fit the model (11.5 GB RAM were used up to now), but it takes a long time and I have to leave, so I have to abort. My  advise is to invest in more RAM and a 64bit OS or get access to a server, where you could run such models. If a less memory intensive method exists in R, it would most likely be even slower. The estimates of the other model parameters are not independent from the correlation matrix and vice versa, so imho your idea won't give the best fit. I believe that SAS needs less memory for this.
Answer: Coincidentally I have been pondering this problem for a little while and resorted to emailing Simon Wood about this only the other day.
His advice to me was (amongst other things but I don't think using bam()'s rho argument is applicable when you have by terms in the model) to check the example at the end of ?magic. That example I reproduce below with outputs:
## Now a correlated data example ...
library(nlme)
## simulate truth
set.seed(1)
n <- 400
sig <- 2
x <- 0:(n-1)/(n-1)
f <- 0.2 * x^11 * (10 * (1-x))^6 + 10 * (10*x)^3 * (1-x)^10
## produce scaled covariance matrix for AR1 errors...
V <- corMatrix(Initialize(corAR1(.6),data.frame(x=x)))
## note here that V is what you would estimate from the model residuals
## but here we are generating the data from known correlation.
## You would plug your estimate of the correlation parameter in to corAR1(X)
##
## for the Cholesky factorisation of V
Cv <- chol(V)  # t(Cv)%*%Cv=V
## Simulate AR1 errors ...
e <- t(Cv) %*% rnorm(n, 0, sig) # so cov(e) = V * sig^2
## Observe truth + AR1 errors
y <- f + e

## GAM ignoring correlation
b <- gam(y ~ s(x, k = 20))

## Fit smooth, taking account of *known* correlation...
## form a weight matrix
w <- solve(t(Cv)) # V^{-1} = w'w
## Use `gam' to set up model for fitting...
G <- gam(y ~ s(x, k = 20), fit=FALSE)
## fit using magic, with weight *matrix*
mgfit <- magic(G$y, G$X, G$sp, G$S, G$off, rank=G$rank, C=G$C, w=w)
## Modify previous gam object using new fit, for plotting...
mg.stuff <- magic.post.proc(G$X, mgfit, w)
b2 <- b ## copy b
b2$edf <- mg.stuff$edf
b2$Vp <- mg.stuff$Vb
b2$coefficients <- mgfit$b

## compare fits
layout(matrix(1:2, ncol = 2))
plot(b, main = "Ignoring correlation")
lines(x, f-mean(f), col=2)
plot(b2, main = "Known correlation")
lines(x, f-mean(f), col=2)
layout(1)

The resulting plot of the two fits looks like this:

You have the additional problem that your $V$ will not be a simple matrix like the one here. As you are fitting by Country your $V$ will be a block diagonal (I think that is the right term) matrix formed by first generating each $V_{country}$ and then stacking them in a diagonal fashion such that observations within a single Country are correlated with one another (so their entries in the matrix are none-zero, being $\rho^{|s|}$ where $\rho$ is the estiated AR(1) parameter for that Country and s is the separation in time points of the two residuals) but are uncorrelated with the observations from other countries (those entries in $V$ are zero). At least that is what the gamm() code you show would produce IIRC.
Although I haven't tried this, there are several options to form block diagonal matrices in R and you could use the function posted to R-Help some years ago to stick your individual $V_{country}$ together. Other options include converting each $V$ into a sparse matrix that the Matrix package understands, use its bdiag() function and then coerce back to a dense matrix using as.matrix(). See the help for the Matrix package for details.
As for obtaining the AR(1) terms for each countries residuals, fit your model via gam() but to help, place all the data in time order within country first before fitting. If you have any NA in the data, make sure to add na.action = na.exclude in the call to gam() as that will place NA back into the resdiuals that you extract via resid() from the model. You can split the vector of residuals by country like this:
res <- resid(mod)
res.spl <- split(res, Dat$Country)

Then you could simply sapply() the function acf() or pacf() to each component of res.spl to extract the lag 1 coefficient for each country. Those are the values to plug into corAR1() in the above example code.
Amazingly, your example code looks very similar to some that of my PhD student (although they are working on lakes) sent me the other day. Do you know someone working on hi-res lake data? If not perhaps they saw your post here?
Comment: many thanks for you very detailed answer. I used a similar script some time ago when I was investigating air temperature variations for a number of countries in Europe and I posted that script on http://r.789695.n4.nabble.com/ so there may be a link there. I cant say that I know of any lake scientsts, although some researches in this department are looking at NAO related
processes in aquatic systems?

Build a covariance matrix for GAM


Add custom cart field to woocommerce

Question: This may be a noob question, but I've googled a lot and haven't found the answer. I've already replaced the woocommerce cart to my child theme subfolder.
I'm trying to add a field to the woocommerce cart, so it will just display the cart subtotal multiplied by a number defined by me. I.e., the cart subtotal is 3,000.00, I want to define the multiplier number 3, so the field I want to show must display 9.000,00.
I've already added the field header to the cart:

        <?php _e( 'Quantity', 'thefoxwp' ); ?>
        <?php _e( 'Total', 'thefoxwp' ); ?>
        <?php _e( 'Total to be Received', 'thefoxwp' ); ?>

The field I want to configure is the class="product-result".
It's not a input field, it will just show the subtotal multiplied by a number defined by me.
I need this information to be sent with the woocommerce email to the client and saved in my order details.
Does anybody know how to do it?
Thanks
Comment: https://wordpress.org/plugins/wc-fields-factory/, although it takes caer of adding fields on product, cart, checkout, order and email too. but you will be needing some customization on your cart page template.
Comment: I downloaded it, but it just allow to add fields to the product page. I can create a hidden field that will show on the cart and checkout page, but how can I make the result of this field be the multiplication of the subtotal and the numbe I decide?
Answer: Could figure it out.
I added two classes to the header

        <?php _e( 'Quantity', 'thefoxwp' ); ?>
        <?php _e( 'Total', 'thefoxwp' ); ?>
        <?php _e( 'Exchange Tax', 'thefoxwp' ); ?>
        <?php _e( 'Total to be Received', 'thefoxwp' ); ?>

And then added this code

       <?php
       $tax = 4.05;
       echo "R$ $tax";
       ?>

        <?php
        $resultado = WC()->cart->subtotal;
        $mostrar = $resultado * $tax;
        echo "R$ "; echo number_format("$mostrar",2);
        ?>

So it's now echo the result of the cart subtotal * the exchange tax.
But now, how can I get this variable to echo on the email sent by woocommerce and on the checkout page?

Add custom cart field to woocommerce


How to detect if VideoView is playing video or Buffering?

Question: How to detect if VideoView is playing video or Buffering?
I want to display a pop-up saying video is buffering.
In android API level 17 there is a call back setOnInfoListener that can provide me this information but i am using API level 15 (android ICS).
I have also seen this question "Detect if a VideoVIew is buffering" but the suggested solution is for MediaPlayer and not for VideoView.
SO how can I detect if VideoView is buffering? is it a good solution to run a thread to check the current seek/progress level and depending on that decide if video is playing or buffering.
UPDATE
It is not like i just need to check if video is playing or buffering at the start of the video only, i want to check it through out video paying.
Answer: To check if VideoView is playing is not you can use its isPlaying() method,
if ( videoView.isPlaying() )
{
     // Video is playing
}
else
{
     // Video is either stopped or buffering
}

To check if VideoView is completed use following,
videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
    @Override
    public void onCompletion(MediaPlayer mp)
    {
             // Video Playing is completed
    }
});

Comment: We need to add `videoView.isPlaying()` to a timer to keep checking if video is buffering or we need to set the `setOnBufferingUpdateListener` to check if it is in buffering mode.
Answer: I came with the following hack in order to not implement a custom VideoView. The idea is to check every 1 second if the current position is the same as 1 second before. If it is, the video is buffering. If not, the video is really playing.
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
    public void run() {
        int duration = videoView.getCurrentPosition();
        if (old_duration == duration && videoView.isPlaying()) {
            videoMessage.setVisibility(View.VISIBLE);
        } else {
            videoMessage.setVisibility(View.GONE);
        }
        old_duration = duration;

        handler.postDelayed(runnable, 1000);
    }
};
handler.postDelayed(runnable, 0);

Answer:            videoView.setOnPreparedListener(new OnPreparedListener()
           {

               public void onPrepared(MediaPlayer mp)
               {
                   progressDialog.dismiss();     // or hide any popup or what ever
                   videoView.start();           // start the video
               }
           });


Rodar uma aplicação sem eclipse mas utilizando o tomcat. Como faço?

Question: Eu sou acostumada a rodar o projeto na ide eclipse mas agora eu criei uma página html no notepad++ e preciso colocar essa página para rodar com o servidor web tomcat não estou conseguindo fazer.
Eu estava dando dois cliques na minha página html mas a url fica errada, ela precisa ser localhost:8080/ e não sei como fica depois daqui. Como deve ficar a url o que eu devo fazer para rodar a minha aplicação com o tomcat sem ide?
Preciso rodar esse html com o servidor porque essa página tem conteúdo dinâmico, tem linguagem java incorporada.
Eu sou muito leiga deixo isso aqui ciente.
Comment: Você tem um projeto java que quer colocar pra rodar ou apenas um arquivo html a parte?
Comment: tenho projeto java
Comment: Consegui resolver : P
Comment: Você poderia compartilhar como resolveu o problema, assim outros poderiam se beneficiar da solução.
Answer: Suponho que você utilizava algum plugin do eclipse para executar o tomcat. Usei por vezes o plugin Mongrel, mas há algum tempo ele deixou de dar suporte às versões mais recentes do tomcat. Deixo abaixo como instalar, configurar e executar o tomcat pelo prompt de comando do windows.
Pré-Requisitos: Tenha o JDK instalado. (irei supor que o jdk está instalado no diretório C:\Program Files\Java\jdk1.8.0_45)
Passo 1: Faça o download (da versão desejada) do tomcat no site oficial http://tomcat.apache.org/, preferencialmente o .zip do tópico "Binary Distributions" e extraia no diretório desejado (Irei supor que extraiu no diretório C:\ e renomeou a pasta para tomcat). Sendo assim, o tomcat está instalado em C:\tomcat.
Passo 2: Crie as variáveis de ambiente necessárias para que o prompt de comando do windows reconheça o tomcat e o jdk nos seguintes passos:

2.1: Abra o "Painel de Controle" > Busque e abra a opção "Sistema" > Na lateral esquerda da janela clique na opção "Configurações Avançadas do Sistema" > Na aba "Avançado" da nova janela clique na opção "Variáveis de Ambiente".
2.2: Na janela que abriu, na área "Variáveis de Sistema" clique em "Novo".
2.3: Na nova janela que abriu terá o campo "Nome da Variável" e "Valor da Variável". No primeiro coloque CATALINA_HOME e no segundo campo coloque o caminho da pasta onde extraiu o tomcat (neste nosso exemplo foi C:\tomcat). Finalize clicando em OK.
2.4: Execute novamente os passo 2.2 e 2.3. Executando novamente o passo 2.3, insira desta vez no primeira campo o valor JAVA_HOME e no segundo campo coloque o caminho do seu jdk (neste exemplo está em C:\Program Files\Java\jdk1.8.0_45). Finalize clicando em OK.
2.5: Busque nessa mesma janela na área "Variáveis de Ambiente" a variável Path, selecione-a e clique em Editar.
2.6: Na nova janela que abriu e no campo "Valor da Variável" vá para o final do texto que já tem lá e adicione um ponto-e-vírgula (;) após todo o texto.
2.7: Adicione o seguinte texto após o ponto-e-vírgula que você colocou: %JAVA_HOME%\bin;%CATALINA_HOME%\bin
2.8: Finalize clicando em OK em todas as janelas abertas neste passo 2.
2.9: Abra um NOVO prompt de comando e execute o comando "java" (sem as aspas) e depois o comando "catalina" (sem as aspas). Se você não recebeu a mensagem "...is not recognized as an internal or external command, operable program or batch file." significa que você adicionou as variáveis de ambiente corretamente.

Passo 3: Adicione suas aplicações na pasta webapps.
Passo 4: No prompt de comando digite "catalina run" (sem as aspas) para iniciar o servidor tomcat. Se a configuração foi feita corretamente o servidor estará acessível em localhost:8080. E para acessar uma página que esteja na pasta webapps/teste, por exemplo teste.html, acesse localhost:8080/teste/teste.html