Strange scheduled tasks on Windows Server 2003

Question: A few days ago, I noticed that our Windows Server 2003 system has strange scheduled tasks. I do not know where they came from or who set them up. I deleted them and they came up again today. They have names such as "At1","At2", "At3" and the status says that they are running.
When I open their properties, the run command looks like rundll32.exe zfypspqu.u,ygxjgq.
What it could be? Does my server have some virus? I did a scan with nod32 and it didn't report anything. I do not have anything unusual set up on this server - it's only running SQLServer 2005 with ReportServer. Two other servers with similar configuration do not have these strange scheduled tasks.
Answer: That's a Conficker infection.
Basic steps to remove it:

Run the latest release of Microsoft's Malicous Software Removal Tool.
Install the KB958644 patch.

If you have multiple systems, make sure you fix them all.
The full Microsoft guide for protecting yourself from Conficker is here.
Good luck, I've had to deal with a Conficker infection at a smallish client, about 30 servers spread throughout 12 sites, it was not fun.
Answer: Try to scan, disinfect, apply patch for all computers in your network at the same time if possible, had bad experience with it (B version, our network has around 300 computers in 3 sites)
http://www.confickerworkinggroup.org
http://www.confickerworkinggroup.org/wiki/pmwiki.php/ENT/Enterprise#toc10
I update batch file to apply for GPO (got it somewhere on Internet)
@echo off

REM   ########################################
REM   Version 6 - 10:19pm Pacific Jan 4th, 2009
REM   Created by Ckemper and Shainw
REM   For disabling infection points and potentially removing Conficker.B malware
REM   http://www.microsoft.com/security/portal/Entry.aspx?Name=Worm%3aWin32%2fConficker.B

REM   #####################################

REM   #####################################
REM
REM   Modify <domain.com> to your domain name in the script portion below.
REM   Rename it to .BAT and drop it in the \\%windir%\sysvol\sysvol\<domain.com>\scriptsfolder (aka, Netlogon share).
REM
REM   Please drop the following tools\files in the Netlogon share for this to work
REM
REM   Getver.exe - attached with this batch file.
REM   SC.EXE - attached with this batch file (can get from a WS2003 or Windows XP system, not native to Windows 2000)
REM   REG.exe - attached with this batch file (can get from WS2003 or Windows XP system, not native to Windows 2000)
REM   windows-kb890830-v2.6.exe - x86 version of MSRT, available from Microsoft Security Support Engineer
REM   windows-kb890830-x64-v2.6.exe - x64 version of MSRT, available from Microsoft Security Support Engineer
REM   sleep.exe - for use with the MSRT tool, attached with batch file
REM   Hotfix update for Windows 2000, Windows XP and Windows 2003, download all updates listed in http://support.microsoft.com/kb/953252, except
REM   the Itanium update as this script does not support Itanium.  Place all 3 updates in the Netlogon directory.
REM   Security update MS08-038 for Windows Vista and Windows Server 2008 - http://www.microsoft.com/technet/security/Bulletin/MS08-038.mspx
REM   This vulnerability is not being exploited, however, to disable Autorun properly this needs to be applied as it contains a fix related to
REM   autorun, same as the one listed above in KB953252.
REM
REM   Place all above in the netlogon directory and edit the <domain.com> values in the script below.
REM
REM   Create a Startup Script policy and reference this batch file.  This needs to be a Startup Script and not a Logon script, so that the
REM   script runs under the machine account.
REM   Link the GPO with the Startup Script to the OU and Groups where you want it to apply.
REM
REM   We do not recommend you use this on DC's or critical servers, those should be cleaned manually so that the services
REM   disabled below do not need to be left disabled for an extended period of time.
REM
REM   Also note that you can set both the Server service (lanmanserver) and Task Scheduler server (schedule) to disabled via group policy
REM   If that is done, then those items can be remarked out below
REM
REM   ###########################################

REM
REM
REM   Methods of spread we will be disabling -
REM
REM
REM   We will disable the Server service and Task Scheduler service.
REM
REM   Why disable the Server service?  This is due to Weak Passwords which the malware attempts to exploit.
REM   The password change will need to be accomplished via password policy for the domain, resetting any local and domain admin password to a
REM   complex password which includes at least 10 characters and contains, alpha-numeric characters and extended characters such as a question
REM   mark or exclamation point.
REM
REM   Why disable the Task Scheduler service?  This is because the malware creates several AT jobs that run every hour to reinfect the system.
REM
REM   MS08-067 security update.  This security update needs to be applied ASAP via your normal patch management process.
REM   http://www.microsoft.com/technet/security/Bulletin/MS08-067.mspx
REM
REM   Why install MS08-067?  This is the main attack vector of the malware.
REM
REM   Autorun - To block the autorun feature, we must apply an and set a registry value.
REM
REM   Why disable Autorun?  This is because the malware drops a binary file called Autorun.inf on all removable drives.
REM

REM
REM   For environments that use Windows Update to deploy updates.  This section will install MS08-067.
REM   You must place the updates that was downloaded from the link above in the Netlogon share and modify <domain.com>
REM   to your domain.  Also, you must remove the REM**** from in front of the lines, note there is one at the bottom also.  Note that the
REM   Windows Vista and WS2008 file is the same for both - Windows6.0-KB958644-x86.msu.
REM

if /i %PROCESSOR_ARCHITECTURE% == IA64 goto :End

REM ****IF not exist %windir%\$NtUninstallKB958644$ goto Check
REM ****IF exist %windir%\$NtUninstallKB958644$ goto Clean

REM ****:Check
REM ****IF not exist %windir%\Servicing\Packages\Package_for_KB958644*.* goto Install
REM ****IF exist %windir%\Servicing\Packages\Package_for_KB958644*.* goto Clean

REM ****:Clean

REM
REM  Checking if already run successfully
REM

\\<domain.com>\netlogon\sc.exe query wuauserv | find "STOPPED" > nul
if %ErrorLevel% EQU 0 goto INIT
if %ErrorLevel% EQU 1 goto END

:INIT

REM
REM   Stopping and Disabling services
REM

\\<domain.com>\netlogon\GETVER.EXE > nul
if %ErrorLevel% EQU 50 goto SC_Stop
if %ErrorLevel% EQU 51 goto SC_Stop
if %ErrorLevel% EQU 52 goto SC_Stop
if %ErrorLevel% EQU 60 goto Vista_2008Server_SC_Stop

:SC_Stop
\\<domain.com>\netlogon\sc.exe stop lanmanserver
\\<domain.com>\netlogon\sc.exe stop schedule
\\<domain.com>\netlogon\sc.exe config lanmanserver start= disabled
\\<domain.com>\netlogon\sc.exe config schedule start= disabled

goto MSRT_RUN

:Vista_2008Server_SC_Stop

\\<domain.com>\netlogon\reg.exe add HKLM\SYSTEM\CurrentControlSet\Services\Schedule /v Start /t REG_DWORD /d 0x4 /f

goto MSRT_RUN

:MSRT_RUN

REM
REM   Running MSRT locally
REM

REM
REM   Checking for x86 or x64
REM   Make sure to edit the <servername>\<share> in the lines below so the logs can be copied up to a central server if desired.
REM   Otherwise the copying of the mrt.log can be remarked out.
REM   Notice the copy of the MRT.log up to a central location has <servername>\<share with write perms>.  This is on purpose.
REM   In most cases, opening a share with everyone write permissions on a DC is not recommended, it is suggested to use a
REM   member server or workstation.
REM

if /i %PROCESSOR_ARCHITECTURE% == x86 goto x86
if /i %PROCESSOR_ARCHITECTURE% == AMD64 goto x64

:x86
call \\<domain.com>\netlogon\Sleep.exe 10
Start /wait \\<domain.com>\netlogon\Windows-KB890830-V2.6.exe /q

copy %windir%\debug\mrt.log \\<servername>\<share>\Logs\%computername%_%username%_mrt.log

goto Tasks

:x64
call \\<domain.com>\netlogon\Sleep.exe 10
Start /wait \\<domain.com>\netlogon\windows-kb890830-x64-v2.6.exe /q

copy %windir%\debug\mrt.log \\<servername>\<share>\%computername%_%username%_mrt.log

goto Tasks

REM
REM   Deleting all scheduled tasks, we have to do this due to the potential random naming of the scheduled task job.
REM   Note, even though we are disabling the Task Scheduler service above, these still need to be remove for when the Task Scheduler service is
REM   started up again.  Erase command is available on Windows 2000 and above OS, so we do not need to make available on Netlogon share.
REM

:Tasks

attrib -h %windir%\tasks\*.job
AT /delete /yes
REM old entry -erase %windir%\tasks\*.job /f /q

REM
REM   Checking for and installing Autorun hotfix. Turning off Autorun for all drives, the malware can spread via this mechanism.
REM   Download all updates listed in http://support.microsoft.com/kb/953252, except the Itanium update as this script does not support Itanium.
REM   Download the Windows Vista and Windows Server 2003 update - http://www.microsoft.com/technet/security/Bulletin/MS08-038.mspx
REM

IF not exist %windir%\$NtUninstallKB950582$ goto Next
IF exist %windir%\$NtUninstallKB950582$ goto Autorun

:Next
IF not exist %windir%\Servicing\Packages\Package_for_KB950582*.* goto 950582
IF exist %windir%\Servicing\Packages\Package_for_KB950582*.* goto Autorun

:950582

REM
REM   Checking OS version for install of KB950582
REM

\\<domain.com>\netlogon\GETVER.EXE > nul
if %ErrorLevel% EQU 50 goto Win2K_950582
if %ErrorLevel% EQU 51 goto WinXP_950582
if %ErrorLevel% EQU 52 goto Win2003_950582
if %ErrorLevel% EQU 60 goto Vista_2008Server_950582

REM
REM   WIN2k section
REM

:Win2k_950582
\\<domain.com>\netlogon\Windows2000-KB950582-x86-ENU.EXE /quiet /norestart
goto Autorun

REM
REM   WINXP section
REM

:WinXP_950582
if /i %PROCESSOR_ARCHITECTURE% == x86 goto WinXP_950582_x86
if /i %PROCESSOR_ARCHITECTURE% == AMD64 goto WinXP_950582_x64

:WinXP_950582_x86
\\<domain.com>\netlogon\WindowsXP-KB950582-x86-ENU.exe /quiet /norestart
goto Autorun

:WinXP_950582_x64
\\<domain.com>\netlogon\WindowsServer2003.WindowsXP-KB950582-x64-ENU.exe /quiet /norestart
goto Autorun

REM
REM   WIN2003 section
REM

:Win2003_950582
if /i %PROCESSOR_ARCHITECTURE% == x86 goto Win2003_950582_x86
if /i %PROCESSOR_ARCHITECTURE% == AMD64 goto Win2003_950582_x64

:Win2003_950582_x86
\\<domain.com>\netlogon\WindowsServer2003-KB950582-x86-ENU.exe /quiet /norestart
goto Autorun

:Win2003_950582_x64
\\<domain.com>\netlogon\WindowsServer2003.WindowsXP-KB950582-x64-ENU.exe /quiet /norestart
goto Autorun

REM
REM   Vista_2008 section
REM

:Vista_2008Server_950582
if /i %PROCESSOR_ARCHITECTURE% == x86 goto Vista_2008Server_950582_x86
if /i %PROCESSOR_ARCHITECTURE% == AMD64 goto Vista_2008Server_950582_x64

:Vista_2008Server_950582_x86
wusa.exe \\<domain.com>\netlogon\Windows6.0-KB950582-x86.msu /quiet /norestart
goto Autorun

:Vista_2008Server_950582_x64
wusa.exe \\<domain.com>\netlogon\Windows6.0-KB950582-x64.msu /quiet /norestart
goto Autorun

:Autorun

\\<domain.com>\netlogon\reg.exe add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer /v NoDriveTypeAuto /t REG_DWORD /d 0xff /f

REM
REM   Removing Hidden setting
REM

\\<domain.com>\netlogon\reg.exe add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\Folder\Hidden\SHOWALL /v CheckedValue /t REG_DWORD /d 0x1 /f

REM
REM   Enabling Automatic Updates, Background Intelligent Transfer and Error Reporting services
REM

\\<domain.com>\netlogon\sc.exe config wuauserv start= auto
\\<domain.com>\netlogon\sc.exe config BITS start= auto
\\<domain.com>\netlogon\sc.exe config ERsvc start= auto

REM
REM   Restarting
REM

Shutdown.exe /r

REM ****:Install

REM ****\\<domain.com>\netlogon\GETVER.EXE > nul
REM ****if %ErrorLevel% EQU 50 goto Win2K
REM ****if %ErrorLevel% EQU 51 goto WinXP
REM ****if %ErrorLevel% EQU 52 goto Win2003
REM ****if %ErrorLevel% EQU 60 goto Vista_2008Server

REM ****:Win2k
REM ****\\<domain.com>\netlogon\Windows2000-KB958644-x86-ENU.EXE /quiet /forcerestart

REM ****:WinXP
REM ****\\<domain.com>\netlogon\WindowsXP-KB958644-x86-ENU.exe /quiet /forcerestart

REM ****:Win2003
REM ****\\<domain.com>\netlogon\WindowsServer2003-KB958644-x86-ENU.exe /quiet /forcerestart

REM ****:Vista_2008Server
REM ****wusa.exe \\<domain.com>\netlogon\Windows6.0-KB958644-x86.msu /quiet

:End
Exit


Within a node, how can I reference the value of a field of a node associated to the current user through a node-reference?

Question: I'm creating a customer extranet for my client. The users are my client's customers. Within the body of a page node, I need to display the ID of the customer (company) to which the current user belongs.
Here's how I've set it up so far:

Drupal 7
I have a Customer content type that has a field called customer_id (among other things).
I have added a node-reference field to the User fields that references one Customer node. (In other words, each user is associated with one Customer.)

So in his profile, the current user has a node-reference value pointing to a Customer node, and I need to retrieve and display (in a page node or block) the value of one field (customer_id) in the Customer node being referenced in the current user's profile.
I've been going through several Drupal books and whatever module documentation I can find, and I've been experimenting with various views using the the Views module, but I'm still pretty stymied. Can somebody point me in the direction of a good way to implement this?
Thank you for your help!
Chris
Comment: Will anybody respond to this? Thanks for your help!!
Answer: You should be able to do this through Views arguments, with the nid of the customer node as the argument. Then that node's fields should be available to you from there.


$\sigma$-algebra intersection of infinite subsets

Question: I am working out a book on Lebesgue measure by Bartle, and would like to see the steps that go into the construction of a proof for the following:

Show that any $\sigma$-algebra of subsets of $\mathbb{R}$ which
  contains all open intervals also contains all closed intervals.

That is, $[a,b]=\cap_{n=1}^{\infty}(a-\frac{1}{n},b+\frac{1}{n})$
Comment: That's a good start! Here are some thoughts on how to continue: For each $x \in [a,b]$, is $x$ in every set on the RHS? Why or why not? Suppose $x > b$. Write $x = b + \delta$ for some $\delta > 0$. Recall the Archimedean property of the reals. Now, do something analogous for $x < a$. Conclusion?
Comment: I can see that the RHS is an intersection of intervals that are a part of the $\sigma-$ algebra and hence, $[a,b]$ is also a part of a $\sigma-$ algebra. The statement looks trivial on a softer note. I am interested in the constructive elements of the proof, that make it seem precise and formal. Am trying to learn from the way, the proof is constructed in showing the equality to be true.
Comment: $x$ can be between $a \leq x \leq b$ for all $n$ from $1$ to $\infty$ in the RHS, where the intersection of these infinite subsets would be $[a,b]$ as the length of the interval is getting larger. But in a case where $x$ is $b$, I would have to continue the proof with this case based on the Archimedean property for the reals. That I will go through here, forth for the second case. Is this another step in the right direction w.r.t the first case?
Comment: What part are you struggling with? For example, do you see *why* the last statement is true? Using the assumptions in the problem statement, what can you conclude from it (even if you don't yet understand why it's true)?
Answer:
We have for each positive integer $n$ that $a-1/n \lt a\lt b\lt b+1/n$, hence $[a,b]\subset (a-1/n,b+1/n)$; in particular $[a,b]$ is contained in the intersection. If $x\in (a-1/n,b+1/n)$ for each positive $n$, then $a-1/n\lt x\lt b+1/n$. Taking the limit $n\to \infty$, we get $x\in [a,b]$.
Let $\mathcal A$ be a $\sigma$-algebra on $\mathbb R$ which contains all the open intervals. Then $\mathcal A$ being stable under countable intersections, this $\sigma$-algebra contains the countable intersections of open intervals. As a closed interval can be expressed like that, we are done.


How do I fit a set of data to Burr Distribution in R?

Question: For example I have a data set as:
(2042.044,2218.153,3670.893,5149.684,5533.429,7111.183,11041.569,15459.771,783.477,1701.520,40810.770,67905.857)
How do I fit the above data in Burr distribution to compute its parameters in R? fitdist does not provide Burr distribution. Can I explicitly define my probability distribution function for the required computation?
Please Help as I am a newbie to R.
Comment: A Burr distribution (at least as defined in [Wikipedia](http://en.wikipedia.org/wiki/Burr_distribution)) will not fit your data.  You need a scaled version of this distribution whose CDF $F$ has three positive parameters, $c,k,\sigma$, and is given by $F(x;c,k,\sigma)=1-(1+(x/\sigma)^c)^{k+1}.$ That will fit your data nicely with $\hat c \approx 2.1, \hat k \approx 0.4,$ and $\hat\sigma \approx 2460$.
Comment: @whuber How did you calculate the three parameters listed above?
Comment: @JonathanDunne I can't recall, but most likely I did a quick maximum likelihood estimate.
Comment: @whuber do you have the formula you used to estimate the parameters via  maximum likelihood estimation? I have been reading a paper  on burr xii parameter estimation here ->  https://dergipark.org.tr/tr/download/article-file/604708, from what I can gather there are four approaches one can take. I am curious to see which approach you would recommend. Cheers, Jonathan
Comment: @JonathanDunne Are you sure that paper is applicable to your situation?  It assumes the shape parameters are known and focuses on estimating the scale and location parameters.  Consider starting a new thread with your question.  That paper appears flawed in several significant respects: it doesn't really analyze the likelihood equations, but only claims they might be unstable (whereas they can be simplified and they don't look problematic to solve); and the equations appear to be incorrect, because the $c-1$ power of $z_i$ that is involved is not necessarily defined.
Answer: Yeah, in ?fitdistr it says you can pass it a density function (CDF), so we just need to define a density function for the Burr distribution. Note that I'm not familiar with the Burr distribution so I just pulled it's CDF off of Wikipedia.
dburr <- function(x, c = 1, k = 1) 1 - (1 + x ^ c) ^ (-k)

# Simulate data from log logistic for a test case
library(FAdist)
obs <- rllog(100)

library(MASS)
fitdistr(x = obs,
         densfun = dburr,
         start = list(c = 1, k = 1), # need to provide named list of starting values
         lower = list(c = 0, k = 0)) # and named list of lower bounds since c, k > 0

I'm also not sure what the relationship is between Burr and log-logistic, so I don't know what the "right" answer is...
Looking under the CRAN Task View on Distributions, apparently the VGAM package includes the Pareto Type-IV distribution, which includes Burr's distribution somehow. So if you know how to parameterize Pareto-IV to become Burr, you can use their dparetoIV function to for fitdstr, and their rparetoIV if you want to simulate data.
Comment: It seems like the actuar package provides the burr distribution: http://artax.karlin.mff.cuni.cz/r-help/library/actuar/html/Burr.html


Get an image from an article/entity

Question: How do I easiest get an image (its path) from the article content type included in Drupal 8?
What I have is an entity. Using $image = $node->fields['field_image'] gives me a hell of a structure, though.
Is there no easier way to get the image path? Also I cannot find the URL in this, what I get is some sort of target_id (the file ID?).
Comment: What does `get_class ($node->fields['field_image'])` give you?
Comment: Drupal\file\Plugin\Field\FieldType\FileFieldItemList is what it gives me, this only seem to contain properties of what is allowed to upload.
Comment: If you iterate the list what types are its members? I haven't checked, but I'd hope for some reasonably strong typing of the field. If all else fails you can use `file_load()` and one of the methods available on [`Drupal\file\FileInterface`](https://api.drupal.org/api/drupal/core%21modules%21file%21src%21FileInterface.php/interface/FileInterface/8)
Comment: Drupal\image\Plugin\Field\FieldType\ImageItem is what I get, not sure how to properly handling that, though.
Comment: file_load is a last resort, but it's depricated and feels so wrong.
Answer: Didn't see this before.
The shortest way to get the referenced entity for a single-value field is this:
$node->field_image->entity->url()

You can also specify the delta explicitly:
$node->field_image[0]->entity->url()

This works with a lot of ArrayAccess and __get() magic.
See also the great cheat sheet at http://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet. and https://www.drupal.org/node/1795854 and the other documentation pages there for more information (still very much work in progress).
Comment: the alt/title is not on the referenced file entity but the field item itself. Just $node->field_image[0]->alt should work fine.
Comment: Nice! I was wondering how we can get the image alt. I tried $node->field_image[0]->entity->alt and $node->field_image[0]->entity->image->alt; which I found in the documentation you mentioned but it does not work with the node entity I think.
Answer: What ended up working for me in D8 is:
$imageUrl = $node->get('field_image')->entity->uri->value;

Using kint($node->get('field_image')->entity) and looking through the array was very helpful

Then in my twig file I used:

Answer: So my solution was to use the method "referencedEntities()" found in the nodeobject. This gave me an array of File-objects which I could iterate through and use the method "url()" from the file objects to retrieve a valid path.
Answer: If your node has more than one image you can use this to get a array of the image urls (helpful for making slideshow modules among alot of other useful things)
$allImagesFound = false;
$imageUrls = array();
$numberOfImages = 0;
while(!$allImagesFound)
{
    //make sure we are not calling a null value, if so then we have found all images
    if($node->get('your_image_field_name')[$numberOfImages] != null) {
        $imageUrls[] = $node->get('your_image_field_name')[$numberOfImages]->entity->url();
        $numberOfImages++;
    } else {
        $allImagesFound = true;
        break;
    }
}

The imageUrls array will hold all the urls for any images associated with the nodes field.
Hope this helps.

Get an image from an article/entity


Extension of Uniformly Differentiable function - from open ball to $\mathbb{R}^n$

Question: Consider $f: U \to \mathbb{R}^m$, where $U$ is an open ball in $\mathbb{R}^n$.

Suppose $f$ is uniformly differentiable on $U$:
$$\forall \epsilon>0\,,\exists \delta>0:|\!|{\bf h}|\!|<\delta,{\bf x},{\bf x}+{\bf h}\in U \Longrightarrow |\!|f({\bf x}+{\bf h})-f({\bf x})-f'({\bf x})({\bf h})|\!|<\epsilon \|{\bf h}\|$$

That is, the $\delta$ is valid for all ${\bf x}$.
I wonder if the following is true:

Question: Can we always construct an extension of $\bar{f}$ of $f$, such that $\bar{f}({\bf x}) = f({\bf x})$, for ${\bf x} \in U$, and $\bar{f}$ uniformly differentiable on $\mathbb{R}^n$?
Answer: Consider $n=m=1$, $U=(-1,1)$, $f(x)=\sqrt{x+1}$.
Obviously $f$ is differentiable on $U$, but not at $x=-1$.
In fact, the tangent there would become vertical, or equivalently:
$f'(x)$ would increase beyond any bound.
--- rk
Comment: Your $f$ is differentiable on $U$, but not uniformly differentiable on $U$.


NextCloud as Oauth Provider

Question: I've noticed that in some of the current versions of NextCloud that there is an admin menu option for adding Oauth 2.0 clients. Doing so gives you a Client ID and a Client Secret as you would expect as well as taking in a redirect URL. Now the question is, how do I use this. I have only found one single mention of it being used online, and that is this.
I currently am using the Oauth2 proxy from Bitly off of github which can be found here. My web server is Nginx and I am running NextCloud 12. I have another internal application that I host as well, this is run along side of an empty GitLab install and that GitLab install is being used as an Oauth 2 reverse proxy to authenticate through before getting to our internal software.
Any help or pointers would be great, this seems like a very powerful feature of NextCloud that has seemly zero support/docs.
To be a bit more specific I will try to better explain my current setup and what I would like it to look like.
Current:
I have 3 "subsites" if you will:

GitLab: www.site.com/subsiteA/
NextCloud: www.site.com/subsiteB/
InternalSite: www.site.com/subsiteC/

User goes to www.site.com/subsiteC and is bounced to the login of GitLab at www.site.com/subsiteA/. Upon successful login they are bounced back to www.site.com/subsiteC/.
Similarly if you go to www.site.com/subsiteB/ you are proxied through www.site.com/subsiteA/, however, the user will still have to sign in through NextCloud.
(Going to subsiteA takes you straight to GtiLab)
Ideal Setup:

NextCloud: www.site.com/subsiteA/
InternalSite: www.site.com/subsiteB/

If you go to www.site.com/subsiteB/ you are bounced through subsiteA but that is it. In this setup there is no need to login to GitLab before logging in to NextCloud.
Answer: Nextcloud has added a section about OAuth2 to its documentation.
You will need various bits of information both about your client applications and about Nextcloud. Here are the most important bits about nextcloud:

Authorization endpoint: SERVER/apps/oauth2/authorize
Token endpoint: SERVER/apps/oauth2/api/v1/token
Profile URL can be accessed as JSON: SERVER/ocs/v2.php/cloud/user?format=json (example output)
Profile information is then stored in ocs.data.id, ocs.data.display-name, ocs.data.email and a few others.

I wrote two howtos:

How to use HedgeDoc (client) with Nextcloud (provider)
How to use GitLab (client) with Nextcloud (provider)

Perhaps those are a good start for your configuration needs. If you encounter any other good tutorials, make sure to mention them in the comments!

NextCloud as Oauth Provider


How to get the current active account in tronlink using tronweb?

Question: I'm trying to access the current logged in tronlink account to make an authentication using tronlink for my dapp.
Using metamask and web3 i can get the current active account on MetaMask using:
const userPublicAddress = web3.eth.coinbase

What's the similar way of doing it with tronweb and tronlink? I havent found about this in the docs.
Answer: const publicAddress = tronWeb.defaultAddress.base58

Comment: this address persists even if TronLink is logged out. Is it correct?
Comment: Hi @VanjaDev! not sure, i don't have the extension anymore to check. Are you able to test?


Why /0(\.\d+)?|1/.test('0.') return true?

Question: Even /0(\.\d+)?|1/.test('...0.0.0')  return true... I just want to get a RegExp to test numbers between 0 and 1.
Comment: Please provide sample data for both the positive and negative cases.  Note that `0.0.0` is not a valid number.
Answer: You need to anchor the regexp with ^ and $, otherwise it matches if the pattern can be found anywhere in the string.

console.log(/^(0(\.\d+)?|1)$/.test('...0.0.0'));
console.log(/^(0(\.\d+)?|1)$/.test('0.1'));
console.log(/^(0(\.\d+)?|1)$/.test('2.3'));
Answer: Well, the reason it's returning true is because it's finding a match in your given text.
/0(\.\d+)?|1/

The regex above will find any 1,0 or 0.d+ in any place in the given text. So for ...0.0.0, it's matching the first 0.d+ it finds. In this case it's 0.0.
Similarly, for the case in your title 0.. Your regex matches the first 0 it finds, ignoring the ..
What you need to look at adding is anchor tags. So you could try the following:
/^((0(\.\d+)?)|1)$/

^ - indicating the start of a string
$ - indicating the end of a string
This makes sure that edge cases like 0. and ...0.0.0 are handled correctly

[
  '...0.0.0',
  '0',
  '0.',
  '0.12546',
  '0.0.0',
  '1',
  '2'
].forEach(exampleString => console.log(exampleString, /^((0(\.\d+)?)|1)$/.test(exampleString)))

When working with Regex, I would highly suggest working with a regex builder like RegExr
Comment: The regexp will find `1`, `0` and `0.d+` (not just `1` and `0.d`), that's why it also matches the `0.` in the title.
Comment: Sorry, I meant the original regexp, not your solution (originally you had only `1` or `0.d` when explaining what the original regexp was finding)
Comment: I'm pretty sure it won't match `0.` but it will most definitely match `0` as well.
Comment: Ahh, you're perfectly correct. I see where my misunderstanding was, I thought you meant that the regex would match `0.` as a whole - instead of just `0` in `0.`


How to handle timeseries extremes (sigma > 20) in deep learning?

Question: I'm using 16-channel, 400-Hz, standardized EEG data to train CNN-LSTM for seizure classification. The data contains $O(3)$ sigma > 20 points, rarely thousands in a row - and $O(4)$ sigma > 10 points (imgs below). Overall, they comprise a very small fraction of all data - regardless, I'm unsure of their impact on model's learning.
I've inadvertently left in one sample in a batch of 32 as nonstandardized, having it end up with sigma=52 - which almost always severely disrupted the model, causing gradient death, and classifier flip-flops (always predicting '0', then always predicting '1', etc). BatchNormalization layers looked completely different in both train and inference modes. This suggests a notable fraction of a single sample having extreme points may notably harm training. Also, such a fraction pre-standardization can, and did, substantially shrink all other points in the sample. Lastly, the data itself is strongly Normally-distributed (img below).
All considered, what's a reliable remedy? Ideas so far:

Clipping - but at what value to clip?
Noisy clipping - e.g. clip at 10, subtract random uniform $\sim(0,1)$
Answer: I would start by determining whether those are are "real" brain signals or noise.
I don't know much about your equipment (and it's not particularly on-topic here), but I associate that exponential shape with an amplifier recovering from saturation. This would be consistent with the signal being much, much larger than expected, so my first guess would be a motion artifact.  Some EEG systems have built-in accelerometers, which might help you check that (and could provide a useful feature for cleaning the data--or even detecting seizures).
At a minimum, you should be able to look up the levels at which your system clips or becomes distorted. You might want to consider introducing a third class ("noise" or "uninterpretable") for segments that approach those limits.


Transform $3^{n} \mod 7 $ to $ n \mod 7$ form

Question: I want to go from that form $3^{n} \mod 7 $ to something that doesn't use exponent.
it says, hint : you should use $ n \mod 7$
I listed the values from $3^0 \mod 7 $ to $ 3^{10} $
$$
3^0  \mod 7 = 1\\
3^1  \mod 7 = 3\\
3^2  \mod 7 = 2\\
3^3  \mod 7 = 6\\
3^4  \mod 7 = 4\\
3^5  \mod 7 = 5\\
3^6  \mod 7 = 1\\
3^7  \mod 7 = 3\\
3^8  \mod 7 = 2\\
3^9  \mod 7 = 6\\
3^{10} \mod 7 = 4\\
$$
Then I want to find a way to get to the values with $n \mod 7$
I tryed with $ 3n \mod 7$ , $3 (n-1) \mod 7$ ,
Also tryed with the gcd(a,n)
also tryed with something like $3(n * n) \mod 7$
Comment: You cannot deduce $3^n\mod 7$ from $n\mod 7$ only. For example, $0\equiv 7\mod 7$, but the values $3^0 \equiv 1$ and $3^7 \equiv 3$ are not identical mod $7$.
Comment: As @azimut says, you want to consider $n\pmod 6$. You can use Lagrange interpolation to find a $5$th degree polynomial to fit these, but I don't see a nice one.
Answer: Show that the values of $3^n\mod 7$ only depend on the remainder of $n\mod 6$. (Hint: Fermat's little theorem)
Then you can tabulate the values of $3^n \mod 7$ like this: $$\begin{array}{l|llllll}n\mod 6 & 0 & 1 & 2 & 3 & 4 & 5\\\hline 3^n\mod 7 & 1 & 3 & 2 & 6 & 4 & 5\end{array}$$
Comment: finally figured it out, thanks a lot. $m = n(\mod p-1)$ then $a^m = a^n (\mod p)$


2sxc Dropdown list string don't appear

Question: I have a problem on a dropdown list, I need to edit it and add some options, but I can't or better I dont' find the string list?
Click there for see Dropdown list string is empty
Can You help me?
i have other dropdown in this app and the other work well
thanks
Fabio
Answer: You are probably affected by an upgrade-issue. 2sxc had to do a change in the field-definition structure when the UI went to angular in 8.0. What happened is this
Previously the entity describing the @String for an input-field had too many properties - many of which never applied to the specific field (like a length-field, which didn't apply to a drop-down).
In 2sxc 8 this was changed, so a string field now has 3 metadata entities describing what the UI should show

@All - containing the main properties like name, help text, required
@String - not containing anything any more
@string-dropdown - containing the settings only relevant to drop-downs

The @String-metadata entity still exists to ensure old UIs still work, but it's deprecated. So the values don't show up any more. But :) you can still get it from debug-mode, to then copy the values to the new container. Here's how:

Go to the admin > data UI
Go into debug mode (Ctrl+Click) http://2sxc.org/en/Blog/post/debugging-2sxc-8-enter-advanced-mode-with-control-click
now open the UI - you should see all hidden fields now

2sxc Dropdown list string don't appear


Enable access to registry in WinForms application of C# .Net

Question: By default : Registry has been disabled
So i get "registry editing has been disabled by your administrator"
In my application i want to let users access registry when the app runs and deny when app stops.
Looking forward for your advice on this.
Comment: Forgot to mention i want this for Windows XP SP2 And SP3 only.
Comment: You want to write a program that has *more* privileges than the admin?  Consider the possibility that Windows doesn't work that way.  Nor admins.  And what would happen, if this actually could work, when the user aborts the program.
Answer: To allow users to edit some registry settings that are normally not accessible, you need to use impersonation. I.e. you need to have your application run as a different user, one with more priviledges.
The easiest way to achieve this it to write a .net Windows Service that runs with higher priviledges. This service can still control what registry settings are allowed to change.
So your users start your Winforms app which communicates with your Service to do the actual changes in the registry.
This does require the user (or operations) to install the service on the machine with admin rights.
Comment: A windows service will always run with a service user.
Open Control Panel > Administrative Tools > Services and take a look at the properties of a service.
http://msdn.microsoft.com/en-us/library/ms677948(VS.85).aspx

How to write a windows service - Google: http://www.google.co.uk/search?hl=en&q=c%23+windows+service&aq=f&aqi=g2g-c1g1g-c1g1g-c3g1&aql=&oq=&gs_rfai=
The top answers will help you get started. It is really easy!
Comment: Thanks for your answer.but can you please share some links / code ( atleast pseudo-code ) for such a .NET Windows Service running as a user at higher privileges.Thanks Again!
Comment: Adding a windows service for this reason only is a big overhead. Not to mention that only a user with administrative rites can install it.
Answer: I am guessing that your app runs on Vista or Win7 and you don't have access to HKEY_LOCAL_MACHINE. In order to edit registry values in that area you need to add a manifest in your project and add this line to it:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

Comment: Forget to mention i want this for Windows XP SP2 And SP3 only.
Answer: I'm pretty sure that your admin has disabled access to Regedit.exe using the "Prevent access to registry editing tools" group policy setting — that's why you're getting that "Registry editing has been disabled by your administrator" message.
That does not affect access to the registry, though. Your application can still access and modify the registry (well, at least HKCU) using the RegistryKey class, for instance.
Answer: Use assembly attribute RegistryPermissionAttribute() above namespace
[assembly: RegistryPermissionAttribute(SecurityAction.RequestMinimum, ViewAndModify = "HKEY_CURRENT_USER")]
//SecurityAction is enum having different security parameters


filtering only if it is not null or undefined

Question:      results.data
              .filter((x) => countries.includes(x.country))
              .filter((x) => x.car_model_year > startYear && x.car_model_year < endYear)
              .filter((x) => x.gender.toLowerCase() === gender.toLowerCase())
              .filter((x) => colours.includes(x.car_color)),

I have this piece of code above countries, startYear, endYear, gender and colours are variables that can be null or undefined. The issue is it should ignore the filteration for that specific variable if the variable is empty(null or undefined). What is the best way to implement it, thank you.
Answer: You can check if a value is null or undefined by comparing it to null (see this answer), so just OR that check into each of your filter expressions and they will only filter if the value is not null or undefined.
results.data
       .filter((x) => countries == null || countries.includes(x.country))
       .filter((x) => startYear == null || endYear == null || x.car_model_year > startYear && x.car_model_year < endYear)
       .filter((x) => gender == null || x.gender.toLowerCase() === gender.toLowerCase())
       .filter((x) => colours == null || colours.includes(x.car_color))

Answer: You can use or operator.
results.data
  .filter(x => !countries || countries.includes(x.country))
  .filter(
    x => (!startYear || x.car_model_year > startYear)
      && (!endYear || x.car_model_year < endYear)
  )
  .filter(x => !gender || x.gender.toLowerCase() === gender.toLowerCase())
  .filter(x => !colours || .filter((x) => colours.includes(x.car_color)))

And so on..


Enterprise Level Anti-virus software with these Requirements

Question: I have read this and this this
But I have a few requirements that I don't know are addressed in those questions.
I am looking for a Replacement for our Symantec Anti virus.  (if you want to know why see the end of this question.  Here are the requirements for the AV software.

1)      Must be Enterprise Wide

2)      Must be able to control it from a server
          (kind of the same as enterprise wide)

3)      Must not have to pay for updates
          (ie virus updates)

4)      Window 7 x32 and x64  bit compatible

5)      Windows 2000 x32 bit compatible
          (This is a sad requirement I know.  If it cannot be filled
           then that is OK, it will just add another reason to get
           this very OLD OS out of our company.)

Background (if you care)
The main reason we are looking for a replacement is that the upgrade path form our current version would require our PC Support to remove any current versions of Symantec before upgrading to this new version.  This is has been the main reason why they have never looked for a new virus software, because it would be too big of a hassle for PC Support to go around to each machine and remove Symantec to install something else.  Symantec is a big resource hog and it would make a big impact on user machines if we could find something better.
Comment: Can you indicate what version of Symantec AV you have in place now?
Comment: Assuming the rest of the company has what I have, 10.1.6
Answer: I can completely recommend ESET NOD32 Business Edition.  I'm not sure about the Windows 7 requirement, but my guess is that it won't be a problem.
NOD32 is lightweight, fully managed, and built for "enterprise" deployment.  The administration interface is a regular application, not some whacky web-based piece of junk. (sore spot for me)  It rates very highly in all of the independent anti-virus test reports I've read.
I moved to NOD32 from Trend Micro Worry-Free recently and couldn't be happier.  I actually had users say, "why is my computer running so fast?"  I'm not kidding.  I marked it on my calendar.
I, like you, waited a long time to switch because of the whole uninstall issue.  Trend didn't disappoint, I had to manually remove the dang thing from almost every machine... and by manually remove I mean manually deleting registry entries, drivers, etc.  In the end it was worth it, though.
The downside to NOD32 is that it's a little bit more difficult to setup initially.  Not too hard though.  It's also a bit more expensive.
I'm not sure what you mean by not having to pay for virus definitions.  You're going to sign into one or two years of support with any managed anti-virus solution.
Comment: Well, at least you can deploy ESET using the MSI domain-wide... But as for removing Symantec, you are out of luck. And it does run on Windows 7 without any hassle.
Comment: You may find that certain ESET resellers are willing to offer very significant (i.e. order-of-magnitude) discounts vs. list price, particularly if you are switching from another product and are willing to purchase a multi-year license.
Answer: My vote would go to NOD32 from eset....as the other threads have suggested.  We moved from Symantec to Eset and have been very happy.  Their admin console can be a bit daunting at first.
I'm running the antivirus 4 client on Windows 7 x64 as I'm typing this.  They also support W2K.
To your background though, as far as I know, you're still going to have to manually remove Symantec and touch each workstation to switch to another product.
Comment: Well, since we are going to have to do that either way, that is not a problem.
Answer: I would also recommend ESET NOD32 Antivirus.  It fulfills all of your requirements.  Additionally, they are able to create a custom installation package to remove your previous antivirus software before installing their package.  ESET refers to this process as Rip and Replace.
Comment: Their custom Rip and Replace installation package worked great for our organization. I removed McAfee VirusScan 8.5 from 350+ workstations without issue.
Comment: Rip and Replace sounds like it could be very useful for us.
Answer: I switched to TrendMicro OfficeScan recently, and I'm reasonably pleased with it.  (Though I also switched from Symantec, so I would have been pleased with a kick in the teeth.)
I do not believe that they charge for virus definition updates (you can download their pattern file for free, so I assume it's free for the software, too), it's client-server based, and they do have clients for 2k through Vista and '08, (Windows 7 isn't listed, but I would be surprised if it wasn't supported).
I believe that it might also have the possibility of uninstalling SAV during installation, possibly even during remote installation.  (I couldn't do it because the stupid Symantec firewall had been enabled and I had to touch each machine anyway.)
Comment: Officescan requires a maintenance contract to receive updates.  If you don't renew, you will have 60 days before the update cease.
Comment: They may disable the automatic download, but the pattern file is freely available.  (Added link in answer.)  It's certainly worth talking to a salesperson to make sure, though.


Why do I have different p-values if calculated differently?

Question: I do have the following dataframe:
df <- data.frame(
  Assay = c("Gene1", "Gene2", "Gene3"),
  DT1 = c(1,2,3),
  DT2 = c(4,5,6),
  DT3 = c(4,5,6),
  DT4 = c(0,8,7),
  DT5 = c(-1,2,5),
  DT6 = c(4,5,3),
  DT7 = c(5,2,9),
  DT8 = c(0,0,4),
  DT9 = c(3,6,2),
  DT10 = c(5,9,1),
  DT11 = c(2,3,4),
  DT12 = c(8,1,6)
)

And I would like to create a column that will contain p-values for groups compared row by row. First 5 columns (2:6) versus Next 7 columns (7:13)
# Perform t-tests row-wise and obtain p-values
p_values <- apply(df[, 2:6], 1, function(row) {
  t_test_result <- t.test(row, df[, 7:13])
  t_test_result$p.value
})

# Add the p-values column to the dataframe
df$p_values <- p_values
df

For the first row when I use this script I have a p-value of 0.09335115 while if I do it manually:
t.test(c(1,4,4,0,-1),
       c(4,5,0,3,5,2,8))

I do have a p-value of 0.1425
What's the issue?
Answer: just do:
p_values <- apply(df[-1], 1, function(row) {
     t_test_result <- t.test(row[1:5], row[6:12])
     t_test_result$p.value
 })

p_values
[1] 0.1425172 0.6840726 0.3266262


Is this set a subspace of $\Bbb{R}^{[4, 6]}$

Question: I am confused as to what this notation means?
$$\textsf W = \{f \in \Bbb{R}^{[4, 6]} : (\forall x \in [4,6])(|f(x)| \le 1)\}$$
Answer: $\mathbb{R}^{[4,6]}$ is the set of all functions $f$ that going from $[4,6]$ to $\mathbb R$. Hence, $\textsf W$ consist of all those functions $f\in\mathbb{R}^{[4,6]}$ for which $|f(x)|\leq 1$ for all $x\in[4,6]$ (because $[4,6]$ is the domain of this functions).
Answer: You're looking at the set of all function $f:[4,6]\to \mathbb{R}$. Such that $|f(x)|\le 1$ for every $x\in [4,6]$. Is this set closed under scalar multiplication?
Answer: The constant function 1 belongs to your set. Its double not. Hence it is not a vector subspace.


pascal's triangle sum of nth diagonal row

Question: today i was reading about pascal's triangle. the website pointed out that the 3th diagonal row were the triangular numbers. which can be easily expressed by the following formula.
$$\sum_{i=0}^n i = \frac{n(n+1)}{2}$$
i wondered if the following rows could be expressed with such a simple formula.
when trying to find the sum for the 3th row i used a method called "differences" i found on this site: http://www.trans4mind.com/personal_development/mathematics/series/sumNaturalSquares.htm
lets call $P_r$ the $r^{th}$ row of pascals triangle. The result for the 4th row was
$$\sum_{i=0}^n P_3 = \frac{n(n+1)(n+2)}{6}$$
and the result for 4th row was
$$\sum_{i=0}^n P_4 = \frac{n(n+1)(n+2)(n+3)}{24}$$
 i guessed the sum of the 5th row would be
$$\sum_{i=0}^n P_5 = \frac{n(n+1)(n+2)(n+3)(n+4)}{120}$$
i plotted the function and looking at the graph it seems to be correct.
it looks like the the sum of each row is:
 $$\sum_{i=0}^n P_r = \frac{(n + 0)\cdots(n+(r-1))}{r!}$$
is this true for all rows? and why?
i think this has something to do with combinatorics/probability which i never studied.
thanks in advance
edit image for  $P_r$:     https://i.stack.imgur.com/3BdRn.png
Comment: Then the relation ${i\choose j}+{i\choose j+1}={i+1\choose j+1}$ is all one needs to prove this by induction.
Comment: What is $P_r$, already?
Comment: i meant sum of rth diagonal row , sorry bit confusing i will add image
Answer: So you basically want to prove that $$\binom{n}{n}+\binom{n+1}{n}+\binom{n+2}{n}+\dotsc+\binom{n+k}{n}=\binom{n+k+1}{n+1}$$
holds for all $n,k$, right?
Of course you can prove this using induction and Pascal's formula
$$\binom{n}{k}+\binom{n}{k+1}=\binom{n+1}{k+1}$$
as suggest by Did.
There is a nice combinatorial interpretation of this using double-counting:
Suppose you have $n+1$ eggs, $n$ of them blue and 1 red.
You want to choose $k+1$ of them which is the RHS: $\binom{n+1}{k+1}$
Either you choose the red one in which case you have $\binom{n}{k}$
possibilities for the remaining ones.
Either you don't choose the red one in which case you have $\binom{n}{k+1}$ possibilities for the remaining ones.
Can you think of a similar combinatorial argument which directly works for the original sum?
Hint: Think of $n+k+1$ balls in a row labelled $1,2,\dotsc,n+k+1$. You want to choose $n+1$ of them. That's the RHS: $\binom{n+k+1}{n+1}$.
Now, distinguish cases about which is the rightmost ball you choose. If it's the ball number $n+k+1$ you have $\binom{n+k}{n}$ possibilities to choose the remaining $n$ balls.
If it's the ball number $n+k$ you have $\binom{n+k-1}{n}$ possibilities etc.
Can you complete it from here?
Answer: Just to be more explicit, here is a proof of: $$\binom{n}{n}+\binom{n+1}{n}+\binom{n+2}{n}+...+\binom{n+k}{n}=\binom{n+k+1}{n+1}$$I will use the property suggested by Did which is valid for general $i$ and $j$,
\begin{equation}\binom{i}{j}+\binom{i}{j+1}=\binom{i+1}{j+1}\end{equation}
Proof:
\begin{align}
\binom{n+k+1}{n+1} & =\binom{n+k}{n}+\binom{n+k}{n+1}\qquad\text{Using above property}\\
&=\binom{n+k}{n}+\left\{\binom{n+k-1}{n}+\binom{n+k-1}{n+1}\right\}\\
&=\binom{n+k}{n}+\binom{n+k-1}{n}+\left\{\binom{n+k-2}{n}+\binom{n+k-2}{n+1}\right\}\\
&=\binom{n+k}{n}+\binom{n+k-1}{n}+\binom{n+k-2}{n}+...+\left\{\binom{n+1}{n}+\binom{n+1}{n+1}\right\}\\
&=\binom{n+k}{n}+\binom{n+k-1}{n}+\binom{n+k-2}{n}+...\binom{n+1}{n}+\binom{n}{n}
\end{align}
Hence proved.
Answer: Try performing the following multiplication, then look up the Binomial Theorem.
$$\begin{array}{lr}
&\binom{5}{5}x^5+\binom{5}{4}x^4+\binom{5}{3}x^3+\binom{5}{2}x^2+\binom{5}{1}x+\binom{5}{0}\\
\times&x+1\\
\hline
\end{array}$$


$F,G \in \text{End} (V)$ share the same eigenvalues for $F \circ G$ and $G \circ F$

Question:
Problem: Let $V$ be a finite dimensional Vector Space over a field $\mathbb{F}$ and $F,G \in \text{End}(V) $
Show that $F \circ G$ and $G \circ F$ have the same Eigenvalues $\lambda$

My approach: Let $\sigma_F:= \lbrace \lambda_i \in \mathbb{F} \mid  \lambda_i \text{ is a Eigenvalue of } F\rbrace $
Thus I have to show that $\sigma_{F \circ G} = \sigma_{ G \circ F} $ and because of the symmetry it is sufficient to show that for example $\sigma_{ F \circ G} \subset \sigma_{G \circ F} $
Suppose $\lambda$ is a Eigenvalue of $F \circ G$ and $v \in V \setminus \lbrace 0 \rbrace$ the related Eigenvector, it follows that for  Case 1) $G(v) \neq 0$: $$ F(G(v))=\lambda v \implies (G\circ F)(Gv)=G(F(Gv))=G(\lambda v)=\lambda G(v) \\ \implies G(v) \text{ is a Eigenvector to $G \circ F$ with Eigenvalue $\lambda$}$$
I am sure the second part is just as easy, but I have been dealing with this problem for too long on my own without consulting help, so I guess I suffer from not seeing the forest for the trees.

Case 2) Let $G(v) = 0$, $v$ as above it follows that: $$ F(G(v))=\lambda v = F(0)=0 \implies \lambda =0 \text{ because } v \neq 0  $$ It is clear to me that I cannot use $G(v)= 0$ as an Eigenvector of $G \circ F$ because $G(v)$ is now the zero vector and therefore, by definition, not a Eigenvector. Therefore I have to come up with a better statement $$\ker (G \circ F) \neq \lbrace 0 \rbrace \iff \lambda =0 \text{ is a Eigenvalue of } G \circ F \tag{*} $$
I have several problems now with the above statement (*), focussing on the $\implies$ direction
Can I use the same Vector $v \in V \setminus \lbrace 0 \rbrace $ for this statement? It is not really clear to me if and why I can do this, I believe that I have to, because all I know for this case is that $G(v)=0 \implies v \in \ker \lbrace G \rbrace $ and applying $F$ to both sides would give $ F(G(v))=F(0)=0 \implies v \in \ker \lbrace F \circ G \rbrace $.
If I for example just say let $ k \in \ker (G \circ F ) \neq \lbrace 0 \rbrace $ such that $k$ is an Eigenvector of $G \circ F$ with Eigenvalue $\lambda$ it would follow that $$G(F(k))= \lambda k = 0 \implies \lambda =0  $$
which seems very artificial (or forced up) to me, furthermore I have not even made use of my premise that $G(v) = 0$, so the above procedure must be wrong.
On the other hand if I choose $v \in \ker \lbrace G \circ F\rbrace \neq \lbrace 0 \rbrace $ (which I don't know if I am allowed to do) it would follow that: $$G(F(v))=\lambda v=0 \implies \lambda =0  $$
which looks better to me, but just as artificial and again I have not made use of the premise.
Answer: Here's what you're missing:
You are correct in stating $0 \in \sigma_A \iff \ker(A) \neq \{0\}$.
If $G(v) = 0$ for some $v \neq 0$, then clearly $\ker(FG)\neq \{0\}$.  To complete our proof, it suffices to show that $\ker(GF) \neq \{0\}$.
Now, suppose there is some vector $u\neq 0$ such that $F(u) = v$. Then clearly $G(F(v)) = 0$, which means that $\ker(GF) \neq \{0\}$, as desired.
Suppose to the contrary that there is no such vector. Then $F \in \text{End}(V)$ is not onto.  What can we deduce about the kernel of $F$?
Comment: Thanks a lot for your answer, I do appreciate it. I understand the first part of it (I've also written that down above), but I am supposed to show that the Eigenvalues are equal and I do not see why that follows by showing that the Kernel of GF is non trivial.
Comment: @Spaced in the first part, you've effectively shown that if $FG$ has some eigenvalue $\lambda \neq 0$, then $GF$ has the same eigenvalue.  For the second part, you only need to show that if $FG$ has $0$ as an eiegenvalue (i.e. has a non-trivial kernel), then $GF$ also has a non-trivial kernel.
Comment: Thanks a lot @Omnomnomnom, that makes sense to me now, I will try to write it down in my words in a few and then come to rest about this problem :)
Comment: To answer your question directed at me. If $F \in \text{End}(V)$ is not onto, then it follows that the dimension of the image is smaller than the dimension of $V$, therefore the dimension of the Kernel of $F$ greater or equal to 1. It follows, that the Kernel of F is non trivial. By the way, did you mean that if $F(u)=v$ it follows that when applying $G$ to both sides, $G(F(u))=G(v)=0 \implies u \in \ker(GF)$ ?
Comment: @Spaced yes, that's exactly what I meant.  And it looks like you have it all down! Nicely done.


Criando e usando componente no angular 2

Question: Criei este componente para mostrar mensagem de sucesso ou não.
import { Component } from '@angular/core';
import { MatSnackBar } from '@angular/material';

@Component({
  selector: 'app-snack-bar',
  templateUrl: './snack-bar.component.html',
  styleUrls: ['./snack-bar.component.css']
})
export class SnackBarComponent {

  snackBar: MatSnackBar

  constructor(

  ) {}

  openSnackBar(message: string, isOnline : boolean) {
    this.snackBar.open(message, undefined,
      { duration: 3000,
        panelClass: isOnline ? ["online", "onlineAction"] : "offline" }
      );
  }
}

Para chamar estou fazendo assim:
onSubmit(form){
    const snackBarComponent = SnackBarComponent;
    snackBarComponent.prototype.openSnackBar(dados.mensagem, true);
}

Só que apresenta este erro no console do navegador:

ERROR TypeError: Cannot read property 'open' of undefined
        at Object.SnackBarComponent.openSnackBar (snack-bar.component.ts:18)
        at MunicipioFormComponent.onSubmit (municipio-form.component.ts:115)
        at Object.eval [as handleEvent] (MunicipioFormComponent.html:1)
        at handleEvent (core.js:13547)
        at callWithDebugContext (core.js:15056)
        at Object.debugHandleEvent [as handleEvent] (core.js:14643)
        at dispatchEvent (core.js:9962)
        at eval (core.js:12301)
        at SafeSubscriber.schedulerFn [as _next] (core.js:4343)
        at SafeSubscriber.__tryOrUnsub (Subscriber.js:243)
    View_MunicipioFormComponent_0 @ MunicipioFormComponent.html:1
    proxyClass @ compiler.js:14653
    DebugContext_.logError @ core.js:14996
    ErrorHandler.handleError @ core.js:1509
    dispatchEvent @ core.js:9966
    (anonymous) @ core.js:12301
    schedulerFn @ core.js:4343
    SafeSubscriber.__tryOrUnsub @ Subscriber.js:243
    SafeSubscriber.next @ Subscriber.js:190
    Subscriber._next @ Subscriber.js:131
    Subscriber.next @ Subscriber.js:95
    Subject.next @ Subject.js:56
    EventEmitter.emit @ core.js:4311
    NgForm.onSubmit @ forms.js:5762
    (anonymous) @ MunicipioFormComponent.html:1
    handleEvent @ core.js:13547
    callWithDebugContext @ core.js:15056
    debugHandleEvent @ core.js:14643
    dispatchEvent @ core.js:9962
    (anonymous) @ core.js:10587
    (anonymous) @ platform-browser.js:2628
    ZoneDelegate.invokeTask @ zone.js:421
    onInvokeTask @ core.js:4740
    ZoneDelegate.invokeTask @ zone.js:420
    Zone.runTask @ zone.js:188
    ZoneTask.invokeTask @ zone.js:496
    invokeTask @ zone.js:1517
    globalZoneAwareCallback @ zone.js:1543
    MunicipioFormComponent.html:1 ERROR CONTEXT DebugContext_ {view: {…}, nodeIndex: 0, nodeDef: {…}, elDef: {…}, elView: {…}}

O que pode ser ?
Comment: Para chamar não seria assim: `snackBarComponent.openSnackBar(dados.mensagem, true);` ?
Answer: Você não esta inicializando o snackBar, você tem que por ele no construtor por angular injetar ele.
import { Component } from '@angular/core';
import { MatSnackBar } from '@angular/material';

@Component({
  selector: 'app-snack-bar',
  templateUrl: './snack-bar.component.html',
  styleUrls: ['./snack-bar.component.css']
})
export class SnackBarComponent {

  constructor(
      private snackBar: MatSnackBar,
      private messageService: MessageService
  ) {
  this.message.getMessages().subscribe(message=>this.openSnackBar(message.message, message.isOnline ))
}

  openSnackBar(message: string, isOnline : boolean) {
    this.snackBar.open(message, undefined,
      { duration: 3000,
        panelClass: isOnline ? ["online", "onlineAction"] : "offline" }
      );
  }
}

message.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class MessageService{
    private messageSubject= new Subject<any>();

    constructor() {}

    addMessage(message) {
        this.messageSubject.next(message);
    }

    getMessages(): Observable<any> {
        return this.messageSubject.asObservable();
    }
}

Comment: Sim, fiz o que você disse. Não ocorreu erro pois, entendo que não chamei este componente.

Como chamo ?

Se faço isto, dá o mesmo erro.

const snackBarComponent = SnackBarComponent;
    snackBarComponent.prototype.openSnackBar(dados.mensagem, true);

Entendeu ?
Comment: Voce quer chamar do mesmo componente? Se sim você pode chamar assim: this.openSnackBar(dados.mensagem, true);
Comment: Não.

Exemplo. Existe os componentes: Bairro, BairroBusca, Estado, EstadoBusca, entre outros, mais de 50.

A idéia é criar este componente e chamar nos formulários passando os parametros quando necessário.

Entendeu ?
Comment: nesse case você precisa criar um serviço que você injeta nos outros components com um behavior subject que você recebe os parâmetros ai você mostra quando necessário. Vou editar minha resposta pra te dar uma ideia.
Comment: Ai para chamar no Bairro, seria assim:

No construtor, coloco assim:

private messageService : MessageService;

ai na execução assim:

messageService.addMessage("minha mensagem");

Correto ?
Comment: tipo isso ou entao vc pode fazer um objeto com a mensagem e o booleano ou um array vai de vc.
Comment: O certo seria criar uma interface export interface Message {message:string, isOnline:boolean}
Comment: ai coloca la addMessage(message:Message)
Comment: Blz. Vou tentar solucionar aqui e coloco o resultado. De qualquer forma obrigado.


Retrieving file and folder inside VM remotely using other system

Question: Recently my teammate accidentally deletes numerous files even important system files inside development server. because of this our staff cannot login even in local so we cannot recover remaining files.
so we plan to try to bring out all remaining files inside /home and /var using other system (another server). its solved if its physical mount, but how we access this folder if this server is not phsyical server? (this is VM, we're using Centos KVM).
sory my bad english,
Answer: In order to connect to the VM over the network from another machine besides the host system, the VM's networking will need to be configured in such a manner so it can access the main network. That is called "bridged mode". That will give that VM an IP address from the main network pool.
Check the NIC device on the "virtual hardware details" screen and verify that the network mode is set to "bridged".


Python multiprocessing Queue child class losing attributes in process

Question: I am trying to implement a child class from the multiprocessing Queue in python. The child class contains a simple Boolean flag "ready". When I send the queue to a new process, the ready attribute is disappearing. The following code demonstrates the problem:
import multiprocessing
import multiprocessing.queues

class ReadyQueue(multiprocessing.queues.Queue):
    def __init__(self, ctx, *args, **kwargs):
        super(ReadyQueue, self).__init__(ctx=ctx, *args, **kwargs)
        self.ready = False

def ready_queue(*args, **kwargs):
    return ReadyQueue(ctx=multiprocessing.get_context(), *args, **kwargs)

def foo(q):
    print(q.ready)

if __name__ == "__main__":
    my_queue = ready_queue()
    print(my_queue.ready)
    p = multiprocessing.Process(target=foo, args=(my_queue,))
    p.start()
    p.join()

With the output:
False
Process Process-1:
Traceback (most recent call last):
  File "C:\Users\acre018\Anaconda3\envs\EIT_Qt\lib\multiprocessing\process.py", line 315, in _bootstrap
    self.run()
  File "C:\Users\acre018\Anaconda3\envs\EIT_Qt\lib\multiprocessing\process.py", line 108, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\acre018\github\EIT_Qt\Experiments\ready_queue_test.py", line 16, in foo
    print(q.ready)
AttributeError: 'ReadyQueue' object has no attribute 'ready'

Comment: What version of Python are you using? Shouldn't you be inheriting from `multiprocessing.Queue` rather than `multiprocessing.queues.Queue`? See https://docs.python.org/3/library/multiprocessing.html?highlight=queue#pipes-and-queues
Comment: I wonder if this is platform-specific. I'm unable to reproduce the issue on macOS/python3.6. The example you gave works as expected.
Comment: @barny I'm using python 3.8.5 from Anaconda on Windows. The docs are a bit confusing on this subject but per https://stackoverflow.com/a/34293098/12952673, `multiprocessing.Queue` is a method that creates queues. To inherit the class you need to use `multiprocessing.queues.Queue`
Comment: @GeorgeD. This seems to be the case. Testing the code on a few web  python interpreters it runs as expected. My sys.version is `3.8.5 (default, Sep  3 2020, 21:29:08) [MSC v.1916 64 bit (AMD64)]` Most web interpreters seem to be GCC rather than MSC
Comment: K - yes the docs aren't at all clear on that. Will try your code n the morning, on Windows.
Answer: I implemented this workaround:
import multiprocessing
from queue import Empty
import time
import ctypes

class ReadyQueue:
    def __init__(self, *args, **kwargs):
        self.queue = multiprocessing.Queue(*args, **kwargs)
        self._ready = multiprocessing.Value(ctypes.c_bool, False)

    def set_ready(self):
        self._ready.value = True

    def set_not_ready(self):
        self._ready.value = False
        self.clear()

    def is_ready(self):
        return self._ready.value

    def clear(self):
        try:
            while True:
                self.queue.get(block=False)
        except Empty:
            pass

    def get(self, block=True, timeout=None):
        return self.queue.get(block, timeout)

    def put(self, obj, block=True, timeout=None):
        return self.queue.put(obj, block, timeout)

    def full(self):
        return self.queue.full()

    def empty(self):
        return self.queue.empty()

    def qsize(self):
        return self.queue.qsize()

def foo(q):
    while q.is_ready():
        time.sleep(1)
        q.put("hello from foo")
    print("q no longer ready, foo loop finished")

if __name__ == "__main__":
    my_queue = ReadyQueue()
    my_queue.set_ready()
    p = multiprocessing.Process(target=foo, args=(my_queue,))
    p.start()

    for i in range(2):
        print(my_queue.get())
        time.sleep(2)

    print("my_queue._ready = %s, qsize: %d. Setting not ready.." % (str(my_queue.is_ready()), my_queue.qsize()))
    my_queue.set_not_ready()
    print("my_queue._ready = %s, qusize: %d" % (str(my_queue.is_ready()), my_queue.qsize()))

With the output:
C:\Users\acre018\Anaconda3\envs\test_pyqt\python.exe C:/Users/acre018/github/EIT_Qt/Experiments/ready_queue_test2.py
hello from foo
hello from foo
my_queue._ready = True, qsize: 2. Setting not ready..
my_queue._ready = False, qusize: 0
q no longer ready, foo loop finished

Process finished with exit code 0

The workaround is to have my ReadyQueue class not inherit from multiprocessing.queues.Queue but have a queue as an attribute. For convenience I implemented the methods that I need from queue, and they just pass through to the queue attribute. I also implemented a clear method.
Note that in my first example I neglected to make self.ready a multiprocessing.Value, so wouldn't have been able to edit it across processes, but I tested after fixing that and it was not the source of the issue.


Where can I get Native American drum and flute samples

Question: I would like to be able to dynamically compose music using JavaScript using the sounds like from this video. I don't know where you would even begin. Do I need to record it all myself or is there some place that already has this sort of thing completely recorded into thousands of variations of drum and flute samples from single real instrument? If I were to purchase them, would they be royalty free for commercial or non-commercial use type thing? I am just trying to get a sense for how I would go about obtaining hundreds if not thousands of drum samples to be able to generate music like that native american video. I'm not sure (a) how many samples per instrument you would need to have a good and realistic, robust, thick sound, and how much it should realistically cost, and (c) what its license restrictions typically are. Trying to get at the gist of  how this process works.
Comment: I'm voting to close this question as off-topic because listing external resources is off topic.
Answer: Sample libraries exist [hundreds of them], but though they all are licensed so you can use them in your own compositions for commercial use, I doubt whether any of them would permit re-use inside what is essentially another application. You'd have to ask the authors very specifically about that.
It may be different if this JavaScript app is essentially just for your own use.
Comment: Are there such things as high quality "open source" native american sample libraries? :)
Comment: I'm not sure what you'd consider to be 'open source' as far as a pre-recorded sample set would be. The 'source' is a mic, a drum & a keen ear. With some not too difficult scripting, you can build your own instruments in structures such as Kontakt, by Native Instruments. You do seem to be wanting to reinvent the wheel... without yet knowing how wheels are currently built. ;) I haven't yet figured out your actual intent in this venture.
Comment: There are also algorithmically-based structures, such as [Chromophone](https://www.applied-acoustics.com/chromaphone-2/) which is entirely modelled & uses no samples.
Comment: Yes I want to reinvent the wheel, that is true. I don't want to learn the existing tools necessarily if it can be avoided, as it will take too long :)


python text processing: identify nouns from individual words

Question: I have a list of words and would like to keep only nouns.
This is not a duplicate of Extracting all Nouns from a text file using nltk
In the linked question a piece of text is processed. The accepted answer proposes a tagger. I'm aware of the different options for tagging text (nlkt, textblob, spacy), but I can't use them, since my data doesn't consist of sentences. I only have a list of individual words:
would
research
part
technologies
size
articles
analyzes
line

nltk has a wide selection of corpora. I found verbnet with a comprehensive list of verbs. But so far I didn't see anything similar for nouns. Is there something like a dictionary, where I can look up if a word is a noun, verb, adjective, etc ?
This could probably done by some online service. Microsoft translate for example returns a lot of information in their responses: https://learn.microsoft.com/en-us/azure/cognitive-services/translator/reference/v3-0-dictionary-lookup?tabs=curl
But this is a paid service. I would prefer a python package.
Regarding the ambiguity of words: Ideally I would like a dictionary that can tell me all the functions a word can have. "fish" for example is both noun and verb. "eat" is only verb, "dog" is only noun. I'm aware that this is not an exact science. A working solution would simply remove all words that can't be nouns.
Comment: What is a noun? What is a verb? How do you differentiate them? Is it language specific? Can `Google` be a verb? Is `Google` a noun? Function words in english might have fixed Parts of Speech but non-function words are in most cases ambiguous without context.
Comment: Updated question
Answer: Tried using wordnet?
from nltk.corpus import wordnet
words = ["would","research","part","technologies","size","articles","analyzes","line"]
for w in words:
    syns = wordnet.synsets(w)
    print(w, syns[0].lexname().split('.')[0]) if syns else (w, None)

You should see:
('would', None)
('research', u'noun')
('part', u'noun')
('technologies', u'noun')
('size', u'noun')
('articles', u'noun')
('analyzes', u'verb')
('line', u'noun')

Answer: You can run a POS tagger on individual fragments, it will have lower accuracy but I suppose that's already a given.
Ideally, find a POS tagger which reveals every possible reading for possible syntactic disambiguation later on in the processing pipeline.  This will basically just pick out all the possible readings from the lexicon (perhaps with a probability) and let you take it from there.
Comment: I've tried it and it works surprisingly well. Spacy is awesome :) still, it's not really an answer to the question (I'm looking for something like an old fashioned dictionary)
Answer: Even if you use a dictionary, you will always have to deal with ambiguity, for example, the same word depending on the context can be a noun or a verb, take the word research

The government will invest on research.
The goal is to research new techniques of POS-tagging.

Most dictionaries will have more than one definition of research, example:
research as a noun
research as a verb
Where do these words come from, can you maybe pos-tag them within the context where they occur?
Comment: They have no context, it's a vocabulary list. You are of course right about the ambiguity, most verbs can be used as nouns, too. A good catch, a nice walk, ... I'm interested in throwing anything away that is obviously not a noun. "beautiful", "learn", "above", ...
Answer: As @Triplee and @DavidBatista pointed out, it is really complicated to find out if a word is a noun or a verb only by itself, because in most languages, the syntax of a word depends on context.
Words are just representations of meanings. Because of that I'd like to add another proposition that might fit what you mean - instead of trying to find out if a words is a noun or a verb, try to find out if a Concept is an Object or an Action - this still has the problem of ambiguity, because a concept can carry both the Action or Object form.
However, you can stick to Concepts that only has object properties (such as TypeOf, HasAsPart, IsPartOf, etc) or Concepts that have both object and action properties (action properties are such as Subevents, Effects, Requires).
A good tool for Concept Searching is Conceptnet, it provides a WebApi to search for concepts in its network by keyword (it is based of Wikipedia and many other sites and is very complete for english language), is open and also points to synonyms in other languages (that are tagged as their common POS - you could average the POS of the synonyms to try to find out if the word is an object [noun-like] or an action [verb-like]).


Commerce Donation page

Question: I want to create a button on each node to a donation page. The button needs to send the title of the node to that page, I have managed to do this.
I have a product type donation. I modify the form price with line item and setup a form where you can select different donations values.
The problem is that I need to find a way to include that title in the donation form so It can be passed to cart.
I have tried commerce add to cart function to alter that, but it doesn't work.
Answer:
Made a Product Type: Donation
After that I created Products of: 2 USD, 10 USD etc.
Created a donation page of form: /donation/*
When I reference the donation page from the node page the links look like this: /donation/%nid
On the donation page I create a custom form and there I modify the submit function.

Commerce Donation page


LilyPond: Subdivided beam grouping for compound time signatures

Question: I'm trying to write a 12/8 drum score in Lilypond, with a lot of 32nd note phrasing, and the default beam grouping looks a bit ugly to me:

(Here's the above example in LilyBin: http://lilybin.com/w0s4nh/2)
I'd like it to be subdivided into 8th note groups, like this:

As can be seen on the LilyBin link I pasted above (line 36), I tried modifying the baseMoment parameter as per the documentation, but it doesn't matter what I set, the beaming always stays the same.
Is there anything else I should be doing here?
Comment: Er, just curious here, but didn't you get it to beam the way you want in the second picture there?
Comment: Hahaha, I'm actually copying a drum sheet to make it fit in fewer pages using lilypond, and the original beaming seems a lot prettier to me. The second picture comes from the original PDF I'm copying =).
Comment: Aha. Thanks. That's what I get for not paying close enough attention. :)
Answer: Here's a good start.
<code>\layout {
  \context {
    \DrumStaff
      drumStyleTable = #(alist->hash-table drum-table)
      subdivideBeams = ##t
      baseMoment = #(ly:make-moment 1/8)
      beatStructure = #'(3 3 3 3)
  }
}
top = \drummode {
  cymc8 \repeat unfold 5 { cymr }
  cymr16 \repeat unfold 8 { sn32 }
  \repeat unfold 6 { toml }
  \repeat unfold 8 { tomfl }
}
bot = \drummode {
  bd4 bd16 bd
  sn bd sn bd sn bd
  bd8 \repeat unfold 5 { hhp }
}
\score {
  \new DrumStaff <<
    \new DrumVoice {
      \voiceOne \time 12/8 \top
    }
    \new DrumVoice {
      \voiceTwo \time 12/8 \bot
    }
  >>
  \layout {}
}
</code>

What this does end up doing is separating your code into more manageable parts: music is just music, layout is just layout, and score is just score. (Well, for the most part). So, when you need to make a change, you can pinpoint a lot more quickly where the change needs to happen.
In a case like this, you might need to temporarily intermix the music and the layout for only one Voice:
<code>\layout {
  \context {
    \DrumStaff
      drumStyleTable = #(alist->hash-table drum-table)
  }
}
top = \drummode {
  \set Voice.subdivideBeams = ##t
  \set Voice.baseMoment = #(ly:make-moment 1/8)
  \set Voice.beatStructure = #'(3 3 3 3)
  cymc8 \repeat unfold 5 { cymr }
  cymr16 \repeat unfold 8 { sn32 }
  \repeat unfold 6 { toml }
  \repeat unfold 8 { tomfl }
}
bot = \drummode {
  bd4 bd16 bd
  sn bd sn bd sn bd
  bd8 \repeat unfold 5 { hhp }
}
\score {
  \new DrumStaff <<
    \new DrumVoice {
      \voiceOne \time 12/8 \top
    }
    \new DrumVoice {
      \voiceTwo \time 12/8 \bot
    }
  >>
  \layout {}
}
</code>

In my opinion, where you can achieve something "programmatically" like the first example, that is preferable. But, in a pinch, or where necessary, the second example can work.
Comment: Thanks! It's always nice to have separation of concerns. I see I still have a lot to learn about the different contexts in LilyPond, this isn't the first time I got all confused trying to change Score definitions when they should actually be Staff or Voice definitions. I updated the LilyBin example (http://lilybin.com/w0s4nh/3) for future reference. Thanks again! =)


Calculating the Odds of Victory in Risk

Question: I am trying to write an odds calculator for risk that calculates the percentage chance of winning a combat between a number of given Attackers and given Defenders.
The calculator will use basic risk rules, that is, the attacker roles dice equal to the number of attackers but no more than 3. The defender does the same but is limited to 2 dice. The resulting roles are sorted and then combat is determined by comparing the two top dice and removing them from the stack. The side with the lower die roll loses one troop. This process continues until one side wins.
What I want to know is if their is an equation that can be used to solve this without creating the normal statistics tree. Creating that tree, while it works, becomes unmanageable after either side goes above 10 or more troops.
My current solution is to simulate 100,000 combats and then take the number of times the Attacker wins/100,000 to get the percent chance of winning the combat. This solution also works, however, since it is based on random chance itself the results can be off by significant amounts. It also requires simulating a lot of combat.
Is there some function I could use to calculate this result without having to use one of the previously mentioned solutions?
Comment: have you made a graph of the basic risk map yet? If you are willing to share, I'd love to see it.
Comment: nevermind, someone else on the web has: http://en.wikipedia.org/wiki/File:Risk_Game_Graph.svg
Comment: Related: [Who has the upper hand in a generalized game of risk?](http://math.stackexchange.com/questions/85679/who-has-the-upper-hand-in-a-generalized-game-of-risk)
Answer: Let $F(m,n)$ be the probability of the attacker winning when the attacker starts with $m$ armies and the defender starts with $n$.  Then for $m \ge 3$ and $n \ge 2$, $F(m,n) = a F(m-2,n) + b F(m-1,n-1) + c F(m,n-2)$ where $a$, $b$ and $c$ are the probabilities of the attacker losing 2, both losing 1, and defender losing 2 on a roll (you can compute these easily).  For $m < 3$ or $n < 2$, the equation changes somewhat because only one army
is lost on a roll.  The boundary conditions are $F(m,0) = 1$ for $m \ge 2$, $F(1,n) = 0$ for $n \ge 1$.  It's then straightforward to determine  $F(m,n)$ in a double loop.
Comment: I agree! I wrote a Risk simulation a few years ago, and I believe this was the method I used to calculate winning probabilities in battles.
Comment: (0.2926 * F(A - 2, D)) + (0.3358 * F(A - 1, D - 1)) + (0.3717 * F(A, D - 2)) I am using this equation for F(m,n) where A and D are the numbers of Defenders and Attackers. However, this is resulting in probabilities greater than 100% for large values of A. I pulled the values of a, b and c from Wikipedia. Any idea what I am doing wrong @robert-israel ?

Calculating the Odds of Victory in Risk


Image classification using Semantic Segmented Images

Question: Can we use the semantic segmented images directly to perform image classification using CNN model?
Updating the question:
I am trying to classify images as below:
a. Input : Images taken from camera fitted on a vehicle.
b. Output : Check if there is an vehicle in front of my vehicle (from where image is taken)
I am currently using the RGB images to perform classification. However in this mis-classification would happen if there is an building (or any other obstacle other than vehicle) in the image.
Could you please clarify if the below approach would improve the accuracy in prediction
Since the semantic segmented images are colored according to the type, will it help in improving the model?
Answer: Semantic segmentation of an image (at least in context of CNN based methods) can simply be viewed as a pixel-wise classification problem, that is to say that you assign a class to every pixel of the image. So in your case if you are able to successfully perform a semantic segmentation of your camera feed then the problem of classification of cars/no cars is trivial or rather non-existent since you were able to solve a more difficult problem of classifying every pixel. Just check for cars in your pixel-wise classification output.
However, if your objective is only to identify whether or not there is a car in frame then honestly semantic segmentation is a overkill and I don't see any reason why you can't train a near perfect binary classifier for cars/no cars problem which would be robust to various background artifacts(buildings etc.) even with limited data. Try transfer learning on ILSVRC pre-trained resnet 34 or smaller variants. Fine tune the final few layers first and then when you hit saturation fine tune the entire network with these updated weights. You can also try cyclical learning rates (https://arxiv.org/abs/1506.01186).
Comment: Thanks for the input. It was really helpful. I have trained binary classification model using Transfer learning (ResNet50, VggNet), however the model is not robust because of below reasons:
1. Color of the obstacle (Car) can be different.
2. Shadow effect
3. Background effect (Building, Road boundary etc)
Answer: Yes, having ground truth segmentation would make classification tasks quite easy, perhaps even trivial.
A small nitpick is that a semantic segmentation map is not an image "colored according to type". The colored image is merely a visualization of the $K$ channel segmentation map, which when $K > 3$, cannot be directly visualized.
Comment: I am bit confused in the statement
*The colored image is merely a visualization of the  channel segmentation map, which when >3, cannot be directly visualized.*
Comment: @KK2491 well a segmentation map is a $H$ by $W$ by $K$ array. A computer screen with only 3 channels cannot display this easily, so we assign each segmentation class to an arbitrary RGB value. Therefore there is an important difference between the *visualization* of a segmentation map (what you refer to as the "segmented image") and the segmentation map itself. It would be pretty weird to feed the visualization and not the map into a network.
Comment: Thanks for the explanation. Now I understood. I was thinking to consider only roads by extracting the ROI from segmented images (visualization of segmentation map). I thought that this will reduce the effect of background on model.


Exim appending hostname to fully qualified sender address

Question: I'm having a problem at the moment on a corporate e-mail server whereby Exim is appending its server hostname onto the end of the sender's e-mail address, despite that e-mail address already being fully qualified.
For example, a user sends an e-mail from:
<code>firstname.lastname@example.com
</code>
and Exim is changing this to:
<code>"firstname.lastname@example.com"@corp-2.mycompany.co.uk
</code>
This is no longer a valid e-mail address and as a result receiving mail servers usually reject the message because it can't verify the sender.
Exim config at: http://pastebin.com/4nS6T1Aw
Exim output from a dummy delivery (exim -bh) at: http://pastebin.com/UTXC8RuR
From the looks of it, something weird is going on with quotation marks and I think Exim's tripping itself up, but I'm scratching my head on this one and would appreciate any help!
Thanks
Answer: In the early days of email, the email address format was generally user@hostname.  Frequently, the sender that was passed to a mail server was simply the username, and the mail server automatically appended its hostname to the supplied username.
Over the past 15 years, it's become much more common for a mail server to be configured to accept email for multiple domains (not just its hostname), which is typically called "virtual mail."  When it comes to virtual mail, the mail server must figure out when the argument being passed is just a local username, or if it's a full email address.  When it's not a full email address, you want Exim to append the hostname (or default domain you specify), but if it is an email address, you want to tell Exim not to append that hostname/domain.
I have this in my MAIL acl, which tells exim to "retain the sender domain" (which is a roundabout way of saying "the domain is supplied, leave it alone").
<code>  accept  authenticated  = *
          control        = submission/sender_retain
          control        = dkim_disable_verify
          add_header     = X-Authenticated-Sender: ${sender_address}
          set acl_c_authenticated = 1
</code>
Comment: Thank you, Todd. Fixed. My control line was

"control       = submission/sender_retain/domain=".

Removing the empty "/domain=" modifier fixed it!

I realise that that modifier was unnecessary unless I wanted to alter the sender's domain (which I didn't), so in effect I was blanking out the sender's original domain and then leaving Exim to pick up the pieces as best it could.
Comment: Ah, that explains why in part of the processing it seemed to recognize the correct domain name, and then mysteriously later it no longer recognized it. I'll try to remember that for the future :-)
Comment: Partially my own fault - I set up that mail server a couple of years ago following somebody's tutorial. It's surprising that I haven't been aware of this problem until now, but it looks like most receiving mail servers are quite tolerant. I've just come against one that's more picky.
Comment: This isn't working for me from an ACL perspective - my ACL tells me that `sender="duncan@domain"@domain`


Creating a cadenza (Boccherini Concerto No 3 in G Maj)

Question: I need to create a cadenza (a virtuoso passage inserted near the end of a concerto movement) for cello for the first part of Boccherini Concerto No 3 in G Maj (Allegro, starting at measure 98 in my score). It must be different from the cadenzas given in the editions.
I'm a little bit dumbstruck about how to start that task.
Is there kind of a standard procedure to do so? How do you start that sort of thing? Do you know of a tutorial for creating such virtuoso passages?
Any help to overcome my inhibition would be greatly appreciated.
Answer: Partial answer: listen to recordings of cadenzas for this piece and others. If you can't use the written one, then listening to other pieces in a similar style should give you some ideas. From this, you should be able to get a general idea of the style, composition, and length you need to apply. If you hear something you like, copy or modify it.


Where can I find jazz piano scales to practice?

Question: I played the piano for years classically when I was younger, but eventually left it alone in my late teens and twenties. I probably wouldn't have if I'd been allowed to do more Jazz as I always wanted to.
I'm just wondering where I can get hold of the scores of good Jazz scales to practice? I'm sure there are many different types but I don't know enough about it to even look!
Comment: [This question](http://music.stackexchange.com/questions/410/how-can-a-classical-pianist-learn-jazz-piano) is at least related, in particular the part about "The Real Book" volumes (the copies I have do not offer scales, but I don't think deducing them from the tons of nice songs they offer should be a problem). I'm not commenting about the "The Jazz Piano Book" because I don't know it.
Answer: The "Scale Syllabus" page inside any Jamey Aebersold book is a good resource.
And how about that, you can get it for free from his website in PDF format:
Scale Syllabus


Simplify log expression with infinite series $\log x - \sum_{i=1}^{\infty} \frac{x^i}{i}$

Question: How would I simplify the expression?
$$\log x - \sum_{i=1}^{\infty} \frac{x^i}{i}$$
I'm fairly confident the series is divergent, if its not can you explain how it converges and where to go from there?
Update: The series can be simplified by a simple identity, due to the fact that it's actually a Taylor series expansion.
Comment: The series is convergent for $-1\le x<1$, and divergent otherwise.
Comment: Note that $ln(x)=ln(1-(1-x))$
Answer: Hint:
taylor series:
$${\displaystyle \log(1-x)=-\sum _{i=1}^{\infty }{\frac {x^{i}}{i}}=-x-{\frac {x^{2}}{2}}-{\frac {x^{3}}{3}}-\cdots \quad {\text{ for }}|x|<1}$$
Comment: @CameronP see https://en.wikipedia.org/wiki/Taylor_series
Comment: Wow. I completely forgot about that identity. Thank you. Is there a proof for the identity that's accessible with an undergrad understanding?


How to send email from non-TLS enabled client through TLS-only Gmail account

Question: I need to be able to send email from a client (an OKI document scanner) which is non-TLS capable. But my company's email service is provided by Gmail-Google Apps, which is configured to force TLS authentication. Therefore the scanner cannot connect to the Google SMTP server.
I have a local linux machine that I could use in the following way: have the scanner connect to some kind of email relay in the linux machine without TLS, and have the linux machine relay the email to Google's server under TLS.
Could you tell me if there is any kind of simple MTA that I could install in the linux machine and that would allow me to do this? I have zero experience with full-fledge MTAs of the likes of sendmail, postfix or exim, so the simplest the solution the better.
If the solution were to use a full-fledge MTA (sendmail, postfix or exim, or whatever), could you also help with the configuration? I understand these are not trivial to configure.
There is of course no need for the scanner to receive emails, just to send them.
Thanks!
Answer: You're going to have to go with a full MTA; the cut-down MTAs only provide service for local message generation.
As far as configuration goes, it should be a simple smarthost configuration, for which there are an infinite number of guides on the Googlez for every MTA under the sun.
Answer: I believe you could use something like stunnel to act as a proxy. Stunnel installed on the Linux machine can accept plaintext connection from the scanner and forward the communication using SSL connection to Google SMTP server.
You can find an example of such a configuration on http://securityconscious.blogspot.com/2011/03/setting-up-stunnel-in-client-mode-in.html.
However the communication between the scanner and stunnel will be in plaintext in this case so your scanner's Google account password will be under the risk of being compromised!
Comment: Hi Fedor, installed stunnel and works perfectly under SSLv3. The scanner and the machine running stunnel are in a controlled local network, so I am not so worried about the plaintext communication. Thanks!


Messing with toggle function when click outside

Question: I'm stuck with my jQuery "functions" (I know basics only).
So I'm working on a responsive website and when the user press an arrow icon → [>] (a#side-toggle), the menu (#header-toggle) slides out, and the icon slides on the left to stay visible, and the text changes to change the arrow → [<].
When I click again on this icon, the menu goes back to where it came and the icon is → [>]. Perfect.
In the first function, an overlay DIV is displayed, to avoid user to press on the content while using the menu. When you click on this overlay, the menu slides back and the overlay disapears. Normal. But the text doesn't change, it's stuck like that → [<]
When I click again on the text to show the menu, it changes to this → [>], and the menu doesn't show up (the function has returned to its original state actually). If I click again, the function toggles, as it should.
I need to fix this, the user should only press once on this icon to show the menu.
Clean my code if it's possible, because I think it's a mess too, haha
Here's the jsfiddle !
The problem is in the JS, here's an extract:
$('#side-overlay').click(function() {
    $(this).hide();
    $("#header-toggle").animate({
        left: "-200px",
        boxShadow: "0px 0px 0px 0px rgba(0,0,0,0)"
      }, { duration: 700, easing: "easeInOutBack", queue: false });
    $("#side-handler").animate({
        left: "0px",
      }, { duration: 700, easing: "easeInOutBack", queue: false });
    $("a#side-toggle").text($(this).text() == '>' ? '<' : '>');
});

Thanks for your help!
Comment: The HTML and CSS would also be helpful. A [jsfiddle](http://jsfiddle.net/) would be even better!
Comment: @BrandonBoone : I updated my question, and put a link to a jsfiddle as you asked
Answer: I think I've found the issue.
The jQuery toggle method is triggered on the click event of the designated selector. That means if you manually "hide" or "show" the overlay and menu without going through this event you'll be out of sync with the internal state of the toggled object.
In other words, click on the arrow and the internal working of toggle will fire the hide event on the next click, however the user clicked the overlay which manually hid the elements. User then clicks on the arrow and the hide event is fired even though the element is already hidden.
Here is the code: Fiddle
var side = $('a#side-toggle');
var overlay = $("#side-overlay")
var header = $("#header-toggle");
var sideHandler = $("#side-handler");

side.toggle(show,hide);

overlay.click(function(){side.click()});

function show(){
    header.animate({
        left: "0px",
        boxShadow: "3px 1px 11px -3px rgba(0,0,0,.45)"
    }, {
        duration: 700,
        queue: false
    });

    sideHandler.animate({
        left: "200px",
    }, {
        duration: 700,
        queue: false
    });
    overlay.show();
    side.text('<');
}

function hide(){
    header.animate({
        left: "-200px",
        boxShadow: "0px 0px 0px 0px rgba(0,0,0,0)"
    }, {
        duration: 700,
        queue: false
    });

    sideHandler.animate({
        left: "0px",
    }, {
        duration: 700,
        queue: false
    });
    overlay.hide();
    side.text('>');
}

Comment: +1, However, your problem description missed it.  You rewrote all of his code into something much cleaner, while I merely found the root cause of his described problem.
Comment: @Sparky672 - Thanks for kudos for the re-write. To clarify my solution: I understood the incorrect "this" selector as you see I have eliminated that part of the problem through the re-write/code-cleanup. However, you'll notice I also eliminated the second issue as well. If you click on the Red Arrow, then the Overlay, then the Red Arrow again; you'll see that the slider behaves correctly in my solution. In the solution you have provided, the user would still be required to click the Red Arrow twice in the last step. This is due to the manual hiding of the elements via the overlay click event.
Answer: Inside your slide-overlay .click() function:
$('#side-overlay').click(function() {
    //...
    $("a#side-toggle").text($(this).text() == '>' ? '<' : '>');});
});

$(this) actually refers to $('#side-overlay'), so since the target is wrong, the arrow does not change.  You must remove $(this) and replace it with the proper target...
$("a#side-toggle").text($("a#side-toggle").text() == '>' ? '<' : '>');});

See it working here:  http://jsfiddle.net/4HXEm/4/


What are $\rho$-, $\beta$-, and $\alpha$-mixing conditions?

Question: I have seen properties named $\rho$-, $\beta$-, and $\alpha$-mixing conditions in papers related to Copulas and Markov processes like this one:

In this paper, we identify conditions on $C$ that suffice for geometrically fast mixing rates. Geometric $\beta$-mixing, equivalent to geometric ergodicity for stationary Markov chains, is established under a rather strong condition that excludes copulas that exhibit tail dependence or asymmetry. Geometric $\rho$-mixing, which implies geometric $\alpha$-mixing, is obtained under a much weaker condition. We verify this condition for various parametric copula functions that are popular in applied work. $\rho$-, $\beta$-, and $\alpha$-mixing conditions may be used as the basis for a range of inequalities and limit theorems that are useful in demonstrating the asymptotic validity of statistical methods;

Beare, B., 2010, Copulas and temporal dependence, Econometrica, 78(1).
I am an engineering student and I have trouble understanding these conditions in statistical texts. Can somebody explain them?
Answer: Before going into the formal definition of mixing coefficients, the main idea of this notion is to quantify the dependence of a sequence of random variables. We would like to have theorems which do not only apply in the independent case, but "if the time series is not too far away from an independent sequence". There are several way for a sequence of random variables to be dependent, and mixing (in the sense $\rho$, $\alpha$ or $\beta$) is one of them.
First of all, we compare the dependence between two $\sigma$-algebras, either directly by comparing the difference between the measure of the intersection and the product of measures ($\alpha$-mixing), or the correlation between what is measurable with respect to the first and second $\sigma$-algebra ($\rho$-mixing).
Then we compare the dependence in these sense between the past and future $\sigma$-algebras.
Comment: How to compare the dependence statistically?
Answer: There is an excellent survey on various notions of mixing. I can personally recommend:-)
R.C. Bradley, "Basic Properties of Strong Mixing Conditions. A Survey and Some Open Questions"


How to get iphone device screenshot when image animation is run on main thread?

Question: I am perfoming image sequences animation is on main thread.
At the same time i want to take snapshot of device screen in back ground.
And by using that snapshots i want make video..
Thanks,
Keyur Prajapati
Answer: For taking the screenshots while running the image animations
use

[self.view.layer.presentationLayer renderInContext:UIGraphicsGetCurrentContext()];

instead of

[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];

it will take screenshots while runing animations
iOS uses Core Animation as the rendering system. Each UIView is backed by a CALayer. Each visible layer tree is backed by a presentation tree. The layer tree contains the object model values for each layer, i.e., values you set when you assign a value to a layer property (A and B). The presentation tree contains the values that are currently being presented to the user as an animation takes place (interpolated values between A and B).
Answer: If you're doing it in CoreAnimation you can render the layer contents into a bitmap using -renderInContext:. Have a look at Matt Longs Tutorial. It's for Objective-C on the Mac, but it can be easily converted for use on the iPhone.
Answer: Create one another thread where you can do this:
    //Create rect portion for image if full screen then 320X480
    CGRect contextRect  = CGRectMake(0, 0, 320, 480);

  // this is whate you need
    UIGraphicsBeginImageContext(contextRect.size);

    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];

  UIImage* viewImage = UIGraphicsGetImageFromCurrentImageContext();

  UIGraphicsEndImageContext();

viewImage is the image which you needed.
You can write this code in function which can be called timely bases like per 5 seconds or according to your requirements.
Hope this is what you needed.
Comment: Thanks. i have already make it by this way.but i can't got images in proper sequence . means i missed some image during images taking time.