Programmatically add values in a select field: issues when submitting

Question: I'm inserting some options in the #options element of the select render array:
foreach ($files['files'] as $file) {
    $form['field_session_row']['widget'][0]['subform'][$field_name]['widget']['#options'][$file['ll_id']] = $file['ll_name'];
}

This ends in an error under the select:
The value you selected is not a valid choice.

I've also tried to set the #validated element to TRUE and unsetting the #element_validate in order to bypass the form element validation.
However, when I submit the form I get the following error:
TypeError: Drupal\Core\Field\WidgetBase::massageFormValues(): Argument #1 ($values) must be of type array, string given, called in /var/www/vhosts/newEcmwf/web/core/lib/Drupal/Core/Field/WidgetBase.php on line 400 in Drupal\Core\Field\WidgetBase->massageFormValues() (line 547 of core/lib/Drupal/Core/Field/WidgetBase.php).

Dumping $values it turns out $values when the error is triggered is _none.
How can I fix it?
Thanks
Code:
Code (optimized and changed compared to the other thread):
/**
 * Implements hook_form_alter().
 *
 * @throws \Drupal\Core\Entity\EntityStorageException
 *
 * @noinspection PhpUnusedParameterInspection
 * @noinspection PhpUnused
 * @noinspection UnusedFunctionResultInspection
 */
function livelink_form_alter(array &$form, FormStateInterface $form_state, $form_id): void {
    if ($form_id === 'node_committee_session_form' || $form_id === 'node_committee_session_edit_form') {
        foreach ($form as $field_id => $field) {
            if (preg_match('/^field_livelink_field_document_..$/', $field_id)) {
                $id = Arr::get($form, "$field_id.widget.0.value.#default_value");
                Arr::set($form, "$field_id.widget.0.list-button", [
                  '#type' => 'button',
                  '#name' => "button_$field_id",
                  '#value' => !empty($id) ? t('Refresh') : t('List'),
                  '#attributes' => ['onclick' => 'return (false);'],
                  '#ajax' => [
                    'callback' => 'livelink_get_files_callback',
                    'wrapper' => "$field_id-folder-info",
                    'effect' => 'fade',
                    'related_field' => $field_id,
                    'select_field' => str_replace('field_livelink_', '', $field_id) . '_select'
                  ],
                ]);
                Arr::set($form, "$field_id.widget.0.folder-info-div", [
                  '#markup' => !empty($id) ? livelink_render_files_from_cache($id) : '',
                  '#prefix' => "
",
                  '#suffix' => '
',
                ]);
            }
        }

        $session_rows = Arr::where(Arr::get($form, 'field_session_row.widget'), fn ($item, $key) => is_int($key) && is_array($item));
        foreach ($session_rows as $index => $session_row) {
            $subform = &$form['field_session_row']['widget'][$index]['subform'];

            $fields = collect($subform)
              ->filter(fn($value, $field_name) => preg_match('/^field_document_.._select$/', $field_name));
            foreach ($fields as $field_name => $value) {
                $select = &$subform[$field_name]['widget'];
                $select['#prefix'] = "
";
                $select['#suffix'] = '
';
                // Get files
                $field = str_replace('_select', '', $field_name);

                // Load files options
                $folder_id = Arr::get($form, "field_livelink_$field.widget.0.value.#default_value");
                if ($folder_id) {
                    $files = livelink_load_files_cache($folder_id);
                    foreach (array_column($files, 'll_name', 'll_id') as $id => $name) {
                        $select['#options'][(string) $id] = $name;
                    }
                }
            }
        }
    }
}

/**
 * AJAX callback to trigger querying a file list from Livelink.
 *
 * @noinspection PhpUnused
 * @noinspection PhpUnusedParameterInspection
 */
function livelink_get_files_callback(array &$form, FormStateInterface $form_state, string $language): AjaxResponse {
    $ajax_info = $form_state->getTriggeringElement()['#ajax'];

    $response = new AjaxResponse();

    $id = $form_state->getValue($ajax_info['related_field'])[0]['value'];
    if ($id) {
        try {
            $response->addCommand(new HtmlCommand('#' . $ajax_info['wrapper'], livelink_render_new_files($id)));
        } catch (GuzzleException) {
            return $response;
        }
        $response->addCommand(new InvokeCommand("[name='{$form_state->getTriggeringElement()['#name']}']", 'val', [t('Refresh')]));

        $response->addCommand(new MessageCommand('The file listing will not be saved until the page is saved.', null, ['type' => 'warning']));

        $files = livelink_load_files_cache($id);
        $files_options = array_column($files, 'll_name', 'll_id');

        $form_state->setRebuild();

        foreach ($form['field_session_row']['widget'] as $index => $widget) {
            if (is_int($index) && is_array($form['field_session_row']['widget'][$index])) {
                $select = $form['field_session_row']['widget'][$index]['subform'][$ajax_info['select_field']]['widget'];

                foreach ($files_options as $id => $name) {
                    $select['#options'][(string) $id] = $name;
                }
                $response->addCommand(new ReplaceCommand("div.livelink-field-wrapper[id^='{$ajax_info['select_field']}']", $select));
            }
        }
    }

    return $response;
}

Comment: I'm guessing you added the options in an #ajax callback. This will not work. Any form options need to be defined in the form definition, as the form has already been cached by the time the #ajax callback happens.
Comment: Would you please also indicate which hook you are implementing? You are trying to modify the options in a select element of a form. Do I have that right?
Comment: I have voted to close this issue until we have *all* the code, because this has become an interview.
Comment: @cilefen Yes, I'm using the form_alter hook. Yes, you are right: I'm trying to add custom/dynamic options to a select
Comment: Dynamic? Is this using the form Ajax API? I think we would need to see more of your code as this site isn't good for interviewing.
Comment: For dynamic I mean custom options loaded with PHP/AJAX and added to #options
Comment: No, the code you see in the OP where I'm editing the form is in the form_alter hook
Comment: @cilefen I've added the full form_alter hook and ajax callback code to the OP
Comment: Your ajax callback is probably not returning the Drupal settings with the returned values. But It's not clear what you're trying to do with the callback, and why you aren't returning part of the form array (as is standard). When done this way, Drupal will also send the updating settings for the form, required for any new ajax enabled elements.
Comment: @Jaypan see here for the updated code where I return the form array: https://drupal.stackexchange.com/questions/313234/adding-options-to-a-select-via-ajax-an-illegal-choice-has-been-detected
Comment: No, you're returning an AjaxResponse, not an array. And please keep your code to one thread, I'm working off the code above.
Comment: @Jaypan I've updated the code above. As you can see I return the form array in the replacecommand because I have to do multiple commands. Shall I do something similar or I have to return only the form array with the options changed? If yes, how can I keep the MessageCommand?
Comment: This question should be closed as a duplicate.
Comment: "As you can see I return the form array in the replacecommand" which means you are returning a replacecommand, not an array.
Answer: The answer was in this comment: https://drupal.stackexchange.com/a/264719/108326
Basically you have to override the allowed_values function of the field and set the new options


how to get copied text from clipboard on Golang [Mac]

Question: first of all I'm beginner of Golang
I wonder how to get copied text from clipboard on GoLang
I've searched about three packages but I don't know the way yet
"github.com/atotto/clipboard"
"github.com/d-tsuji/clipboard"
"golang.design/x/clipboard"

I just want to get copied text like this
this is python code

copy_string = pyperclip.paste()

help me guys
Answer: That will depend on your OS. That is why packages you mention have _unix.go _windows.go _darwing.go etc.
There is no copy function from std lib if that is your question!
On mac, there are two function available to you:
pbpaste and pbcopy.
So if you want to copy/paste on mac without a library:
func copy(content string) error {
    cmd := exec.Command("pbcopy")
    in, err := cmd.StdinPipe()
    if err != nil {
        return err
    }
    if err := cmd.Start(); err != nil {
        return err
    }
    if _, err := in.Write([]byte(content)); err != nil {
        return err
    }
    if err := in.Close(); err != nil {
        return err
    }
    return cmd.Wait()
}

func paste() (content string, err error) {
    cmd := exec.Command("pbpaste")
    out, err := cmd.Output()
    return string(out), err
}

Comment: now I wanna copy text without "cmd+c" is there a way to do that? I tried your copy func but nothing happen
Answer: This is what I'm looking for
I hope this code will help someone like me
import "github.com/d-tsuji/clipboard"

text, err := clipboard.Get()
fmt.Println(text)


Chord symbols and Pedal markings

Question: Adding Chord symbols is a great way to simplify reading music and memorizing it. Now I cannot decide if I should or should not put them in all scores. Should I just put it in sazz songs and improv. pieces?
Smaller question: Pedal markings - omitting them saves space, so when should I omit them?
Comment: Certainly in jazz, also in pop and Musicals type pieces. But in a piece such as Bach, Beethoven , Ravel, Grieg, etc. would have written, the harmonies can change so fast, it would be meaningless.
Answer: Where the precise written texture matters, make people read the notes!   Where 'busking' is appropriate, chord symbols can be useful.
But if you want to use them for analysis, fine.
Pedalling?  Vastly over-done, both in notation and performance.  You don't need to be meticulous - a simple 'con pedale' will get you normal legato pedalling.  Anything EXCEPT 'senza pedale' will probably get it anyway!
This sort of pedalling can avoid a load of messy ties.

Chord symbols and Pedal markings


How do I allow only 1 Java Semaphore to be created on a server?

Question: This is similiar to How do I allow only 1 named Semaphore to be created on a server? but I am asking here for Java.
I would like to create a semaphore in my Java app, where the creation will fail (with a clear exception), if another instance of the app is running and has already created the semaphore. So only one per server.
I'd like the limit of only one to hold across the server, not just the JVM. But I do not want it to hold across multiple servers (or VMs). i.e. I want the app able to run on 2 distinct servers.
Is this possible? If so, how?
Comment: what kind of semaphore do you mean? If java.util.concurrent.Semaphore, the question has no sense. If some kind of system semaphore, available across all processes, then you should name the operating system used.
Comment: @AlexeiKaigorodov Yes a java.util.Semaphore. And I want this to work on any O/S (that's the idea with Java). Thanks
Answer: You could write a mywebapp.lock file in the /tmp directory, and check if this file exists.
Here's some king of code you could use (not tested) :
Say that applicationFileLock is a FileLock that would hold the lock during application execution. You can have the following code executed during application startup :
FileOutputStream fos = new FileOutputStream(new File(System.getProperty("java.io.tmpdir"),"mywebapp.lock"));
try {
   applicationFileLock = fos.getChannel().tryLock();
   if (fileLock == null) {
     throw new AlreadyStartedApplicationException("Cannot ...");
   }
} catch (IOException e) {
   // handle or rethrow.
}

Be sure to release the lock using applicationFileLock.release() at the end of the application.
Comment: Of course, you have to do it using some kind of : http://docs.oracle.com/javase/6/docs/api/java/nio/channels/FileChannel.html#lock%28%29
Comment: that file would continue to exist even after the jvm is accidentally killed; preventing any further instantiation of that application.
Comment: More sophisticated the file could contain the JVM process id to check if it is alive.
Comment: +1 for nio lock. I believe that to be acceptable for @David's purpose. show some code/example/link for completeness.
Comment: I don't think this will work. What if the app does not have R/W access to that directory?
Comment: `tmp` directory is just an example, file could be placed anywhere where the JVM has write access.
Comment: @GuillaumeDarmont that's not going to work for us. We have customers running this where the system does not have write access to the file system. It wouldn't surprise me if some don't even allow read access (all I/O going to the database).
Comment: No write access at all ? I.E. no GC logs, no filesytem logging, no hsperfdata, ... ? That would be a really bad choice. BTW, if database is allowed, you could still use it as a lock : write (ServerName, PID) in a row. The second starting instance would have to check if this row exists and if PID is exists on ServerName. This time, I'm running out of ideas :)


How to find the area of a rhombus with two given side lengths and given height?

Question: Link to the Rhombus: Rhombus with given side lengths of 11 and a height of 8
Edit: I just realized that this rhombus is a parallelogram so because the 8 inches is the height and that the 11 inches is the base, I can simply times the 8 inches by the 11 inches to make 88 inches^2, so I think the answer is 88 inches^2.
Comment: Hi, please provide some context, such as what you have tried or any other relevant information in order to make this question suitable for our site.
Answer: Notice that there is a square of 8 inch sides inside of the rhombus. Calculate the area of the square first and then the area of the two other triangles that make up the rhombus.
Comment: Thank you very much for that response, that is greatly appreciated and I hope you have a good day.
Comment: Please do not answer questions that do not meet our site's quality standards.
Comment: I mean he had a question so I awnsered there's nothing much to it
Comment: Please also read the [meta announcement](https://math.meta.stackexchange.com/questions/33508/) regarding quality standards.


Which is the random variable in a Kalman filter?

Question: When estimating a hidden state $x$ with a Kalman filter, there is the posterior and prior estimate. There are also covariances associated with those estimates. Some authors call these the covariances of the estimates. How can estimates have covariances when they are expectations of the hidden state?
Answer: The covariance matrix computed by the Kalman filter is not the covariance matrix of the "estimate."
The Kalman filter is iteratively computing the mean $\bar{\mathbf{x}}_{t|t}$ and the covariance matrix $\mathbf{P}_{t|t}$ of the marginal posterior distribution $p(\mathbf{x}_t\,|\,\mathbf{y}_{1:t})$. So conditional on the data, the hidden state at time $t$ is a random variable with a distribution, and the Kalman filter is computing that distribution's mean and covariance matrix.
You can think of the mean $\bar{\mathbf{x}}_{t|t}$ as an "estimate" of the hidden state, but you shouldn't think of the covariance matrix $\mathbf{P}_{t|t}$ as the covariance of the estimate. That is, if you're thinking of $\bar{\mathbf{x}}_{t|t}$ as an estimator for $\mathbf{x}_t$, it will have a sampling distribution with respect to the randomly sampled data $\mathbf{y}_{1:T}$. But $\mathbf{P}_{t|t}$ is not the covariance matrix of that sampling distribution.


Access_ Dined reseller3.0 - RapidReseller

Question: I see the code in github https://github.com/google/enterprise-deployments/tree/master/apps/python/reseller3.0/RapidReseller,
and I try implement for see manage my reseller domain, but I have some problems.
I have :
INFO     2014-11-14 14:36:56,663 client.py:680] Refreshing access_token
INFO     2014-11-14 14:36:57,603 client.py:699] Failed to retrieve access token: {
  "error" : "access_denied",
  "error_description" : "Requested client not authorized."
}
File "/home/eduduarte/Downloads/ApisGoogle/google_appengine1.915/revenda/oauth2client/client.py", line 710, in _do_refresh_request
    raise AccessTokenRefreshError(error_msg)
AccessTokenRefreshError: access_denied
I created the key, the enable of Api, do download of key to the app, and too I use my account super admin: in settings.py RESELLER_ADMIN, and I have "access_denied"
Please, can someone help me.
Eduardo Duarte
Answer: Did you also added the scopes in the Admin Console for the clientID of your application?
In the Admin Console https://admin.google.com go to Security > Advanced Settings > In the Authentication section go to "Manage API client access". In the "Client Name" textbox write the clientID of your app and in the "One or More API Scopes" add the next scopes:

https://www.googleapis.com/auth/apps.order
https://www.googleapis.com/auth/siteverification
https://apps-apis.google.com/a/feeds/user/
https://www.googleapis.com/auth/admin.directory.user

this is done so the domain grant the app access to the information.
Answer: I would strongly recommend checking out the codelab that we just posted.  We just posted samples in four languages that walk through the entire end-to-end process of provisioning a resold customer.
https://developers.google.com/admin-sdk/reseller/v1/codelab/intro


How can i use python built-in function like isinstance() in julia using PyCall

Question: PyCall document says:
Important: The biggest difference from Python is that object attributes/members are accessed with o[:attribute] rather than o.attribute, so that o.method(...) in Python is replaced by o:method in Julia. Also, you use get(o, key) rather than o[key]. (However, you can access integer indices via o[i] as in Python, albeit with 1-based Julian indices rather than 0-based Python indices.)
But i have no idea about which module or object to import
Comment: Make the question clearer. Ways to do this: a) Add some of your code. b) Explain what is the purpose of your function or what it is trying to calculate. c) Make the code you share runnable and perhaps add some results or errors you get. d) Add a sentence which is a question (? at the end) and try to describe what would an answer be. Any combination of (a),(b),(c), and (d) would help.
Comment: Thank you anyway, the first answer below solved my problem.
Answer: Here's a simple example to get you started
<code>using PyCall

@pyimport numpy as np           # 'np' becomes a julia module

a = np.array([[1, 2], [3, 4]])  # access objects directly under a module
                                # (in this case the 'array' function)
                                # using a dot operator directly on the module
#> 2×2 Array{Int64,2}:
#> 1  2
#> 3  4

a = PyObject(a)                 # dear Julia, we appreciate the automatic
                                # convertion back to a julia native type,
                                # but let's get 'a' back in PyObject form
                                # here so we can use one of its methods:
#> PyObject array([[1, 2],
#>                 [3, 4]])

b = a[:mean](axis=1)            # 'a' here is a python Object (not a python
                                # module), so the way to access a method
                                # or object that belongs to it is via the
                                # pythonobject[:method] syntax.
                                # Here we're calling the 'mean' function,
                                # with the appropriate keyword argument
#> 2-element Array{Float64,1}:
#>  1.5
#>  3.5

pybuiltin(:type)(b)             # Use 'pybuiltin' to use built-in python
                                # commands (i.e. commands that are not
                                # under a module)
#> PyObject <type 'numpy.ndarray'>

pybuiltin(:isinstance)(b, np.ndarray)
#> true
</code>


Removing selected rows from the table in angular 2 using angular material table

Question: I am trying to implement a simple table in angular 2 using angular material selection table .
I used a button to remove the selected rows from the table.But on click of the button how can i delete the rows ?
Below shown is my html file for the table

  <mat-table #table [dataSource]="dataSource">

    <ng-container matColumnDef="select">
      <mat-header-cell  style="max-width: 100px;" *matHeaderCellDef>
        <mat-checkbox (change)="$event ? masterToggle() : null"
                      [checked]="selection.hasValue() && isAllSelected()"
                      [indeterminate]="selection.hasValue() && !isAllSelected()">
        </mat-checkbox>
      </mat-header-cell>
      <mat-cell   style="max-width: 100px;" *matCellDef="let row">
        <mat-checkbox (click)="$event.stopPropagation()"
                      (change)="$event ? selection.toggle(row) : null"
                      [checked]="selection.isSelected(row)">
        </mat-checkbox>
      </mat-cell>
    </ng-container>

    <ng-container matColumnDef="num">
      <mat-header-cell style="max-width: 100px;" *matHeaderCellDef> No. </mat-header-cell>
      <mat-cell style="max-width: 100px;" *matCellDef="let element"> {{element.num}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="name">
      <mat-header-cell *matHeaderCellDef> Message </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.name}} </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;"
             (click)="selection.toggle(row)">
    </mat-row>
  </mat-table>

   <mat-paginator #paginator
                 [pageSize]="10"
                 [pageSizeOptions]="[5, 10, 20]">
  </mat-paginator>

<button style="background: #3B4990; color:white;" (click)="deleted($event)">Remove Selected Messages</button>

Below shown is my .ts file.
import {Component, ViewChild} from '@angular/core';
import {MatPaginator, MatTableDataSource} from '@angular/material';
import {SelectionModel} from '@angular/cdk/collections';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
   styleUrls: ['./home.component.scss']
})

export class HomeComponent {

displayedColumns = ['select', 'num', 'name'];
  dataSource = new MatTableDataSource<Element>(ELEMENT_DATA);

  @ViewChild(MatPaginator) paginator: MatPaginator;

  /**
   * Set the paginator after the view init since this component will
   * be able to query its view for the initialized paginator.
   */
  ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
  }

  selection = new SelectionModel<Element>(true, []);

  /** Whether the number of selected elements matches the total number of rows. */
  isAllSelected() {
    const numSelected = this.selection.selected.length;
    const numRows = this.dataSource.data.length;
    return numSelected === numRows;
  }

  /** Selects all rows if they are not all selected; otherwise clear selection. */
  masterToggle() {
    this.isAllSelected() ?
        this.selection.clear() :
        this.dataSource.data.forEach(row => this.selection.select(row));
  }

    deleted($event)
{
 delete(this.dataSource.data.forEach(row => this.selection.select(row));)
}

}

export interface Element {
  name: string;
  num: number;
}

const ELEMENT_DATA: Element[] = [
  {num: 1, name: 'Message1'},
  {num: 2, name: 'Message2'},
  {num: 3, name: 'Message3'},
  {num: 3, name: 'Message4'},
  {num: 4, name: 'Message5'},
  {num: 5, name: 'Message6'},
];

can anybody please help me how can i remove the selected rows from the table using the button.
Answer: You should be removing the selected items and refresh the datasource as below,
removeSelectedRows() {
    this.selection.selected.forEach(item => {
       let index: number = this.data.findIndex(d => d === item);
       console.log(this.data.findIndex(d => d === item));
       this.data.splice(index,1)
       this.dataSource = new MatTableDataSource<Element>(this.data);
     });
     this.selection = new SelectionModel<Element>(true, []);
  }

LIVE DEMO
Comment: @Sithys example works fine now! thanks for notification
Comment: is it not possible instead of deleting them all to only remove a portion according to selection?
Comment: @Aravind Thank you for the LiveDemo, though when taking a look when I click on Remove buttons I can still see the row it is not removed. Is it normal ? I'm using google chrome
Comment: and in your example if the previous dataSource had some paginator and sort aren't you losing them? like @ViewChild('myPaginator') myPaginator: MatPaginator; in onInit() -> dataSource.paginator = myPaginator;
Comment: great work brother. It worked for me with little modification I was able to do add part too.@Aravind
Comment: @MonkeyD.Luffy happy to know that it helped you
Comment: Is there any other way to remove/add the item from/to MatTableDataSource without reinitializing it?
Answer: You can use the renderRows() method from the MatTable API.
This way you don't have to re-instantiate the array on every click.
Check-out the Live Demo
Comment: @LoganWlv It was introduced on [V.5.2.x](https://github.com/angular/material2/blob/5.2.x/src/cdk/table/table.ts)
Comment: Your live demo link was helpful but it worked without me having to call `renderRows()`
Comment: Is it only Angular 6 method ?
Comment: Yep saw it too, but somehow I can not find this method inn MatTable using Angular 5 :(
Answer: Can you try below?
  removeSelectedRows() {
    var oldData = this.dataSource.data;
    var oldData = oldData.filter((item) => !this.selection.selected.includes(item));
    this.dataSource = new MatTableDataSource<Topic>(oldData);
    this.selection.clear()
    this.dataSource.filter = "";
  }

Comment: While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply.
Answer: Thanks to Aravind as his answer helped me solve the same problem.  However, I didn't like that the MatTableDataSouce was in the forEach loop as I assumed that meant that it was creating a new datasource on each loop.  Also, for me, creating a new MatTableDataSource breaks my use of the default Paginator.  So I modified his answer and am posting here for anyone that may benefit.
removeSelectedRows() {
    //sort the selected rows first so that they are in descending order
    //this allows us to splice without the index getting confused
    let selectedRows = this.selection.selected.sort((a,b) => {return b.position - a.position});

    let ds = this.dataSource.data; //take a copy

    selectedRows.forEach(item => {
        ds.splice(item.position-1,1); //splice out the selected rows
    });
    this.dataSource.data = ds;  //set the datasource so it fires the refresh

    this.selection = new SelectionModel<Element>(true, []);
}

Haven't tested it yet but my guess is that some clean up will be required in both the accepted answer and mine as the positions will be out of synch which could mean subsequent calls fail.
Comment: Subsequent calls do indeed fail... need to add a couple of lines before setting the datasource

    let i = 1;
    ds.forEach(item => { item.position = i++;  });


Complex Analysis: Convergence of Power Series

Question:
Problem
  Let $p(z)=(z-a_1)(z-a_2)...(z-a_N)$, where $a_1, a_2, ..., a_N$ are distinct complex numbers. Let $M=\min_{1\le{k}\le{N}}|a_k|$. Prove that it is possible to express $\frac{1}{p(z)}$ as a power series $\sum_{n=0}^{\infty}c_nz^n$, for $|z|<M$.

Progress
We look to prove this by induction on $N$. The case $N=1$ is rather simple. We see that $$\frac{1}{p(z)}=\frac{1}{z-a_1}=-\frac{1}{a_1}\sum_{n=0}^{\infty}(\frac{z}{a_1})^n$$ which converges for $|z|<M$ by comparison with $\sum_{n=0}^{\infty}z^n$.
We assume now that the proposition holds for arbitrary $N$ and consider the '$N+1$' case.
Now, $p(z)=(z-a_1)(z-a_2)\cdots(z-a_N)(z-a_{N+1})$. By the assumption of our inductive hypothesis, $\frac{1}{(z-a_1)(z-a_2)\cdots(z-a_N)}$ can be expressed in the form $\sum_{n=0}^{\infty}c_nz^n$ for some complex coefficients $c_n$.
As such, $$\frac{1}{p(z)}=-\frac{1}{a_{N+1}}\sum_{n=0}^{\infty}c_nz^n\sum_{n=0}^{\infty}\frac{1}{(a_{N+1})^n}z^n=-\frac{1}{a_{N+1}}\sum_{n=0}^{\infty}\sum_{k=0}^{n}\frac{c_n}{(a_{N+1})^{n-k}} z^n$$ which is of the correct form, but I'm not sure how to demonstrate that convergence holds for $|z|<M$
Any help would be very appreciated. I'm not sure if induction is the best approach to proving this.
EDIT 1
I'll leave previous working here for reference. It seems simply writing $\frac{1}{p(z)}$ as a linear combination of the fractions $\frac{1}{z-a_k}$ for $1\le{k}\le{N}$ is a far less cumbersome approach. Thanks to all who have helped.

Further Problem:
  Could the radius of convergence exceed $M$?
Comment: Hint: One can decompose $1/p(z)$ as a linear combination of the fractions $1/(z-a_k)$, and expand each $1/(z-a_k)$ as a power series in $z$. The result is $1/p(z)=\sum\limits_{n=0}^{+\infty}b_nz^n$ for some complex numbers $b_n$ (and not what you write in the question, which is absurd).
Comment: Hint: $$\frac{1}{p(z)}=\sum_{j=1}^N\ \frac{1}{p'(a_j)\ (z-a_j)}\quad.$$
Comment: I think the simplest way is this: Put $a:=a_1$. We have $$\frac{1}{p(z)}=\frac{b}{z-a}+f(z)$$ with $f$ defined at $a$. Multiplying by $z-a$ and letting $z$ tend to $a$, we get $$\frac{1}{p'(a)}=b.$$ And there is nothing special about $a_1$.
Comment: What I meant is that there are plenty of misprints e.g. in $\sum p(z)z^n$ (which is actually equal to $p(z)/(1-z)$) do you really mean that or do you mean $\sum p_n(z)z^n$ for certain sequence $p_n$? I just want you to think about your problem carefully and then read the question carefully. I myself often makes the mistake to skip some necessary assumption etc.
Comment: If you try, can you read this if I wrote the question?
Comment: Recall *partial fractions*.
Comment: @AD: Not sure what you mean I'm afraid.
Comment: @AndréNicolas: How would I use that in this case?
Comment: It is better to do $N=2$ for concreteness. But in general there exist (complex) numbers $c_1,\dots,c_N$ such that $\frac{1}{p(z)}=\frac{c_1}{z-a_1}+\cdots+\frac{c_N}{z-a_N}$. The power series for the $\frac{c_i}{z-a_i}$ are done like your case $N=1$.
Comment: It seems I've made a number of 'absurd' errors here. I'm very new to the forum so I apologise. Thanks for the help though; hadn't thought about simply writing $\frac{1}{p(z)}$ as a linear combination of the $\frac{1}{z-a_k}$ fractions.
@Pierre-YvesGaillard: How do we know that the coefficient for each fraction is $\frac{1}{p'(a_j)}$? Thanks again by the way.
Comment: Dear @TJO: Short answer: "clear denominators". If it's too short, tell me! (You're welcome.)
Comment: @Pierre-YvesGaillard: I fear that may be too short.
Comment: @Pierre-YvesGaillard Magic! Once again, thanks!
Comment: @TJO: Again, you're welcome, and, again, I didn't invent this! (+1 for your question!)
Comment: @AD.: Apologies for the confusion there; I've edited appropriately.
Comment: You might be interested in the [Mittag-Leffler theorem](http://en.wikipedia.org/wiki/Mittag-Leffler%27s_theorem) applied to the set $\{a_1,\ldots,a_N\}$.
Comment: Regarding the "Further Problem": No, it can't, since there's a pole at distance $M$ from the origin and the radius of convergence can't extend beyond a pole.
Answer: Write $f = C \prod_i \frac{1}{1 - z/a_i}$, each has the regular power series expansion for $\frac{1}{1+z}$ for $|z| < |a_i|$, done!
Answer: A standard theorem of complex analysis says: If $z\mapsto f(z)$ is analytic in the disk $D_M:=\{z\in{\mathbb C}\ |\ |z|<M\}$ then the Taylor series of $f$ at the origin has a convergence radius $\rho\geq M$. In your case the function $f(z):={1\over p(z)}$ satisfies the assumption of the theorem, and in addition it has a pole on $\partial D_M$. Therefore one definitely has $\rho=M$.


Status bar and overlay

Question: I'm showing a custom overlay with this parameter inflating the view from a service:
params = new WindowManager.LayoutParams(WindowManager
        .LayoutParams
        .MATCH_PARENT,
        statusBarHeight, WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY, WindowManager
        .LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
        | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams
        .FLAG_NOT_FOCUSABLE, 0);
params.gravity = Gravity.CENTER | Gravity.TOP;

The problem is that if the status bar is expanded, the overlay is over the quick settings menu. How can I avoid that? I'm using android 6.
Answer: Instead of TYPE_SYSTEM_OVERLAY use TYPE_SYSTEM_ERROR.
params = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.MATCH_PARENT,
            100,
            // Allows the view to be on top of the StatusBar
            WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
            // Keeps the button presses from going to the background window
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
            // Enables the notification to recieve touch events
            WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
            // Draws over status bar
            WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
            PixelFormat.TRANSLUCENT);

params.gravity =  Gravity.TOP|Gravity.CENTER;

mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mWindowManager.addView(mView, mLP);

This should solve your issue.
Comment: I had to remove not touchable flag as you wrote in addition.

Status bar and overlay


Need absolute file path of selected file using Intent.ACTION_OPEN_DOCUMENT in android pie

Question: I want to get pdf and convert it into base64.
use this code to start picker
<code>Intent  intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            String [] mimeTypes = {"image/*", "application/pdf"};
            intent.setType("*/*");
            intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
            startActivityForResult(intent, 1);
</code>
I had used below solution :
https://stackoverflow.com/a/41440869/6864437
but it is not working on android pie
getting below error:
Request header queries do not support projections, selections or sorting
How to get the Full file path from URI
Comment: Why would you need a a File path? You can do all using the obtained url directly.
Comment: Instead of the FileInputSTream you could use an InputStream directly for the obtained uri: `InputSTream is =getContentResolver().openInputStream(data.getData());`. The rest of the code is the same.
Comment: For the rest you should post the relevant code.
Comment: String base64 = "";
        try {
            byte[] buffer = new byte[(int) file.length() + 100];
            @SuppressWarnings("resource")
            int length = new FileInputStream(file).read(buffer);
            base64 = Base64.encodeToString(buffer, 0, length,
                    Base64.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return base64;       use this code to create base 64 and file name is also required to store it in server @blackapps
Comment: @blackapps Also need to retrieve file name and extension
Comment: You can get the DISPLAY_NAME with querying the contentresolver with the obtained uri.
Answer: Solution used : I use input stream (suggested by @blackaaps) to get data from file and create new file which I can use to get full path.


Hypothesis testing of two dependent samples when pair information is not given

Question: For two samples equal sample size $(n\ =\ 100)$ that are randomly selected and dependent,  only the sample means$(\overline x_1, \overline x_2)$ and sample standard deviations($ s_1,s_2 $) for both samples are given and the pair data for two samples are not given.
Also, it is given that population variances are equal for the two samples.
The question is to find whether there is a difference in mean between sample 1 and sample 2.
How do I solve this problem. Since the two samples are dependent , can I use the two-tailed t-test for difference between means ?

But my problem is, since the data pairs are not given, how do you find the terms $ \overline d$ and $s_d$.
Or is there another formula for solving this type of question ?
Answer: If you only have information about each sample separately and nothing about either the pair-differences or say the pair-correlation (nor covariance, nor any other relevant information), you don't have the ability to work out $s_d$. If you assume that the dependence is non-negative (an uncontroversial assumption in most circumstances) you can bound $s_d$ by the usual independent samples pooled standard deviation estimate.
So if all you have is $\bar{x}$, $s$ and $n$ for each sample, and literally nothing more, there's likely nothing to do but treat it as if it were an independent test and work with what should then be an upper bound on the p-value.
It would be good to see the context, because sometimes there's some subtlety that may not be obvious on first glance which, naturally, we won't see in a paraphrased question.
Comment: thanks alot for the answer


Binding Ilist value with Combobox in datagridview

Question: I have a requirement like i have list of values in a List.I need to bind a Combobox in a DataGridView And add the values in the Combobox.
<code>   private void btnBrowse_Click(object sender, EventArgs e)
    {
            dgvFiles.Rows.Clear();
            dgvFiles.Columns.Clear();
            dgvFiles.Columns.Add("FileName", "File Name");
            dgvFiles.Columns.Add("Size", "File Size");
            dgvFiles.Columns.Add("Extension", "Extension");
            dgvFiles.Columns.Add("Non-OCR Pages", "Non-OCR Pages");
            dgvFiles.Columns.Add("OCR Pages", "OCR Pages");
            dgvFiles.Columns.Add("Total Pages", "Total Pages");
            DataGridViewComboBoxColumn tb = new DataGridViewComboBoxColumn();
            dgvFiles.Columns.Add(tb);
            tb.Name = "Non-OCR PageNos";
            tb.HeaderText = "Non-OCR PageNos";
            DataGridViewComboBoxColumn tb1 = new DataGridViewComboBoxColumn();
            dgvFiles.Columns.Add(tb1);
            tb1.Name = "OCR PageNos";
            tb1.HeaderText = "OCR PageNos";
            string[] files = Directory.GetFiles(filepath, "*.pdf");
            //string[] templist = File.ReadAllLines("d:\\pdfcheck.txt");
            textBox1.Text = null;
            textBox2.Text = null;
            //StreamWriter OpStream = new StreamWriter("d:\\OCR_NonOCR_Report.csv");
            List<int> listNonOcr = new List<int>();
            List<int> listOcr = new List<int>();
           dgvFiles.Rows.Add(f.Name, f.Length, f.Extension, label4.Text.ToString(), label3.Text.ToString(),listNonOcr, listOcr, total.ToString();
   }
</code>
Answer: you can do like this.....
<code>public class SomeClass
{
  private string name;

  public SomeClass(string name)
  {
     this.name = name;
  }

  public string Name
  {
     get{return name;}
  }

  public object This
  {
     get{return this;}
   }
}

so that you  can specify:

DataGridViewComboBoxColumn column = new DataGridViewComboBoxColumn();
column.ValueMember = "Name";
column.ValueMember = "This";
column.DataSource = new List<SomeClass>(new SomeClass[]{new
SomeClass("Fred")});
</code>


Available height to position UI elements assuming keyboard always shows

Question: I am encountering a problem that I'm not sure how to solve.  If you look at the screenshot below, you'll see that the UI is laid out so that it neatly fits into the space between the safe area layout guide's top anchor and the top of the keyboard.
The keyboard will ALWAYS be shown in this view controller.  But I need a way of knowing what the height of the keyboard is so that I can do some math to figure out how to tall to make the UITextView (the red box).
I tried the approach of registering for notifications on when the keyboard will show, but that is too late.
I need a way of knowing the height of the keyboard before the view renders so that I can configure the height of each of the elements in the UI.
Is there a way to do this?
Thank you!
Answer: One option would be to capture the dimensions of the Keyboard when it IS presented then pass those dimensions into this view.
However, you will also want to make sure that you are handling cases such as the split keyboard on an iPad and things of that nature.
For that you might choose to look at the documentation on using the keyboardLayoutGuide and use it with some constraints.
https://developer.apple.com/documentation/uikit/keyboards_and_input/adjusting_your_layout_with_keyboard_layout_guide


HttpModule: Como tratar erros de HttpApplication sem HttpContext?

Question: Venho encontrando uma situação particularmente interessante. Tenho uma rotina genérica de tratamento de erro implementada dentro de um HttpModule, e recentemente eu percebi um comportamento estranho: O evento HttpApplication.Error é disparado, mas HttpContext.Current é null.
Esta é a parte relevante do HttpModule:
public void Init(HttpApplication context)
{
    context.Error += context_Error;
    context.PostMapRequestHandler += context_PostMapRequestHandler;

}

void context_PostMapRequestHandler(object sender, EventArgs e)
{
    var aux = HttpContext.Current.Handler as Page;
    if (aux != null) aux.Error += context_Error;
}

void context_Error(object sender, EventArgs e)
{
    _localLog.Add("HttpApplication error handler reached.");
    try
    {
        if (HttpContext.Current == null)
        {
            _localLog.Add("No HttpContext.");
        }
        else
        {
            var objError = HttpContext.Current.Server.GetLastError();

            if (objError == null)
            {
                _localLog.Add("GetLastError(): no error.");
                return;
            }

            //[Proper error handler follows here...]
        }
    }
}

E o evento aparece da seguinte maneira:

Uma possibilidade é que a exception esteja sendo gerada em uma thread fora de contexto.
De qualquer maneira, como posso interceptar este erro a fim de tratá-lo?
Crosspost: https://stackoverflow.com/questions/26018273/httpmodule-how-to-handle-httpapplication-errors-without-httpcontext
Answer: No método context_Error podes fazer cast do parâmetro sender para HttpApplication e aí aceder à propriedade Context. Também pode acontecer que seja uma excepção que ocorra sem que haja nenhum pedido HTTP, por exemplo, código de inicialização/warmup da aplicação web.
Comment: Ponto interessante, Ricardo! Obrigado  pela sugestão, eu vou testar o cast para HttpApplication.


Find the distance between 2 coords in pandas with haversine error

Question: I want to find the distance between 2 coords with Haversine in pandas, but it gives me the error:
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
my df:
   latitude    longitude    buc_lat    buc_long
0  46.161411   27.662575    44.433     26.1024
1  44.420262   26.126688    44.433     26.1024
2  44.413853   26.096157    44.433     26.1024

my code:
import numpy as np

def haversine_vectorize(lon1, lat1, lon2, lat2):

    newlon = lon2 - lon1
    newlat = lat2 - lat1

    haver_formula = np.sin(newlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(newlon/2.0)**2

    dist = 2 * np.arcsin(np.sqrt(haver_formula ))
    km = 6367 * dist #6367 for distance in KM for miles use 3958
    return km

Comment: Please share a [mcve] with data which is easily usable.
Comment: All the `lat` and `long` in `haversine_vectorize()` must be in radians. Do it by multiplying with `np.pi/180`.
Answer: You fails to use correct units when dealing with computation concerning lat and long in the relevant formulas. Here are the runnable code, step by step.
from io import StringIO
import pandas as pd
import numpy as np

data_str = """index   latitude    longitude    buc_lat    buc_long
0  46.161411   27.662575    44.433     26.1024
1  44.420262   26.126688    44.433     26.1024
2  44.413853   26.096157    44.433     26.1024"""

df3 = pd.read_csv(StringIO(data_str), sep='\s+', index_col='index')

At this step, the dataframe df3 is
        latitude  longitude  buc_lat  buc_long
index
0      46.161411  27.662575   44.433   26.1024
1      44.420262  26.126688   44.433   26.1024
2      44.413853  26.096157   44.433   26.1024

Your distance function should look like this.
def haversine_vectorize(row):
    rho = np.pi/180
    # convert all values to radians
    lon1=row.longitude*rho
    lat1=row.latitude*rho
    lon2=row.buc_long*rho
    lat2=row.buc_lat*rho

    newlon = lon2 - lon1
    newlat = lat2 - lat1

    haver_formula = np.sin(newlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(newlon/2.0)**2

    dist = 2 * np.arcsin(np.sqrt(haver_formula ))
    # use appropriate value for radius of the earth (this is crude!)
    km = 6367 * dist #6367 for distance in KM for miles use 3958
    print(" Distance {} km:".format(km))
    return km

To compute and get the distances, do this.
ans = df3.apply(haversine_vectorize, axis=1)

Create a new column in the dataframe df3 to keep the distances just obtained.
df3["distance_km"] = ans

Finally, you will get the dataframe as
        latitude  longitude  buc_lat  buc_long  distance_km
index
0      46.161411  27.662575   44.433   26.1024   227.506591
1      44.420262  26.126688   44.433   26.1024     2.391419
2      44.413853  26.096157   44.433   26.1024     2.184640


How do I know which Drupal 8 modules are supported by Drupal 8 versions?

Question: How do I know which Drupal 8 modules are supported by Drupal 8 versions?
For example is Page Manager 8.x-1.0-alpha8 module supported in every Drupal 8 version? And if not how do I know which Drupal 8 version supports some module?
Which version of Drupal 8 supports Paragraphs 8.x-1.0-alpha2 module?
Answer:
How do i know which drupal 8 modules are supported by Drupal 8 versions?

You can't.
Specific projects might release alpha/beta versions in sync with core but if that's so and which version requires which version is something you have to figure out for each project separately.
You can try to get guess based on the release date, check if a release came out before or after a beta version. But it might be that an older release still works.
No contrib project that I've seen so far explicitly defines version specific dependencies, and it's actually not really possible, because you don't know yet when you release whether the module is going to be compatible with the next beta or not and when something will break it.
That said, there should be fewer and fewer API changes that break contrib modules from now on.
Answer: Unfortunately, you can only see which modules have a release that was at one point compatible with a pre-release of Drupal 8; you can't tell whether a module is actually still compatible without testing it - unless the maintainer explicitly mentioned it on the page.
For example, the Paragraphs project you asked for states:

the alpha2 version is working with Drupal 8 beta 4. We try to keep the 8.x-1.x-dev branch compatible with the Drupal 8 HEAD.

You can make a good guess, though, using the module's activity and the core release cycle: The older a module is, the more likely it is to be broken by a major API change. For example, the .info -> YAML switch (early 2013) broke all modules. The hook_menu() -> YAML switch (late 2013 / early 2014) broke all modules that have menu paths. Other APIs have been changed even more recently.
For example, the Page Manager project you asked about was last pushed yesterday, and the last alpha was released the same day as the last core beta. You have very good odds there.

how do i know which Drupal 8 version supports some module?

Sorry to be blunt, but knowing this wouldn't really help you (unless you're working on porting the module, and need to know what to change). If the module isn't supported by the latest beta, then the last version that did support it is presumably an outdated and unstable pre-release. ;-)


XML Mapping Tool Delphi Tokyo

Question: Gostaria de saber qual a forma correta de mapear um .XML pelo Delphi Tokyo com o xml mapping tool e ler no ClientDataSet.
Utilizando o XML Mapping Tool com o Delphi 7 consigo fazer o mapeamento e ler os arquivos pelo ClientDataSet sem problema.
if OpenDialog1.Execute then
     begin
         XMLTransform1.SourceXmlFile:= OpenDialog1.FileName;
         XMLTransform1.TransformationFile:= ExtractFilePath(ParamStr(0))+ 'transformation.xtr';
         Cds_Fornecedor.XMLData:= XMLTransform1.Data;
     end;

Quando passa pela linha:

Cds_Fornecedor.XMLData:= XMLTransform1.Data;

Retorna o seguinte erro:

XML PARSE ERROR:
  Reason: O Sistema não pode localizar o objeto especificado.

Obs.: Gerei o schema.xml e o .xtr pelo Delphi 7 e depois gerei pelo Delphi Tokyo
Answer: Li um artigo na net que o programador usava o XMLTransformProvider no Delphi Tokyo ao invés de usar o XMLTransform (igual ao Delphi 7). Então mudei o componente e o código ficou assim:
 If ClientDataSet1.Active then
    ClientDataSet1.Close;
 ClientDataSet1.providerName:= 'XMLTransformProvider1';

 XMLTransformProvider1.TransformRead.TransformationFile:= 'arquivo.xtr'
 XMLTransformProvider1.XMLDataFile:= OpenDialog1.FileName;
 ClientDataSet1.Active:= True;

Preferi responder a minha própria pergunta ao invés de apagá-la, pois sei que se eu tive essa dificuldade, com certeza, outra pessoa também terá.

XML Mapping Tool Delphi Tokyo


MYSQL query that orders data by timestamps contained in two tables

Question: I'm trying to build a query that will order results by date and time, but the date and time upon which I want to base the ordering is contained in two tables. Additionally,  I'd like to group the data by loc_id for rows having the same date.
For example, if I had this data:

Notes:
- parent_id links to the id in TABLE A.
- there are two other tables USER and LOC which are used to get the user name and location name.
- comments are optional in TABLE A, but will always exist in TABLE B.
I've found a lot of info on this site that's close to what I need, but nothing that's quite helped me solve this issue.
Thanks.
Answer: SELECT a.`date`
     , a.`time`
     , l.loc_name AS l_name
     , a.rating
     , a.comment
     , u.user_name
FROM table_a AS a
  LEFT JOIN loc AS l
    ON l.loc_id = a.loc_id
  LEFT JOIN `user` AS u
    ON u.user_id = a.user_id

UNION ALL

SELECT b.`date`
     , b.`time`
     , l.loc_name AS l_name
     , NULL AS rating
     , b.comment
     , u.user_name
FROM table_b AS b
  LEFT JOIN table_a AS a
    ON a.id = b.parent_id
  LEFT JOIN loc AS l
    ON l.loc_id = a.loc_id
  LEFT JOIN `user` AS u
    ON u.user_id = b.user_id

ORDER BY `date`
       , l_name
       , `time`

Comment: I think this will do what I need, but I'm getting an error on the loc_id in the ORDER BY clause: MySQL said: Documentation
#1054 - Unknown column 'loc_id' in 'order clause'
Comment: I added one more entry to each SELECT: , a.loc_id.  Now it works!  Thanks!
Comment: Yes, change it to `loc_name`. If you need to order by `loc_id` there, it will be only a bit more complex.
Comment: Thanks.  I edited your answer so everyone can see what I did, but I don't think you'll see the changes until it's been peer reviewed.  It does exactly what I asked for so thanks!  One more question if you don't mind. Would it be easy to add a WHERE clause so that I could run the query on a specific location?  (something like WHERE l.loc_id = 26, for example)?
Comment: @user418775: yes, just add `WHERE l.loc_id = 26` to **both** subqueries.
Comment: And a note: This kind on `UNION` and then `ORDER BY` can result in a very slow query if your tables are just a bit more than small.
Answer: Something like this?
(Assumed your users table was called users and your locations table locations.)
SELECT a.date, a.time, l.loc_name, a.rating, b.comment, u.user_name
FROM table_a a
JOIN locations l ON l.loc_id = a.loc_id
LEFT JOIN table_b b ON b.parent_id = a.id
RIGHT JOIN users u ON a.user_id = u.user_id

GROUP BY a.loc_id

ORDER BY a.date DESC, a.time DESC

Comment: I've been trying this solution, but I get an error on the GROUP BY: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'GROUP BY a.loc_id.  If I remove ORDER BY I don't get the error.  Any ideas?
Comment: Yes, the Group By should be placed ABOVE the Order By. My bad.. -.-
Comment: Thanks for your answer.  I placed GROUP BY above and the query run now, but it only returns data from table_a.  The other answer provides what I need.  Cheers.
Comment: @Jules: Actually, `GROUP BY` is not needed, despite the OP's description (`I'd like to group the data by loc_id`). He means to **order by** date, then loc_id, then time (as the result set shows).
Comment: @ypercube: Mmmh, then I misinterpreted his question.. :(


Unable to get MAX time inside join but with distinct id MySQL

Question: I have 3 tables to get desired output(latest filepath) :-

Events Table [having event Id]
Event_media Table [having event Id,media Id and creation_time]
Media Table [having media Id and filepath]

I want to get- all distinct events with their filepath where creation_time of event media Table is MAX such that i can have all events with their updated filepath

MySQL Query:-
<code>select e.event_id, m.filepath, em.creation_time as latest from event e join event_media em on e.event_id=em.event_id join media m on em.media_id = m.media_id where em.creation_time=(select MAX(em.creation_time) from event_media where em.event_id =e.event_id);
</code>
Output :-
<code>+----------+------------------------------------------------------------------------------------+---------------------+
| event_id | filepath                                                                           | latest              |
+----------+------------------------------------------------------------------------------------+---------------------+
|  1000055 | http://localhost:3000/static/images/glasoimage/event1.jpg                          | 2017-07-06 02:06:30 |
|  1000056 | http://localhost:3000/static/images/glasoimage/event2.jpg                          | 2017-07-06 02:15:15 |
|  1000058 | http://localhost:3000/static/images/glasoimage/event3.jpg                          | 2017-07-06 02:22:17 |
|  1000059 | http://localhost:3000/static/uploads/media/upload_b46a5d6f37f1c77a17b87fcbe5ccb975 | 2017-07-06 02:23:17 |
|  1000066 | http://localhost:3000/static/images/glasoimage/event6.jpg                          | 2017-07-06 17:10:59 |
|  1000057 | http://localhost:3000/static/uploads/media/upload_12b7a15dfae2ce4f7864c957b8ecf5a6 | 2017-07-06 02:20:52 |
|  1000062 | http://localhost:3000/static/images/glasoimage/event4.jpg                          | 2017-07-06 16:45:22 |
|  1000063 | http://localhost:3000/static/images/glasoimage/event5.jpg                          | 2017-07-06 16:47:30 |
|  1000071 | http://localhost:3000/static/uploads/media/upload_d00ab7878fcf6bacdbf800249678b818 | 2017-07-15 14:10:36 |
|  1000071 | http://localhost:3000/static/uploads/media/upload_0c85d276316550ef33e2f274635b99c7 | 2017-07-15 23:42:03 |
|  1000072 | http://localhost:3000/static/images/defaults/default-image.jpg                     | 2017-07-15 23:29:24 |
|  1000073 | http://localhost:3000/static/images/defaults/default-image.jpg                     | 2017-07-16 12:21:57 |
|  1000074 | http://localhost:3000/static/images/defaults/default-image.jpg                     | 2017-07-16 12:25:09 |
|  1000075 | http://localhost:3000/static/images/defaults/default-image.jpg                     | 2017-07-16 13:40:11 |
|  1000076 | http://localhost:3000/static/images/defaults/default-image.jpg                     | 2017-07-16 13:43:10 |
|  1000077 | http://localhost:3000/static/images/defaults/default-image.jpg                     | 2017-07-16 14:04:58 |
|  1000067 | http://localhost:3000/static/images/defaults/default-image.jpg                     | 2017-07-13 21:55:21 |
|  1000068 | http://localhost:3000/static/uploads/media/upload_d32e3685c22232d00602e827f55f6f64 | 2017-07-13 22:45:04 |
|  1000069 | http://localhost:3000/static/uploads/media/upload_e0aab7ea8150ee5e7e1f55d98366e51f | 2017-07-13 22:47:50 |
+----------+------------------------------------------------------------------------------------+---------------------+
19 rows in set (0.18 sec)
</code>
For event Id 1000071 on line 9 & 10 in output I have two filepath old and new.

I want the new Filepath only with no duplication of event Id

Thanks in Advance
Answer: You could use a group by and a join on the max
<code>  select
      e.event_id
      , m.filepath
      , em.creation_time as latest
  from event e
  join event_media em on e.event_id=em.event_id
  join media m on em.media_id = m.media_id
  join (
      select
           event_id
          , MAX(creation_time) as max_time
      from event_media
      group by event_id
    ) t on t.event_id = em-event_id and em.creation_time = t.max_time
</code>
Comment: Thanks a lot @scaisEdge, it worked. I don't know how i missed that but thanks once again


Send the text of cell clicked, to the next view

Question: 1.1, I have a TableView, linked with sqlite, when i click a cell, the program goes to the prepareForSegue, before getting the value inside of tableView didSelectedRow.
For this in the first visit of secondView the value of Label is nil, if i back to the previous view and select other cell, i get the first cell value.
I have a UILabel in the secondView and this text would be the cell selected.
I don´t know how i can say at segue the text value of the tableView.
May be somebody can help me, apologies if my english is bad.
Thanks.
#import "farmacopeaViewController.h"
import "AddFarmacoViewController.h"  //second View`
@implementation farmacopeaViewController
@synthesize copiaFarmaco,farmacos,descript;
- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
   // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.

}
- (void)viewDidLoad
{
   [super viewDidLoad];
[self populateFarmacos];
[self populateDescrip];
}
-(void) populateFarmacos
{
  self.farmacos = [[NSMutableArray alloc] init];
FMDBDataAccess *db = [[FMDBDataAccess alloc] init];
self.farmacos = [db getFarmacos];
}
-(void) populateDescrip
{
   self.descript = [[NSMutableArray alloc] init];
FMDBDataAccess *db = [[FMDBDataAccess alloc] init];
self.descript = [db getDescripcion];
}
- (void)viewDidUnload
{
    [super viewDidUnload];
  }
- (void)viewWillAppear:(BOOL)animated
{
   [super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
   [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
   [super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.

return 1;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
self.copiaFarmaco = [[[tableView cellForRowAtIndexPath:indexPath] textLabel]text];
    NSLog(@"%@",copiaFarmaco);
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([[segue identifier] isEqualToString:@"pasarDatos"]){
    AddFarmacoViewController *segundoView = [segue destinationViewController];

    segundoView.nombre = self.copiaFarmaco;
}

}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
   return [self.farmacos count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
 Farmaco *farmaco = [farmacos objectAtIndex:[indexPath row]];
[[cell textLabel] setText:[NSString stringWithFormat:@"%@",farmaco.farmacoId]];
    return cell;
}
@end
Comment: please provide your code to understand it better.
Answer: You should create the segue from the First ViewController to second ViewController (Not from a Button to Second ViewController)
Inside your didSelectRowAtIndexPath
 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
         [self performSegueWithIdentifier:@"segueToLocation" sender:the object you want to pass];
    }

then get the object here
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString: @"segueToLocation"]) {
         SecondViewController *dest = (SecondViewController *)[segue destinationViewController];
         //the sender is what you pass into the previous method
         dest.labelValue=sender
    }
}

Comment: In secondView make this:

 - (void) viewDidLoad{
titulo.text = nombre;
}

I think the problem is here becose the program get the title label right, and after retur to this method and titulo.text //is a label and nombre are nil.

Your anwer is right can help me in the final pass?
Comment: it might be that you are pushing the controller twice. This response is right tho. You might have a connection done in your storyboard from the tableView to push next VC on tap. In that case, remove it and do it in code like this response suggests .


Find all solutions of the equation $\cos 4x + \cos x = 0$.

Question: I am writing my first university maths exam . I truly have no clue as to how I should proceed. Any tips or methods on how to solve this would greatly appreciated.
Question:
By using the addition formulae show that $$\cos(A + B) + \cos(A - B) = 2 \cos A\cos B$$
Setting $u = A + B$ and $v = A - B$, deduce that $$\cos u + \cos v = 2 \cos\frac{u + v}{2} \cdot \cos \frac{u-v}{2}.$$
Use this to find all solutions of the equation $$\cos 4x + \cos x = 0.$$
Comment: Please be more specific about where you are stuck. The question is pretty explicit about what to do.
Comment: Welcome to MathSE. Some of your characters are not displaying correctly (your minus sign appears as an upside-down exclamation mark: ¡). Please have a look at [this tutorial and reference guide](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) and edit your post accordingly.
Comment: Thank you.Sorry for the editing error just really stuck. Maths is not my strongest subject and I would really like to pass my exam this weekend.
Comment: What do you mean by university ?
Comment: @ritwiksinha https://en.wikipedia.org/wiki/University
Answer: 1. :- $cos(A + B)+ cos(A-B)$ = $cosAcosB - sinAsinB + cosAcosB + sinAsinB$ = $2*cosAcosB$
2. :- $u = A+B, v= A-B$
$cos(u) + cos(v)$
$ = cos(A + B)+ cos(A-B) = 2*cos(A)cos(B) = 2*cos(\frac{A+B + A-B}{2})cos(\frac{A+B - A+B}{2})$
= $2*cos(\frac{u + v}{2})cos(\frac{u - v}{2})$
3. :- $cos(4x) + cos(x)$ = $2*cos(\frac{4x+x}{2})cos(\frac{4x-x}{2})$ = $2*cos(\frac{5x}{2})cos(\frac{3x}{2}) = 0$
$cos(\frac{5x}{2})$ = $cos(\frac{\pi}{2})$
$\frac{5x}{2} = \frac{\pi}{2}$
$x = \frac{\pi}{5}$
$x = 2\pi*n \pm \frac{\pi}{5}$ $or$
$x = 2\pi*n \pm \frac{\pi}{3}$
Comment: Thank you , i still am confused about what im meant to do,but thank you for your help
Comment: @Daniel Then ask. whats is the confusion ?
Comment: Please note that MathJaX knows commands for certain standard formulae, such as $\sin\cos x$=`\sin\cos x`. If a function does not have a MathJaX command, then you can use the command `\operatorname` like this: $\operatorname{rang} f$=`\operatorname{rang} f`.
Comment: @gebruiker i did not know this when i wrote this answer. I know these commands now.
Answer: Well do exactly what it says:
" By using the addition formulae"
Okay, first thing is to remember and remind ourselves what the addition formulae are.
There are $\sin(x + y) = \sin(x)\cos(y) + \sin(y)\cos(x)$
And $\cos(x + y) = \cos(x)\cos(y) - \sin(x)\sin(y)$
" show that cos(A + B) + cos(A - B) = 2 cosAcosB"
Okay $\cos(A + B) = \cos(A)\cos(B) - \sin(A)\sin(B)$
and  $\cos(A - B) = \cos(A)\cos(-B) - \sin(A)\sin(-B) = \cos(A)\cos(B) + \sin(A)\sin(B)$ (as $\cos(-B) = \cos(B)$ but $\sin(-B) = -\sin(B)$
So $\cos(A + B) + \cos(A - B) = \cos(A)\cos(B) - \sin(A)\sin(B)+\cos(A)\cos(B) + \sin(A)\sin(B) = 2\cos(A)\cos(B)$.
": Setting u = A + B and v = A - B deduce that cos u + cos v = 2 cos (u + v)/ 2 x cos (u-v)/2 :"
$\cos(u) + \cos(v) = \cos(A+B) + \cos(A-B) = 2\cos(A)\cos(B)$
Now $\frac{u+v}{2} = \frac{(A+B) + (A- B)}{2} = \frac{2A}2 = A$ and $\frac{u-v}{2} = \frac{(A+B) - (A- B)}{2} = \frac{2B}2 = B$
So $\cos(u) + \cos(v) =  2\cos(A)\cos(B)= 2\cos(\frac{u+v}{2})\cos(\frac{u-v}{2})$
NOTE!!!!:  This is true of ALL u and v, even if we weren't given what A and B were in the first place!
That's the point of this exercise.  For any $u$ and $v$ we can set $A = \frac{u+v}2$ and $B = \frac{u - v}2$ and it will be true that $u = A + B$ and $v = A - B$.
Use this to ¯find all solutions of the equation cos 4x + cos x = 0:
Okay $\cos(4x) + \cos(x) = 2\cos(\frac{4x + x}{2})\cos(\frac{4x - x}{2})$
$=2\cos{\frac{5x}2}\cos{\frac{3x}2} = 0$.
So $\cos{\frac{5x}2} = 0$ or $\cos{\frac{3x}2}=0$.
So how do we solve $\cos W = 0$?  Well, that means $W = \frac{\pm \pi}2 + 2k\pi$ where $k$ is some integer.
So the possible solutions are
$5x/2 = \frac{\pm \pi}2 + 2k\pi$
$5x = \pm\pi + 4k\pi$
$x = \frac{\pm \pi}{5} + \frac{4k}5\pi$.
Or
$3x/2 = \frac{\pm \pi}2 + 2k\pi$
$3x = \pm\pi + 4k\pi$
$x = \frac{\pm \pi}{3} + \frac{4k}3\pi$.
So $x = \{\frac{\pm \pi}{5} + \frac{4k}5\pi, \frac{\pm \pi}{3} + \frac{4k}3\pi\}$ are all the solutions.
Comment: great explanation.


How to move system time to coprocessor1 correctly?

Question: In MARS mips I get current time with:
li $v0, 30
syscall

Then I try to move the system time which is 64 bit to coprocessor1 to do some calculation on the number:
mtc1.d $a0, $f0

The problem is in the inspector on the right it shows me that the double value in $f0 is something else than I was expecting.
If I take the hex and convert it to decimal using Google, the result is different than  what MIPS shows when I change to decimal view. I know for a fact that Google is correct, so I don't move the data correctly?
How to correctly move the system time in coprocessor1 to do arithmetic on it?
Answer: According to http://www.ece.lsu.edu/ee4720/2016/lfp.s.html, mtc1.d just moves copies the integer bit-pattern.
You have to use cvt.d.w  $f0, $f0 to convert that bit-pattern in $f0 from int to double.
They give an example:
    addi $t1, $0, 1    # Integer 1
    mtc1 $t1, $f1
    cvt.s.w $f1, $f1      # $f1 = single-precision float 1.0
    add.s $f3, $f1, $f2   # FP add to $f2

If you have a 64-bit timestamp in two 32-bit halves, you're going to have to convert it in 2 parts and add, or combine into a 64-bit integer in an FP register if MIPS has an instruction for that.  Or is mtc1.d copying a 64-bit integer register?  (I haven't used MARS, I wasn't sure if it only emulated classic MIPS, or if it emulated 64-bit MIPS III or whatever revision of the ISA 64-bit was added.)
Comment: I managed to do it by doing the calculations using some 64 subroutines I created. I only needed to add and subtract to calculate time difference. But you were right on the conversion part. Once I did the calculations, when I moved to float registers I needed to convert the value to doubles.
Comment: @Romeo: You mean you just used 64-bit integer math?  That sounds sensible.  `double` can't exactly represent every possible 64-bit integer, only up to 2^53.  Beyond that, the distance between two representable `double` is 2, then 4, then 8, as the exponent field grows.
Comment: Basically yeah. That was actually another problem I had: i was moving the value returned by the system time into the double, which was to large for MIPS to see it correctly. But if I moved only the time difference, it was seen ok because this was actually at a reasonable size (I presume this means that it was < 2^53).


Express the following power series as a raional function

Question: Consider the following power series:
$f(x) = \sum\limits_{i>=1} 2^{i-1}x^{3i}$ = $\ x^3 + 2x^6 + 4x^9 + ...$
$g(x) = \sum\limits_{i=2}^{20} f(x)^{i}$
Express both f(x) and g(x) as rational functions, ie p(x)/q(x) where P(x) and q(x) are polynomials.
How would I go about doing this? Is there some kind of algorithm or pattern I can follow?
Comment: The series defining $f(x)$ is geometric.  Do you know how to deal with those?
Comment: I can see that now when I change it into the form below. The formula for that is 1/(1-r) which does make sense to me. The limits on the summation are more difficult though. I can't find anywhere how that affects the geometric series formula.
Answer: Hints:
$$2^{i-1}x^{3i}=\frac12\left(2x^3\right)^i$$
So assuming
$$2|x|^3<1\;\;\text{(why?)}\;,\;\;\text{we get}\;\;\sum_{k=1}^\infty2^{i-1}x^{3i}=\frac12\frac{2x^3}{1-2x^3}$$
Comment: why is there a 2x^3 in the numerator? Is it because it starts at k=1 instead of k=0?
Comment: Yes: the first element in an infinite geometric series must appear in the denominator.


Custom entity api admin UI overview table how to add extra columns and operations? Drupal 7

Question: I've seen this: Custom entity operation links but it's for Drupal 8 and dealing with nodes whereas mine is a non-node type entity.
So how does one go about adding stuff to the row? I want to add custom operations and basically get control of it but I can't see where to start.
I've extended EntityDefaultUIController in the conventional way (like this). When you go the administrative UI we can debug and break in entity.ui.inc and see the following code snippets which seems to be where this gets invoked. But I've got a feeling that there's a quicker and easier way than adding extended versions of the already existing EntityDefaultUIController functions. But what holds the operations & additional column row information?
entity.ui.inc
within overviewTable(...) ...
foreach ($entities as $entity) {
  $rows[] = $this->overviewTableRow($conditions, entity_id($this->entityType, $entity), $entity);
}

... which leads us to the following function (same file)
protected function overviewTableRow($conditions, $id, $entity, $additional_cols = array()) {

and we get use of $additional_cols in the 4th (0th + 3 in array speak) parameter but as you can see it's not passed as a parameter above so how do you go about getting this additional information added into the overviewTable?
    // Add in any passed additional cols.
    foreach ($additional_cols as $col) {
        $row[] = $col;
    }

Answer: I figured out how do do this, and it, of course, isn't terribly straightforward...
You're on the right track, you just need to override the EntityDefaultUIController::overviewTable function in your own custom class. I don't think there's an easier way (since you're looking for one).
So, copy the the implementation of overviewTable from EntityDefaultUIController (in entity/includes/entity.ui.inc in the Entity API module) into your custom ui controller class and look for the calls to:
$this->overviewTableRow($conditions, entity_id($this->entityType, $entity), $entity);

...and add the $additional_cols parameter which should be an array populated with the extra data (which you can pull from the $entity object already populated in the foreach loop. So, do something like:
foreach ($entities as $entity) {
  $additional_cols = array($entity->someField, $entity->someOtherField);
  $rows[] = $this->overviewTableRow($conditions, entity_id($this->entityType, $entity), $entity, $additional_cols);
}

In addition to that you'd have to add the associated headers into the render array at the end of the overviewTable function like so...
$additional_headers = array('some field', 'some other field');

$render = array(
  '#theme' => 'table',
  '#header' => $this->overviewTableHeaders($conditions, $rows, $additional_headers),
  '#rows' => $rows,
  '#empty' => t('None.'),
);

...my guess is that you already figured out this much, but to answer your question, no, I don't think that there's an easier way. I hope this helps you, or someone else. ...or if someone knows this easier way, let me know too... =)
Answer: If you want to accomplish this cleaner and with less code, override the overviewTableHeaders and overviewTableRow functions (instead of overviewTable) in your controller class.
class CustomEntityDefaultUIController extends EntityDefaultUIController {

    protected function overviewTableHeaders($conditions, $rows, $additional_header = array()) {
        $additional_header[] = t('My Custom Field');
        $additional_header[] = t('My Other Custom Field');
        return parent::overviewTableHeaders($conditions, $rows, $additional_header);
    }

    protected function overviewTableRow($conditions, $id, $entity, $additional_cols = array()) {
        $additional_cols[] = $entity->my_custom_field;
        $additional_cols[] = $entity->my_other_custom_field;
        return parent::overviewTableRow($conditions, $id, $entity, $additional_cols);
    }

}


Mentally finding factors of an integer of up to three-digits.

Question: I'm looking for the easiest methods to find factors, not necessarily prime, of positive integers $<1000$, preferably mentally, but using pen and blank paper when required.
Although these techniques might be useful for a certain televised Numbers Game, I'm just looking for methods faster than trial division.
I take for granted full knowledge of the twelve by twelve multiplication tables, and recognition of primes up to $101$
This, with the addition of $7\cdot13=91$ should cover much of the factorisation up to two digits.
Notation
Using the idea of hundreds, tens and units, so $n=100H+10T+U$ is the number, I'll use $H,T,U$ for the individual digits,  $HT$ for the first two digits and $TU$ for the last two.
For example, $n=456$ gives $H=4$, $T=5$, $U=6$, $HT=45$ and $TU=56$
Some easy published divisibility tests
If $U=0$ then $10|n$
If $(TU)\equiv 0{\pmod{25}}$ then ${25}|n$
If $U=5$ then $5|n$
If $U\equiv 0{\pmod 2}$ then $2|n$
If $(H+T+U)\equiv 0{\pmod 9}$ then $9|n$
If $(H+T+U)\equiv 0{\pmod 3}$ then $3|n$
Merged published divisibility tests for primes $p=7$ to $47$
With $z$ taken from the following, if $(HT+zU)\equiv 0{\pmod p}$ then $p|n$
$$(p,z)$$
$$(7,-2)$$
$$(11,-1)$$
$$(13,4)$$
$$(17,-5)$$
$$(19,2)$$
$$(23,7)$$
$$(29,3)$$
$$(31,-3)$$
$$(37,-11)$$
$$(41,-4)$$
$$(43,13)$$
$$(43,-30)$$
$$(47,-14)$$
For some examples in the range, the test may need to be repeated on the result.
As $31^2=961$, the last few test are of limited use.
Alternative divisibility test for $11$
If $(H+U-T)=0$ or $11$ then $11|n$
Difference of two squares
Using $a^2-b^2\equiv(a+b)(a-b)$ helps in a few cases. For example,
$$899=900-1=(30+1)(30-1)=31\cdot29$$
$$91=100-9=(10+3)(10-3)=13\cdot7$$
$$391=400-9=(20+3)(20-3)=23\cdot17$$
My question
I was tempted to ask what other divisibility or factorisation techniques exist that are potential easier than trial division, but "easier" is subjective; so I questions is:.
What other mental divisibility or factorisation techniques exist for an integer up to three digits?
Clarification update 11 May 2018
Sorry, I don't feel I've sufficiently emphasised the importance of time, just assuming that easier was faster.
Full factorisation is ideal; partial factorisation is much better than nothing, so $663=3\cdot13\cdot17$ is best, but $663=3\cdot221$ is better than nothing.
Obtaining more than one small prime factor with one test is desirable, where the prime factors are obvious, as per the tests for $10,25$ and $9$, but a full list of all possible factors of $n$ is not needed.
Comment: For three digit numbers you only have to do 11 trial divisions to find factors (for the primes from 2 up to 31). If none of them divides your number, no number does (except 1 and the number itself, of course). Trial divisions for 2,3,5,7 and 11 are easy.
Comment: @YukiJ The OP wants to _find factors, not necessarily prime_. For instance, 6 is a factor.
Comment: @scaaahu Yes, but if we observe that 2 and 3 are factors in a number then their product $2\cdot 3 =6$ is necessarily also a factor. Hence, if you find the prime factors, you also found the remaining other factors.
Comment: @YukiJ Having a factor 9 implies having a factor 3, not the other way around.
Comment: @scaaahu True but if you know that 3 divides $n$ then you can also check if 3 also divides $n/3$. If so, 9 divides $n$. In the particular case with 9 you could even check if the sum of digits of $n$ is divisible by 9.
Comment: Some professional mental calculators memorized the factorization of small numbers up to 10,000.
Answer: As you have stated:
Checking a number is even will automatically give you the factor of $2$.
Summing the digits, if the digit sum is a multiple of $3$ or $9$, the number is also a multiple of $3$ or $9$.
Multiples of $5$ end in $5$, multiples of $10$ end in $0$.

For my extra method, let's consider $473$. It has no obvious factors based on those rules, so here I would use prime multiple subtraction. Start with $7$, the multiple of $7$ that ends in $3$ is $7\cdot9=63$, so subtract $63$ to get $410$. $41$ is not a multiple of $7$ or $9$, so neither are factors. Then consider $11$. $3\cdot 11=33$ so subtract $33$ to get $440$. $440=40\cdot 11$, hence we can see that $473=43\cdot 11$.

Note for $11$ that if you have $ab\cdot11$ , where $a,b$ represent the digits, the result is $a(a+b)b$, again to mean digits: e.g. $35\cdot11=385$. When $a+b>10$, it is harder to spot but still possible. What you should look for then is: $a(a+b-11)b$, and this is $(a-1)b \cdot 11$. E.g. for $528$, $5+8-11=2, \therefore 528=11*48$

If you can identify numbers as concatenations of multiples  of the same number, they will be a multiple of that number. E.g. $654$ contains $6$ and $54$, both of which are multiples of $6$, and so we can do $6\div6=1$, and $54\div6=09$, therefore $654\div6=109$
Comment: Thanks for your answer, which I've up-voted. I've used a similar method with numbers such as $721$.
Comment: Thanks for the upvote. Note that $721$ is $7\cdot103$, you can see this by the subtraction method, or notice that $7$ and $21$ are both multiples of $7$, and so we can simply divide both by $7$ for $1$ and $03$ and then put these back together. A different example might be $726$, we see $72=12\cdot 6$ and $6=1\cdot 6$, putting back together we get $121$.


can websphere application server 9 be installed side by side with 8.5.5?

Question: Can websphere application server 9 be installed side by side with 8.5.5 on the same developer box?
We want to be able to still continue maintaining our older J2EE projects.
Thanks,
Bert
Answer: Yes, the only restriction in this area is with some of the obscure separately installable "Edge components" bundled with some editions of WebSphere.  You will find that even the port assignment is coordinated across the two installs/versions.
Comment: Thank you. The profile creation did not go as you suggested, it wanted to create AppSrv01 which existed already. I had to change that to AppSrv09 and manually modify each of the port settings.


Chromonica (chromatic harmonica) notes relating to holes

Question: I have several chromonicas from the 50s/60s, and none seem to be 'standard'. There is only the one C/B hole in each octave, whereas it appears that standard includes two C holes (in a C instrument) next to each other. So it's blow/draw for C/D E/F G/A, and draw/blow for B/C.
They aren't be-bop or blues. classical, solo or minor tuned, and certainly not Richter, so what are they?
There's one which plays in C# when the button's out, and C when pushed in. It's stamped C, and may be 'Irish tuning', but with some delving, Irish tuned harmonicas drop from C to B when the button is used, so it maybe isn't that.
Using an interesting harminoca tag...
EDIT  I just can't believe it ! I checked again, and yes, it has two C notes in holes adjacent to each other! Been playing on and off for a very long time, and honestly thought there was only the one C. Perhaps as a kid I automatically by-passed the 'other C' each time, so didn't actively think it existed. Sorry to cause any confusion - I guess the question is now null and void - except for the backwards harmonica.
Not a complete idiot - I just help them out when they're short...
Comment: Could you be more specific about the harmonica models, and either be more specific about how they diverge from solo tuning (which holes play which notes) or map out the note layout?
Comment: Larry Adler professional; 64 chromonica; Chromonika III; Chromonica II deluxe; Chrometta 10.All have blow/draw - C/D, E/F, G/A and draw/blow B/C, all the way along.
Comment: _I just can't believe it ! I checked again, and yes, it has two C notes in holes adjacent to each other!!_ This is very disappointing...
Comment: _Irish tuned harmonicas drop from C to B_ - If it's tuned that way. I think the point of Irish tuning is to drop half a step - regardless of key. But C# is a weird key to start with. I see @Some_Guy gave you the answer anyhow.
Comment: @Stinkfoot - true, the idea of Irish tuning *is* to drop down into B. Reason given in Wiki is that a lot of Irish tunes are in G or D, but the relevance of *that* escapes me. What's B got to do with G or D??
Comment: _What's B got to do with G or D_ I don't know why B should be of such importance to those keys, no - but I don't know anything about Irish music either. I thought it said someplace that Irish music had a lot of minor notes, etc. That makes sense: you'd like to be able to drop down half a step from the root instead of having to having to work backwards with enharmonics, etc.
Comment: @Stinkfoot - There's a lot of Irish tunes in Dorian and Mixolydian, (and Aeolian), but how that translates back to B major, I don't know. In fact, from where I see it, it doesn't. Another question spawned?
Comment: @Tim as I've said before, don't use wikipedia for a reference about harmonica, there is misinformation and information in equal measure.  In regards to "Irish Tuning".  I've never heard of it.  It may be a legitimate thing, or it may just be something that one guy uses in one place and decided to go down in history by adding it to the wiki.  Wikipedia is good for some things but for harmonica it is an absolute joke.
Comment: @Tim - I don't see how it has anything to do with B major, but if you're playing C Dorian, Mixolydian or Aeolian, being able to quickly drop down a half step to Bb or Eb or Ab just by hitting the slide on that hole is cool.
Comment: @Tim - There are chroms today in a lot of different keys. One of the most popular seems to be one that's tuned to B - I surmise it's because by moving the slide you're in C. I was thinking of getting one: If your default mode of playing is with the slide in, then you've got "Irish tuning" - great for the modes you mentioned. Or you coul flip it over, like your weird C# chrom - then you'd have authentic "irish tuning".
Comment: @Some_Guy - "Irish tuning" is legit. See: [**_Irish Fiddle Tuning...At this stage, knowledge of the Eddie Clarke tuning (aka Irish tuning) is common..._**](http://eugeneryan.blogspot.com/2014/11/overview-i-came-up-with-tuning-few_14.html) .
Comment: @Tim: [**_Irish Fiddle Tuning...At this stage, knowledge of the Eddie Clarke tuning (aka Irish tuning) is common..._**](http://eugeneryan.blogspot.com/2014/11/overview-i-came-up-with-tuning-few_14.html) .
Comment: _and honestly thought there was only the one C_  On a standard chrom in C major there are actually 3 C's. Blow on hole 4 and slide and you get B#, or C, depending on how you use it.
Answer:
So it's blow/draw for C/D E/F G/A, and draw/blow for B/C.

This seems to fit with the standard tuning for a chromatic, "solo" tuning, which is the following repeated pattern:
<code>       1  2  3  4  5  6  7  8  9  10… etc.
       ------------------------------------
blow: |C |E |G |C |C |E |G |C |C |E...etc.
draw: |D |F |A |B |D |F |A |B |D |F...etc
       ------------------------------------
</code>
In which the blow note C is found repeated, as the end of one octave, then the beginning of the next.
On a chromatic harmonica this therefore results in 3 ways to play C, the 4 blow, 5 blow, and the 4 draw with the slide in, and 2 "C holes": one a C/D hole and the other a C/B hole.
A tuning without a repeated C would be like one of the following:
"Bebop":
<code>       1  2  3  4  5  6  7  8  9  10… etc.
       ------------------------------------
blow: |C |E |G |Bb|C |E |G |Bb|C |E...etc.
draw: |D |F |A |B |D |F |A |B |D |F...etc
       ------------------------------------
</code>
F6/G6  (starting from -2 reflects the easiest way to retune from a stock harp: from an F chromatic)
<code>     (-2)(-1)1  2  3  4  5  6  7  8  9  10… etc.
       ------------------------------------
blow: |F |A |C |D |F |A |C |D |F |A |C |D...etc.
draw: |G |B |D |E |G |B |D |E |G |B |D |E...etc.
       ------------------------------------
</code>
As for the C# harp, it may simply be that the slider is on backwards, so in/out is reversed for all notes, does this fit with your experience?  Is the blow chord a Db/C# major chord and the draw an Eb/D# minor 6 chord?)
Comment: Having a very off day today! Looking as closely as I should have before posing the question, the 'backwards' one does appear to have the slide in the opposite way to the other harmonicas, which would go along with your suggestion.


Multipeer Connectivity Error "Send BINDING_REQUEST failed" in iOS10

Question: I'm seeing the following errors in my MPC app in iOS 10 and I'm looking for some help explaining them.  After the peers are connected, several of the errors below pop up.  The peers end up connecting, but it is slower than in iOS 9 (appears that the event causing the error messages are occurring on the main thread).  These errors do not appear in the app when running on an iOS < 10.
<code>[ViceroyTrace] [ICE][ERROR]     Send BINDING_REQUEST failed(C01A0041).
Not in connected state, so giving up for participant [47CD8292] on channel [0].
</code>
Any input would be greatly appreciated!
Answer:
the reason and meaning of the error

NAT
In order to explain the reason and meaning of error, we have to start with NAT (you can skip this part if you are familiar with it).
NAT is a way to mapping same 'global' IP address for multiple devices in the same local network, i.e. multiple devices share same address (may be in different time, may be using different port -- NAPT), in which way we can save a lot of 'global' address and ease the depletion of ipv4 address. And also because of this, devices's local address can only be used in LAN, not outside. The datagram want to send outside will go through NAT device (always a router) which will modify the address in header to global address. One more point is devices in the different LAN may use same IP address.
<code>                 |
                 | /------------  'Global'
          X1':x1'|/               Address
           +------------+
           |    NAT     |
           +------------+
                 |
                 | /------------  Local
             X:x |/               Address
             +--------+
             |        |
             | Agent  |
             |        |
             +--------+
</code>
ICE
Now, we want to make to peer communicate directly, so we have to know peer's address. But as we know, the use of NAT make the address of devices just a local address which can't be used outside the Internet and fail to communicate using it.
The purpose of ICE is to discover which address the peer should use to communicate directly with other peer.
Gather Candidates Addresses
The first phase it to gather candidates addresses:

address of its interface
translated addresses on the public side of a NAT (SERVER REFLEXIVE CANDIDATES)
(optional): addresses on TURN servers (RELAYED CANDIDATES)

In order to get the public side address, device will send a 'Binding request' to a public server (called STUN server, outside LAN) and server send back address called 'Binding response'.
Connectivity Checks
When devices has the addresses they have, they will send to other peer  over the signaling channel. When peer (we call it 'R') receive list of addresses from our device (we call it 'L'), R will collect its own addresses and respond its own list. At the end of this process, it result in CANDIDATE PAIRS.
To see which pairs work, each agent schedules a series of CHECKS with 'Binding request' & 'Binding response'.
<code>L                        R
-                        -
STUN request ->             \  L's
          <- STUN response  /  check

           <- STUN request  \  R's
STUN response ->            /  check
</code>
Conclusion
So in conclusion, possible reasons before more details:

fail to connect to STUN server;
the normal failure when testing address pair;

Suggestions:

check the info about the phases of ICE to know the differences of ICE implementations between ios10 and others.
This thread is some discussions about the bug of mpc, which may inspire you.

Ref:

ICS RFC
NAT


I got $S = \bigl\{\tfrac{1}{n}\bigr\}$ where $n \in \mathbb{Z} \setminus \{0\}$ its limits should be -1, 1, which is not true. Where is the mistake?

Question: Consider set $S = \bigl\{\tfrac{1}{n}\bigr\}$ where $n \in \mathbb{Z} \setminus \{0\}$. This makes $S$ an infinite bounded set with bounds $-1$ and $1$. So according to Bolzano–Weierstrass theorem, its limits should be $-1$, $1$, which is not true. Am I making some mistake here?
Edit: By limit points, I mean elements of derived set of $S$.
Comment: How are you applying BW?
Comment: Please let the title specificially represent the question.
Comment: What is a limit of a set ?
Comment: Read the theorem statement carefully. What is your sequence? (Not the set of numbers $S$, but the sequence itself, i.e. the assignment for each $n \in \mathbb{N}$ of a number $x_n \in S$)
Comment: @dmh In a book, I have seen a sub theorem under Bolzano–Weierstrass theorem stating "Every infinite bounded set has the greatest and the smallest limit points, i.e. the derived set of an infinite bounded set attains its bounds.". By that logic, -1 and 1 should be in the derived set right because they are bounds of the original set?
Answer: Bolzano-Weierstrass theorem says that any infinite bounded set in $\mathbb{R}^n$ has an accumulation point, which is not the same thing as a boundary point. Your example has an upper and lower boundary of $\pm 1$ but these are not accumulation points; however $0$ is an accumulation point of $S$ since any open interval containing the origin contains infinitely many points of $S$. It does not violate Bolzano-Weierstrass if the accumulation point lies outside of $S$, it just has to exist.
Comment: The derived set of $S$ consists of only one point, $0$. This is set is bounded above and below by $0$, which is in the set, this example checks out. You are confusing the bounds of the derived set $S'$ being contained in $S'$ with the bounds of $S$ being contained in $S'$; the latter is not necessarily true as your example shows.
Comment: In a book, I have seen a sub theorem stating "Every infinite bounded set has the greatest and the smallest limit points, i.e. the derived set of an infinite bounded set attains its bounds.". By that logic, -1 and 1 should be in the derived set right because they are bounds of the original set? Or let me know If there is some gap in understanding.
Comment: Okay, it is talking about bounds of S', now I am getting this. Thanks for the explanation.


Vision Transformer models in vit-keras

Question: I have used vit_b32 and vit_b16 models in vit-keras. What are the other available models and their input image sizes in vit-keras? Are there any combined models (ResNet + Vit) available?
Thanks
Answer: The other two options are vit_l16 and vit_l32. Each model is created using the build_model method, and the image size is checked in the build_model method. image_size must be a multiple of patch_size (patch_size is 16 for vit_b16 or vit_l16 and 32 for vit_b32 or vit_l32).

Vision Transformer models in vit-keras


Uniformity inducing Topology

Question: If $\mu$ is any covering uniformity on a set $X$ inducing the topology $\mathcal{T}$ on $X$ and if $(\mathcal{B_n})_{n \in \mathbb{N}}$ is a normal sequence of open covers of $X$ then $\mu \cup \{\mathcal{B_1},\mathcal{B_2}, \mathcal{B_3}\ldots\}$, being a normal family of open covers, is  a subbase for a uniformity , say $\nu$. How to show that $\nu$ generates the same topology $\mathcal{T}$ on $X$ ?
Comment: are you NK on Topology atlas?
Answer: The uniformity $\nu$ can be described as
$$\mathcal{U} \in \nu \text { iff } \exists \mathcal{V} \in \mu \exists n: \mathcal{B_n} \wedge \mathcal{V} \prec \mathcal{U}$$.
as always with subbases, as I also used in my other answer, e.g.
Now if $O$ is open w.r.t. $\nu$, then let $x \in O$. Then there is some cover $\mathcal{U} \in \nu$ such that $\operatorname{st}(x,\mathcal{U}) \subseteq O$. Find $\mathcal{V}$ and $\mathcal{B_n}$ as in the above characterisation.
Then (by standard facts about stars of covers):
$$ \operatorname{st}(x,\mathcal{V}) \cap \operatorname{st}(x,\mathcal{B_n}) = \operatorname{st}(x, \mathcal{B_n} \wedge \mathcal{V}) \subseteq \operatorname{st}(x,\mathcal{U})$$
The left hand side is open in $\mathcal{T}$ (as $\mu$ induces it, and as the covers $\mathcal{B}_n$ are open covers w.r.t. $\mathcal{T}$). This shows that $x \in \operatorname{Int}_{\mathcal{T}}(O)$, and as this holds for all $x \in O$, $O \in \mathcal{T}$. So $\mathcal{T}_\nu \subseteq \mathcal{T}$.
$\mathcal{T} = \mathcal{T}_\mu \subseteq \mathcal{T}_\nu$ is obvious as $\mu \subseteq \nu$, and so $\mathcal{T} = \mathcal{T}_\mu = \mathcal{T}_\nu$.

Uniformity inducing Topology


voiceschanged event not fired in Safari

Question: As far as I can tell, the voiceschanged event doesn't fire in Safari, either on macs or in iOS. Also odd, it doesn't seem to fire in Chrome on iOS either, but I'm assuming Chrome on iOS uses the same JavaScript engine as Safari.
Here's a demonstration that I used to verify: http://jsbin.com/gosaqihi/9/edit?js,console (taken from Getting the list of voices in speechSynthesis of Chrome (Web Speech API))
I've also tried it using addEventListener:
speechSynthesis.addEventListener("voiceschanged", function () {
    var voices = speechSynthesis.getVoices(),
        keys = Object.keys(voices[0]),
        i, j;

    document.write("

");

    for ( i = 0; i < keys.length; i++ ) {
        document.write("" + keys[i] + "	");
    }

    document.write("
");

    for ( i = 0; i < voices.length; i++ ) {
        document.write("
");
        for ( j = 0; j < keys.length; j++ ) {
            document.write("" + voices[i][keys[j]] + "	");
        }
        document.write("
");
    }

    document.write("
");
}, false);

Both approaches (onvoiceschanged, addEventListener) work fine in Chrome for Windows, Android, and Mac, but fail on Chrome for iOS and Safari for Mac and iOS. As far as I can tell, Safari simply doesn't fire the voiceschanged event.
Complicating things, I don't actually own any Apple devices, so I've had to figure this out by having friends try things.
Is there something special I need to do in Safari to get the list of voices? Or is the Speech Synthesis API simply not (fully) implemented yet?
Answer: Apparently Safari only has partial support for the Web Speech API so far.
What you could do for your code to work in different environments is to detect if onvoiceschanged exists in speechSynthesis. If not, you can just call speechSynthesis.getVoices() without listening for onvoiceschanged.
function doVoices() {
    var voices = speechSynthesis.getVoices(),
    // ...
}

if ('onvoiceschanged' in speechSynthesis) {
    speechSynthesis.onvoiceschanged = doVoices;
} else {
    doVoices();
}

Comment: Thanks. I wish this was better documented somewhere. :/
Comment: With this answer, we can select voice in Safari because only setting 'lang' was not enough. Thank you!

voiceschanged event not fired in Safari