Can I use requirejs to load modules in typescript code?

Question: I'm using typescript and requirejs.  I want to import my library code as modules, to avoid making everything an ambient global.  My problem is that any use of import or export in a typescript file turns the entire file into a module.  In the case of my application code, this means it can't be invoked directly.
Here's a sample app.
index.html
<!DOCTYPE html>

        <title>My Test App</title>

tsconfig.json
{
    "compilerOptions": {
        "module": "amd",
        "target": "es5",
        "noImplicitAny": false,
        "sourceMap": false
    }
}

greeter.ts
export function greet(name: string) {
    alert(`Hello ${name}`);
}

app1.ts
import { greet } from './greeter';
greet('alice');

app2.ts
import { greet } from './greeter';
greet('bob');

tsc runs with no problem, but here's one of the files I get as output.
tsc output: app1.js
define(["require", "exports", './greeter'], function (require, exports, greeter_1) {
    "use strict";
    greeter_1.greet('alice');
});

That doesn't work.  From require.js

Be sure to load all scripts that call define() via the RequireJS API.
  Do not manually code script tags in HTML to load scripts that have
  define() calls in them.

So how can I convince the typescript compiler to produce output without a define() call in it.  In app1.ts, I don't intend to define a module, just consume other modules.  require() seems more appropriate for that.  Is there a way to make import compile to require()?
Answer: If you have a single module kicking off everything that needs to load for your page, you can use data-main. If you need to kick off the loading with more than one module, then use require to load the modules:

You may be used to always passing a single string argument to require, but this is AMD. The native AMD require takes an array of dependencies as the first argument, and an optional callback as the 2nd.
If you are using require.config you can use the deps option for the same purpose:

There's currently no way to get tsc to output require instead of define. I would not hold my breath waiting for such a feature to be added because there are readily available ways to get the same end results that such a feature would allow.
Answer: Fix
From the docs you already found:

Be sure to load all scripts that call define() via the RequireJS API.

Also from the docs start page : http://requirejs.org/docs/start.html

and only reference require.js with a requirejs call like so to load your script:

^ this is the script tag that should load your application entry point.
More

So how can I convince the typescript compiler to produce output without a define() call in it.

Yes. But if you want to use requirejs, then this is the wrong question to be asking. The fix is as I mentioned, i.e. use the correct script tag.
Comment: Thanks but this isn't ideal.  My example has two entry points and there's only one data main. If not require js, is there some other way to use import in browser compatible typescript?


msal plugin is undefined

Question: I follow the git post below to implement MSAL in Cordova iOS application but it seems like cordova plugin is null.
https://github.com/wrobins/cordova-plugin-msal
This is always null
let isAvailable = typeof(cordova.plugins.msalPlugin) !== "undefined";

I get this error
Cannot read properties of undefined (reading 'msalPlugin')
Not allowed to launch '' because a user gesture is required.
Comment: You have to check msalPlugin present in plugins folder and confirm Cordova.js present in www folder.
Answer: Yesterday I have face some issue, I am using out systems and integrated this plugin and try to run o browser then getting some error
So For Resolution
I have installed my app on android phone then run application. It is working fine.
In short, you need to install app on mobile either it is iOS/android phone Because cordova is only available on phone not on browser

msal plugin is undefined


prove this inequality $a^n>b^n+c^n$

Question: We know a,b and c are positive and
 $a^2=b^2+c^2$
How we can conclude this inequality:
$a^n>b^n+c^n$  , $n>2$
I tried Binomial Theorem  but I can't prove this.
Thanks
Comment: Hi matinhabi. Your question is very interesting, but it would be very useful if you had more details (what already do you  have tried, your efforts, where you found this question, and so on). This will help a lot the community helping you to find your way toward the solution!
Comment: My teacher in high school give it to me.
Comment: what was the topic your teacher was teaching you when he/she asked this question?
Comment: He teaches Geometry
Answer: $$a^n=(a^2)^{\frac{n}{2}}=(b^2+c^2)^{\frac{n}{2}}>b^n+c^n$$
the inequality is equivalent to $(b^2+c^2)^n>(b^n+c^n)^2$ - this is not hard to prove by Newton's binomial formula
Comment: Can you continue? I tried Newton's binomial formula but can't do anything
Comment: $n>2\implies(b^2+c^2)^n>b^{2n}+n(b^2c^{2n-2}+b^{2n-2}c^2)+c^{2n}$ by Newton. now apply $x+y\ge 2\sqrt{xy}$ for the middle part and you're done!
Comment: How about the case where $n$ is not an even integer?
Answer: If $n=2m$ is even, then this is straightforward:
$$ a^n=(a^2)^m=(b^2+c^2)^m> b^{2m}+c^{2m}=b^n+c^n$$
If $n>2$ is odd, then since $n-1$ is even it follows that
$$ a^{n}=a\cdot a^{n-1}\geq a(b^{n-1}+c^{n-1})$$
using either equality if $n-1=2$, or what we have shown above if $n-1>2$.
Finally, $a^2=b^2+c^2$ with $a,b,c>0$ implies that $a>b$ and $a>c$, hence
$$ a(b^{n-1}+c^{n-1})>b\cdot b^{n-1}+c\cdot c^{n-1}=b^n+c^n$$
Comment: Can we use induction?
Comment: Probably, but it's not necessary
Answer: $a^2=b^2+c^2\iff 1=(\frac ba)^2+(\frac ca)^2$ and clearly $\frac ba <1$ and $\frac ca <1$. Hence $$1=(\frac ba)^2+(\frac ca)^2>(\frac ba)^3+(\frac ca)^3>(\frac ba)^4+(\frac ca)^4>......>(\frac ba)^n+(\frac ca)^n$$
Thus $$1>(\frac ba)^n+(\frac ca)^n\iff a^n>b^b+c^n$$

prove this inequality $a^n>b^n+c^n$


Unlimited balls to $t$ cells with conditions

Question:
Assuming an unlimited number of balls to be put into $t$ cells, such that each cell doesn't contain more than 2 balls - an empty cell will contain to balls, and a full cell will contain 2 balls. In how many ways can we put the balls in the cells such that the number of full cells will be even and the numer of empty cells will be odd ?

Attempt -
I thought about doing a double sigma, but i am not sure how to approach the problem and if my counting is even right -
$$\sum_{k=0}^t \sum_{n=0}^t \binom{t}{2k+1}\binom{t}{2n}$$
I know that this is not true, What do you think ?
Comment: If $2k+1$ cells are empty then $t-2k-1$ can be used to carry $2$ balls. Not $t$ as you seem to think. So you get terms like $\binom{t}{2k+1}\binom{t-2k-1}{2n}$
Answer: A summation of trinomial coefficients:$$\sum_{k\in\mathbb Z}\sum_{n\in\mathbb Z}\binom{t}{2k+1,t-2k-2n-1,2n}\tag1$$
Here the term is taken to be $0$ if at least one of $2k+1$, $t-2k-2n$ and $2n$ takes a value that is not in $\{0,1,\dots,t\}$
You can also write $(1)$ as:$$\sum_{k\in\mathbb Z}\sum_{n\in\mathbb Z}\binom{t}{2k+1}\binom{t-2k-1}{2n}$$
where we use the convention that for nonnegative integer $n$ and integer $k$ we have $\binom{n}{k}=0$ if $k\notin\{0,\dots,n\}$
Answer: The simplest form of the answer I could come up with is:

$$\tfrac{1}{4}(3^t-(-1)^t)\tag{Answer}$$

assuming the cells are distinct but the balls are not.
Which I arrive at through the exponential generating function
$$e^x\sinh(x)\cosh(x)\tag{1}$$
We see that
$$\sinh(x)=1+\frac{x^2}{2!}+\frac{x^4}{4!}+\cdots$$
has even powers of $x$ and so coefficients of $x^k/k!$ represent the possible number of ways of having even full cells.
Then
$$\cosh(x)=\frac{x^1}{1!}+\frac{x^3}{3!}+\frac{x^5}{5!}+\cdots$$
has odd powers of $x$ and so represents the number of ways of having odd empty cells.
Finally
$$e^x=1+\frac{x^1}{1!}+\frac{x^2}{2!}+\cdots$$
represents the possible numbers of ways of having any number of cells with a single ball.
The coefficient of $x^t/t!$ in $e^x\sinh(x)\cosh(x)$ therefore gives the required count.
Well, since $\sinh(x)=(e^x-e^{-x})/2$ and $\cosh(x)=(e^x+e^{-x})/2$ our exponential generating function $(1)$ becomes:
$$\begin{align}e^x\sinh(x)\cosh(x)&=\tfrac{1}{4}e^x(e^x-e^{-x})(e^x+e^{-x})
\\ &=\tfrac{1}{4}(e^{3x}-e^{-x})\end{align}$$
taking the $x^t/t!$ coefficient:
$$\begin{align}[x^t/t!]e^x\sinh(x)\cosh(x)&=[x^t/t!]\tfrac{1}{4}(e^{3x}-e^{-x})\\&=\tfrac{1}{4}(3^t-(-1)^t)\end{align}$$
which is our result at the top.
Answer: The first problem is that your first summation index should only go up to $\lfloor \frac{t}{2} \rfloor - 1$, not up to $t$. The second problem is that if you have chosen some cells to be empty, you can't choose them again to be full. So you get
$$ \sum_{k=0}^{\lfloor \frac{t}{2} \rfloor-1} \sum_{n=0}^{\lfloor \frac{t-2k-1}{2} \rfloor} {t \choose{2k+1}} {t-2k-1 \choose{2n}}.$$


Godot: exported boolean variable is always false

Question: I have a problem with an exported set of boolean variables, flags to enable an Area2D feature:
tool

extends Area2D

signal direction_changed

export(bool) var allow_right
export(bool) var allow_left
export(bool) var allow_up
export(bool) var allow_down

var controlled_component = null

var directions: PoolVector2Array
var direction: Vector2

func _init():
    init_directions()

func init_directions():
    print_debug(allow_down, allow_left, allow_right, allow_up)
    directions = []
    if(allow_right):
        directions.append(Vector2(1,0))
    if(allow_down):
        directions.append(Vector2(0,1))
    if(allow_left):
        directions.append(Vector2(-1,0))
    if(allow_up):
        directions.append(Vector2(0,-1))

and this results in showing the flags in my Scene inspector:

what I don't get is why if I flag a couple of them like this:

why the print_debug statement results in this:
FalseFalseFalseFalse
Shouldn't two of the bool variables be set to True?
Am I missing something?
Answer: You are using a tool script, which runs inside the IDE. Therefore the "_init()" function (where you call "init_directions()" with print_debug) is called when you open a scene with this script for the first time. When you make a change in the inspector, the change will be applied if you save, close the scene and open it again.
Comment: Thanks! It was my fault, I should have used the _ready() method, not the _init() one


Exchange 2010 suppress Get-MailboxStatistics warnings

Question: How do I suppress warnings from Exchange 2010's PowerShell Get-MailboxStatistics cmdlet?
I've tried both of these options:

Get-MailboxStatistics -WarningAction SilentlyContinue
Get-MailboxStatistics -ErrorAction SilentlyContinue

However I still get this warning output to the console about users that's haven't logged onto their mailboxes:

WARNING: The user hasn't logged on to
  mailbox ...[snipped]..., so there is
  no data to return. After the user logs
  on, this warning will no longer
  appear.
Comment: I also tried $WarningActionPreference = "SilentlyContinue" --This will set all warning messages to silent.  Looks like something is broken.

Looks like there is a bug.
https://connect.microsoft.com/PowerShell/feedback/details/541500/warning-verbose-and-debug-streams-do-not-respect-action-preferences-the-way-they-should
Comment: @st3v3o - why not make that an answer and get set up for some bounty?
Comment: good call..but I'm not sure I really full answered the question...but worth a shot :P
Comment: oh I didn't realize you answered the question sorry Kev.
Answer: I also tried $WarningActionPreference = "SilentlyContinue" --This will set all warning messages to silent. Looks like something is broken. Looks like there is a bug.
https://connect.microsoft.com/PowerShell/feedback/details/541500/warning-verbose-and-debug-streams-do-not-respect-action-preferences-the-way-they-should
Comment: FWIW I was doing some additional testing and just running Get-MailboxStatistics -Database  will output all of the users and system boxes that are listed.  It will however skip over user accounts that have no statistical data to output (without displaying a warning)
Comment: +1 You'll probably win this, but I'll leave to run until the end of the bounty before awarding.
Answer: I've been playing with this one, trying to recreate the issue (I'm on Exhcange 2007, though, so this may make a difference. I'm also pretty new to powershell). Starting with a new mailbox, "Testy McTest":
>get-variable |where { $_.Name -match "Preference" }

Name                           Value
----                           -----
ConfirmPreference              High
DebugPreference                SilentlyContinue
ErrorActionPreference          Continue
ProgressPreference             Continue
VerbosePreference              SilentlyContinue
WarningPreference              Continue
WhatIfPreference               False

I can run the following:
>Get-MailboxStatistics "Testy McTest"
WARNING: There is no data to return for the specified mailbox 'Testy McTest', because it has not been logged on to.
>Get-MailboxStatistics -WarningAction SilentlyContinue "Testy McTest"   (No Output)
>Set-Variable WarningPreference SilentlyContinue
>Get-MailboxStatistics "Testy McTest"   (No output)
>

This seems to work as normal. It might be worth mentioning that the variables for Error and Warning actions are actually ErrorActionPreference and WarningPreference. Not sure why they differ like that.
As a workaround for the specific command in the question, you could qualify the output, with something like:
>Get-MailboxStatistics |where { $_.LastLogonTime }

Which seems to list only those mailboxes that have a logon time.
Comment: Looks like things are slightly different in the Exchange powershell way of doing things between 2007 and 2010 ...I tried your above setting and still get output with the EMS for 2010.
Comment: @st3v3o - yep same here.


Opening files in pygame error

Question: I just can't figure out the problem. So i'm making a game and im using money to buy things in the game and this doesn't seem to be working. I try  to write the new spent money in the .txt file and i just get an error.
with open("money.txt", "r") as rm:
game_money = rm.read()
with open("money.txt", "w") as fm:
fm.write(str(game_money))

def Function():
            ............
            slowdown_price = 20
            elif action == "buy_slowdown":
            if game_money >= 20:
                time.sleep(0.5)
                game_money -= slowdown_price
                slowdown_powerup += 1
                with open("money.txt", "w") as wm:
                    wm.write(str(game_money))

I get the following error:
TypeError: unsupported operand type(s) for -=: 'str' and 'int'

Comment: what is `slowdown_price`? `game_money` looks like it's a string. you still have indentation errors
Comment: what error are you getting? Can you correct your indentation errors?
Comment: i tried everything converting integers to strings.. simply doesn't work.
Comment: always add in question **FULL** error message - there are other usefull information - ie. which line makes problem, etc.
Comment: ForceBru I tried every thing........ please help. i'm scratching my brain for a few days here
Answer: You are using Python 2, which will happily compare integers with strings, so if game_money >= 20: works fine. However, you can't subtract an integer from a string, so game_money -= slowdown_price fails. Convert that value to an integer (or float) after you read it in:
game_money = int(rm.read())

or
game_money = float(rm.read())

If you use floating-point numbers, keep in mind that they aren't exact, so exact comparisons with == and != aren't reliable.
Comment: I'm not using python 2 im using python 3.4 but this seems  to work just fine thanks.
Comment: @StrozeR - No you're not. If you were using Python 3, there would be an error when you tried to see if a string was more than an integer.
Comment: Im positive that i use Python 3.4 compiler
Comment: @StrozeR - I'm sorry, but that isn't possible, given the traceback. Try adding `print(__import__('sys').version)` somewhere in your code, and check the output.
Comment: I get the output : 3.4.4 (v3.4.4:737efcadf5a6, Dec 20 2015, 19:28:18) [MSC v.1600 32 bit (Intel)]
Comment: @StrozeR - And are you doing that in a script, in the exact same way that you are running the current script? There is literally no way for Python 3 to be successfully doing `if game_money >= 20:` with `game_money` being a string, and then failing on `game_money -= slowdown_price` two lines later.
Comment: @StrozeR - Do you have Python 2 installed?
Comment: @StrozeR - Look, there's no way for your posted code to be successfully processing that line with Python 3. It is a failing error.
Comment: Try it for yourself.
Comment: @StrozeR - I have. See [here](http://stackoverflow.com/questions/3270680/how-does-python-compare-string-and-int). Only Python 2 will process that line without a problem.
Answer: Reading from a file results in a string. That means that game_money is a string that contains the characters of a number, e.g "30".
You should cast the string to an integer:
game_money = int(rm.read())

Do take note that this could fail if the file does not contain just a number, but other non-numerals.
Answer: It seams that you try to substract number slowdown_price from text game_money. You have to convert game_money to number first. ie.
game_money = int(game_money)

Opening files in pygame error


Firefox and safari can't create fetch request of 'CORS' mode

Question: My app is work perfectly in chrome when i try to create a cross origin request.
but in firefox i get following error:

'mode' member of RequestInit 'CORS' is not a valid value for
  enumeration RequestMode.

i create my request header like following:
    this.requestParameter = {

        method: this.config.method,
        mode: 'CORS',
        headers: new Headers(headerConfig)
    }

    this.request = new Request(url,this.requestParameter);

how can i solve this problem in firefox?
Answer: just change your request mode to 'cors' mean lower case the word as following:
this.requestParameter = {

    method: this.config.method,
    mode: 'cors', //change this
    headers: new Headers(headerConfig)
}

this.request = new Request(url,this.requestParameter);


Alter an existing form

Question: We just starting out with Drupal 8 and very quickly we ran into our first problem.
How should I alter an existing form in Drupal 8?
We need to alter the save method for the node form to do a redirect to an other page. We want to alter the node form to become something like a multistep form. After the user creates new content they get redirected to a new form (we created) to get some more information.
We solved our problem implementing hook_entity_type_alter().
function mymodule_entity_type_alter(&$entity_info) {
  $handlers = $entity_info['node']->get('handlers');
  $handlers['form']['default'] =    'Drupal\mymodule\Form\MyExtendedNodeForm';
  $handlers['form']['edit'] = 'Drupal\mymodule\Form\MyExtendedNodeForm';
  $entity_info['node']->set('handlers', $handlers);
}

We then created a new form class that extends the node form and alter the save method.
class MyExtendedNodeForm extends NodeForm {

    public function save(array $form, FormStateInterface $form_state) {
      parent::save($form, $form_state);
      $node = $this->entity;
      $form_state->setRedirect('entity.regions.add_form', ['nid' => $node->id()]);
  }

}

This works perfectly, but is it good? If another module does the same, our code does not get executed anymore.
Comment: Drupal 8 still supports `hook_form_alter()`. If you just need to redirect the form, it's enough to add a form submission handler that does the redirect.
Comment: @kiamlaluno That should be the answer I think :)
Comment: @Berdir That alone would not be much helpful, I am afraid: My knowledge of Drupal 8 is pretty limited. Plus, the OP should make clear what "alter the `save()` method" actually means. Does it mean changing the way data is saved, or just do a redirect? In the first case, the answer is more complex.
Comment: @kiamlaluno Thx for the answer. In this case we only need to do a redirect after the save() so your answer should work. But I was also interested in how to alter other things in the form in the right Drupal 8 way. For example change how it is saved, or add fields to the form.. etc..
Answer: I had to do the exact same thing yesterday, and I am still looking for a more Drupal 8 way to do this, but haven't found it. I ended up doing it this way:
<?php

/**
 * @file
 * This is my module.
 */

use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Implements hook_form_alter().
 */
function MODULE_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'user_form') {
    $form['actions']['submit']['#submit'][] = '_MODULE_goto';
  }
}

/**
 * Make the form go to route.id.
 */
function _MODULE_goto($form, FormStateInterface $form_state) {
  $form_state->setRedirect('route.id');
}

I am still very interested in doing it a different way, my module looked so clean without the .module file :).
Answer: I'm using Drupal 8.1.1 and was trying to redirect users after they modified their account, i.e. clicking the Save button on the /user/edit page. I initially tried this:
/**
 * Implements hook_form_alter().
*/
function MODULE_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'user_form') {
    $form['#submit'][] = '_MODULE_goto';
  }
}

While that worked for the user_login_form, it would not work for user_form. For user_form I had to use
$form['actions']['submit']['#submit'][] = '_MODULE_goto';

I hope that helps others who stumble across the same problem!
Answer: Well I wanted to alter the site_information_settings form to add some fields.
As you, I had choice between

hook_form_alter (or hook_form_FORM_ID_alter)
extend the original form class

Wanted to make some OOP so I started writing a route subscriber service altering the system.site_information_settings route's _form attribute.
Then in my new class extending the SiteInformationForm,
after the fields & their validators have been added and the submit function extended I felt exactly the same way as you...
Now what if another module rewrites the form's route as well to use its own class ?
Back to the beginning, I had choice between two options... seems like I picked the wrong one.
hook_form_alter / hook_form_FORM_ID_alter seem to be the best way to alter an existing form.
Answer: After checking this issue, this is what I've found that should suit your case :
/**
 * Implements hook_entity_type_alter().
 */
function mymodule_entity_type_alter(&$entity_info) {
 $entity_info['node']->setFormClass('edit','Drupal\mymodule\Form\CustomNodeForm');
}

Answer: It looks like what you want to do, it not really to alter the save method, but to change the redirect when a node is saved.
In this situation, doing much like Drupal 7, hook_form_alter along with a custom submit handler (on the form or the button, depending on the form and requirement) would be a good solution.
What you describe in the question also works, but I would avoid overwriting the base class, unless I actually want to change something in the class.
The save method use just used as a submit handler anyways, so doesn't make much sense to overwrite just to add a redirect.
Answer: I think the better method is to still use one of the hooks from the form_alter family, attached a submit handler, and within that set your redirect.
Contrib extending base classes to do this is hairy in my opinion. Especially since no function is changing, just redirecting.
Answer: You can create a new EventSubscriber which listens to the KernelEvents::REQUEST event, and then react when you are submitting a node form, something like this
Anyway the hook_form_alter way works ok.
Answer: What i  found so far:
Implementing a form alter hook and try to change the validate/submit handlers in the form alter hook itself only works if you change the $form['#validate]/ $form[#submit'] handlers. (calling form_state functions for this wont work in the form alter hook itself)
But when you try this inside a validation handler, it tends to work:

// Load form submit handlers.
$submit_handlers = $form_state->getSubmitHandlers();

// Drop the core entity submitForm function.
$key_core_submit = array_search('::submitForm', $submit_handlers);
if ($key_core_submit !== FALSE) {
  unset($submit_handlers[$key_core_submit]);
  // Add your own submit handler.
  array_unshift($submit_handlers, 'yourmodule_submit_handler');
}
// Update submit handlers.
$form_state->setSubmitHandlers($submit_handlers);

This is because the form has now been built completely, not the case in the form alter hook itself.
The idea is: you can add a validation handler as the last one, evaluate other handlers that exist for the submit, and change them right there.
If you want to also change validation handlers, make sure yours runs prior to any other and change what you want in the validate handler.
Still searching for a better way myself, i just always need to replace the  validate/submit handlers for the user register form. But other modules could exist that break my modules implementation. So my module would need to be able to check for these, and that's possible this way. I do wonder if some entity form after build function exists to pull this off. (something that runs when the form has been completed and is about to be delivered) (that's not way to complex for this simple case)
Bypassing the save() method's redirect is not possible, but unsetting the save() is via this way (+ implement your own). True, a class is nicer and offers easier access to objects/etc, but overriding a core class indeed leads to issues when other modules want to use these. That's not the case if you use this code.

Alter an existing form


Class loader not finding form class

Question: I am trying to create a custom form in my drupal 8 instance, and I have followed a few different tutorials, but every time I try to go to the forms path I see the following error on the page:
The website encountered an unexpected error. Please try again later.

When I check my apache log, I see it came because of this error:
Uncaught PHP Exception InvalidArgumentException: "Class "Drupal\report_service_call\Form\ReportServiceCallForm" does not exist." at /var/www/html/abcnj/core/lib/Drupal/Core/DependencyInjection/ClassResolver.php line 24
I do have my ReportServiceCallForm set up at the following path under my module:
lib/Drupal/report_service_call/Form/ReportServiceCallForm.php
this is the contents of that file:
<?php
/**
 *@file
  *Contains /Drupal/report_service_call/Form/ReportServiceCallForm
  */

  namespace Drupal\report_service_call\Form;

  use Drupal\Core\Form\FormBase;
  use Drupal\Core\Form\FormStateInterface;
 /**
  *Implements Drupal form Interface
  */
 class ReportServiceCallForm extends FormBase{

 /**
  *{@inheritdoc}
  */
  public function getFormID(){
     return 'report_service_call_form';
  }
 /**
  *{@inheritdoc}
  */
public function buildForm(array $form, array &$form_state){
  $form['company_name'] = array(
    '#type'=> 'textfield',
    'title'=> $this->t('Company Name')
  );

$form['cotact_name'] = array(
  '#type'=> 'textfield',
  'title'=> $this->t('Contact Name')
);

$form['current_system_type'] = array(
  '#type'=> 'textfield',
  'title'=> $this->t('Current System Type')
);

$form['telephone_number'] = array(
  '#type'=> 'tel',
  'title'=> $this->t('Telephone Number')
);

$form['email'] = array(
  '#type'=> 'email',
  'title'=> $this->t('Email Address')
);

$form['service_request'] = array(
  '#type'=> 'textfield',
  'title'=> $this->t('Service Request')
);

$form['actions']['#type'] = 'actions';
$form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => $this->t('Save'),
    '#button_type'=>'primary',
);
return $form;
}

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

  }

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

  }
}

Also I have the contents of my routing.yml as follows:
report_service_call.form:
    path: '/Customer-Service/Report-Service-Call'
defaults:
  _title: 'Report Service Call Form'
  _form: 'Drupal\report_service_call\Form\ReportServiceCallForm'
requirements:
  _permission: 'access content'

Answer: The file needs to be located at [MODULE FOLDER]/src/Form/ReportServiceCallForm.php
Comment: You were right, I changed to this and it worked. Must have been using outdated documentation/tutorials. Thanks!

Class loader not finding form class


Matrix transformation: not how to interpret this question

Question: It says "By computing the eigenvalues and eigenvectors of the matrices, give a geometrical description of the linear transformation associated with the matrices"
And then i was given 4 2/2 matatrice like $$\begin{bmatrix} 3&0 \\ 0&1\end{bmatrix}$$
Do i just find the diagonal and P (i forgot its real name) as and $P^-1$
Such that
A = $PDP^{-1}$
$$\begin{bmatrix} 3&0 \\ 0&1\end{bmatrix} = \begin{bmatrix} 0&1 \\ 1&0\end{bmatrix} \begin{bmatrix} 1&0 \\ 0&3\end{bmatrix}\begin{bmatrix} 0&1 \\ 1&0\end{bmatrix} $$
Then try to somehow make note if these are a "shear", "orthogonal projection (through line or on the origin or not)", "rotation",
The diagonal $\begin{bmatrix} 1&0 \\ 0&3\end{bmatrix}$ kinda makes sense as an expansion by 3 $\begin{bmatrix} 0&1 \\ 1&0\end{bmatrix}$ is just none sense.
I just need help with the concept and what question actually wants
Comment: P is called the eigenvector and its diagonal entries consist of the eigenvalues of D.
Comment: @CivilSigma What?!?! $P$ is a *matrix* of *eigenvector**S***.  The diagonal entries of $P$ are *not* the eigenvalues.
Comment: Guys can you help with the question though?
Answer: I think i got what the question meant. I think it just wants you to demonstrate the characteristics of the relationship of an eigenvalue with its eigenvector. A matrix A is scaled by the eigenvalue in the direction of the eigen vector.
So for my example. The eigenvalues and eigenvectors are 3, $\begin{bmatrix} 1\\ 0\end{bmatrix} $  and 1,$\begin{bmatrix} 0\\ 1\end{bmatrix} $ So the matrix is scaled by 3 in the direction $\begin{bmatrix} 1\\ 0\end{bmatrix} $ and 1  in the direction $\begin{bmatrix} 0\\ 1\end{bmatrix} $.


How do I execute this SublimeREPL shortcut

Question: How do I execute this shortcut?  What key combination is that?  I don't get what ",," means.
Answer: You press ctrl+, at the same time, release them, then press s.
Comment: Yes, right.  The keymap sequence really doesn't look 'right' as it is displayed in the drop down menu.  In case you or anyone else is interested, you can check the package's `.sublime-keymap` file and find the sequence in a much more friendly syntax:  `{ "keys": ["ctrl+,", "s"], "command": "repl_transfer_current", "args": {"scope": "selection"}},`
Comment: So one `,` is for keyboard key <>kbd>, and other for , punctuation ? Nice I didn't know this ..


How can i run a select and update query simultaneously from phpmyadmin

Question: I have a scenerio. I have a field called card_no. Some entries are blank. We don't want to handle that. Some have 16 digit integers and some have the proper data I need. What I need is that I want to select all the records that are 16 digits integer and replace them with xxxxxxxxxxxxLAST4DIGITS (The credit card format). Can i do that via mysql?
Answer: You don't have to SELECT the rows.
You can apply an UPDATE to a subset of rows matching a condition.
UPDATE scenario
SET card_no = CONCAT('xxxxxxxxxxxx', RIGHT(card_no, 4))
WHERE LENGTH(card_no) = 16

Comment: my table name is cards and my field name is card_no
Comment: UPDATE `cards` SET 'card_no' = CONCAT('xxxxxxxxxxxx', RIGHT(card_no, 4)) WHERE LENGTH(card_no) = 16
Comment: I have attached a image.
Answer: Yes. But you have to have this field as char(4) as you might want to store a number 0002 as 0002 not just 2. So I would first update the datatype of the field and then update the field entries as desired.
-- update datatype
alter table `cards`
modify column `card_no` char(4);

-- update values in card_no
update `cards`
set `card_no` = LPAD(if(length(`card_no`) > 4, substr(`card_no`, -4, 4), `card_no`), 4, '0')
where `card_no` is not null;

The 'xxx' append operation you can do at application code side or else it will take extra memory in db.


Algebraic and combinatorial proof of an identity

Question: For any two integers $2 \le k \le n-2$, there is the identity
$$\dbinom{n}{2} = \dbinom{k}{2} + k(n-k) + \dbinom{n-k}{2}.$$
a) Give an algebraic proof of this identity, writing the binomial coefficients in terms of factorials and simplifying.
b) Give a combinatorial proof (and interpretation) of this identity.
For part a, I turned the combinations into factorials and tried to get the RHS equal to the LFS, which is $\frac{n!}{2!(n-2)!}$. However, I got stuck on the third step with all the $k$'s and $(n-k)!$'s.
For part b, I got as far as saying you choose 2 kids out of n kids to receive candy on the LHS. I see the $k$ and $n-k$ in a way accounts for each other on the right but I cannot explain this in words.
I am fairly new to mathematical proofs and any help is appreciated. Thanks!
Answer: HINT: For (a), you have
$$\binom{k}2+k(n-k)+\binom{n-k}2=\frac{k!}{2!(k-2)!}+k(n-k)+\frac{(n-k)!}{2!(n-k-2)!}\;.$$
Start by doing a lot of cancellation:
$$\begin{align*}
\frac{n!}{(n-2)!}&=n(n-1)\\
\frac{k!}{(k-2)!}&=k(k-1)\;,\text{ and }\\
\frac{(n-k)!}{(n-k-2)!}&=(n-k)(n-k-1)\;.
\end{align*}$$
Once you've done that, the algebra becomes very straightforward.
For (b), suppose that there are $k$ boys and $n-k$ girls. Then $\binom{k}2$ is the number of ways to choose two boys, $\binom{n-k}2$ is the number of ways to choose two girls, and $k(n-k)$ is the number of ways to choose ... what?
Answer: Part (a) is straightforward:
\begin{align*}
  \dbinom{k}{2} + k(n-k) + \dbinom{n-k}{2}
    &= \frac{k!}{(k-2)!2!} + k(n-k) + \frac{(n-k)!}{2!(n-k-2)!} \\
    &= \frac{k(k-1)}{2} + k(n-k) + \frac{(n-k)(n-k-1)}{2} \\
    &= \frac{k^2-k+2nk-2k^2 + n^2 - 2nk - n + k^2 + k}{2} \\
    &= \frac{n(n-1)}{2} = \dbinom{n}{2}.
\end{align*}
Answer: Part (b) is also straightforward. The LHS measures how many ways there are to choose 2 balls from n. This is the same as counting the ways to choose 2 from the first k, or 2 from the last n-k, or one in the first k and one in the last n-k.


root pattern of second degree polynomial

Question: I'm considering the following 2nd degree polynomial for the case where the roots are complex conjugate.
$
P(z) = z^2 + (f^2 + f q -2)z + (1 - f q) = (z - z_1) (z - z^*_1)
$
where f and q are real positive parameters.
Question 1:
Is there a geometric interpretation of parameter q?
There is a simple geometric interpretation of parameter f. It is $|z_1 - 1| = f$. In words, it is the distance between the roots to the point 1 on the real axis.
But I can't find/formulate a geometric interpretation for q.
Question 2:
This is a little bit more difficult to formulate but it is based on an observation I will explain.
If parameters f and q are constrained to values in the set  V = {0, 1, 2, ..., 2^N-1} / 2^(N-1). In words, f and q obtain values lying on equal interval grid points between 0 and 2.
If the possible roots of P(z) are plotted when f is fixed to any value in V and q is traced through V the roots lie on a circle with center (1,0) and radius f.

If the possible roots of P(z) are plotted when q is fixed to any value in V and f is traced through V the roots lie on curves looking like this

If many more roots are plotted the pattern looks like this

It looks like the roots must lie on straight lines radiating from (1,0). I can't find any expression from which it is clear that this is true. So my questions is: Is it possible to find an expression that shows that the roots must line on straight line passing through (1,0)?
Comment: You are right, it should have been $P(1) = f^2$. This follows from $Q(z) = P(z + 1) = f^2 + (f^2 - f q ) z + (1 - f q) z^2$ where obviously $Q(0) = f^2 = P(1)$. From the same $Q(z)$ however, it also follows that the product of the roots - which is the square of the absolute value for complex conjugates - is $f^2 / (1 - f q)$, where root $z_1$ of $Q(z)$ corresponds to root $z_1 - 1$ of $P(x)$. P.S. Note that your initial representation of $P(z)$ is off by a factor of $(1 - f q)$. It should be $P(z) = (1 - f q) (z - z_1) (z - z_1^*) $.
Comment: `There is a simple geometric interpretation of parameter f.` No, $f = |z_1 - 1|$ is wrong. What's true is that $f^2 = P(-1)$, and also $|z_1 - 1|^2 = f^2 / (1 - f q)$, but neither has a direct geometric interpretation in terms of $f, q$ individually.
Comment: hmm, are you sure? I mean, if $z_1 = Re^{i\theta}$ isn't $|z_1 - 1|^2 = R^2\sin^2(\theta) + (1 - R\cos(\theta) )^2 = 1 - 2R\cos(\theta) + R^2 = f^2$. Shouldn't it be $P(1) = f^2$ ?
Comment: Doh! $P(z)$ is not correct. Sorry! It was your comment regarding the factor $(1-fq)$ that made me see I wrote P(z) incorrectly.Sorry sorry sorry! I have update P(z) in the question.
Answer: Let $P(z) = z^2 + (f^2 + f q − 2) z + (1 − f q)$ with $f, q \in \mathbb R$. The following will prove that if $f \ne 0$ and $|f + q| \lt 2$ then $P(z) = 0$ has two complex roots, and for each such root:
$$
|z - 1| = |f| \\
\cos \varphi = - sgn(f) \frac{f + q}{2} \,\,\,\,\text{ where }\,\, \varphi = \arg (z - 1)\,\,\text{ and }\,\, sgn \,\,\text{ is the signum function }
$$
In the complex plane, this translates to:

for $f = const$ the locus of the roots $z$ of $P(z)$ is a circle centered at point $(1, 0)$;
for $f + q = const$ the locus of $z$ is a pair of straight lines through point $(1, 0)$.

Since the point of interest is $(1, 0)$ it is natural to consider $P(z) = Q(z - 1)$ around the origin. After simple calculations:
$$
\begin{align}
Q(z) = P(z + 1) & = (z + 1)^2 + (f^2 + f q − 2) (z + 1) + (1 - f q) \\
 & = z^2 + f (f + q) z + f^2
\end{align}
$$
Its discriminant is:
$$
\begin{align}
\Delta & = f^2 (f + q)^2 - 4 f^2 \\
 & = f^2 (f + q - 2) (f + q + 2)
\end{align}
$$
Therefore the conditions for $\Delta \lt 0$ so that $Q(z)$ has complex roots are:
$$
\begin{cases}
f \ne 0 \\
-2 \lt (f + q) \lt 2 \text{ } \iff \text { } |f + q| \lt 2
\end{cases}
$$
Since the product of the two complex conjugate roots is $z \bar z = |z|^2$, it follows from Vieta's formulas that $|z|^2 = f^2$ which proves the first point.
Then the two roots are $z, \bar z = |f| ( \cos \varphi \pm i \sin \varphi)$ and their sum is $z + \bar z = 2 |f| \cos \varphi = -f (f + q)$ again by Vieta's formulas. It finally follows that:
$$
\cos \varphi = - \frac{f}{|f|} \frac{f + q}{2} = - sgn(f) \frac{f + q}{2}
$$

[EDIT] This is a followup to the question of a geometric interpretation of q asked in the original post, and again in a comment. Short answer is that there doesn't appear to be any direct "nice" geometric interpretation of $q$, and here is why.
The answer above focused on the roots of $Q(z)$, and the geometric interpretations for $f$ and $f+q$ followed as corrolaries, almost as if by chance. However, the problem can be approached from the other end, too. Suppose one wants to directly determine how the parameters affect the roots, specifically what the locus is of roots $z, \bar z$ if a parameter is kept constant. Below is a derivation of the answer for $f$ since that's the easier of the two to calculate, and also provides the basis of why there is no comparably simple geometric interpretation for $q$.
The two complex conjugate roots $z, \bar z$ of$Q(z)$ satisfy the simultaneous equations.
$$
\begin{cases}
z^2 + f (f + q) z + f^2 = 0 \\
{\bar z}^2 + f (f + q) {\bar z} + f^2 = 0
\end{cases}
$$
$q$ can be easily eliminated between the two equations - by solving the first one in $q$ then substituting in the second one, or simply by multiplying the two equations by $\bar z, z$ respectively, then subtracting. In the end it reduces to:
$$
(z - \bar z) (|z|^2 - f^2) = 0
$$
Since the roots are non-real complex numbers $z \ne \bar z$, so it follows that $|z|^2 - f^2 = 0$. This is the same relation derived in the original answer, and has a nice direct geometric interpretation. It means that $|f|$ is the absolute value of $z$ so the roots for $f = const$ lie on a circle centered at the origin.
It is technically possible to do the same analysis for $q$ of course. But since the equations are quadratic in $f$, eliminating it between the two is more laborious, and the end results is a quartic curve parameterized in $f$. Each $q = const$ gives a different quartic curve, but other than that there is no obvious (to me) geometric interpretation for $q$.
Comment: @niaren I don't think there really is much of a `geometric interpretation of q` - see the [EDIT] at the end of my answer.
Comment: thanks for the edit. The alternative expression I mentioned above was for the slope of the lines and it also depends on $f+q$ only. The reason I thought that there ought to be some 'nice' geometric interpretation/understanding of $q$ is because of $f q = 1 - R^2$ where $R$ is the modulus of the roots of $P(z)$. So it looks a bit like pythagoras or some simple trigonometric identity could be used to obtain som geometric understanding..
Comment: I'm going to accept this answer. Particularly, I like the idea of analyzing  the modified polynomial $Q(z)$. Unfortunately, this idea would never have occurred to me. I think I derived an alternative expression for $\cos \varphi$. This is something I will look into. So the reason for the lines radiating from (1,0) is because $\varphi$ depends 'only' on $f+q$...It would be interesting if you could give your formulation of a geometric interpretation of $q$...


Maps and text in css

Question: I am new to CSS but have a relatively simple goal. My objective is to format a webpage to display a series of maps with text in between.  In the end, the layout will be as follows with the page scrollable:
text
map
text
map
text
map

Both text and maps should be centered.  In order to place the maps in the center of the page, I attach each map to the map-container but I am not sure that this is the right method.  The following markdown overlaps the maps, and does not allow one to scroll down the page.
<!DOCTYPE html>

    <meta charset='utf-8' />
    <title></title>
    <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />

    <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.38.0/mapbox-gl.css' rel='stylesheet' />

TEST

<button id='pause'></button>

Both maps are children of the same parent element. I have tried changing the position parameter, changing top/bottom although nothing works - either one map covers the other or they overlap. What am I doing wrong ? Any suggestions or basic template on how to put maps in between text would be very helpful.
Comment: Hello! I would love to assist you with your problem. From looking at your code, I can see that there are a lot of unnecessary css that takes place. Displaying every item as a block element "display: block;" and placing them in a proper place in the html markup, will grant you the result that you desire. Here is a CodePen that I setup: https://codepen.io/CapySloth/pen/NgJwZq.
Comment: Your main culprits for overlaying of maps are the setting of maps with parameters "position:absolute" and "position:fixed". Both are not meant to be "dynamic". To try describe it in a metaphor; They do not care about the existence of each-other, so instead of what you want them to do (sit next to each-other), one will sit on top the other.
Comment: Can map be more then 100% of screen width?
Answer: You can achieve this via flexbox. No need for additional containers. Demo:

body {
  /* Make body a flex-container */
  display: flex;
  /* Specify direction where all items will */
  flex-direction: column;
  /* Center all items in this direction */
  align-items: center;
}
Look how many maps we've got!

Some text

This is also text

Maps are awesome
Comment: Unfortunately this also does not work because the maps I am displaying  are not images
Comment: @the_darkside That doesn't matter. You can display them as `div`s with `background-image` with fixed sizes. The main idea is to have `flex-container` with direct children. Does it help you?
Comment: If `position` is not defined, the maps will not display at all.  Can you provide an example with a simple mapbox map?
Comment: @the_darkside Can you please create clear fiddle where I can reproduce your markup?
Comment: @the_darkside Is it possible to rewrite your markup using this method without absolute positioning? If you don't need overlap try avoiding absolute positioning. But even if you need absolute positioning I can't help you without some clear example where I can see some results, not just code.
Comment: This map can be used and reproduced three times in between text for example - though it should not be 100% of the screen - rather only 500px by 500px box in the middle of the screen
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/149529/discussion-between-the-darkside-and-vadim-ovchinnikov).
Comment: @the_darkside Well, I can't see anything that I would just call text on fiddle. You've posted me all code you've got, not just minimal example to reproduce the issue and it's very hard even to understand your issue, not speaking about to fix it. To center box in the middle of screen is trivial. https://jsfiddle.net/2rs72wus/1/
Comment: @the_darkside I would chat with you, but it's very late my time, I need to go to bed. Sorry.
Answer: Use this code and all of your content is in the center

Maps and text in css


Defining the sigma-algebra of events of a probability space

Question: Suppose we have a sample space of outcomes.
How do we define a suitable $\sigma$-algebra of events on this sample space, such that we can then create a good probability measure on the events? Is there a general procedure for doing so?
An example from my book (A First Look at Rigorous Probability Theory, by J Rosenthal) is to first define a probability measure $P$ on a  suitable  algebra $\mathcal{A}$ of events and then extend $P$ to  the generated $\sigma$-algebra $\sigma(\mathcal{A}$), letting $\sigma(\mathcal{A})$ be the set of events for our probability space. But I wonder if such an algebra can always to be found while still being sufficiently broad to cover most events we'd care about. I mean, would it be possible to just take an arbitrary set $S$ of events that we'd like, extend that into an algebra if it's not already, then a $\sigma$-algebra, and then have a nice measure defined on that??? (I know about Caratheodory's extension theorem, but that only answers my question in the case where we already have a measure on an  algebra of events we'd want in our space. It doesn't answer whether we can just extend an arbitrary set of events into an algebra, or whether we can necessarily find a good measure on that algebra.)
Sorry if this question is somewhat unfocused, but there's a general feeling of confusion I have about this topic so any answer that clears it up would be greatly appreciated.
Answer: The following result may help you.
Theorem. (Durrett, A.1 (1.3), p.439) Let $\mathcal{S}$ be a semi-algebra and let $\mu$ defined on $\mathcal{S}$ have $\mu(\emptyset) = 0$. Suppose (i) if $S \in \mathcal{S}$ is a finite disjoint union of sets $S_i \in \mathcal{S}$, then $\mu(S) = \sum_i \mu(S_i)$, and (ii) if $S_i, S \in \mathcal{S}$ with $S$ the countable disjoint union of the $S_i$, then $\mu(S) \leq \sum_i \mu(S_i)$. Then $\mu$ has a unique extension $\bar{\mu}$ that is a measure on $\bar{\mathcal{S}}$, the algebra generated by $\mathcal{S}$. Moreover, if the extension is $\sigma$-finite, then by the Caratheodory theorem there is a unique extension $\nu$ that is a measure on $\sigma(\mathcal{\bar{\mathcal{S}}})$.
Answer: Algebra generated by a family of subsets $\mathcal M \subseteq 2^\Omega$ is $Alg(\mathcal M)=(\mathcal M \cup \mathcal M^c)_{ds}$, which is the closure of $\mathcal M$ with respect to complement $c$, finite intersections $d$ and finite unions $s$. By convention, the empty union is $\emptyset$ and the empty intersection is $\Omega$
The measure defined on $\mathcal M$ can be extended on $Alg(\mathcal M)$ by using this constructive approach.
$\sigma$-algebra generated by a family of subsets has a much more complicated construction, which I don't understand fully myself. $\mathcal M$ is repeatedly closed under complements and countable unions $\sigma$:
$\mathcal M_1=\mathcal M$
...
$\mathcal M_{i+1}=(\mathcal M_i \cup \mathcal M_i^c)_\sigma$
Then $\sigma$-algebra generated by $\mathcal M$ is $\bigcup \mathcal M_i$
But the union is until the first ordinal with an uncounted number of predecessors (!) Otherwise this construction does not exhaust all elements of the $\sigma$-algebra
This is why it is much harder to extend a measure to the $\sigma$-algebra generated. In fact it's impossible to extend the Lebesgue measure to all subsets of $\mathbb R$
Comment: OP is asking about extending a measure on a arbitrary set to an algebra/sigma algebra generated by the set.
Comment: I was in the process of editing it. Besides, this is not the definition of the algebra generated by a family of sets, but a construction of it that justifies the extension.


Sending data to a list of ip addresses - c++

Question: Currently I am using enet to stream info, updated multiple times per second, to a list of
provided ip addresses / ports. I am creating a client connection for each of these
addresses (and there are server enet host connections running on those computers).
I am wondering if there is a more efficient way to send these messages(or simply a better solution to the problem)? Some way that I do not have to create
a enet host for each connection? I do need reliable delivery.
I am only using enet as it is convenient and already available in the system I am using.
Answer: A great solution for this problem is ZeroMQ.
It is a networking library with C++ bindings that specializes in the reliable delivery of messages in a variety of configurations, like the pub/sub model that looks like what you are trying to do.
ZeroMQ would effectively allow you to not even need to list the IPs of the subscribers, since they would indeed subscribe by connecting to your publisher. The publisher then would send data regardless of the number of subscribers (see http://zguide.zeromq.org/page:all#Getting-the-Message-Out).
Comment: Thanks for a great suggestion.  This might not work for me due to certain constraints (due to which I will now have to implement very similar functionality myself), but I will keep ZeroMQ in mind for the future.
Comment: @user1666594 may I ask you what kind of constraints you are talking about ?
Comment: The biggest problem with ZeroMQ is that it is not a neutral carrier .. which we need it to be


Calculating Monte-Carlo Error For Confidence Interval Estimation

Question: I am simulating from a Categorical process such that each $x_i \in \mathbb{R}$ is an independent sample. After drawing $N$ samples, I want to use my samples to estimate the standard error of the empirical confidence interval. How could I approach this problem?
Comment: Are your data categorical (nominal or ordinal), or numerical. If the observations $x_i$ lie on the real line, that ordinarily means they are numerical. If they are not assumed to be numerical, then what do you mean by standard error? // You say you have $N$ samples: Does that mean that you have one sample with $n$ observations? Or are you doing some sort of re-sampling and have $N$ re-samples of size $n?$ Is the goal to make a confidence interval (as in your title) or to find a 'standard error' (as in the text of your question)? For coherent answ, please give sample of data and state purpose.
Answer: I will crawl very far out on a limb and speculate that you have
Likert-7 data from $n = 100$ subjects, and that you are making the
usual (but not always defensible) assumption that it is OK to regard
them as numerical. If this is way off target, you can use that as
a basis for refining your question. Then maybe one of us can come closer to a useful answer.
Thus your data might be something like the fictitious data simulated and described in R below:
set.seed(421)
x = sample(1:5, 100, rep=T, p = c(1,1,2,3,3))
table(x)
x
  1  2  3  4  5
 14 10 20 35 21

summary(x)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
   1.00    3.00    4.00    3.39    4.00    5.00

stripchart(x, ylim=c(.7,2.5), meth="s", pch=20)

Classical approaches are questionable. The data are pretty clearly not normal, so I am reluctant to trust
a t confidence interval $(3.13, 3.65)$ as valid. Also, there are too
many tied values to make good sense of a 95% confidence interval $(3,4)$ for the 'pseudo-median' based
on a one-sample nonparametric Wilcoxon test. I am not saying that either
of these intervals is "wrong"--only that I cannot confirm that the
assumptions underlying them are warranted.
Nonparametric bootstrap CIs. One kind of bootstrap confidence interval arises from taking $B = 3000$
re-samples from among the $n = 100$ scores x, and take the average of each re-sample. This gives a good idea of the variability of average scores
Finally, by taking quantiles 0.025 and 0.9975 of the re-sampled averages
I get a quantile 95% nonparametric CI $(3.13, 3.64)$ for the population mean Likert-5 score.
Perhaps without taking any assumed numerical meaning
of the Likert scores too seriously, we can say the the average population
scores lie between 3 and 4. [Even so, we have inevitably assumed some
numerical qualities for Likert scores: for example, that the differences
between scores 1 and 2 are as important as differences between scores 3 and 4. That these assumptions are almost routinely made in some disciplines does not mean that they are always correct or useful.]
set.seed(2021)
a.re = replicate(3000, mean(sample(x,100,rep=T)))
quantile(a.re, c(.025,.975))
 2.5% 97.5%
 3.13  3.64

Among the 3000 re-sampled means a.re there only 82 uniquely distinct
values, so we should not take the second decimal places in the boundaries
of the bootstrap CI very seriously. For example, the corresponding 90% CI $(3.17, 3.61)$ and 99% CI $(3.06, 3.67)$
are not a lot different.
length(unique(a.re))
[1] 82

quantile(a.re, c(.05,.95))
  5%  95%
3.17 3.61

quantile(a.re, c(.005,.985))
 0.5% 98.5%
 3.06  3.67

Here is a histogram of the 3000 resampled averages, along with the
boundaries of our 95% nonparametric bootstrap CI.

Treating Likert scores as if numerical, the point estimate of the population mean score is $\bar X = 3.39$ (in the summary table above):
if you really need a 'standard error` of this average, then you might
use $0.133.$
sd(a.re)
[1] 0.1327829

It is not very much different than the standard error of $\bar X,$ which is $S/\sqrt{n} 0.131.$ (That would be correct for normal numerical data.)
sd(x)/sqrt(100)
[1] 0.1309599

Comment: This is an amazingly rich interpretation of an otherwise unfathomable question.  Kudos for creativity; but I think we need the OP to clarify their question.
Comment: Thanks and agreed.


Differentiability in Generative Adversarial Networks

Question: I've got some questions about the differentiability condition of GAN's, i.e. both G and D need to be differentiable wrt. their inputs and the parameters describing them. It's of more mathematical nature and I just couldn't find a clear answer to that anywhere else and I want to make sure I understand these things correctly before presenting them in a seminar. I'm always referring to goodfellows paper / tutorial in the following questions.
https://arxiv.org/abs/1406.2661
https://arxiv.org/abs/1701.00160
1) Is differentiability of G and D wrt. their parameters only required to train them by gradient descent or are there other reasons?
2) Why do we need differentiability wrt. the inputs of the generator? I don't think we need that to apply gradient descent algorithms. (Please correct me if I'm wrong there.) Differentiability of the Discriminator wrt it's inputs is required for gradient descent (having a look at the objective function and applying the chain rule).
3) Somewhat related to the other two questions: When Good fellow et al talk about probability distribution in their paper, $p_{data}$, $p_z$ and $p_g$, are they talking about discrete or continuous probability distributions?
I don't think it's made clear in the paper and in the latter case it would imply, for instance, that both $p_{data}$ and $p_g$ be differentiable since the optimal Discriminator is essentially a function of their ratio. Also, the existence of a continuous $p_g$ is non-trivial by just assuming a continuous $p_z$.
4) In the case that the answer to 3 is discrete distributions: Differentiability of G implies continuous outputs of the generator. How can this work together with a discrete distribution $p_g$ of its outputs? Does the answer have something to do with the fact that we can only represent a finite set of numbers with computers anyway?
Thank you very much!
Best
EDIT: updated link for tutorial by goodfellow
Answer:
1) Is differentiability of G and D wrt. their parameters only required
  to train them by gradient descent or are there other reasons?

I believe it's also assumed in a lot of GAN convergence proofs. example. Granted, this is mostly of theoretical interest rather than practical.

2) Why do we need differentiability wrt. the inputs of the generator?

Yeah, you're right, wrt. the parameters should be good enough.

are they talking about discrete or continuous probability
  distributions?

Usually continuous. However there is work which explores discrete domain GANs (which have interesting applications in language or molecule generation). The discrete case usually requires some sort of trick like gumbel-softmax or Reinforce.

Also, the existence of a continuous $p_g$ is non-trivial by just assuming a continuous $p_z$.

I'm not familiar with theory here, but the paper I linked above does analyze convergence on absolutely continuous generator distributions versus the general case.
Comment: Thanks for your input! I'm pretty confident that this settles the debate regarding 1 and 2. I will check the paper you linked. Actually, a lot of the reasoning in the original appears to work for both the continuous and discrete case. Also, it's totally fine to assume continuous distributions for our data and the latent variables. However, given that optimal D is a function of both these distributions makes it kind of necessary for them to be differentiable (since we want D to be differentiable). This is imo a assumption too strong to just not mention it. (although I think you can get away wit


QDataStream and quint16 serialization weirdness

Question: I've written a small Packet class consisting of some quint8's, quint16's, QByteArrays and a quint32 that has a toByteArray() method to return a serialized version of the object, conforming to a protocol specification.
Packet Spec

Protocol identifier [4 byte] (Version 1 = 0x74697331)
Session ID, a MD5 hash salted with the timestamp + user IP. [16 bytes]
Command ID [1 byte]
Argument Size [2 byte]
Args [1-8,192 bytes]
CRC-B (X-25) [2 bytes]

Most of the data serializes fine. The exception is the last quint16 (my crc), which seems to get clobbered.
I don't believe the problem is in the declaration of my class. I've re-created the serialization function in this code sample which demonstrates the bug I'm receiving, without my packet class. (But the same final QByteArray layout)
(More) Minimal reproducible testcase
<code>#include <iostream>

#include <QByteArray>
#include <QDebug>

using namespace std;

int main()
{
    QByteArray arr;

    quint32 m_protocolId = 0x74697331;
    QByteArray m_sessionId;
    m_sessionId.resize(16);
    m_sessionId.fill(0);
    quint8 m_commandId = 0x1;
    quint16 m_argsSize = 0x0e;
    QByteArray args;
    args.append("test").append('\0');
    args.append("1234qwer").append('\0');
    quint16 m_crc;
    m_crc = 0xB5A2;

    QDataStream out(&arr, QIODevice::WriteOnly);
    out.setByteOrder(QDataStream::LittleEndian);

    out << m_protocolId;
    out.writeRawData(m_sessionId.data(), 16);
    out << m_commandId;
    out << m_argsSize;
    out.writeRawData(args.data(), args.length());
    out << m_crc;

    foreach (char c, arr)
    {
        qDebug() << QString::number((int)c, 16).toAscii().data();
    }

    return 0;
}
</code>
Here's the output I get:
73
69
74
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
e
0
74
65
73
74
0
31
32
33
34
71
77
65
72
0
ffffffffffffffa2
ffffffffffffffb5
Those last two should be 0xa2, 0xb5. I guess it's some sort of alignment issue. Is there any way to correct this while still conforming to the packet spec?
Answer: I think you just need to tweak your debug output. Try:
<code>..
foreach (unsigned char c, arr)
..
</code>
Comment: Yeah, that's it; thanks a bunch! (I also had to cast to unsigned int in the QString::number() call). Sigh, now it feels like I wasted a few hours..


compute the cartesian product of n lists and n dimensions arrays

Question: Do you know how to compute the cartesian product of n lists and n dimensions arrays?
example:
d = 3
x = [0, 1, 2]
y = [0, 1, 2]

[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 2, 0), (0, 2, 1), (0, 2, 2), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 2, 0), (1, 2, 1), (1, 2, 2), (2, 0, 0), (2, 0, 1), (2, 0, 2), (2, 1, 0), (2, 1, 1), (2, 1, 2), (2, 2, 0), (2, 2, 1), (2, 2, 2)]

Comment: You example is ambiguous, what would be the result for `x = [1, 2, 3] ; y = [10, 20, 30]`?
Answer: Please check if the below-mentioned solution works for you, do let me know if any changes are required:
import itertools

d = 3
x = [0, 1, 2]
y = [0, 1, 2]
third_lst = [0, 1, 2] # this list is required for the third dimension

input_lst = [x, y, third_lst]

final_lst = list(itertools.product(*input_lst))

print(final_lst)

Output:
[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 2, 0), (0, 2, 1), (0, 2, 2), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 2, 0), (1, 2, 1), (1, 2, 2), (2, 0, 0), (2, 0, 1), (2, 0, 2), (2, 1, 0), (2, 1, 1), (2, 1, 2), (2, 2, 0), (2, 2, 1), (2, 2, 2)]


How to add two footer row in jqgrid using userdata?

Question: I am using this jqgrid
        $("#griglia-navgrid").jqGrid( {
        url: 'search.do?report='+r,
        datatype: "json",
        colNames:[ ...    ],
            colModel:[ ...    ],
            rowNum:50,
        rowList:[20,50,100],
        pager: '#pager',
        autowidth:true,
        height:'auto',
            viewrecords: true,
        sortname: "MATNR",
            sortorder: "asc",
            footerrow : true,
            userDataOnFooter: true,
            jsonReader: {
                root:"INVDATA",
                page: "CURRPAGE",
                total: "TOTALPAGES",
                records: "TOTALRECORDS",
                repeatitems: false,
                id: "0",
                userdata: "USERDATA",
            }
        }); //jqGrid

On server side I calculate the totals and I use "userdata" like this:
"userdata":{"total":1234,"name":"Totals"}

And it's works. Now I need to show 2 footer row with totals. And i try something like this:
"userdata":[{"total":1234,"name":"Totals"},{"total":5678,"name":"Totals"}]

But does not work. Is it possible add two footer rows using "userdata"? How can I do this?
Comment: Please refer http://stackoverflow.com/questions/13697523/how-to-create-two-footer-rows-in-jqgrid/13703037#13703037
Answer: You can use my old answer as a basis of the solution which you need. It shows how to add two rows in the footer.
If you examine the source code of jqGrid for the usage of userDataOnFooter option you would find that in case of usage datatype: "json" it's only one line of code:
if(ts.p.userDataOnFooter) { self.jqGrid("footerData","set",ts.p.userData,true); }

So jqGrid just get the value of userData parameter (the userdata in the JSON response from the server) and uses it as the parameter of footerData method. So you can just remove userDataOnFooter option and uses the approach described in the referenced above answer to add two rows in the footer with the information from userData.
Comment: Thanks Oleg. I'm almost done :D But one thing, when I create the second row, I have to fill it field by field like this: " $newFooterRow.find(">td[aria-describedby=" + this.id + "_invdate]").text("Grand Total:"); " ?
Comment: @GiacomoSavioli: You are welcome! Sorry, but I don't understand your question. The grid from my demo had the column with `name: "invdate"`. So I used the selector `">td[aria-describedby=" + this.id + "_invdate]"` to fill the cell in the column `invdate` in the second row. You need replace `invdate` part of the selector with another name from `colModel` which you use.
Comment: Sorry I didn't explain clear. To fill the 1st row i used $this.jqGrid("footerData", "set", data[0]); I thought to fill the second row, I could use something like this. But I could not, so I used:  $newFooterRow.find(">td[aria-describedby=" + this.id + "_VRKME]").text(data[i].VRKME); for each column. Another question, is it possible to add n footer row?
Comment: @GiacomoSavioli: Sorry, but I still don't understand your current question. Do you can now successfully add the second footer and fill it or you still have some problems?
Comment: I solved the problem, at the moment I'll add 2 footer row. However, in the future, I could have the need to add 2-3-4..n footer rows. Is it possible?
Comment: @GiacomoSavioli: [The answer](http://stackoverflow.com/a/13703037/315935) demonstrates how *manually* add and fill additional row in the footer and how to fill new row. The code just clone the first row of the footer, clan some properties of the row and append it after the first footer row (see call of `insertAfter`). You can use the same code to add mutiple rows in the footer.


Estimating a VAR model via OLS

Question: I am looking at Vilasuso (2001), who says that when using least-squares to estimate causality in mean, there is significant size distortion if the conditional variances are correlated.
My question is, if I estimate a VAR line by line, how can the error in equation (2) impact the estimation of equation (1).
To elaborate following the comments:
If I have a bivariate VAR(1),

Let's say the conditional variances are correlated, and I ignore it and go ahead and estimate equation (1) the top line of the VAR using OLS, how can the relationship between the conditional variances show up.
My question is, account for the relationship would I have to jointly estimate the VAR using GLS or is the OLS still possible.
I am trying to show size distortion rather than correctly estimating a model.
Comment: Can you elaborate on why you find this surprising?  It is a VAR.  Equation (1) includes lagged values of the dependent variable in equation (2) on the right-hand side.  Maybe you are mixing up meanings of "error in equation (2)"?  It's not that equation 2 was estimated incorrectly that is the problem for estimating equation 1, it is the relationship between the true "error" (innovation) terms.
Comment: Hi @MattP, I am saying if the conditional covariances are correlated, but I only estimate the first equation how does the second innovation impact the estimation of the first equation!
Comment: Hi: you need to make an assumption about the covariance elements if you want to estimate a VAR with correlated error terms. The assumption usually makes certain elements zero and is often arbitrary which is a criticism of VARS. See Enders or Hamilton or Lutkepohl for detailed discussions of this issue.
Comment: I am following Vilasuso (2001) and he ignores the heteroskedasticity and then estimates the VAR using LEast Squares. My question is if the conditional variances are correlated can I estimate the VAR line by line and then the correlated conditional variances still impact the first equation (top half) of the VAR.
Comment: Hi Jack: It's been a while since I dealt with VARS but your question has to do with the difference between a reduced form VAR and a recursive VAR. It's been so long that, at the moment,  I couldn't explain it if I wanted to.  But the idea between the difference is explained in this document. ( near the end, he uses a recursive VAR by ordering the error terms ). Still, I highly recommend Enders for a more detailed and not mathematically complex explanation. Lutkepohl and Hamilton are also good but they are at a  higher level than Enders.  All the best.
Comment: Oops: I forget to include the link. http://web.uconn.edu/cunningham/econ397/VARs-SW.pdf
Comment: Jack:  I  think this one is better than the previous in terms of providing a full overview. Don't look at the other one until you check this one out first. https://faculty.washington.edu/ezivot/econ584/stck_watson_var.pdf
Answer: You can use OLS! Remember that VAR have structural qualities that permit OLS for estimation equation by equation. Namely, in VAR models each dependent variable is a linear function of both lagged values of itself as well as the other time series included in the model. If you expand your equations by multiplying out the matrices, you will see how the errors affect the other estimates.
With reference to your question about "distortion" do you mean bias or inefficiency in the parameter estimates? I think I know how to answer your question but I want to make sure I understand it first. LMK!

Estimating a VAR model via OLS


What type of bowlers are these?

Question: In cricket commentary, some bowlers are called 'chinaman bowlers' and some 'orthodox bowlers'. What type of bowlers are these?
Comment: Related answer: http://sports.stackexchange.com/questions/1601/why-are-left-arm-spinners-called-differently/1609#1609
Comment: @edmastermind29 there is no reference to _Chinaman_ or _orthodox_ bowlers in that answer.
Comment: @Mistu4u it's supplemental, not *referential*...perhaps reading the [question](http://sports.stackexchange.com/questions/1601/why-are-left-arm-spinners-called-differently/1609) will help.
Answer: There are two types of left arm spin bowlers, Chinaman and Orthodox.
Chinaman Bowler or Unorthodox Left arm Spinner- A Chinaman bowler is a left arm unorthodox spin bowler who spins the ball using Wrist spin so that the ball goes from off side to leg side for a right handed batsman. They often use leg break or leg spin for mixing variety.
Example: Michael Bevan(Australia), Brad Hogg(Australia), Sir Garry Sobers and Dave Mohammad(West Indies) etc.
Orthodox Bowler or Orthodox Left arm Spinner- An orthodox bowler is also a left hand bowler but he uses his fingers to spin the ball such a way that it goes from right side to left side of the pitch(from POV of the bowler).
Example: Daniel Vettori(New Zealand), Yuvraj Singh and Pragyan Ojha(India) etc.
Reference: Spiffyd and
           Wikipedia
Answer: What is a Chinaman bowler?
A bowler who bowls chinamans is a left(1) handed spin bowler whose stock(2) ball spins from off stump to leg stump when bowled to a right handed batsman. Sometimes referred to as a left handed off spinner as opposed to a right handed off spinner. The term chinaman differentiates between a left handed off spinner and a right handed off spinner.
A right handed off spinner bowls exactly the same ball as a chinaman (i.e. spinning from off stump to leg stump) with the single difference that it's bowled with the right hand rather than the left.
Also, please ignore any references to finger spin and wrist spin. These are terms to describe how revolutions are imparted to make the ball spin. A finger spinner uses his fingers to spin the ball and a wrist spinner uses his wrist to spin the ball. These have nothing to do with with the direction the ball will spin in or whether it's a left handed or right handed bowler.
Where does the term chinaman originate from?
It comes from the first bowler to bowl in this way - Ellis Edgar Achong
Who was of Chinese decent, hence the term. Read more about him.
What is a left arm orthodox spin bowler?
This is the term given to left arm(1) spin bowlers who spin the ball in the direction assumed to be natural for a left armed spin bowler whose stock(2) ball would spin from leg stump to off stump when bowled to a right handed batsman.
Hence the term orthodox. We naturally assume when a left arm spinner is mentioned that he will spin the ball in this way.
What is the difference between left arm orthodox and right arm orthodox?
A right handed off spinner is considered to be an orthodox right arm spin bowler as he naturally spins the ball from off stump to leg stump when bowling to a right handed batsman. You'll note this is the same direction as the chinaman. A left arm orthodox spin bowler will bowl the ball in the opposite direction.
What is the right handed version of the chinaman?
That would be the leg spinner, because he bowls the ball to spin in the opposite direction to the orthodox right handed off spinner, i.e. from leg stump to off stump when bowled to a right handed batsman.
You'll notice that the terms used here describe one of two things -
1/ The arm used to bowl the ball, and
2/ The direction the ball spins.
Left arm orthodox spins the ball in the same direction as a right arm leg spinner. Right arm orthodox spins the ball in the same direction as the left arm chinaman.
I hope this has helped to clarify this answer.
Note:

(1)The term doesn't apply to right handed bowlers

(2) The term stock ball refers to the ball that would normally be bowled even though the bowler may have other variations balls, such as one that doesn't spin at all but goes straight on.

What type of bowlers are these?


How to arrange dataset of species list from most abundant species to least abundant species

Question: I have a dataset that looks something like the below. Is there a line of code in R to arrange the different species from most abundant (occurs the most in the column) to least abundant? Thank you!
df <- tibble::tribble(
  ~name,
  "Species A",
  "Species A",
  "Species B",
  "Species C",
  "Species A",
  "Species C",
  "Species B",
  "Species A"
)

Answer: You can try to use table, sort this, use match to the names and order.
df[order(match(df$name, names(sort(table(df$name), decreasing=TRUE)))),]
## A tibble: 8 × 1
#  name
#  <chr>
#1 Species A
#2 Species A
#3 Species A
#4 Species A
#5 Species B
#6 Species B
#7 Species C
#8 Species C

Or using split:
. <- split(seq_len(nrow(df)), df$name)
df[unlist(.[order(lengths(.), decreasing=TRUE)], FALSE, FALSE),]
## A tibble: 8 × 1
#  name
#  <chr>
#1 Species A
#2 Species A
#3 Species A
#4 Species A
#5 Species B
#6 Species B
#7 Species C
#8 Species C

Or in case only the vector should be sorted:
. <- sort(table(df$name), decreasing=TRUE)
rep(names(.), .)
#[1] "Species A" "Species A" "Species A" "Species A" "Species B" "Species B"
#[7] "Species C" "Species C"

Answer: There is the function fct_infreq from the forcats package to order elements by their abundance:
library(tidyverse)

data <- tibble(
  species = c(
  "Species A",
  "Species A",
  "Species B",
  "Species C",
  "Species A",
  "Species C",
  "Species B",
  "Species A")
)

data %>%
  mutate(species = species %>% fct_infreq()) %>%
  arrange(species)
#> # A tibble: 8 × 1
#>   species
#>   <fct>
#> 1 Species A
#> 2 Species A
#> 3 Species A
#> 4 Species A
#> 5 Species B
#> 6 Species B
#> 7 Species C
#> 8 Species C

Created on 2022-05-11 by the reprex package (v2.0.0)
Answer: You can also reorder the factor by number of occurrences, and then sort the factor:
data$species <- reorder(data$species, data$species, FUN = length) |>
  sort(decreasing = T)

output
data

    species
1 Species A
2 Species A
3 Species A
4 Species A
5 Species C
6 Species C
7 Species B
8 Species B

Answer: data.table solution
library(data.table)

data <- setDT(data)[, n := .N, species][order(-n, species)][, n := NULL]

output
data

#      species
# 1: Species A
# 2: Species A
# 3: Species A
# 4: Species A
# 5: Species B
# 6: Species B
# 7: Species C
# 8: Species C

data
data <- tibble(
  species = c(
  "Species A",
  "Species A",
  "Species B",
  "Species C",
  "Species A",
  "Species C",
  "Species B",
  "Species A")
)


Problem with deleting files in Laravel and jquery

Question: I'm beginner with Laravel and JQuery.
I have this code:

- upload/other/1c186a1229c8c502c9bae2794b52a6f0.pdf
      [delete file]

- upload/other/65b13b47f09fc785d901e43e7864bab2.pdf
      [delete file]

- upload/other/19846324513791f79013fb8e5a7854d8.pdf
      [delete file]

- upload/other/fca69b7c02ae223cd167202368d3a555.pdf
      [delete file]

- upload/other/2a1f88cd9f223a423a29594be3d8ce7a.pdf
      [delete file]

- upload/other/dbe585a9716bd417437be6b0d5695a6a.pdf
      [delete file]

- upload/other/585b8aa2cfd6a871eb3ed0e1c6d5e2b9.pdf
      [delete file]

$(".removeThisFile").click(function () {
                    var id = $(this).attr("id");
                    $('.file-id-' + id).hide();
                    $.ajax({
                        url: 'http://test.test/psCMS/removeOtherFile?id=52',
                        type: 'get',
                        dataType: 'json',
                        _token: $('meta[name="_token"]').attr('content'),
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
                        },
                        cache: false,
                        success: function (response) {
                            $(this).hide();
                        }
                    });

Generally, jquery correctly sends a query to php (Laravel).
The problem occurs in deleting files. The first file is deleted correctly. The next file can not be slept.
I suspect that I have an invalid X-CSRF-TOKEN token after deleting the previous file.
How can I fix this problem?
Comment: What is '_token'? Is it simple laravel api token?
Answer: In js code:
$(".removeThisFile").click(function () {
    var id = $(this).attr("id");
    $('.file-id-' + id).hide();
    $.ajax({
        url: 'http://test.test/psCMS/removeOtherFile/'+id,
        type: 'get',
        dataType: 'json',
        cache: false,
        success: function (response) {
            $(this).hide();
        }
    });
});

In route file (web.php):
Route::get('/psCMS/removeOtherFile/{id}', 'YourController@removeOtherFile');

In controller:
public function removeOtherFile($id){

    $my_id = $id;
    // here is your id
}

Answer: Its possible that you may have some x-csrf issues, as this doesn't look like what I'm used to seeing (though it may work just fine).  You might have better luck using the @csrf in the top of your form, and calling a general header in an ajax setup method.
$.ajaxSetup({
 headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
 }
});

However, to directly answer you question, I believe the issue is much easier - I think it is a typo. You've hard coded the id.  Try changing this line:
url: 'http://test.test/psCMS/removeOtherFile?id=52',

to:
url: 'http://test.test/psCMS/removeOtherFile?id='+id, // <--- note the variable


For a given CDF compute $\Bbb P(X^2 \in A)$

Question: Let
$$
F(x)=\begin{cases}
0  &  \text{if} & x <-1\\
\frac{1}{4} & \text{if} & x \in [-1,0)\\
\frac{x+1}{4} & \text{if} & x \in [0,3)\\
1 & \text{if} & x >3
\end{cases}
$$
I need to get $\Bbb P(X^2 \in (\frac{1}{9},1]) $ and I got
\begin{align}
\Bbb P(X^2 \in (\frac{1}{9},1]) &= \Bbb P(X\in [-1,-\frac{1}{3})\cup(\frac{1}{3},1]) \\
&= F(1)-F(\frac{1}{3})+F(-1)-F(-\frac{1}{3})=\frac{1}{2}-\frac{1}{3}+\frac{1}{4}-\frac{1}{4} \\
&=\frac{1}{5}
\end{align}
Am I right?
Answer: It should be $F(1)-F(\frac{1}{3})+F(-\frac{1}{3})-F(-1)$, not $F(1)-F(\frac{1}{3})+F(-1)-F(-\frac{1}{3})$,
though in this particular case they happen to be te same.
Finally, $\frac{1}{2}-\frac{1}{3}=\frac{1}{6}$, not $\frac{1}{5}$.


Least positive integer $n$ such that any set of $n$ pairwise relatively prime $>$ $1$ and $<$ $2005$ contains at least one prime number.

Question:
Find the least positive integer $n$ such that any set of $n$ pairwise relatively prime integers greater than $1$ and less than $2005$ contains at least one prime number.

The given solution of the above problem opens with the following line:

The example $2^2, 3^2, 5^2,\dots, 43^2$ where we considered the squares of the first $14$ prime numbers, shows that $n\geq 15$.

How does this happen? Why are we considering squares of primes?
Answer: The condition is: If we pick any arbitrary set of $n$ numbers so that all numbers in set are pairwise relatively prime then there exists a prime number in that set.
So, if $n \le 14$, then when we pick the set $\{ 2^2,3^2, \ldots , 43^2 \}$ (which has $14$ numbers in set) where there is no prime in this set, which contradicts to our condition. Thus, $n \ge 15$.
They choose squares of primes to guarantee that

All numbers are pairwise relatively prime.
The set doesn't contain any prime number.

If we can find set $A$ that guarantee this, then $n \ge |A|+1$ (the proof using contradiction is similar to when $|A|=14$). Thus, it suffices to find set $A$ with maximal number of elements.
Note that we can choose differently $$B= \{ 2 \cdot 997, 3 \cdot 661, 5 \cdot 397, 7 \cdot 269, 11 \cdot 173, 13 \cdot 151, 17 \cdot 113, 19 \cdot 103, 23 \cdot 83, 29 \cdot 67, 31 \cdot 61, 37 \cdot 53, 41 \cdot 47, 43^2 \}.$$ This also shows that $n \ge |B|+1=15$. It seems that $n=15$ is the smallest possible.
The randomly chosen set $A$ is to show that $n \ge 15$. But that's not all the problem required, we also need prove that $n=15$ is the smallest possible.


How do I free a variable set using variable_set()?

Question: I have used variable_get(), and variable_set() in my form search, but when I visit another page, and come to the module again, it shows the previous results. How can I free the variable at the time of reloading the module?
/**
* @file
* The theme system, which controls the output of Drupal.
*/
function myform_help($path, $arg) {
    switch ($path) {
        case "admin/help#myform":
        return '
' . t("MyForm Module") . '
';
        break;
    }
}

function myform_menu() {
    $items['myform/newform'] = array(
        'type' => MENU_CALLBACK,
        'access arguments' => array('access content'),
        'page callback' => 'drupal_get_form',
        'page arguments' => array('myform_newform'),
        'access callback' =>TRUE
    );
    return $items;
}

function myform_newform($form, &$form_state) {
    //Create a list of headers for your Html table (see Drupal 7 docs for theme_table here

    $form['search'] = array(
        '#type' => 'textfield',
        '#title' => t('Search for Members'),
        '#size' => 60,
        '#maxlength' => 128
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Search'),
        '#submit' => array('myform_newform_submit'),
    );
    $header = array(
        // The header gives the table the information it needs in order to make
        // the query calls for ordering.
        array('data' => t('ID'), 'field' => 't.id'),
        array('data' => t('First Name'), 'field' => 't.fname'),
        array('data' => t('Last Name'), 'field' => 't.lname'),
    );

    if((variable_get('results'))!="") {
        $query = db_select('myform', 't')
            ->extend('TableSort')        //Sorting Extender
            ->orderByHeader($header)
            ->extend('PagerDefault')
            ->condition('lname',variable_get('results'),'=')
            ->limit(2)
            ->fields('t', array('id', 'fname', 'lname'));
        $results = $query->execute();
        foreach($results as $node)
        {
            $rows[$node->id]=array('data'=>(array)$node);
        }
    }
    else {
        $rows = array();
    }
    $form['pager_table'] = array(
        '#theme' => 'table',
        '#header' => $header,
        '#rows' => $rows,
        '#empty' => t('Empty Rows')
    );
    // attach the pager theme
    $form['pager_pager'] = array('#theme' => 'pager');
    return $form;
}

function myform_newform_submit($form,&$form_state) {
    variable_set('results',$form_state['values']['search']);
}

Comment: You can do by using variable_del($name) function but I think it not the better way. By this variable_del($name) function you can delete the stored value from the variable table.
Comment: variable_set() or variable_get() will store information in the variable table so I think it is not the better way. You can use sessions or cookies for this kind of functionality.
Comment: Yup Sessions and cookies could be used but I want to know is there any other way using variable set and get methods
Comment: Where to add variable_del($name) so that when form gets unloaded it should delete the variable which have been set
Comment: where you are creating your form array
Comment: In the form itself
Answer: In this specific case, you don't need to use persistent variables. It's sufficient to set $form_state['rebuild'] to TRUE in the form submission handler and set a value in the $form_state array that is then checked by the form builder function. The workflow in these cases is the following.

The form is used to ask input from users
The form submission handler uses that input to query the database and stores the result in $form_state (for example, in $form_state['rows'])
The form submission handler sets $form_state['rebuild'] to TRUE
The form builder checks the value in $form_state is set (for example, with if (isset($form_state['rows'])) { /* ... */ }) and shows those values in a table before the form

The array key used to store the value just needs to be a key that doesn't conflict with Drupal core or contributed modules core. To avoid that, the key name is usually prefixed by the module machine name (or it's the module machine name).


What is ideal directory for kafka messages

Question: The default value of logs.dir=/tmp/kafka-logsin server.properties. Usually /tmp is avoided from keeping any important files and we are storing messages and offsets!
Any particular reason why one may not choose /var/log/kafka-logs or /opt/kafka-logs
NOTE - Assuming /tmp, /var/log are all same file-system type.
Comment: It baffles me that kafka developers continue to have /tmp as the default location for critical data! Why is there not more noise about this?
Answer: You'll always find me placing files in standard directories or as close to them as possible.
The reason for this is so that future admins can find them later -- because very often that future admin is me!
Consider logs, for instance, since that's what you have brought up. I would create a subdirectory in /var/log to store these, such as /var/log/kafka. The directory /var/log is where most admins will go first to look for logs for any package. Apache's default of /tmp/kafka-logs is pretty senseless, as you've already discovered. Cloudera's default log directory /var/log/kafka makes much more sense.
If it turns out that you need to mount a disk partition to store logs, you don't have to change the log directory; instead, you can mount the new disk space directly at /var/log/kafka.
And /opt is intended for large third party packages; it's not where I expect to find most things. There are few standards or conventions for anything in this directory, so things could end up difficult to find.
Comment: Please be aware that kafka logs are not really logs but kafka stream messages https://stackoverflow.com/questions/42757742/kafka-logs-folder-too-huge . So the recommendation for /var/log/ might not be the best one :)
Comment: And, hopefully you don't mind, but the default is from cloudera which is an spinoff like ambari, confluent-kafka. The question only contains kafka, so that might be apache kafka http://kafka.apache.org/090/documentation.html#brokerconfigs .They do have at least a couple of difference between them. I hope this helps us both.
Comment: That's all true. I'm going to think about it a bit more and will probably edit this later.
Comment: I understand why /tmp is not recommended, but why /opt as well? if it is intended for third party packages then it means this doesn't get cleaned up as /tmp is...?
Answer: The best place is a separate partition mounted to have all of the data in the same place, which holds no other function for the OS and/or other installed packages
/var/log/ is being handled by other programs also, logrotate etc. so not really safe to have your Kafka data there
/opt/ should not hold any program data, only additional installed software
Depending on what kind of messages you have, you might want to limit any interaction/possible issue with them.
Comment: You could create an directory under /var/ and hold the data there. Make sure that the kafka folder does not reside on root(as that might crash the VM) and you have enough space there for what you need. Np, we are all learning.
Comment: Thanks @Alex H. I am not so good in linux file system, so don't understand the partitions/blocks that well. Can you please provide me an example in terms of dir?


General procedures and tips for solving dependency problems (Debian, Lenny)

Question: I'm more or less as good a sysadmin as my serverfault rep mirrors. I have to upgrade a Debian (lenny) server with Plesk control panel. Plesk is supposed to manage that but the upgrade over the control panel doesn't work and I read and hear that this is often the case.
So I have to do it manually and now I'm running into seemingly circular dependency problems...
I get a lot of messages like this:
psa-updates depends on sw-cp-server (>= 1.0-6); however:
  Package sw-cp-server is not configured yet.
dpkg: error processing psa-updates (--configure):
 dependency problems - leaving unconfigured

My sources.list is up to date and working, apt-get clean and apt-get update works fine and completes without errors.
What are the correct ways of solving such problems?
Answer: Sounds like your previous install/update was interrupted/unsuccessful. You need to check a few things:

That your apt sources list points to a valid server and has the necessary packages there on the server. This ensures that you will be able to update and install packages.
That your local apt-cache is up-to-date. Do a apt-get update on your system. This ensures that apt can find your updates. Sometimes, it looks for an older package that no longer exists on a system.
Do a dpkg -a --configure in case a previous install/update was interrupted. If a previous one was interrupted, there might still be some unsolved configuration problems that prevent new packages from installing successfully.

Hope it works. Good luck!
Comment: Thanks for your answer. Points 1 and 2 I'm familiar with and issues with these have been resolved. Point 3 is new and I will look into it right away!
Comment: Issuing `dpkg -a --configure` results in `Starting SWsoft control panels server... stale pidfile. failed` and a whole bunch of previous errors, as posted in the original question.
Comment: Oh, sounds like the SWsoft control panel server needs to be restarted. You might get away with just deleting the pidfile manually and stopping/starting the service manually. Then, repeat the dpkg process.
Comment: Can you give me a hint about where to find that pid file?
Comment: They're typically in `/var/run` directory.
Comment: yes, that's where they are :) I deleted the pidfile of SWsoft but still the same problem. In the meantime my research has shown that this could be a problem with openssl, but even downgrading openssl didn't resolve the situation.
Comment: ...and got further with this now: http://forum.parallels.com/pda/index.php/t-101127.html
Comment: it wasn't openssl, it was a problem with several plesk control panel instances running and blocking tcp:10001. problem resolved.


Does Transitivity imply Recurrence?

Question: Consider the usual Poincaré recurrence theorem, and the notion of topological transitivity e.g. from here.
Does transitivity (on a compact measurable space) imply recurrence?
Due to different uses of the terms transitivity and recurrence in literature, I could not find a proper answer
Answer: Within the usual definitions in topological dynamics the answer is yes:
Let $(X,d)$ be a complete separable metric space ($X$ compact is allowed here) and let $X$ be perfect (that is, $X$ has no isolated points). Moreover
let $f:X \to X$ be continuous, and let $O(x)$ and $\omega(x)$ denote the orbit and the omega limit set of $x \in X$ (with respect to $f$). Within this setting the following theorem of Birkhoff is known:
Theorem: Equivalent are:

$f$ is topological transitive;
$D(f):=\{x \in X \mid \overline{O(x)}=X\} \not= \emptyset$;
$D(f)$ is a dense $G_\delta$-set.

Next, $x \in X$ is called recurrent if $x \in \omega(x)$. As each $x \in D(f)$ satisfies $\omega(x)=X$ we have that each $x \in D(f)$ is recurrent.
A dense $G_\delta$-set is "big" in the topological sense (its complement is of first category in the sense of Baire). Having a complement of first category can be considered as the topological analogue to "having a complement of measure $0$". Thus, in view of Birkhoff's Theorem
one can say that if $f$ is topological transitive then most points are recurrent.
Comment: Thank you!, this is what I was thinking
Comment: More specifically, J. C. Oxtoby in his book _"Measure and Category"_ says that the set of not recurrent points is in fact both **of first category and null measure**.
However J. W. Milnor, introducing some measure on the space and the concept of _measure transitivity_ shows that the answer is still **yes**

Does Transitivity imply Recurrence?


Wronskian of two independent solutions equaling zero at a specific point only?

Question: Given $y_1(x)=\sin(x^2)$ and $y_2(x)=\cos(x^2)$, I constructed a linear, homogenic ODE of order 2 by solving:
$$
        \begin{vmatrix}
        y & y_1 & y_2 \\
        y' & y_1' & y_2' \\
        y'' & y_1'' & y_2'' \\
        \end{vmatrix}=0
$$
Now, I noticed that the Wronskian of $y_1$ and $y_2$ at $x=0$ equals $0$. But the Wronskian of independent solutions is never $0$. And if it $0$ at one point, it is zero everywhere, which I don't see happening here, as
$$
        W(y_1,y_2)=\begin{vmatrix}
         y_1 & y_2 \\
        y_1' & y_2' \\
       \end{vmatrix}=-2x
$$
How does this make sense?
Answer: make sure that the coefficient of the highest order derivative doesn't vanish anywhere in the domain and the coefficient of the rest of the derivatives are continuous.specially check at x=0
Comment: I agree. Indeed, at $x=0$ the coefficient of $y''$ is the determinant $$\det\begin{bmatrix} 0 & 1 \\ 0 & 0\end{bmatrix}$$
Comment: Thank you for your answer. If the coefficient of the highest order derivative vanishes, what does it imply?
Comment: See that doesn't imply anything straight away but you can't just blindfoldly apply the properties of wronskian without taking account the other assumptions under which the properties of wronskian get applied.please go through your concept and you yourself will find an answer for your question....