"statusCode": 422 should be number in loopback 4

Question: I have json object from angular as {"weight": "50"} but LoopBack 4 needs {"weight": 50}. How can I achieve this? I do not want to make any change in angular. Is there any settings in LoopBack 4?
Please help.
Answer: Hello from the LoopBack team
LoopBack uses the popular library AJV to validate incoming requests. It is possible to configure AJV to coerce types during validation, e.g. convert string "50" to a number 50 for a numeric property, see Coercing data types.
To enable coercion, modify your main application file (src/application.ts) as follows:
Import RestBindings from @loopback/rest:
import {RestApplication, RestBindings} from '@loopback/rest';

Add the following line at the end of your application constructor:
this.bind(RestBindings.REQUEST_BODY_PARSER_OPTIONS).to({
  validation: {coerceTypes: true},
})

Please note this setup will enable coercion for all model properties and all value types. See AJV Coercion Rules to better understand what will happen to different value types.
Comment: Thank yo will try this and let you know.


Drupal and apache rewrites

Question: I'm just migrating a site that has a proxy pass in the vhost config like the following.
ProxyPass /n/ http://xxx.xxx.xxx.xx:80/n/
ProxyPassReverse /n/ http://xxx.xxx.xxx.xx:80/n/

I need to replicate that in the drupal .htaccess file as I don't have direct access to the hosting as we're using a fully managed drupal solution. I have tried the following but it does not work, when I navigate to the drupal site /n I just get a 404.
RewriteRule /n/?$ http://xxx.xxx.xxx.xx:80/n/ [P]

Answer: Be aware that [P] requires mod_proxy to be enabled:
RewriteEngine on
RewriteRule /n/(.*)$ http://xxx.xxx.xxx.xx:80/n/$1 [P]

Drupal and apache rewrites


Compare 2 dates in a batch file

Question: I am using this to get the date modified of a file:
@echo off
FOR %%? IN ("C:\some.exe") DO (
    ECHO Last-Modified Date   : %%~t?
)

The above returns something like: Last-Modified Date   : 26/03/2013 14:43.
How can I take the date part from the above and compare it against another file which's name contains a date ie: 23-Sep-13.exe?
I need to be able to perform some code in the batch file if the file that contains the date in its name is later than the file modified version ie install the update.
Answer: @ECHO OFF
SETLOCAL
:: No doubt for international use, this could be retrieved from the registry
SET monthnames=Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
:: get last modified date of target file - your format as specified
:: (I used THIS BATCH FILE)
FOR %%i IN ("%~f0") DO SET target=%%~ti
:: parse the target date
FOR /f "tokens=1-3delims=/ " %%i IN ("%target%") DO SET targetf=%%k%%j%%i
::
:: parse name from 'other file'
SET other=23-Sep-13.exe
FOR /f "tokens=1-3delims=.- " %%i IN ("%other%") DO SET od=%%i&SET omn=%%j&SET oy=%%k
:: Convert monthname to number
:: @ECHO on
SET om=101
FOR %%i IN (%monthnames%) DO (
IF DEFINED omn IF /i %omn%==%%i (SET omn=) ELSE (SET /a om+=1)
)
:: Build date of 'other file' in same format (YYYYMMDD)
SET otherf=20%oy%%om:~-2%%od%
ECHO is %other% later than %target% ?
ECHO IF %otherf% gtr %targetf% GOTO later
ECHO.
::
:: parse name from 'another other file'
SET other=23-Jan-13.exe
FOR /f "tokens=1-3delims=.- " %%i IN ("%other%") DO SET od=%%i&SET omn=%%j&SET oy=%%k
:: Convert monthname to number
SET om=101
FOR %%i IN (%monthnames%) DO (
IF DEFINED omn IF /i %omn%==%%i (SET omn=) ELSE (SET /a om+=1)
)
:: Build date of 'other file' in same format (YYYYMMDD)
SET otherf=20%oy%%om:~-2%%od%
ECHO is %other% later than %target% ?
ECHO IF %otherf% gtr %targetf% GOTO later
ECHO.

Code takes date of (this batch) as the target (your 'C:\some.exe'- change to suit.
test then applied to two different filename-is-date+ext format filenames to test.
Can be easily adjusted if comparisons to 20th-Century date is required... :)
Comment: Thanks Peter - this works a treat.

Do you know how to do the same but using the exe's File Version instead of date for the compare ? ie exe file version: 184.108.40.206 = file name: 4050400.exe

Compare 2 dates in a batch file


Counter-intuitive result to an Integral calculus problem

Question: Consider the equations $y=x$ and $y=x^2$ in the first quadrant,
My hypothesis is that the solids produced by rotating the area enclosed by the equations about x axis and y axis will have the same volume.
But when i use integration methods to find the volume of those solids
For rotation about x-axis:-
$ V_1=\pi\int_{0}^{1}( x^2-x^4 )\,dx $
For rotation about y-axis:-
$ V_2=\pi\int_{0}^{1}( y-y^2)\,dy $
$Clearly,  V_1\neq V_2$
But this is very counter intuitive for me since both volumes can be understood as infinite sum of the same area about the two different axes.
Is there something that i am missing?
Thanks for your help
Edit:
When i sweep the area slice by a small constant angle about both axes ,i will endup with a larger arclength as a result of larger outer radius in case of the rotation with respect to $y axis$ compared to $x axis$ giving more volume for the same angle no matter the angle.
This extends my intuition to considering areas as sum of arclengths,which i need to consider more.
Comment: The solid that comes about from rotating around the $y$ axis will be larger because the "meatier" part of the crescent gets rotated through a wider a circle than if you were rotating about the $x$ axis, because the shape in general is "further away" from the $y$ axis than the $x$ axis.
Comment: No, there is no reason to think so. As an extreme case, take a rectangle $[0,2]\times[0,1]$. If you rotate it both ways, which one has the larger volume? Do they still have the same cross sectional area even though their volumes are different?
Comment: You're forgetting that the small infinitesimal rotation length element is given by $rd\theta$, not just $d\theta$. The one with the larger arc length (which means larger radius) would have the larger volume slice.
Comment: Hmmm, but if i consider rotating the area element about x axis with a small angle d(theta) and i do the same with the y axis, do you think we will get the same result?
Comment: Both will give rise to cylinders with different volumes but same cross sectional area. Hmmm , but does this hold for small rotations as well ? I mean they will approximately have the same value but do they still have a difference?
Comment: Please don't use a differential geometry tag if you don't know what it's for.
Comment: @Planck this may be of interest to you too (esp. the second theorem)  https://en.wikipedia.org/wiki/Pappus%27s_centroid_theorem#:~:text=Goodman%20%26%20Goodman%20generalize%20the%20second,solid%20does%20not%20intersect%20itself.)
Comment: @Math Lover thanks !! What prerequisites do i need for understanding its proof in for n-dimensions
Answer: Rotating about the $y$ would be the same thing as using the shells method on $x$. Compare the two integrals
$$\pi\int_0^1 f_1^2(x)-f_2^2(x)dx$$
$$2\pi\int_0^1x(f_1(x)-f_2(x))dx$$
Assuming $f_1>f_2$ on $(0,1)$ et's see when the integrands are equivalent
$$\pi(f_1^2(x)-f_2^2(x)) = 2\pi x(f_1(x)-f_2(x)) \implies f_1(x)+f_2(x) = 2x$$
so if the sum of the functions is less than $2x$, than rotation about the $y$ will be larger.
Comment: I still have to look into shells method, thanks for letting me know of it's existence.


Blow-up and resolving a singularity

Question: Given a variety $X=\{F:=x_0^3+t(x_1^3+x_2^3+x_3^3+x_4^3+1)=0\}\subset \mathbb{C}^6$, where $(x_0,...,x_4,t)$ are coordinates of $\mathbb{C}^6$. How to resolve the singularity by only blow-up smooth subvariety of $X$ that is contained in $\{x_0^3=0\}$? How many steps do we need for blow-ups, and what are the exceptional divisors for each step?
Can we even use computers? :-)
Answer: This might not be a complete answer, but it's far too long for a comment.
The software package singular might help: It can resolve singularities. It can resolve yours as well, quite fast actually.
I used this code:
<code>LIB"resolve.lib";
ring R=0,(a,b,c,d,e,t),dp;
ideal I=a^3+t*(b^3+c^3+d^3+e^3+1);
list L=resolve(I,1);
</code>
The complete output is as follows:
<code>                     SINGULAR                                 /
 A Computer Algebra System for Polynomial Computations       /   version 3-1-6
                                                           0<
 by: W. Decker, G.-M. Greuel, G. Pfister, H. Schoenemann     \   Dec 2012
FB Mathematik der Universitaet, D-67653 Kaiserslautern        \
> LIB"resolve.lib";
// ** loaded /usr/share/Singular/LIB/resolve.lib (13499,2010-10-15)
// ** loaded /usr/share/Singular/LIB/sing.lib (14840,2012-04-20)
// ** loaded /usr/share/Singular/LIB/random.lib (14661,2012-03-05)
// ** loaded /usr/share/Singular/LIB/matrix.lib (13658,2010-11-16)
// ** loaded /usr/share/Singular/LIB/nctools.lib (14246,2011-05-26)
// ** loaded /usr/share/Singular/LIB/poly.lib (14852,2012-04-30)
// ** loaded /usr/share/Singular/LIB/ring.lib (15322,2012-10-12)
// ** loaded /usr/share/Singular/LIB/general.lib (14191,2011-05-04)
// ** loaded /usr/share/Singular/LIB/inout.lib (13499,2010-10-15)
// ** loaded /usr/share/Singular/LIB/linalg.lib (13733,2010-12-06)
// ** loaded /usr/share/Singular/LIB/presolve.lib (14203,2011-05-05)
// ** loaded /usr/share/Singular/LIB/primdec.lib (14732,2012-03-30)
// ** loaded /usr/share/Singular/LIB/absfact.lib (14191,2011-05-04)
// ** loaded /usr/share/Singular/LIB/triang.lib (13499,2010-10-15)
// ** loaded /usr/share/Singular/LIB/elim.lib (14661,2012-03-05)
> ring R=0,(a,b,c,d,e,t),dp;
> ideal I=a^3+t*(b^3+c^3+d^3+e^3+1);
> list L=resolve(I,1);
++++++++++++++ Overview of Current Chart +++++++++++++++++++++++
Current number of final charts: 0
Total number of charts currently in chart-tree: 1
Index of the current chart in chart-tree: 1
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

==== Ambient Space:
_[1]=0

==== Ideal of Variety:
_[1]=b3t+c3t+d3t+e3t+a3+t

==== Exceptional Divisors:
empty list

==== Images of variables of original ring:
_[1]=a
_[2]=b
_[3]=c
_[4]=d
_[5]=e
_[6]=t

-------------------------- Upcoming Center ---------------------
_[1]=t
_[2]=a
_[3]=b3+c3+d3+e3+1
----------------------------------------------------------------
++++++++++++++ Overview of Current Chart +++++++++++++++++++++++
Current number of final charts: 0
Total number of charts currently in chart-tree: 4
Index of the current chart in chart-tree: 2
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

==== Ambient Space:
_[1]=x(2)^3+x(3)^3+x(4)^3+x(5)^3-x(6)*y(2)+1

==== Ideal of Variety:
_[1]=x(2)^3+x(3)^3+x(4)^3+x(5)^3-x(6)*y(2)+1
_[2]=x(6)*y(1)^3+y(2)

==== Exceptional Divisors:
[1]:
   _[1]=x(6)
   _[2]=x(2)^3+x(3)^3+x(4)^3+x(5)^3+1

==== Images of variables of original ring:
_[1]=x(6)*y(1)
_[2]=x(2)
_[3]=x(3)
_[4]=x(4)
_[5]=x(5)
_[6]=x(6)

-------------------------- Upcoming Center ---------------------
_[1]=x(2)^3+x(3)^3+x(4)^3+x(5)^3-x(6)*y(2)+1
_[2]=x(6)*y(1)^3+y(2)
----------------------------------------------------------------
++++++++++++++ Overview of Current Chart +++++++++++++++++++++++
Current number of final charts: 1
Total number of charts currently in chart-tree: 4
Index of the current chart in chart-tree: 3
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

==== Ambient Space:
_[1]=x(2)^3+x(3)^3+x(4)^3+x(5)^3-x(1)*y(2)+1

==== Ideal of Variety:
_[1]=y(0)*y(2)+x(1)
_[2]=x(2)^3+x(3)^3+x(4)^3+x(5)^3-x(1)*y(2)+1

==== Exceptional Divisors:
[1]:
   _[1]=x(1)
   _[2]=x(2)^3+x(3)^3+x(4)^3+x(5)^3+1

==== Images of variables of original ring:
_[1]=x(1)
_[2]=x(2)
_[3]=x(3)
_[4]=x(4)
_[5]=x(5)
_[6]=x(1)*y(0)

-------------------------- Upcoming Center ---------------------
_[1]=y(2)
_[2]=y(0)
_[3]=x(1)
_[4]=x(2)^3+x(3)^3+x(4)^3+x(5)^3+1
----------------------------------------------------------------
++++++++++++++ Overview of Current Chart +++++++++++++++++++++++
Current number of final charts: 1
Total number of charts currently in chart-tree: 6
Index of the current chart in chart-tree: 4
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

==== Ambient Space:
_[1]=0

==== Ideal of Variety:
_[1]=x(2)^3*y(1)^3+x(3)^3*y(1)^3+x(4)^3*y(1)^3+x(5)^3*y(1)^3+y(1)^3+y(0)

==== Exceptional Divisors:
[1]:
   _[1]=x(2)^3+x(3)^3+x(4)^3+x(5)^3+1

==== Images of variables of original ring:
_[1]=x(2)^3*y(1)+x(3)^3*y(1)+x(4)^3*y(1)+x(5)^3*y(1)+y(1)
_[2]=x(2)
_[3]=x(3)
_[4]=x(4)
_[5]=x(5)
_[6]=x(2)^3*y(0)+x(3)^3*y(0)+x(4)^3*y(0)+x(5)^3*y(0)+y(0)

-------------------------- Upcoming Center ---------------------
_[1]=x(2)^3*y(1)^3+x(3)^3*y(1)^3+x(4)^3*y(1)^3+x(5)^3*y(1)^3+y(1)^3+y(0)
----------------------------------------------------------------
++++++++++++++ Overview of Current Chart +++++++++++++++++++++++
Current number of final charts: 2
Total number of charts currently in chart-tree: 6
Index of the current chart in chart-tree: 5
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

==== Ambient Space:
_[1]=x(2)^3+x(3)^3+x(4)^3+x(5)^3-x(7)^2*y(2)+1

==== Ideal of Variety:
_[1]=x(7)*y(1)+y(2)
_[2]=x(2)^3+x(3)^3+x(4)^3+x(5)^3-x(7)^2*y(2)+1

==== Exceptional Divisors:
[1]:
   _[1]=y(2)
   _[2]=x(2)^3+x(3)^3+x(4)^3+x(5)^3+1
[2]:
   _[1]=x(7)
   _[2]=x(2)^3+x(3)^3+x(4)^3+x(5)^3+1

==== Images of variables of original ring:
_[1]=x(7)*y(2)
_[2]=x(2)
_[3]=x(3)
_[4]=x(4)
_[5]=x(5)
_[6]=x(7)^2*y(1)*y(2)

-------------------------- Upcoming Center ---------------------
_[1]=y(2)
_[2]=x(7)
_[3]=x(2)^3+x(3)^3+x(4)^3+x(5)^3+1
----------------------------------------------------------------
++++++++++++++ Overview of Current Chart +++++++++++++++++++++++
Current number of final charts: 2
Total number of charts currently in chart-tree: 8
Index of the current chart in chart-tree: 6
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

==== Ambient Space:
_[1]=x(6)^2*y(0)*y(2)-x(2)^3-x(3)^3-x(4)^3-x(5)^3-1

==== Ideal of Variety:
_[1]=x(6)*y(0)+y(2)
_[2]=x(2)^3+x(3)^3+x(4)^3+x(5)^3+x(6)*y(2)^2+1

==== Exceptional Divisors:
[1]:
   _[1]=y(2)
   _[2]=x(2)^3+x(3)^3+x(4)^3+x(5)^3+1
[2]:
   _[1]=x(6)
   _[2]=x(2)^3+x(3)^3+x(4)^3+x(5)^3+1

==== Images of variables of original ring:
_[1]=x(6)*y(2)
_[2]=x(2)
_[3]=x(3)
_[4]=x(4)
_[5]=x(5)
_[6]=x(6)^2*y(2)

-------------------------- Upcoming Center ---------------------
_[1]=y(2)
_[2]=x(6)
_[3]=x(2)^3+x(3)^3+x(4)^3+x(5)^3+1
----------------------------------------------------------------
++++++++++++++ Overview of Current Chart +++++++++++++++++++++++
Current number of final charts: 2
Total number of charts currently in chart-tree: 10
Index of the current chart in chart-tree: 7
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

==== Ambient Space:
_[1]=x(7)^3*y(1)^2-x(1)^3-x(2)^3-x(3)^3-x(4)^3-1

==== Ideal of Variety:
_[1]=x(6)*y(1)+1
_[2]=x(1)^3*x(6)+x(2)^3*x(6)+x(3)^3*x(6)+x(4)^3*x(6)+x(7)^3*y(1)+x(6)
_[3]=x(7)^3*y(1)^2-x(1)^3-x(2)^3-x(3)^3-x(4)^3-1

==== Exceptional Divisors:
[1]:
   _[1]=1
[2]:
   _[1]=y(1)
   _[2]=x(1)^3+x(2)^3+x(3)^3+x(4)^3+1
[3]:
   _[1]=x(7)
   _[2]=x(1)^3+x(2)^3+x(3)^3+x(4)^3+1

==== Images of variables of original ring:
_[1]=x(7)^2*y(1)
_[2]=x(1)
_[3]=x(2)
_[4]=x(3)
_[5]=x(4)
_[6]=x(6)*x(7)^3*y(1)^2

-------------------------- Upcoming Center ---------------------
_[1]=x(6)*y(1)+1
_[2]=x(1)^3*x(6)+x(2)^3*x(6)+x(3)^3*x(6)+x(4)^3*x(6)+x(7)^3*y(1)+x(6)
_[3]=x(7)^3*y(1)^2-x(1)^3-x(2)^3-x(3)^3-x(4)^3-1
----------------------------------------------------------------
++++++++++++++ Overview of Current Chart +++++++++++++++++++++++
Current number of final charts: 3
Total number of charts currently in chart-tree: 10
Index of the current chart in chart-tree: 8
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

==== Ambient Space:
_[1]=x(5)^3*y(0)-x(1)^3-x(2)^3-x(3)^3-x(4)^3-1

==== Ideal of Variety:
_[1]=x(6)+y(0)
_[2]=x(5)^3*y(0)-x(1)^3-x(2)^3-x(3)^3-x(4)^3-1

==== Exceptional Divisors:
[1]:
   _[1]=y(0)
   _[2]=x(1)^3+x(2)^3+x(3)^3+x(4)^3+1
[2]:
   _[1]=1
[3]:
   _[1]=x(5)
   _[2]=x(1)^3+x(2)^3+x(3)^3+x(4)^3+1

==== Images of variables of original ring:
_[1]=x(5)^2*y(0)
_[2]=x(1)
_[3]=x(2)
_[4]=x(3)
_[5]=x(4)
_[6]=x(5)^3*x(6)*y(0)

-------------------------- Upcoming Center ---------------------
_[1]=x(6)+y(0)
_[2]=x(5)^3*y(0)-x(1)^3-x(2)^3-x(3)^3-x(4)^3-1
----------------------------------------------------------------
++++++++++++++ Overview of Current Chart +++++++++++++++++++++++
Current number of final charts: 4
Total number of charts currently in chart-tree: 10
Index of the current chart in chart-tree: 9
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

==== Ambient Space:
_[1]=x(6)*x(7)^3*y(1)^2-x(1)^3-x(2)^3-x(3)^3-x(4)^3-1

==== Ideal of Variety:
_[1]=x(6)*y(1)+1
_[2]=x(7)^3*y(1)+x(1)^3+x(2)^3+x(3)^3+x(4)^3+1
_[3]=x(1)^3*x(6)+x(2)^3*x(6)+x(3)^3*x(6)+x(4)^3*x(6)-x(7)^3+x(6)

==== Exceptional Divisors:
[1]:
   _[1]=1
[2]:
   _[1]=y(1)
   _[2]=x(1)^3+x(2)^3+x(3)^3+x(4)^3+1
[3]:
   _[1]=x(7)
   _[2]=x(1)^3+x(2)^3+x(3)^3+x(4)^3+1

==== Images of variables of original ring:
_[1]=x(7)^2*y(1)
_[2]=x(1)
_[3]=x(2)
_[4]=x(3)
_[5]=x(4)
_[6]=x(7)^3*y(1)^2

-------------------------- Upcoming Center ---------------------
_[1]=x(6)*y(1)+1
_[2]=x(7)^3*y(1)+x(1)^3+x(2)^3+x(3)^3+x(4)^3+1
_[3]=x(1)^3*x(6)+x(2)^3*x(6)+x(3)^3*x(6)+x(4)^3*x(6)-x(7)^3+x(6)
----------------------------------------------------------------
++++++++++++++ Overview of Current Chart +++++++++++++++++++++++
Current number of final charts: 5
Total number of charts currently in chart-tree: 10
Index of the current chart in chart-tree: 10
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

==== Ambient Space:
_[1]=x(5)^3*x(6)*y(0)-x(1)^3-x(2)^3-x(3)^3-x(4)^3-1

==== Ideal of Variety:
_[1]=x(6)+y(0)
_[2]=x(5)^3*y(0)^2+x(1)^3+x(2)^3+x(3)^3+x(4)^3+1

==== Exceptional Divisors:
[1]:
   _[1]=y(0)
   _[2]=x(1)^3+x(2)^3+x(3)^3+x(4)^3+1
[2]:
   _[1]=1
[3]:
   _[1]=x(5)
   _[2]=x(1)^3+x(2)^3+x(3)^3+x(4)^3+1

==== Images of variables of original ring:
_[1]=x(5)^2*y(0)
_[2]=x(1)
_[3]=x(2)
_[4]=x(3)
_[5]=x(4)
_[6]=x(5)^3*y(0)

-------------------------- Upcoming Center ---------------------
_[1]=x(6)+y(0)
_[2]=x(5)^3*y(0)^2+x(1)^3+x(2)^3+x(3)^3+x(4)^3+1
----------------------------------------------------------------
============= result will be tested ==========

the number of charts obtained: 6
=============     result is o.k.    ==========
</code>
However, I am too unexperienced with singular to be sure how to interpret the output exactly. You might have to read this tutorial quite carefully:
http://www.singular.uni-kl.de/tutor_resol.ps
Comment: Thank you for your answer. It is very powerful. However, I am worrying about if the procedure of blowing-up just blow up smooth sub variety from the original singular set. Does it change the original smooth locus?

Blow-up and resolving a singularity


Regular Expression pattern to match a html tag in LEX utility?

Question: I m new to Lex.
I want to write a lex program to extract all html tags from a file.
I tried several patters to match the tags but all failed to work properly.
I tried
"<"[^>]*> /*The quotes because lex utility gives error that improper start of expression*/
"<"[a-z]+[/]*>

and many more... But when I execute a line like

 This is a heading

on them, and try to print it with yytext, it simply prints complete line of code as it is instead of just printing

Any solutions?
Comment: Don't parse HTML with regular expression.
Comment: What else can be done? My problem definition is to create a lex program which extracts all html tags out of a input file.
Answer: I have got the answer.
What I was doing was, having no action for the rest unmatched text.
I made my rule section of lex program as:
"<"[^>]*> { /* action for tags */ }
.|\n     ;

And thats that. Now it prints the desired output.


What do composite basketballs offer over leather basketballs?

Question: What do composite basketballs offer over leather basketballs? I notice the designs are slightly different, and composite basketballs would not have to be broken in and can maintain itself better than leather basketballs during a game.

In 2006, the NBA introduced a new composite (synthetic) basketball for use during the 2006-2007 NBA Season.

Midway through the 2006-2007 season, leather basketballs were reintroduced. Players were suffering from cuts on their hands due to composite basketballs.
Answer: One reason is cost. When you're having to produce so many basketballs, finding a cheaper way to do it would make sense.
From the eHow article on basketballs (emphasis mine):

Balls that are 100 percent genuine leather are the best ones available and are used in the NBA and WNBA. Leather balls develop a broken-in feel after repeated use. This type of leather basketball should only be used on indoor courts. It is also the most expensive type of ball to purchase because it is made of genuine leather.
Synthetic or composite leather is an artificial type of material that feels like leather but is cheaper to produce. The materials are also more versatile and can be used both indoors and outdoors. Synthetic leather doesn't need to be broken in as it already has that softer feeling to it.

From Wikipedia (emphasis mine):

Balls are generally designated for indoor (generally made of leather or absorbent composites), or all-surface use (generally made of rubber or durable composites, also known as Indoor/Outdoor balls). Indoor balls tend to be considerably more expensive than all-surface balls due to cost of materials.

Through these clips, we can also see that composite balls are more durable, especially for outdoor use, which really shouldn't matter in the NBA. Their longevity compared to leather balls would also help reduce costs since replacements wouldn't be needed as frequently.
Another reason is quality. Straight from NBA.com in 2006:

The material is a microfiber composite with moisture management that provides superior grip and feel throughout the course of a game. Additionally, the new composite material eliminates the need for a break-in period, which is necessary for the current leather ball, and achieves consistency from ball to ball.

The players disagreed with the first point made here, causing the league to revert back to leather balls. With how hard NBA players pass and shoot, it is possible that the "superior grip and feel" translated to a rougher ball that caused small cuts.
The consistency between balls without breaking them in is an improvement that theoretically would provide a more level playing field for teams. Having better consistency would reduce the number of variables that could impact game outcomes. This seems minor and relatively silly, but the league wants to ensure the only variables between games is how well a team plays; any reduction in variability outside of team skill would try to be controlled.


How to fix the "request time out" error in Xcode archives

Question: Sometime we can get an error, when Xcode try to fetch the accounts from apple server. the error is shown below
Answer: There are solutions out there to solve this, but their is one more simple solution for this type of error
go to Xcode

Xcode Preference
Source Control Tab

xcode preference image
Here you can see the "refresh server status automatically" title.
tick the checkbox and close the preference. then again try to build.
if it didn't work, try to build again after some mins. it always works for me.
Hope this helps.


Como fazer uma requisição GET em Javascript?

Question: Sou iniciante em programação e estou fazendo alguns projetos e estudando para montar um portfolio. O meu problema atual está sendo com uma API de imagens (unsplash). Testei primeiro pelo insomnia fiz uma requisição GET para https://api.unsplash.com/photos/random, lá forneci o Client-ID da API no header Authorization e recebi com sucesso um JSON com o link da imagem e outras informações. O meu gargalo está na hora de codar isso. Tentei usar o fetch como no código abaixo:
    function setWallpaper() {
        fetch(`https://api.unsplash.com/photos/random`).then(response => {
            return response.json();
        })
        .then(data => {
            const { id } = data.id
            console.log(id);
        })
    }

Eu espero receber o ID da imagem, mas no console não aparece nada. Talvez seja porque falta colocar o Client-ID na header Authorization, mas não sei onde colocar essa informação no código.
Comment: Em `const { id } = data.id` na verdade você cria um objeto e joga fora. Tente `const id = data.id` e seu código deve funcionar.
Answer: Exatamente como é explicado na MDN:

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Supplying_your_own_request_object
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Headers

Exemplo:
const myHeaders = new Headers({
    'Header-do-Client-ID': 'valor do header do Client-ID'
});

const myInit = {
  method: 'GET',
  headers: myHeaders
};

const myRequest = new Request('https://api.unsplash.com/photos/random', myInit);

fetch(myRequest).then(response => {
    return response.json();
})
.then(data => {
    const { id } = data.id
    console.log(id);
});

Obviamente troque Header-do-Client-ID pelo nome do header correto e troque o valor do header do Client-ID também. Um exemplo se fosse com bearer (possivelmente):
const token = 'valor aqui';

const myHeaders = new Headers({
    'Authorization': `Bearer ${token}`
});

const myInit = {
  method: 'GET',
  headers: myHeaders
};

Comment: Como posso saber se os valores foram retornados corretamente? O `console.log(id)` não é exibido no navegador, acho que não está pegando o json...
Comment: @DavidLima olha o console, veja se ocorreu algum erro.
Comment: @DavidLima tá entrando no then ou não?


MailJet | how to Send Mail with Python using variables in text part?

Question: I want to add "print (variable_name)" to the following statement:
'Text-part': 'Dear passenger, welcome to Mailjet! May the delivery force be with you!',
How can it be done?
Following is the Python code:
from mailjet_rest import Client
import os

data = {
        'FromEmail': '****@****.com',
        'FromName': '****',
        'Subject': 'Available DB Names:', #Subject
        'Text-part': 'Dear passenger, welcome to Mailjet! May the delivery
         force be with you!',
         'Recipients': [{ "Email": "****@****.com"}]
          }
         result = mailjet.send.create(data=data)
         print (result.status_code)
         print (result.json())

Thanks in advance
Answer: I assume you want something like this?
data = {
        'FromEmail': '****@****.com',
        'FromName': '****',
        'Subject': 'Available DB Names:', #Subject
        'Text-part': 'Dear {}, welcome to Mailjet! May the delivery
         force be with you!'.format(variable_name),
         'Recipients': [{ "Email": "****@****.com"}]
          }

Comment: Thanks a lot for your answer, correct, finally worte following and it worked for me:

 'Text-part': 'Dear {}, welcome to Mailjet! May the delivery '  + str(variable_name)
Comment: @Josh Friedlander why do you cast to `str()` before passing into `format()`? You're ruining all the goodness that `format()` has to offer!
Comment: @NilsWerner thanks for pointing that out. As you'll see in the edit history, my original answer didn't include `str` - not sure why I changed it, but I've reverted it now...
Answer: Do not forget to also declare your vars section within the call. That is were you would give a value to your custom variables.
"Variables": {
                                "day": "Monday"
                        }

And the placeholder within the HTML-Part or Text-Part would look as such {{var:day}} which would be replaced by the value of your custom variable at the recipients end.


Working on trombone sound

Question: I've been playing the trombone for a couple of years and only now I've understood how breath and sound are important. When I listen to my long notes I can hear that the tone is not clear and some air comes along with the sound not through the embouchure but further(does it make any sense?). Anyway, I'm listening to the professionals and their sound is so soft and deep without any even little air noise. Moreover, when I'm trying to reach high notes I strain my lips hard and get tired fast which shouldn't occur. And it also makes the sound unclean. Are there any ways to learn the clean sound, exercises or something?
Is the problem about breathing, carrying embouchure or lips position?
PS Many people say that playing long notes is the solution but I've been playing them for months and they were still unclean.
Answer: There are many ways you could approach this, but the best way is to find a qualified teacher. For something like this, even one lesson a month, (or even less frequently) would do much to help your tone along. Since embouchure and tone are such individual characteristics, both of you and your equipment, I can only offer a few sweeping generalizations.
In my experience, especially in younger/newer players, there is a misunderstanding when it comes to playing exercises, including long tones. Simply playing long tones will not make your tone much better. What you want to do is play long tones while isolating the good portions of tone. Listen carefully to your tone, and morph it so it sounds the best it can be. You won't hear an immediate difference overnight, and the changes will be subtle, but the key is to LISTEN. This rule applies to any exercise you do. I also recommend slow lip-slurs (note changes without using your tongue) as a good strengthening exercise. Again, do them slowly, while listening, and don't accept a bad sound or execution. Your goal is to learn the cleanest, prettiest ways of playing a particular passage, and move the percentage so it sounds like that every time you play it. This takes time.
Breath is important as well. I won't go in depth as there are countless good sources of breathing information out there. It's essentially the same for any musician that uses air, but I highly recommend checking out breathing tips for singers. Singers tend to concentrate more on a relaxed, tension-free breath than many instrumentalists do, and I advocate that technique. Most importantly, low and slow, filling up your abdomen. Your shoulders and chest should not move much, if at all; however you should feel and see your stomach expand.
Embouchure questions really should be directed to a competent teacher who can watch and hear you play, but here are a few things you can experiment with before heading to one:
Try putting more of the top-lip in the mouthpiece, and less of the bottom lip. Try vice-versa. Make sure the mouthpiece is relatively centered on your lips from side-to-side. (Assuming you don't have problematic teeth, as I did in the past). Try keeping your same embouchure placement, but concentrate on focusing your airstream down, up, or straight down the tube. (Alternate). Try puckering more, or less. Try pointing your instrument more down, or more up, in gradual increments, without moving your head to adjust the pressure from the top to bottom lip. Make written notes of what works, and preferably record or videotape your playing.
Lastly, as much as I hate to advocate equipment changes early, if you are playing on a 12c mouthpiece, try obtaining a 61/2AL size mouthpiece. Everyone's lips/mouth/face/playing habits are different, and the idea of a one-size-fits-all mouthpiece is ludicrous. This should be tried after the above steps.
Again, my advice is to find a teacher. However if you have a good ear, and you spend some time at it, simply experimenting with some of the things above may help you.
PS. I didn't address the high-note straining you mentioned, as it's  not necessarily related to your tone issue. However your lips should not be doing most of the work. Above all don't use mouthpiece pressure on your lips to get the high notes! Try whistling a low note, skipping up to a high note, then back down. Notice your tongue goes from "oo" or "ah" to "ee" this extends to playing too! Focus on that change, then concentrate on blowing faster air. Less air, but at a higher speed. You'll get it, but it takes time. My advice is concentrate on the tone issue first.
Comment: Epic +1 for **RECORD YOURSELF PLAYING** - The sound from behind the bell is _significantly_ different from what someone in the audience of a hall would hear. You may find the slight "airyness" you perceive in your tone is only noticeable from behind the instrument. High notes will come with time and consistent practice. When you started playing D4 for the first time, it probably sounded like your current upper limit does now.
Comment: wow, thanks for the great answer, unfortunately I can't find a teacher but I'll try to listen to myself
Answer: I don't play now, haven't for over 20 years. But when I was in high school and took lessons, one concept helped me immensely when trying to overcome reaching for the high notes. Incidentally, with my lessons I became first chair in the upper level symphonic band, orchestra, and jazz ensemble, so I agree with the other post about taking lessons...you'll do yourself quite a favor by following that advice.
On to hitting the high notes, my thought is a little different than the other poster's. The notes, as one typically thinks about it, are high - re: the analogies of "reaching" for them, which to me implied reaching up. However, the advice that worked for me was to think about them as not "up" but "further away". For me, it was not trying to get my lips tighter (which is, of course, required), but getting more air moving across them. They are "further away" which meant (for me) that I had to blow harder to get the note. YMMV, but I hope this helps!

Working on trombone sound


In a clairvoyance test, a stack of 25 cards with 5 types is used. You take 3 cards at once. In how many ways can you not take cards of type 1 and 2?

Question: In a clairvoyance test, a stack of 25 cards is used, with each of the 5 types of cards occurring 5 times.
You take 3 cards at once. In how many ways can you not take cards of type 1 and type 2?
Solution:
There is no difference between cards of the same type.
The possible cards that you can take are:
type 3 - type 3 - type 3
type 4 - type 4 - type 4
type 5 - type 5 - type 5
type 3 - type 3 - type 4
type 3 - type 3 - type 5
type 4 - type 4 - type 3
type 4 - type 4 - type 5
type 5 - type 5 - type 3
type 5 - type 5 - type 4
type 3 - type 4 - type 5
I think there are 10 possibilities. However, my book provides ncr (15,3) as a solution. What is correct?
Comment: Your book is considering there to be a difference between cards of the same type, where as you are not, hence the difference in your answers.
Comment: What about the comment of @quasi? I think it is wrong...
Comment: quasi is assuming the cards within a type are distinct, and is correct under that assumption.
Comment: Indeed, but that is just what you said. Isn't it? My answer is correct in case that we do not district cards of the same type?
Comment: This is why it is better to ask these sorts of problems about probabilities, which are unambiguous, rather than (only) enumeration. The only advantage (but it is huge) of treating the cards as distinct is that the outcomes are equally likely which makes the probability computation simple. The text books should be more careful about these sorts of ambiguities in the wording of pure enumeration questions, since the "equally likely" aspect is of no relevance if you aren't computing probabilities.
Comment: @Ned what do you mean with "since the equally likely aspect is of no relevance if you aren't computing probabilities"?
Comment: What does "ncr(15,3)" mean.
Comment: " My answer is correct in case that we do not district cards of the same type?"  Yes, but why would you not distiguish between cards of the same type?  The jack of diamonds is a completely different card than the three of diamonds.
Comment: I mean the OP's interpretation is a perfectly valid combinatorial problem -- the number of distinguishable unordered hands where the the multiple cards of each type are taken to be indistinguishable. Now it's kind of silly to be asking for that when you give the additional info of "5 cards of each type" which in math-text-book-talk surely is implying that you should treat the cards as distinguishable. But that's why I think it is better to ask for the probability since then there is no ambiguity .... beginners may not be familiar with the linguistic conventions of math problem sets.
Answer: The book is correct.

To see where you went wrong, consider the following outcomes . . .

The number of ways to get three $3$'s is ${\large{\binom{5}{3}}}=10$.

The number of ways to get two $3$'s and one $4$ is
${\large{\binom{5}{2}}}{\large{\binom{5}{1}}}=50$.

The number of ways to get one $3$, one $4$, and one $5$ is
${\large{\binom{5}{1}}}^3=125$.

So these three outcomes are not equally numerous as $3$-card hands, but in your analysis, you gave them the same weight.

The key is that the $25$ cards cards are physically distinct, so two distinct cards of the same rank should not be regarded as the same card.

Thus, since there are $15$ cards with ranks $3$, $4$, or $5$, the number of $3$-card hands from those $15$ cards is ${\large{\binom{15}{3}}}$.
Comment: Bu the number of ways to get three 3's is just 1? There is no difference between cards...
Comment: Number the cards from $1$ to $25$ using invisible ink. Now they are all different, even if the test taker can't see the difference. Alternatively, consider the position of a card in the deck, A card with rank $3$ at positiion $1$ is not the same card as a card of rank $3$ at position $8$, say.
Comment: The book is clearly regarding physically distinct cards as distinct (which is the natural interpretation, unless specified otherwise).
Comment: Also note: The context is a "clairvoyance test", so a blind guess of $3,4,5$ should not be credited the same as a blind guess of $3,3,3$, since the outcome $3,4,5$ is $12.5$ times more likely to occur than the outcome $3,3,3$.


Can an agent be trained in a completely random environment (the rules and actions stay the same)

Question: I am specifically talking about the FrozenLake example from openAI gym to illustrate my question.
https://gym.openai.com/envs/FrozenLake-v0/
The way I understand how Q-Learning or DQL works on the FrozenLake environment is that the agent plays the same map a lot of times until either the Q-table or the NN can approximate the value of a given state action tuple.
However while doing some research, I found no one attempting to try to use the randomly generated map of this environment.
I also dont understand how it would work... It seems to me that an agent only tries to learn the different states of a specific environment. However if this environment changes every time, the agent can not use its previously learned information (e.g. the agent can not remember where the holes are to avoid as they change every time the level is newly generated)...

Is it impossible to train an agent on a changing environment if the observation space is only its current position (but not the whole level) *
Is it possible to create an agent that can somehow generalise and learn to navigate every random level he is confronted with?

If yes, is DQN the right algorithm to do so?
If yes, is the solution to give the agent more information about the state (i.e. a bigger observation space) (if  yes, what kind of information could be given additionally? the whole level would be too much because then other algorithms could be used, or not?)

Am I understanding something else wrong?

(*) Intuitively I would say yes, at least in the case of the FrozeLake example. If the only information about the state the algorithm receives is its current position in the state, there should be no way for an agent to predict where a hole could be, so he can only guess where to go and might fall in a hole.
Answer:
Is it impossible to train an agent on a changing environment if the observation space is only its current position (but not the whole level)

No, it is possible to learn an optimal policy for the average environment:
To answer this question, let's try to identify the optimal policy first analytically:
According to the linked file:

The start is always in the top left, the goal is always in the bottom right corner.
The reward is 1 if we reach the goal, and 0 if we fall into a hole.
The action space is the cardinal directions, lets assume that the ice is not slippery.

The rest of the tiles are random, but it is guaranteed that we have a possible path from start to finish.
So what is the optimal policy here?
As we can not know the location of the holes, we might as well ignore them, and it becomes apparent that any policy that moves towards the bottom right, i.e. only moves to the bottom and to the right is optimal.
This is quickly illustrated in the colab I wrote for the task, which shows that we can learn a policy that is far better than a random agent, even when switching the environment each time.

The learned policy also looks almost as expected, the top right corner was however visited so infrequently, that the policy is not optimal there:
<code>Learned policy (Down, Right, Left, Up):
['D', 'D', 'D', 'U']
['D', 'D', 'D', 'D']
['D', 'D', 'D', 'D']
['R', 'R', 'R', 'D']
</code>

Is it possible to create an agent that can somehow generalise and learn to navigate every random level he is confronted with?

No, the best we can do given only the position as observation is to learn an agent that performs optimally on the average task, as above.

If yes, is the solution to give the agent more information about the state (i.e. a bigger observation space) (if yes, what kind of information could be given additionally? the whole level would be too much because then other algorithms could be used, or not?)

As long as the information is enough to infer the position of the holes, we can learn an optimal policy on every new map, as such the whole map provides sufficient information.
Answer: I will be adding links that I found helpful to answer my question here, while still hoping I will receive an actual answer.

https://stackoverflow.com/questions/52744919/is-reinforcement-learning-applicable-to-a-random-environment
This seems to indicate that using a changing or random environment seems to be possible, however difficult and not really feasible with reinforcement learning based algorithms that try to approximate the value of a state, like DQN, ...


How to download the public key of the AWS account?

Question: A co-worker asked me to share with him my PGP public keys to send us encrypted credentials to access the data. But I don't know how to do that.
It was not me who created my key, it was the former colleague who sent me a csv file with my identifiers:
<code>User name,Password,Access key ID,Secret access key,Console login link
firstname.lastname@example.com,unpassword, ELACCESSKEYID, S3/CR33T//AcCessKeY , https://numeros.signin.aws.amazon.com/console
</code>
Then I followed the documentation to download the public key but there are no keys:

I am using Windows10
Answer: AWS does not use PGP keys.
The credentials you have shown are used to login to the AWS management console. They are unrelated to encrypting emails.
If you want to use PGP for encrypting email contents, you would do this outside of AWS.


Assign IP range per switch?

Question: Is it possible to handout IP ranges per switch with the use of one DHCP server?
Example, i have 2 Swicthes (A & B). I like to:

switch a => 192.168.1.50 - 192.168.1.75
  switch b => 192.168.1.76 - 192.168.1.100

My problem is i have a few switches that are hooked up with a 'test bench'. On each bench they connect a dozen of systems. Then they load software on each system. The loaded software sends some data to a server, and the server needs to know form which bench that data came.
By having fixed ip ranges per switch, i could determine it. An other option would be to know which port each system was connected to (based on MAC??)?
Comment: You're life will be easier and happier if you learn to use the switches management functions to show IP->MAC tables, and MAC->Port assignments.
Answer: Switches are L2 devices, as such they don't even know about IP (a L3 protocol), or do you mean a switch-router? Either way DHCP is a one-device-per-request protocol, have you thought about using DHCP device reservations to get what you need?
Comment: You mean reserve ip based on MAC? Yes, but that can't work. Since all devices are new (and therefor new MAC addresses).
Answer: As Chopper has pointed out, you couldn't do this as you are setup right now.  DHCP is a first come first server protocol and the switches couldn't inspect the traffic to filter it as you desire.  However, if you separate out the switches into different VLANS/ Subnets, you could utilize the single DHCP server with multiple scopes (one for each bench) and dhcp helper addresses setup in the switch.  For this, you would need some sort of routing between the VLANs, which could be something as simple as a Layer 3 switch with an IP on each VLAN interface.
You would then be able to determine which bench the traffic came from, based on it's IP/ subnet.

Assign IP range per switch?


Record and upload (to server) audio with HTML5/Flash

Question: I know that getUserMedia() wont be supported in a few browsers so I have to use more or less a flash based audio recorder. Its very important for me to upload the captured audio to a server via POST even if I could get access to the clientside captured audio would be pretty awesome. So do you guys know a libary/plugin/extension to do this?
I found some scripts as well like:
https://github.com/mattdiamond/Recorderjs
https://github.com/jwagener/recorder.js/
But the upload doesnt work. I dont know how I could continue.
Comment: Since you are using flash, why not program the flash app to upload it using Actionscript
Comment: Isnt worth, I need to do it clientside because I need to show a progressbar as well. Cant start do develop a complete flash app to finish this...
Comment: well flash is clientside, but ok, you said you used the two libs listed what errors did you get when trying to upload.
Comment: Wrong explanation on my side, yea flash is clientside, but I would prefer to make use of javascript/html5
Comment: im still getting an - uncaught exception: Error in Actionscript. Use a try/catch block to find error. Its kinda weird. It works at home, but not at the university
Answer: You can save the recorded data as a blob and then use a FileReader to upload the data via POST with AJAX.
Something similar along these lines:
<code>function uploadAudio(mp3Data){
    var reader = new FileReader();
    reader.onload = function(event){
        var fd = new FormData();
        var mp3Name = encodeURIComponent('audio_recording_' + new Date().getTime() + '.mp3');
        console.log("mp3name = " + mp3Name);
        fd.append('fname', mp3Name);
        fd.append('data', event.target.result);
        $.ajax({
            type: 'POST',
            url: 'upload.php',
            data: fd,
            processData: false,
            contentType: false
        }).done(function(data) {
            //console.log(data);
            log.innerHTML += "\n" + data;
        });
    };
    reader.readAsDataURL(mp3Data);
}
</code>
This code is taken directly from the gitHub project Recordmp3js available here:
https://github.com/nusofthq/Recordmp3js
It records audio and saves it MP3 format using just HTML5 and JS and then uploads the data on the webserver.
It only works on Chrome and Firefox though.


map to the sphere that preserves measure

Question: Let $A$ be any Borel set in $\mathcal{B}([0,10]\times[0,10])$. I want to have a map $\phi$ from $\mathbb{R}^2$ to the unit sphere $S^2\subset \mathbb{R}^3$ such that the spherical measure $\sigma(\phi(A))$ can be estimated from below and above by a constant times the Lebesgue measure |A| of $A$. The constant shall, of course, not depend on $A$. Is such a map known?
Answer: As $|A|$ is unbounded, the lower constant must be $0$, whatever the transformation (unless you allow non-injective mappings).

A lifting map
$$z=\sqrt{1-x^2-y^2}$$ will map a centered square of size $\dfrac1{\sqrt2}$ to a unit half-sphere with a coefficient between $1$ and twice the area of the projected patch.

In fact you can make the square as small as you want and map with a coefficient $\sim1$. IMO the question is incomplete.
Comment: Ok, you are right. I have edited the question. Now $A$ is bounded.
Answer: Letting $J_\phi$ denote the absolute value of the Jacobian determinant of $\phi\colon \mathbb R^2\to S^2$, the change of variable formula for integrals reads
$$
\int_{\phi(A)} \, d\sigma = \int_A J_\phi\, dx.$$
Thus, you are asking whether there is a map $\phi$ and a constant $C>0$ such that
$$
\frac{1}{C}\le J_\phi(x) \le C.$$
If you take the inverse of the stereographic projection, that is
$$
\phi(x, y)=\left( \frac{2x}{1+x^2+y^2},\frac{2y}{1+x^2+y^2}, \frac{1-x^2-y^2}{1+x^2+y^2}\right), $$
then the Jacobian is
$$
J_\phi(x, y)=\left(\frac{2}{1+x^2+y^2}\right)^2, $$
and if you restrict yourself to any bounded domain of $\mathbb R^2$ it is bounded both above and below.
Comment: How do you calculate $J_\phi$ here? I somehow cannot recover the correct result.
Comment: @user406143: Maybe it's me who's wrong then. I am going to post the computations.
Comment: I got it, everything seems to be correct. Thank you.
Comment: Great. I am glad it helped.
Comment: Do you know a nice reference for the version of the change of variable formula above? I've only found versions for diffeomorphisms from $\mathbb{R}^n $ to $\mathbb{R}^n$.
Comment: Me too, it is something that stumped me for a long time. The true setting in which to do these changes of variable is Riemannian geometry. The most comprehensive reference that I have found to date is the book of Burago-Burago-Ivanov, §5.5.1. Riemannian volume and Jacobians. Maybe too comprehensive. In the end, the only thing that is needed is the formula $dV=\sqrt{g}dx_1\ldots dx_n$.
Answer: Consider as $\varphi$ the inverse of the stereographic projection.
Answer: If you take the inverse of any equal-area planar map of a spherical Earth model with the map scaled and translated so that $[0,10]\times[0,10]$ is inside the map, the spherical measure $\sigma(\phi(A))$ will be exactly a fixed constant times $\lvert A\rvert$ for any $A$.
The constants for the upper and lower bound then are the same.
Numerous equal-area projections are known.
Comment: Very interesting answer.


Artificial harmonics extra sound

Question: I'll repeat what I've already said in the last few posts of mine: I am a complete beginner in the fingerstyle guitar technique, and have absolutely no experience or any skills in this field. I am just starting out.
Well, if you look at my last post you will notice that I am having some problems with the right hand position. So in the meanwhile I tried playing artificial harmonics. The problem is that, when I lift my index finger (which is touching the string on the required fret) after picking the string with my right middle finger, the index finger is unable to move without disturbing the sound.
More specifically, take an example. Suppose I play C4, i.e. hold second string first fret and place index on 13th fret, then while removing the index finger while the string is still vibrating (to keep the sound sustained for a little bit longer and prevent muting the sound), the index finger produces a C4 sound in addition to the sound of the artificial harmonic.
Could you please suggest some exercises/technical changes to counter this?
Comment: Maybe someone was just in a really bad mood. The close vote reason is not even playing the same gig, or the same town, or the same day as the question.
Comment: Why the dv and especially the close reason?
Answer: One can't tell without observing you, but one thing that beginners often don't realize about harmonics is just how light a touch is needed. We're used to depressing the string, but that's not necessary here. More touch can be needed (and tolerated) the thicker the string is (so, for instance, harmonics on bass can need more of the fleshy part of the finger), but especially for high strings, the slightest feather-weight is enough. I demonstrate to my violin students by having them bow an open string, and while they do, I simply touch a piece of paper to a node and it produces a harmonic.
Answer: Firstly, there's no need to remove the finger that's over the 13th fret (in this case). The string isn't moving at that point - it's a node. In fact, I show students that they can put a finger back on the string at the node, and it makes no difference at all to the sound.
It may be you have sticky fingers, or inadvertently pull the string slightly as you lift off. Try leaving it there, if that solves the problem, you know what to do!
Or - try playing with other digits. I tend to play (pluck) artificial harmonics with a finger - often the middle, and use thumb to touch the node point. That way, I can get a good deal of 'pull' on the string, so the harmonic can be sounded as loud as I want. Others will prefer the other way round, or even use two fingers - one to touch, another to pluck. But mine works well (for me at least), due to the extra leverage it can produce. And don't temporarily release the fretted note with the other hand at the same time, keep it solid on the fret.
Comment: +1 for thumb on the node. Your thumb is already better-placed to do that anyway, I've always thought. To get your finger on it you've to 'reach over'.
Comment: "Inadvertently pull the string" yes this is exactly what I wanted to communicate! +1 and I'll update and accept if it works.
Comment: Thank you so much! That thumb technique is A.W.E.S.O.M.E. .

Artificial harmonics extra sound


Sum of digits after the decimal point of the order of $10$ in $(\frac{\Bbb{Z}}{p\Bbb{Z}})^*$

Question: Let $p$ be a prime number and $a$ an integer such that $0<a<p.$
If I look at $(\frac{\Bbb{Z}}{p\Bbb{Z}})^*$, and the order of $10.$

I discover numerically that if the order of $10$ is even $2n$ then if we look at the list $(q_1,q_2,\cdots,q_{2n})$ the digits after the decimal point of $a/p$ then we have always $q(k)+q(k+N)=9$ for $k=1,\cdots,n.$

Can anyone enlighten me on how to prove this ?
Comment: If you set $Q = \sum_{k = 1}^{2n} q_k\cdot 10^{2n-k}$, then you have $$\frac{1}{p} = \sum_{m = 1}^\infty \frac{Q}{10^{2nm}} = \frac{Q}{10^{2n}-1}.$$ Now look at $(10^n+1)\cdot \dfrac{1}{p}$.
Comment: Yes and no. Take the expansion of $\frac{1}{p}$, shift it by $n$ places, and add (you don't need to actually do that, just think about what happens, and how it relates to your observation). Then you need to note that $\dfrac{10^n + 1}{p}$ is an integer. And what do you know about decimal expansions of integers?
Comment: No, I mean integers. Either you have nothing at all after the decimal point, or … what?
Answer: If the order of $10$ modulo $p$ is $r$, then we have
$$\frac{1}{p} = \frac{Q}{10^{r}-1} = \sum_{m = 1}^\infty \frac{Q}{(10^{r})^m},$$
where
$$Q = \sum_{k = 1}^r q_k \cdot 10^{r-k}.$$
If $r$ is even, $r = 2n$, we can write $Q = 10^n\cdot a + b$, where $0 \leqslant a,b < 10^n$, and then
$$\frac{1}{p} = \sum_{m = 1}^\infty \frac{c_m}{(10^n)^m}$$
with $c_m = a$ if $m$ is odd, and $c_m = b$ if $m$ is even. Thus we find
$$10^n\cdot \frac{1}{p} = a + \sum_{m = 1}^\infty \frac{c_{m+1}}{(10^n)^m}$$
and therefore
$$\frac{10^n+1}{p} = a + \sum_{m = 1}^\infty \frac{c_m + c_{m+1}}{(10^n)^m} = a + \sum_{m = 1}^\infty \frac{a+b}{(10^n)^m}.$$
Since $p$ divides $10^{2n} - 1 = (10^n-1)(10^n+1)$ but not $10^n - 1$ (the order of $10$ modulo $p$ is $2n$), it follows that $p$ divides $10^n+1$. It follows that
$$g := \sum_{m = 1}^\infty \frac{a+b}{(10^n)^m} = \frac{a+b}{10^n - 1}$$
is an integer. Since $0 \leqslant a+b \leqslant  2\cdot (10^n-1)$, $g \in \{0,1,2\}$. $g = 0$ would imply $a = b = 0$, hence $Q = 0$ and so $\frac{1}{p} = 0$, which is absurd. $g = 2$ would imply $a = b = 10^n - 1$, hence $Q = 10^{2n}-1$, and thus $\frac{1}{p} = 1$, which is also absurd. It follows that $g = 1$, i.e. $a + b = 10^n - 1$. This is just the assertion $q_k + q_{n+k} = 9$ for $1 \leqslant k \leqslant n$.


Weird error C2131 with constexpr declared variable

Question: I'm trying to compile the following snippet with VS2017 but it is throwing an error C2131: expression did not evaluate to a constant without any further detail in the output log.
class Example
{
public:
    constexpr Example() : m_int()
    {
        for (int i = 0; i < 256; ++i)
        {
            for (int j = 0; j < 256; ++j)
            {
                m_int[i] = i;
            }
        }
    }

private:
    int m_int[256];
};

int main()
{
    constexpr Example vv; // <-- error C2131 here
    return 0;
}

However for some reason unknown to me, if I stop the j counter at < 255 (instead of 256), the code compile fine.
What's the explanation behind this and how can I fix it?
Comment: Don't see anything obviously wrong, so this looks like a compiler bug. gcc compiles the above without any issues.
Comment: Compiles fine with [MSVC](https://gcc.godbolt.org/z/6DdSmD)
Comment: I have just found the solution, I'll post the answer right away, thanks!
Comment: What does the inner loop even do?  It's just assigning to the same element over and over again.
Answer: Further searching landed me on the following link and after some trial and error with the parameters values I found the solution.
Adding /constexpr:steps10000000 to the project additional options in C++ compiler settings has fixed the error and now it compiles fine. I wish VS2017 would throw the error C4593 in this case instead of C2131 as it would have saved me a headache!


Melhor forma de garantir isolamento de consulta

Question: Tenho o seguinte cenário:
Uma tabela no SQL Server que contém registros de processos que podem ser executados em vários serviços (Windows Services em C#) de vários servidores. Algo como:
CREATE TABLE Processo
(
    Id          INT IDENTITY NOT NULL,
    Status      VARCHAR(100)
)

GO

INSERT INTO Processo VALUES
  ('Aguardando processamento'), ('Aguardando processamento'), ('Aguardando processamento')

SELECT  *
FROM    Processo

/*
| Id  | Status                   |
| 1   | Aguardando processamento |
| 2   | Aguardando processamento |
| 3   | Aguardando processamento |
*/

Os serviços consultam esta tabela simultaneamente buscando um processo com status "Aguardando processamento". Assim que um destes serviços encontra o processo, o status é atualizado para "Processando" em um método mais ou menos assim:
using (SqlConnection conn = new SqlConnection("string de conexão"))
{
    conn.Open();

    using (SqlCommand command = conn.CreateCommand())
    {
        command.CommandType = System.Data.CommandType.Text;
        command.CommandText = "SELECT Top 1 Id FROM Processo WHERE STATUS = 'Aguardando processamento'";
        int processo = (int)command.ExecuteScalar();

        command.CommandText = "UPDATE Processo SET STATUS = 'Processando' WHERE Id = @Id";
        command.Parameters.Add(new SqlParameter("Id", processo));
        command.ExecuteNonQuery();
    }
}

O problema acontece quando no meio tempo entre a consulta e a alteração do status para "Processando" em um serviço "A", um serviço "B" encontra o mesmo registro e também começa a processar.

Eu preciso garantir que quando um serviço encontre um processo, nenhum outro possa encontrar ou alterar este mesmo registro.

Qual é a melhor maneira de garantir isso?
EDIT: O objetivo da minha pergunta é resolver o problema considerando aplicações .NET em múltiplos servidores, o sugerido como "possível duplicada" (291665) não abrange a tecnologia utilizada e as respostas não se aplicam ao meu caso.
Comment: Possível duplicata de [Consulta e alteração simultânea](https://pt.stackoverflow.com/questions/291665/consulta-e-altera%c3%a7%c3%a3o-simult%c3%a2nea)
Comment: @ramaral Na verdade minha pergunta é mais específica e acho que a mencionada não tem respostas muito práticas para este caso. Editei para deixar claro isso.
Answer: Você pode executar ambos os comandos dentro de uma transação usando SqlTransaction:
using (SqlTransaction trans = conn.BeginTransaction())
{
    using (SqlCommand command = conn.CreateCommand())
    {
        command.CommandType = System.Data.CommandType.Text;
        command.CommandText = "SELECT Top 1 Id FROM Processo WHERE STATUS = 'Aguardando processamento'";
        int processo = (int)command.ExecuteScalar();

        command.CommandText = "UPDATE Processo SET STATUS = 'Processando' WHERE Id = @Id";
        command.Parameters.Add(new SqlParameter("Id", processo));
        command.ExecuteNonQuery();
    }
    trans.Commit();
}

Referência do MSDN: SqlTransaction
Comment: uma vez que o código rode em vários computadores, seria bom colocar o nível de isolamento da transação como `Serializable`, o banco irá se encarregar de tratar as concorrencias
Comment: @RovannLinhalis sim é uma boa ideia, uma vez que o padrão é *ReadCommited*.  Para quem quiser se aprofundar mais, aqui o link da documentação: https://msdn.microsoft.com/pt-br/library/system.data.isolationlevel(v=vs.100).aspx
Comment: Obrigado @RicardoPontual, usei sua resposta com o `conn.BeginTransaction(IsolationLevel.Serializable)` para garantir o isolamento e funcionou.
Comment: @RicardoPontual Obrigado. Neste caso é melhor abrir a transação e isolar tanto o select como o update (como foi feito), ou apenas no select já garantiria o isolamento ?
Comment: Você seta o *IsolationLevel* para toda a transação, então vai valer para o select e o update


File's line numbering with sed

Question: I would like to know if sed is capable of doing some line counting work while numbering specific lines, suppose I have the file
  Some question
         some answer
         another answer
  Another question
         another answer
         other answer

I want a command that transforms that into: Desired Output
  1_ Some question
         a_ some answer
         b_ another answer
  2_ Another question
         a_ another answer
         b_ other answer

Is that possible with sed? If not, how can that be done without bash scripting a solution?
Comment: Can you be clearer about what your definition of "bash scripting" is and isn't?
Comment: a program made in bash that uses control structures like while, for, etc
Comment: What are you trying to achieve? What do you _need_ this for? I smell the [XY-problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) here
Comment: I'm needing this to properly format some hand-typed exam questions I copied today while learning about this topic in the process
Answer: It's better to try with awk. I assume that you want to number lines that don't begin with any withespace character:
awk '$0 !~ /^[[:blank:]]/ { print ++i "_", $0; next } { print }' infile

It yields:
1_ Some question
         some answer
         another answer
2_ Another question
         another answer
         other answer

Comment: @NicoRodsevich: It's because `sed` can't use variables. Where do you keep the next number that you have to print? Difficult.
Comment: Would u mind saying why would it be better trying with awk rathen than sed?
Answer: Perl has a handy feature that ++ works on characters:
perl -lpe '
    /^\S/ and do {$inner_counter="a"; s/^/ ++${outer_counter} . "_ "/e};
    /^\s/ and s/^\s+/$& . ${inner_counter}++ . "_ "/e
' file

1_ Some question

     a_ some answer

     b_ another answer

2_ Another question

     a_ another answer

     b_ other answer

File's line numbering with sed


Asymptotic behaviour of real sequences

Question: Let's say we have two real sequences $(a_n)_{n\in\mathbb{N}}$ and $(c_n)_{n\in\mathbb{N}}$ with $c_n\in o(\frac1n)$ (i.e. $c_n(\frac1n)^{-1}\xrightarrow{n\rightarrow\infty}0$). And for all $\epsilon>0$ holds that
$$\frac{1-\epsilon}n-\frac1\epsilon |c_n|\leq a_n\leq \frac{1+\epsilon}n+\frac1\epsilon |c_n|.$$Is it true that $a_n\sim \frac1n$ i.e. $a_n(\frac1n)^{-1}\xrightarrow{n\rightarrow\infty}1$? I think it should hold but I'm really confused by the $\epsilon$'s because I can't just consider the limit for $\epsilon\rightarrow0$.
Thanks and I'm sorry if it's a really stupid question!
Answer: Fix $\epsilon\gt0$. Then $n|c_n|\to0$ and, for every $n$,
$$
1-\epsilon-\epsilon^{-1}n|c_n|\leqslant na_n\leqslant1+\epsilon+\epsilon^{-1}n|c_n|,
$$
hence
$$
1-\epsilon\leqslant\liminf_{n\to\infty}\,na_n\leqslant\limsup_{n\to\infty}\,na_n\leqslant1+\epsilon.
$$
This holds for every $\epsilon\gt0$ hence
$$
1=\liminf_{n\to\infty}\,na_n\leqslant\limsup_{n\to\infty}\,na_n=1,
$$
which implies
$$
\liminf_{n\to\infty}\,na_n=\limsup_{n\to\infty}\,na_n=1,
$$
that is
$$
\lim_{n\to\infty}na_n=1.
$$

Asymptotic behaviour of real sequences


IntelliJ & JavaFX - How to resolve java.lang.IllegalArgumentException: Invalid URL or resource not found?

Question: I've been searching for quite a while on why I kept getting this error even though the path to my image was set correctly.
In IntelliJ, right click on your "resources" folder and press "Mark directory as" > "Resources root"
Then, when referring to your image, you can use this code:
<code>Image myImage = new Image("myImage.jpg");
</code>
As you can see, this appeared to be set up correctly, but somehow that still gave me this error.
Edit: This is not a question on how to get the correct file path, as the file path is correct. It's more a question (& answer) on how to resolve this build error. Therefore the duplicate is invalid in my opinion.
Comment: Also see the [eden resource guide](https://edencoding.com/where-to-put-resource-files-in-javafx/) referenced in the answer to the duplicate.
Comment: "I kept getting this error even though the path to my image was set correctly" -> The path you are using is incorrect, otherwise you will not see the message "Invalid URL or resource not found".  Follow the troubleshooting steps in the duplicate answer.
Comment: I advise using a build tool.  You are using Idea, so [create a new JavaFX project](https://www.jetbrains.com/help/idea/javafx.html), and place the image in the resource directory (the new project will have this setup automatically, you don't need to manually configure it), following one of the suggested location patterns from the eden guide and perform the location lookup according to the guide.
Comment: @jewelsea How come I could just rebuild the project and that fixed it then? If the path is incorrect, rebuilding shouldn't help, right?
Comment: "How come I could just rebuild the project and that fixed it then? If the path is incorrect, rebuilding shouldn't help, right?" -> I don't know.   If it was already built, then rebuilding without a configuration change shouldn't make a difference as you say.  It is possible that Idea indices got corrupted somehow, so forcing a rebuild fixed the issue, but other than that I couldn't say.
Answer: It looks like the image somehow wasn't added to the build, so even though it was in the project's code, it wasn't in the build, thus it couldn't be referred to.
These steps resolved the issue:

Remove the "out" folder
Rebuild the project by clicking the greene hammer on the top right of the screen
Try to re-run the project, and it should work! :)


In homomorphic image of Jacobson ring Nilradical is equal to the Jacobson radical.

Question: I want to show in homomorphic image of Jacobson ring Nilradical is equal to the Jacobson radical. By Jacobson ring we know that every prime ideal is intersection of maximal ideals.
Where I stuck is the following. Given  $f:A \to B$ surjective ring homomorphism and $A$ be a Jacobson ring. Consider $y \in Jac(B)$ then want to show that for any  prime ideal $p$ of $B,$ $y \in p.$ Now if $f^{-1}(y) \cap f^{-1}(p)= \phi $   I cannot draw any contradiction. Please help me to  prove this way.
Answer: Hint: We know that $B\cong A/I$ for some ideal $I\subset A$. Thus, what you want to show is that $\operatorname{nil}(A/I)=\mathcal{J}(A/I)$. Use the correspondence between prime ideals of $A$ and those of $A/I$.
Comment: Enough to show $rad(I)= \cap m_{\alpha}$ where $m_{\alpha}$ the collection of all maximal ideals of $A$ containing $I.$ But since every prime ideal is intersection of maximal ideals $A$ and $rad(I)$ is the intersection of all prime ideals containing $p$..it follows. Am I correct ?
Comment: @user371231 Yes, try to write down all the details! (There is a typo in what you wrote. It should say $I$ instead of $p$)
Comment: yes $rad(I)$ is intersection of all prime ideals containing $I.$


Viewbag para todas as controllers Asp.Net MVC C#

Question: Tenho um aplicação em ASP.Net MVC, depois que o usuário faz o login preciso mostrar seu nome no topo da pagina sempre, independente de qual pagina ele está.
Essa aplicação é um administrativo onde ficará o nome da empresa na parte de cima, eu vi algumas soluções para o meu problema mas não consigo decidir qual seria  melhor, por ter pouco conhecimento.

Construir um controller base com a pesquisa do nome da empresa e retornando ela para uma viewbag.
Não me lembro bem pois não encontrei a pergunta novamente, mas era para usar o padrão [discriminação] nos controllers (caso alguém consiga me explicar como se faz).

Agora uma dúvida que tenho sobre viewbag, caso eu use a primeira opção e crie um controller que retorna para essa viewbag, como vou usá-las nas páginas? No caso preciso apenas usar na Shared\_Layout, certo ? Alguém conseguiria me da um exemplo?
Eu tenho pouca noção sobre essa parte o que esta dificultando meu aprendizado, gostaria de uma resposta um pouco mais didática sobre o funcionamento até mesmo das viewbag, eu encontrei outras respostas sobre esse assunto mas não consegui compreendê-las por completo.
Comment: Está usando o que para autenticação, Identity?
Comment: Não fiz a parte do login, mas acabei de fazer um pergunta sobre o login e pelo que vi não e identity, porque ele usa um arquivo para redirecionamento chamado 'Starup.Auth.cs'  e não possui este arquivo no projeto, eu fiz o redirecionamento no 'web.config' usando o ''  não sei se ajuda .
Comment: Você utilizará este valor para alguma operação ou apenas para mostrar na tela?
Comment: Apenos mostro ela na tela
Answer: Uma forma de solucionar o seu problema utilizando as viewbags seria usando partial view, então você poderia colocar uma controller customizada definindo a viewbag e apenas dar um @Html.RenderAction na página de layout compartilhada do seu sistema. Dessa forma teriamos:
html
No exemplo vamos utilizar como _Nome.cshtml ela pode estar na mesma pasta do _Layout.cshtml

    @Viewbag.nome

controller
No exemplo vamos colocar como ActionController.cs
public PartialViewResult Action(){
    Viewbag.nome = "nome";
    return PartialView("~/views/Shared/_Nome.cshtml");

}

_layout
@Html.RenderAction("Action", "Action");

Agora existem diversas outra soluções sem utilizar viewbag.
Comment: Então eu estava querendo saber qual seria a forma mais indicada para o meu caso, por exemplo, o meu menu já _Partial , mas eu chamo ele como layout , e é nesse pagina que ficaria a informação que preciso compartilhar. Pode ser com ou sem viewbag, se for com gostaria de saber um pouco mias sobre a forma de aplicar .  Se possivel e claro , mas muito obrigado por sua resposta, vou tentar aqui
Comment: Você poderia dar uma explicação um pouco mais detalhada dessa controller customizada? eu tenho que criar essa controler e so atribuir a viewbag com o valor que eu preciso ?
Comment: Eu vou criar uma controller e uma view para essa controller , irei atribuir o valor da viewbag na controller e adicionar na minha  _Layout, @Partial_Html(NovaView) certo ?  estou um pouco de dificuldades de entender essa logica, depois que ue usar essa partial na minha layout eu ja consigo usar a viewbag ?
Comment: Só um segundo, vou tentar melhorar minha explicação
Comment: Pronto, tentei esclarecer o código e como fazer. Mudei a função de render para ver se facilitava também, qualquer duvida Tamo aí
Comment: Não consegui impleta da forma que você me disse , eu creiei um controle apenas com a Consulta e atribui o valor que eu precisava a Viewbag.Nome  e retornei a view que eu criei , segui o exemplo e puz o nome e  na layout chame essa _nome ,com o @Html.Patial ( o renderAction não funcionou) , mas nada de funcionar


Drupal reuses its hash salt

Question: The instructions in default.settings.php say

This variable will be set to a random value by the installer. All one-time
   login links will be invalidated if the value is changed. Note that if your
   site is deployed on a cluster of web servers, you must ensure that this
   variable has the same value on each server. If this variable is empty, a hash
   of the serialized database credentials will be used as a fallback salt.

but this explanation of salting says

A new random salt must be generated each time a user creates an account or changes their password.

and goes on to clarify that each salted hash (eg password) should have its unique salt stored along with the hashed+salted password in the database.
Am I misunderstanding the article I read on salting, or is Drupal using a faulty practice for the sake of convenience, or is the article wrong, or is there something else going on?
Comment: Good question...re-using the salt would be required as I understand it...otherwise the resulting password hash would never be the same for the same password...for one-time login this might not matter...I would think if Drupal stored password salt for each account individually then the end result would be more secure...a quick google seems to confirm my suspicion that the authentication layer is pluggable and would allow a custom module to do just that. If you find anything more concrete on this subject please share :)
Answer: I have migrated other CMS's to Drupal and had experience moving user accounts.  Drupal's password algorithm is extremely good.
The salt you are referring to in the settings.php is not used for passwords. The drupal_hash_salt salt is used for generation of things like cookies.  Hence why it says you must keep it the same across all web servers if you are in a load balanced setup.
Generation of passwords uses the SHA512 algorithm with randomly generated salts using openssl php libraries (not mt_rand or other weak random number generators).
If you want to learn more about password generation you can start here reading the API documentation for Drupal
You see that in the function to generate it calls a "private" function to generate a new password salt (<code>_password_generate_salt()</code>). Which in turn calls a lot of other private, custom Drupal functions (it is a long rabit hole).
So in general the password scheme used for Drupal is extremely deep and nested, it does not use PHP functions considered to be "weak".
Comment: This answer matches my understanding. Drupal 7 and up use a password hashing mechanism based on http://www.openwall.com/phpass/ and there is the phpass contrib backported to 6.x for anyone on 6.x
Comment: Ah, I was misunderstanding what the salt in the settings.php file was actually being used for. Thanks!

Drupal reuses its hash salt


Calculating the parameters of a Beta-Binomial distribution using the mean and variance

Question: I'm trying to do the same thing that was done in this question:
Calculating the parameters of a Beta distribution using the mean and variance
for the Beta-Binomial distribution for which the mean is
$\mu = n\frac{\alpha}{\alpha+\beta}$
and the variance is
$\sigma^2 = n\frac{\alpha\beta(\alpha+\beta+n)}{(\alpha+\beta)^2(\alpha+\beta+1)}$
How can I calculate $\alpha$ and $\beta$ in terms of $\mu$ and $\sigma^2$ for a given $n$?
Also some information regarding the bound of the mean and variance similar to the answer above would be appreciated, e.g. I know that  $\mu \in (0,n)$.
Comment: $n$ is needed. Otherwise no solution.
Comment: Assume that n is given. I adjusted my question accordingly.
Answer: $$\alpha = (n\mu-\sigma^2 -\mu^2)/T$$
$$\beta = (n-\mu)\left(n-\frac {\sigma^2 +\mu^2}{\mu}\right)/T$$
where $$T=\frac {n\sigma^2}{\mu} - n +\mu$$
$$0 \lt \mu \lt n$$
$$0 \lt \sigma^2 \lt n^2/4$$
$$\sigma^2 = n\frac{\alpha\beta(\alpha+\beta+n)}{(\alpha+\beta)^2(\alpha+\beta+1)} = n\frac{\alpha}{\alpha+\beta}\frac{\beta}{\alpha+\beta}\left (1+\frac {(n-1)}{(\alpha+\beta+1)}\right)$$
$max(\frac{\alpha}{\alpha+\beta}\frac{\beta}{\alpha+\beta}) = 1/4 $ when $\alpha = \beta$.
$max\left (1+\frac {(n-1)}{(\alpha+\beta+1)}\right) = n$ when $\alpha+\beta$ goes to zero.
$\alpha = \beta$ and $\alpha+\beta$ goes to zero can be true simultaneously, so got the results.
Comment: Thank you for the quick reply. Out of curiosity, is this information available in literature or did you derive it yourself? If the latter, how did you get the upper variance bound?
Comment: When I re-derived upper bound, I found a mistake. I corrected it and wrote the steps in Answer.


Rcpp - generate multiple random observations from custom distribution

Question: This question is related to a previous one on calling functions within functions in Rcpp.
I need to generate a large number of random draws from a custom distribution, in a way similar to rnorm() or rbinom(), with the additional complication that my function produces a vector output.
As a solution, I thought about defining a function that generates observations from the custom distribution, and then a main function that draws n times from the generating function via a for loop. Here below is a much simplified working version of the code:
#include <Rcpp.h>
using namespace Rcpp;

// generating function
NumericVector gen(NumericVector A, NumericVector B){
  NumericVector out = no_init_vector(2);
  out[0] = R::runif(A[0],A[1]) + R::runif(B[0],B[1]);
  out[1] = R::runif(A[0],A[1]) - R::runif(B[0],B[1]);
  return out;
}

// [[Rcpp::export]]
// draw n observations
NumericVector rdraw(int n, NumericVector A, NumericVector B){
  NumericMatrix out = no_init_matrix(n, 2);
  for (int i = 0; i < n; ++i) {
    out(i,_) = gen(A, B);
  }
  return out;
}

I am looking for ways to speed up the draws. My questions are: is there any more efficient alternative to the for loop? Would parallelization help in this case?
Thank you for any help!
Comment: @SymbolixAU I think it doesn"t matter because a matrix is a vector. But it is nice to be explicit.
Comment: should `NumericVector rdraw` be `NumericMatrix rdraw`?
Comment: @Jinglestar Not sure you can speed up the draws (maybe with RcppArmadillo?). However, you could allocate less memory if directly assigning in `gen`. Why are you not doing this in R directly?
Comment: @F.Privé thank you for your comments! Probably due to inexperience I am not following you: what do you mean by "assigning in" the function?
Comment: @Jinglestar In `gen`, you're creating a new vector each time, you fill it and then use this vector to fill your matrix. You could fill your matrix directly.
Answer: There are different ways to speed this up:

Use inline on gen(), reducing the number of function calls.
Use Rcpp::runif instead of a loop with R::runif to remove even more function calls.
Use a faster RNG that allows for parallel execution.

Here points 1. and 2.:
#include <Rcpp.h>
using namespace Rcpp;

// generating function
inline NumericVector gen(NumericVector A, NumericVector B){
  NumericVector out = no_init_vector(2);
  out[0] = R::runif(A[0],A[1]) + R::runif(B[0],B[1]);
  out[1] = R::runif(A[0],A[1]) - R::runif(B[0],B[1]);
  return out;
}

// [[Rcpp::export]]
// draw n observations
NumericVector rdraw(int n, NumericVector A, NumericVector B){
  NumericMatrix out = no_init_matrix(n, 2);
  for (int i = 0; i < n; ++i) {
    out(i,_) = gen(A, B);
  }
  return out;
}

// [[Rcpp::export]]
// draw n observations
NumericVector rdraw2(int n, NumericVector A, NumericVector B){
  NumericMatrix out = no_init_matrix(n, 2);
  out(_, 0) = Rcpp::runif(n, A[0],A[1]) + Rcpp::runif(n, B[0],B[1]);
  out(_, 1) = Rcpp::runif(n, A[0],A[1]) - Rcpp::runif(n, B[0],B[1]);
  return out;
}

/*** R
set.seed(42)
system.time(rdraw(1e7, c(0,2), c(1,3)))
system.time(rdraw2(1e7, c(0,2), c(1,3)))
*/

Result:
> set.seed(42)

> system.time(rdraw(1e7, c(0,2), c(1,3)))
   user  system elapsed
  1.576   0.034   1.610

> system.time(rdraw2(1e7, c(0,2), c(1,3)))
   user  system elapsed
  0.458   0.139   0.598

For comparison, your original code took about 1.8s for 10^7 draws. For point 3. I am adapting code from the parallel vignette of my dqrng package:
#include <Rcpp.h>
// [[Rcpp::depends(dqrng)]]
#include <xoshiro.h>
#include <dqrng_distribution.h>
// [[Rcpp::plugins(openmp)]]
#include <omp.h>
// [[Rcpp::depends(RcppParallel)]]
#include <RcppParallel.h>
// [[Rcpp::plugins(cpp11)]]
// [[Rcpp::export]]
Rcpp::NumericMatrix rdraw3(int n, Rcpp::NumericVector A, Rcpp::NumericVector B, int seed, int ncores) {
  dqrng::uniform_distribution distA(A(0), A(1));
  dqrng::uniform_distribution distB(B(0), B(1));
  dqrng::xoshiro256plus rng(seed);
  Rcpp::NumericMatrix res = Rcpp::no_init_matrix(n, 2);
  RcppParallel::RMatrix<double> output(res);

  #pragma omp parallel num_threads(ncores)
  {
  dqrng::xoshiro256plus lrng(rng);      // make thread local copy of rng
  lrng.jump(omp_get_thread_num() + 1);  // advance rng by 1 ... ncores jumps
  auto genA = std::bind(distA, std::ref(lrng));
  auto genB = std::bind(distB, std::ref(lrng));

  #pragma omp for
  for (int i = 0; i < n; ++i) {
    output(i, 0) = genA() + genB();
    output(i, 1) = genA() - genB();
  }
  }
  return res;
}

/*** R
system.time(rdraw3(1e7, c(0,2), c(1,3), 42, 2))
*/

Result:
> system.time(rdraw3(1e7, c(0,2), c(1,3), 42, 2))
   user  system elapsed
  0.276   0.025   0.151

So with a faster RNG and moderate parallelism, we can gain an order of magnitude in execution time. The results will be different, of course, but summary statistics should be the same.
Comment: Great! Thank you for your explanation! Unfortunately this example is much simpler than the real code: my generating function cannot be vectorised, so point 2 cannot be applied. Do you think there's any faster alternative to the for loop in this case?
Comment: @Jinglestar Why do you think the `for` loop might be problematic? It does make sense to use a fast RNG and as little memory allocation as possible, c.f. point 3, which can also be used without parallelization in case that looks to scary.


Formal Construction of Polynomial Ring in Several Variables

Question: The formal construction of the polynomial ring in one variable is briefly the following:
We take a ring $(R,+,\cdot)$ with $1_R$.
We define $R^{ \mathbb{N}}$ be the set of all the sequences $(a_0,a_1,a_2,a_3,...)$, $a_i \in R^{ \mathbb{N}},\forall i\in \mathbb{N}$ and we define the following operations:
$$+:  R^{ \mathbb{N}} \times  R^{ \mathbb{N}} \longrightarrow  R^{ \mathbb{N}},\  ((a_0,a_1,a_2,...),(b_0,b_1,b_2,...))\mapsto (a_0,a_1,a_2,...)+(b_0,b_1,b_2,...):= (a_0+b_0,a_1+b_1,a_2+b_2,...)$$ and $$\cdot:  R^{ \mathbb{N}} \times  R^{ \mathbb{N}} \longrightarrow  R^{ \mathbb{N}},\ ((a_0,a_1,a_2,...),(b_0,b_1,b_2,...))\mapsto (a_0,a_1,a_2,...) \cdot (b_0,b_1,b_2,...):=(c_0,c_1,c_2,...)$$
with $c_n=a_0b_n+a_1b_{n-1}+...+a_{n-1}b_1+a_nb_0,\forall n\in \mathbb{N}=\{0,1,...\}$.
Furthermore we define the equality $(a_0,a_1,a_2,...)=(b_0,b_1,b_2,...) \iff a_i=b_i, \forall i\in \mathbb{N}$. With these two binary operations we have that $(R^{ \mathbb{N}},+\cdot )$ is a ring with $1_{R^{ \mathbb{N}}}=(1_R,0_R,0_R,...)$. Now, polynomial is every element of the last ring of the form $(a_0,a_1,a_2,...,a_n,0_R,0_R,...)$. If $R[X]$ is the set of all the polynomials then $R[X]$ is a subring of $R^{ \mathbb{N}}$ and the mapping $f:R\longrightarrow R[X]$, $a\mapsto (a,0_R,0_R,...) $ is a monomorphism. So, we can say that $R$ is a subring of $R[X]$, and after this we have all the usual theorems.
My question is:
How we can do exactly the same construction in the polynomial ring in several variables with the same procedure?
PS 1: I apologize for my English. If you don't understand something ask me please.
PS 2: I know that a similar question already exists, but I think I have a different procedure.
Thank you in advance.
Comment: Special case of a  [monoid ring,](https://en.wikipedia.org/wiki/Monoid_ring)  viz. $R[\Bbb N^{\large k}]\ \ $
Comment: Sources that do it "right": **1)** Serge Lang, *Algebra*, Revised Third Edition, 2002 ( http://link.springer.com/book/10.1007/978-1-4613-0041-0 ), Chapter II, §3. **2)** Thomas W. Hungerford, *Algebra*, 12th printing, 2003 ( http://link.springer.com/book/10.1007/978-1-4612-6101-8 ), Chapter III, §5. **3)** Herbert Amann, Joachim Escher, *Analysis I*, 2005 ( http://www.springer.com/us/book/9783764377557 ), §8. The idea is either to use monoid rings as @BillDubuque suggested, or to follow the univariate construction but replace ...
Comment: Typically, when considering the formal construction, I think one defines polynomial rings in several variables via induction, i.e. $R[X_{1}, \ldots, X_{n}] := (R[X_{1}, \ldots, X_{n-1}])[X_{n}]$. I suppose you could define them using sequences as above. For two variables, e.g., you could have $a_{0}$ be the degree $0$ monomial terms, $a_{1}, a_{2}$ be the degree $1$ monomial terms, $a_{3}, a_{4}, a_{5}$ be the degree $2$ monomial terms, etc. I think it should be possible, but very annoying, to write down the associated convolutions (multiplications) then; I wouldn't bother with this though. :)
Comment: ... sequences by "multisequences", i.e., maps from $\mathbb{N}^n$ to $R$. The recursive approach mentioned by @AlexWertheim has several drawbacks -- it fails generalizing to infinitely many variables or even to finitely many variables without a canonical ordering.
Comment: Thank you for you answers.
Could anybody write me down the complete proof?
Answer: First, there is a little mistake in your definition : a polynomial has only finitely many non-zero coefficients. Instead of $R^\mathbb{N}$, you should hence consider
$S :=\{(a_0,\dots) \in R^\mathbb{N} \big| \exists d \in \mathbb{N}, \, \forall e>d,\, a_e=0\}$
To do the same construction for n variables, you just need to change the index set :
define $S_n :=\{(a_t) \in R^{\mathbb{N}^n} \big| \exists d \in \mathbb{N}^n, \, \forall t,\,sum(t)>sum(d) \Rightarrow a_t=0\}$, where $sum((t_1,\dots,t_n))$ denotes
$t_1 + \dots + t_n$.
the idea : for $t = (t_1, \dots, t_n) \in \mathbb{N}^n$, $a_t$ is the coefficient of the monomial $X_1^{t_1}\dots X_n^{t_n}$.
Addition is defined componentwise : $(a_t) + (b_t) = (a_t + b_t)$
Multiplication is somewhat trickier : $(a_t) \cdot (b_t) := (c_t)$, where for each $t \in \mathbb{N}^n$,
$$c_t := \sum_{u, v\in \mathbb{N}^n, \, u+v=t} a_u \cdot b_{v}$$
where $u + v = (u_1 + v_1, \dots, u_n + v_n)$.
Comment: Thank you for your answer!
Answer: Perhaps there is a way to do this as the "free-est" possible associative, unital $R$-algebra with unit (thus the algebra structures are defined by just morphisms of rings with unity from $R$ to the algebras) such that the set of variables commutes with the "copy" of $R$ and each other. That would define it even for an infinite set of variables $T$.
We could start with formal products in the set of variables, such that all but a finite number of exponents are $0$, where if all the exponents are $0$ we'll identify that with $1_{R[T]}$ then define the product of such unit coefficient monomials, then define formal multiplication with elements of $R$ to obtain the set of monomials and constants from $R$; then formal sums in the previous set such that all but a finite number of terms has $0_R$ as coefficient, where multiplication is extended linearly. Etc...


Collect all elements of binary tree that are power of 2

Question: I can't get the following to work. This is what I got so far:
stepen(2).
stepen(X):-
   X mod 2=:=0,
   X1 is X/2,
   stepen(X1).//stepen means power(in Serbian).

spoji([],Y,Y).
spoji([X|Xs],Y,[X|Z]):-spoji(Xs,Y,Z).//spoji means append lists

vadi(nil,[]).
vadi(t(X,L,R),[X|Xs]) :-
   stepen(X),
   vadi(L,SL),
   vadi(R,SR),
   spoji(SL,SR,Xs).//list of nodes that are power of 2.

Answer: (So far nobody commented your code. So I will try)
stepen/1 loops
I assume you refer here to the non-negative powers of two. That is, 2^(-1) and the like are not considered.
First of all, your stepen/1 definition produces an error in ISO conforming systems like gnu-prolog or sicstus-prolog.
| ?- stepen(6).
! Type error in argument 2 of (is)/2
! expected an integer, but found 3.0
! goal:  _193 is 3.0 mod 2

This is due to X1 is X/2 which always produces a float or an error, but never an integer. You may replace this by X1 is X div 2 or equivalently X1 is X >> 1.
Will this program now always terminate? After all X div 2 will approach zero. From the negative side, it will end at -1 which then will fail. But from the positive side, it will stay at 0!
Here is the looping program (failure-slice) reduced to its minimum:

?- stepen(0).

stepen(2) :- false.
stepen(X):-
   X mod 2=:=0,
   X1 is X div 2,
   stepen(X1), false. % stepen means power(in Serbian).

As Nicholas Carey has suggested, you can simplify this predicate to:
stepen(X) :-
   X > 0,
   X /\ (X-1) =:= 0.

vadi/2 logic
In your definition, this predicate is true, if all nodes of the trees are powers of two. I assume you wanted to "filter out" the powers. The easiest way to do this is by using DCGs instead of spojii/3 vl. append/3. Let's first consider a simpler case, just the nodes of a tree:
nodes(nil) --> [].
nodes(t(X, L, R)) -->
   [X],
   nodes(L),
   nodes(R).

?- T = t(1,nil,t(2,t(3,nil,t(4,nil,nil)),t(5,nil,nil))), phrase(nodes(T),L).
  T = t(1,nil,t(2,t(3,nil,t(4,nil,nil)),t(5,nil,nil))), L = [1,2,3,4,5].

Now, you no longer want all elements, but only certain, I will use a separate nonterminal for that:
st(E) --> {stepen(E)}, [E].
st(E) --> {\+stepen(E)}.  % nothing!

Or more compactly:
st(E) --> {stepen(E)} -> [E] ; [].

Now, the final non-terminal is:
stepeni(nil) --> [].
stepeni(t(X,L,R)) -->
   st(X),
   stepeni(L),
   stepeni(R).

?- T = t(1,nil,t(2,t(3,nil,t(4,nil,nil)),t(5,nil,nil))), phrase(stepeni(T),L).
T = t(1,nil,t(2,t(3,nil,t(4,nil,nil)),t(5,nil,nil))), L = [1,2,4].

Answer: You might find this method of determine whether or not N is a a power of 2 a little more efficient. It's a bit-twiddling hack that takes advantage of the two's complement representation of integer values:
is_power_of_two( N ) :-
  integer(N) ,
  N \= 0 ,
  0 is N /\ (N-1)
  .

Edited to note that the property holds true regardless of the sign of the integer: with one exception — 0, hence the test for non-zero — the only two's-complement integer values for which this property is true are powers of two:
?- between(-1025,+1025,N),pow2(N).
N = 1 ;
N = 2 ;
N = 4 ;
N = 8 ;
N = 16 ;
N = 32 ;
N = 64 ;
N = 128 ;
N = 256 ;
N = 512 ;
N = 1024 ;
false.

Comment: This is not a bit fiddling hack. You are not exploiting the representation of two's complement at all as you are (as I suppose) not into negative numbers, that is `N > 0` should be there instead of `integer/1 and (\=)2`
Comment: If you use a negative operand for `(/\)/2` (bitwise and), you are getting into the muddy details of two's vs. one's complement. In ISO parlance: you are now depending on implementation defined properties.
Comment: If you can name a modern CPU architecture that uses something other than two's-complement notation for signed integer data types, I'd interested in knowing  what it is.
Comment: @NicolasCarey: According to [this informed answer](http://stackoverflow.com/a/1449812/772868): Power6 and z10.
Comment: @NicolasCarey: 7.1.2 note 3 of 13211-1:1995: A processor may provide as an extension more than one integer type. .... Compris ?
Answer: If you consider that 1 is 2^0, you need to change the base case of stepen/1 predicate.
A more important correction is required because your vadi/2 predicate will fail when any node not power of 2 is found in the tree.
Then you should add a clause
vadi(t(X,L,R),Xs) :-
   % \+ stepen(X), this test is not mandatory, but it depends on *where* you add the clause
   vadi(L,SL), vadi(R,SR), spoji(SL,SR,Xs).

Comment: thank you for your answer...i already tried this clause earlier,but i didn't thought it is important where it should be...now it works...thank you


Solving a Polynomial Expression

Question: If $x$ and $y$ are integral solutions of $$2x^2 -3xy - 2y^2= 7$$
What will be the value of $|x+y|$
I have no idea how to proceed
Answer: HINT:
$$7=2x^2-3xy-2y^2=x(\underbrace{2x+y})-2y(\underbrace{2x+y})=(2x+y)(x-2y)$$
As $x,y$ are integers so will be $2x+y,x-2y$
What are the aliquot divisors of $7?$
Comment: @JyrkiLahtonen, Thanks for your observation.

Solving a Polynomial Expression


Categorical covariates in Cox model in R

Question: When there are multiple levels in a variable (ex. 1,2,3,4), should I use as.factor() to transform it to a factor when I fit a cox model in R?
When there are only two levels (ex. 1 for male and 2 for female), the results are the same. But when there are more than 2 levels, using as.factor or not makes the results different.
Should I use as.factor() here?
I would be very appreciated if someone could answer this question.
Answer: Numbers are often used to mark the different levels of a categorical predictor variable, either explicitly by the investigator or implicitly by the software. If the software interprets those numbers as numbers instead of as labels for categories by the software, the categorical variable will be treated as if it were a continuous numeric variable.
If the levels have a natural ordering, for example Stages I through IV of a particular type of cancer, you have what's called an ordinal predictor. If the software interprets that as a numeric variable, it assumes equal associations with outcome between successive levels of the predictor. In some cases that assumption might be close to true, as you might find with cancer Stage labeled 1 through 4 and treated as numeric. In that situation you might miss the mis-interpretation of Stage by the software, unless you notice that you are only getting 1 coefficient for Stage instead of the 3 coefficients you should be getting for differences from the reference for each of the other levels.
If the levels have no natural ordering, say different types of cancer, then results with more than 2 levels of an unordered categorical predictor variable coded as numbers and treated as numeric will bear no necessary relation to reality. Results might differ dramatically depending on the assignment of the numeric labels to the levels, as you found.
If you are assigning the numbers yourself to the levels, make sure that the software interprets them either as ordinal indicators or as labels, and not as numbers. If your software allows (as R does), it can be less confusing and make outputs easier to interpret if you use character strings as names for levels of an unordered categorical variable (or, if appropriate, specify a categorical predictor as ordinal), and let the software handle the rest.