Integrate $\int \frac{\tan \left(x\right)}{\sin ^2\left(x\right)}dx\cdot \int \log _{3x}\left(x^2\right)dx$.

Question:
Integrate the following integral:
$$\int \frac{\tan \left(x\right)}{\sin ^2\left(x\right)}dx\cdot \int \log _{3x}\left(x^2\right)dx$$

I did this question a while ago and the answer is correct. However, when I started revising this topic again, I can't seem to figure out how I went from the first step $\left( \text{for this integral}\int \log _{3x}\left(x^2\right)dx\right)$ to the second step. Here's my attempt:
\begin{align}
\int \frac{\tan \left(x\right)}{\sin ^2\left(x\right)}dx  &= {\int{\frac{2}{\sin{\left(2 x \right)}} d x}} \\
&= {\int{\frac{1}{\sin{\left(x \right)} \cos{\left(x \right)}} d x}} \\
&= {\int{\frac{\sec^{2}{\left(x \right)}}{\tan{\left(x \right)}} d x}} \\
&\stackrel{{u = \tan{\left(x\right)}}}{=} {\int{\frac{1}{u} d u}} \\
&= {\ln{\left(u \right)}} + c \\
&= \ln{\left(\left|{\tan{\left(x \right)}}\right| \right)}+
\end{align}
\begin{align}
\int \log _{3x}\left(x^2\right)dx &= x\log _{3x}\left(x^2\right)-\int \frac{2\ln \left(3\right)}{\ln ^2\left(3x\right)}dx \\
&= x\log _{3x}\left(x^2\right)-\left(-\frac{2\ln \left(3\right)x}{\ln \left(3x\right)}+\frac{2}{3}\ln \left(3\right)\text{Ei}\left(\ln \left(3x\right)\right)\right) \\
&= 2x\log _{3x}\left(x\right)+\frac{2\ln \left(3\right)x}{\ln \left(3x\right)}-\frac{2}{3}\ln \left(3\right)\text{Ei}\left(\ln \left(3x\right)\right) + c
\end{align}
Therefore:
$$\int \frac{\tan \left(x\right)}{\sin ^2\left(x\right)}dx\cdot \int \log _{3x}\left(x^2\right)dx = \left(\ln \left|\tan \left(x\right)\right|+c\right)\left(2x\log _{3x}\left(x\right)+\frac{2\ln \left(3\right)x}{\ln \left(3x\right)}-\frac{2}{3}\ln \left(3\right)\text{Ei}\left(\ln \left(3x\right)\right)+c\right)$$
Answer: $ \sin{(2x)} = 2 \cos{(x)} \sin{(x)}$ if that's what you are asking for...
Comment: I meant the integral with the log part. Sorry for the confusion. See the updated version.
Answer: I think you are asking to verify that
$$\frac{\tan \left(x\right)}{\sin ^2\left(x\right)}.$$ RIGHT?
if so, $$\frac{\sin(x)/\cos(x)}{\sin ^2\left(x\right)}=\frac{1}{\sin(x)\cos(x)}=\frac{2}{2 \sin(x)\cos(x)}=\frac{2}{\sin(2x)}$$
Comment: I meant the integral with the log part. Sorry for the confusion. See the updated version.
Comment: @SkiMask, To make it easy, You should not induced the first integral


All of my android studio projects and all new ones give me errors coming from the debug android manifest file

Question: Everytime i try to build a project the debug\manifest file comes up and says files under the build folder are generated and should not be edited and many errors come up saying android:version name, allow backup and others should not be here, even though I did not edit them. This happens for every android project, even new empty ones ones.
I try invalidating cache and restarting
Rebuilding/ cleaning projects
Uninstalling/Reinstalling android 3.0, this error occured once I upgraded from 2.3.3 to 3.0 btw.
Here are the gradle build errors
Information:Gradle tasks [:app:generateDebugSources, :app:generateDebugAndroidTestSources, :app:mockableAndroidJar, :app:compileDebugAndroidTestSources, :app:compileDebugUnitTestSources, :app:compileDebugSources]
C:\Users\moiz_\Desktop\AndroidStudioProjects\MyApplication2\app\build\intermediates\manifests\full\debug\AndroidManifest.xml
Error:(2) error: attribute 'package' in <manifest> tag is not a valid Java package name: 'com.example.moiz_.myapplication2'.
Error:(2) attribute 'package' in <manifest> tag is not a valid Java package name: 'com.example.moiz_.myapplication2'.
Error:java.util.concurrent.ExecutionException: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:Execution failed for task ':app:processDebugResources'.
> Failed to execute aapt

I am guessing that android is adding code to the generated debuggable manifest files for some reason but I have no clue why, any advice on this problem would be great thanks, here is an example of the generated manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.moiz_.myapplication2"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="24"
        android:targetSdkVersion="26" />

    <application
        android:allowBackup="true"
        android:debuggable="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity android:name="com.example.moiz_.myapplication2.MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <meta-data
            android:name="android.support.VERSION"
            android:value="26.1.0" />
        <meta-data
            android:name="android.arch.lifecycle.VERSION"
            android:value="27.0.0-SNAPSHOT" />
    </application>

</manifest>

and here is an example of the actual manifest file which does not have any errors
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.moiz_.myapplication2">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Here is the build.gradle(Module:app) file for reference
apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.moiz_.myapplication2"
        minSdkVersion 24
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

And the build.gradle project file
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Comment: Can you post your build.gradle file?
Comment: Added both the build.gradle files
Answer:
You're getting the error because AAPT2 does not allow the underscore character '_' as a first or last character in a piece of the package name. In your package name it's the last character in 'moiz_'.
Please follow the open bug at https://issuetracker.google.com/68468089 for more info.
Comment: I removed the underscore from the package name and it succesfully builded, thanks


Tricerat Screwdrivers alternative

Question: Is there another solution I could use instead of
http://www.tricerat.com/products/screwdrivers
I have used them but the maintenance expired and now we have to move our servers from 2003 to 2008 and these guys are somewhat lacking in support and the overall buying experience.
Comment: Shopping Questions are Off-Topic on any of the [se] sites. See [Q&A is hard, lets go Shopping](http://blog.stackoverflow.com/2010/11/qa-is-hard-lets-go-shopping) and the [FAQ] for more details.
Answer: I might suggest using Terminal Services Easy Print.
http://blogs.msdn.com/b/rds/archive/2007/04/26/introducing-terminal-services-easy-print-part-1.aspx
Answer: Easy Print is great, IF it works for you.
This blog post shows that it does not work for everyone...
Comment: @samsmith: Your reference looks like a very edge case to me.
Comment: It is not edge case if you write software that does raw printing.... like we do....
Answer: Cortado makes a comparable product called ThinPrint.
http://www.thinprint.com/

Tricerat Screwdrivers alternative


Django newbie - Need help hiding parts of a table that is built dynamically

Question: I need to hide/show parts of a table that is dynamically built, as shown below.  I want to show or hide the table with class="newtable" if "checkbox" is unchecked.  However, I only want to hide the instance of it that corresponds to that iteration of the loop.  So if the checkbox is checked, the user sees the extra information and has to fill it in.  If not, they don't see it and have no further action.  This logic would be applied for each row of the table.  I can see how to use javascript to hide ALL instances of "newtable", but I only want to hide those that correspond to "checkbox" being checked.  Any help is greatly appreciated.
By the way, I had to build this "form" the long way because my variables come from different models.  Couldn't see any way to use a django form, model form, or formset to accomplish.  Thanks!

{% for x,y,z in stuff%}
    {{ x.foo }}
    {% for item in y %}
        <input type="checkbox" name="stuff.{{ item.id }}" class="item" value="True" checked/> {{ item }}

    {%  endfor %}

    <input type="radio" name="pref_id{{ z.id }}"  value="1" checked> blah

{%  endfor %}

    {% endfor %}

Answer: You can easily hide all checked checkboxes under the table .newtable using jQuery.
<!DOCTYPE html>

<input type="checkbox" checked/>

<input type="checkbox">

If you rather would have had the entire row hidden you could use
$(".newtable input[type=checkbox]:checked").parent().parent().hide()

Alternatively you could hide them when generating the form, assuming you are setting some check boxes to checked depending on item.checked
{% if item.checked %}
    <input type="checkbox" checked style="display:none" ..../>
{% else %}
    <input type="checkbox"  ..../>
{% endif %}

Comment: Thanks for the answer.  I ended up doing something very similar.  The only difference is that I needed to dynamically add a unique id to the element I wanted to hide, then used JQuery to hide it.  Thanks very much for your help!


adodb with sql server odbc connection problem

Question:
ADODB Error: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

I downloaded the odbc driver for PHP. I pasted that driver in the PHP ext directory, then I get the error. Can anybody help me?
Comment: your question is not clear; you should provide example code.
Answer: A few things that I would try,

Make sure that the extension is included in your php.ini
Make sure that you've extracted the db driver to the right place c:\windows\drivers in some cases!
Have you rebooted? As you'll need to reboot your server to load the driver, I assume you have as you get the error :)

As the comment above states, which driver you are using, it's version, and which database you're connecting to would also be handy to know :)
I assume that you're using PHP5 to connect to MSSQL2005. In which case the driver is really dodgy, or was when I last worked with it. It would maintain a connection about 1/3 tries. What web server are you using? As I recall when we were using IIS to serve the PHP+MSSql we had some configuration to do in the IIS setup.
Answer: try:
<code># config file
$oODBC = new stdClass();
$oODBC->driver = "odbc_mssql";
$oODBC->dns = "Driver={SQL Server};Server=127.0.0.1;Database=yourdatabhase;";
$oODBC->user = "username";
$oODBC->pass = "password";

# connect
$mDB = $oODBC;
$db =& ADONewConnection($mDB->driver); // ex: odbc_mssql
$db->PConnect($mDB->dns, $mDB->user, $mDB->pass);
</code>


Exponential Distribution - Rate - Bayesian Prior?

Question: I have gone through WinBugs documentation (for example, http://www.mrc-bsu.cam.ac.uk/bugs/thebugsbook/examples/html/Chapter-11-Specialised/Example-11_7_2-leukaemia.html). And also through this book (http://www.amazon.ca/Bayesian-Survival-Analysis-Joseph-Ibrahim/dp/0387952772).
Both use a gamma distribution prior for the rate (lambda) for the exponential distribution. They alternate between Gamma(0.01,0.01) and Gamma(0.001,0.001).
I would like to use a non-informative prior.... but I don't think this is it?
Could someone explain whether this is a non-informative prior? If not, can anyone suggest one?
Answer: Edit: This answer seems to entail some confusion about different ways to parameterize the Gamma distribution.  It's probably best to ignore it.

I think I know what's going on. It has to do with a decision about
  what you want your prior to be uninformative about: the rate parameter or the distribution of survival times.
Gamma(0.001, 0.001) has a lot of very small values (close to 0).
When the Exponential distribution's rate parameter is close to zero
  ($\epsilon$), then it has a very high expected value (1/$\epsilon$)
  and is very flat over a wide range of values.
In R, you can see this by plotting an exponential distribution with
  mean .0001 from 0 to 100:
curve(dexp(x, .0001), ylim = c(0, 1E-4), to = 100)
It's essentially uniform (i.e. uninformative) over this range.  It's
  much less flat if you look all the way out to 10000, though, which is
  why you might prefer an even smaller rate parameter.
Hope this makes sense.
Comment: Are you sure that you're interpreting the Gamma distribution to be parametrized by shape and rate rather than shape and scale?  That is, having density $f(x) \propto 1/x$
Comment: Also, I don't understand why being certain that the exponential is uniform should be uninformative.  If we wanted that, we could choose a Gamma prior with shape 0 and rate 10000, which is much more concentrated on small values.  This is *more* informative.
Comment: @NeilG I'm not sure.  user13&c accepted my answer, which may indicate that my description matches their parameterization. Setting the shape to 0 results in an improper distribution, I think, which may be why BUGS doesn't like it.
Comment: @NeilG also, I'm not the first one to suggest that a prior with lots of values close to 0 is uninformative: the Jeffreys prior for lambda is also very concentrated: see Eqn 2.5 here: http://interstat.statjournals.net/YEAR/2008/articles/0804002.pdf
Comment: Oops, I think I linked to the wrong Jeffreys prior.  Try page 64 here.  The general point still stands. http://seor.gmu.edu/~klaskey/SYST664/Bayes_Unit3.pdf
Comment: Hi David, Yes, on page 64 you find that the Jeffreys prior is $f(x) \propto 1/x$ as I wrote above.  If you look at the pdf of the Gamma distribution you will find that that corresponds to shape 0 and rate 0.
Comment: Also, we know the prior cannot have *scale* 0 because then the Bayesian update would never change the scale.  It must be rate 0…
Comment: I think this answer should be corrected…
Comment: @NeilG I'm not sure I understand your concern, although I'd be happy to make a correction if one is warranted.  From your other comments in this thread, it seems like you think the Jeffreys prior is the last word on what's uninformative.  That's not the case. See e.g. [here](http://andrewgelman.com/wp-content/uploads/2012/07/timeseries06272012.pdf). Especially given that User13&c was just looking for intuition and that we both agree that Gamma(0,0) won't actually work for their context, I'm not sure what the problem is.
Comment: Ah, figured out what the disconnect is. I'm busy at the moment, but I'll make sure to see if anything needs to be corrected.
Comment: Your answer, to me, sounds like you're saying that the prior is concentrated at zero, which makes the prior predictive distribution a flat exponential distribution.  To be uninformative, the prior should be the Jeffreys' prior, or at least be flat-ish.  The flatness of the prior predictive (the exponential distribution in this case) is immaterial.
Answer: What does uninformative prior mean to you?
If you mean the Jeffreys prior, then it is $\beta \sim \textrm{Gamma}(0,0)$ as @Daniel points out.
If you mean a flat prior (which isn't uninformative, although it gives the illusion of being uninformative), then it is simply $\beta \sim \textrm{Gamma}(1,0)$, which you can verify by looking at the pdf to be an improper flat prior.
However, if there is a big difference between the priors, then you probably don't have enough data.
Answer: Using $\text{Gamma}(a,b), \; a\approx b \approx 0 $ is uniform logarithmic-ally. This gives the non-informative prior, in terms of what your model want to do with the input data.
As an example of this, you can see this:
http://jmlr.csail.mit.edu/papers/volume1/tipping01a/tipping01a.pdf
search for "gamma".
Also check this out: http://www.stats.org.uk/priors/noninformative/YangBerger1998.pdf
Comment: From my own experience, gamma distribution with parameters close to zero might be quite informative, i.e. even with sample of moderate size. In addition, if you are using WinBUGs, gamma distribution migh give a "headache" for the software. My suggestion would be to use completely flat prior distribution.
Comment: @Tomas: No, he's right. Gamma(0,0) is the Jeffreys prior, and thus truly uninformative.


D3 force simulation in Angular

Question: I'm trying to have a d3 force simulation in Angular app. Basically what I have is run method that initialize and set simulation options and ticked method that updates simulation on each tick. I have a couple of problems related to this. (JavaScript version of the code works just fine)
My initial code is
private run() {
  this.simulation = d3.forceSimulation()
  //some code
  this.simulation.on('tick', this.ticked())
}

private ticked() {
  //code
}

This does not work (simulation does not tick). But if I inline the ticked method like below, it works and simulation continues.
private run() {
  this.simulation = d3.forceSimulation()
  //some code
  this.simulation.on('tick', () => {
   //code
  })
}

Is there a specific reason for this? I'm new to Angular and d3, it might be simple as how JavaScript behaves.
second question, previous code snippet (2nd one) works for few seconds and then simulation freeze. There are no error messages in the console. Can you guess why this is happening?
I hope this is detailed enough. I can add more details if needed.
Comment: `this.ticked()` will execute the function right away and the expression will evaluate to the function's return value. You want to pass the function itself, instead: `this.simulation.on('tick', this.ticked)` (not the missing parentheses) which is basically equivalent to the inlined version which is alread working.
Comment: yep that makes sense. thanks for missing parentheses bit. It's so simple, now I feel stupid about asking this question. Do you have any idea why simulation is stopping after some time.
Answer: The first attempt you made you was passing the return value from your method 'ticked' to the event function.
The event 'on' receives two parameters, the first is the event you are binding to, in this case 'tick' and a callback function that executes when the event returns a value. You was passing as second argument a value, and not a callback function. So it was executing your function before the event was triggered.
You can use your function 'ticked' with the callback like this:
this.simulation.on('tick', () => this.ticked());

Comment: That makes sense. Do you have any idea why simulation is stopping after some time.
Comment: I never used D3 before, but i found this link that maybe answer your question: https://stackoverflow.com/questions/28745398/why-do-we-need-force-ontick-in-d3
Comment: Thanks @Matheus, that question is not directly related but was useful understanding whats going on. I have some clues why its stopping after some time. I will try to investigate bit further. If I didn't get further answers, I'm going to mark this as correct answer tomorrow.

D3 force simulation in Angular


Motivation behind word quotient

Question: Why set of all cosets of a subspace W of a vector space V is called quotient space. What is the motivation behind word quotient?
Comment: Because you have *divided* your whole set into pieces. If you divide a 500g cake into 125g portions, you'll get a quotient set of 4 pieces, 4 = 500/125.
Answer: Because the quotient of $V \times W$ by $W$ is $V$.
(more precisely, the quotient of $V \times W$ by the subspace $\{ 0 \} \times W$ is naturally isomorphic to $V$)
There are more general situations, but that it covers this particular situation is, in my opinion, a pretty strong motivation.
The idea is even clearer in the case of abelian groups; finite abelian groups are sort of like numbers. If $C_k$ denotes a cyclic group of $k$ elements, then the quotient of $C_{mn}$ by the subgroup (isomorphic to) $C_m$ is (isomorphic to) $C_n$.

The notion of quotient can even be applied to pure sets; if $\sim$ is an equivalence relation on a set $S$, then there is a quotient set $S/\!\!\sim$; typically we define this to be the set of equivalence classes.
If every equivalence class has exactly $m$ elements, then $|S /\!\!\sim\!\!| = \frac{|S|}{m}$
Answer: Two possible motivations:
For finite-dimensional vector spaces over finite fields,
$$
|V/W|=|V|/|W|\;.
$$
And for $m\mid n$,
$$
n\mathbb Z/m\mathbb Z\sim(n/m)\mathbb Z\;.
$$
More generally, see also the Wikipedia article on equivalence classes. Whenever the equivalence classes of an equivalence relation all have the same size $d$, forming the quotient with respect to that equivalence relation divides the size of the structure by $d$.

Motivation behind word quotient


BCD to bargraph decoder vhdl design code

Question: The inputs represent a binary value between 0 and 9. There are nine outputs. Each output drives an LED. When an output is 0, its associated LED is ON. When it is 1, its associated LED is OFF. The LEDs are stacked in a vertical bar. The top LED is driven by bar_graph(8) and the bottom LED is driven by bar_graph(0).
I have pasted my code here and it has a few errors and i am not sure if this is the correct way.
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;

entity bcd_2_bar is

port (bcd : in std_logic_vector (3 downto 0);

  bar_graph : out std_logic_vector (8 downto 0));

end bcd_2_bar;

architecture test of bcd_2_bar is

begin

  bar_graph<="111111111" when "0000" else

  bar_graph<="111111110" when "0001" else

  bar_graph<="111111100" when "0010" else

  bar_graph<="111111000" when "0011" else

  bar_graph<="111110000" when "0100" else

  bar_graph<="111100000" when "0101" else

  bar_graph<="111000000" when "0110" else

  bar_graph<="110000000" when "0111" else

  bar_graph<="100000000" when "1000" else

  --nothing is displayed when number greater than nine.

  bar_graph<="111111111" when others;

end test;

Comment: You need to check the correct syntax for "conditional assignment statements".
Answer: Or something like this
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std_unsigned.all;

entity bcd_2_bar is
  generic (
    led_on : std_logic := '0');
  port (
    bcd       : in  std_logic_vector(3 downto 0);
    bar_graph : out std_logic_vector(8 downto 0));
end entity bcd_2_bar;

architecture rtl of bcd_2_bar is
begin
  led_driver: process (bcd) is
  begin
    for led in bar_graph'range loop
      bar_graph(led) <= not led_on when bcd > bar_graph'length else
                        led_on when led < bcd else
                        not led_on;
    end loop;
  end process led_driver;
end architecture rtl;

Answer: You have not written a properly formatted statement. You could do one of the following:
bar_graph <= "111111111" when bcd = "0000" else
             "111111110" when bcd = "0001" else
             "111111100" when bcd = "0010" else
             "111111000" when bcd = "0011" else
             "111110000" when bcd = "0100" else
             "111111111";

or
with bcd select bar_graph <=
             "111111111" when "0000",
             "111111110" when "0001",
             "111111100" when "0010",
             "111111000" when "0011",
             "111110000" when "0100",
             "111111111" when others;

or
process(bcd)
begin
  case bcd is
    when "0000" => bar_graph <= "111111111";
    when "0001" => bar_graph <= "111111110";
    when "0010" => bar_graph <= "111111100";
    when "0011" => bar_graph <= "111111000";
    when "0100" => bar_graph <= "111110000";
    when others => bar_graph <= "111111111";
  end case;
end process;

I didn't include all your bcd values, but you should get the idea.


Deriving the conditional distribution of a multivariate normal, for inequalities

Question: This question is slightly related to Deriving the conditional distributions of a multivariate normal distribution. In that question, the following situation was given.
If $Y$ follows a multivariate normal distribution, $Y \sim N(\mu,\Sigma)$ and you partition $Y$ into $Y = [y_1,y_2]$, how can you derive the resulting conditional distribution of $y_2|y_1=a$? In words, if you start from a  multivariate normal distribution, and you fix some of the values($y_1=a$), what is the conditional distribution of the remaining elements of $Y$?
My question is, how can you arrive at the conditional distribution $y_2|y_1<a$, again for $Y \sim N(\mu,\Sigma)$ and $Y = [y_1,y_2]$?
It seems to me that the approach used in the case $y_2|y_1=a$ does not work here.
Answer: We find $f_{Y_1,Y_2}(y_1|y_2)$, which is normal, with mean as a function of $y_2$, $\mu_{y_1|y_2}(y_2)$ and deviation, $\sigma$, as shown in the wiki page. Then, we can calculate $P(Y_1<a|Y_2=y_2)=\Phi\left(\frac{a-\mu(y_2)}{\sigma}\right)=\phi(y_2)$.
Using Bayes Rule, we'd have
$$f_{Y_2|Y_1<a}(y_2)=\frac{P(Y_1<a|Y_2=y_2)f_{Y_2}(y_2)}{P(Y_1<a)}\propto \phi(y_2)f_{Y_2}(y_2)$$
which isn't normal any more (in general) due to the term $\phi(y_2)$.
This was for the bivariate case (your variables seem to be), but can be generalized into multivariate similarly if you like. However, $y_1$ is always univariate since you compare it with a constant.


Best way to insert footer on certain pages Laravel

Question: I added footer component in app.blade.php
@if(!isset($noFooter))
@include('footer/full')
@endif

As you can see there is that if that checks is the variable is present. If it is then the footer is inserted. I think that this is a bad practice and I wonder how can I make this better.
I want to show footer on all pages except a few, like login/register page, my account page etc.
So at this moment I just pass this variable $noFooter in controller to the routes that I don't want the footer. Do you know a better way to do this?
Answer: You can achieve this by checking current url usign \Route facade. Something like below code may help you:
@if(in_array(\Route::currentRouteName(),['login', 'register']))
    @include('footer/full')
@endif

Answer: Not sure about bad practice, but if there is a condition, there would be "if" somewhere.
You mentioned that only a few pages won't show the footer, you can check whether the current page is in the list.
@php
    $pageList = collect(['login', 'register']);
@endphp
@if(!$pageList->contains(request()->path()))
    @include('footer/full')
@endif


Codeigniter session not working with long array

Question: I have to assign a long array to a codeigniter session but its not working. If I am using an array with three four element then this work. My array is given below.
     $value['id']                   = $checkout_product['checkout']['id'];
     $value['user_id']              = $checkout_product['checkout']['user_id'];
     $value['name']                 = $checkout_product['checkout']['name'];
     $value['maker']                = $checkout_product['checkout']['maker'];
     $value['model']                = $checkout_product['checkout']['model'];
     $value['color']                = $checkout_product['checkout']['color'];
     $value['size']                 = $checkout_product['checkout']['size'];
     $value['slug']                 = $checkout_product['checkout']['slug'];
     $value['route_id']             = $checkout_product['checkout']['route_id'];
     $value['description']          = $checkout_product['checkout']['description'];
     $value['quantity']             = $checkout_product['checkout']['quantity'];
     $value['p_units']              = $checkout_product['checkout']['p_units'];
     $value['images']               = $checkout_product['checkout']['images'];
     $value['label_type']           = $checkout_product['checkout']['label_type'];
     $value['product_type']         = $checkout_product['checkout']['product_type'];
     $value['auction_id']           = $checkout_product['checkout']['auction_id'];
     $value['product_id']           = $checkout_product['checkout']['product_id'];
     $value['budget_min']           = $checkout_product['checkout']['budget_min'];
     $value['budget_max']           = $checkout_product['checkout']['budget_max'];
     $value['bid_start_date']       = $checkout_product['checkout']['bid_start_date'];
     $value['bid_end_date']         = $checkout_product['checkout']['bid_end_date'];
     $value['status']               = $checkout_product['checkout']['status'];
     $value['bid_id']               = $checkout_product['checkout']['bid_id'];
     $value['bidder_id']            = $checkout_product['checkout']['bidder_id'];
     $value['bid_product_id']       = $checkout_product['checkout']['bid_product_id'];
     $value['bid_date']             = $checkout_product['checkout']['bid_date'];
     $value['bid_qty']              = $checkout_product['checkout']['bid_qty'];
     $value['bid_amount']           = $checkout_product['checkout']['bid_amount'];
     $value['total_amount']         = $checkout_product['checkout']['total_amount'];
     $value['payable_amount']       = $checkout_product['checkout']['payable_amount'];
     $value['shipping_in']          = $checkout_product['checkout']['shipping_in'];
     $value['shipping_method']      = $checkout_product['checkout']['shipping_method'];
     $value['shipping_amount']      = $checkout_product['checkout']['shipping_amount'];
     $value['pro_type']             = $checkout_product['checkout']['pro_type'];
     $value['warranty_month']       = $checkout_product['checkout']['warranty_month'];
     $value['warranty_type']        = $checkout_product['checkout']['warranty_type'];
     $value['bid_note']             = $checkout_product['checkout']['bid_note'];
     $value['bid_status']           = $checkout_product['checkout']['bid_status'];
     $value['customer_id']          = $checkout_product['checkout']['customer_id'];
     $value['customer_username']    = $checkout_product['checkout']['customer_username'];
     $value['customer_firstname']   = $checkout_product['checkout']['customer_firstname'];
     $value['customer_lastname']    = $checkout_product['checkout']['customer_lastname'];
     $value['customer_email']       = $checkout_product['checkout']['customer_email'];
     $value['customer_image']       = $checkout_product['checkout']['customer_image'];

     $this->session->set_userdata('checkout', $value);

This code is not working for me. Please help me how I can post big array in session in codeigniter.
Comment: I would use the database to store your sessions: https://ellislab.com/codeigniter/user-guide/libraries/sessions.html Also, it looks like you're making a cart. Have you looked at CI's built-in cart class? https://ellislab.com/codeigniter/user-guide/libraries/cart.html
Answer: By default CodeIgniter stores the session data in a cookie, which has an upper limit of 2KB-4KB in size depending on browser.
If you are trying to store more than 4KB of data in the session you will start running into issues.
The easiest solution is to store the session details in the DB. The Codeigniter session documentation details the process for storing the session in the DB.
Comment: Thanks Vinod VT for your helpful answer. Can I encrypt such kind of array. I have checked when I try to encrypt big array then this skip some data.
Comment: @hirasingh why not seralize the array?
Comment: @hirasingh there is no point in "thinking" you have access to a development environment. Try it out and see
Comment: @DarylGill I have checked before. This skipped some data. when I tried to unseralize this, only half array was printed.


Jersey on Tomcat 7 throws java.net.SocketException: Invalid argument

Question: I've built two Jersey web applications and running both of them on Tomcat 7. For the sake of simplicity I'll call them "App A" and "App B".
There is an endpoint on "App A" that internally makes an HTTP request to "App B".
When consuming this endpoint on "App A" in Java, it occasionally returns the following exception when trying to make the request to "App B":
java.net.SocketException: Invalid argument
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.read(SocketInputStream.java:150)
    at java.net.SocketInputStream.read(SocketInputStream.java:121)
    at org.apache.http.impl.conn.LoggingInputStream.read(LoggingInputStream.java:67)
    at org.apache.http.impl.io.SessionInputBufferImpl.streamRead(SessionInputBufferImpl.java:130)
    at org.apache.http.impl.io.SessionInputBufferImpl.fillBuffer(SessionInputBufferImpl.java:146)
    at org.apache.http.impl.io.SessionInputBufferImpl.readLine(SessionInputBufferImpl.java:259)
    at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:141)
    at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:58)
    at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:262)
    at org.apache.http.impl.DefaultBHttpClientConnection.receiveResponseHeader(DefaultBHttpClientConnection.java:163)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.http.impl.conn.CPoolProxy.invoke(CPoolProxy.java:138)
    at com.sun.proxy.$Proxy141.receiveResponseHeader(Unknown Source)
    at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:272)
    at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:124)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:254)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:176)
    at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:77)
    at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:101)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:106)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:57)

The exception happens exactly where "App A" tries to make a request to "App B". This happens with Tomcat 7 running in Eclipse, and also when it runs standalone. And it happens with both MacOSX 10.9 and Centos 6.
Trying to make the same request with Python, it ocassionally returns the same exception:
  File "/Library/Python/2.7/site-packages/requests/api.py", line 88, in post
    return request('post', url, data=data, **kwargs)
  File "/Library/Python/2.7/site-packages/requests/api.py", line 44, in request
    return session.request(method=method, url=url, **kwargs)
  File "/Library/Python/2.7/site-packages/requests/sessions.py", line 361, in request
    resp = self.send(prep, **send_kwargs)
  File "/Library/Python/2.7/site-packages/requests/sessions.py", line 464, in send
    r = adapter.send(request, **kwargs)
  File "/Library/Python/2.7/site-packages/requests/adapters.py", line 356, in send
    raise ConnectionError(e)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.1', port=8080): Max retries exceeded with url: /mashape-apis-database-server/v1/tags/ (Caused by <class 'httplib.BadStatusLine'>: '')

I'm running Java 1.7.0_25, Jersey 2.4.1, Tomcat 7, and MacOSX 10.9 (or Centos 6).
Answer: Running the apps on separate Virtual Machines fixed the problem.


How to configure Apache to rewrite following condition?

Question: I'd like to enable Apache mod_rewrite to work as follow:
www.mysite.example/g/abcde   "redirect" to www.mysite.example/mypage.php?code=abcde&mode=g

and
www.mysite.example/v/abcde   "redirect" to www.mysite.example/mypage.php?code=abcde&mode=v

My questions are:

How to configure mod_rewrite in my Ubuntu 18.04 installation ?
How to write that configurations ?
Answer: I solved:
RewriteRule ^g/([A-Za-z0-9-/_]+)?$ /g.php?param1=$1&%{QUERY_STRI$


When was baseball introduced to Latin America?

Question: I was watching Sports Center this morning and realized that baseball has a lot of players of Hispanic origin.
When was baseball first introduced to Latin America? When did recruiting Latin American / Hispanic players become fairly commonplace? Beyond that, why are/were so many Latin American players recruited for baseball?
Answer: I'll start with the why.
The reason that there are so many Latin American baseball players is manifold. It's part socioeconomic, part lack of professional sports opportunities in their home countries and it's part the amount of money, time and effort various Major League Baseball (MLB) organizations have put into recruiting and signing Latin born players. Similar efforts are going on in Korea and other Asian countries, however they have not met with the same success, probably because there is not quite the same rich history of baseball tradition in those countries (although it's coming)
Let's start with the socioeconomic/lack of pro-sports opportunity issue. In most places in Latin America, if you want to play pro sports you play soccer (futbol). It's the only major organized professional sport in several countries, and the only one besides baseball in most of the others. However, the salaries are not like professional sports in the US or Europe, and while they are a decent living, most truly amazing players in soccer or in baseball quickly find themselves whisked away to better competition in the US or Europe.
While Latin America is progressing economically, many of these countries have huge areas of poverty. For kids with athletic talent sports is a great way to get out of where you are and find a better life (same can be said of many low income folks in the US as well). Baseball, like soccer is an easy sport to find equipment for (you don't kneed a glove or a real bat, just a ball and a broom handle if you really want to play). With low barriers to entry it can become a fun game for kids to play in the street and they can get quite good.
Baseball teams have capitalized on this desire to make a better life, and the abundance of athletic children with limited opportunities in their home countries and have opened academies in several Latin American countries (Puerto Rico (I know Us territory, but still), the Dominican and Venezuela are the primary ones), and have begun recruiting kids at very young ages. Children as young as 16 may be signed by MLB teams.
Until the current Collective Bargaining Agreement (CBA) MLB has been fairly lax as to how much money these players can be given (the new CBA now has a pool of money that may be spent on international signings of players under 19). Because theses players do not have to go through a draft process they are free agents and may go to the highest bidder. Recent young Cuban defectors have signed for millions of dollars upfront.
So the why, in my opinion, is a combination of lack of opportunities in their home countries, combined with a significant investment on the part of MLB teams and also the ability for teams to freely sign these players rather than force them through the draft (although this part is going away gradually).
Finally lets get some history. Obviously for the above to have happened there has to be some history here.
Baseball came to Latin America in the late 1800s starting in Cuba and Venezuela shortly thereafter. According to the Hispanic Baseball Museum Cubans have been playing in the United States since 1871. And the first Hispanic to play in the Major Leagues was Louis Castro in 1902. So we have well over 100 years of Hispanic players playing major league baseball and doing very well doing it. Significantly, black Latinos did not start playing in the Major Leagues until 1949.
According to the timeline MLB clubs have been routinely recruiting in Latin America since Cincinnati around 1911. The first baseball academy in the Dominican did not open until 1973 (although I suspect they opened in other places much earlier). There are numerous Hispanic Hall of Famers. And many more successful players that have not made it to the hall of fame. Based on this, and the fact that MLB teams continue to invest heavily in Latin America, it looks like MLB's investments in Latin America are both historic and seemingly well founded.
Answer: Baseball has been popular in Latin America since the 1800's. it was Cuba's national sport i beleive, and was more popular than soccer. heres a link about the history of latin american baseball:
http://www.ehow.com/about_6374367_history-latin-american-baseball.html
As far as why latin americans are recruited, well, if you think about it, there still are many more players from north america then latin americans. but since the latin americans had thier own leagues and everything, mlb teams starting recruiting the stars from across the globe. the same goes fro all the japenese players.
well, i hope that helped, if it didnt, tell me why and ill try to be more specific.
Answer: Actually the first Latin American player in the Majors, was Esteban Bellan, a Cuban.  He played for the Troy Haymakers of the National Baseball Association.  The Association became the National League in 1876.
Furthermore, it was the Cubans who took baseball to Venenzuela, as well as the Dominican Republic, Puerto Rico and the eastern coast of Mexico. In northern Mexico and Nicaragua, it was the Americans whos took the nation's past time there.
Comment: Could you source these claims?


Radius of convergence of $\sum_{n=1}^{\infty} {\frac{ \sin^nx + 2}{x^{2n} + 1}}$

Question:
Calculate the radius of convergence of  $\sum_{n=1}^{\infty} {\frac{ \sin^nx + 2}{x^{2n} + 1}}$

When I tried, I got that $-1 < x < 1$ and when checking edges ($x=-1,x=1$) the two were divergent.
Is that correct?
Comment: $\sin(x^n+2)$ or $\sin(x^n)+2$ or $(\sin x)^n+2$?
Comment: the third, sorry. edited.
Comment: This is not a power series so we may say about the set of convergence only. If $|x| \le 1$, then the necessary condition of convergence of a number series fails.
Answer: You can't say anything for the radius of convergence because you are not dealing with a power series. However, as you've already noticed the series diverges for $ |x|\le 1$ because
$$
\frac{\sin^nx+2}{x^{2n}+1} \ge \frac12 \quad \forall |x|\le 1.
$$
For $|x|>1$ the series converges because we have
$$
\frac{1}{x^{2n}+1}\le \frac{\sin^nx+2}{x^{2n}+1} \le 3\left(\frac{1}{x^2}\right)^n \quad \forall |x|>1
$$
Answer: First at all note that the given series isn't a power series so you can't tell about the radius of convergence but rather we look for the set of $x$ for which the series is well defined.
A necessary condition for the convergence of the series is
$$\lim_{n\to\infty}\frac{ \sin^nx + 2}{x^{2n} + 1}=0\iff |x|>1$$
Now we verify that this condition is suffisant:
$$\left|\frac{ \sin^nx + 2}{x^{2n} + 1}\right|\leq \frac{3}{x^{2n}}=3 \left(x^{-2}\right)^n=v_n$$
so for $|x|>1$ the given series is (absolutely) convergent by comparison with the geometric convergent series $\displaystyle \sum_n v_n$ and we conclude:
$$\text{  the given series is defined for }\ x\in(-\infty,-1)\cup (1,+\infty)$$
Answer: You can't give it a radius of convergence because it's not of the form $\sum a_n x^n$.
For $x=0$, you get $\sum 2$ which obvious diverges.
But for $x=\pi$, you get $\sum \cfrac{2}{\pi^{2n}+1}$ which converges.
So a radius of convergence would be of little help since it wouldn't tell you anything about what converges and what does not.


Permission restrictions deny you access to this broken link

Question: In Reports -> Broken links page for some records it is showing

permission restrictions deny you access to this broken link

Site have only one language also, some of the broken links are showing with https link also. So I don't think the problem with protocol or language.
What is the part of link-checker cron. It was not running and i tried running it manually? But still the broken link is not showing (which I intentionally put some broken link).
What else could be the problem? How to resolve this issue?
Please suggest other than "Re-Analyze link data", that removes all old records also not showing the new one.
Answer: I was able to view what the links were by modifying linkchecker.pages.inc line 158 to be the following:
if (empty($nids) && empty($cids) && empty($bids) && !user_access('bypass node access')) {

With this change, assuming that you have bypass node access, you will be able to see the links instead of the annoying message. Unfortunately, the "Edit Link Settings" option will not work for these rows still, because the link data may be out of date. (There are no nodes, comments, or blocks that have the link.)
In order to fix the result list for real, I ran the following drush commands, one after the other. They are defined in linkchecker.drush.inc:
drush linkchecker-analyze

Reanalyzes content for links. Recommended after module has been upgraded. This can also be done from the settings page: /admin/config/content/linkchecker
drush linkchecker-check

Check link status. (Note that this doesn't check them all, only the batch number set in your linkchecker settings.)

If necessary, you may also try running this first:
drush linkchecker-clear

Clears all link data and analyze content for links. WARNING: Custom link check settings are deleted. This can also be done from the settings page: /admin/config/content/linkchecker
Answer: One possible reason for your manual edit/test run not being flagged by Linkchecker is that the linkchecker scan didn't include your edit in the batch of content/data scanned.
The Linkchecker module's cron job only processes batches of content at a time (similar to Drupal's built-in search index), and may need to be run several times if there's a lot of content being generated during the course of the day.

With respect to the error message you're seeing

permission restrictions deny you access to this broken link

on the Broken Links report page, you should check to make sure the module is up-to-date.

If your site is still running version 7.x-1.1, then LinkChecker may be showing the error because of the cross domain issue previously reported here: https://www.drupal.org/project/linkchecker/issues/2264181
If your site is running a more recent/current version of LinkChecker, you may still be encountering the language issue if the site is old.  Some content may have no language attribute (undefined), while others reflect (english).  If this is the case, you can bulk set the language attribute of all the nodes.  Refer to How can I set the language of nodes in bulk to existing content when making a site multilingual?
This error message is also known to occur when a link points to an unpublished node or any content/view pages that require authentication/sign-in.


Remove Mouthpiece Tarnish

Question: I have a fifty year old F.E. Olds & Sons Ambassador cornet. It lay unused for 30+ years (it is now oiled and greased properly). There is considerable tarnish on the mouthpiece and on the slides. Any suggestions for removing the tarnish?
Will toothpaste or aluminum foil work, or will they have side affects to the tarnished area?
Answer: The mouthpiece is likely silver plated; silver polish will work well on that, as would the aluminum foil trick. (Since it's silver plated as opposed to solid silver, perhaps try that trick first.)
I think the aluminum foil trick: http://scifun.chem.wisc.edu/homeexpts/tarnish.html will likely be the least damaging, but I'm not an expert in metallurgy.
The slides could be silver plate, or (in my opinion more likely) nickel plate. My nickel plated trombone bell didn't tarnish as "dark" as my solid silver one. It was more of a brassy look, likely because of the copper in the nickel silver. I can't say you'll always be able to tell the difference… but it's a shot.
Nickel silver can usually be cleaned and polish like silver; all mine have been fine with that, as it's designed to be a silver look-alike. Check out this resource: http://www.ehow.com/how_5210485_clean-nickel-silver.html.
I don't personally know about toothpaste, as I haven't heard of it's use. I'd imagine it'd put a slight patina of small scratches on any polished metal, as it's an abrasive.
Whichever technique you ultimately use, clean all pieces thoroughly before reassembling and using.
Comment: As for toothpaste, abrasives making scratches is how we create a brilliant polish, as when we grind a mirror or lens. It's a matter of creating *small, very fine* scratches. Toothpaste is a fine enough abrasive that you will not have to worry about dulling the metal finish.

Remove Mouthpiece Tarnish


How can i overcome a decimal place issue when using int(float(x)?

Question: I have a csv file that I am using that is made up of several fields.
I am adding the name fields - to get full name and then pulling out the price and qty fields - which are strings in the CSV file.
def mapper(self, key, value):
            fields = value.split(",")
            name = fields[6] + " " + fields[7]
            Price = int(float(fields[4]))
            Qty = int(fields[5])
            avgPrice = (Price*Qty)
            yield name,avgPrice

my output is giving me
Becca Nelson 25.0
but i am missing the decimal places i think it is because I  have had to use int(float(x)
I want the output to be
Becca Nelson 25.55
How can i get around this?
Comment: when you call int you're "killing" de decimal point part, why would you call int in a variable that you want to be float?
Answer: You could use standard python module decimal to accurately process real values.
from decimal import Decimal

def mapper(self, value):
    fields = value.split(",")
    name = fields[6] + " " + fields[7]
    price = Decimal(fields[4])  # here
    qty = int(fields[5])
    avg_price = price * qty
    return name, avg_price

Also I'd recommend you use csv reader and pandas instead of string operations (example).
Comment: Thank you @Vladimir I will attempt this.


zipping encrypted files in Java

Question: Having trouble zipping the files. The application I'm making lets you add a password to a group of files, those files are then encrypted with DES (in the process of changing to AES ) then saved to a folder. But how to zip them after they've been encrypted and password protected? I've specified where the encryption begins to make it easier.
package gui;
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.security.AlgorithmParameters;
    import java.security.spec.KeySpec;

    import javax.crypto.Cipher;
    import javax.crypto.CipherInputStream;
    import javax.crypto.CipherOutputStream;
    import javax.crypto.SecretKey;
    import javax.crypto.SecretKeyFactory;
    import javax.crypto.spec.IvParameterSpec;
    import javax.crypto.spec.PBEKeySpec;
    import javax.crypto.spec.SecretKeySpec;
    import javax.swing.ImageIcon;
    import javax.swing.JFileChooser;
    import javax.swing.JMenuItem;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;

    public class FileTable extends JPanel {

        /**
         *
         */
        private static final long serialVersionUID = 1L;
        private JTable table;
        private DefaultTableModel tableModel = new DefaultTableModel(new String[] {"File", "Size", "Status" }, 0);
        private File dir;
        private File temp;
        private JPopupMenu popup;
        private String key;
        private PasswordStorage passwordStorage;
        private JFileChooser fileChooser;
        private static String salt = "loquetdeliciouslysalty";
        private static byte[] IV;

        public FileTable() {

            // Set Layout Manager
            setLayout(new BorderLayout());

            // Create Swing Components
            table = new JTable();
            table.setModel(tableModel);
            table.setDropTarget(new TableDnD(table));
            table.setShowGrid(false);
            table.setFillsViewportHeight(true);
            table.getColumnModel().getColumn(0).setPreferredWidth(250);

            passwordStorage = new PasswordStorage();
            fileChooser = new JFileChooser();
            popup = new JPopupMenu();

            JMenuItem removeItem = new JMenuItem("Remove");
            removeItem.setIcon(new ImageIcon("removeMenu.png"));
            popup.add(removeItem);

            // Add Components to pane
            add(new JScrollPane(table), BorderLayout.CENTER);

            table.addMouseListener(new MouseAdapter() {
                public void mousePressed(MouseEvent e) {
                    int row = table.rowAtPoint(e.getPoint());
                    table.getSelectionModel().setSelectionInterval(row, row);

                    if(e.getButton() == MouseEvent.BUTTON3) {
                        popup.show(table, e.getX(), e.getY());
                    }
                }
            });

            removeItem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {
                    int row = table.getSelectedRow();
                    if(row > -1) {
                        tableModel.removeRow(table.getSelectedRow());
                    }
                }
            });
        }

        public boolean isTableEmpty() {

            if(tableModel.getRowCount() == 0) {
                return true;
            }
            else {
                return false;
            }
        }

        public void addFile(File file) {
            tableModel.addRow(new Object[]{file, file.length() + " kb","Not Processed"});
        }

        public void removeFile() {
            int[] rows = table.getSelectedRows();

            for(int i = 0; i < rows.length; i++) {
                tableModel.removeRow(rows[i]-i);
            }
        }

        public void clearTable()
        {
            int rowCount = tableModel.getRowCount();

            for(int i = 0; i < rowCount; i++) {
                tableModel.removeRow(0);
            }

            table.removeAll();
        }

        public void encrypt() {

            if(!isTableEmpty()) {
                try {
                    do {
                        key = JOptionPane.showInputDialog(this,
                                "Enter password", "Password",
                                JOptionPane.OK_OPTION|JOptionPane.PLAIN_MESSAGE);   // key needs to be at least 8 characters for DES

                        if(key == null) break;
                    } while(key.length() < 8);

                    // If OK and length of password >= 8 encrypt files
                    if(key != null) {

                        // Store password
                        passwordStorage.write(key);

                        // Custom Folder for encrypted files
                        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

                        if(fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
                            dir = fileChooser.getSelectedFile();
                        }

                        else {
                            // Default Folder for decrypted files
                            dir = new File("encrypted");
                            dir.mkdir();
                        }

                        for(int i = 0; i < tableModel.getRowCount(); i++) {
                            temp = (File) tableModel.getValueAt(i, 0);

                            FileInputStream fis2 = new FileInputStream(temp);
                            FileOutputStream fos2 = new FileOutputStream(dir + "\\" + (temp.getName()));

                            encrypt(key, fis2, fos2);
                        }

                        for(int i = 0; i < tableModel.getRowCount(); i++) {
                            File toDelete = (File) tableModel.getValueAt(i, 0);
                            toDelete.delete();
                        }

                        // Encryption complete message
                        JOptionPane.showMessageDialog(this, "Files encrypted succesfully!");

                        // CLEAR LIST
                        table.removeAll();
                        clearTable();
                    }
                } catch (Throwable te) { te.printStackTrace(); }
            }
        }

        public void decrypt() {

            if(!isTableEmpty()) {
                try {

                    key = JOptionPane.showInputDialog(this,
                            "Enter password", "Password",
                            JOptionPane.OK_OPTION|JOptionPane.PLAIN_MESSAGE);

                    while(!passwordStorage.isPassword(key)) {
                        key = JOptionPane.showInputDialog(this,
                                "Enter password", "Wrong Password!",
                                JOptionPane.OK_OPTION|JOptionPane.ERROR_MESSAGE);
                    }

                    // If OK and length of password >= 8 decrypt files
                    if(key != null) {

                        // Custom Folder for decrypted files
                        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

                        if(fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
                            dir = fileChooser.getSelectedFile();
                        }

                        else {
                            // Default Folder for decrypted files
                            dir = new File("decrypted");
                            dir.mkdir();
                        }

                        for(int i = 0; i < tableModel.getRowCount(); i++) {
                            temp = (File) tableModel.getValueAt(i, 0);

                            FileInputStream fis2 = new FileInputStream(temp);
                            FileOutputStream fos2 = new FileOutputStream(dir + "\\" + (temp.getName()));

                            decrypt(key, fis2, fos2);
                        }

                        for(int i = 0; i < tableModel.getRowCount(); i++) {
                            File toDelete = (File) tableModel.getValueAt(i, 0);
                            toDelete.delete();
                        }

                        // Encryption complete message
                        JOptionPane.showMessageDialog(this, "Files decrypted succesfully!");

                        // CLEAR LIST
                        table.removeAll();
                        clearTable();
                    }
                } catch (Throwable te) { te.printStackTrace(); }
            }
        }

        /*************************************************************************************************************
         *      ENCRYPTION METHODS ***********************************************************************************
         *************************************************************************************************************/
        public static void encrypt(String key, InputStream is, OutputStream os) throws Throwable {
            encryptOrDecrypt(key, Cipher.ENCRYPT_MODE, is, os);
        }

        public static void decrypt(String key, InputStream is, OutputStream os) throws Throwable {
            encryptOrDecrypt(key, Cipher.DECRYPT_MODE, is, os);
        }

        public static void encryptOrDecrypt(String key, int mode, InputStream is, OutputStream os) throws Throwable {

            char[] kgen = key.toCharArray();
            byte[] ksalt = salt.getBytes();

            SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
            KeySpec spec = new PBEKeySpec(kgen, ksalt, 65536, 256);
            SecretKey tmp = factory.generateSecret(spec);
            SecretKey aesKey = new SecretKeySpec(tmp.getEncoded(), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

            /*DESKeySpec dks = new DESKeySpec((salt + key).getBytes());
            SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
            SecretKey desKey = skf.generateSecret(dks);
            Cipher cipher = Cipher.getInstance("DES"); // DES/ECB/PKCS5Padding for SunJCE*/

            if (mode == Cipher.ENCRYPT_MODE) {
                cipher.init(Cipher.ENCRYPT_MODE, aesKey);
                CipherInputStream cis = new CipherInputStream(is, cipher);
                AlgorithmParameters params = cipher.getParameters();
                byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
                saveIv(iv);
                doCopy(cis, os);
            } else if (mode == Cipher.DECRYPT_MODE) {
                cipher.init(Cipher.DECRYPT_MODE, aesKey, new IvParameterSpec(getIv()));
                CipherOutputStream cos = new CipherOutputStream(os, cipher);
                doCopy(is, cos);
            }
        }

        public static void saveIv(byte[] iv) {
            IV = iv;
        }

        public static byte[] getIv() {
            return IV;
        }

        public static void doCopy(InputStream is, OutputStream os) throws IOException {

            byte[] bytes = new byte[1024];
            int numBytes;

            while ((numBytes = is.read(bytes)) > 0) {
                os.write(bytes, 0, numBytes);
            }

            os.flush();
            os.close();
            is.close();
        }

    }

Answer: One remark, I did not see an invokeLater to do the encryption after event handling.

Compress first (if desired), GZipOutputStream to turn a .txt  file into a .txt.gz file.
Encrypt
Zip to have one file, ZipOutputStream, without compression, by setMethod(ZipOutputStream.STORED)

Replace
                for(int i = 0; i < tableModel.getRowCount(); i++) {
                    temp = (File) tableModel.getValueAt(i, 0);
                    FileInputStream fis2 = new FileInputStream(temp);
                    FileOutputStream fos2 = new FileOutputStream(dir + "\\"
                            + (temp.getName()));
                    encrypt(key, fis2, fos2);
                }

by
                // Zip
                ZipOutputStream zipOut = ...
                zipOut.setMethod(ZipOutputStream.STORED); // No compression.

                for(int i = 0; i < tableModel.getRowCount(); i++) {
                    // Single file
                    File originalFile = (File) tableModel.getValueAt(i, 0);
                    FileInputStream originalStream = new FileInputStream(originalFile);

                    // GZipped single file:
                    GZipOutputStream gzipOut = ...; ...

                    // Input of the gzipped thing
                    InputStream gzipResultIn = ...

                    // Make a new ZipEntry:
                    ZipEntry zipEntry = new ZipEntry(originalFile.getName()
                            + ".gz.enc");
                    zipOut.putNextEntry(zipEntry);
                    encrypt(key, gzipResultIn, zipOut); // Should not close the input
                    zipOut.closeEntry();
                }

                zipOut.close();

Using pipes (connecting input and output, PipedInputStream, PipedOutputStream) for the gzipped intermediate result would be even nicer. But you may try ByteArrayOutputStream, ByteArrayInputStream, or as you did a temp file, first.
Answer: There is little reason to perform zipping after encryption, as compression requires that the input data contains patterns that can be compressed. Encryption on the other hand will produce a ciphertext that is indistinguishable from random. So chances are very high that this data cannot be compressed. You should compress data before encryption instead.
Answer: Just instantiate your file streams and use:
http://docs.oracle.com/javase/6/docs/api/java/util/zip/GZIPOutputStream.html

zipping encrypted files in Java


Need an Explanantion

Question: I hope someone could spend some seconds to help me understanding this paragraph.
 The paper by Von Neumann:
This part is little bit confusing for me

Let $E$ be a set of positive measure which contains no measurable subsets of smaller positive measure. It follows that for each $n$ one of the two sets, $EA_n$, and $E(X-A_n)$ has measure zero and the other one has measure $m(E)$.

My question is : what does this notation $EA_n$ mean, and the main idea of this part
This is the reference
The Neumann Compendium, p.146
Comment: I think somtimes instead of writing $A \cap B$, some authors write $AB$, for sets
Answer: It just means $E \cap A_n$.  You may have heard some people talk about "set algebra" or "Boolean algebra".  It's possible to interpret set operations as an algebra with $A + B = A\cup B$ and $A\times B = A\cap B$.  (The comutitivity, transitivity and distributivity properties all still hold).
If you replace $EA_n$ with $E\cap A_n$  and $E(X-A_n)$ with $E\cap (X_n - A_n)$ the meaning should be clearer.
Comment: Excellent, thanks alot yes I have heard about Set algebra and Boolean algebra.

Need an Explanantion


cometd bayeux client can't get subscribed acknowledgement?

Question: Actually i am running cometd-demo server in my local using maven jetty run shown in the doc https://docs.cometd.org/current/reference/ and trying to subscribe and publish something in a broadcast channel. Using Groovy script shown below,
ClientSessionChannel.MessageListener mylistener = new Mylistener();

def myurl = "http://localhost:8080/cometd/"

MyHttpClient httpClient = new MyHttpClient();

httpClient.start()

Map<String, Object> options = new HashMap<String, Object>();

ClientTransport transport = new LongPollingTransport(options, httpClient);

BayeuxClient client = new BayeuxClient(myurl, transport)

println 'client started on URL : '+ client.getURL()

client.handshake ( new ClientSessionChannel.MessageListener() {

    public void onMessage(ClientSessionChannel channel, Message message) {
        if (message.isSuccessful()) {
            println 'Handshake Message : ' + message
        }
    }
})

boolean handshakecheck = client.waitFor(1000, BayeuxClient.State.CONNECTED);

println 'Handshake check : '+ handshakecheck

    client.batch( new Runnable() {

        public void run() {

            client.getChannel("/foo/hello").subscribe(

                    new ClientSessionChannel.MessageListener() {

                        public void onMessage(ClientSessionChannel channel,
                                              Message message) {
                                println "subscribed : "+ message
                        }
                    })
        }

    });

The program Output :
client started on URL : http://localhost:8080/cometd/
Handshake Message : [minimumVersion:1.0, clientId:fv0ozxw8cb5e11vtlwpacm7afp, supportedConnectionTypes:[websocket, long-polling, callback-polling], advice:[reconnect:retry, interval:0, maxInterval:10000, timeout:20000], channel:/meta/handshake, id:1, version:1.0, successful:true]
Handshake check : true

Here I can't get the subscribed message as in the code. But in server log It prints like shown below,
2018-02-12 20:30:32,687 qtp2069584894-17 [ INFO][examples.CometDDemoServlet] Monitored Subscribe from fv0ozxw8cb5e11vtlwpacm7afp,last=0,expire=0 for /foo/hello

Update 1:
Also i can't subscribe with callback method, i get the message as  [channel:/meta/subscribe, id:4, subscription:/foo/hello, error:403:denied_by_not_granting:create_denied, successful:false].  I don't know what i am doing wrong ? I am just following the documentation steps. Thanks in advance.
Comment: where are you publishing a message?
Comment: @BojanPetkovic at same channel.. but it doesn't matter before that i can't get the subscribed message in client side onMessage.. am i saying correct..?
Comment: Error : 403. means forbidden, likely that topic can only have messages published from accounts, which your listener does not have access to.

You likely cannot get messages in the subscribe part, since no messages were sent.  From your log: "last=0" <- seems to indicate no messages were sent yet.
Comment: @BojanPetkovic Then How to publish & subscribe properly.. it is little confusing ?
Answer: The ClientSessionChannel.MessageListener that you pass to the subscribe(...) method will be invoked whenever a message will be published on channel /foo/hello.
Your program never publishes a message on that channel, so the listener is never invoked, therefore in your code subscribed is never printed.
You want to double check what version of the subscribe() method you want to use, as there are 2 versions.
The single parameter version takes a listener, while the two parameter version takes a listener and a callback.
Guessing from your code, you want the subscribed log line be in the callback not in the listener, so you just need to change your code to use the two parameter version of the subscribe() method.
Also, pay attention to the fact that if the JVM exits at the end of your groovy script, then that client will be gone and will never receive any message.
Comment: As you said, Also I tried `subscribe` with callback method. It shows `error:403:denied_by_not_granting:create denied`
Comment: This happens because the CometD demo server restricts the channels a client can publish to, see [this section](https://docs.cometd.org/current/reference/#_java_server_authorizers) of the documentation.  Change the channel in your example from `/foo/hello` to `/chat/hello` and you will succeed.  The authorizers for the demo are defined in [this file](https://github.com/cometd/cometd/blob/3.1.3/cometd-java/cometd-java-examples/src/main/java/org/cometd/examples/ChatService.java).
Comment: sorry for my Late response. Learned . As you said in answer, What is the correct way to keep the Bayeux Client JVM to recieve the published results inside the subscribe


How to display api call response in Reactjs

Question: I am new in Reactjs and i am working with nextjs, i tried to integrate "newsletter",
I created a component for this which is working fine but i am unable to display "success" or "error"
message in screen/WebsitePage,i am getting "success" message in console but "success/error" message
not showing
Here is my code
import React, { useEffect, useState } from "react";

const Subscribe = () => {
 const [email, setEmail] = useState('');
 const [error, setError] = useState('');
 const [success, setSuccess] = useState('');

const subscribeMe = async (event) => {
            const emails = email;
            event.preventDefault();
            const res = await fetch('https://example.com/admin-panel/Api/subscribe?email='+emails);
            const { error, message } = await res.json();
            if (error) {
                    console.log(error);
                    setError(error);
            } else {
                    console.log(message);
                    setSuccess(message);
            }
};

And i put following code just below my form close,But nothing is showing in my screen,How can i do this ?
{success
    ?

        {success}

    :

{error}

Comment: Please provide the full code in stackoverflow code snippet, or a live editor like codesandbox.
Answer: Actually, you have not taken the value from JSON properly. I have posted a demo code that is working exactly as you wanted.
Also, you have not used === operator for comparing string true. The status value of JSON is not in boolean it's a string.
import "./styles.css";
import { useState } from "react";

export default function App() {
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");

  const subscribeMe = async (event) => {
    const res = await fetch(
      "https://mocki.io/v1/65583d53-9071-47af-b7d7-840e88763d08"
    );

    const data = await res.json();
    const error = data["status"];
    const message = data["msg"];

    if (error === "false") {
      console.log(error);
      setError(error);
    } else {
      console.log(message);
      setSuccess(message);
    }
  };
  return (

Hello CodeSandbox

        {" "}
        {error} {success}

      <button onClick={subscribeMe}>Press me </button>

Start editing to see some magic happen!

  );
}

Here is a demo URL https://yfv7c3.csb.app/
Comment: your code gave me solution,Thank you so much for help :)
Answer: It might be due to trying to render an object,  try to JSON.stringify the data
Comment: as i said i am new in nexjs so can you update code so i can check and implement in my side
Comment: Hey, Ritika can you show us your JSON response so that I can try it on my laptop. Anyway, I have tried the dummy code and it's working fine for me. https://pastebin.com/Epwt1DeR
Comment: @NalinNishant: whenever i hit api i am getting following message as json response
{"status":true,"msg":"Email saved successfully"}
Comment: K give me 5 mins i am trying
Comment: @NalinNishant: i am also trying , according to me something wrong with following code
I just need to change correct if else condition ( means if we use same email id then giving us message "{"status":false,"msg":"Email already exist"} " so i just need to use if else condition according to response return, current code is

 if (error) {
                     const error='errror';
                     setError(error);
             } else {
      const message='subscribed successfully';
               console.log(message);
                     setSuccess(message);
             }
Comment: I solved it let me show you my code
Comment: @NalinNishant  sure i am waiting
Comment: @NalinNishant please show your code


Can quantile regression be used to pool multiply imputed count data?

Question: I am using the mice package in R to impute missing data in small study. The study investigates the effect of a behavioral intervention on the frequency of a particular behavior, i.e., count data that can range from anywhere between 0-5 times for most participants and several hundreds for some participants. I have used a package for imputation of count data (https://github.com/kkleinke/countimp) and have successfully imputed the missing data with a reasonable distribution.
Now I want to report the estimated frequency at pre-treatment and post-treatment as well as the pre- to post-change and a significance test of the change, all based on the pooled data. The convention in the field is to report medians and IQR of pre- and post-frequencies as well as the median change in frequency.
Can this be properly done with multiply imputed data? My current idea is to calculate the medians and IQR with standard errors using the quantile regression library for R (quantreg), by employing intercept only regression models for quantiles .25, .50, .75 for each imputation (pre, post, and change score), and then pooling these estimates with standard errors using mice. However, this essentially means that I am taking the mean of medians, which does not feel right.
I'm pasting code that calculates the median (50th percentile) of the pre- and post-frequencies as well as the change in frequency using quantreg and then pools the estimates using mice. After that are calculations of the corresponding means.
<code># demo.median contains the imputed data

# vcov.rq is called by pool to get the covariance estimate of the
# quantile regression
vcov.rq <- function(fit)summary(fit, se="nid", cov=T)$cov

l <- list()
l$pre <- summary(pool(with(demo.median, rq(x_PRE ~ 1, tau = .5))))
    l$post <- summary(pool(with(demo.median, rq(x_POST ~ 1, tau = .5))))
l$pre_post <- summary(pool(with(demo.median, rq(I(x_PRE - x_POST) ~ 1, tau = .5))))

# Print pooled medians of pre, post and change score
do.call(rbind.data.frame, l)

l <- list()
l$pre <- summary(pool(with(demo.median, lm(x_PRE ~ 1))))
    l$post <- summary(pool(with(demo.median, lm(x_POST ~ 1))))
l$pre_post <- summary(pool(with(demo.median, lm(I(x_PRE - x_POST) ~ 1))))

# Print pooled means of pre, post and change score
do.call(rbind.data.frame, l)
</code>
Output
<code># Medians

           est        se        t       df     Pr(>|t|)     lo 95     hi 95 nmis        fmi    lambda
pre      8.000 1.3250825 6.037360 91.75287 3.286786e-08 5.3681774 10.631823   NA 0.02110754 0.0000000
post     2.875 1.0997478 2.614236 76.09011 1.077545e-02 0.6847043  5.065296   NA 0.16031744 0.1385330
pre_post 2.400 0.8801746 2.726732 52.96378 8.654540e-03 0.6345650  4.165435   NA 0.34977967 0.3256813

# Means

               est       se        t       df     Pr(>|t|)     lo 95    hi 95 nmis        fmi      lambda
pre      18.252632 3.417037 5.341655 92.05265 6.619670e-07 11.466153 25.03911   NA 0.02104097 0.000000000
post     12.019474 2.413928 4.979217 91.32515 2.999330e-06  7.224731 16.81422   NA 0.02889543 0.007858808
pre_post  6.233158 2.316257 2.691047 91.26050 8.471778e-03  1.632374 10.83394   NA 0.02957225 0.008535556
</code>
My question is: Is this proper? If not, can I achieve my goal of estimating absolute and change score medians from multiply imputed data in any other way?
Answer: This is a great question, one that I share. I am using a method identical to yours in a current project, but I have found no statistical publications that support this practice.
In general, the sampling distribution of the median depends on the distribution from which the median is calculated/sampled. That being said, I did some small simulations, drawing quantiles from a few different distributions, and found that the distributions of the sampled medians looked close to normal for most of the cases. I use this as back-of-the-napkin evidence that using the "mean of the medians" and the SE from the quantile regression is probably good enough for the purpose of summarizing imputed datasets.
That being said, I hope someone smarter than me does a nice simulation study to show whether I am right or not.
Brant Inman
Answer: Excellent question, indeed!
Rubin's Rules for constructing a "pooled" estimated value for the parameter of interest from the estimated values provided by each imputation rely on the normality of the underlying estimator used to produce those estimated values.
In some cases, normality can be achieved only after an appropriate transformation (e.g., log-transformation, Fisher's transformation) is applied to that estimator.
If normality (even after a transformation) is in doubt, then one can stay away from using Rubin's rules and report instead summary statistics (e.g., median, range) of the distribution of estimated values of that parameter obtained from the $m$ imputations.
See https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2727536/#!po=0.537634 for more details.
So the real question is:
Does the estimator of a quantile produced by quantile regression have a sampling distribution which is normal, at least for large enough sample sizes? (If yes, the sampling distribution of the difference between two such quantiles would also be expected to be normal.) The normality of the sampling distribution of the quantile of interest can be established either by consulting the literature on quantile regression or via simulation.


Riemannian manifold of absolutely continuous functioins

Question: I´m struggling with a definition of a Riemannian metric proposed in the textbook "Functional and Shape Data Analysis" by Anuj Srivastava, Eric P. Klassen:
Let $\mathcal{F}$ be the set of absolutely continuous functions $f: [0,1] \rightarrow \mathbb{R}$ and let $\mathcal{F}_0 = \{ f \in \mathcal{F}|\, f'>0 \}$.
Definition: Let $f \in \mathcal{F}_0$ and $v_1, v_2 \in T_{f}(\mathcal{F})$, where $T_{f}(\mathcal{F})$ is the tangent space of $\mathcal{F}$ at $f$, the Fisher-Rao Riemannian metric is defined as the inner product
\begin{align}
    \langle\langle v_1, v_2 \rangle \rangle_{f} = \frac{1}{4} \int_0^1 v_1'(t)  v_2'(t) \frac{1}{| f'(t)|}  dt.
\end{align}
My questioin is: How do I check $\mathcal{F}_0$ is a Riemannian manifold in this context? The textbook does not give any comments on this and after several hours of thorough web searching I feel particularly lost.
Answer: They are quite sloppy here. Caveat: I am a differential geometer, not an expert in data analysis, so take what will say here with a grain of salt.

I think, they implicitly assume that the function $f$ not only has the property $f'>0$ (almost everywhere), but satisfies the condition
$$
\frac{1}{f'(t)}\in L^1([0,1]).
$$
Without this assumption, the integral that they write may diverge.

They completely neglect to indicate which topology they use on the space ${\mathcal F}$: Without such a specification, it is meaningless to talk about structure of an infinite-dimensional Riemannian manifold. There is a chance, they simply take the $L^1$ topology on the space of derivatives of functions $f\in {\mathcal F}$. (In fact, they'll need a bit more control to ensure openness of ${\mathcal F}_0$. I will refrain from speculating what conditions they would impose, maybe $f\in C^1$, or maybe they have in mind only constructing a metric space rather than an infinite-dimensional Riemannian manifold. In this case, all what they care about are lengths of paths. My guess is that it is the latter.) To make this work, they need to normalize functions $f\in {\mathcal F}$ so that one can uniquely recover $f$ from its derivative. For instance, one may require $f(0)=0$ or $\int_0^1 f(t)dt=0$.

I will be assuming some normalization like that in what follows (you will see why soon).
Then the space they are dealing with is a convex open subset in a Banach space, hence, a Banach manifold.

Now, let's check at least some Riemannian properties of the F-R metric:

(a) Bilinearity and semipositivity of the form that they define is clear.
(b) Suppose that $\langle v, v \rangle_f=0$, i.e.
$$
\int_0^1 \frac{(v'(t))^2}{f'(t)} dt=0.
$$
Since $f'>0$ a.e., the integrand has to vanish a.e., which implies that $v'(t)=0$ a.e., hence, $v$ is constant. This, of course, does not imply that $v\equiv 0$ as required by the definition of a Riemannian metric. Since I assumed (unlike the authors of the book) that elements of ${\mathcal F}$ are normalized, the tangent vectors $v\in T_f{\mathcal F}$ are also normalized, which implies that indeed $v\equiv 0$.
Lastly, as a Riemannian geometer, I would like to check that my Riemannian metric depends smoothly on $f\in {\mathcal F}$. However, since the authors do not compute connections or curvatures, they do not really need smoothness. All what they need is continuity, so that they can define lengths of paths in ${\mathcal F}$. I suspect they do this only for "nice" paths $\alpha: [0,1]\to {\mathcal F}_0$,
for which the integral
$$
\int_0^1 ||\alpha'(s)||ds
$$
converges. But this is something for you to check.


In Raft distributed consensus, what do I set votedFor to?

Question: I am trying to implement the Raft consensus algorithm. Here is my general understanding around all the times we set the term and votedFor attributes of a server's state:

Upon startup term is 0 and votedFor is null
Upon a server's election timeout, the server becomes a Candidate, increments its term by 1, and sets its votedFor to itself.
When a server receives a RequestVote RPC with a term higher than its own, it should update the term to the number observed, then update votedFor to the sender iff the receiving server has a votedFor of null and its log is not more up-to-date than the sender's log.
When a Candidate receives an AppendEntries RPC, and the sender's term is higher than or equal to its own, the Candidate should update its term to the sender's term then set its votedFor to the sender and have it's state become Follower, thereby acknowledging the sender as its legitimate leader.
In all other cases when a server receives any RPC request or response containing a term higher than its own, it should set its own term to the received server's term and set votedFor to null.

Together, do these make up the only 5 ways that term and votedFor are set in a correct implementation of Raft, and are these cases correctly summarized? I am confused about this because the paper only mentions that at certain times a node will go through a conversion to a follower which does not specify whether votedFor should be the value of the sender with the higher term or null. I am worried that case 4 is wrong and should be this instead: on AppendEntries if the sender's term is greater, then the receiver should update their term to that of the sender, then set votedFor to the sender, regardless of whether or not the receiver is a Follower, Candidate, or stale Leader.
Answer: As you can see in the "Rules for All Servers" of Figure 2 of the original paper:

If RPC request or response contains term T > currentTerm:
set currentTerm = T, convert to follower (§5.1)

in which case you are supposed to reset votedFor to null.
As a result, in your rule 3, when a server receives a RequestVote RPC with a term higher than its own, it should update the term to the number observed and also reset the votedFor to null (meaning that in this case, it will always vote for the requesting server).
Comment: What can lead to an endless loop where a request vote is resetting the election and not converging to a leader?


Pegar id do usuario por SESSION

Question: Estou com uma duvida , como eu pego o id do rapaz que efetuou login no meu sistema? Para que posteriormente ele possa alterar seus dados.
<?php
    if (isset ($_POST ["loginUsuario_externo"])){
        include_once("../controllers/Usuario_Externo_Controller.php");
        $usuario_externo = new Usuario_externo_Controller;
        $usuario_externo->login();
    }

Funçao login
public function login() {

    $this->usuario_externos->email($this->input->get('email'))
                           ->senha($this->input->get('senha'));

    $resultado = $this->usuario_externos->login();

    if($resultado) {
      session_start();
      $_SESSION['login'] = $resultado;
      echo '';
      echo ('Aguarde, redirecionando.');
    } else {
        echo ('E-mail ou Senha incorreto(os).');
    }
}

MODEL
  public function login() {

    $sql  = "SELECT * FROM usuario WHERE email = :email AND senha = :senha AND status = 1 LIMIT 1";
    $stmt = $this->conn->prepare($sql);
    $stmt->bindParam(':email', $this->email, PDO::PARAM_INT);
    $stmt->bindParam(':senha', $this->senha, PDO::PARAM_STR);
     $stmt->execute();
    return $stmt->fetch();

}

starta sessão e vrf se há sessao
 <?php
  session_start();
  function session_checker(){
    if (! isset($_SESSION['login'])){
      header ("Location:../");
      exit();
    }
  }
  session_checker();
  ?>

Comment: sim eles estao vindo da view , atraves do get
Comment: Mude, para `$_SESSION['login']->id`, caso queira acessar como um array, faça `return $stmt->fetch(PDO::FETCH_ASSOC);`
Comment: login();

}
Comment: eu tentei
`$codigo = mysql_query("SELECT u.id, u.nome FROM usuario_externos u WHERE u.nome = '" . $_SESSION['nome'] . "';");
echo mysql_result($codigo, 0);`
Comment: deixa ver se entendi, você quer armazenar na sessão esse ID do usuário vindo do banco, e depois recuperar essa sessão com o ID pra alteração dos dados ?
Comment: isso :) mas nao esta dando certo de jeito algum
Comment: Você precisa editar a pergunta e colocar o código que inicia a sessão e faz o login.  a gente não sabe o que `login()` faz, nem se vc fez a atribuição em `$_SESSION` ou se iniciou a sessão no outro arquivo.
Comment: Eu não entendi o que essa linha faz,    `$this->usuario_externos->email($this->input->get('email'))
                           ->senha($this->input->get('senha'));` você esta passando uma senha por get? no login do seu model veja se email e senha tem algum valor.
Comment: `print_r($stmt->fetch())` exibe algo? no bind do email, mude : `PDO::PARAM_INT` para `PDO::PARAM_STR` ou deixe sem nada.
Comment: tipo se eu colocasse no controller $id=$_SESSION['id']; era pra pegar a carniça do id ? ou nao?
Comment: `print_r($stmt->fetch())` trouxe `stdClass Object ( [id] => 1 [nome] => marcus [cpf] => [email] => email@example.com [perfil] => 1 [senha] => 6fab33feda475044 [status] => 1 [instituicao_ext] => unie )`
Comment: Sim é para pegar o id, deve ser `$_SESSION['login']['id']` na dúvida de um `print_r($_SESSION)`.
Comment: `Fatal error: Cannot use object of type stdClass as array in C:\xampp\htdocs\portoaberto\app\controllers\Usuario_Externo_Controller.php on line 45` PQ???? ehwaaeauw só da erro ahweauw
Comment: rray vc e o bixao vei *----------------* poe ai nas respostas que deu certo *--*
Answer: O problema parece ser o acesso a sessão, pelos comentário foi visto que o retorno do login() model retornar um objeto e jogava ele na sessão ele deveria ser acessado assim $_SESSION['login']->id.
Caso deseja acessar as informações do usuário na sessão como um array, define o tipo de retorno no fetch(). return $stmt->fetch(PDO::FETCH_ASSOC);
NÃO passe informaçãoes sensiveis como uma senha pelo método get, pois ela ficará visivel na url, práticamente você oferece o ouro ao bandido.
Comment: Muito obrigado, resolveu um grande impedimento para o meu projeto .
Answer: Tente desta maneira, utilizando o session_id()
<?php
session_start();
$r=session_id();

echo "o id da sessão é: ".$r;

?>

Comment: eu tentei isso , porem ele aparece o id da sessão e nao do usuario que logou na sessão.

Pegar id do usuario por SESSION


Vertical Align Text Inside Container even when font size changes

Question: I'm trying to vertical-align: middle a text inside a container with different font sizes. This has been asked before, but I can't get any of the solutions to work for me, What I'm missing?
I want the text with different font sizes to align vertically in the middle of the container.
Here is the code:
.

let upperGuideText = document.getElementById("upperGuideText");

let guide = "Some text here"

      setTimeout(function(){
      upperGuideText.style.fontSize = "3vw";
      upperGuideText.innerHTML = `${guide}`;

      }, 500);

       setTimeout(function(){
      upperGuideText.style.fontSize = "5vw";
      upperGuideText.innerHTML = `${guide}`;

      }, 2500);
.upperGuideContainer {
    position: absolute;
    overflow: hidden;
    left: 10vw;
    top: 51vh;
    height: 26vh;
    width: 88vw;
    display: flex;
    justify-content: center;
    align-items: center;
    outline: 0.1vw dashed orange;
}

.upperGuide {
    position: absolute;
    font-family: 'Open Sans', sans-serif;
    font-weight: bold;
    color: rgb(128, 128, 128);
    left: 0.5vw;
    top: -11.4vh;
    opacity: 1;
    vertical-align: middle;
}

Answer: You're asking your CSS to do two different things, which is causing your problem.
the below flexbox properties that you included in the parent container are enough to achieve what you want.
.upperGuideContainer {
    display: flex;
    justify-content: center;
    align-items: center;
}

When you tell the child
 to take an absolute position, you're breaking the flexbox properties of the parent
.upperGuide {
    /* position: absolute; */
    font-family: 'Open Sans', sans-serif;
    font-weight: bold;
    color: rgb(128, 128, 128);
    /* left: 0.5vw; */
    /* top: -11.4vh; */
    opacity: 1;
    /* vertical-align: middle; */
}

EDIT: If you want to learn more about the magical properties of flexbox, I highly recommend this article. I reference it constantly.
Answer: I think you are using position absolute on the child when you don't really need to do it. once your parent container has "display: flex" as a property you can align things with "align-items" and "justify-content", there is no need for the child to have position absolute unless you need it to for other purposes.

.upperGuideContainer {
    position: absolute;
    overflow: hidden;
    left: 10vw;
    top: 51vh;
    height: 26vh;
    width: 88vw;
    display: flex;
    justify-content: center;
    align-items: center;
    outline: 0.1vw dashed orange;
  }

  .upperGuide {
    /*position: absolute;*/
    font-family: 'Open Sans', sans-serif;
    font-weight: bold;
    color: rgb(128, 128, 128);
    /*left: 0.5vw;*/
    /*top: -11.4vh;*/
    opacity: 1;
    /*vertical-align: middle;*/
  }

As a side note, if you are using position absolute in a container inside of an absolute container, you should avoid using vh (viewport height) and vw (viewport width) as these are values coming from the viewport. I recommend using % or px instead as these are more accurate.
Answer: Remove position:absolute, and top from .upperGrid. Because when you use absolute it is positioned according to the nearest containing block that is not absolute. Also the element is taken out of the flex display.
.upperGuideContainer {
    position: absolute;
    overflow: hidden;
    left: 10vw;
    top: 51vh;
    height: 26vh;
    width: 88vw;
    display: flex;
    justify-content: center;
    align-items: center;
    outline: 0.1vw dashed orange;
}

.upperGuide {
    font-family: 'Open Sans', sans-serif;
    font-weight: bold;
    color: rgb(128, 128, 128);
    left: 0.5vw;
    opacity: 1;
    vertical-align: middle;
}

Comment: and what if we want to align left horizontally at the same time?


Question from 14.6 "Galois Groups of Polynomials" from Dummit and Foote

Question: I am confused in the proof of proposition 30 in Dummit and Foote on page 608. Near the end of this "proof" he goes on to say,

By the Fundamental Theorem of Galois Theory, the fixed field of $S_{n}$ has index precisely $n!$ in $F(x_{1},...,x_{n})$.

I am very confused about how he gets this or even how the Fundamental Theorem applies. By index does he mean the group index? I really don't know what he's talking about...
Explanation would be greatly appreciated.
Comment: He means that the field degree of the big field over the little field is $n!$. Since this number is the cardinality of your group, which is acting as a Galois group of the big over the little, it's a direct application of FTGT.
Comment: While you're free to wait for an answerer who happens to have a copy of your text on hand, it would help if you could at least state the proposition.
Comment: @Omnomnomnom it's a popular enough text that it's not unlikely that someone has it on hand
Comment: @Lubin that's kind of what I was thinking.
Comment: @Lubin

Okay thanks, I get it now. The proof is poorly written in my opinion but I see what he's saying now. Thank you very much for the help.
Comment: BTW, as far as I can tell, there is a gap in Dummit&Foote's proof.  At least, they have not justified the conclusion that the fixed field "is the field of rational functions in the elementary symmetric functions".  They only show that the fixed field is generated by the $s_k$ over $F$.  You need transcendence degree theory (from section 14.9) to justify this.
Comment: And honestly, they really only gesture at the proof of the existence of transcendence degree in 14.9.
Answer: The Proposition is the following.  Let $x_1, \ldots, x_n$ be indeterminates over a field $F$, and let $s_i$ be the $i^\text{th}$ elementary symmetric function in $x_1, \ldots, x_n$.
Proposition 30: The fixed field of the symmetric group $S_n$ acting on the field of rational functions in $n$ variables $F(x_1, \ldots, x_n)$ is the field of rational functions in the elementary symmetric functions $F(s_1, \ldots, s_n)$.
$S_n$ acts on $F(x_1, \ldots, x_n)$ by permuting the subscripts of the $x_i$, so the elements of $S_n$ can be considered as field automorphisms of $F(x_1, \ldots, x_n)$.  Let $K$ be the fixed field of $S_n$. As Lubin points out, then $[F(x_1, \ldots, x_n): K] = |S_n| = n!$ by the Fundamental Theorem of Galois Theory.