Expected value conditional on a function

Question: Let $X$ and $Y$ be random variables. What is the relationship (if any) between $E[Y|X]$ and $E[Y|g(X)]$?
I have been trying to Google or look in books but I'm having trouble even articulating this properly. Any insight would be greatly appreciated.
Comment: I'm not sure if much can be said in general. For example, if $g(x) = c$ for some constant $c$, then we don't learn anything by observing $g(X)$.
Comment: One of the particular cases I'm interested in has $X$ be a random vector of dimension $k$ and $g(X) = X'a$, where $a \in \mathbb{R}^k$. In this setting $g$ is not constant but it is not one-to-one.

I was able to find in the Wikipedia page for conditional expectations that $E[E[Y|X]|g(X)] = E[Y|g(X)]$, although I'm not sure how to prove it. I wonder if this is as much as can be said in general.
Answer: $P(Y=y \& g(X)=g(a)) =P(Y=y | g(X)=g(a))P(g(X)=g(a))\\
\begin{align} &=P(Y=y \& g(X)=g(a) \& X=a)+ P(Y=y \& g(X)=g(a) \& X \neq a)
\\&=P(Y=y \&  X=a)+ P(Y=y \& g(X)=g(a) \& X \neq a)
\\&=P(Y=y |  X=a) P(X=a)+ P(Y=y | g(X)=g(a) \& X \neq a)P(g(X)=g(a) \& X \neq a)
\end{align}$
And we get this when $P(g(X)=g(a)) \neq 0$. :
$P(Y=y | g(X)=g(a))=P(Y=y |  X=a) r +P(Y=y | g(X)=g(a) \& X \neq a)(1-r)$
where $r= P(X=a)/P(g(X)=g(a))$.
$\int y f_{Y|g(X)=g(a)} dy= r \int y f_{Y|X=a} dy+ (1-r) \int y f_{Y|g(X)=g(a) \& X \neq a}dy$
$E[Y|g(X)=g(a)]= r E[Y|X=a] +(1-r)E[Y|g(X)=g(a) \& X \neq a]$
When g is a one-to-one function, r would be 1 so they are equal.
I guess this equation could be related to Bayesian statistics.
I posted misleading answer before and now I improved it and post it again. Any advice and crrections are always welcome. I am also a studying student.
Comment: Your notation is vague and therefore leads easily to misinterpretation: sometimes you seem to use "$x^{*}$" (which you don't actually define) in the sense of the *inverse image* $\{x\mid g(x)=g^{*}\}$ and other times it seems to denote some particular element of that set.  Could you edit this answer to clarify what you're trying to say?
Comment: Sorry for misleading answer. I was trying to say one specific value of the function $g$ as a $g*$. I will edit this answer now. Thank you for your comment.
Comment: That clarifies things--but it makes it evident your first equation is wrong, because it implicitly assumes $g$ is one-to-one.
Comment: You're right. I will delete my answer to avoid confusion. I am so sorry.
Comment: I had improved this answer so I didn't delete it.


If $AA^* $ and $BB^*$ are unitarily similar Can we prove that $A $ and $B$ are unitarily similar?

Question: Let $A,B \in M_n$ and $AA^* $ and $BB^*$ are unitarily similar.
Can we prove that $A $ and $B$ are unitarily similar?
Answer: No, this is false in general. Consider $A=I_n$  and $B=-I_n$. Since only $I_n$  is unitarily equivalent to $A$, $A$ and $B$ are not unitarily equivalent, but $AA^\ast = BB^\ast$.


How to get comment votes using raw sql query?

Question: In a D7 site, comments are voted using rate module.
I'm wondering how to get the rating of all comments of 'story' content using raw sql query?
Comment: of all nodes of contenty type `story` or just particular one?
Comment: Ideally all of them. But even if I know how to make a query for one node, it should be easy to generalize.
Answer: Here you are SQL to get the total vote count for widget type number for each comment od node type "story"
SELECT c.cid,count(v.vote_id) FROM votingapi_vote v JOIN comment c ON v.entity_id=c.cid JOIN node n ON n.nid=c.nid WHERE n.type='story' GROUP BY v.entity_id;

If you want to get the total numer of votes for all "story" nodes then:
SELECT c.cid,count(v.vote_id) FROM votingapi_vote v JOIN comment c ON v.entity_id=c.cid JOIN node n ON n.nid=c.nid WHERE n.type='story'

Or conditional for voting type like you did:
SELECT c.cid, count(v.value) FROM votingapi_vote v JOIN comment c ON v.entity_id=c.cid JOIN node n ON n.nid=c.nid WHERE n.type='story' and v.value_type='points' GROUP BY v.entity_id;

Comment: I think count(vote value) = count(votes given) for comment, at least for vote type number
Comment: This is good hint, but what I want is the total value (not total number) of votes given to each comment, exactly as what users see on pages. When I run the above query it returns only one row while there are many comments.
Comment: Well, this one worked for me:  `SELECT c.cid, count(v.value) FROM votingapi_vote v JOIN comment c ON v.entity_id=c.cid JOIN node n ON n.nid=c.nid WHERE n.type='story' and v.value_type='points'
GROUP BY v.entity_id;`  Please modify answer and I'll accept it. Thanks a lot.


Change background image on button click

Question: I'm using eclipse to code my android app and I'm wondering how I can change the background image of my MainActivity when I click a button. I have img1.png and img2.png. The background is currently set on img1.png with the following xml code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/img1"
    tools:context=".MainActivity" >
<Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="46dp"
        android:layout_marginTop="55dp"
        android:background="@android:color/transparent"
        android:text="" />

</RelativeLayout>

I'm just unsure what java code I would use to change the background image on btn1 click.
Comment: use drawable with states
Answer: This code can be used to set background image programmattically
RelativeLayout layout =(RelativeLayout)findViewById(R.id.relativelayout);
layout.setBackgroundResource(R.drawable.img1);

Comment: Yes,it can be done for `LinearLayout` also like `LinearLayout layout =(LinearLayout)findViewById(R.id.linearlayout);`
Comment: There's no need to cast. `findViewById` returns a `View`, `RelativeLayout` and `LinearLayout` are both `View`s, and `setBackgroundResource` is a method on `View`.
Comment: Can you also do this for Linear Layout's, or is this a Relative Layout-only feature? Just wandering.
Comment: I get a red line under this part (R.id.relativelayout); underneath the relativelayout part ?
Comment: Check the id of your relative layout in your xml file..That should be replaced for the `relativelayout`..
Answer: This could be a solution.
In your layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/lyt_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/img1"
tools:context=".MainActivity" >

In your Activity
RelativeLayout layout;
public void onCreate(Bundle savedInstanceState){
super.onCreate(Bundle savedInstanceState);
setContentView(your_xml.xml);
layout = (RelativeLayout) findById(R.id.lyt_main);
button = (Button) findById(R.id.lyt_main);
button.setOnClickListener(new OnClickListener{
      public void onClick(View v) {
               layout.setBackgroundDrawable(your_image));
      }
});
}

Comment: What would I change R.id.lyt_main to?
Answer: Add android ID to Your Layout:
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/img1"
        android:id="@+id/rlayout"
        tools:context=".MainActivity" >
...
</RelativeLayout>

Now In Your MainActivity.java :
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btn = (Button) findViewById(R.id.btn1);

        btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                RelativeLayout rlayot = (RelativeLayout) findViewById(R.id.rlayout);
                rlayot.setBackgroundResource(R.drawable.img2);
            }
        });
    }

Change background image on button click


How to diagnose/fix CloudFormation/autoscaling SSL errors on file download

Question: I have an autoscaling group that was created by AWS CloudFormation. It runs on Amazon Linux 2. Last week, it was working fine. Now, new instances throw a "certificate has expired" error when trying to download phpMyAdmin. It appears cfn-init is running yum fine, and grabbing files from S3 fine, but not working when it goes to grab remote files (which it appears it does with Python).
EDIT: see below, but I initially thought this was some problem with the Python scripts. I'm no longer sure that's true, because it works fine in a different autoscaling group grabbing different files. So ... now I'm thinking it's actually some problem with the certificate on phpMyAdmin, but ... I'm not sure. And I still don't know how to diagnose further.
/var/log/cfn-init.log:
2021-10-06 10:08:24,895 [INFO] -----------------------Starting build------------
-----------
2021-10-06 10:08:24,896 [DEBUG] Not setting a reboot trigger as scheduling suppo
rt is not available
2021-10-06 10:08:24,898 [INFO] Running configSets: default
2021-10-06 10:08:24,899 [INFO] Running configSet default
2021-10-06 10:08:24,906 [INFO] Running config config
2021-10-06 10:08:34,173 [DEBUG] Installing/updating ['mod_ssl', 'ksh', 'httpd']
via yum
2021-10-06 10:08:37,523 [INFO] Yum installed ['mod_ssl', 'ksh', 'httpd']
2021-10-06 10:08:37,523 [DEBUG] No groups specified
2021-10-06 10:08:37,523 [DEBUG] No users specified
2021-10-06 10:08:37,523 [DEBUG] No sources specified
 ... [successfully installs some files from S3 ... ]

2021-10-06 10:08:37,621 [DEBUG] Writing content to /tmp/phpmyadmin.tgz
2021-10-06 10:08:37,621 [DEBUG] Retrieving contents from https://www.phpmyadmin.
net/downloads/phpMyAdmin-latest-all-languages.tar.gz
2021-10-06 10:08:37,640 [ERROR] SSLError
Traceback (most recent call last):
  File "/usr/lib/python3.7/site-packages/cfnbootstrap/packages/requests/packages
/urllib3/connectionpool.py", line 544, in urlopen
    body=body, headers=headers)
  File "/usr/lib/python3.7/site-packages/cfnbootstrap/packages/requests/packages
/urllib3/connectionpool.py", line 341, in _make_request
    self._validate_conn(conn)
  File "/usr/lib/python3.7/site-packages/cfnbootstrap/packages/requests/packages
/urllib3/connectionpool.py", line 762, in _validate_conn
    conn.connect()
  File "/usr/lib/python3.7/site-packages/cfnbootstrap/packages/requests/packages
/urllib3/connection.py", line 238, in connect
    ssl_version=resolved_ssl_version)
  File "/usr/lib/python3.7/site-packages/cfnbootstrap/packages/requests/packages/urllib3/util/ssl_.py", line 265, in ssl_wrap_socket
    return context.wrap_socket(sock, server_hostname=server_hostname)
  File "/usr/lib64/python3.7/ssl.py", line 423, in wrap_socket
    session=session
  File "/usr/lib64/python3.7/ssl.py", line 870, in _create
    self.do_handshake()
  File "/usr/lib64/python3.7/ssl.py", line 1139, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1091)
...

but, if I log into the machine, downloading with wget works just fine, EDIT no longer true: so I don't think it's a problem on the remote site, I think it's something with cfn-init or the associated Python scripts.
EDIT: From a different autoscaling group, also created by CloudFormation, the remote downloads work:
...
2021-10-07 04:21:10,855 [DEBUG] Writing content to /tmp/mysql80.rpm
2021-10-07 04:21:10,855 [DEBUG] Retrieving contents from https://dev.mysql.com/g
et/mysql80-community-release-el7-2.noarch.rpm
2021-10-07 04:21:11,425 [DEBUG] Setting mode for /tmp/mysql80.rpm to 000600
2021-10-07 04:21:11,425 [DEBUG] Setting owner 0 and group 0 for /tmp/mysql80.rpm
...

So, it's successfully downloading from https://dev.mysql.com/, but failing with an "expired certificate" from https://www.phpmyadmin.net, even though wget and going directly there through a browser don't show any errors.
end EDIT
Any idea on how to debug this?
Answer: Short answer:
Use openssl to find if there is an expired certificate:
openssl s_client -showcerts -connect <falingwebsite.com>:443 | grep "certificate has expired"
Get the new, unexpired certificate and attach it to the AWS package ca_bundle:
cat <newcert>.pem >> /path/to/your/python/env/lib/python3.9/site-packages/cfnbootstrap/packages/requests/cacert.pem
Long answer:
I ended up writing some python scripts to try and download the server side certificate, to see if there was something going awry with the download. I never did get the certificates directly downloaded with urllib3, but while chasing that down on StackOverflow, @clockwatcher discovered the actual problem, and it seems likely it will affect others, and not just with phpMyAdmin.
It has to do with the DST Root CA X3 Expiration, which happened on September 30th. AWS does not include the new certificate in their bundled approved certificates, so you have to manually add the new one.
You can grab the self-signed ISRG Root X1 pem file from LetsEncrypt, and then add it to cfnbootstrap's ca_cert.pem file, as per above.
Now, this solves the problem in the case where you have a running machine; however, it's still an issue for autoscaling groups, as there's no easy way to use the
  AWS::CloudFormation::Init:
    config:
    files:
        /path/to/file:
          source: https://somewhere.using.letsencrypt.com/file

behavior. So, anywhere in your CloudFormation templates using that paradigm, will need to be rewritten so that both the file you actually want and the LetsEncrypt certificate are downloaded with wget as part of the commands: section. For example,
        01_get_phpmyadmin:
          command: !Join ["",
                       ["wget -O  phpmyadmin.tgz ",
                        "https://www.phpmyadmin.net/downloads/",
                        "phpMyAdmin-latest-all-languages.tar.gz"]]
          cwd: /tmp


bind structured arraylist to database

Question: I have an arraylist
ArrayList backupSpecList = new ArrayList();

And a structure:
public struct BackupSpecEntry
{
   //for Multiple BACKUP_SPEC_EXCLUDE_PATHS
   public string path;
   public string inclExcl;
   public byte inclExclFlags;
   public bool indexContents;
   public int serverBackupSpecId;
   public int freq;
   public int retention;

   //for Multiple BACKUP_SPEC_EXCLUDE_FILE_NAMES

   public BackupSpecEntry(string Path, string InclExcl, byte InclExclFlags, bool IndexContents,
    int ServerBackupSpecId, int Freq, int Retention)
   {
      path = Path;
      inclExcl = InclExcl;
      inclExclFlags = InclExclFlags;
      indexContents = IndexContents;
      serverBackupSpecId = ServerBackupSpecId;
      freq = Freq;
      retention = Retention;
   }
}

I put this structure in the arraylist and send it to the next page as a session
Session["BackupSpecList"] = backupSpecList;

I retrieve this on the next page as
ArrayList jaja = (ArrayList)Session["BackupSpecList"];

All this is happening perfect, but I need help to put this in the database.
Can someone please guide me? Thanks.
Comment: Use a System.Generic.List instead.
Comment: Ugh- .Net 1.1, right?  Otherwise, tsk tsk.
Comment: If this is 3.5 you *really* don't need `ArrayList`.
Comment: so how should i go about doing it..??
I did arraylist because there are many structured values.
One structure is for one row...
Comment: To provide an answer, we need to know what kind of database you are using and what database access technology you plan to use with it.
Answer: Assuming you want to insert or update your database with the contents of your struct, then ADO.NET is a good place to start.  Here is a good tutorial that walks you through the basics of reading, updating and inserting against a SQL Server database.  There is also the official MSDN site for more in depth info.
Answer: Using .NET 3.5 you have the option of using the Entity Framework, or LINQ to SQL .  I recommend the latter for a beginner.  This way you get all the database plumbing done for you, all you have to do is bind and enjoy.  Please note that you don't have to know much at all about LINQ to use the infrastructure.
The normal route to using LINQ to SQL is to create your database entities first, and let Visual Studio generate objects for you based on them.  Here you would create a BackupSpecEntry table, and follow one of these tutorials for setting up data binding to LINQ to SQL Classes:

Data Binding using LINQ to SQL in
C#
LINQ to SQL Databinding to
ASP.NET
LINQ to SQL (Part 5 - Binding UI
using the ASP:LinqDataSource
Control)

I have no guarantee of the quality of the above articles (except for ScottGu's).  I just quickly picked them out of a search because the looked appropriate.
To add your own functionality to the generated BackupSpecEntry class, you can derive your own class from the generated one, or use a partial class.  I recommend using partial classes over inheritance whenever possible, because that is how Microsoft intend us to extend the generated classes.
Answer: What you need is called a data-persistence layer. In .NET the best way to access data stored in Relational Database Management Systems (e.g. SQL Server) is ADO.NET. It provides the low-level nuts and bolts to do so.
All Kinds of data-persistence layers work with ADO.NET internally, but provide abstractions on top of it.
From the phrasing of your question (your using objects to represent you applications data) I suggest you use a Data Mapper. Such a Data Mapper maps between your objects and the database. Since you probably use an RDBMS you'll need an Object-Relational-Mapper (ORM).
There are several options available. Since you use .NET Framework 3.5 you can use Linq-To-Sql or the Entity-Framework that are both provided by Microsoft and have good IDE integration. Other options are NHibernate etc. There is lots of information about that here on SO.

bind structured arraylist to database


MySQL Service Not Starting

Question: I installed MySQL 5.1.65 on Windows 2000 Server and it got properly installed for the first time. After some time I uninstalled it, deleted all the installation files and then wasn't able to finish the installation. It didn't give me any error, just the installer would stop responding while starting MySQL service. I tried at least 5 times but no luck.
I also tried selecting different service name while installing, but that too didn't help. ANy idea how can I get this sorted out ?
Comment: You should check for the log files. They are usually in the data directory. You should have a file named ".err"
Comment: [See here](http://www.windowsvalley.com/uninstall-mysql-from-windows/)it could help you
Answer: I had this issue a while back, if your installing the complete package install the minimum features, and this should work. Theirs a bug in MySQL that doesn't allow it to reinstalled on certain machines and versions of windows without reinstalling the OS.

MySQL Service Not Starting


Enable Visual styles on windows and buttons for wxpython

Question: In windows 7 there is a setting I can set called "Use visual styles on windows and buttons" however the change in there does not reflect on wxPython.
I am attempting to write a dialog box which would look as native as possible.
If I open a dialog in Windows 7 i.e. the "Run" dialog when visual styles are enabled the background of the dialog is white and there is a separator. When the visual style is off then the whole dialog is grey.
None of this is reflected in wxpython, wxpython produces a dialog with a grey background regardless of whether the visual styles are enabled or disabled.
Note: This is also true for wx.Panel where sub-classing it regardless of visual style defaults to always using a grey background (unless the user changes the default)
Is there a way to enable visual styles for wxpython applications?
It seems that wx.Lua has this functionality: http://sourceforge.net/p/wxlua/svn/195/
Also the wxWidgets library states support for it: WxWidgets visual style
this maybe a bug/missing functionality in the wxpython build taken from: wxPython
Visual styles http://msdn.microsoft.com/en-gb/library/windows/desktop/bb773187(v=vs.85).aspx

Windows XP and later operating systems support a feature called visual styles that enables the appearance of common controls to change based on the theme chosen by the user. Prior to Windows 8, you must specifically configure your application to use visual styles; otherwise, the application's common controls are always rendered in the style associated with the Windows Classic theme, regardless of the currently selected theme.

Visual style on

Visual style off
Answer: wxPython does what is native by default because it uses native widgets. There are some custom widgets in wx.lib that may or may not look native. I am guessing you are sub-classing wx.Dialog. This is probably normal / native behavior for a subclassed wx.Dialog. If you want something more generic, then you should use wx.MessageDialog.
Comment: It seems that the wxpython is following what you are saying which is the native style. When the visual styles are turned on, then each widget ignores the personalised colour set by the user and uses a constant colour which is known to look good regardless of user choice.


A simple mathematical induction proof.

Question: Let n be a natural number, and let $ f:\{ i \in \mathbb{N}  : 1 \le i \le n\} \rightarrow\mathbb{N} $ be a function. Show that there exists a natural number M such that $f(i) \le M $ for $1 \le i \le n $
We prove this by induction on n, when n = 1, $f(i) \le M $ for $1\le i \le1$. since if M := 1, the above holds.
now suppose that we have already proven the proposition for some $ n \ge 1$, we have to prove it for $n++$,
by the induction hypothesis, we know that there exists a natural number $ M $ such that $f(i) \le M $ for $1 \le i \le n $, in particular there must exist a natural number $ M+1$, in which case $f(i) \le M +1 $ for $1 \le i \le n++ $
Could someone shed some light on whether i have logically proved this?
Comment: No, you have not proved this. It looks like you are assuming that $f(n+1)=M+1$, which is by no means true.
Answer: You haven't proved it because neither your base-case argument nor your induction step argument is correct.
For example, when $n=1$, suppose $f$ is the function that sends $1$ to $5$.  You claim that if $M=1$ then $f(i)\le M$ when $i=1$.  But $f(1)=5>1=M$.  What do you need to do to fix this?
As for the induction step, when $n=2$, $f$ might be the function that sends $1$ to $1$ and $2$ to $1$.  So if we choose $M=1$, then $f(i)\le M$ for each $i$.  But now,, if $g$ is the function that sends $1$ to $1$, $2$ to $1$ and $3$ to $5$, then it is not the case that $f(i)\le M+1$ for each $i$.  Indeed $f(3)=5>2=M+1$.  What do you need to do to fix this?
Comment: AH would i introduce a new variable. say M' and let M' be the largest value taken by either M or f(n+1), using the fact that the proposition is true for n? since  M is the upper bound for when n is true
Comment: $M = f(1)$ for the first question. I'm not so sure about the second, would $M := f(n+1)?$
Comment: @HMPARTICLE **Hint:** suppose $f(i)=1000$ for $i=1,\dots,n$ and $f(n+1)=1$.  Does setting $M=f(n+1)$ work in that case?  And how are you going to use the fact that the proposition is true for $n$ to deduce that it's true for $n+1$?
Comment: You're very close though!
Comment: @HMPARTICLE Yes, that's basically the right idea.  Try and write the whole proof out in full now!
Comment: We prove this by induction on n, when n = 1, f(i)≤M for 1≤i≤1.if we choose M := f(1), the above holds.

now suppose that we have already proven the proposition for some n≥1, we have to prove it for n++, by the induction hypothesis, we know that there exists a natural number M such that f(i)≤M for 1≤i≤n, in particular there must exist a natural number M':=max{M,f(n+1)}, in which case f(i)≤M' for 1≤i≤n++. I honestly feel like this proves it?
Comment: Yes - well done.  That's the right answer.
Comment: As a small nitpick - it's better to write something like this: 'If $M\ge f(n+1)$, then let $M'=M$; otherwise, let $M'=f(n+1)$', rather than just writing $M'=\max\{M,f(n+1)\}$.  The reason for this is that the point of this induction proof is to show that you can take the $\max$ of an arbitrary finite set; indeed, if you know this, then you can just let $M=\max\{f(1),\dots,f(n)\}$ and you're done immediately.
Comment: No, thank you, i shall alter my notes asap, could i ask you to look at another proof? i posted it on this site,http://math.stackexchange.com/q/1076474/197848 . @Donkey_2009
Answer: Unless you know something about $f$ that you haven't written, you haven't proven it.
In you base step you say that $M=1$ makes it hold, but $f$ might be $2$ for all natural numbers.
As Ian points out in his comment, you induction step also uses assumptions about $f$ that you don't know.
A hint on how you might show it:
$\{i\in\mathbb N:1\leq i\leq n\}$ is a finite set.

A simple mathematical induction proof.


Connecting Audio interface to amp head to use 4x12 Cabinet as a monitor?

Question: Forgive me if this is a stupid question but I want to make use of my old 6505 head and cab as a dedicated guitar monitor.
In theory I'd like to Guitar > AI > Bias FX2 > AI line out > input head(or effects loop?) > Cab
Thoughts? Suggestions?
I don't really want to expand my pedal board any further
Answer: In my personal experience (read: for my personal taste) amp cabinet sims in the Bias FX2 will sound bad fed into a guitar amp: they are better targeted to a full-range audio system. The pedal effects (etc) will otherwise sound fine. You will want to adjust your interface output levels such that with no effects defined, the audio levels are the same with the interface in bypass mode (disabled).
I only play at home for personal gratification and was using only PC-based sims but have recently gone to a simplified pedal setup with the interface between a compressor and a tube-screamer type device. the hard part about a mixed environment like this is that all the effect on the interface are inserted into the chain as a block.
If you are only going to use the Bias (no physical pedals), you will want to use what is called a re-amp device between the "AI-out" and the amp-head in for impedance reasons. I used a DIY kit called "line2amp," but there are several commercial options. I think you will need the reamp device if you output to another pedal also (I do this because I think it sounds better), but I do not know if it is required.
If you are going to use this outside of a DAW playback setup (which has track envelopes), you will probably want a midi expression pedal (or several). Don't know if Bias supports MIDI input, but if it does, you will want one for wah or volume. Most audio hosts will allow you to tag a midi input to any possible pedal parameter and often several at once. I use a usb MIDI 3-button pedal and a midi expression pedal.
Comment: For reference, my chain is: guitar > fuzz > compressor > interface {PC MAGIC} > re-amp box > tube pedal > 50 watt amp set (mostly) clean.


Node.js app doesn't load when location path is not /

Question: For some reason, my Node.js app running on 127.0.0.1:8081 requires /.
If I start with this, BOTH / and /projectb are able to load the page.
server {
        listen 80;

        location / {
                proxy_pass http://127.0.0.1:8081;

                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";
        }

        location /projectb {
                proxy_pass http://127.0.0.1:8081/;

                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";
        }
}

When I change it to this, /projectb is no longer able to fully load the page. When I look at the network tab, some (but not all) requests fail, for example some images, .js, some wrong endpoints.
server {
        listen 80;

        location /somethingelse {
                proxy_pass http://127.0.0.1:8080/;

                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";
        }

        location /projectb {  # I'd expect this to still work.
                proxy_pass http://127.0.0.1:8081/;

                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";
        }
}

To summarize, it works when I hit the port directly 123.456.78.910:8081, and when I have BOTH / and /projectb proxy to http://127.0.0.1:8081/, but not when I proxy to /projectb by itself.
Why might this be the case?
Comment: What requests failed?
Answer: From nginx docs on proxy_pass:

If the proxy_pass directive is specified with a URI, then when a
request is passed to the server, the part of a normalized request URI
matching the location is replaced by a URI specified in the directive:
location /name/ {
    proxy_pass http://127.0.0.1/remote/;
}

If proxy_pass is specified without a URI, the request URI is passed to
the server in the same form as sent by a client when the original
request is processed, or the full normalized request URI is passed
when processing the changed URI:
location /some/path/ {
    proxy_pass http://127.0.0.1;
}

In your 2 examples, the latter one provides a URI (terminating / in the URL), which makes the URI being normalised, this would make relative links in js/css files to break. Remove the /:
server {
        listen 80;

        location /somethingelse {
                proxy_pass http://127.0.0.1:8080;

                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";
        }

        location /projectb {
                proxy_pass http://127.0.0.1:8081;

                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";
        }
}


How to get min(date), max(date) and its quantity from the same table?

Question: I am new in this sql coding, I am trying to learn something new. Hence I create a delivery table with a few attribute like item code, delivery date, delivery quantity. So
how to get first delivery date (min date) and the quantity delivered and also latest delivery date (max date) and its quantity delivered from the same table?
I tried to use union clause to get the min (date) and max (date) with its quantity. But the output doesn't display like what I imagined
Here is what I tried
SELECT item_code , MAX(date) AS "Latest_delivery_date", quantity
FROM delivery
WHERE item_code='110192'
GROUP BY item_code
union all
SELECT item_code , MIN(date) AS "First_delivery_date", quantity
FROM delivery
WHERE item_code='110192'
GROUP BY item_code;

I want the output to look something like
Answer: One way to solve this is to make a derived table of the MIN and MAX delivery dates for an item and then JOIN that back to the table to find the quantities for those dates. For example:
SELECT m.item_code,
       m.min_date AS "First_delivery_date",  d1.quantity AS "First_quantity",
       m.max_date AS "Latest_delivery_date", d2.quantity AS "Latest_quantity"
FROM (SELECT item_code, MAX(date) AS max_date, MIN(date) AS min_date
      FROM delivery
      GROUP BY item_code) m
JOIN delivery d1 ON d1.item_code = m.item_code AND d1.date = m.min_date
JOIN delivery d2 ON d2.item_code = m.item_code AND d2.date = m.max_date

Demo on dbfiddle
To select results for one particular item_code, add a WHERE clause to the derived table. That will restrict the results of that table to only the row for that item_code, making the subsequent JOINs more efficient. For example:
SELECT m.item_code,
       m.min_date AS "First_delivery_date",  d1.quantity AS "First_quantity",
       m.max_date AS "Latest_delivery_date", d2.quantity AS "Latest_quantity"
FROM (SELECT item_code, MAX(date) AS max_date, MIN(date) AS min_date
      FROM delivery
      WHERE item_code = '010997'
      GROUP BY item_code) m
JOIN delivery d1 ON d1.item_code = m.item_code AND d1.date = m.min_date
JOIN delivery d2 ON d2.item_code = m.item_code AND d2.date = m.max_date

Comment: what if there is a lot of items and II want to filter the item code? where should I place the item_code ='010997'?
Comment: @newbeginnner it would be most efficient to put the `WHERE item_code = '010997'` into the derived table. That will cut down the results from that table to 1 row and thus make the subsequent JOINs much faster.
Comment: I have tried it, and it works. The code is easier to be understand. Thanks for your help, sir
Comment: @newbeginnner unfortunately you can't accept two answers! I'm glad you've got a working solution.
Comment: @newbeginnner just add it to the derived table. See this demo https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=42e6dd3ef6ce9238292518ac319c4043
Answer: You can use analytical functions as the following:
SQL> CREATE TABLE DELIVERY (
  2      ITEM_CODE   NUMBER,
  3      DATE_       DATE,
  4      QUANTITY    NUMBER
  5  );

Table created.

SQL>
SQL> INSERT INTO DELIVERY VALUES (
  2      110192,
  3      DATE '2019-05-05',
  4      30
  5  );

1 row created.

SQL>
SQL> INSERT INTO DELIVERY VALUES (
  2      110192,
  3      DATE '2019-01-01',
  4      10
  5  );

1 row created.

SQL>
SQL> INSERT INTO DELIVERY VALUES (
  2      110192,
  3      DATE '2019-10-10',
  4      25
  5  );

1 row created.

SQL>
SQL> INSERT INTO DELIVERY VALUES (
  2      110192,
  3      DATE '2019-08-08',
  4      19
  5  );

1 row created.

SQL>
SQL> SELECT DISTINCT
  2      ITEM_CODE,
  3      MIN(DATE_) OVER(
  4          PARTITION BY ITEM_CODE
  5      ) AS FIRST_DELIVERY_DATE,
  6      MAX(QUANTITY) KEEP(DENSE_RANK FIRST ORDER BY DATE_) OVER(
  7          PARTITION BY ITEM_CODE
  8      ) AS FIRST_QUANTITY,
  9      MAX(DATE_) OVER(
 10          PARTITION BY ITEM_CODE
 11      ) AS LATEST_DELIVERY_DATE,
 12      MAX(QUANTITY) KEEP(DENSE_RANK FIRST ORDER BY DATE_ DESC NULLS LAST) OVER(
 13          PARTITION BY ITEM_CODE
 14      ) AS LATEST_QUANTITY
 15  FROM
 16      DELIVERY;

 ITEM_CODE FIRST_DEL FIRST_QUANTITY LATEST_DE LATEST_QUANTITY
---------- --------- -------------- --------- ---------------
    110192 01-JAN-19             10 10-OCT-19              25

SQL>

Cheers!!
Comment: this works! Since I am new in this sql coding, I didn't know about the Over Partition By clause. Thank you for showing me something new.


Is there a way to set the first enum value to 1 in protobuf?

Question: The first enum value needs to be 0 in protobuf, but this does some trouble in a dropdown component of Primeng.
Is there a way to set the first enum value to 1 ?
Answer: According to the documentation, Protobuf is not allowed to set the first enum value to other value except 0:

As you can see, the Corpus enum's first constant maps to zero: every enum definition must contain a constant that maps to zero as its first element. This is because:

There must be a zero value, so that we can use 0 as a numeric default value.
The zero value needs to be the first element, for compatibility with the proto2 semantics where the first enum value is always the default.
Comment: This is correct. I solved my problem by introducing a 'default' enum that gets filtered out when I fill the dropdown.


Como sabe qual a linha da planilha, no qual o item do listview selecionado está?

Question: Preenchi meu ListView e apliquei um filtro, para que o usuário possa escolher os valores a serem observados.
No entanto, preciso que o usuário possa adicionar informações ao item selecionado e que esses valores sejam salvos na planilha fonte do banco de dados na mesma linha e em uma coluna vazia especifica através do botão "ADD ACTION".
Eu tentei de várias maneiras e não sei se meu código também está fazendo sentido...
Obrigado a todos!
'''
Private Sub CommandButton1_Click()

Dim lineDp As Integer
Dim Dp As Worksheet
Dim Ultima_coluna As Long
Dim ColH As ColumnHeader
Dim Index As Long

Set Dp = Sheets("Details Pipeline")

'Number of Rows count
 lineDp = Dp.Range("A100000").End(xlUp).Row

'Number of Colums count - Ctrl + Shift + End
Ultima_coluna = Dp.Cells(lineDp, Dp.Columns.Count).End(xlToLeft).Column

For i = 4 To Ultima_coluna

If Dp.Cells(3, i).Value <> "" Then

For j = 1 To ListView1.ListItems.Count

    If ListView1.ListItems.Item(j).Checked Then

        txt_id = ListView1.ListItems.Item(j)
        Dp.Cells(j, i) = TextBox6.Text

     End If

Next j

End If

Next i

'''
Comment: Crie um [mcve] com uns dados de exemplo numa tabela.
Answer: Você pode carregar a lista atraves de um For e a primeira coluna colocar a linha que está o registro, porém você deixa essa coluna com a largura zerada na tabela.
Ex:
Private Sub CarregarListaEmail()
Dim ws As Worksheet
Dim ul As Integer

Set ws = ThisWorkbook.Sheets("Emails")
ul = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

With lstEmail
    .Clear

    .ColumnCount = 7 'NÚMERO DE COLUNAS QUE CONTEM SUA TABELA

    ' OBSERVA QUE O PRIMEIRO '0 PT' É DA COLUNA QUE REPRESENTA O NÚMERO DA LINHA
    .ColumnWidths = "0 pt;170 pt;138,95 pt;38 pt;110 pt;60 pt;0 pt"

    If ul > 1 Then
        For Each lin In ws.Range("A2:A" & ul)
            .AddItem lin.Row
            .List(.ListCount - 1, 1) = lin.Value
            .List(.ListCount - 1, 2) = lin.Offset(0, 1).Value
            .List(.ListCount - 1, 3) = lin.Offset(0, 2).Value
            .List(.ListCount - 1, 4) = lin.Offset(0, 3).Value
            .List(.ListCount - 1, 5) = lin.Offset(0, 4).Value
            .List(.ListCount - 1, 6) = lin.Offset(0, 5).Value
        Next lin
    End If

End With

End Sub
Api quando você quiser manipular o registro na planilha é só usar o número da linha que da primeira coluna.
Meu exemplo é com ListBox, porém a lógica será a mesma para ListView.
Usei esse exemplo, pois tenho fácil aqui.


clearcase snapshot hijacked files : how to checkout/checkin changed files

Question: Clearcase sucks a lot. It seems I cannot just save modifications to my project quickly. By quickly I mean in less than 1 second.
The solution I have found is to use the combo clearcase + git. I'm using snapshots views because I can easily hijack my files without having to checkout all the files in my project every time I want to do refactoring.
The problem is, when I play with git and navigate between new and old versions, clearcase think all the files are hijacked. Then I need to do the following.

cleartool update
cleartool ls -recurse | grep "hijacked" | xargs cleartool diff -prev [...] > changed
cat changed | xargs cleartool co -nc
cat changed | xargs cleartool ci -c 'some words...'
rm **/*.keep
git checkout .

The operation consisting of "clearcase push" which takes about 2 seconds with git will last for at least 10 minutes. I see only two explanation regarding this issue:

I really do not know how to use clearcase
Clearcase really sucks!

Does somebody knows how to quickly checkout then checkin modified hijacked files with Clearcase not UCM version ?
Edit:
Following the advices of Vonc I made a script that uses clearfsimport:
#!/bin/bash/
OUT="$(mktemp -d)"
DST=/vob/project_root/
echo -e "\nCreating temporary folder..."
echo $OUT

echo -e "\nCopying relevant elements..."
find . | grep -E '.*?\.(c|h|inc|asm|mac|def|ldf|rst)$' | xargs -I % cp --parents % $OUT
DOUT=$(cygpath -d $OUT/*)
DDST=$(cygpath -d $DST)
echo -e "\nImporting new elements to cleacase..."
clearfsimport -rec -unco -nset $DOUT $DDST

echo -e "\nRemoving temporary files..."
rm -rf $OUT

The reason why I need to make a copy of my repository is that clearfsimport cannot directly exclude files or directories and wildcard options does not work with this tool. It takes a directory tree as is. Also I do not want to remove all my unversionned files such as object files or even the .git from my working directory.
I think I can make this script much better by identifying with git all the files that changed since the last execution of my script. Might be a bit tricky to do...
Also I can set my matching files pattern using .gitignore
Perhaps others already made such scripts...
Comment: Great script and feedback. Regarding the modified files, maybe http://stackoverflow.com/a/1552353/6309 or http://stackoverflow.com/a/8016831/6309 could help?
Answer: Your sequence for updating ClearCase file from a git working tree is pretty much the "optimal" one, meaning it won't get much faster.
One alternative I have been playing with when using ClearCase and Git is clearfsimport, with 2 ClearCase views.

one snapshot view is for updating a set of files which are then make hijacked (for a git working tree to use)
one snapshot (or dynamic actually) view to be the recipient, the destination of the changes done in the first working tree.

clearfsimport allows you to take any working tree (managed or not by ClearCase, it doesn't care), and import it in a ClearCase view (it can be a dynamic view, by the way), and:

checkout only the modified files
leave the identical files alone
remove / add the files in the ClearCase view, which were deleted/created in the working tree

It is a process more efficient than diff'ing everything, and it should be much faster.
That doesn't mean it is fast.
It is still, after all, ClearCase.
Comment: @coin yes, `clearfsimport` is made to import a directory tree as is (cleaned up beforehand), not to be used as you want: cleanup first the tree structure, then you can use the `clearfsimport`. As said in the man page http://publib.boulder.ibm.com/infocenter/cchelp/v7r0m1/index.jsp?topic=/com.ibm.rational.clearcase.cc_ref.doc/topics/clearfsimport.htm: "For each path name, the leaf of the path name is imported into the target VOB. For example, `/usr/src/lib/foo.c` is imported into the VOB `/vobs/mylib` as `/vobs/mylib/foo.c` or into the VOB `/bigvob` as `/bigvob/foo.c`."
Comment: I'm confused with `clearfsimport`. It tries to check all the thousands files in my .git folder. How can I ignore .git and obj/ folders ?
Comment: @coin simply make sure the .git isn't store in a working tree you intent to import in ClearCase. Remember that `GIT_DIR` can be set up in order to reference a .git outside of a working tree. See also http://stackoverflow.com/a/10824664/6309
Comment: This doesn't solve the case of obj/*.o and all temp files. I made a HUGE list with wildcard. This is ugly but it seems to works...
Comment: And I agree with you "It is much faster. That doesn't mean it is fast" :(
Comment: @coin or you could do *several* clearfsimport, in order to not import the wrong subfolders.
Comment: Arf! If I use the syntax: `clearfsimport -rec -unco -nset ~/.../*.c /ccase/vob/project/` it will put all the new elements to the root of my dest folder. `...` doesn't work as I expected. Any suggestion?


How to count 6/8

Question: How do I count with metronome for 6/8 measure especially for this music?

Thanks,
Nader
Comment: Seems like much ado about nothing.  It's quite obviously 6/8 with triplets, as @nath answered.  Why in the world anyone is trying to make it into something else is beyond me!
Comment: @Fugu 3/4 would lend it a triple feel (three beats per measure) instead of the duplex feel of 6/8. 6/4 could work, but not 3/4! (Note also that doubling the note values puts it in 6/4. It already fits in 3/4.)
Comment: I wonder very much about this being labelled 6/8. Unless the tempo is rather fast I'd say this is better served being written as 3/4 with all of the note values doubled. That said, if it really is supposed to be 6/8 then you still just count it like you normally would.
Comment: @Fugu Of course the asker is not in a position to change the time signature, but even if they were, 6/8 is a march feel and 3/4 is a waltz feel, so they are not equivalent time signatures, regardless of any tuplets present.
Comment: @Richard I think if you have sixteenth note triplets in one voice and a quarter note-eighth note repeating pattern in the other then counting this as compound (double) is weird unless the tempo is fast. Look at the two answers - both suggest counting the subunits of three. That together with my own intuition that you're going to have to count this as three unless the tempo is brisk suggests to me that this is not compound time. 6/4 doesn't play into this at all and doesn't really have anything to do with my suggestion.
Comment: @ToddWilcox I agree that they're not equivalent; otherwise there'd be little point in saying "this one seems wrong". I only brought it up to indicate that I feel that the question asker's issues counting the piece are perhaps based on the (questionable) choice to call this 6/8.
Comment: @Fugu Ummm it says 6/8 right on the score! Are we somehow looking at two different images? Also beaming and phrase marks.
Comment: @ToddWilcox I see the score. 6/8 was a choice made by whoever composed/notated this and I think it's an odd choice, that's all, like if someone wrote a piece in 4/4 but had all of the stresses grouped in threes for the entire piece. It makes it more difficult to count than it needs to be.
Comment: @Fugu Respectfully, I'm still confused by what you're saying. This piece **is** stressed "grouped in threes," hence the compound feel, hence 6/8 and not 3/4.
Comment: @Fugu - it would sort of work in 3 time, but not 3/4. Two lots of 3/8 in each bar is good - bringing it back to 6/8. But the OP still needs to be able to count those triplet semis.
Answer: Wow, that's a good one! Triplets on triplets! It's sort of compound compound time.
6/8 is 1 2 3 4 5 6, taking three counts from each of the two main emphasised beats in each bar. So 1** 2** becomes 1 2 3 4 5 6. but this subdivides again, with some of the counts becoming triplets for themselves.
What I'd do is re-divide each bar into a sort of 12/8 feel. so a gentle 1,2,3,4 count, which would then be sub-divided into triplets. Like 1 2 3 2 2 3  3 2 3 4 2 3  5 2 3 6 2 3  This then puts it all into a fair timing grid.
I think at this point, the metronome would need to be set so each click represented the bold count number, the whole thing could be counted and played more easily. As in each click is the first of each 'sub-triplet'.
Comment: To keep it clear, I've always counted 6/8 as `one-and-uh two-and-uh` because the feel should be a compound march and I want to keep my thinking in a "one two one two" mode. For the triplets, I would probably invent a syllable (*end*) and count `one and-ee-uh end-ee-uh two and-ee-uh end-ee-uh`, but instead I think I would rather just count `one-and-uh two-and-uh` and fit the triplets evenly in the count. Not every rhythmic element should have its own count - that's not what counting is for.
Answer: this is a really nice one, I would proceed as follows:

would you mind adding the title and maybe the Op.Nr?
Answer: Since it's a 6/8, try to convey the feel of a duplet rhythm.
1) To count a 6/8 is 1 + + 2 + +. Start slow with the metronome with 1 beat equivalent to 1 quaver note; to get the correct rhythm.
2) To count the rhythm of your piece is to replace '+' with e.g. banana or any 3-syllables words.
3) New counting will be: [1] ba-na-na ba-na-na [2] ba-na-na ba-na-na...etc.
Comment: Not *any* three syllable word. 'Ba**na**na' generally has its emphasis on the middle syllable. As such, it's not particularly useful as the word to use. That needs to be a three syllable word with emphasis on the *first* syllable. **Co**conut, for example.

How to count 6/8


face detection does not work

Question: I'm using OpenCV on a 64-bit Win 7, with VS2010 (C++).
I've tried so many source codes for detecting faces, they compile and run, but no detection takes place.
I'll give two examples:
1) In this first example, I'm using source code from:
http://www.bsd-noobz.com/opencv-guide/60-3-face-detection
I get the picture, but not the squares.
2) In this second example, I'm using code that I had downloaded some time ago (can't remember where from). This one shows the stream from the webcam, and again no detection is happening.
#include "stdafx.h"
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"

#include <iostream>

using namespace std;
using namespace cv;

 /** Function Headers */
 void detectAndDisplay2( Mat frame );

 /** Global variables */
 String face_cascade_name = "haarcascade_frontalface_alt.xml";
 String eyes_cascade_name = "haarcascade_eye_tree_eyeglasses.xml";
 CascadeClassifier face_cascade;
 CascadeClassifier eyes_cascade;

//RNG rng(12345);

 /** @function main */
 int main()
 {
   CvCapture* capture;
   Mat frame;

   //-- 1. Load the cascades
   if( !face_cascade.load( face_cascade_name ) ){ printf("--(!)Error loading face cascade\n"); return -1; };
   if( !eyes_cascade.load( eyes_cascade_name ) ){ printf("--(!)Error loading eye cascade\n"); return -1; };

   //-- 2. Read the video stream
   capture = cvCaptureFromCAM( 1 );
   if( capture )
   {
     while( true )
     {
   frame = cvQueryFrame( capture );

   //-- 3. Apply the classifier to the frame
       if( !frame.empty() )
       { detectAndDisplay2( frame ); }
       else
       { printf(" --(!) No captured frame -- Break!"); break; }

       int c = waitKey(10);
       if( (char)c == 'c' ) { break; }
      }
   }
   cvReleaseCapture(&capture);
   cvDestroyWindow("Capture - Face detection");

   return 0;
 }

/** @function detectAndDisplay */
void detectAndDisplay2( Mat frame )
{
  vector<Rect> faces;
  Mat frame_gray;

  cvtColor( frame, frame_gray, CV_BGR2GRAY );
  equalizeHist( frame_gray, frame_gray );

  //-- Detect faces
  face_cascade.detectMultiScale( frame_gray, faces, 1.1, 2, 0|CV_HAAR_SCALE_IMAGE, Size(30, 30) );

  for( int i = 0; i < faces.size(); i++ )
  {
    Point center( faces[i].x + faces[i].width*0.5, faces[i].y + faces[i].height*0.5 );
    ellipse( frame, center, Size( faces[i].width*0.5, faces[i].height*0.5), 0, 0, 360, Scalar( 255, 0, 255 ), 4, 8, 0 );

    Mat faceROI = frame_gray( faces[i] );
    vector<Rect> eyes;

    //-- In each face, detect eyes
    eyes_cascade.detectMultiScale( faceROI, eyes, 1.1, 2, 0 |CV_HAAR_SCALE_IMAGE, Size(30, 30) );

    for( int j = 0; j < eyes.size(); j++ )
     {
       Point center( faces[i].x + eyes[j].x + eyes[j].width*0.5, faces[i].y + eyes[j].y + eyes[j].height*0.5 );
       int radius = cvRound( (eyes[j].width + eyes[j].height)*0.25 );
       circle( frame, center, radius, Scalar( 255, 0, 0 ), 4, 8, 0 );
     }
  }
  //-- Show what you got
  imshow( "Processed", frame_gray );
  imshow( "Capture - Face detection", frame );

 }

I'd be really grateful if someone can help.
Comment: Make sure you have `haarcascade_frontalface_alt.xml` in the same folder like your program. For me, this codes works.
Comment: Thanks. The problem seems to have been with the Property Sheets. I opened a new project using new (correctly organized) property sheets that used the standard OpenCV libraries (rather than recompiling for 64-bit) and it worked.
Answer: This is a opencv project in github. This error stems from two issues that I can see.
1) Make sure you've installed the correct OpenCV version. I suggest this install guide… It worked well for me.
2) Then, make sure you have added haarcascade_frontalface_alt.xml to inside of the executable file – which should be in a folder like ../build/bin/haarcascade_frontalface_alt.xml when you built the project).

face detection does not work


Setting capitalization of the first letter on keyboard

Question: I have a button which presents an alert with a text field in it. When clicked on the button it automatically focuses in the text field and keyboard shows. However the letters in the keyboard start as lower-case. How can I fix that so it starts as upper-case?
Edit:
alertTextField.autocapitalizationType = .sentences

This was what I was looking for.
Comment: See https://stackoverflow.com/questions/45310261/swift3-uitextfield-in-uialert-validation-after-button-pressed for an example.
Answer: Try this
let mytextfield = UITextField()
mytextfield.autocapitalizationType = .allCharacters

Other types :


indefinite system for finding extreme values

Question: The function $f(x,y) = xe^y$ has a false system does this mean that there are no extreme values?
EDIT: false system not an indefinite system sorry for the confusion
Answer: Not sure what an indefinite system means in this context, but since $f(x,y) = g(x)h(y)$ your maximum occurs when both $g,h$ have their respective maxima. For the minimum, note that $g(x)$ and $h(y)$ are both unbounded as $x,y \to \infty$. Also, $h(y)=e^y \ge 0$, so let $(x,y) \to (-\infty,\infty)$.
UPDATE
You are right, to find the stationary points you have to solve
$$
\begin{pmatrix} 0 \\ 0 \end{pmatrix}
 = \vec{\nabla} f(x,y)
 = \begin{pmatrix} e^y \\ xe^y \end{pmatrix}
$$
and the first equation has no solutions. Therefore, there are no stationary points of $f(x,y)$. The reason for this can be explained like the original argument above.
Comment: It's the terminology we use in Dutch but I was actually mistaken. We were taught for finding the extrema we have to differentiate the function in respect to each variable, which would give the following system: e^y = 0 && xe^y = 0 and since e^y can never be 0, the system is considered "false", right? So in case the question was to find the extrema, my response would have to be that there are none? Anyways, thank you for your time!
Comment: @LLScheme thanks for the clarification, please see the updated answer.


Converter string em inteiro

Question: Não estou conseguindo converter o texto do meu TextBox em inteiro.
namespace Pag98_Exe1
{
    public partial class frmveiculos : Form
    {
        public frmveiculos()
        {
            InitializeComponent();
        }

        Veiculos veiculos = new Veiculos(); //Declarando a classe veiculos

        private void btnenviar_Click(object sender, EventArgs e)
        {
            if(mskTxtplaca.Text != "" && cbxmarca.Text != "" && txtanofabricacao.Text != "")
            {
                veiculos.Placa = mskTxtplaca.Text; //Atribuindo o valor de Placa ao texto do TextBox
                veiculos.Marca = cbxmarca.Text;
                veiculos.AnoFabricacao(int.Parse(txtanofabricacao.Text)); //Passando o valor do TextBox para inteiro e atribuindo ao TextBox
            }
        }
    }
}

Comment: Qual é o problema?
Comment: @bigown Gravidade Código Descrição Projeto Arquivo Linha Estado de supressão
Erro CS0029 Não é possível converter implicitamente tipo "string" em "int" Pag98_Exe1 C:\Users\home\Desktop\Trabalhos COTEMIG\Pag98_Exe1\Pag98_Exe1\frmveiculos.cs 28 Ativo
Comment: @bigown a linha do erro é a 3ª dentro da condição if
Comment: Já tentou Convert.toInt32() ?
Answer: Como o texto vem de um controle que o usuário pode digitar não há garantias que o texto pode ser convertido para inteiro, então tem que tentar fazer, se der certo faz o que deseja, caso contrário precisa tratar isso de alguma forma, emitir um erro, colocar um valor padrão, alguma coisa assim. Isso se faz com o método TryParse(). Outras soluções são falhas, não use a não ser que tenha certeza que o valor poderá ser convertido, o que não parece ser o caso. Tenho minhas dúvidas se o resto da lógica é adequada, mas não posso falar sem conhecer os requisitos.
private void btnenviar_Click(object sender, EventArgs e) {
    if(mskTxtplaca.Text != "" && cbxmarca.Text != "" && txtanofabricacao.Text != "") {
        veiculos.Placa = mskTxtplaca.Text;
        veiculos.Marca = cbxmarca.Text;
        int anoFabricacao;
        if (int.TryParse(txtanofabricacao.Text, out anoFabricacao) {
            veiculos.AnoFabricacao = anoFabricacao;
        } else {
            //aqui coloque o que deve fazer se a conversão falhar
        }
    }
}

Em C# 7 pode fazer um pouco mais simples:
private void btnenviar_Click(object sender, EventArgs e) {
    if(mskTxtplaca.Text != "" && cbxmarca.Text != "" && txtanofabricacao.Text != "") {
        veiculos.Placa = mskTxtplaca.Text;
        veiculos.Marca = cbxmarca.Text;
        if (int.TryParse(txtanofabricacao.Text, out var anoFabricacao) {
            veiculos.AnoFabricacao = anoFabricacao;
        } else {
            //aqui coloque o que deve fazer se a conversão falhar
        }
    }
}

Coloquei no GitHub para referência futura.
Comment: Muito boa a explicação, aproveitando, você sabe me dizer como deixar certos espaços de um text box mascarado para receber apenas um tipo de caractere ? Ex: Placa de veiculo (AAA-0000) a parte em que está as letras só recebe letras e a que estão os numeros apenas numeros
Comment: @CaioVieira dê uma olha no [tour], a gente é diferente de um fórum, então cada dúvida precisa estar em uma pergunta diferente para que ela possa ser avaliada independentemente por todo mundo e que possa ajudar outras pessoas que tenham o mesmo problema. Nem daria para responder apropriadamente em um comentário curto e com baixa capacidade de formatação. Mas parece estar no caminho certo em usar o {`MaskedTextBox`](https://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox(v=vs.110).aspx)
Comment: Obrigado pela força ai
Answer: Seu posto tá um pouco confuso, pelo o que eu entendi do código tenta essa solução:
veiculos.AnoFabricacao = int.Parse(txtanofabricacao.Text);

Comment: Deu certo meu amigo, obrigado pela ajuda
Comment: aceita a resposta ai
Comment: Só daqui a 5 min.

Converter string em inteiro


Scaled coeficients in mixed model

Question: I'm running a mixed model with two continuous predictor variables, using lme4. I got the following error:

Model is nearly unidentifiable: very large eigenvalue - Rescale variables?

When exploring the data, the problem I saw was that there were different scales (x1 were numbers less than 0, x2 were whole numbers greater than 20). So I scaled the variables, and the problem was over. However, I would like to know how to interpret the regression coefficients. I understand that with scaled variables, it's necessary to divide the coefficient between the sd of the selected variable, to be able to interpret them as usual. So I have these questions:

It's correct to use this in a mixed model (for individual level coefficients, I think))?
How can I do it in R?
Can the coef() function be used on a single variable to do this procedure, one by one? or is there another way?
Answer:
yes, scaling of regression coefficients works the same way in any linear-type model (linear models, linear mixed models, GLMs, GLMMs, ...)
if the log-likelihoods of the two fits are nearly identical (say, within 0.001 units of each other), then it's probably the case that the warning about the very large eigenvalue is a false alarm, and you can go ahead and interpret the unscaled model without worry. (If the large difference in scaling were actually causing numerical problems it's unlikely that the original model would fit just as well as the model with scaled coefficients.)
there are a variety of posts on Stack Overflow that give R solutions for retrieving unscaled coefficients from the scaled fit: e.g. here, here, here ...

Scaled coeficients in mixed model


How to add tags to View-created RSS feed?

Question: How to add tags to View-created RSS feed?
I have added some tags to each of my articles, but the RSS feed generated by Views does not show the tags.
Answer: You can include them in the fields for the view display. If they are taxonomy terms, you can add them from the views fields list.
Comment: but in RSS mode, it said, "The selected style or row format does not utilize fields."


Syntax error. Help with one small JS snippet :(

Question: Hey guys. I don't know much JS, but I wanted to do some quick work with jQuery.
But I've been staring at this for about an hour and I don't understand what I missed:

jQuery library is included at the beggining of the document.
Thanks.
Answer: Use parseInt function, not (int) casting
Comment: Be sure to use the `radix` parameter to force base 10 when using `parseInt()` --- `parseInt($("#qty_6035").val(), 10);`
Answer: Javascript is a dynamic language so in order to convert a string into a number you could use the parseFloat/parseInt functions:

Answer: JavaScript is not Java. int is a reserved keyword but doesn't have any functionality assigned to it, and you can't cast a value that way.
You probably want:
substractedQty = parseInt($('#qty_6035').val(), 10);

Answer: Javascript doesn't support type casting like strong typed languages (C#, Java) do. To convert the field values (which are strings) to numbers you need to use the global functions parseInt() or parseFloat().
You'll probably also want to make sure the values are parsed correctly, in case a user entered some bad input instead of a number. Use isNAN() for that.


How to test whether the absolute change of two paired samples different from zero

Question: I have two paired samples.
$\text{Group 1}: X_1,X_2, ...,X_n$
$\text{Group 2}: Y_1,\;Y_2,...,\;Y_n$.
$(X_1, Y_1)$, $(X_2, Y_2), ..., (X_n, Y_n)$ are paired respectively.
The null hypothesis is $\mu_{|X-Y|} = 0$,
the alternative hypothesis is $\mu_{|X-Y|} > 0$
What is the appropriate test for this purpose?
Comment: If you have data that's roughly normalish, I'd suggest a paired-t-test. If you don't, there are a variety of choices, but if the differences aren't too skew, I'd lean toward a permutation test.
Comment: Like a (two-tailed) paired t-test, Wilcoxon signed rank test or sign test, for example? What aspect of the distribution of the difference are you most interested in?
Comment: I am interested if the mean of the absolute difference significantly different from zero or not.
Comment: Could you remind me how permutation test can be used here
Comment: Sure I'll expand my comments to an answer.
Comment: Your present null hypothesis makes no sense. Even when $X$ and $Y$ are from the same population $E(|X-Y|)$ is only $0$ when the common variance is $0$. That is, when $X-Y$ is *always* $0$. A single $x_i\neq y_i$ is sufficient to cause rejection. Please clarify further.
Comment: try the following R code, you will see a single $x_i \neq y_i$ is not sufficient to cause rejection.  > foo = c(1:9,9)
> goo = c(1:10)
>  t.test(foo,goo,paired=T). The p.value also depends on the variation of the differences.
Comment: That's because you're not testing the hypothesis in your question, but a different hypothesis. $|X-Y|$ is always $\geq 0$. Pretty much the only test procedure that makes sense is "reject if any $x_i\neq y_i$", because if even one pair is unequal, the chance the null is true is $0$.
Comment: I need to conduct this test for a few different data sets. And I am interested in ranking the p-values. In other words, I am interested in seeing which data set has the most evidence to show the difference between the profile of the two paired samples.
Comment: What you want doesn't change the problem with what you're trying to do.
Comment: I see your point now. Right, the chance that $\mu=0$ under null hypothesis is zero.
Comment: So, maybe I didn't form the null hypothesis correctly. What do you think the null hypothesis should be, if I want to test how much the profile change is between two paired samples.  By profile change, I mean the increase or decrease of the value for every paired data points.
Comment: If you're really interested in testing whether the mean difference ($\mu_{X-Y}$) is nonzero, a tendency for  X-Y to be sometimes large negative and sometimes large positive is simply a situation of large variance. It makes it harder to detect whether the means differ, which does reduce power. There's not really a way around that. You just test the hypothesis you care about, the best way you can. I can't tell you your hypothesis, but note *carefully* that hypotheses are about populations, not *data*.
Comment: If you want to test individual pairs of points, you're going to have almost no power.
Comment: Good point. I really appreciate!!
Answer: In comments you specify an interest in the alternative $\mu_D\neq 0$, I'll discuss several   possibilities:
1) paired t-test: suitable if the differences are approximately normal. Moderately tolerant of non-normality.
2) Wilcoxon signed rank test: effectively a permutation test on the mean of the signed ranked differences. Assumes symmetry of the differences (and under that assumption, works as a test for the mean difference being zero).
3) Sign test. Does not assume symmetry, but is not a test for the mean difference being zero if you don't have symmetry. Since it tends to have lower power unless the tails are very heavy, if you're going to assume symmetry you'd usually be better off with (2).
4) permutation test. This has the same assumptions as (2) - independence, symmetry of differences, but it has better power at the normal than (2) (so if you're really having trouble working out which of (1) or (2) to do, you should probably do (4) instead. If your tails are heavier than normal, say logistic-ish, you might be slightly better off with (2) from a power point of view. On the other hand, the loss of power at the normal if you do (2) is surprisingly small, so there's not all that much to worry about either way.
The permutation test works as follows:
If the null is true and the distribution of differences is symmetric, then the differences would be as likely to have one sign as the other - under the null hypothesis, the signs are arbitrary.
So you can generate pseudosamples by taking the absolute differences and giving each one a random sign.
For each pseudosample you calculate some test statistic which will tend to be unusual compared to the null case (i.e. is sensitive to the alternative). One example is the sum of the signed differences.
If $n$ is the number of differences, then there are $2^n$ such sets of signs. If $2^n$ is tractable (say $n<20$ or so), you can compute all possible arrangements of signs.
If $n$ is too big to find them all, you can randomly sample the sets of signs (making it a randomization test rather than a permutation test).
Either way, you end up with a distribution for the test statistic. You find where your sample statistic lies in the distribution. If it's in either extreme tail (say the top of bottom $n\alpha/2$ values, you would reject the null.
Comment: Thanks for your answer! However, as I mentioned in the question, I am interested in the absolute change of these two groups. The tests in your answer are all used for testing the equality of the two group means. In the case that half of samples are increased and the other half of the samples are decreased, a test for testing the equality of two group means will probably give a non-significant p-value. However, I suppose if we test the ABSOLUTE CHANGE, the result will be very likely significant.
Comment: Your original phrasing was ambiguous. It suggested to me that you were after a difference in either direction - I even asked you to confirm the kind of thing with my initial comment, to which your response merely repeated the same somewhat ambiguous information (a simple 'no, I don't mean that' would have been more help), again leaving me guessing. Please edit your question to include an algebraic definition (in terms of what you have measured) of what you want to compare, and a clear statement of your null and alternative hypotheses, and I will modify my answer.
Comment: It sounds like you want to compare mean deviation from the mean, as a way of comparing spreads, is that right? Can you define your variables, clarify how many there are and make explicit the comparison, please?
Comment: I apologize for confusion. The original question is edited. Thank you!


Figure out what day each array starts and ends on?

Question: I have an array of words and each word is valid from 5PM that day until 5PM the next day, then the next word is valid. Except on weekends in which a word for Friday lasts until Monday at 5PM.
Now what I am trying to do is determine if the users inputted word is valid for that period of time. I have a working example which works fine, but my problem is the weekends mess everything up. And I can't seem to figure out how to make them work.
I got a function to figure out how many weekends occur between two timestamps
<code>// Figure out how many weekends occured between two dates
function weekends($date1, $date2) {
    $d1 = new DateTime('@' . $date1);
    $d2 = new DateTime('@' . $date2);

    // Compare the two dates
    $diff = $d1->diff($d2);

    // Get number of days between them
    $days = $diff->format('%a');

    // Find out day of the week we start on
    $start = $d1->format('w');

    // Verify we are not on a weekend
    if($start == 0 || $start == 6)
        return false;

    // Number of days until weekend
    $until_weekend = 7 - $start; // (6 is Saturday but we are counting today)

    // Find out how many days are left between the first weekend and the end
    $left = $days - $until_weekend;

    // How many weekends
    $weekends = floor($left / 7) + 1;

    return $weekends;
}
</code>
And then I got a function to determine if the word is valid for that date range
<code>// Keyword Validation
function keyword_validate($keywords = array()) {
    if(empty($keywords)) return false;

    // Break into values
    $keyword = $keywords['keyword'];
    $contest = $keywords['contest'];
    $keywords = $contest['keywords'];

    // Get some dates
    $now = new DateTime('now');
    $start = new DateTime('@' . $contest['start_time']);
    $s1 = new DateTime('@' . $contest['start_time']); // value for timestamps
    $s2 = new DateTime('@' . $contest['end_time']); // value for timestamps
    $end = new DateTime('@' . $contest['end_time']);

    // Verify keyword exists
    if(in_array($keyword, $keywords) === FALSE)
        return false;

    // Get index
    $index = array_search($keyword, $keywords);

    // See if we somehow got more then one keyword
    if(count($index) != 1)
        return false;

    // get number of weekends
    $weekends = weekends($start->getTimestamp(), $end->getTimestamp());

    // Based on index get the two container timestamps
    $s = $s1->add(new DateInterval('P' . $index + $weekends . 'D'));

    // Verify start doesn't equal Friday or a Weekend

    $e = $s2->add(new DateInterval('P' . $index + $weekends + 1 . 'D'));

    if($s === FALSE || $e === FALSE)
        return false; // Something really bad happened

    // Based on dates find out if the keyword works.

    print $s->getTimestamp();
    print $e->getTimestamp();
    // Get the current time

}
</code>
As you can seem the keyword function doesn't work atm. What I am doing atm is matching the index of the keyword to day, but if it is say Tuesday (2 weekends after) how can I make it so the index is increased by 4. Sorry if this doesn't make any sense, I'm a little lost.
Answer: Could you not just have an array that can contain seven spaces? When the "friday" index is changed, set the "Saturday"/"Sunday" to mirror it.
Answer: Try redefining the problem to make it simpler. Instead of trying to do math with funny exceptions to figure out which item is associated with which day, perhaps try creating a new array with a value of the word for each day. It could look like this:
<code>array(
    'cake',
    'pie',
    'pudding',
    'happy', //friday
    'happy', //saturday
    'happy', //sunday
    'nothappy',
    ...
);
</code>
Building this array should be simpler than the things you're trying to do now. Once you have this array, checking should be trivial.


Cannot figure out the output of my array list

Question: This might be a dumb question but its frustrating me. I am adding into my array list a object during a loop but outside of the loop, all of the array list is overwritten with the last element in the array. It goes something like this.
while(fin.hasNextLine())
{
    String line = fin.nextLine();
    String[] user = line.split(",");
    r.add(new User(user[0], user[1]));
    System.out.println(r.get(count).getName());
    count++;
}

This gives me an output of something like this (USER1, USER2, USER3, etc.) during the loop.
However, right after the loop I now have an output of something like this (USER500, USER500, USER500).
while(fin.hasNextLine())
{
    String line = fin.nextLine();
    String[] user = line.split(",");
    r.add(new User(user[0], user[1]));
    System.out.println(r.get(count).getName());
    count++;
}

for (int i  =0; i < r.size(); i++)
{
    System.out.println(r.get(i).getName());
}

I managed to verify that this is the class where I'm having the problem and only one other method uses the array list in this class which i commented out.
Comment: Where is r defined? you might print out its size() to check it has the right number of entries
Comment: Something is amiss in the code.. Can you post full code please.
Answer: I'm going to have to put on my psychic debugging goggles, but I predict tht your User class looks like this:
public class User {
    private static String name;

    public User(String x, String somethingElse) {
        name = x;
    }

    public String getName() {
        return name;
    }
}

Note that name is static. Therefore that's one variable - not one per instance of User. You want it to be an instance field, so that each User object has a different name variable.
Comment: Thanks. That was exactly it. I can't believe I missed it before.


One of two unfair coins arbitrairly chosen and flipped 10 times.

Question: If the probability of heads for coin 1 is 0.4, and the probability of heads is 0.7 for coin 2, and assuming either coin is selected with equal probability:
a. What is the probability that 7 of 10 flips is heads?
I did part a simply enough, $0.5[\left( \begin{matrix} 10\\ 7\end{matrix} \right) *0.4^7*0.6^3 + \left( \begin{matrix} 10\\ 7\end{matrix} \right) *0.7^7*0.3^3]$
Part b is is a bit confusing to me:
What is the conditional probability that 7 of 10 flips is heads given that the 1st flip is heads?
I have event A: the first flip is heads, and event B, 7 of the 10 flips are heads:
So the $P(B|A)=\dfrac {P(A \cap B)} {P(A)}$. $P(A) = .5(0.4+0.7)=0.55$ How do I take the dependence of event B on event A into account when figuring this out? Our professor assured us that the answer in the solutions manual is wrong for part b.
Comment: I think you can use Bayes' theorem.
Answer: To calculate the probability  of $A\cap B$, proceed more or less like in your calculation for a). With probability $0.5$ we are flipping the first coin. For that coin, calculate the probability $p_1$ that the first toss is head and that there are $6$ heads in the next $9$ tosses. This is $0.4$ times a "binomial" expression of a kind familiar to you.
Define $p_2$ similarly. Then $\Pr(A\cap B)=(0.5)(p_1+p_2)$.
Answer:
Let $A$ be the event that: the 0.4 biased coin is selected.
Let $B$ be the event that: the 0.7 biased coin is selected.
Let $C$ be the event that: the first flip is a head
Let $D$ be the event that: the subsequent 9 flips contain 6 heads.

Noting that C and D will be conditionally independent given A (or B) we have:

$$\mathsf P(D\mid C) = \mathsf P(D\mid A)\;\mathsf P(A\mid C)+\mathsf P(D\mid B)\;\mathsf P(B\mid C)$$
Can you evaluate the RHS 's four conditional probabilities?


Docker Toolbox image operating system "windows" cannot be used on this platform

Question: I have installed docker toolbox on my windows 10 home pc.
I ma facing two problems.
1.When I click on docker quickstart terminal, it gives unix/linux prompt.
2.When I try to run this command docker build (on windows command prompt), I get this error :image operating system "windows" cannot be used on this platform.
docker build .
Sending build context to Docker daemon  2.584MB
Step 1/17 : FROM microsoft/aspnetcore:2.0-nanoserver-1709 AS base
2.0-nanoserver-1709: Pulling from microsoft/aspnetcore
407ada6e90de: Pulling fs layer
10288d944410: Pulling fs layer
4880fefbf99e: Pulling fs layer
df193da25173: Waiting
60ab1f0af432: Waiting
f4d477fb2108: Waiting
878954290d5e: Waiting
ae61d8e352f7: Waiting
88faab7b6014: Waiting
e7331f21ccb7: Waiting
image operating system "windows" cannot be used on this platform

How do I correct my configuration so that it accepts my windows 10 os.
How can I configure docker toolbox so that I can dockerize my dot net applications.
My question is, if docker toolbox installs a linux vm on my system, how is it going to help me with commands like " docker build ." , it gives this error :image operating system "windows" cannot be used on this platform. So, essentially, I cannot do anything.
Is that correct? or is there a way by which I can invoke docker on windows 10 home?
Thanks is advance.
Comment: Possible duplicate of [Can I run windows containers using docker-toolbox on windows 7?](https://stackoverflow.com/questions/42482154/can-i-run-windows-containers-using-docker-toolbox-on-windows-7)
Comment: My question is, if docker toolbox installs a linux vm on my system, hiw is it going to help me with commands like " docker build ." , it gives this error :image operating system "windows" cannot be used on this platform. So, essentially, I cannot do anything.

Is that correct? or is there a way by which I can invoke docker on windows 10 home?
Answer: Change to FROM microsoft/aspnetcore:2.0-nanoserver-1709 to microsoft/dotnet:2.1-aspnetcore-runtime
Explanation:
microsoft/aspnetcore:2.0-nanoserver-1709 is a windows native container image. It can only be run on windows 10 or windows server.To run on Linux container, pull the similar image for Linux as described here
Comment: This just explains how to switch to a linux based image. But Windows 10 should be able to run the Windows based image, how can we do that?
Answer: To be able to run Windows containers, you first need to install Hyper-V: open PowerShell as an administrator and enter Enable-WindowsOptionalFeature -Online -FeatureName $("Microsoft-Hyper-V", "Containers") -All. Restart your computer, launch Docker Desktop and then right click on Docker Desktop at the bottom right the windows task bar, and click "Switch to windows container"

You should now be able to run any docker image based on Windows.
Answer: Based on the last answer, I changed my base to: microsoft/dotnet:2.1-aspnetcore-runtime AS base
and the build to microsoft/dotnet:2.1-sdk AS build in the Dockerfile and now it works.


Finding all nth roots of a complex number in C#

Question: Consider a generic complex number:
System.Numerics.Complex z = new System.Numerics.Complex(0,1); // z = i

And now consider the n-th root extraction operation of z. As you all know, when having a problem like z^n = w (having z and w complex numbers and n a positive not null integer) the equation returns n different complex numbers all residing on the complex circle having its radius equal to the module of z (|z|).
In the System.Numerics namespace I could not find such a method. I obviousle need some sort of method like this:
Complex[] NRoot(Complex number);

How can I find this method. Do I really need to implement it myself?
Comment: There is a `static Complex FromPolarCoordinates()`
Comment: Is it possible to get/set the complex number by its polar coordinates? that would make the task way easier.
Comment: I was going to say the same... However really there is no implementation of a generic method to extract the nth roots of a complex number?
Comment: I know it is not difficult to write such a method, but I suppose that an optimized implementation exists, using the mathematical definition might not be the best possible solution!
Comment: Someone did edit my post title removing "C#" from it. I disagree with this because it is the essence of my question. As I have explained, I am not looking for an algorithm to find the roots, I need to know whether the .NET framework (in particular, C# libraries) already implements a method to do this.
Answer:
How can I find this method.

You can't, it's not built into the Framework.

Do I really need to implement it myself?

Yes.
Sorry if this comes across as a tad flip, I don't mean to, but I suspect that you already knew this would be the answer.
That said, there's no magic to it:
public static class ComplexExtensions {
    public static Complex[] NthRoot(this Complex complex, int n) {
        Contract.Requires(n > 0);
        var phase = complex.Phase;
        var magnitude = complex.Magnitude;
        var nthRootOfMagnitude = Math.Pow(magnitude, 1.0 / n);
        return
            Enumerable.Range(0, n)
                      .Select(k => Complex.FromPolarCoordinates(
                          nthRootOfMagnitude,
                          phase / n + k * 2 * Math.PI / n)
                      )
                      .ToArray();
    }
}

Most of the work is offloaded to the Framework. I trust that they've implemented Complex.Phase, Complex.Magnitude correctly ((Complex complex) => Math.Sqrt(complex.Real * complex.Real + complex.Imaginary * complex.Imaginary) is bad, Bad, BAD) and Math.Pow correctly.
Comment: Do you have a link to a proper implementation of complex magnitude should it turn out that .Net's is "bad, Bad, BAD"?
Comment: @Gabe: Nope, but it's pretty well-known. The problem is that the naive `|x + yi| = Sqrt(x^2 + y^2)` can overflow well before it should. It's very easily avoided with `|x + yi| = |x| Sqrt(1 + (y / x)^2) if |x| >= |y|, otherwise |y| * Sqrt(1 + (x / y)^2) if |x| < |y|` (this can still overflow). I suspect it's somewhere in [Numerical Recipes](http://www.nr.com/) but I don't have my copy handy right now. Like I said, I *trust* that the Framework got this right. That's possibly a mistake, given the infamous binary search overflow bug that was in Java, something they should have known.
Comment: @Gabe: I just tested (someone with access to a code decompiler can do better) on `new Complex(Math.Sqrt(Double.MaxValue), Math.Sqrt(DoubleMaxValue))` and the Framework gets it right whereas the naive would overflow and get it wrong.
Comment: A quick look in ILSpy shows an implementation as you describe (with an added check for 0, obviously).
Comment: Guess it can't be helped. Thanks for you efforts Jason and thank you for posting code!
Comment: @Gabe: Here's a [Wikipedia article](http://en.wikipedia.org/wiki/Hypot) on the subject.


Definition of $\mathcal{O}(D)(U)$

Question: Let $L(D)$ denote the space of meromorphic functions $f$ on $M$ (complex manifold), s.t. $D+(f)\ge0$. Then we can find a global meromorphic section of $\mathcal{O}(D)$ $s_0$ with $(s_0)=D$. Then we have the identification $L(D)\xrightarrow{\otimes s_0} H^0(M,\mathcal{O}(D))$.
On Griffiths, Harris p.138, it says that if $D=\sum a_iV_i$ is an effective divisor, more generally, if $E$ is any holomorphic vector bundle on $M$, $\mathcal{E}$ its sheaf of holomorphic sections,  $\mathcal{E}(D)$ for the sheaf of meromorphic sections of $E$ with poles of order $\le a_i$ on $V_i$. Again, tensoring with $s_0$ gives identification $\mathcal{E}\xrightarrow{\otimes s_0}\mathcal{O}(E\otimes [D])$. (Here $[D]$ is the line bundle of $D$)
Now I wonder why is the condition effective necessary? In particular, in $L(D)\xrightarrow{\otimes s_0} H^0(M,\mathcal{O}(D))$, we don't require $D$ to be effective.
And in particular, take $E$ to be the trivial line bundle, I think I can conclude that to any divisor $D$, (may not be effective) $\mathcal{O}(D)$ can be identified as the sheaf of meromorphic functions s.t. $D+(f)\ge 0$ on $V_i$, is that right?
Moreover, we know when $D$ is effective we have the short exact sequence:
$0\to \mathcal{O}(-D)\to \mathcal{O}_X\to \mathcal{O}_D\to 0$
I wonder why we require $D$ to be effective? Since to any divisor $D$, $\mathcal{O}(-D)$ can be identified as the sheaf of meromorphic functions s.t. $-D+(f)\ge 0$ on $V_i$, and $\mathcal{O}_D$ is the cokernel sheaf.
Answer: The hypothesis that the divisor be effective is used in giving the interpretation that the sections have poles of order $\le a_i$ on $V_i$. If you modify the "description" to say that when $a_i<0$, we require a zero of order $\ge |a_i|$ along $V_i$, then it works fine.
In the case of your final short exact sequence, you need $D$ effective here because when $V$ is a hypersurface, there is no sheaf injection $\mathscr O_X(V) \to \mathscr O_X$. (Locally, a meromorphic function with a pole along $V$ is not a holomorphic function.) Also, we interpret $\mathscr O_V$ as the structure sheaf of the hypersurface $V$, and I've never seen this in the context of the structure sheaf of the "formal" $-V$.
Comment: How to interpret $\mathcal{O}_{2V}$ and $\mathcal{O}_{V+V'}$ I wonder what are the associated spaces? Are they V and $V\cup V'$?
Comment: Also I think the $s_0$ on p.138 is different from the $s_0$ on p.136, here $s_0\in H^0(M,\mathcal{O}([D])$, but if D is of negative degree, $ H^0(M,\mathcal{O}([D])$ might be zero, then we don't have such an $s_0$. However, if we consider as p.136, I.e. $s_0$ is a meromorphic section s.t. $(s_0)=D$ then it seems it works. Am I right?
Comment: They are the same when $D$ is effective (which is the assumption on p. 138). By the way, G/H specify that they're considering the context of your short exact sequence only in the case $D$ is a smooth analytic hypersurface (bottom p. 138 to top p. 139).

Definition of $\mathcal{O}(D)(U)$


Expected value of error in neural network

Question: I wanted to take a look at the properties of the error vector that is propagating during backpropagation. The error vector $\boldsymbol{\delta}$ at layer $i$ is nothing more than the derivative of some loss function $L$ with regard to the inputs $\boldsymbol{z}$ at that layer:
$$\boldsymbol{\delta}^{(i)} = \frac{\partial L(\boldsymbol{y}, \boldsymbol{g})}{\partial \boldsymbol z^{(i)}}$$
where $\boldsymbol{y}$ is the expected output and $\boldsymbol{g}$ is the output of the network.
This formula can be decomposed by means of the chain rule, assuming $L$ hidden layers (layer $0$ is the input layer and layer $L+1$ is the output layer)
$$\boldsymbol{\delta}^{(i)} = \frac{\partial L(\boldsymbol{f}, \boldsymbol{g})}{\partial \boldsymbol{g}} \frac{\partial \boldsymbol{g}}{\partial \boldsymbol{z}^{(L+1)}} \frac{\partial \boldsymbol{z}^{(L+1)}}{\partial \boldsymbol{z}^{(L)}} \ldots \frac{\partial \boldsymbol{z}^{(i+2)}}{\partial \boldsymbol{z}^{(i+1)}} \frac{\partial \boldsymbol{z}^{(i+1)}}{\partial \boldsymbol z^{(i)}}$$
which makes it easy to see that following recursion holds:
$$\boldsymbol{\delta}^{(i)} = \boldsymbol{\delta}^{(i+1)} \frac{\partial \boldsymbol{z}^{(i+1)}}{\partial \boldsymbol{z}^{(i)}}$$
Also note that
$$\frac{\partial \boldsymbol{z}^{(i+1)}}{\partial \boldsymbol{z}^{(i)}} = \frac{\partial \boldsymbol{z}^{(i+1)}}{\partial \boldsymbol{h}^{(i)}}\frac{\partial \boldsymbol{h}^{(i)}}{\partial \boldsymbol{z}^{(i)}} = {\mathbf{W}^{(i)}}^T f'(\boldsymbol{z}^{(i)})$$
with $f : \mathbb{R}^n \to \mathbb{R}^n$ an (element-wise) activation function and $\boldsymbol{h}^{(i)} = f(\boldsymbol{z}^{(i)})$ the output of layer $i$. $\mathbf{W}^{(i)}$ is a matrix holding the weights between layer $i$ and layer $i+1$.
Now I would be interested in computing
$$\mathrm{E}\left[\delta_j^{(i)}\right] = \mathrm{E}\left[f'(z_j^{(i)}) \cdot {\boldsymbol{w}^{(i)}}^T_j \cdot \boldsymbol{\delta}^{(i+1)}\right] $$
but due to the dependence of $\boldsymbol{\delta}^{(i+1)}$ with all inputs and weights, there is no way to simplify this and I would need to find an expression of $\delta$ as a function of $z$ and integrate over the whole thing, which I am not sure is possible.
I also tried to compute the expectation as
$\begin{align*}
  \mathrm{E}\left[\delta_j^{(i)}\right] & = \mathrm{E}\left[\frac{\partial L}{\partial z_j^{(i)}}\right] \\
  & = \int_{-\infty}^{\infty} \frac{\partial L}{\partial z} p(z; \mu, \sigma^2) \mathrm{d}z \tag{$z = z_j^{(i)}$} \\
  & = \frac{1}{\sqrt{2 \pi} \sigma} \int_{-\infty}^{\infty} \frac{\partial L}{\partial z} \exp\left(-\frac{(z - \mu)^2}{2 \sigma^2}\right) \mathrm{d}z \tag{Gaussian assumption} \\
  & = \frac{1}{\sqrt{2 \pi} \sigma} \left[ \left. L(\boldsymbol{y}, \boldsymbol{g}) \cdot \exp\left(-\frac{(z - \mu)^2}{2 \sigma^2}\right) \right|^\infty_{-\infty} \right. \\
  & \qquad \left. + \frac{1}{\sigma^2} \int_{-\infty}^{\infty} L(\boldsymbol{y}, \boldsymbol{g}) \cdot (z - \mu) \exp\left(-\frac{(z - \mu)^2}{2 \sigma^2}\right) \mathrm{d}z \right]
\end{align*}$
but this leads to an expression that does not seem to be very integrable, because the network output looks something like $$\boldsymbol{g} = f(\mathbf{W}^{(L)} \cdot f(\mathbf{W}^{(L-1)} \cdot f( \cdots f(\boldsymbol{z}) \cdots )))$$
I am not really a true mathematician, so I hope I did not make too much mistakes in my explanation/notation. This is probably also the reason why I am not completely sure how I could proceed and whether it even makes sense to proceed. Is there any chance I could compute an expectation like this or should I just give up? Are there other tricks I could consider to try to compute this integral?
Any help or hint would be greatly appreciated (also if it concerns my question not being clear enough)
Comment: What is the purpose? If it is to reduce the error from single "neuron", a feedback mechanism might be easier to tackle, see https://www.nature.com/articles/ncomms13276 . If it is only to track numerical errors in backpropagation, it may not be that practical,  we can't do much with the error information without relating that to learning.
Comment: @MehmetSüzen The purpose was to analyse the statistics of the backward pass. Eventually I made the simplifying assumption that everything is uncorrelated for this analysis and got some results that could be verified empirically. If I have some time I might actually be able to formulate an answer to this question by now.
Comment: It would be easy to calculate this sort of thing numerically, by just logging the values as you pass through your data set. Most nnet platforms (tensor flow, pytorch) should support this
Answer: This problem isn't simple to approach. The reason that backpropagation works well for neural networks is because we can pass the inputs through the network once, record the activation value of each neuron, and use them to compute the derivatives of each neuron.
When you integrate over $z$ you are changing the activation value of a neuron which will change every neuron in every subsequent layer. This is very unlike backpropagation where we get the partial derivatives for a single activation value for each neuron.
There is no reason to expect that this would have a nice solution so my honest advice to you would be to give up.
Comment: I am not exactly looking for a nice/clean/easy solution... I am just wondering if it is possible to solve an integral like this in any way (maybe by making more assumptions)
Answer: Eventually I ended up assuming that everything is independent, i.e.,
$$\mathop{\mathrm{E}}[\delta_j^{(i)}] = \mathop{\mathrm{E}}[f'\big(z_j^{(i)}\big) \cdot \boldsymbol{w}_j^{(i)} \cdot \boldsymbol{\delta}^{(i+1)}] \approx \mathop{\mathrm{E}}[f'\big(z_j^{(i)}\big)] \cdot \mathop{\mathrm{E}}[\boldsymbol{w}_j^{(i)}] \cdot \mathop{\mathrm{E}}[\boldsymbol{\delta}^{(i+1)}].$$
Of course, this is rather inaccurate, but the theoretical results I obtained using this approach turned out to be good enough in empirical experiments.
In the meantime I also went to the struggle of computing the expectation with dependencies for the simplest possible case: the delta for the inputs to the last layer in a network that is to be trained with the MSE loss function at initialisation time. In this case, $\boldsymbol{\delta}^{(i + 1)} = \boldsymbol{z}^{(i)} - \boldsymbol{y} = \boldsymbol{W}^{(i)} \cdot f(\boldsymbol{z}^{(i)}) - \boldsymbol{y}$. As a result, the expectation can be computed as follows:
$$\begin{align}
  \mathop{\mathrm{E}}[\delta_j^{(i)}] &= \mathop{\mathrm{E}}[f'\big(z_j^{(i)}\big) \boldsymbol{w}_j^{(i)} \cdot \boldsymbol{\delta}^{(i+1)}] \\
&= \mathop{\mathrm{E}}[f'\big(z_j^{(i)}\big) \boldsymbol{w}_j^{(i)} \cdot \big(\boldsymbol{W}^{(i)} \cdot f(\boldsymbol{z}^{(i)}) - \boldsymbol{y}\big)] \\
&= \mathop{\mathrm{E}}[f'\big(z_j^{(i)}\big) \boldsymbol{w}_j^{(i)} \cdot \boldsymbol{W}^{(i)} \cdot f(\boldsymbol{z}^{(i)})] - \mathop{\mathrm{E}}[f'\big(z_j^{(i)}\big) \boldsymbol{w}_j^{(i)} \cdot \boldsymbol{y}] \\
&= \mathop{\mathrm{E}}[\boldsymbol{w}_j^{(i)} \cdot \boldsymbol{W}^{(i)}] \cdot \mathop{\mathrm{E}}[f'\big(z_j^{(i)}\big) f(\boldsymbol{z}^{(i)})] - \mathop{\mathrm{E}}[f'\big(z_j^{(i)}\big)] \mathop{\mathrm{E}}[\boldsymbol{w}_j^{(i)}] \cdot \mathop{\mathrm{E}}[\boldsymbol{y}]
\end{align}$$
If we furthermore assume i.i.d. weights, such that $\mathop{\mathrm{E}}[w_{ij}] = \mu_w$ and $\mathop{\mathrm{E}}[w_{ij} w_{kl}] = \delta_{ik}\delta_{jl} \sigma_w^2 + \mu_w^2$, this becomes
$$\begin{align}
  \mathop{\mathrm{E}}[\delta_j^{(i)}] &= M (\sigma_w^2 \boldsymbol{e}_i + \mu_w^2 \boldsymbol{1}) \cdot \mathop{\mathrm{E}}[f'(z_j^{(i)}) f(\boldsymbol{z}^{(i)})] - \mu_w \boldsymbol{1} \cdot \mathop{\mathrm{E}}[\boldsymbol{y}] \mathop{\mathrm{E}}[f'\big(z_j^{(i)}\big)] \\
  &= M \sigma_w^2 \mathop{\mathrm{E}}[f'(z_j^{(i)}) f(z_j^{(i)})] + \mu_w \left(\sum_{k=1}^M \bigg[\mu_w \sum_{l=1}^H \mathop{\mathrm{E}}[f'(z_j^{(i)}) f(z_l^{(i)})] - \mathop{\mathrm{E}}[f'(z_j^{(i)})] \mathop{\mathrm{E}}[y_k]\bigg]\right),
\end{align}$$
with $M$ and $H$ the number of outputs and hidden units, respectively. I.e., $\boldsymbol{y} \in \mathbb{R}^M$ and $\boldsymbol{z} \in \mathbb{R}^H$.
Note that only if $M \sigma_w^2 \mathop{\mathrm{E}}[f'(z_j) f(z_j)] \approx 0$ and
$$\mu_w \left(\frac{\mathop{\mathrm{E}}[f'(z_j) f(z_j)]}{\mathop{\mathrm{E}}[f'(z_j)]} + \sum_{l=1, l \neq j}^H \mathop{\mathrm{E}}[f(z_l^{(i)})]\right) - \mathop{\mathrm{E}}[y_k] \approx \mathop{\mathrm{E}}[\delta_k^{(i+1)}],$$
the independence assumption gives a good approximation.


"foreach" dentro de consulta usando PHP PDO " $sql = $pdo->prepare( )"

Question: Bom dia a todos, estou tentando criar uma view em tempo de execução.
Pra isso preciso listar todos os campos da tabela e jogar dentro da instrução o problema é que não to conseguindo transferir o array $obj1[0] pra $variavel e assim listar todos ou concatenar um foreach dentro da query.
alguma ideia? desde já agradeço.
<code>  if(@$_POST['op']=='criaview'){
    $bancoview = $_POST['bancotabelas'];
    $tabeaview = $_POST['tabelasbanco'];

    $pdo = new PDO(DB_SERVER.":host=".DB_HOST.";dbname=".$bancoview,DB_USER,DB_PASSWORD);
    $sql1 = $pdo->prepare("SHOW FIELDS FROM ".$tabeaview);
    $sql1->execute();
    foreach($sql1 as $obj1){
        $variavel = $obj1[0];
    }

    $pdo = new PDO(DB_SERVER.":host=".DB_HOST.";dbname=".$bancoview,DB_USER,DB_PASSWORD);
    $sql = $pdo->prepare(
    "CREATE VIEW  view_".$tabeaview."  AS
    SELECT
    *
    /**
    ".$variavel."<----------------aqui devem aparecer todos os campos
    **/
    FROM
        ".$tabeaview."
    ");
    $sql->execute();
  }
</code>
Comment: o seu código é só esse?
Comment: por enquanto sim.
Answer: Resolvido! refiz todo o código.
Então, é assim consegui criar uma view dinamicamente.
<code>    $dir = PATH.$_SESSION['database'].'\\';  //Pega o diretorio atual
    $filename = PATH.$_SESSION['database'].$_POST['tabelasbanco'].".view.php";  //Raiz onde vai ser salvo o arquivo

    $bancoview = $_POST['bancotabelas'];
    $tabeaview = $_POST['tabelasbanco'];

    if(file_exists($filename)){
       unlink($filename);
    }
    $file = fopen($filename, "w+");
    $filedate = date("d.m.Y");

    $view = 'CREATE VIEW view_'.$tabeaview.' AS SELECT';

    $pdo = new PDO(DB_SERVER.":host=".DB_HOST.";dbname=".$_SESSION['bancotabelas'],DB_USER,DB_PASSWORD);
    $sql = $pdo->prepare("show fields FROM ".$tabeaview." ");
    $sql->execute();
    foreach($sql as $obj){
        $data[] = $tabeaview.'.'.$obj[0];
    }

    $view.=' '.implode(",", $data).' ';

    $view.=' FROM '.$tabeaview.' ';

    $pdo = new PDO(DB_SERVER.":host=".DB_HOST.";dbname=".$_SESSION['bancotabelas'],DB_USER,DB_PASSWORD);
    $sql3 = $pdo->prepare("select * from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where TABLE_NAME = '".$tabeaview."' AND TABLE_SCHEMA = '".$_SESSION['bancotabelas']."' ");
    $sql3->execute();
    foreach($sql3 as $obj3){
        $pdo = new PDO(DB_SERVER.":host=".DB_HOST.";dbname=".$_SESSION['bancotabelas'],DB_USER,DB_PASSWORD);
        $sql4 = $pdo->prepare("select COLUMN_NAME from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where TABLE_NAME = '".$obj3['REFERENCED_TABLE_NAME']."' AND TABLE_SCHEMA = '".$_SESSION['bancotabelas']."' LIMIT 1 ");
        $sql4->execute();
        foreach($sql4 as $obj4){
            $view.=' LEFT JOIN '.$obj3['REFERENCED_TABLE_NAME'].' ON '.$tabeaview.'.'.$obj4[0].' = '.$obj3['REFERENCED_TABLE_NAME'].'.'.$obj4[0].' ';
        }
    } $pdo = null;

    fwrite($file, $view);

    $pdo = new PDO(DB_SERVER.":host=".DB_HOST.";dbname=".$bancoview,DB_USER,DB_PASSWORD);
    $sql = $pdo->prepare("$view");
    $sql->execute();
    $pdo = null;
</code>