Broken results on batch convert with ImageMagick command line on Linux

Question: This is my IM command:
/usr/bin/convert
'src.tif'
  -limit memory 0
  -limit map 0
  -limit file 0
  -alpha transparent
  -clip
  -alpha opaque
  -resize 800x600
  'end.png'
2>&1

So this will remove the white background of my TIFF by clipping the path that is given in the file. It will be resized and saved as transparent PNG.
I got no errors from IM running this.
But if I run this command with PHP to execute it on about 13000 files - I sometimes get these errors:
sh: line 1: 25065 Killed                  /usr/bin/convert \
            'public_html/source_files/XXXX123/XXXX123/XXXX123.tif' \
             -limit memory 0 -limit map 0 -limit file 0 -alpha transparent \
             -clip -alpha opaque -resize 800x600 \
            'public_html/converted/XXXX123/XXXX123/XXXX123_web.png' 2>&1

sh: line 1: 25702 Killed                  /usr/bin/convert \
            'public_html/source_files/XXXX123/XXXX123/XXXX123.tif' \
             -limit memory 0 -limit map 0 -limit file 0 -alpha transparent \
             -clip -alpha opaque -resize 800x600 \
            'public_html/converted/XXXX123/XXXX123/XXXX123_web.png' 2>&1

But the bigger problem is: Some of the pictures are broken. Below is a "bad" image on the left, a "good" image on the right (ondrag/on a dark background you see the problem better):

On running the command manually the result was ok. Only on running this PHP loop script will provide broken results. ( PHP loop script )
I run the script this way: php55 run.php. A simple loop with find as shell script provides same results.
So I searched, asked in the IM discourse server and run this procedure on 2 machines with different distribution (Debian Wheezy, Ubuntu Server 14.04)
Note/EDIT 1: Running the command in the terminal with the same file provides a perfect result.
EDIT 2: Added example TIFF file here
Comment: Have you tried limiting/unlimiting the time, with `-limit time X` where `X` is in seconds. How about posting a working and a broken input image?
Comment: How much free space on your disk do you *really* have? How much RAM is available on your system? How many *inodes* are taken and how many are still available on your file system? Your `-limit [memory|map|file] 0` settings basically tell ImageMagick: *"Ignore all limits. You've enough resources!"*
Comment: @MarkSetchell, Links to broken / good images are in the post as well under the second code block.
Comment: The links are PNG files, not TIFs.
Comment: Sorry, some example files are here: http://gab3.de/share/new/
Comment: Another question: Is your problem reproducible? Does it return the b0rken result every time you run the command inside the PHP loop? (I mean: if running in the loop, does the b0rken result occur every time for the same image?) And every time when manually run the command for the b0rken image in a shell/terminal it will return a "good" result? Or is the problem appearing intermittently, affecting image A in one run, and image B in another run?
Comment: Did you try unlimiting the time yet?
Comment: The time isn't limited afaik. - The broken pictures are randomly different. Sometimes the first 150 are good and then nearly every third picture is broken. Sometimes the 22nd picture is already broken.
Comment: Your IM version is rather outdated, being v6.7.7. -- I wonder if you are experiencing a bug with the specific version you have installed. Do you have the opportunity to test your batch process with the same files on a different system with a more recent IM version?
Comment: I've here a VPS with Ubuntu 14.04 - and the latest stable I get for this system is 6.7.7
Answer: I'm not sure if this is an answer. For now it is pure speculation. So here goes...
By setting the limits to a 0 value, you are basically telling ImageMagick: "Your resources are not limited at all. You do not need to care for any limits."

What if didn't set any limit? Remove all -limit ... 0 parts from your command. In this case ImageMagick would use its built-in defaults, or the otherise defined settings (which may be contained in the policy.xml file of your IM installation, or through various environment variables). You can query the current limits of your system with the following command:
identify -list resource

On my system, I get these values:
File       Area     Memory     Map       Disk  Thread  Throttle        Time
---------------------------------------------------------------------------
 192    4.295GB       2GiB    4GiB  unlimited       1         0   unlimited

What if you did set these limits to a reasonable value, that matches your system's really available resources? Assuming you have: 8 GByte of RAM, 50 GByte of free disk space and plenty of free inodes on your disk volume. Then try to set it like this: -limit disk 10GB -limit memory 3GB -limit map 6GB.

ImageMagick resource management
For all its processing and intermediate steps, ImageMagick needs access to an intermediate pixel cache memory/storage, before it can deliver the final result.
This need for pixel cache storage can be satisfied by different resources:

heap memory,
anonymous memory map,
disk-based memory map,
direct disk.

ImageMagick makes use of all these resources progressively:

Once heap memory is exhausted, it stores pixels in an anonymous map.
Once the anonymous memory map is exhausted, it creates the pixel cache on disk and attempts to memory-map it.
Once memory-map memory is exhausted, it simply uses standard disk I/O.

Disk storage is cheap but very slow too: it is in the order of 3 magnitudes (a thousand times) slower than memory. Some speed improvements (up to 5 times) can be obtained by using memory mapping to the disk-based cache.
ImageMagick is aware of various ways to control the amount of these resources:

Built-in default values. These limits are: 768 files, 3GB of image area, 1.5GiB memory, 3GiB memory map, and 18.45EB of disk space.
policy.xml config file. Please look up what's in your own policy.xml file. Use convert -list policy to find the location of this file first. Then use cat /some/path/policy.xml to see its contents. (The file uses an XML syntax. Don't forget: anything enclosed in  is a comment!) It also contains comments explaining various details. The policy.xml can define much more things than just the available limit resources. Settings in policy.xml take precedence over the built-in default values if they are defined there.
Environment variables. Here is a list of environment variables which can limit IM resources: MAGICK_AREA_LIMIT (image area limits), MAGICK_DISK_LIMIT (disk space limit), MAGICK_FILE_LIMIT (maximum no. of open files limit), MAGICK_MEMORY_LIMIT (heap memory limit), MAGICK_MAP_LIMIT (memory map limit), MAGICK_THREAD_LIMIT (maximum no. of threads limit) and MAGICK_TIME_LIMIT (maximum elapsed time in seconds). These environment variables, if set, take precedence over the policy.xml config file.
-limit <name> <value> settings on command line. The following <names> are recognized:

width (maximum width of an image). When limit is exceeded, exception is thrown and processing stops.
height (maximum height of an image). When limit is exceeded, exception is thrown and processing stops.
area (maximum number of bytes for any single image to reside in pixel cache memory).  When limit is exceeded, automagical caching to disk (possibly memory-mapped) sets in.
memory (maximum memory allocated for the pixel cache from anonymous mapped memory or heap).
map (maximum amount for memory map allocated for pixel cache).
disk (maximum amount of disk space permitted for use by pixel cache). When limit is exceeded, pixel cache is not created and a fatal exception is thrown.
files (maximum number of open pixel cache files). When limit is exceeded, all subsequent pixels cached to disk are closed and reopened on demand.
thread (maximum number of threads which can in parallel).
time (maximum time in seconds a process is permitted to execute). When this limit is exeeded, an exception is thrown and processing stops.

The -limit setting on a command line takes precendence and overrides all other settings.
Comment: I've added the 'limit 0' just for testing. Changes nothing. Will try with limits.
Comment: The machine is running a Intel Xeon with 4c/8t @ 3.3GHz, 32GB RAM, 3TB HDD space (2,2TB free space). The command returns this https://gist.github.com/CodeBrauer/496e56397053c89d61b7
Comment: So what limit do you prefer for the machine mentioned one answer before?
Comment: @GabrielW: Which exact version is your ImageMagick? Please provide (links to) the output of the following commands: `convert -version` and `convert -list configure`.
Comment: So i tried it now `-limit disk 50GB -limit memory 10GB -limit map 20GB` and it works (for now) like a charm - my script is now about 15% done and all images I watched are looking good.


Colocar um hífen quando o valor for 0 no select

Question: Como posso fazer no mysql uma query (SELECT) para que quando o valor for igual a 0, substitua-o por hífen(-).
Campo do valor: int.
Comment: Um update? Qual o tipo da coluna?
Comment: Qual é o tipo de campo? varchar?
Comment: Um `SELECT` o campo é do tipo `int`
Answer: Você pode usar um IF na consulta.
O IF recebe três "parâmetros", o primeiro é a condição, o segundo é o valor que a coluna assumirá caso a condição seja atendida e o terceiro é o valor que a coluna vai assumir caso contrário.
Select If(Campo = 0, '-', Campo) From Tabela

Documentação do IF
Answer: @Eduardo Santos,
Caso você queira trocar o 0 pelo hífen em um select você faz assim:
SELECT IF(seu_campo = 0, '-', seu_campo) AS nome_para_esse_resultado FROM sua_tabela;

Answer: Select IIF(Campo = 0, '-', campo) AS CAMPOSELECIONADO from TABELA

Isso funcionaria para o seu caso.


Can a Quine-Rosser ordered pair be a coordinate of itself?

Question: Given a set $x$ and a Quine-Rosser ordered pair $p\ne\emptyset$, is it possible to have $p=(p,x)$ or $p=(x,p)$?
I am working in the context of ZFC to be clear.
I'm asking this because with this definition of ordered pairs there is, in general, no membership chain linking $a$ or $b$ to $(a,b)$.
I tried to do a proof by contradiction, but didn't manage to find any. In fact, I tried to prove that
$p=(p,p)$ leads to a contradiction, and realised just moments ago that this is not the most general case
anyway, so in the end I spent quite some time trying to prove the wrong thing.
Does anybody know if this is possible?
Comment: Assuming that you follow the definition on wikipedia, let $p$ be any set such that no element of $p$ contains a natural number. Then you can see that $p = (p, \emptyset)$.
Answer: Consider the sets $p = \{ \{n\} \:|\: n \in \mathbb{N} \}$ and $q = \{ \emptyset \}$.
We have $\varphi[p] = \{ \varphi(x) \:|\: x \in p \} = \{ \varphi(\{n\}) \:|\: n \in \mathbb{N} \} = \{ \sigma[\{n\}] \:|\: n \in \mathbb{N} \} = \{ \{n + 1\} \:|\: n \in \mathbb{N} \} $.
We have $\psi[q] = \{ \psi(\emptyset) \} = \{ \{0\}\}$.
Therefore, $(p,q) = \varphi[p]\: \cup \psi[q] = \{ \{n + 1\} \:|\: n \in \mathbb{N} \} \:\cup\: \{ \{ 0 \} \} = \{ \{n\} \:|\: n \in \mathbb{N} \} = p$.
Comment: Well, that was way simpler than I thought. Thanks.


creating a custom loop for children to use: eg. repeat(5){ //code to be executed 5 times }

Question: I'm trying to simplify the introduction of loops to children in JS and p5.js with writing some helper functions to ease difficult things. What I'm aiming for is something like repeat(5){ //code to be executed 5 times }
something similar can be achieved with a higher order function, but it's not quite as simple/transparent as I hope it could be.
for example:
function repeat(n = 1) {
  let i = 0;
  return fn => {
    while(n--) {
      i++;
      fn(i)
    }
  }
}

// example usage:
repeat(10)(i => {
  console.log('floop boop', i)
})

but the usage and curly/parens will confuse children. I'm aware that a while loop is one direction to go, but It's sort of goes in an inverse direction of what a repeat loop might do. It's the direction to push them, but maybe not ideal for day 1 of coding.
ultimately We could eventually use it something like:
let i = 0;
repeat(10){
   i++
   console.log('we are repeating and we're on iteration number ', i)
}

Comment: This is incredibly more confusing than a basic loop
Comment: I must stress that anonymous functions are not day 1 material, it will confuse your students! Teach them proper foundational knowledge -- variables, conditionals, loops, functions, THEN get into the more advanced work, such as anonymous functions, etc.
Comment: `Array(n).map(() => // code)`
Comment: If you have lodash, there is a `_.times` method that does this. Additionally, you can use `map` or `forEach` but make sure the array is filled or it won't work. EG: `Array(100).fill(undefined).forEach(() => { /*stuff*/ })`
Comment: You can try introducing recursion before loops if you want to go down the functional route.
Comment: I'm aware that loops are unavoidable and that they should be introduced after variables, etc., but what I'm trying to write is a function a 7 year old can use and understand immediately to do visual rendering with p5.js within a workshop setting.
Comment: The syntax you're asking for isn't possible in JavaScript.
Answer: If you are teaching JavaScript you won't be able to avoid first class functions. I would start by creating a method called repeat, it takes in a number of times to repeat and the function with the behaviour you want repeated.
function repeat(times, fn) {
  var i = 0;
  while(times--) {
    i++;
    fn(i);
  }
}

repeat(10, function(i) {
  console.log('we are repeating and we\'re on iteration number ', i);
});

I agree that a higher order function may be confusing. In both cases you don't need functions to teach loops.
Comment: you wouldn't need to teach functions right away when using something like p5.js for rendering, yes eventually, but not right away. How can we talk about the idea of loops to a group of 7 year olds in a one day workshop? having a repeat function seems like a straightforward way.
Answer: I'm using Coffescript and p5.
for i in range 10
  rect 20*i,20,10,10
Range has same defintion as in underscore.
Python indentation without colon
P5dojo.com is my site.


how to set the source connection in drupal d2d migrate

Question: I am migrating my taxonomy and users from d6 site to d7 site. How can I set the legacy connection of source db of d6 site.
The user is root and password id empty with source database name as d6 for the Drupal 6 site.

hook_flush_caches().

 $common_arguments = array(
        'source_connection' => 'd6_migration',
        'source_version' => 6,
      );

will it migrate data from d6 to d7 when I install the custom migrate_d6 module in Drupal 7 site?
My Settings file of Destination project is
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'd7',
      'username' => 'root',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  'd6_migration' =>
  array (
    'default' =>
    array (
      'database' => 'd6',
      'username' => 'root',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

Comment: I tried changing the key second key value and I got some errors which is better than nothing at all http://pastebin.com/LLgxW53X
Comment: The code you have is correct. From the errors you list below it seems you have issues with your drupal 6 database. Are you sure you have the full database and it is not corrupt in any way and you don't have a prefix for the tables?
Answer: The migrate module provides basic migrate functionality while the migrate_d2d module extends on that functionality providing interfaces for reading and importing into Drupal 5, 6 and 7. Migrate comes with Drush integration and supports rolling back migrations which is very handy during development.
Add the following code into your settings.php file or you can specify database connection details within your migration scripts:
<?php
// Our Drupal 7 database configuration.
$databases = array (
'default' =>
  array (
    'default' =>
    array (
      'database' => 'db_drupal7',
      'username' => 'drupal7_user',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  // Here we add in the connection to our Drupal 6 database.
  'legacy' =>;
  array (
    'default' =>;
    array (
      'database' => 'db_drupal6',
      'username' => 'drupal6_user',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

If you want to create the script for migrating the content than please have look at this useful tutorials:
http://devblog.com.au/migrating-drupal-6-to-drupal-7-with-the-migration-framework
https://drupal.org/node/1813498

Personal suggestion:
Now the migrate_d2d module is providing a stable UI for migration the contents and that is very easy to do as well, have a look at it documentation here: https://drupal.org/node/1813498
Also if you have a larger database than you can use the drush commands to migrate the contents after setting up the database connections, the list of drush commands for migrating the content: https://drupal.org/node/1561820
Comment: I tried ur method but i am getting an error "PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'source6.filter_formats' doesn't exist: SELECT f.format AS format, f.name AS name FROM {filter_formats} f; Array ( ) in DrupalVersion6->getDefaultFormatMappings() (line 30 of /home/vishal/Dropbox/sites/destination7/sites/all/modules/migrate_d2d/d6/d6.inc)."
Comment: @vishal It seems you are half done as the source connection is correctly taking place (which was your main concern) otherwise you wont be getting this error.
Now coming to error, the reason of this error is "filter format table does not exists in you drupal 6 installaton", Have you manually removed it, otherwise this table is by default created on drupal installation, this is the screenshot of table: http://awesomescreenshot.com/00a1rx24ec

So may you be you try importing only the "format filter" table from the fresh drupal installation of drupal 6. And that must contain the required formats
Comment: yes the able was deleted that was the issue thank you.
Comment: its not allowing me for another 2 hrs. will do it once I am allowed :)
Answer: You can enter the db connection inside the module without having to change the settings.php file, like this:
$common_arguments = array(
'source_version' => 6,
'source_connection' => 'legacy',
'source_database' =>  array('driver' => 'mysql','database' => 'dbname','username' => 'dbuser','password' => 'dbpass','host' => 'localhost','prefix' => '',)

);
I hope this will help you
Ciao
r.
Comment: does this work for localhost(offline server on my computer) to remote server?
Comment: this did not work for me.
Comment: FWIW, this is essentially what the module documentation describes, here: https://www.drupal.org/node/1813498 Works as expected.
Answer: Can you please delete the semicolons after
'legacy' => and 'default' =>?
This is almost the only settings.php example you find by google.
Yeah, the error is already in http://devblog.com.au/migrating-drupal-6-to-drupal-7-with-the-migration-framework where you cited from.
It should look like this:

'default' =>
  array (
    'default' =>
    array (
      'database' => 'db_drupal7',
      'username' => 'drupal7_user',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  // Here we add in the connection to our Drupal 6 database.
  'legacy' =>
  array (
    'default' =>
    array (
      'database' => 'db_drupal6',
      'username' => 'drupal6_user',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

Thank you for the example. Rare that nobody have noticed this before :-) Drush directly shows errors for the two semicolons.
Sorry, that i'm not writting a comment to your post.
I've not enough bucks. 50 is minimum.


Population or Sample Standard Deviation: monthly climate data

Question: I have daily mean temperature values for every day of every month for 90 years.
I want to figure out:

"SD$_m$": the standard deviation of daily temps across all days in a given month, for each month
"SD$_{yr}$": The standard deviation of monthly means for a given year, for each year.

My question: Do I use sample [s] or population [$\sigma$] standard deviations for each of these above calculations?
$$s = \sqrt{\frac{\sum_{i = 1}^N(x_i - \mu)^2}{N - 1}} $$
$$\sigma = \sqrt{\frac{\sum_{i = 1}^N(x_i - \mu)^2}{N}} $$
My goal is to compare SD$_m$ to SD$_{yr}$ via regression to gauge their relationship for developing a climate metric. My confusion comes from the fact that both metrics are calculated from the same data, but both metrics would qualify "population" differently (i.e., SD$_m$'s "population" consists of all days in each given month while SD$_{yr}$'s population consists of all months within a given year). Or am I thinking about this incorrectly??
Answer: You probably want the first equation. The difference between the two quickly gets into mathematical statistics and opinions (we don't all agree on the best way to estimate mean; for instance, look at the midhinge or trimean), but R calculates variance the first way (sd(X)). Python/NumPy calculates it the second way (np.std(X)), though, so it's a matter of style, but you'd probably want to use the first equation.
The first estimator is related to an unbiased estimator (see footnote), meaning that, on average, it estimates the correct population variance. The second estimator is biased but has a nice statistical property known as maximum likelihood.
However, both are instances of statistical inference, where the goal is to make a conclusion about some greater population, given that we have sampled some subset of that population. It's not clear to me that you're doing inference. The opposite would be descriptive statistics, where you're just describing the values you have. I would argue that you have the population under consideration, in which case, your second equation is the correct one to do since it aligns with the calculus of population variance (related to something called the second moment of a distribution). Nonetheless, your field probably uses that first equation you gave, as that is the standard deviation estimator given in freshman or AP statistics that so many people take and use as their statistics background.
Footnote: The estimator you've given is biased, but you're taking the square root of an unbiased estimator for variance. Amazingly, the square root of that unbiased estimator winds up being biased, but I suppose being the square root of an unbiased estimator is something.
Footnote 2: There are examples of silly estimators that are, in some sense, legitimate (the technical term is admissible). For instance, you could define your estimate as a constant function, saying that standard deviation is 3 no matter what data you collect, and that would be an admissible estimator since it gets the right answer when population standard deviation indeed is 3. So you see how the estimator to pick can be a matter of opinion!
Comment: No, R uses also the first way (denominator $n-1$): `var(c(-1, 0, +1))
[1] 1`


Proof that magic square cannot be transformed

Question: How do I prove that the first magic square below cannot be transformed into the second by a sequence of row and column exchanges.
$$(a)\;\pmatrix{15&2&1&12\\4&9&10&7\\8&5&6&11\\3&14&13&0}\qquad\qquad(b)\;\pmatrix{14&8&5&3\\9&15&2&4\\7&1&12&10\\0&6&11&13}$$
Answer: Look at row 2 of the second matrix; it contains 15 and 4. After any sequence of column swaps,  any row that contains 15 and 4 will still contain these two numbers. A similar statement goes for any sequence of row-swaps: since there's a row containing 15 and 4 before the swaps, there'll always be some row containing 15 and 4 after the swaps. But the first matrix doesn't have 15 and 4 in the same row.
A proper proof of this would involve induction, with the inductive hypothesis being that after $k$ swaps, the matrix will have a row containing both $4$ and $15$, and the overall claim being that for any sequence of $n$ operations applied to matrix "b", the $n$ result cannot be matrix "a". But I'll let you write that out.
Comment: Maybe add that column swaps will also leave 15 and 4 in the same row, since both row and column swaps are allowed. (And +1)
Comment: I tried to work out the proof by induction, but I am having trouble in how to do it. Can you please help me?
Comment: Why don't you write out what you have so far, and I'll nudge you along. (You can write it in the original question by clicking on "edit".)


What is the number of n-digit numbers that can be written with the numbers 2, 3 and 4 that add up to be odd?

Question: What is the number of 4-digit numbers that can be written with the numbers 2, 3 and 4 that add up to be odd?
for example:
3-23-32-43-34-223-243-232-234-322-324-342-344-...
...
n-digit numbers.
Comment: Try to prove by induction that the answer is $\frac12(3^n-1)$.
Comment: Welcome to MSE. For some basic information about writing mathematics at this site see, *e.g*., [basic help on mathjax notation](https://math.stackexchange.com/help/notation), [mathjax tutorial and quick reference](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference), [main meta site math tutorial](https://meta.stackexchange.com/questions/68388/there-should-be-universal-latex-mathjax-guide-for-sites-supporting-it/70559#70559), and [equation editing how-to](https://math.meta.stackexchange.com/questions/1773/do-we-have-an-equation-editing-howto).
Answer: Let $a_n$ be the number of $n$-digit numbers with digits from $\{2,3,4\}$ with an odd number of $3$s.  Consider two mutually exclusive cases:

If the first $n-1$ digits contain an odd number of $3$s, the $n$th digit must be $2$ or $4$.
If the first $n-1$ digits contain an even number of $3$s, the $n$th digit must be $3$.

These two cases imply that
$$a_n = 2a_{n-1} + (3^{n-1}-a_{n-1}) = a_{n-1} + 3^{n-1}.$$
The initial condition is $a_0=0$, and iterating the recurrence yields
$$a_n = \sum_{k=0}^{n-1} 3^k = \frac{3^n-1}{3-1} = \frac{3^n-1}{2}.$$


Why is a network is converging slower with Nesterov than with plain SGD?

Question: With Nesterov, I had to lower the learning rate to 1e-5 to avoid exploding gradients even though I have He weight initialization. As a result the network is not converging to the same result as the network had with plain SGD. Does it mean that SGD is performing better ?
Answer: Nesterov momentum works better than SGD in a mathematical idealization of the problem. It requires the following assumptions:

The cost function is a quadratic bowl in the region you are evaluating
You are using the correct momentum coefficient

The first assumption could be inaccurate if your cost surface has many local minima in the region you are evaluating. In Geoffrey Hinton's coursera lectures he suggests that using SGD to begin with and adding momentum later in the training may be a better idea because later on in training you will be closer to the global minima and there will be fewer local minima in the region.
The second assumption means that you have a hyperparameter to optimize and you are not guaranteed better results just by using a standard momentum coefficient.
Comment: I trained the network for 20 epochs using plain sgd and then another 20 epochs using Nestrov and the result was much better. It is strange for me how network converged in two different implementation. I did Apply He weight initialization to avoid exploding gradient but it seems didn't help so I'm back to the initial initialization sqr(6/(in+out)) using uniform


R: Express the residuals of a linear model in percentages

Question: I'm using rlm() method in R. My equation is y ~ x
The result should be y = x + error. How do I get this error from my results? Is this the Standard Error or the Residual standard error?
And how do I convert it in percentage?
Thank you in advance!
My results are shown below.
Call: rlm(formula = (B4FPS) ~ QPB4)
Residuals:
     Min       1Q   Median       3Q      Max
-10.8617  -3.7255  -0.6841   3.5321  15.3887

Coefficients:
            Value   Std. Error t value
(Intercept)  0.7982  1.6530     0.4829
QPB4         1.7062  0.0619    27.5548

Residual standard error: 5.524 on 187 degrees of freedom

Comment: You really need to explain why you want to get "the error" and transform it into a percentage.
Comment: Cross-post: http://stackoverflow.com/q/35866606/1412059
Answer: You should use the resid() function to get your residuals (i.e. errors). You can also formulate the values in the percentage, although I doubt that this may not be that meaningful. In any case, the following should get you the error values in percentage:
library(MASS)
data <- data.frame(x=rnorm(200), y=rnorm(200)+5)
lm1 <- rlm(y~x, data=data)
#getting the residuals in percentage (y-yhat)/y
err_percent <- 100*(resid(lm1)/data$y)
head(err_percent)
        1          2          3          4          5          6
 -1.445646 -44.408882 -15.993623   5.244996  -3.311191  24.453182

Keep in mind that some values will be negative because you are working with the residuals, and not the squared errors.
Comment: Thank you for your response. So in case I want the average error I will get the `mean(err_percent)` right? Also, I'll use `err_percent <- 100*abs(resid(lm1)/data$y)`
Comment: It very much depends on what you want to do with the results. If you care about both direction and magnitude--like by how much the predicted value is bigger or smaller than the data--then you may want to stick with the current response. But if you only need the magnitude of the difference between actual value and predicted value, then you may go ahead and use the absolute value of the residual values. Either way you are at a decent starting point.


Let $A, B$ be some sets such that $A\setminus B$ is infinite while $B$ countable or finite. Prove that $A\setminus B\sim A$

Question: The problem is the following :
Let $A, B$ be some sets such that $A\setminus B$ is infinite while $B$ countable or finite. Prove that $A\setminus B\sim A.$
I got stucked in this problem by trying the following :
First, as $A\setminus B$ and $A\setminus B\subseteq A.$ By lemma, I can assume that there is an injection $f$ such $f: A\setminus B\to A.$ Thus, now I need to find an injection from $A\to A\setminus B,$ so I can use the Schröder–Bernstein theorem, that states :
If there's an injection $f$ such $f: A\to B,$ and there's another injection $g$ such $g: B\to A,$ then there is a bijection from $A$ to $B.$
As $A\setminus B$ is inifinite, there must exist a set $C$ countable such $C\subset A\setminus B.$
Now I may write that $A= (A\setminus B)\cup(C)\cup(A\cap B).$ Since $A\cap B\subseteq B,$ and $B$ is countable or finite, then $A\cap B$ is countable or finite as well, that means there exists an injection $A\cap B\to\mathbb{N}.$
But $C$ is countable, then there exists an injection $l$ such that $l: A\cap B\to C.$
That is, I found an injection from $A\cap B\to C,$ but how can I find now an injection $A\to A\setminus B$ in order to prove by the theorem ?
Answer: $A\setminus B=A-A\cap B$.
If $A$ is countable , so is $A\setminus B$ as $A\setminus B\subseteq A$ and therefore map every $i$th element of $A\setminus B$ to $i$th element of $A$ to get a bijection.
If $A$ is uncountable then so is $A\setminus B$  because if not then $A=(A\setminus B)\cup (A\cap B)$ is countable which is a contradiction.
Since $A\setminus B$ is uncountable, it contains a countable (infinite) subset $C$.
$A\setminus B=(A\setminus B-C)\cup C$ and $A=(A\setminus B-C)\cup ((A\cap B)\cup C)= (A\setminus B-C)\cup X$, where $X=(A\cap B)\cup C$ is countable.
Define $f:A\setminus B\to A$ by $f(x)=x$, if $x\in A\setminus B-C$ and $f(x_i)=y_i\in X$ for $x_i\in C$. $f$ is one -one.


Why TestNG Optional parameter coming with double quotes

Question: With TestNG 7.0.0 and Eclipse 2019-03
When trying to use @Optional Parameters value, it comes with double-quotes. Not getting why?
Check the below screenshot for details.
[]
What am I missing? I expect the optional value without quotes just like myBrowser variable.
Comment: I have just run into the same problem. I know you posted this almost a year ago, but did you manage to figure out how to solve this annoying issue? As you wrote below, it's possible to avoid the problem my explicitly getting rid of the quotation marks with "replace" (or similar) but that feels like a weird workaround, so I'm wondering if there's a better way?
Answer: This is correct way to use @optional annotation.
I hope you know it that we can pass values from Testng.xml to @Test. If we are not passing any value from xml to test case then @Optional comes in picture. Whatever value we will pass in @Optional it will be default value. So that we need to pass this value in double quotes as it is not a function arguement.
For more detail, check it:
https://www.seleniumeasy.com/testng-tutorials/optional-annotation-in-testng
Comment: Thanks, @Muzzamil for your comment but still I am not getting this right. If you see the last output block from the link you mentioned, it shows **IamOptional** without any quotes. I am doing the same but I am getting it with double-quotes. If I add code like @Optional(mychrome) then it doesn't get compile. I have to add @Optional("mychrome") then it gets compiled but I am expecting here mychrome in the output without any quotes but it always showing with quotes. I know we can replace quotes from the string for a workaround but the based behavior remains unanswered.


There are 3 candidates for professorship and one is to be elected by the votes of 5 voters. In how many ways the votes can be given?

Question: I found by thinking that there are twelve ways to divide 5 votes into 3 sectors(where in a  sector there may be zero).
And each of those 12 ways should be permuted.
For example: one way of casting vote is to give three persons 1,0 and 4 votes respectively.  Any of these amount of votes can be got by any candidates. To get all possible way for casting those votes is to multiply 3! with that.
So total no ways of casting the  votes=  12 . 3! = 72
But the answer given in the book is 243. Can you please show me the correct way of solving it? Thanks.
Comment: No voter is a woman?
Answer: If each of the 5 men has 3 choices to vote for, there are $3^5=243$ possible ways to distribute the votes.


Chamar classe Java dentro do Oracle

Question: gostaria de saber se é possível a chamada de uma classe Java dentro do banco de dados Oracle.
Consegui instalar já a JVM dentro do servidor do Oracle, mas não consigo compilar a classe Java.
Alguém conhece alguma maneira de como posso fazer isso?
Comment: Qual a finalidade de "chamar" uma classe Java dentro do Oracle?
Comment: Provavelmente a questão é como executar um código da aplicação quando ocorre algum evento no banco de dados, por exemplo, se outro sistema insere dados numa determinada tabela. Esta é uma questão comum e recorrente. A melhor resposta que tenho, até agora, é ler o banco de dados ininterruptamente em determinado intervalo de tempo. Uma alternativa seria fazer o sistema que insere o registro "avisar" a aplicação através de uma chamada posterior à gravação. Porém, o ideal mesmo, seria abandonar essa técnica e partir para RESTful Web Services.
Comment: @utluiz sério que você interpretou isso? Estou quebrando a cabeça a um bom tempo e só consegui interpretar coisas absurdas, rs.. Estava tentando escrever um comentário pedindo esclarecimentos mas até isso estava difícil. Erico, poderia dizer se é isso que o utluiz deduziu? Seria bom se pudesse melhorar o texto da sua pergunta.
Comment: @Math É um chute. Na verdade, eu sei que o Oracle realmente possui uma integração com Java, assim como o SQL Server possui integração com C#, onde é possível estender o banco de dados com novas funcionalidades. Porém, pelo menos no caso do Oracle, nunca vi ninguém fazendo isso.
Comment: @Marciano.Andrade a finalidade é fazer utilização de alguns pacote do pentaho para a regra de negócio que necessito. Preciso processar um arquivo no banco de dados, gerado pelo pentaho
Answer: Sim, é possível chamar código Java dentro do banco de dados Oracle. Segue link para documentação oficial: http://docs.oracle.com/database/121/JJDEV/chthree.htm#JJDEV13167.
Vide exemplo da Oracle, você deve seguir os seguintes passos:

Definir uma classe java:
public class Hello
{
  public static String world()
  {
    return "Hello world";
  }
}

Compilar a classe normalmente usando um JDK:
javac Hello.java

Abrir a classe java compilada dentro do banco:
loadjava -user MEUUSER Hello.class

Criar a chamada para o método Java:
CREATE OR REPLACE FUNCTION helloworld RETURN VARCHAR2 AS
LANGUAGE JAVA NAME 'Hello.world () return java.lang.String';
/

Você pode consumir a função Java diretamente do PL/SQL conforme exemplo da Oracle:
 VARIABLE myString VARCHAR2(20);
 CALL helloworld() INTO :myString;
 PRINT myString;

Porém, conforme comentário do utluiz, tenha em mente que consumir uma classe Java diretamente do Oracle nem sempre é a melhor decisão arquitetural. Muitas vezes é melhor expor um Web Service e consumi-lo através do banco. Isso pode ser feito, por exemplo, com o pacote UTL_HTTP.
Comment: @Anthony.Accioly, valeu cara, com isso consegui fazer o que eu precisava. Obrigado

Chamar classe Java dentro do Oracle


How to convert yuv420sp data to jpeg data?

Question: Preview Data in camera is yuv420sp style data. But the data delivered in datacallback is jpeg data. How to convert yuv420sp data to jpeg data before datacallback?
It is very difficult to convert in JAVA layer. So what else method you have?
Answer: No need to convert. The Camera.PictureCallBack returns a JPEG.
See "http://developer.android.com/reference/android/hardware/Camera.html#takePicture(android.hardware.Camera.ShutterCallback, android.hardware.Camera.PictureCallback, android.hardware.Camera.PictureCallback, android.hardware.Camera.PictureCallback)"

How to convert yuv420sp data to jpeg data？


local variable 'user' referenced before assignment error in django function

Question: I have this function in django that adds a new item to the wishlist, the function is doing what it should do but when I add a new user that was not registered, when adding an item to the wish list it returns this error, but when i refresh the page the error no longer exist.
I think the problem is that when a new user registers, he still does not have the database created in the wishlist model, so the try: condition fails because the user does not yet exist in the model, passing the except: condition where the user database is created, but I have to manually refresh the page so that the page no longer shows me the error.
How can I fix this so that the page no longer shows me this error?
def add_or_remove(request, listing_id):
    if request.method == "POST":
        if (request.POST["action"]) == "add":
            try:
                user = Wishlist.objects.get(user=request.user)
                listing = Listing.objects.get(pk=listing_id)
                user.item.add(listing)
            except:
                create = Wishlist(
                user=request.user,
                )
                create.save()
                user.item.add(listing)
                messages.success(request, 'you added to Wishlist')

        elif (request.POST["action"]) == "remove":
            user = Wishlist.objects.get(user=request.user)
            item = user.item.get(id=listing_id)
            user.item.remove(item)

            messages.success(request, 'you removed from Wishlist')

        return redirect(reverse("listing", args=[listing_id]))

Comment: Maybe instead of your `try` / `except` you want to use [`get_or_create()`](https://docs.djangoproject.com/en/4.1/ref/models/querysets/#get-or-create)?
Answer: Django ORM's 'get' function may raise an exception when the requested object is not in the database, you can assure the existence of the 'user' object before going to the next line with a simple logic like this (I've renamed it to 'wishlist' according to the model name):
try:
   wishlist = Wishlist.objects.get(user=request.user)
except Wishlist.DoesNotExist:
   wishlist = Wishtlist(user=request.user)
   wishlist.save()

Or you can use Django's built-in get_or_create() function that does the same thing out-of-the-box.
wishlist = Wishlist.objects.get_or_create(user=request.user)

Please note that your naming conventions may be a little misleading. And also, you need the same logic for the 'listing' object after 'user'.
Answer: As the error suggests, simply assign it as empty string at just starting of POST method, so:

def add_or_remove(request, listing_id):
    if request.method == "POST":
        user=""
        if (request.POST["action"]) == "add":
            try:
                user = Wishlist.objects.get(user=request.user)
                listing = Listing.objects.get(pk=listing_id)
                user.item.add(listing)
            except:
                create = Wishlist(
                user=request.user,
                )
                create.save()
                user.item.add(listing)
                messages.success(request, 'you added to Wishlist')

        elif (request.POST["action"]) == "remove":
            user = Wishlist.objects.get(user=request.user)
            item = user.item.get(id=listing_id)
            user.item.remove(item)

            messages.success(request, 'you removed from Wishlist')

        return redirect(reverse("listing", args=[listing_id]))
Comment: I found the solution ensuring the existence of user first and create before adding the item, but thanks for the help ❤
Comment: hi, I tried but it shows this error: 'str' object has no attribute 'item'
Comment: @kroma235 Then I think mistake is somewhere else, but the error means this what I provided. Can you share the full traceback of error?


What happens if the last two teams from the UCL pot are draw together in the round of 16, but they are from the same country/group?

Question: If teams from the same country or group cant be draw together, so what if the last two teams available are from the same country or group? Do they redraw it? As far as I know, they move on to the next team, but what if there isn't any available?
What do we do in this situation? Real Madrid and Atletico are the only options left, but they are from the same country
Comment: The knockout stage does not use a Pot 1/Pot 2 draw system. Your example makes no sense, as explained in the answer by dly, and I would suggest removing it entirely.
Answer: The Round of 16 draw is not like any other draw you might know.
The draw will be held as follows:

Every group winner has a dedicated bowl containing 8 balls with their name in it.
There is one bowl containing all runners-up.
A runner-up is drawn.
A computer checks the possible opponents and a ball from each of their bowls will be placed into an empty bowl and shuffled. This way no ineligible opponents can be drawn.
If only one possible opponent for a team remains the match will be placed directly.

To see how it's done you can watch last year's draw on YouTube:
Comment: @HosseinHatami  as I've said the computer regularly checks all possible outcomes (or at least they say so). You even have three runners-up from La Liga in the last three games, which would be extremely rare. Normally the computer would do as I stated under 5 and draw directly once there is no more than one possibility left for any of the teams. How it would end up in a three way tie - I don't know for sure. From my understanding from previous draws Porto would have only Spanish teams in their bowl (or just draw Real directly) to keep Dortmund, City and Bayern for the Spanish runners-up.
Comment: I edited it, could you pls look again. I don't think I got my question answered.


Infinite-dimensional spaces for which strong and weak topologies coincide

Question: For a dual pair $\langle X, Y \rangle$ of vector spaces $X$ and $Y$ denote by $\sigma(X,Y)$ the weak topology and by $\beta(X,Y)$ the strong topology on $X$. Consider the following known statement
(S) if $X$ is normed and $\sigma(X,X') = \beta(X,X')$ then $X$ is finite-dimensional.
There are infinite-dimensional locally convex spaces $X$ with $\sigma(X,X') = \beta(X,X')$. In fact, if $Y$ is any vector space and $Y^*$ the algebraic dual of $Y$ then $\sigma(Y^*, Y) = \beta(Y^*, Y)$. As an example, if $Y = \varphi$ (the space of sequences that are eventually $0$) with its largest locally convex topology then $Y' = Y^* = \omega$ (the space of all sequences) and thus $\sigma(\omega, \varphi) = \beta(\omega, \varphi)$. In other words, $X := \omega$ equipped with the topology $\sigma(\omega, \varphi)$ is an infinite-dimensional locally convex space for which its strong topology coincides with its weak topology. But note also that $X$ is a Fréchet space.
To which types of locally convex spaces $X$ can statement (S) be extended?
Answer: For a (Hausdorff) locally convex space (l.c.s.) you have $\sigma(X,X')=\beta(X,X')$ if and only if all $\sigma(X',X)$-bounded subsets of $X'$ are finite dimensional (i.e., their linear span has finite dimension).
In general, this is a surprisingly rich class of l.c.s.: By an old result of Susanne Dierolf every l.c.s. is a quotient of such a space (which is also complete).
On the other hand, if $X$ is barrelled with $\sigma(X,X')=\beta(X,X')$ then the $\sigma(X',X)$-bounded sets are equicontinuous and this implies that that all continuous semi-norms of $X$ have co-finite dimensional kernel (so that you are very close to a product of lines).
Comment: Thank you. Do you possible know of some more explicit classification of dual pairs $\langle X, Y \rangle$ satisfying $\sigma(X, Y) = \beta(X,Y)$, e.g. involving direct sums or products of real lines (or complex planes)? Or is it just hopeless to write down such an explicit list?


inv-gamma distribution as prior for multivariate normal distribution

Question: it's known the conjugate priors for multivariate normal distribution are the normal & inverse-whishart distributions.  but i'm interest in very specific case where the correlation matrix is $R$ multiply by random variable $\kappa^2$  with inverse-gamma prior summed with $\sigma^2 I$  . I'm trying to get the closed-form posterior from an inverse gamma prior and a likelihood based on a multivariate normal distribution expecting to get inverse gamma posterior but I don't have any success . I appreciate it if you could help me get the posterior. the model:
$$ Y | \kappa \sim \mathcal{N}_j(0,( \kappa^2 R + \sigma^2 I))$$
$$ \kappa \sim \text{InverseGamma} (A_0, B_0)$$
Where $A_0$, $B_0$, and $\sigma^2$ are known constants and $R$ is $j$ by $j$ known matrix we can even say it is rank(1) matrix . $I$ is a $j$ by $j$ identity matrix.
Comment: I wouldn't be surprised if there is no closed form posterior.
Answer: [This answer refers to a previous version of the question with the covariance matrix being the inverse of what it is now]
Since the distribution of $Y$ given $\kappa$ is an exponential family, as
a sample $(y_1,\ldots,y_n)$ from $\mathcal{N}_j(0,( \kappa^2 R + \sigma^2 I)^{-1})$ has density
$$|\kappa^2 R + \sigma^2 I|^{n/2}\exp-\frac{1}{2}\text{tr}\left\{ (\kappa^2 R + \sigma^2 I)\sum_{i=1}^n Y_iY_i^t\right\}$$
i.e.,
$$|\kappa^2 R + \sigma^2 I|^{n/2}\exp-\frac{1}{2}\left\{ \kappa^2 \text{tr}\left(R\sum_{i=1}^n Y_iY_i^t\right) + \sigma^2 \text{tr}\sum_{i=1}^n Y_iY_i^t\right\}$$
there exists a conjugate family on $\kappa$ but not of the inverse Gamma variety.
[This answer refers to the new version of the question]
Since the distribution of $Y$ given $\kappa$ is a curved exponential family, as a sample $(y_1,\ldots,y_n)$ from $\mathcal{N}_j(0,( \kappa^2 R + \sigma^2 I)^{-1})$ has density
$$|\kappa^2 R + \sigma^2 I|^{-n/2}\exp-\frac{1}{2}\text{tr}\left\{ (\kappa^2 R + \sigma^2 I)^{-1}\sum_{i=1}^n Y_iY_i^t\right\}$$
which factorises through the sufficient statistic $\sum_{i=1}^n Y_iY_i^t$, there exists a conjugate family on $\kappa$ but not of the inverse Gamma variety, since this family is actually $j(j+1)/2$ dimensional.
Comment: actually  the density suppose to by like that $$|\kappa^2 R + \sigma^2 I|^{-n/2}\exp-\frac{1}{2}\text{tr}\left\{ (\kappa^2 R + \sigma^2 I)^{-1}\sum_{i=1}^n Y_iY_i^t\right\}$$   it is possible to use woodbary decomposition but still what is the family of  $\kappa$? thanks
Comment: yes you right i edit the question.


Why choosing proper initial centroids is very important for K-means?

Question: I don't fully understand why choosing proper initial centroids is very important for K-means. Demos or simple explanations will be very grateful. Thank you !
Answer: The algorithm may find a suboptimal solution when the centers are chosen badly. Google for "k-means local minimum example" and you will likely find some examples.
There is no feasible way to guarantee finding the optimal solution (NP hard, too expensive), so you need heuristics.
But one of the most effective heuristics is to simply choose random points initially, but retry this several times and keep the best only. k-means++ may or may not help (and you still need to run it multiple times for best results).
Answer: There's a terrific visualization of k-means at http://www.naftaliharris.com/blog/visualizing-k-means-clustering/.  You can select the number of centroids and their initial placement, and see how the initial placement impacts the ultimate cluster assignments (that is, how the solution resolves to local minima).
Answer: There are many different algorithms for solving the K-means problem. The most common one is called Lloyd's algorithm. The K-means problem itself is NP-hard, so any algorithm with a runtime that's practically usable will only give a locally optimal solution. The fact that we'll converge to a local minimum is what makes the procedure sensitive to initialization conditions. Methods like Lloyd's algorithm start with the parameters at some initial point. They iteratively adjust parameters to reduce the loss function at each step, then halt when no local step can give further improvements. Because the loss function is, in general, nonconvex, each local minimum will have a basin of attraction that surrounds it. The basin of attraction is a region of parameter space where--if initial parameters lie within it--the algorithm will converge to that local minimum. So, the initial parameters determine which solution is ultimately obtained. But, some local minima are better than others. This is why initialization matters. It's also worth mentioning that the difficulty of solving the K-means problem and the sensitivity to initial conditions can vary with the dataset.
Answer: Choosing adequate initial seeds affects both the speed and quality when using the Lloyd heuristic algorithm, an algorithm for solving K-means problem. It is because the algorithm works by iteratingly improving the centroids position, from previous centroids.
I would suggest you to use an algorithm for choosing the initial values if you don't know how to choose your seeds. Randomly selected ones is not always a good option. The k-means++ algorithm garantees to find a solution that is O(log k) competitive to the optimal k-means solution.
See here.


A given polynomial equation of 5 degree has three equal roots .

Question: Given equation is $x^5-10a^3x^2+b^4x+c^5=0$ which has 3 equal roots. What I know is that since its a 5th degree equation therefore it must have 5 roots out (of which 3 are equal).
Aim is to establish the relationship between the constants $a,b$ and $c$.
Options given are:
1) $6a^5+c^5=0$.
2) $b^4=15a^4.$
I have to find which one is correct out of the two, any help?
Comment: @AnirudhSoni-Please use @ sign before writing to Mr.Gerry so that he can receive your comment.
Comment: The polynomial, its derivative, and its second derivative must have a common factor. That should be useful.
Comment: Have you tried using Vietas rule?
Comment: I don't know what it is...please elaborate ...thanks in advance.
Comment: Is it taking summation of the roots taking one at a time,two at a time and so on...
Comment: You certainly know it.Maybe you are not familiar with the name.It is the formula of calculating the product and sum of roots of a polynomial.Do you know it?
Comment: Yes I knew it then
Comment: I have tried it but I am a bit confused.
Comment: Gerry how can you say that?
Comment: @Gerry Myerson- how it can be said so????
Comment: This question is wrong. It should be: "Which of the following is necessarily true? (1) ... (2) ..." Because the answer is "Both of them".
Answer: Let $$f(x) = x^5 - 10a^3x^2 + b^4x + c^5 = (x - m)^3g(x)$$ where $m$ is the repeated root, and $g(x)$ is some second-order polynomial.
Then, differentiating and substituting $x = m$,
$$5x^4 - 20a^3x + b^4 = (x - m)^3g'(x) + 3(x - m)^2g(x)$$
$$5m^4 - 20a^3m + b^4 = 0$$
Differentiating another time, and similarly substituting $x = m$,
$$20x^3 - 20a^3  = (x - m)^3g''(x) + 3(x - m)^2g'(x) + 3(x - m)^2g'(x) + 6(x - m)g(x)$$
$$20m^3 - 20a^3 = 0$$
$$m = a$$
Substituting this back into our first result,
$$5a^4 - 20a^3\cdot a + b^4 = 0$$
$$b^4 = 15a^4$$

Note: The fact that $(x - m)$ appears in every term of $f'(x)$ and $f''(x)$ is in fact a usable basis for proving what Gerry Myerson mentioned in the comments - that $f(x), f'(x), f''(x)$ all have a common factor.
Comment: @macavity: that's wrong. If you substitute in the original polynomial, you find that 1) is true as well.
Answer: Let $t$ the triple root and consider the coefficients $r,s$ of the quadratic factor so one has the polynomial $(x-t)^3(x^2+rx+s)$. The equality of corresponding coefficients gives $$r-3t=0$$ $$s-3tr+3t^2=0$$ $$-3ts-t^3+3t^r=-10a^3$$  $$3t^2s-t^3r=b^4$$  $$-t^3s=c^5$$   Solving easily this system we have a parameterization of $a,b,c$ in function of the triple root.
$$a=t$$ $$b=\sqrt[4]{15}\space t$$   $$c=-\sqrt[5]{6}\space t$$
The simplest relationship between $a,b,c$ is $$a=\frac{b}{\sqrt[4]15}=\frac{-c}{\sqrt[5]6}$$
Comment: Nice way ..thanks
Answer:
Question : I have to find which one is correct out of the two, any help?

Answer : Actually, both the options are correct. I am giving the explanation.
Let $~f(x) = x^5 – 10a^3x^2 + b^4x + c^5~$.
$$~⇒ f'(x) = 5x^4 – 20a^3x + b^4~~~~ ⇒ f'' (x) = 20x^3 – 20a^3~$$
Since $~x = \alpha~$ be a root that is repeated three times, so
$$f''(\alpha) = 0,~~~~~~ f'(\alpha) = 0,~~~~~~ f(\alpha) = 0$$
$$⇒ 20\alpha^3 – 20a^3=0,~~~~~~ 5a^4 – 20a^3\alpha + b^4 = 0,~~~~~~ \alpha^5 – 10a^3\alpha^2 + b^4\alpha +c^5 = 0$$
$$⇒ \alpha = a,~~~~~~ 5a^4 – 20a^3\alpha + b^4 = 0,~~~~~~ \alpha^5 – 10a^3\alpha^2 + b^4\alpha +c^5 = 0$$
$$⇒ b^4 = 15a^4, ~~~~~~c^5 + ab^4 – 9a^5 = 0\qquad (\text{using the  result}~~\alpha = a )~~~~$$
$$⇒ b^4 = 15a^4, ~~~~~~c^5 + 15a^5 – 9a^5 = 0\qquad (\text{using the  value}~~b^4 = 15a^4)$$
$$⇒ b^4 = 15a^4, ~~~~~~6a^5 + c^5 = 0~.$$


Gráficos 3D python

Question: Tenho 3 arrays, a partir dos arrays devo desenhar um gráfico 3D. Já tentei de várias formas mas não consegui. Creio que não estou criando os data frames corretamente. Estou tentando fazer desta forma:
x = np.array(x_values)
y = np.array(y_values)

X, Y = np.meshgrid(x, y)
Z = np.array(z_values)

ax = plt.axes(projection='3d')
ax.plot_surface(X, Y, Z, rstride=1, cstride=1,cmap='viridis',edgecolor='none')

plt.show()

O código está retornando o seguinte erro:

ValueError: Argument Z must be 2-dimensional.
Comment: O argumento Z deve ter duas dimensões e no caso que você colocou o seu Z só tem uma dimensão. Dá uma olha da no exemplo neste site: https://matplotlib.org/3.1.1/gallery/mplot3d/surface3d.html
Answer: Z tem que ser uma função que dependa de X e Y. Ex: np.sin(x)*np.sin(y)

Gráficos 3D python


How come when I update my iPhone SDK all the frameworks in my project turn red (not there)?

Question: I'm getting sick of this stuff happening. How come whenever I update my iPhone SDK all the frameworks in my project turn red as if there are not there anymore? Whats the situation?
Answer: Make sure that all your references to frameworks are "relative to base SDK"


How to modify this bump function so that the "bump" is at $y=1$?

Question: $$f(x) =
  \begin{cases}
    e^{-1/(1 - x^2)} & -1 < x < 1\\
    0 & \text{otherwise}
  \end{cases}
$$
I noticed that when I multiply the denominator of the fractional part of this function (the $1 - x^2$ part) by larger and larger numbers, the "bump" almost reaches $1$, but it never does (even when I put in $99999\cdot1 - x^2$). I am trying to modify this function so that $f(x) = 1$ for $a \leq x \leq b$, where $a = b = 0$ in this particular case, but still maintain that $f(x) = 0$ for $x < \alpha$ and $x > \beta$ where $\alpha = -1$ and $\beta = 1$ in this case. $f(x)$ must also be smooth.
Answer: If you're trying to make the maximum value of the function 1, just divide it by its maximum value, so it'll be 1 at the maximum.
If you want to define a $C^\infty$ function that is 1 on $[-a,a]$ and 0 outside the interval $[-b,b]$ with $a<b$, you can do the following.
Scale and shift your argument x so that your function is supported on $[-b,-a]$. Subtract another copy of it that's supported on $[a,b]$. Now if you integrate this function from $-\infty$ to $x$ you'll get a function that's similar to what you want, but its maximum value is not 1. Just divide it by the integral under one of the bumps to make it 1.
Answer: If you want to have that $f(0) = 1$, just let $f(x) = e^{-\frac{1}{1-x^2}+1}$ within $x\in(-1,1)$ instead.

Why does this work? Your function attains its maximum value at $x=0$, which is $f(0) = e^{-1}$. Dividing by this value (which is multiplying by $e$) will force the maximum to be $1$, hence the function will be
$$e\cdot f(x) = e^{-\frac{1}{1-x^2}+1} $$
when $x\in(-1,1)$ and $0$ otherwise.
This, however, only works for one point. If you want to make the function equal to $1$ within an interval, you're going to need to use another approach.


Prove identity related to nths root of unity

Question: If $1=z_0,z_1,...,z_{n-1}$ are nth roots of unity, prove that
$$(z-z_1)(z-z_2)...(z-z_{n-1})=1+z+z^2+...+z^{n-1}$$
I don't know what is meant by the condition given. If I substitute $1=z_0,z_1,...,z_{n-1}$, isn't it become
$$(z-1)^{n-1}=1+z+z^2+...+z^{n-1}$$
Does this holds?
Answer: Consider the equation
$$z^n-1=0$$
The roots of this equation are the $n^{th}$ roots of unity, which let's say are 1,$z_1$,$z_2$,...,$\, z_{n-1}$. Then the expression on the LHS can be rewritten as the product of its factors:
$$(z-1)(z-z_1)(z-z_2)...(z-z_{n-1})=z^n-1$$
Taking $(z-1)$ to RHS,
$$(z-z_1)(z-z_2)...(z-z_{n-1})={z^n-1 \over z-1}$$
Notice that the RHS has now become the sum of the geometric series $1+z+z^2+$...
Which proves the result
$$(z-z_1)(z-z_2)...(z-z_{n-1})=1+z+z^2+z^3+...+z^{n-1}$$
You cannot substitute 1 for all the $n$ roots. Only one root can be one and the rest are complex, excluding -1.
Answer: You know that your roots are the solutions of $z^n-1=0$, hence
$$z^n-1=(z-z_0)(z-z_1)(z-z_2)...(z-z_{n-1})=(z-1)(z-z_1)(z-z_2)...(z-z_{n-1})$$
Now you just have to divide by $z-1$
$$\frac{z^n-1}{z-1}=(z-z_1)(z-z_2)...(z-z_{n-1})$$
but the l.h.s. is the partial sum of the geometric series, i.e. $\sum_{k=0}^{n-1}z^k$, hence
$$\sum_{k=0}^{n-1}z^k=(z-z_1)(z-z_2)...(z-z_{n-1})\ .$$
If you don't know the result on the geometric series you can compute the ratio directly or try to proove it.
Comment: You don't have to invoke the geometric series: $$1-x^n=(1-x)(1+x+x^2+\dots+x^{n-1})$$ is a well-known factorisation identity. Actually the formula for the geometric series is *deduced* from this one.


Tamanho limite do campo VARCHAR2 no Oracle

Question: Tenho uma coluna com o tipo VARCHAR2 (4000 CHAR) e estou testando o tamanho limite do campo VARCHAR2 no Oracle. Achava que havia um limite de 4000 bytes no campo, mesmo especificando o valor 4000 em caracteres, devido a esse erro já ter acontecido no trabalho e o problema ter sido resolvido.
Ao tentar inserir uma string contendo mais de 2000 caracteres á, ocorria um erro dizendo que o valor era grande demais para o campo. Isso acontecia porque o caractere á ocupava 2 bytes no banco de dados. Porém, hoje foi feito o mesmo teste e dessa vez o banco de dados inseriu o valor corretamente.
Isso ocorreu em apenas uma das máquinas do local onde trabalho, que possui a mesma configuração das outras.
O que pode estar acontecendo?
Existe alguma configuração no Oracle que pode estar permitindo inserir uma string com mais de 4000 bytes?
Comment: Provavelmente está usando um *encoding* diferente. http://pt.stackoverflow.com/q/21230/101 Ou se for um *encoding* que cada caractere ocupa um tamanho diferente pode ser o texto diferente que fez caber.
Comment: De que maneira ele é inserido no banco, através de uma aplicação como PL/SQL ou SQL developer?
Comment: Tentei inserir pelo SQL developer e também através da aplicação que estou desenvolvendo. A máquina em que ocorreu o problema tem Windows. As demais são variantes de Linux ou Mac. O que estamos achando é que o problema é o encoding do Windows, mas ainda não temos certeza.
Comment: Dependendo do client que está utilizando você consegue especificar o encoding. Está definição do encoding pode ser feito nos softwares client ou até mesmo na string de conexão do seu app. Você precisa trabalhar com VARCHAR2? Pergunto isso pois dependendo da quantidade de caracteres seria interessante mudar para um tipo de dado diferente.
Answer: VARCHAR2 armazena caracteres alfanuméricos de tamanho variável, entre 1 e 4000 bytes ou caracteres. O tamanho padrão desta coluna é definido em bytes, no seu caso, este pode ser o problema.
Ao criar uma coluna VARCHAR2 podemos especificar se os dados serão contabilizados como bytes ou caracteres. Existe uma grande diferença entre essas duas opções, por exemplo, se utilizar o encode UTF-8, 1 único caractere pode ser armazenado em até 3 bytes, logo, o limite de armazenamento pode cair consideravelmente se existirem muitas palavras/letras acentuadas, nestes casos neste caso seria melhor especificar o armazenamento da coluna em character.
Maiores informações em: https://docs.oracle.com/cd/B28359_01/server.111/b28318/datatype.htm
Answer: A resposta aceita para a pergunta é correta e a documentação tem muita informação, mas vou dar um exemplo prático pois já sofri bastante com isso no oracle.
Vamos começar verificando, com o SQL abaixo, o valor do NLS_CHARACTERSET, que é o "causador" do problema:
SELECT *
FROM nls_database_parameters
WHERE parameter = 'NLS_CHARACTERSET';

Se você estiver usando UTF8, como já informado, um único caractere pode ocupar 3 bytes. Então, em um banco configurado dessa forma, se executar o seguinte SQL:
CREATE TABLE NLS_TESTS (
    COMCHAR VARCHAR2(3 CHAR),
    SEMCHAR VARCHAR2(3)
);

INSERT INTO NLS_TESTS VALUES('aei', 'aei'); --Será inserido
INSERT INTO NLS_TESTS VALUES('áéí', 'áéí'); --Não será inserido!!
INSERT INTO NLS_TESTS VALUES('áéí', 'aei'); --Será inserido!!

O segundo insert não será inserido, pois o SEMCHAR VARCHAR2(3) usa o NLS_LENGTH_SEMANTICS atual para determinar o tamanho do texto. Ou seja, para UTF8 se o caractere ocupar 2 bytes, então esses 2 bytes serão ocupados de fato na coluna.
Já o terceiro insert será executado sem erro, pois a coluna COMCHAR VARCHAR2(3 CHAR) está usando 'CHAR', que basicamente indica que a coluna deve ter espaço suficiente para 3 caracteres, independente de quantos bytes esse ocupa.
Já passei por esse problema onde alterar coluna a coluna para VARCHAR2(x CHAR) era inviável, uma forma de contornar isso seria usando o seguinte código na sua transação atual, para alterar o NLS_CHARACTERSET da sessão:
declare
    v_s_CharacterSet VARCHAR2(160);
begin
    select VALUE
    into v_s_CharacterSet
    from NLS_DATABASE_PARAMETERS
    where PARAMETER = 'NLS_CHARACTERSET';
    if v_s_CharacterSet in ('UTF8', 'AL32UTF8') then
        execute immediate 'alter session set nls_length_semantics=char';
    end if;
end;

Isso também explica por que quando executando de outro computador funcionou. A sessão que foi aberta onde deu certo, não usava UTF8 ou AL32UTF8.
Answer: Só uma nota: se tiveres Oracle 12c, podes extender esse limite para 32767 bytes. Para isso, é necessário alterar o parametro MAX_STRING_SIZE = EXTENDED.
Neste link tens mais alguma informação: https://docs.oracle.com/database/121/SQLRF/sql_elements001.htm#SQLRF55623
Comment: Sua resposta não responde a pergunta. Para fazer um comentário use o campo de comentário. Link relativo: [Por que e como algumas respostas são excluídas?](http://pt.stackoverflow.com/help/deleted-answers)


sed question on how to add a # to beginning of a pattern match

Question: How do you add a comment in front of this line with sed?
I'm trying to add a # sign to line in front of this but my sed is not working.
When I attempt to there is no match.
auth           required        pam_wheel.so use_uid
sed -i 's/auth           required        pam_wheel.so use_ui/#auth           required        pam_wheel.so use_ui/g' /etc/pam.d/su but it is not matching.

Answer: Using sed
$ sed -i.bak '/pam_wheel.so use_ui$/s/^/#/' /etc/pam.d/su

-i.bak will create a backup of the file with .bak extension (or anything you wish to name it).


Visual Studio Redeploy feature for BizTalk solution does not work

Question: My BizTalk solution has 10 BizTalk projects that are referenced between each other.
In each project's properties I have set redeploy feature to 'true' (it's by default).
But when I try to redeploy the whole solution from VS 2012, I get following errors for some projects in solution:

Error 201 Failed to add resource(s). Change requests failed for some
  resources. BizTalkAssemblyResourceManager failed to complete end type
  change request. Cannot update assembly "Project1, Version=126.96.36.199,
  Culture=neutral" because it is used by assemblies which are not in the
  set of assemblies to update. To update the assembly, remove the
  following assemblies: Project2, Version=18.104.22.168, Culture=neutral
  Project3, Version=188.8.131.52, Culture=neutral Project4, Version=220.127.116.11,
  Culture=neutral Project5, Version=188.8.131.52, Culture=neutral Project6,
  Version=126.96.36.199, Culture=neutral

As I read from this article:
http://blog.codit.eu/post/2013/07/30/Redeployment-notes-of-a-BizTalk-solution-from-Visual-studio.aspx

In the process of deploying a BizTalk assembly, you first needed to
  manually stop, unenlist, and unbind artifacts contained in the
  assembly in BizTalk Server and then remove the assembly from the
  BizTalk Management (configuration) database before deployment. Visual
  Studio will handle all those steps for you with this option Redeploy.

What could be the reason of my problem and possible solution?
Answer: Please check if you use subfolders in your solution.
I suggest to create new (additional) solution just for deployment purpose where you should avoid to use any solution subfolders
Andrei
Comment: Awesome! I am really using solution subfolders... You helped me a lot and saves me a lot of days! Thanks!
Answer: You can try deleting the temp binding files at: C:\Users\%username%\AppData\Roaming\Microsoft\BizTalk Server\Deployment\BindingFiles
Then try again.
Answer: Check in the configuration manager for solution if any project is not marked for deployment. Right click on solution then select Configuration Manager and make sure all projects are selected for deploy,
Answer: Check that one of the assemblies hasn't gone into the Default Application rather than the application you are deploying too.  If you find one in the wrong place you can right click it and select Move to Application. (The other option is to remove it, but then quite often you have to remove all the dependent ones as well).
Check each project that the Application is set.
Then re-deploy.
This happens quite often, especially if you just got a project down from source control, as the Application is saved in the user file rather than the project file.
Edit: Also check your solution setting to make sure all projects have deploy ticked.
Comment: For each project application name is set and there are no artifacts in default application. For some reason visual studio can not delete dependent assemblies and asks me to do it before I click 'deploy'. That is strange...
Answer: Apparently there is some problem with BizTalk 2016 party export/import that prohibits re-import of bindings during deploy from Visual Studio.
My workaround is to export bindings manually before deploy, and manually import bindings after "successful" deploy (cited from the deploy log in visual studio ;).
Other reference:
https://social.msdn.microsoft.com/Forums/en-US/c49758c0-0465-4c13-97a3-300c05d00d3a/biztalk-2016-redeploy-and-orchestration-bindings?forum=biztalkgeneral&prof=required


dyld cache '/System/Library/dyld/dyld_shared_cache_x86_64h' not loaded: syscall to map cache into shared region failed

Question: I'm getting this error when trying to use python 3. How can I solve this issue?

dyld[2675]: dyld cache
'/System/Library/dyld/dyld_shared_cache_x86_64h' not loaded: syscall
to map cache into shared region failed dyld[2675]: Library not loaded:
/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation
Referenced from:
/Library/Frameworks/Python.framework/Versions/3.6/Resources/Python.app/Contents/MacOS/Python
Reason: tried:
'/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation'
(no such file),
'/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation'
(no such file)
Answer: This looks like you've got multiple installations of Python 3 that may have carried over from a previous macOS upgrade. If you directly type /usr/bin/python3 and don't get an error then this is likely an issue with a homebrew/macports/something else custom installation. You can type which python3 to see what it would execute by default when just using python3, but the fix depends on what you've done to your system. Check dyld: Library not loaded: /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation for more help.
Comment: Thanks for this answer! The link to the other question explained what happened on my machine exactly (macOS -> updated to monterey and got a new version of python3). I have installed way too many python environments directly so deleting some of them from /Library/Frameworks/Python.framework/Versions solved the problem.
Comment: `which python3` returns: /Library/Frameworks/Python.framework/Versions/3.6/bin/python3. I guess that is a bad version. I have tried using /usr/bin/python3 to run my file but this gives an error that I don't have a package installed. When I run pip list the package is there.
Comment: It looks like you may have some incorrect mental models of how Python manages packages and how pathing works for shells in Unix-like OSes. I'd highly suggest spending some time learning a bit about that and how virtual environments work so that you can more effectively isolate your own projects from global packages or the system itself.
Answer: It happened because the new macos installed a newer version of python3 and was not able to connect to the existing older version. I could solve it by looking under /Library/Frameworks/Python.framework/Versions and updating the pointed python3 version (as current) in my interpreter settings within pycharm ide.


Understanding the tangent of an $\arcsin(2x)$-- where to start

Question: I'm having difficulty seeing where to start the problem of $\tan(\arcsin(2x))$ where x is restricted to $0\leq x \leq1/2$.
Not clear as to first step even.
Comment: The usual method is to draw a right triangle where one angle is $\arcsin(2x)$.
Answer: $$\tan  (arcsin(2x))=\frac { \sin { \left( arcsin(2x) \right)  }  }{ \cos { \left( arcsin(2x) \right)  }  } =\frac { 2x }{ \sqrt { 1-{ \sin ^{ 2 }{ \left( \arcsin { \left( 2x \right)  }  \right)  }  } }  } =\frac { 2x }{ \sqrt { 1-{ 4{ x }^{ 2 } } }  }  $$
Answer: One may write, for $0<x<\frac12$,
$$
\tan\left(\arcsin(2x) \right)=\frac{\sin\left(\arcsin(2x) \right)}{\cos\left(\arcsin(2x) \right)}=\frac{2x}{\sqrt{1-\sin^2\left(\arcsin(2x) \right)}}=\cdots.
$$
Comment: it would seem to me that the triangle in the x-y plane has vertices at: (0,0) and (2x,0) and $(2x,\sqrt(1-4x^2)$. If this is the triangle, isn't the tan of that $\sqrt(1-4x^2) / 2x$  ??


Does influence graph have multiple directed edges?

Question: so I am studying about graphs from the book discrete maths by Keneth Rosen 7th edition.Pg:645
However, I am bit unsatisifed with one of the statements from the book. So I would like to get it reviewed from someone who knows.

Here the textbook says that in figure 7 there is no multiple directed edges. However I can clearly see there is multiple directed edges between Brian and Yvonne. Is the textbook getting wrong here or I seriously need to look back my concepts? Please help me.
Answer: "Multiple edges", in this context, has a technical meaning. (Used informally, it's obviously nonsense, because of course the graph has more than one edge.) It means that edges cannot have multiplicity: the same edge cannot appear multiple times.
It is okay to have the edge $(\text{Brian}, \text{Yvonne})$ as well as the edge $(\text{Yvonne}, \text{Brian})$, because these are different directed edges. However, in this context, it would be meaningless to have two copies of the edge $(\text{Brian}, \text{Yvonne})$: what would it mean, to have Brian "influence Yvonne twice"?
I would not say that an influence graph is a widely-recognized term, so you don't have to worry about its definition in other contexts. However, the term simple directed graph is commonly used for graphs that don't have loops (edges of the form $(u,u)$) or multiple edges (multiple copies of the same edge $(u,v)$). Some sources will also just call this a directed graph and assume by default that it is simple, and say directed multigraph to allow loops and multiple edges.
It is also possible to make other sets of assumptions:

A loopless directed (multi)graph forbid loops, but allows multiple copies of the same edge.
An oriented graph (this is a less common term, but still often used) is even more restrictive, and forbids the thing that happens in the question: at most one of the edges $(u,v)$ or $(v,u)$ can exist. These directed graphs are called "oriented graphs" because they are exactly the class of graphs that can be obtained from undirected graphs by giving each edge an orientation.


Probability mass function question

Question: So I'm teaching myself some probability and stats which go beyond the discussion of my behavioural research/stats book, and I'm stuck on one problem.
This following problem has been taken from Statistics and Probability for Scientists and Engineers by Anthony Hayter, 2012. Chapter 2, Exercise 2.1.4, Q.no. is 2.1.11, page number 81.

A consultant has six appointment times that are open, three on Monday and three on Tuesday. Suppose that when making an appointment a client randomly chooses one of the remaining open times, with each of those open times equally likely to be chosen. Let the random variable X be the total number of appointments that have already been made over both days at the moment when Monday's schedule has just been completely filled. (a) What is the state space of the random variable X? (b) Calculate the probability mass function and the cumulative distribution function of X.

I was able to find out (a) which is X = {3,4,5,6} but I am having trouble with (b). The answer for the PMF is 1/20, 3/20, 6/20, 1/2.

What I did: I tried to work it out, and I feel like the denominator might have 6C3 to account for the 20 since the selection is out of the 3 available appointments on Tuesday and total number of appointments which could have been chosen is 6.
I did (3C0)/(6C3) to get 1/20 and (3C1)/(6C3) to get 3/20, but couldn't get 6/20 and 1/2, so I'm sure I'm doing something wrong.
Comment: I think the PMF should be $P(3)=1/16, P(4) =3/16, P(5)=P(6)=3/8$
Comment: Would it be possible for you to show how you came to your solution and post it as an answer to this question?
Answer: Hint:
In order for all the Monday appointments to be filled on day $X$, there must have been $2$ Monday appointments and $X-3$ Tuesday appointments on the first $X-1$ days, followed by a Monday appointment on day $X$, for $3 \le X \le 6$.
Comment: @HJ_beginner I corrected a typo in the hint, changing $n-3$ to $X-3$.  (I had made a change in notation earlier and missed one of the spots I needed to change.)  Sorry if this caused any confusion.
Comment: That is a good insight, that you know the last appointment made is the last appointment slot for Monday.
Comment: @awkward I'm afraid I still cannot understand.

Probability mass function question


Weakly continuous but not norm continous

Question: Cosinder a Hilbert space $H$ with ON-basis $\{e_n\}_{n\in\mathbb{N}}$ and set $X=\{0\}\cup\{\frac{1}{n}:n\in\mathbb{N}\}$.
Further, let $f:X\to B(H)=\{\text{complex linear maps $H\to H$ with finite operator norm}\}$ be given as $f(0)=0$ and $f(1/n)(e_k)=e_{k+n}$.
So far I have shown that $f$ is not strongly continuous. But why is it weakly continuous, i.e. why do we get $x_n\to y\Rightarrow (u,f(x_n)(v)-f(y)(v))\to 0$ for all $u,v\in H$?
Comment: The only limit point of $X$ is $0$ under the standard topology on $\Bbb{R}$ (even lower limit topology if you want), so you may take $y=0$.
Comment: Yes, I am aware of this and thus started to work out that case, but it did not go well.
Answer: Let $u=\displaystyle\sum_{i=1}u_{i}e_{i}$, $v=\displaystyle\sum_{i=1}v_{i}e_{i}$, then
\begin{align*}
\left(u,f(x_{n})(v)-f(y)(v)\right)&=\left(\sum_{i=1}u_{i}e_{i},f(x_{n})\left(\sum_{i=1}v_{i}e_{i}\right)-f(y)\left(\sum_{i=1}v_{i}e_{i}\right)\right)\\
&=\sum_{i=1}\sum_{j=1}u_{i}\overline{v_{j}}(e_{i},f(x_{n})e_{j}-f(y)e_{j})\\
&=\sum_{i=1}\sum_{j=1}u_{i}\overline{v_{j}}(e_{i},e_{j+n})\\
&=\sum_{i=1}u_{i}\sum_{j=1}\overline{v_{j}}(e_{i},e_{j+n})\\
&=\sum_{i=n+1}u_{i}\overline{v_{i-n}},
\end{align*}
where we have assumed that $x_{n}=1/n$, so
\begin{align*}
\left|\left(u,f(x_{n})(v)-f(y)(v)\right)\right|&\leq\left|\sum_{i=n+1}u_{i}\overline{v_{i-n}}\right|\\
&\leq\left(\sum_{i=n+1}|u_{i}|^{2}\right)^{1/2}\left(\sum_{i=n+1}|\overline{v_{i-n}}|^{2}\right)^{1/2}\\
&=\left(\sum_{i=n+1}|u_{i}|^{2}\right)^{1/2}\|v\|\\
&\rightarrow 0
\end{align*}
as $n\rightarrow\infty$.
Comment: Why can we assume $x_n=1/n$?
Comment: If $y=1/n_{0}$, then $x_{n}=1/n_{0}$ eventually, so this is easy. For $y=0$, of course you may have $x_{n}=0$ eventually, this is easy. If $x_{n}=0$ infinitely many and of the form $1/n$ infinitely many, actually you may recast the proof, discarding the $0$, the terms left are about strictly increasing $n_{k}$, it is not hard to see that it is not a problem to have the similar estimate.
Comment: The only limit point in $X$ is $0$.  Any "interesting" (repeated entries stripped off) convergent sequence in $X$ is a subsequence of $(x_n)_n$ with $x_n=1/n$, so it suffices to show the case $x_n=1/n$.
Comment: Except the trivial case where eventually  $x_n = 0$,   you only need prove continuity for  strictly decreasing sequences ! and it is clear that any strictly decreasing sequence in $X$ is a subsequence of the $\{\frac{1}{n}\}$

@VML
Comment: Alright, but your sums may be infinite so why  can you use linearity?
Comment: That is by the continuity of inner product.
Answer: if $x_n \to x ≠ 0$ then $x_n$ is eventually constant so the result is obvious. Hence, suppose $x_n \to 0$.  Write $u = \sum_i u_i e_i $ and $v = \sum_i v_i e_i$. The result we want is then plainly
$$ (u, f(x_n)(v) ) \to 0$$ Linearity lets us write
$$(u, f(x_n)(v) ) = \sum_{i,j} u_i \overline{v_j}  ( e_i , f(x_n) e_j)$$
If $x_n = 0$ then $f(x_n) = 0 $, so $(u, f(x_n)(v) )=0$ immediately. Else $f(x_n)(e_j) = e_{j+ 1/x_n}$, which collapses the double sum into a single sum which we can bound via Cauchy-Schwarz,
$$|(u, f(x_n)(v) )| =  \left|\sum_{i=1}^\infty u_i \overline{v_{i+1/x_n}} \right| \overset{C-S}{≤}\|u\|_H \sqrt{\sum_{i=1/x_n}^\infty |v_i|^2 }\to 0$$
where the last line is from the fact that $1/x_n\uparrow\infty $ and $\sum_1^\infty |v_i|^2 = \|v\|_H^2 < \infty$, so the tail sum is null.
Comment: Thank you! I do not feel well with your 'linearity let us write...' equation because the sum may be infinite. Why is that not an issue?
Comment: @VML This is because the inner product is continuous in each input, due to Cauchy-Schwarz.
Comment: @VML so $a_n\to a$ implies $(a_n,b)\to (a,b)$. In particular if you use $a_n = ∑_1^n c_i$ for some $∑c_i$ convergent in $H$, then the finite sums converge to both $(∑_1^\infty c_i , b) $ and $∑_1^\infty (c_i,b)$. By uniqueness of limits, they coincide.
Comment: @VML does the above argument make sense for you? (Of course, once you deal with the first input, you repeat the argument for the second input.)
Comment: @VML a smarter way to write the above would have been $$ (∑_1^\infty c_i ,b) = ( \lim_n ∑_1^n c_i ,b) \overset{!!!}{=} \lim_n (∑_1^n c_i , b) = \lim _n ∑_1^n (c_i,b) = ∑_1^\infty (c_i,b)$$ where continuity was used for the equality marked "!!!".
Comment: Yes, this makes Sense. But you also need $f(x_n)$ to be continuous. Is it bounded?
Comment: @VML fortunately $f(x_n) \in B(H) = \{ \text{ bounded operators on $H$} \}$ is assumed.
Comment: But we have a concrete $f$ given, so it is well defined, i.e. really a map in B(H)?
Comment: @VML Well $f(x_n)$ is defined on a basis and then extended via linearity to an operator $f(x_n) : H \to H$. So if $x_n ≠ 0$, and $v = ∑_i v_i e_i$, then
$$ f(x_n) v  := ∑_1^\infty v_i e_{i+1/x_n} $$
so$$ \| f(x_n) v\|^2 = \| ∑_1^\infty v_i e_{i+1/x_n}  \|^2 = ∑_1^\infty |v_i|^2  = \| v\|^2 $$ by orthonormality. In particular then each $f(x_n)$ for $x_n≠0$ is even an isometry.
Comment: You are great, thank you. Where do you use your 'if some $x_n =0$'-case? And I do not see how you have used CS and why that converges to 0, sorry.
Comment: I used it to assume without loss that $x_n ≠ 0$, so that I can write $1/x_n < \infty$. I used CS in the space of square-summable sequences $\ell^2(\mathbb N)$. The basis $e_n$ in a sense, gives you a way to move between this space and $H$.
Answer: Let $x\in H.$ Then
$$f(1/n)(x) = f(1/n)((x_1,x_2, \dots)) = (x_{n+1},x_{n+2}, \dots).$$
Thus
$$\|f(1/n)(x)\| = \left(\sum_{k=n+1}^{\infty}|x_{k}|^2\right )^{1/2}.$$
The last expression $\to 0$ as $n\to \infty.$ Thus $f(1/n) \to 0 = f(0)$ pointwise on $H.$ That is the desired conclusion.


How can I connect netlify-cms with self-hosted gotrue and git-gateway?

Question: The title is pretty self-explanatory I think.
Repos can be found here:

https://github.com/netlify/netlify-cms/
https://github.com/netlify/git-gateway
https://github.com/netlify/gotrue

I try to not use netlify's commercial solution and handle this only with their open source software.
Comment: I wasn't able to add tags for git-gateway and gotrue as it needs 1500 points of reputation...
Answer: This is the best example I'm aware of, and where I generally point folks to as an example. Setting up these projects is currently non-trivial.
https://github.com/hfte/netlify-cms-with-selfhosted-gotrue-and-git-gateway
Comment: That github link is going to a 404 now. Does anyone have other examples? Much appreciated!


Poisson regression model selection

Question: I'm in the process of learning about Poisson regression and i am wondering if anyone here could give me some valuable advice on model selection. I'm looking for values and tests like the Hosmer-Lemeshow test and the Roc curve for logistic regression but instead more appropriate for count data.
What's your process when comparing two Poisson regressions? Surely your selection cannot be only based on AIC values?
Comment: If your question has been answered to your satisfaction, you can accept an answer by clicking the check mark under the voting arrows.
Answer: You might want to use the following for assessment of fit:

Analysis of residual statistics

Graph residuals (e.g: standardised Pearson or Anscombe residuals) by prediction
Look for nonrandom patterns

Likelihood ratio test
Use score test to test for overdispersion
Use Lagrange Multiplier Test to test for overdispersion
Use chi-square test to assess predicted against observed counts

You might want to use AIC or BIC for model selection criteria.
Answer:
Surely your selection cannot be only based on AIC values?

Sure it can, assuming you're using the same dataset for both. Any generic model-selection method applies just as well when one or more of the models is a Poisson regression model. What made you think otherwise?
Comment: What would you then do if the models came from different datasets?
Comment: @Janono The whole idea of model selection requires you to be comparing models on the same data.

Poisson regression model selection


How to use Same Short Cut key in menu items and child windows buttons?

Question: Have used same short cut key option in menu Items and child window buttons.
Short cut key event fired in menu item when cursor focus in child window.But Child window events not fired. But i want to fired the events in child window buttons when used the short cut keys in child window.
Answer: You will want to look into using Commands
From above MSDN Link:

Commands have several purposes. The first purpose is to separate the
  semantics and the object that invokes a command from the logic that
  executes the command. This allows for multiple and disparate sources
  to invoke the same command logic, ...


How can I get more then one row with "AND" query in php mysql

Question: id - idProduct - idFilter
65 -    494    -    3
66 -    495    -    3
67 -    497    -    17
68 -    500    -    17
69 -    500    -    3

How I can get all idProducts who have idFilter 17 AND 3. In this case this is only product with id - 500
I try something like this:
$query="SELECT idProduct FROM tablename WHERE (idFilter = '3') OR (idFilter = '17') GROUP BY idProduct";
I know it's stupid but I don't know any idea?
Thank you
Comment: Where is your code you tried? And it is unclear wht you are trying to make. .. Explain it more
Comment: Can you try this `SELECT distinct(idProduct),count(*) as total FROM  tablename WHERE idFilter IN (17,3) GROUP BY idProduct  having total = 2;`
Comment: Thank you @Ajith it looks nice. I get what I want. Thank you one more time.
Comment: @MilosPopovic Welcome :) I ll post my answer so that someone can use the same
Comment: @MilosPopovic Please accept the answer if it does helps you
Answer: In case if you need to compare multiple row values on a single column, Such that the value should satisfy with an ANS condition.
Then you can do the following trick to achieve that:
SELECT distinct(idProduct) as idProduct,count(*) AS total FROM  tablename
        WHERE idFilter IN (17,3) GROUP BY idProduct
        HAVING total = 2;
        //Having will force result to have both 17 and 3  else 17 or 3 alone will be in the result

If using php variable for the above ids, you can try the following
$inArray = array(17,3);
$sql = "SELECT distinct(idProduct) as idProduct,count(*) AS total FROM  tablename
        WHERE idFilter IN (".implode(',',$inArray).") GROUP BY idProduct
        HAVING total = '".count($inArray)."'";