Multinomial logistic predictor matrix

Question: I'm reading Tuerlinkx & Wang, "Models for Polytomous Data". They write: "Apart from the intercept, the predictors that are included in the predictor matrix X can be classified into seven groups: item predictors, person predictors, logit predictors, and the four combinations of them. ... A logit predictor has the same value in all rows of the predictor matrix referring to the same component of the vector-valued link function. Interactions between a logit predictor and any of the other predictors are also possible."
I don't understand what a logit predictor is. If it has the same value in all rows, then it sounds like it's just the intercept term. But from the first sentence it sounds like there's also another intercept term? And how can you have an interaction between an intercept and another predictor?
It'd be helpful to see a model matrix, but table 3.1 doesn't answer my questions.
Answer: In the section you've referenced, they're speaking of the class of mixed multinomial models. I don't think the authors' nomenclature is either intuitive or conventional.
What they're calling "person predictors" are random effects which are implicit model terms that handle unmeasured sources of variation between clusters, such as repeated measures within individuals, sites, or across time. I am not sure this is correct since these values are not explicitly part of the design matrix which we refer to as $\mathbb{X}$, however if the number of clusters are small we can adjust for them using fixed effects which may have been the authors' point. That is not a mixed model then.
I'm not sure, but the "logit predictors" are the fixed effects in the model, such as age, gender, or intervention status. The "item predictors" is a redundancy referring to breaking out a polytomous category like "race" into two or more columns of Y/N variables for specific race levels.
I would check out the text Longitudinal Data Analysis by Zeger, Heagerty, Liang, and Diggle for a good alternative slant on the topic.
Comment: (+1) for neither intuitive nor conventional. This is almost certainly domain jargon.
Comment: (+1) Your comment is almost exactly what I was about to write!
Comment: In 2nd par of sec. 3.3, they say that $X$ is the fixed predictor matrix that can contain person predictors; random effects go in the matrix $Z$. And a "logit predictor" cannot be just a covariate such as age or gender, because it's value is the same for all rows of the predictor matrix.
Comment: The specific language was "A logit
predictor has the same value in all rows of the predictor matrix referring
to the same component of the vector-valued link function
" which I took to mean: if two individuals are both of the same age category (say 30-40), they'll have the same "logit predictor". Anyway, it's totally confusing language. The logit is a link function, and logit predictor sounds like the conventional "eta" (linear predictors) from the McCullogh and Nelder book. It's frustrating to read.
Answer: As @AdamO says, tough language.
The "vector-valued link function", see eqs. 3.3 and 3.5, is the McCullagh & Nelder $\eta$.
Suppose you have a baseline-categories regression with 3 categories. There are two multinomial "comparisons" (cat 0 vs. cat 1, and cat 0 vs. cat 2), with two logit predictors (0-v-1 and 0-v-2). Predictors you might have:

an intercept that's constant across all comparisons.
a covariate "main" effect that's constant across all comparisons.
a "logit predictor" that's a separate intercept for each comparison.
a covariate interaction (e.g., item-by-logit), with the covariate having a different effect in each comparison.

Is it conventional to have "global" predictors like (1) and (2) or interacting ones like (3) and (4)? I don't know.

Multinomial logistic predictor matrix


Number of unique sets from subsets

Question: I have six sets: {2, 6}, {2, 6}, {1, 3}, {1, 5}, {4, 5} and {3, 4}. How many different combinations can I produce by taking one value from each set so that I produce the set {1, 2, 3, 4, 5, 6}?
A possible combination is:
S1: 2
S2: 6
S3: 1
S4: 5
S5: 4
S6: 3
and another:
S1: 6
S2: 2
S3: 1
S4: 5
S5: 4
S6: 3
Comment: To be picky, you have only five sets since $\{2,6\} = \{2,6\}$. This eliminates some possibilities, since you can only choose a 2 or a 6 from that set, as opposed to choosing a 2 from the "first" set and a 6 from the "second" one. Your meaning is clear but the notation doesn't express what you want.
Answer: Picky note: Use curly braces for sets: $\{2,6\}$ not $(2,6)$.
You must either choose 2 from the first $\{2,6\}$ or the second $\{2,6\}$ and then are forced to choose $6$ from the opposite pair.
Next, you must choose $3$ from either $\{1,3\}$ or $\{3,4\}$.
Case 1: Choose $3$ from $\{1,3\}$ forces you to choose $1$ from $\{1,5\}$ which forces $5$ to be chosen from $\{4,5\}$ which then forces $4$ to be chosen from $\{3,4\}$
Case 2: Choose $3$ from $\{3,4\}$ forces $4$ to be chosen from $\{4,5\}$ etc.
Thus there are 2 ways to deal with 2 and 6 and 2 ways to deal with 1,3,4,5. These options are independent, so there are a total of $4=2\cdot 2$ ways to choose.
Comment: Is this brute-force method the best way to go?
Comment: I'm not sure there is a nice "slick" way to proceed. I think brute force is about all you can do. This sort of counting problem gets really complicated as the size of the problem increases. It's not terribly far off from a [knapsack problem](http://en.wikipedia.org/wiki/Knapsack_problem).

Number of unique sets from subsets


gcp dataflow templates, ERROR: (gcloud.beta.dataflow.jobs.run) INVALID_ARGUMENT: There is no support for job type with environment version

Question: full error
ERROR: (gcloud.beta.dataflow.jobs.run) INVALID_ARGUMENT: (4361fe83f99d0cfe): There is no support for job type  with environment version . Please try upgrading the SDK to the latest version. You can find the instructions on installing the latest SDK at https://cloud.google.com/dataflow/docs/guides/installing-beam-sdk. If that doesn't work, please contact the Cloud Dataflow team for assistance at https://cloud.google.com/dataflow/support.
staging command
mvn compile exec:java  -Dexec.mainClass=com.jobs.wordcount.TextToPubsub  -Dexec.args="--runner=DataflowRunner \
          --project=my_project \
          --stagingLocation=gs://bucket_name/tmp/staging \
          --templateLocation=gs://dataflow-templates/latest/Stream_GCS_Text_to_Cloud_PubSub_metadata"

run command
gcloud dataflow jobs run template_test \
--gcs-location gs://dataflow-templates/latest/Stream_GCS_Text_to_Cloud_PubSub_metadata \
--staging-location=gs:/my_bucket/tmp/staging \
--parameters \
inputFilePattern=gs://bucket_nam/input/*.json,\
outputTopic=projects/my_project/topics/testTopic

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
 <project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>word_count_cicd_test</groupId>
    <artifactId>word_count_cicd_test</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>
     <dependency>
        <groupId>org.apache.beam</groupId>
        <artifactId>beam-sdks-java-core</artifactId>
        <version>[2.20.0, 2.99)</version>
    </dependency>

    <dependency>
        <groupId>org.apache.beam</groupId>
        <artifactId>beam-sdks-java-io-google-cloud-platform</artifactId>
        <version>2.20.0</version>
    </dependency>

    <dependency>
        <groupId>org.apache.beam</groupId>
        <artifactId>beam-runners-google-cloud-dataflow-java</artifactId>
        <version>[2.20.0, 2.99)</version>
    </dependency>
 </dependencies>

The java code and the metadata template is provided by google
https://cloud.google.com/dataflow/docs/guides/templates/provided-streaming#gcstexttocloudpubsubstream
gcloud version
bash-3.2$ gcloud version
    Google Cloud SDK 278.0.0
    beta 2019.05.17
    bq 2.0.52
    core 2020.01.24
    gsutil 4.47

I am getting the same error when launching in the console. I think it might have to do with this feature being in beta.
Comment: What version of the Cloud SDK are you using? (`gcloud version`)
Comment: gcloud version added
Answer: gs://dataflow-templates/latest/Stream_GCS_Text_to_Cloud_PubSub_metadata is not a valid template. It is the metadata file for the template, gs://dataflow-templates/latest/Stream_GCS_Text_to_Cloud_PubSub.
If you want to run Google's provided version of the template, you can set --gcs_location=gs://dataflow-templates/latest/Stream_GCS_Text_to_Cloud_PubSub in your gcloud command.
If you want to create your own template, you will have to use your own GCS bucket in templateLocation in your staging command.


Area under curve of ROC vs. overall accuracy

Question: I am a little bit confused about the Area Under Curve (AUC) of ROC and the overall accuracy.

Will the AUC be proportional to the overall accuracy? In other words, when we have a larger overall accuracy will we definitely a get larger AUC? Or are they by definition positively correlated?

If they are positively correlated, why do we bother reporting both of them in some publications?

In real case, I performed some classification task and got the results as follows: classifier A got an accuracy 85% and AUC of 0.98 and classifier B got an accuracy of 93% and AUC of 0.92. Question is, which classifier is better? Is it possible to get results similar to these (or do my results indicate a bug in my implementation)?
Comment: I found a paper may have some interest for some of you. https://www.google.co.uk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=10&cad=rja&ved=0CG8QFjAJ&url=http%3A%2F%2Fwww2.unil.ch%2Fbiomapper%2FDownload%2FLobo-GloEcoBioGeo-2007.pdf&ei=RWAkUtfkC8iW0AXu_oCgAg&usg=AFQjCNEvmOPt92quGwJ1earYdTprclWLuA&sig2=p6i_EMbre0ZNtYWley8wAQ
Comment: ROC AUC is beneficial when the classes have different size. If 99% of objects are positive, an accuracy of 99% is obtainable by random sampling. Then the ROC AUC value will be much more meaningful.
Comment: Isn't AUC supposed to be less than the overall accuracy since we count for the false positive rate in the AUC measure while we don't in the accuracy???
Answer: While the two statistics measures are likely to be correlated, they measure different qualities of the classifier.
AUROC
The area under the curve (AUC) is equal to the probability that a classifier will rank a randomly chosen positive instance higher than a randomly chosen negative example.  It measures the classifiers skill in ranking a set of patterns according to the degree to which they belong to the positive class, but without actually assigning patterns to classes.
The overall accuracy also depends on the ability of the classifier to rank patterns, but also on its ability to select a threshold in the ranking used to assign patterns to the positive class if above the threshold and to the negative class if below.
Thus the classifier with the higher AUROC statistic (all things being equal) is likely to also have a higher overall accuracy as the ranking of patterns (which AUROC measures) is beneficial to both AUROC and overall accuracy.  However, if one classifier ranks patterns well, but selects the threshold badly, it can have a high AUROC but a poor overall accuracy.
Practical Use
In practice, I like to collect the overall accuracy, the AUROC and if the classifier estimates the probability of class membership, the cross-entropy or predictive information.  Then I have a metric that measures its raw ability to perform a hard classification (assuming false-positive and false-negative misclassification costs are equal and the class frequencies in the sample are the same as those in operational use - a big assumption!), a metric that measures the ability to rank patterns and a metric that measures how well the ranking is calibrated as a probability.
For many tasks, the operational misclassification costs are unknown or variable, or the operational class frequencies are different to those in the training sample or are variable.  In that case, the overall accuracy is often fairly meaningless and the AUROC is a better indicator of performance and ideally we want a classifier that outputs well-calibrated probabilities, so that we can compensate for these issues in operational use.  Essentially which metric is important depends on the problem we are trying to solve.
Comment: Dikran, do you have a reference for your first paragraph ?
Comment: @Bunder not directly, the AUROC is the probability that a randomly selected +ve pattern will be ranked higher than a randomly selected -ve pattern (https://en.wikipedia.org/wiki/Receiver_operating_characteristic#Area_under_the_curve) and hence is a measure of the quality of the ranking, as we would want that probability to be as high as possible.
Answer: AUC (based on ROC) and overall accuracy seems not the same concept.
Overall accuracy is based on one specific cutpoint, while ROC tries all of the cutpoint and plots the sensitivity and specificity.
So when we compare the overall accuracy, we are comparing the accuracy based on some cutpoint. The overall accuracy varies from different cutpoint.
Comment: Oh, I see. You are comparing the best overall accuracy and AUC. But they are still different concept again. The AUC is the P(predicted TRUE|actual TRUE) vs P(FALSE|FALSE), while the overall accuracy is the P=P(TRUE|TRUE)*P(actual TRUE) + P(FALSE|FALSE)*P(actual FALSE). So this depends on the proportion of the true value on your data set very much. In practice, it seems that the best overall accuracy is usually achieved when the cutpoint is near the P(actual TRUE).
Comment: Thanks very much for your reply!
I understand that the overall accuracy is obtained from certain cut-point (or threshold value). However, there is one best cut-point, i.e., the one nearest to the top left corner.
For example, my overall accuracy is calculated using this best cut-off point, and the AUC is for all the different cut-points. Then how to interpret this accuracy and AUC? For example, the performance of the two classifiers I mentioned above.
Comment: So AUC and the best overall accuracy may be not consistent, depending on the proportion of the true value of your data set. In your case, it seems that one of the classifier is more focus on sensitivity while the other on specificity. And on your current data set, the P(TRUE) is not 50%. So sensitivity and specificity contribute to the overall accuracy by different weighted. In practice, the ROC can give us more information, and we would like to choose the classier case by case. For example, the spam classifier may be more focus on P(not spam|not spam) to prevent from missing important emails.
Comment: Thanks for your answer. It is much clearer now. But if someone has more want to discuss please post here.
Answer: Is AUC really very useful metric?
I would say expected cost is more appropriate measure.
Then you would have a cost A for all False Positives and cost B for all False Negatives. It might easily be that other class is relative more expensive than other. Of course if you have costs for false classification in the various sub-groups then it would be even more powerful metric.
By plotting cut-off in the x-axis and expected cost on then y-axis you can see which cut-off point minimizes expected cost.
Formally you have a loss-function Loss(cut-off|data,cost) which you try to minimize.
Comment: The expected cost can only be evaluated if you know the false-positive and false-negative costs, which are not necessary for calculation of the AUC, which is a good statistic to use if the costs are unknown or variable.
Answer: Like all the answers have been posted: ROC and accuracy are fundamentally two different concepts.
Generally speaking, ROC describes the discriminative power of a classifier independent of class distribution and unequal prediction error costs (false positive and false negative cost).
Metric like accuracy is calculated based on the class distribution of test dataset or cross-validation, but this ratio may change when you apply the classifier to real life data, because the underlying class distribution has been changed or is unknown. On the other hand, TP rate and FP rate which are used to construct AUC will be not be affected by class distribution shifting.


How can I play an already uploaded video inside an Amazon S3 bucket? And how can I use the String Authentication on it?

Question: I´m new with video module, and with Amazon S3.
I need a video (that I´ve already uploaded to an Amazon S3 bucket), to be able to be played inside my site. I don´t want to upload it again through Drupal.
This video needs to be private. I´ve read something about "S3 Query String Authentication" but didn´t get how to actually implement that in my site.
I´m not able to point to a video that´s already uploaded to a bucket. I can only upload through Drupal, or upload it to a folder inside my drupal installation. How can I just grab the video?
And Should I do that using string authentication? How can I avoid people that´s not logged in to see or link to the video? (I know that there´s no way to stop other people to copy your stuff, but I´ve read about hot links and would like to avoid that from happening if I can).
I need that video to be available for a long period of time for my users, I just don´t want them to post the link in other sites (and use my bandwith).
I´m pretty clueless. Please I would love some help if you can. Thanks!!!!
Rosamunda
Comment: Can you link to the module your using? This is very module specific support so it's hard w/out knowing exactly your setup. And this is Drupal 6 or 7? Always be sure to tag appropriately.
Comment: Thanks electblake. I´m using D6. Fortunately I´ve found a workaround... just not using this module at all. I was referring to the Video Module. I just used jwplayer directely to play the videos already stored in my S3 buckets. In fact, you can´t use this video as I thought (to point directely to S3). Here´s some more information: http://drupal.org/node/1317520
Answer: I'm answering this, hoping I can help anyone else with the same problem.
If you're trying to play videos already uploaded to your S3 Amazon account, you won't find an appropriate Drupal Module to do so. (see this).
What I did is to get myself an Amazon Cloudfront account and protect the videos manually with an expiration date; then I pasted the video (using the player jwplayer), and I controlled the access to that node using any of the node access modules.
Comment: how did you end up referencing the S3 video in Drupal? Did you use the workaround described in #10? http://drupal.org/node/1317520#comment-5400750
Comment: No, sadly, I just uploaded the video to S3 and then put the link inside a Drupal node (inside a script that actually plays the video). But couldn´t do that in the way that I intended to.
Comment: yeah, I ended up doing the same ;-)


WPF C# Get array position of grid button from Click Event

Question: I have a window that I'm basically building ghetto minesweeper in.  I have a grid that I feed a jagged array into, set up so that it will adapt to any change in the size of the array (no hard set values or rows/columns).  Over top of that, I have a grid of blank buttons that simply adapts in size to the grid below.
When you click a button, it hides revealing the value under it, and I need some way to return the position of the button clicked, so I can compare against the original jagged array to find out whether not the item was a bomb. (this would also help me for doing a fill action on empty tiles).  But given how I have it set up, the Grid.GetRow or Grid.GetColumn just return 0's.
Does anyone know how I can get the array position (preferably row and column) from the setup that I have?
XAML Below, the C# click events follow it.
<Window x:Class="MinesweeperWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Minesweeper" SizeToContent="WidthAndHeight" Height="Auto" Width="Auto">
    <Window.Resources>
        <DataTemplate x:Key="Buttons_Template">
            <Button Content=""
                    Height="20"
                    Width="20"
                    Margin="0,0,0,0"
                    Visibility="Visible"
                    Click="ButtonClick"
                    MouseRightButtonUp="RightClick"/>
        </DataTemplate>
        <DataTemplate x:Key="DataTemplate_2">
            <TextBlock Text="{Binding}"
                           Height="20"
                           Width="20"
                           Margin="0,0,0,0"
                           FontFamily="Rockwell"
                           HorizontalAlignment="Center"
                           VerticalAlignment="Center"
                           Padding="5"/>
        </DataTemplate>
        <DataTemplate x:Key="DataTemplate_1">
            <ItemsControl ItemsSource="{Binding}" ItemTemplate="{DynamicResource DataTemplate_2}">
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <StackPanel Orientation="Horizontal"/>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
            </ItemsControl>
        </DataTemplate>
        <DataTemplate x:Key="Buttons_Template2">
            <ItemsControl ItemsSource="{Binding}" ItemTemplate="{DynamicResource Buttons_Template}">
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <StackPanel Orientation="Horizontal"/>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
            </ItemsControl>
        </DataTemplate>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid>
            <TextBlock x:Name="RemainingMines" HorizontalAlignment="Left" />
            <TextBlock x:Name="Difficulty" HorizontalAlignment="Center" />
            <TextBlock x:Name="Timer" HorizontalAlignment="Right" />
        </Grid>
        <Grid Name="ResetButton" Grid.Row="1">
            <Button Name="Reset" Content="Reset"/>
        </Grid>
        <Grid Name="GridBoard" ShowGridLines="True" Grid.Row="2">
            <ItemsControl x:Name="GridItems" ItemTemplate="{DynamicResource DataTemplate_1}"/>
        </Grid>
        <Grid Name="ButtonsBoard" ShowGridLines="True" Grid.Row="2">
            <ItemsControl x:Name="ButtonItems" ItemTemplate="{DynamicResource Buttons_Template2}"/>
        </Grid>
    </Grid>
</Window>

Click Methods in C#
private void ButtonClick(object sender, RoutedEventArgs e)
{
    int col = Grid.GetColumn((Button)sender); //this just returns 0
    int row = Grid.GetRow((Button)sender);  //this just returns 0
    Button source = e.Source as Button;
    source.Visibility = Visibility.Hidden;
    Console.WriteLine("L: {0} x {1}", col, row);  //prints L: 0 x 0
}
private void RightClick(object sender, RoutedEventArgs e)
{
    int col = Grid.GetColumn((Button)sender);  //this just returns 0
    int row = Grid.GetRow((Button)sender);  //this just returns 0
    Button source = e.Source as Button;
    if(source.Content.Equals(""))
    {
        source.Content = "\u2691";
    }
    else
    {
        source.Content = "";
    }
    Console.WriteLine("R: {0} x {1}", col, row);  //prints R: 0 x 0
}

Any help would be appreciated on this.
Comment: Have you tried `e.Source as UIElement` instead of the `Button` ?
Comment: Are you familiar with MVVM? and, could you provide a picture of what you want to achieve?
Comment: var index = Array.FindIndex(Array, x => x == buttonClicked), could this work? Then return the index?
Comment: http://stackoverflow.com/a/1511802/5273015
Answer: You need to use appropriate control for buttons to host. In your xaml you are using items control inside Grid. But Items control do not have row and column index. Thats why you are not able to get the index.
Use  UniformGrid or some relevant control.
You can refer this article
https://stackoverflow.com/a/13588066/5273015
Will help you a lot in other assignments as well


How to configure facebook to enable "facebook login" for a django server?

Question: I have difficulites to configure the facebook developer page in order to use the "facebook authentication" for a web site based on django and django-allauth.
Here is the Context :
DNS : www.mysite.com
Subdomain  for development : dev.mysite.com redirected to XX.XX.XX.XX :8000

The server is running on my windows PC  behind a simple home router. I launch it with the usual command:
Django runserver 0.0.0.0 :8000

The connection to server : dev.myste.com is OK
But the click on « login with facebook » button gives this error:
URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app's Client OAuth Settings. Make sure Client and Web OAuth Login are on and add all your app domains as Valid OAuth Redirect URIs.

The Facebook configuration is:
Settings/basic :
App Domains= mysite.com
Site url : dev.mysite.com

Product/login:
Client OAuth Login : Yes
Web OAuth Login: Yes
Embedded Browser OAuth Login : Yes
Force Web OAuth Reauthentication : No
Valid OAuth redirect URIs: http://dev.mysite.com
Login from Devices: No

Thank you for you help and attention.
Comment: Go check what the _actual_ value of the `redirect_uri` parameter in your login dialog call is – _that_ URL (minus the URL-encoding applied to pass the value in the login dialog URL) is the one you need to specify as Valid OAuth Redirect URI.
Comment: Hi CBroe, 5 minutes ago i was unable to understand your comments. Now thanks to you and Firebug i found the solution. Many Thanks
Answer: Using Firebug, i see that the django server sends to facebook the following oauth request.
https://www.facebook.com/dialog/oauth?scope=email&state=RXBpz0X5agrX&redirect_uri=http%3A%2F%2FXX.XXX.XXX.XX%3A8000%2Faccounts%2Ffacebook%2Flogin%2Fcallback%2F&response_type=code&client_id=ABCDEFGF
Notice redirect_uri parameter in the request.
I add the redirect_uri parameter to the field "Valid OAuth redirect URIs" in the facebook/login page and it works immediately.


What is the best protocol for uploading images in batch via FTP?

Question: What is the best protocol for uploading images in batch via FTP?
Let's say my website has 3 images.
Original size is 1000x1000
I upload all images via backend as "image upload".
Later on, I want to substitute all 1000x1000 images with identical images with same name but at size 400x400.
Curious as to what is the best workflow for Drupal for this scenario.
Comment: You have multiple questions here (how to upload batch images, whether to upload images in separate folders); on *Drupal Answers*, you need to stick to one question per post.  Also, why would you upload lower resolution versions later?  Upload the highest resolution needed at the beginning, and let Drupal's image styles handle any required downsizing.
Comment: Patrick, let's say I upload an image that's 5000 pixels wide and weights 10 megs, and I choose my image style size as 400 pixels (reducing image size to 100kb), will the browser render the 10 meg version or the 100kb one? I've always wondered about that...
Comment: The browser will render whatever you configure in Drupal-- you can choose to show whatever image style (including "original") you like. You can mix and match styles using views, display suite, panels, or many other modules.
Answer:
I want to substitute all 1000x1000 images with identical images
  with same name but at size 400x400.

Since they are identical, simply use image styles. Create an image style of 400x400 and assign it to your content type's image field OR in your image field settings in a View.
Watch: How to apply image styles in Drupal
Comment: @BrunoVincent in that case, find them in the `/sites/all/default/files` folder. Have the 400 x 400 be the same name and override them via SFTP upload.
Comment: Yes, but with image styles, the size of the file remains the same on the server right? I'm looking at 5 gigs of images for this particular case...


Proving an Element is of the Largest Order

Question: I am trying to prove that $(1,1)$ is an element of largest order in $Z_{n_1} \oplus Z_{n_2}$, where $\oplus$ refers to the external direct product.
I am slightly confused because there is no restriction on $n_1$ or $n_2$ being distinct. For instance, wouldn't it be the case that $Z_{2} \oplus Z_{2}$ does not even have $(1,1)$ as an element?
Comment: Don't you mean external direct sum? If so, then the external direct sum is isomorphic to the internal direct sum.
Comment: I am using Gallian's text, and he refers to what I have written above as the external direct product.
Answer: hint try to prove that the order of $(1,1)$ is always the lcm of $n_1,n_2$.
Notice that, $1 \in \mathbb{Z}_n$ for all $n \in \mathbb{N} \setminus \{ 0 \}$,  So $(1,1) \in \mathbb{Z}_{n_1} \times \mathbb{Z}_{n_2}$


Getting Error while adding pubcenter ads in Metro App

Question: I have followed these steps
https://msdn.microsoft.com/en-us/library/dn284011(v=msads.10).aspx
At step 10 when i press ok i get a message that says

An Error Occured
Answer: That's because you cannot create new application and adunit in PubCenter for now. PubCenter has been integrated into Windows Dev Center.
Note: You will no longer be able to create ad units or new app promotion campaigns in pubCenter. For information on how to create ad units in Dev Center, see Monetize with ads. For information on how to create app promotion campaigns in Dev Center, see Create an ad campaign for your app.
Please see https://msdn.microsoft.com/en-us/library/windows/apps/mt186437.aspx for details
Answer: I think the process evolved and you should follow this guide : https://msdn.microsoft.com/en-us/library/mt313186(v=msads.30).aspx


X & Y planes of two dimentional Cartesian system.

Question: I found that sometimes y-axis is shown perpendicular with x-axis at counterclockwise direction but sometimes y-axis is shown perpendicular with x-axis at clockwise rotation. What is the difference between them ?
What comes in my mind is that for a counterclockwise rotation of a system they put y-axis perpendicular in counter clockwise direction w.r.t x-axis to define any function related to that system
&
for a clockwise rotation of a system they put y-axis perpendicular in clockwise direction w.r.t x-axis to define any function related to that system.
Am i right ? Kindly share your thoughts with me on this.
Comment: Short answer: $x$ and $y$ are just arbitrary names. We can name the axes $a$ and $b$, or exchange the names arbitrarily. There is no meaning in it. A function does not have to be $y(x)$, it can be $x(y)$ or $a(b)$. So name your axes whatever you want and need.
Comment: Your first diagram ... the vertical line is labeled "$y$-axis", but has a letter $x$ at the top.  That is probably an error.
Answer: For 2D coordinate systems there is not substantial difference with the two systems it is purely a matter of convention.
For 3D coordinate systems we can distinguish between Right Hand System and Left Hand System.
Refer also to this  MSE OP for more details.


Under what conditions for $p$ and $q$ will the following equation of a graph touch the x-axis?

Question: $y=x^3+px+q$
So in order for the graph to touch the x-axis the derivative has to be 0. $y'=3x^2+p$ from here $x=\sqrt \frac{-p}{3}$. but from here I don't know how to go forward I guess I have to solve  the equation $y=x^3+px+q$ for x and then equal it to $x=\sqrt \frac{-p}{3}$, but I don't know how to solve the equation for x. Could you please help me? Thanks in advance.
The answer is $(\frac{p}{3})^3 + (\frac{q}{2})^2=0$
Answer: For the graph to touch the $x$-axis, the derivative must be zero at one of the roots of the cubic equation. Since the values at which the derivative is zero is $\pm\sqrt{-\frac p3}$. Our condition becomes
\begin{align}
&x(x^2+p)+q=0\\
\implies &x(3x^2+p)-2x^3=-q\\
\implies &4x^6=q^2\\
\implies &\frac{(3x^2)^3}{27}=\frac{q^2}{4}\\
\implies &\frac{p^3}{27}+\frac{q^2}{4}=0
\end{align}
This is the required condition. (Note that when the graph crosses $x$-axis but still the $x$-axis is tangent to the graph at point of intersection, that is also counted as "touched" here. For example, $p=q=0$ satisfies this condition).
Answer: Hint: for the graph to touch the x-axis, the y-value has to be zero when you plug in the x value you calculated.
Your logic is not quite correct: in fact $y'=0$ when $x= \pm\sqrt{-p/3}$.
Comment: I do that but I still don't get the answer. Is the answer maybe wrong or have I miscalculated something ?
Comment: It's just algebra to get from the original condition to the textbook answer. You can probably do that algebra better than I can. You do have to worry about the fact that $y'=0$ when $x= -\sqrt{-p/3}$.
Comment: oh, ok. Thank you very much :)
Answer: You want $$f(\sqrt \frac{-p}{3})=0$$
Thus plug $x=\sqrt \frac{-p}{3}$ in your cubic and find the condition for p and q.


Count occurence of True or False for a range of rows in Pandas

Question: I am using a similar question on SO, except that I need to limit the range of rows in the Pandas dataframe Count occurrences of False or True in a column in pandas
So using this example, I would like to count the number of False occurrences in rows that start with values between 50000 and 80000.
I would need to first sort by values in Column 0,
then find the range of rows that is between 50000 and 80000,
then count the number of false occurrences for that limited range.
The table is below:
patient_id  test_result has_cancer
0   79452   Negative    False
1   81667   Positive    True
2   76297   Negative    False
3   36593   Negative    False
4   53717   Negative    False
5   67134   Negative    False
6   40436   Negative    False

Answer: I will assume the data you presented is in a variable called "df".
import pandas as pd
# 0
df = pd.DataFrame()

# 1
df = df[(df['patient_id'] >= 50000) & (df['patient_id'] <= 50000)]

# 2 retrieves a series object
df['has_cancer'].value_counts()

# 3 retrieving the actual number
df[~df['has_cancer']].shape[0]

0: if stored in csv, used pd.read_csv() or look up how to read your specific file type with pandas
1: the first line with patient id just extracts what you specified: patient_id in your interval (assuming ids are int types)
2: We take the series "has_cancer" and counts the number of occurences of each entry (True or False in this case)

we grab the series of "has_cancer" which is already boolean, so when passed in the df[...], we would only get the values that are True.  So, we use the ~ to negate the values and only get the values that are False.  calling df.shape gives you a tuple that is (# rows, # columns), so we grab the item in the first index which is the number of rows.

No need to sort given these solutions but if necessary just call df.sort_values([columns we want to sort by]) and pass a list of the column name(s) you want to sort by.


How to integrate Graph Engine with C# application

Question: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)
The type initializer for 'Trinity.Global' threw an exception.
Comment: i want use Global.LocalStorage.##_Accessor_Selector() method to work graph engine in memory data processing integration with .Net App.   I have changed Target Plateform to x64 . but that not help me . need help
Answer: I fixed this to change setting
Tool-Option --   Project and solution-- Web Projects--checked checkbox use the 64 bit version of IIS Express for web site and project
    enter code here
And
able to Trininty Dll integrate with my WebAPI (Odata) application


How to stop a callback method in NodeJS?

Question: <code>var chokidar = require('chokidar');
var watcher = chokidar.watch('folder-name');
var log = console.log.bind(console);
watcher
    .on('add', path => log(`File ${path} has been added`));`
</code>
It should show the output when I add new files into the folder, and I want to stop it, when I add maximum of two files. Then I want to print those file names separately.
Answer: <code>// Stop watching.
watcher.close();
</code>
doc
Comment: No, I want to add 2 new files into the folder , after that it should stop automatically.
Comment: and i want to print name of the file separately  which could be added by me.
Comment: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference.  Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/19470528)
Comment: @pradeep essential part is included, link is only here for reference.


EM Algorithm For Bipolar Normal Distribution

Question: Question:
Let $x_1, \dots, x_m$ be an i.i.d. sample from a normal density with mean $\mu$ and variance $\sigma^2$.
Suppose for each $x_i$ we observe $y_i = |x_i|$ . Formulate an EM algorithm for
estimating $\mu$ and $\sigma^2$.
My solution:
Define a latent variable $Z$, when $z_i = 1, x_i = y_i$ and $z_i = 0, x_i = -y_i$ and the probability $p(z_i = 1| \Theta, y_i) = p$. It can be easily known that $-x_i \sim \mathcal{N}(-\mu, \sigma^2)$.
$$ \begin{equation}
  \begin{aligned}
  l(\mathbf{x},  \mathbf{z}, p, \Theta) = \sum_{i = 1}^m z_i\left[ -\frac{1}{2}\ln 2\pi - \frac{1}{2}\ln \sigma^2 -\frac{1}{2\sigma^2}(x_i - \mu)^2 + \ln p\right]\\ + \sum_{i = 1}^m (1 - z_i)\left[ -\frac{1}{2}\ln 2\pi - \frac{1}{2}\ln \sigma^2 -\frac{1}{2\sigma^2}(x_i + \mu)^2 + \ln (1-p)\right],
  \end{aligned}
 \end{equation}$$
The E step in EM algorithm is:$E_{\Theta_{n}}[l(\mathbf{x},  \mathbf{z}, p, \Theta) | \mathbf{y}]$.
My question:

It seems that some problems happens in my model since two latent variables $z_i, p$ and unknown $x_i$ involved in the E step. So could anyone tell me where is the mistake?

I see the answer for updating the $\mu$ involves $f(y_i | \Theta_n)$, but honestly speaking, from the E step: $E[x_iz_i | \Theta_n, y_i]$, there would be no $f_i$ involved. So how come the formula?

Thanks in advance!

The likelihood function can be further expressed as:
\begin{equation}
  \begin{aligned}
   Q(\Theta, \Theta_{n}) = & E_{\Theta_{n}}[l(\mathbf{x},  \mathbf{z}, \Theta) | \mathbf{y}]\\
   = & \sum_{i = 1}^m\left( -\frac{1}{2}\ln 2\pi - \frac{1}{2}\ln \sigma^2 - \frac{E_{\Theta_{n}}[x_i^2|y_i]}{2\sigma^2} - \frac{\mu^2}{2\sigma^2} - \frac{1-2\mu E_{\Theta_{n}}[x_iz_i|y_i]}{\sigma^2}\right)
  \end{aligned}
 \end{equation}
The expectation of $E[x_iz_i | \Theta_n, y_i]$
$$
\begin{equation}
\begin{aligned}
E[x z | \Theta_n, y] = & \int \sum_l xz_lp(x_k,z_l | \Theta_n, y) dx\\
= &\int  xp(x_k,z = 1 | \Theta_n, y)dx\quad \text{only z = 1 left}\\
= & p(z = 1 | \Theta_n, y)\int x f(x | z = 1, \Theta_n, y)dx\\
= & \frac{f(y_i|\theta_n)}{f(y_i|\theta_n) + f(-y_i|\theta_n)} \mu_n
\end{aligned}
\end{equation}$$:
But still stuck.
Answer:
There is no probability $p$ in this problem as
$$\mathbb P_\theta(Z_i=1)=\mathbb P_\theta(X_i>0)=1-\Phi(\mu/\sigma)$$
There is only one type of latent variable, $\mathbf Z$, since $\mathbf X$ is a deterministic function of $\mathbf Y$ and $\mathbf Z$, as discussed below.
the complete likelihood can thus be expressed in terms of $\mathbf Y$ and $\mathbf Z$ only

If $X\sim\mathcal N(\mu,\sigma^2)$, then $Y=|X|$ has a Dirac mass distribution at $|X|$ conditional on $X$. The marginal distribution of $Y$ is the folded Normal, with density
$$\sigma^{-1}\varphi(y;\mu,\sigma)+\sigma^{-1}\varphi(-y;\mu,\sigma)$$
Conversely, the distribution of $X$ conditional on $Y$ is a sum of Dirac masses at $Y$ and $-Y$ with respective masses proportional to $\varphi(y;\mu,\sigma)$ and $\varphi(-y;\mu,\sigma)$. Note that
$$Z=\mathbb I_{X=|Y|}$$
is a deterministic transform of $(X,Y)$, hence that $Z$ is known given $(X,Y)$ and that $X$ is known given $(Z,Y)$. This implies that
$$\mathbb E_{\theta_{n}}[l(\mathbf{X},  \mathbf{Z}, \theta) | \mathbf{y}]
=\mathbb E_{\theta_{n}}[l(\mathbf{X(Z,Y)},  \mathbf{Z}, \theta) | \mathbf{y}] $$
and, since
\begin{equation}
  \begin{aligned}
  l(\mathbf{x},  \mathbf{z}, p, \Theta) &= \sum_{i = 1}^m \mathbb I_{z_i=1}\left[ -\frac{1}{2}\ln 2\pi - \frac{1}{2}\ln \sigma^2 -\frac{1}{2\sigma^2}(x_i(1,y_i) - \mu)^2 \right]\\ &\quad + \sum_{i = 1}^m \mathbb I_{z_i=0}\left[ -\frac{1}{2}\ln 2\pi - \frac{1}{2}\ln \sigma^2 -\frac{1}{2\sigma^2}(x_i(0,y_i) - \mu)^2 \right],\\
&= \sum_{i = 1}^m \mathbb I_{z_i=1}\left[ -\frac{1}{2}\ln 2\pi - \frac{1}{2}\ln \sigma^2 -\frac{1}{2\sigma^2}(y_i - \mu)^2 \right]\\ &\quad + \sum_{i = 1}^m \mathbb I_{z_i=0}\left[ -\frac{1}{2}\ln 2\pi - \frac{1}{2}\ln \sigma^2 -\frac{1}{2\sigma^2}(-y_i - \mu)^2 \right],
  \end{aligned}
 \end{equation}
the E-step writes as
\begin{equation}
  \begin{aligned}
\mathbb E_{\theta_n}[l(X,Z,\theta)|y) &= -\frac{m}{2}\ln 2\pi - \frac{m}{2}\ln \sigma^2- \frac{1}{2\sigma^2}\sum_{i = 1}^m \mathbb E_{\theta_n}[\mathbb I_{z_i=1}|y] (y_i - \mu)^2 \\ &\quad -\frac{1}{2\sigma^2}
\sum_{i=1}^m \mathbb E_{\theta_n}[\mathbb I_{z_i=0}|y] (y_i + \mu)^2
  \end{aligned}
 \end{equation}
This implies that $\mu_{n+1}$ for the M-step is solution of the equation
$$\sum_{i = 1}^m \mathbb E_{\theta_n}[\mathbb I_{z_i=1}|y] (\mu-y_i)
+\sum_{i=1}^m \mathbb E_{\theta_n}[\mathbb I_{z_i=0}|y] (y_i + \mu) = 0$$
Comment: Thanks! Good answer!


Problems with getting an assoccation to display all of its belonging models

Question: I'm creating a registration system for my University.
I've got two models, one being Register and the other being Student.
A Register has many Students, and I have depicted the following in their respective .rb files:
class Student < ActiveRecord::Base
 belongs_to :register
attr_accessible :first_name, :last_name, :university_id

class Register < ActiveRecord::Base
  belongs_to :student
  belongs_to :module_class
  belongs_to :event
  has_many :students
  attr_accessible :date, :present, :time_of_arrival, :student_id, :module_class_id, :event_id

The tables look like this, from the schema.rb file:
  create_table "registers", :force => true do |t|
    t.integer  "student_id"
    t.boolean  "present"
    t.integer  "module_class_id"
    t.integer  "event_id"
    t.time     "time_of_arrival"
    t.date     "date"
    t.datetime "created_at",      :null => false
    t.datetime "updated_at",      :null => false
  end

  add_index "registers", ["event_id"], :name => "index_registers_on_event_id"
  add_index "registers", ["module_class_id"], :name => "index_registers_on_module_class_id"
  add_index "registers", ["student_id"], :name => "index_registers_on_student_id"

My question now is that, I want to be able to view a list of students within a Register, in order to mark them Present or Absent (in register/1 for instance). This is how it looks like currently:

However, at the moment I can only assign one student to a register, and the Present checkbox appears (This is in the register/new page) .
The register index itself looks like this:

I'm using simple_form gem for the forms, in case that gives more clues.
EDIT: Added the Diagram from RubyMine to show dependancies:
Comment: `ModuleClass` is a particularly unfortunate class name in ruby...
Comment: Images don't help us debug your code. Show the code the outputs the students. Show the code that saves the students (to prove you're making the associations correctly).
Comment: What exactly do you need @Deefour? And yes @PinnyM, very unfortunate, as `Module` and `Class` are already defined by Ruby, hence I had to come up with this
Answer: A Register has many students you say, then why do you use belongs_to :student and added a student_id column in your register-table?
Comment: Ok i changed that, must have forgotten to taken it out.
I'm still unable however to select a whole list of students to be part of one register
Comment: This is the `register/_form.html.erb` file
`<%= simple_form_for(@register) do |f| %>
  <%= f.error_notification %>

    <%= f.association :students %>
    <%= f.input :present, :autofocus => true %>
    <%= f.association :module_class %>
    <%= f.association :event %>
   <%= f.input :time_of_arrival %>
    <%= f.input :date %>

    <%= f.button :submit %>

<% end %>`

And the view part for the student in the `show` is:
`
Student:
  <%= Student.find_by_id(@register.student_id).name %>
`


If $A_{n}\rightarrow A$, when can we say $\mu\left(A_{n}\right)\rightarrow\mu\left(A\right)$?

Question: If $A_{n}\rightarrow A$, when can we say $\mu\left(A_{n}\right)\rightarrow\mu\left(A\right)$, where $\mu$ is a measure on $\left(X,\mathcal{A},\mu\right)$ and $A_{n},A\in\mathcal{A}$ for all $n$?
As far as I know, if  $A_{n}\nearrow A$, then $\mu\left(A_{n}\right)\nearrow\mu\left(A\right)$. I also think if $A_{n}\searrow A$, then $\mu\left(A_{n}\right)\searrow\mu\left(A\right)$.
Is it true if $A_{n}\rightarrow A$, then $\mu\left(A_{n}\right)\rightarrow\mu\left(A\right)$ as well? (I don't think so...)
I see in a lot of proofs they use the $$A_{n}\searrow A,\;\;\;\text{then}\;\;\;\mu\left(A_{n}\right)\searrow\mu\left(A\right)$$ "trick", but they always say if $\mu\left(X\right)<\infty$, than the previous trick holds. More precisely, I always see: if $\mu\left(X\right)<\infty$ and $A_{n}\searrow\emptyset$, then $\mu\left(A_{n}\right)\rightarrow0$, but I don't really get why we need the $\mu\left(X\right)<\infty$ criterion.
Comment: What is your definition of $A_n\to A$? Is it the set-theoretic limit? Also note that $A_n\searrow A$ does not necessarily imply $\mu(A_n)\searrow\mu(A)$; the claim will hold if $\mu(A_n)$'s are eventually finite. One typical counter-example is $A_n=[n,\infty)$ with the Lebesgue measure on $\mathbb{R}$.
Comment: So this is the reason why we need the $\mu\left(X\right)<\infty$ criterion? Because if $\mu\left(X\right)$ is finite, then for every $A_{n}\subseteq X$ the measure of $A_{n}$ must be finite as well: $\mu\left(A_{n}\right)\leq\mu\left(X\right)<\infty$, thanks to the monoton property of the $\mu$ measure? By the monoton property I mean if $A\subseteq B$, then $\mu\left(A\right)\leq\mu\left(B\right)$.
Answer: Let $X$ be a covering of all $A_n$. By dominated convergence theorem,
$$\lim_{n\rightarrow\infty} \int_{X} i_{A_n} d\mu=\int_{X}i_{A}d\mu$$ (We assume the measure of all sets involved is finite so that the indicators are integrable)
Comment: (And as the comment about $[n, \infty)$ shows, one must indeed require some finiteness condition on the measures of the sets involved.)


With a multi-tenant application, better alternative to chained CNAME?

Question: Let's assume I have a multi-tenant webserver that runs an application for 500+ domains. I have an AWS Loadbalancer url, my_application.elb.eu-west-1.amazonaws.com, which have A and AAAA records to the actual LB. Now I want to ensure that all the domains I have point to this LB. Then I would see three options:

Read the A and AAAA records from my LB, and copy them for each domain.
Make a CNAME record for each domain, to the LB url (suggested solution by AWS)
Register one custom domain, e.g. applicationdns.com, and create a CNAME record to the LB url for e.g. www.applicationdns.com. Then for each domain create a CNAME record to this record (www.applicationdns.com).

Of course, option 1 is horribly inefficient so discarded right away.
Option 2 is the suggested approach, which works fine. However, if at any point I would need to migrate the Loadbalancer to a different URL, I would need to fix 500+ DNS records, possibly distributed over multiple providers, so it is hard to automate.
Option 3 would solve this problem, however it introduces a "chained CNAME". From what I've seen (RFC 1034) this is technically valid, but not considered good practice.
What is the best way to approach this challenge? Is there another approach that might work?
Comment: Option two is recommended  (when you actually own and directly manage all those domains) and now is probably a good moment to start automating  your dns management. See https://github.com/StackExchange/dnscontrol for one possible solution for that. - When not you, but your customers manage their own DNS records your option three will work much better. That will simply work as intended in most cases but comes with some concerns as explained here: https://serverfault.com/q/798417/546643
Comment: Another possibility with AWS for additional cost is using their Global Accelerator product with the ALB to get static IPs, and there's also BYOIP if you want/need that control. If customers are pointing their domain apex then they'll need A records rather than CNAME.
Answer: When you are able to register the custom domain to point to the Loadbalancers in AWS Route53, you can actually make alias A (and AAAA) records that function similar to CNAME records. This prevents chaining CNAME records, but still allows you to migrate the Loadbalancer url if necessary.
This is also explained in the AWS documentation, you can just repeat the described procedure for AAAA records if you want to support Ipv6.
Answer: From an automation point of view, option 1 & 2 automate the same.
Scaling in managed configuration can be done quite swiftly with the help of templates + variables.
I would personally favour 1 over 2, since CNAME incur an extra step on domain resolution while adding no real benefit to the ease of configuration, provided (again) you use managed configurations and you do not update them manually.
All in all, the keystone would be how you manage your hundreds of domains' configuration.
Since you are using external providers, the quality of their API seems to be the landmark to look out for.
If you go for self-hosted/managed authoritative name servers, even old technology allows for dynamic reload of individual zones, so there is really nothing standing in the way of automated (rolled out?) deployment.


How to combine results from two different Lucene Indexes?

Question: Use case:

JBoss Portal / Gatein
Pentaho BI

Both have Lucene based search built on top of them. As a user I need to see both Portal Content and BI Reports for my search query.
Is there a way to query both and then combine the results?
Schema and configuration is different for both Indexes I assume so Merging or Solr Distributed Search options don't seem to fit.
Thanks
Comment: AFAIK there is nothing out of the box. Since: when the schema (documents) are different, how should the scoring be accomplished or be set in relation to each other? This is something you need to think about. Then you can write code to deliver merged results.
Answer: You should implement this on your logic layer by providing some Wrapper service that will get results from both systems and then combines results.


Got to Get the value to the controller

Question:

 <% foreach (var item in Model)
         { %>

            <%: Html.LabelFor(model =>item.Customer) %>
             <%: Html.Encode(item.Customer) %>

         <%break; %>

         <%} %>

          <input id="Submit1" type="submit" value="Create New"  />

Need the value in item.Customer to be sent To the Controller Through the "Create New Button"
Answer: You should be able to put the value in a hidden form field and then add that field as a parameter to the controller action to which the form posts.
Answer: First, make sure you start a form that submits the appropriate controller/action. Second, store the value in a hidden field (via the HiddenFor extension method):
<% using(Html.BeginForm("YourAction","YourController)) { %>

        <% foreach(var item in Model){ %>

                <%= Html.LabelFor(model => item.Customer) %>
                <%= Html.HiddenFor(model => item.Customer %>

        <% } %>

        <input id="Submit1" type="submit" value="Create New" />

<% } %>

Comment: so now how do i get the Hidden field value in the controller
Comment: @user512967 - It depends on how you code the action method in the Controller. The most basic way would be for your action method to take a FormCollection as a parameter. You could then get the value from there.
Comment: Can u give me an Example for the collection of the Hidden field data In controller...Ne code u can comeup with
Comment: Changing your View Model (assuming its List) to Customer type will solve the issue and you can get rid of the foreach loop breaking.

Got to Get the value to the controller


Typecasting an object in C#

Question: Assume I have a method which returns object of class A
A getItem(int index)
Now I have following line of code, (I assume B is subclass of A)
B b = (B) obj.getItem(i);
but before this I have to make sure that I can typecast it into B as getItem can return object of some other subclass, say C, of A
Something like this
    if(I can typecast obj.getItem(i) to B) {
             B b = (B) obj.getItem(i);
    }

How I can do this?
Comment: Here is a useful link: :)

http://stackoverflow.com/questions/7042314/can-i-check-if-a-variable-can-be-cast-to-a-specified-type
Answer: Two options:
object item = obj.getItem(i); // TODO: Fix method naming...
// Note: redundancy of check/cast
if (item is B)
{
    B b = (B) item;
    // Use b
}

Or:
object item = obj.getItem(i); // TODO: Fix method naming...
B b = item as B;
if (item != null)
{
    // Use b
}

See "Casting vs using the 'as' keyword in the CLR" for a more detailed comparison between the two.
Answer: var item = obj.GetItem(i);
if(item is B) {
   B b = (B) item;
}

Answer: Use as instead:
B b = obj.getItem(i) as B;
if(b != null)
    // cast worked

The as operator is like a cast operation. However, if the conversion isn't possible, as returns null instead of raising an exception.
Answer: Try the as keyword. See https://msdn.microsoft.com/en-us/library/cscsdfbt.aspx
Base b = d as Base;
if (b != null)
{
   Console.WriteLine(b.ToString());
}

Typecasting an object in C#


using ATL component in Delphi

Question: [rewritten to be more comprehensible]
I am lost trying to use a COM object in Delphi. The object was created using Visual Studio ATL.
I have tested the object in VBScript:
Set ourObj = Server.CreateObject( "JC_ATL_Q.JCsimple")
ourJCversion = ourObj.JCversion
Response.Write "
Get: JCversion = " + cstr( ourJCversion)

In Delphi, I followed:

http://101.lv/learn/delphi/ch15.htm1

to create the code below, but this produces the error
"The specified procedure could not be found"
I have checked the registry and the TGUIDs seem to be correct.
Am I doing the correct thing to access an IDispatch interface? Is there a way of getting further information as to what is going wrong?
IJCsimple = interface(IUnknown)
    ['{96154141-4169-4321-BADC-A08F1B2D53A4}']
    function get_JCversion: Integer; stdcall;
  end;

const
CLASS_JCsimple: TGUID = '{6724FCDA-14F6-4D40-82A1-C8FD451BED9C}';

var
  Form2: TForm2;
  Result : variant;

implementation

procedure TForm2.Button1Click(Sender: TObject);
  begin

    Result := CreateComObject(CLASS_JCsimple) as IJCsimple;

  end;

end.

Solution:
As Remy Lebeau points out, I should not be reinventing the wheel, but should use the Component >> Import Component >> Import Type Library tool
Comment: What is your specific question.
Comment: Trying to access the property "Version" causes an Exception. Can anyone help get this sorted?
Comment: But what is your question? What specific detail in the text do you want us to address. "Can anyone help" isn't a valid question here.
Comment: Funny that you mention an exception twice in you question and once more in the comments, but you never say what the exception message is! Maybe you havn't read it or maybe you think it is irrelevant to the problem you have?
Answer: You are using the wrong declaration for your interface method.  It should look more like this:
type
  IJCsimple = interface(IUnknown)
    ['{DA13AEFD-C5A1-4A94-AD74-B9C355E1F19C}']
    function get_Version(out Result: Integer): HResult; stdcall;
    property Version: Integer read get_Version;
  end;

Or this:
type
  IJCsimple = interface(IUnknown)
    ['{DA13AEFD-C5A1-4A94-AD74-B9C355E1F19C}']
    function Version: Integer; safecall;
  end;

That being said, you should not be implementing the interface unit manually to begin with.  The correct solution is to have the IDE import the COM object's TypeLibrary and generate proper wrapper code for you:
Importing Type Library Information

using ATL component in Delphi


How to correctly to dowload xlsx file on client?

Question: I need to download a file in xlsx format. I get the contents of the file from the backend(nodeJS) and do some configuration like this :
  let blob = new Blob([excelData], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
  URL.createObjectURL(blob);
  var link = document.createElement("a");
  link.download = name;
  link.href = URL.createObjectURL(blob);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  delete link;

Its just example.I use React on client. excelData looks llike enter image description here
But when I try to open the downloaded file in Microsoft Excel, I get the message "the file is corrupt, it cannot be opened."
I tried to get the contents of the file through postman and open it - everything worked.
I think the problem in forming a link on the client.
Anybody can tell me how to solve this problem ?
thanks y'all
Comment: In the above, what's `excelData`?
Comment: FWIW, if you use [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/GlobalFetch/fetch), you can read the response as a `Blob` directly, rather than having to create one yourself.
Comment: Try this does the job nicely I have been using it for quite some time now.. https://github.com/eligrey/FileSaver.js/
Comment: @T.J.Crowder I fixed the question. Look at the attached photo
Answer: var blob = new Blob([s2ab(atob(excelData))], {      type: ''     });
 var link = document.createElement("a");
 link.download = name;
link.href = URL.createObjectURL(blob);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
delete link;
function s2ab(s) {
  var buf = new ArrayBuffer(s.length);
  var view = new Uint8Array(buf);
  for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
  return buf;
}

try this method if your excelData is correct then you will get the correct data format
Comment: Hi. I tried using your solution and got the following error : **Unhandled Rejection (InvalidCharacterError): Failed to execute 'atob' on 'Window': The string to be decoded contains characters outside of the Latin1 range.**
Answer: I solved the problem. Maybe someone will be useful. Need to get data like arrayBuffer
Example:
fetch('someURL').then(response => response.arrayBuffer()).then(result => {
 const blob = new Blob([result], {
          type: mimeType,
        });
})


Integração Sonar + Maven + Jenkins

Question: Bom dia a todos, pessoal estou configurando um servidor de integração usando Jenkins + Maven + Sonar Quebe, mas estou com o seguinte cenário:
1 - Se os testes do jUnit falham o maven interrompe o deploy da aplicação. Blz esse é o resultado esperado.
2 - Se o sonar aponta problemas em meu código(bug) o maven não para e faz o deploy normalmente.
Minha dúvida é se tem como fazer com que o Maven não faça o deploy quando o sonar indicar um bug ou até se possível um número máximo de bugs
Desde já obrigado.
Answer: Existem algumas opções para você utilizar depedendo da sua versão do Jenkins, para versões mais antigas essa funcionalidade de checagem dos Quality Gates era feita manualmente através de scripts.
1. Quality Gate Plugin
Uma simples integração através deste plugin, você pode configurá-lo em poucos passos conforme mostra a documentação oficial
2. Webhooks
A partir da versão 6.2 do Sonar essa checagem pode ser feita por meio de webhooks, conforme mostra este artigo
3. Shell Script
Conforme apontado por ansolsi zied nesta thread, você pode verificar utilizando o script abaixo:
if [ "\`curl -sL -w %{http_code} http://sonar_host/api/qualitygates/project_status?projectKey=project_key -o /dev/null -S --quiet 2>&1 | jsawk -a 'return this.status'\`" == "ERROR" ];
then
  exit 1;
fi;

Substituindo project_key pela key do seu projeto cadastrado no Sonar

Nas versões anteriores do Sonar, havia um plugin chamado Build Breaker Plugin, ele foi descontinuado e aqui você pode ler um artigo do Sonar explicando porque ele não deve mais ser utilizado.
Comment: Obrigado amigo, funcionou perfeitamente usando o Quality Gate Plugin

Integração Sonar + Maven + Jenkins


I have 8 server-grade machines used for development. Should I create a VPS cloud?

Question: My idea is that each user can spawn a VM, then use dist-cc to do compile using other VMs in the cloud.
Is such practice common in development environment? Would performance be much worse than just giving the users the physical machine access?
Comment: What kind of targets are you compiling for?  What environments are the machines running?
Answer: Your win with VMs is in manageability and failover/HA.
You will take a performance hit by running something in a VM vs on real hardware. The hit may me small or big depending on the type of load you are generating and how the VMs are set up.
IF you are going for maximum compile farm speed, I would probably not virtualize. However, VMs can be set up to be pretty quick especially if you can get some fast disk to back them. Management overhead concerns can often win over the perf hit.
I suggest a hybrid approach: let the users stand up some number of VMs for their dev environment, and have the distcc farm be physical boxes. They are easy to set up as they only do one thing...you can have an image or use something like cfengine/Chef to set them up if they die on you. This will give the users their own space that they can use, and will give you max perf from the compiler boxes.


Ensuring Secure Backend Access for Mobile App Using Firebase App Check

Question: Our mobile app includes a feature that requires access to an expensive service on our backend. To secure this service and prevent unauthorized access, we have implemented Firebase App Check for authentication. The process involves the app obtaining a token from Firebase App Check for each request, which is then validated by our backend before allowing access to the expensive service.
I have a few questions to ensure we are following best practices:

Is it a good practice to get the Firebase App Check token for each request made by the mobile app? Will this approach impact performance and introduce unnecessary overhead?

Considering that Firebase App Check tokens have a limited validity period (e.g., one hour), should we consider storing the token on the device for a specific amount of time and reuse it for subsequent requests within that timeframe? How can we strike a balance between security and efficiency in this scenario?

If we implement the token storage approach in question 2, could this introduce potential vulnerabilities? For instance, could an attacker potentially replay a previously used token within its validity period and gain unauthorized access to the expensive service?

class SomethingExpensiveService extends ExpensiveService {
  Map<String, String> prepareHeaders(String appCheckToken) {
    return {
      'accept': 'application/json',
      'Content-Type': 'application/json',
      'X-Firebase-AppCheck': appCheckToken,
    };
  }

  @override
  Future<...> makeExpensiveRequest(...) async {
    try {
      var token = await FirebaseAppCheck.instance.getToken();
      var headers = prepareHeaders(token);
      ...
    } catch (e) {
      ...
    }
  }
}

Answer: The Firebase App Check SDK itself already stores the token for up to an hour, and return that cached token - unless you explicitly tell it to force a refresh of the token by passing true to the call. So there's no additional need to do this yourself.

During this time period the token can be intercepted and used to impersonate calls coming from your device and app, which is why you should ensure to only send the token over secured connections.
In scenarios where you want to even further reduce the risk of these so-called replay attacks, you can use request a limited use token, which can be used only once. Doing this will affect your application performance (as you need to request a new token more often) and you may into attestation provider limits (as most f those have a quota limit).


remove a column of input file in c and write to output file

Question: I have a question and I wanted to remove first column from my input file and write it to the output file. I have no idea how to do it.
I searched through the site but I could not find my intended answer.
Here is my input file with the first line being header :
7 11 11
4 5 1 3 2 2 1
2 1 1 3 2 4 1
5 5 3 4 2 2 2 1 2
3 2 1 3 2 6 2 7 5
1 1 1 3 3 6 2
6 5 2 4 2 7 6
2 6 6 4 5

and my intended output file will look like this :
7 11 11
5 1 3 2 2 1
1 1 3 2 4 1
5 3 4 2 2 2 1 2
2 1 3 2 6 2 7 5
1 1 3 3 6 2
5 2 4 2 7 6
6 6 4 5

How can I do this in C?
this is what I have tried so far
int main()
{
FILE *ifp;
FILE *ofp;
char fname[]="input.txt";
char fname2[]="input-v2.txt";
char *mode = "r";
int n;
int m;
int fmt;
ifp = fopen(fname, "r");
ofp= fopen(fname2, "w");
char *token;
char *s=" ";
char line[100000];
if (ifp == NULL)
{
   printf("\nFailed to open file.\n");
    exit(1);
}
fscanf(ifp,"%d %d %d",&n,&m,&fmt);
while (fgets(line, sizeof(line), ifp)) {
    char *copy=strdup(line);
    if(line[0] == '\n')
        continue;
    char *copy=strdup(line);
    if(line[0] == '\n')
        continue;

    token=strtok(copy,s);

    while (token!=NULL && token!=""){
    char *val=token;
    val="";
    fprintf(ofp,"%s",val)
        token=strtok(NULL,s);
    }
      fprintf(ofp, "\n");
}

fclose(ifp);
return 0;
}

I am really not sure what to do. I actually need to remove first character from every line but this unfixed column number make me confused.
Comment: What are you having a problem with? The file IO (opening, closing, reading writing)? Or the string manipulation?
Comment: Are no. of columns constant for every line ?
Comment: no it is not. I do not have fixed number of columns in lines
Comment: Could you show what you have tried ? But the idea behind is just to read the file and them remove the 2 first caracters. Btw, what happen with an empty line ?
Comment: @JohnnyMopp I have problem with the process of removing the column.
Comment: @kaldoran I editted my answer so that you can see what I did before. I do not have problem with the empty lines.
Comment: You say as much in your question. But we need specifics! What exactly is it that is not working? You say "unfixed column number" but have not explained what that is... Remember this is not a site where people will just hand you a working program.
Comment: @Toby I cannot configure how to do this using strtok which I used in my program.
Comment: I would use [`strchr`](http://www.cplusplus.com/reference/cstring/strrchr/) instead. Just read the line, find the first space, then write the rest of the line. `char *space = strchr(line, ' '); if (NULL != space) fprintf(ofp, "%s\n", space + 1);`
Comment: Posted the wrong link in my comment. Here's the right link: http://en.cppreference.com/w/c/string/byte/strchr
Answer: I found it by you helps thank you. Here is the solution :
 while (fgets(line, sizeof(line), ifp)) {
    char *copy=strdup(line);
    if(line[0] == '\n')
        continue;

    token=strtok(copy,s);
    token=strtok(NULL,s);
    while (token!=NULL && token!=""){
        fprintf(ofp,"%s ",token);
        token=strtok(NULL,s);
     }
    fprintf(ofp, "\n");
}

Answer: In place of your loop you could use this -
token=strtok(copy,s);
token=strtok(NULL,s);              // get complete string after space
if(token != NULL){
     fprintf(opf, "%s", token);
}

Some problem in your loop -
while (token!=NULL && token!=""){
    char *val=token;
    val="";                         // why point val to "" ?
    fprintf(ofp,"%s",&val)          // & is not required with val
    token=strtok(NULL,s);
}

Comment: I wanted val to make my token="" which seems not a good logic.
Comment: Thank you so much for your help. I could figure it out by this trick.
Answer: You don't mention which part you are having problems with (indeed you don't show any code you have so far at all...)
Assuming you do not know the logic required to perform the task you describe I have described it in psuedo-code below
Open(input-file)
if(open failed)
    Return

Open(output-file)
if(open failed)
{
     Close(input-file)
     Return
}

read(first input-file line) // Get the header line but do nothing with it

while(not end of input-file)
{
    string = read(next input-file line)
    if(line not empty && not just new-line)
    {
        find(first character after first space in string)
        write(remainder of string to output file)
    }
}

Close(output-file)
Close(input-file)

Your example data shows that the first, header, line is not affected by the removal of the column so the first line is read in but then not used (as marked by the inline comment), you could instead simply seek the end of the first line and then start the while loop after that.


Notation of joint event probability

Question: I have been using several books and I came across different notations that I am assuming they mean the same thing, but I am not 100% sure.
Are these probabilities the same thing?
$P(AB) \equiv P(A,B) \equiv P(A \land B) \equiv P(A \cap B) \equiv P(A \times B)$?
Edited:
added $P(A \times B)$
Comment: $P(AB)$ looks more like $P(A \times B)$.
Comment: So, $P(A,B) \not \equiv P(A \times B)$?
Comment: I think the notation just originates from early developments in modern logic more precisely Boole and Boolean Algebra. In this tradition it is standard to associate mutiplication with logical AND and addition with logical inclusive or. Then since $AB$ and $A\times B$ are standard for multiplication they are were used for AND (although probably not so much any longer). You could just think of multiplying indicator functions getting 1 if and only if both indication $I[\omega \in A]$ and $I[\omega \in B]$ are equal to 1 hence the same as logical AND also denoted $\wedge$.
Answer:
$P(A, B)$ is a pretty standard notation for joint probability two events $A$, $B$, both being true,
$P(A \cap B)$ means the same, but it is using set theory notation for intersection, in probability theory it is just as a notation used for saying $A$ and $B$,
$P(A \land B)$ is the same, but is using a notation borrowed from logic for conjunction,
$P(AB)$ or $P(A \times B)$ is a confusing choice of notation; as noticed in the comment if you multiply binary numbers then $AB = A \land B$, so it would be equivalent.
However, if we start talking about random variables, then the notation $p(x, y) = P(X = x, Y = y)$ still has the same sense, while $p(xy)$ is not the same thing, since this is a distribution of a product of two random variables, that is not the same as their joint distribution (both formally, since $p(xy)$ is a function of single variable, while $p(x,y)$ is a function of two variables, and in terms of the probabilities returned by it). To give an example, say that you ask what is $P(X=5, Y=3)$, since $5\times 3 = 15$, then $XY = 15$ would be true both if $x=3$ and $y=5$, and if $x=5$ and $y=3$. This would be the case, informally speaking, if there was some kind of equivalence between $X$ and $Y$, and they were independent of each other.
Answer: $P(AB)$ is not a standard notation, $AB$ can be the name of the event, or as in your example, each letter can denote different events. But, $P(A,B)$, which maybe used for shorthand purposes, and others most probably mean the same thing.
Comment: In your opinion, $P(AB)$ is a bad notation because it may lead to confusion (you bet it), ok. I added $P(A \times B)$, do you think it is also the same?
Comment: I don't recall seeing that notation for referring probabilities. It's like a cartesian product. Not saying that it is invalid, but probably rare. All books and lecture notes use their own notation, although they have a lot in common.
Comment: Why $P(A,B)$ may be used for shorthand? What do you mean?

Notation of joint event probability


Integrate: $\int \frac{dx}{x \sqrt{(x+a) ^2- b^2}}$

Question: How to evaluate
$$\int \frac{dx}{x \sqrt{(x+a) ^2- b^2}}$$
I tried trigonometric substitution $x + a = b \sec \theta$ and I encountered
$$\int \frac{\tan \theta}{ (b - a \cos \theta) \sqrt{\tan^2 \theta}}d\theta$$
how to handle this term $\displaystyle \frac{\tan \theta}{|\tan \theta|}$?
Comment: The expression you should get might depend on whehter $ba$.
Comment: @MichaelHardy yes sorry
Comment: $
\int \frac{dx}{x \sqrt{(x+a) ^2- b^2}} = \begin{cases}
 \frac{1}{\sqrt{b^2-a^2}} \tan^{-1}\frac{ax +a^2-b^2}{\sqrt{(b^2-a^2)((x+a)^2-b^2)}},& ab
\end{cases}
$
Answer: I substituted $x=1/y$ and got
$$-\int \frac{dy}{\sqrt{1+2 a y+(a^2-b^2) y^2}}$$
I then completed the square in the square root to get
$$-\frac{1}{\sqrt{a^2-b^2}} \int \frac{dy}{\displaystyle\sqrt{\left(y+\frac{a}{a^2-b^2}\right)^2-\left(\frac{a}{a^2-b^2}\right)^2}}$$
Now let
$$y=\frac{a}{a^2-b^2} (\cosh{u}-1)$$
Then the integral becomes
$$-\frac{1}{\sqrt{a^2-b^2}} \int du \frac{\sinh{u}}{\sinh{u}} = -\frac{1}{\sqrt{a^2-b^2}} u+C$$
where $C$ is a constant of integration.  Back substituting, we get
$$\int \frac{dx}{x \sqrt{(x+a)^2-b^2}} = -\frac{1}{\sqrt{a^2-b^2}}\text{arccosh}{\left(\frac{a^2-b^2}{a x}+1 \right)} + C $$
Use $\text{arccosh}{z} = \log{(z+\sqrt{z^2-1})}$ to express the result in terms of logs.
Answer: First, examine separately intervals where $\tan\theta>0$ and where $\tan\theta<0$. After that, see if you can express the answer in a way that's less-than-explicitly piecewise (perhaps by using absolute values).
Comment: let it be $I$ if $\theta>0$, then if  $\theta<0$, then my answer is $-I$, but Mathematica gives me something negative of $\log(-x)$ for my original integration $\frac{1}{x \sqrt{(x+a)^2 - b^2}}$
Comment: mathematica evaluates it to $$
\frac{\log (-x)-\log \left(\sqrt{a^2-b^2} \sqrt{(a+x)^2-b^2}+a (a+x)-b^2\right)}{\sqrt{a^2-b^2}}$$ I can't get this $\log(-x)$ part
Comment: Before checking details, by initial reaction is that $\log|x|$ occurs as the antiderivative of $1/x$, and that's the same as $\log x$ if $x>0$ and it's the same as $\log(-x)$ if $x<0$.


Generalization for interpreting a test?

Question: At my college I am doing a lot of testing, such as testing for autocorrelation, White , DW, $t$, $F$ etc.
However, I always have to look up, when to reject and when to accept for example $H_0$
Hence, I was wondering if there is a generalization for interpreting a statistical test such as:
When $value$ is greater than $value$ always reject H0.
From the point of view of your professional experience, is there a pattern in all statistical tests?
Comment: okay gonna take this as an answer then
Comment: The p-value you mean?
Comment: Yes, after what I have read at the moment. I think its the p-value.
Comment: Read the first sentence: http://en.wikipedia.org/wiki/P-value
Answer: In general the decision which significance level to take and when to reject depends on the prior knowledge of the researcher, which is a way to incorporate this knowledge in the test.
Read up on the p-value, which is basically what you are looking for. However, given that testing is highly dependent on the sample, the experiment or model, there are dangers when generalizing on the p-value.
A parallel thread to this has a good post on the issue: https://stats.stackexchange.com/a/61027/18459
The corresponding article can be downloaded here: http://www.psych.umn.edu/people/meehlp/113TheoreticalRisks.pdf
Answer: It's not true for all tests in statistics. Some non-parametric tests have reverse decisions.
Usually it is said that if the calculated value of a test statistic is greater than the tabulated value then we fail to reject $H_0$.
It is better to have a decision on the basis of the p-value. If the p-value is less than the chosen level of significance then we fail to reject $H_0$.

Generalization for interpreting a test?


NullPointerException at java.io.File.(Unknown Source) no Java com Lucene

Question: Estou recebendo o seguinte erro no meu código em Java
Exception in thread "Thread-2" java.lang.NullPointerException
    at java.io.File.<init>(Unknown Source)
    at Indexador.indexaArquivosDoDiretorio(Indexador.java:42)
    at Princ$1$1.run(Princ.java:235)
    at java.lang.Thread.run(Unknown Source)

Não sei por que começou a dar esse erro, acredito que seja algo relacionado aos objetos do tipo File não aceitarem String. Segue o código:
public void indexaArquivosDoDiretorio() {
    try {
        Properties prop = getProp();
        // Diretório que irá guardar o índice;
        String diretorioDosIndices = prop.getProperty("diretorio.indice");
        // Diretório que contém os documentos que serão indexados;
        String diretorioParaIndexar = prop.getProperty("diretorio.fonte");
        File diretorio = new File(diretorioDosIndices);
        apagaIndices(diretorio);
        // Directory: representa o diretório do índice;
        Directory d = new SimpleFSDirectory(diretorio);
        // Analyser/StandardAnalyser: fazem o pré-processamento do texto.
        // Existem analisadores inclusive em português;
        Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_47);
        // IndexWriterConfig: configurações para criação do índice. No
        // projeto serão utilizados os valores padrão;
        IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_47,
                analyzer);
        // Inicializa o IndexWriter para gravação;
        writer = new IndexWriter(d, config);
        long inicio = System.currentTimeMillis();
        indexaArquivosDoDiretorio(new File(diretorioParaIndexar));
        // Fecha o IndexWriter e comita as mudanças
        writer.commit();
        writer.close();
        long fim = System.currentTimeMillis();
        JOptionPane.showMessageDialog(
                null,
                "Quantidade de arquivos indexados: " + i + "\n"
                        + "Tempo para indexar: "
                        + String.valueOf((fim - inicio) / 1000) + "s");
    } catch (IOException e) {
        logger.error(e);
    }
}

Linha 42:
File diretorio = new File(diretorioDosIndices);

Comment: Você chegou a debugar e ver qual o conteúdo da variável `diretorioDosIndices`?
Comment: Tentou fazer um `sysout` para ver o conteúdo da variável `diretorioDosIndices`?
Comment: Tentei, mas o Eclipse não para nos breaks ou não chega neles.
Answer: File possui construtor que recebe como argumento uma instância de String, veja o javadoc do construtor.

File(String pathname)
  Creates a new File instance by converting the given pathname string into an abstract pathname.

Essa exceção ocorre por conta do argumento passado no construtor ser null, nesse caso a variável diretorioDosIndices está nula.
No construtor de File que recebe String como argumento existe a seguinte documentação para exceções lançadas:

Throws:
  NullPointerException - If the pathname argument is null

Java doc retirado desse endereço.
Por fim, verifique a obtenção do valor da variável diretorioDosIndices, pois não há dúvidas que a chamada prop.getProperty("diretorio.indice") não encontra a propriedade e por essa razão retorna null.
Comment: Realmente, o valor estava null. Mas o motivo está muito estranho, pois eu tive que alterar o nome do prop por que estava dando conflito com outro que eu uso na mesma classe.


Sony Camera Remote API available over USB on new models?

Question: While Sony teases new camera models to customers (UMC-R10C, UMC-S3C) and mentions both API access and USB connectivity (rather than wifi) - the Sony Camera Remote API currently only mentions wifi. Is there any information on how to use those upcoming cameras? Some 'selected' developers are integrating them already (see: http://diydrones.com/profiles/blogs/sony-3dr-announce-new-enterprise-camera-for-solo) but independent developers are left in the dark.
Will the API be the same as the current Camera Remote API?
What kind of USB connection will it have. Just a USB network interface?
Answer: +1 on question/request. A lot of DIY'ers are interested in (buying and) controlling Sony cameras via USB. WiFi in 'noisy' environments is problematic.


Exercise 6, Section 17 of Munkres' Topology

Question:
Let $A$, $B$, and $A_\alpha$ denote subsets of a space $X$. Prove the following:
(a) If$A\subseteq B$,then$\overline{A} \subseteq \overline{B}$. (b) $\overline{A\cup B}=\overline{A}\cup \overline{B}$.
(c) $\overline{ \bigcup A_{\alpha}} \supset \bigcup \overline{A_\alpha }$ ; give an example where equality fails.

My attempt: (a) $A\subseteq B \subseteq \overline{B}$. Since $\overline{B}$ is closed and $A\subseteq \overline{B}$, we have $\overline{A} \subseteq \overline{B}$. Is this  proof correct? If you think last step is bit of a jump, you can look at https://courses-archive.maths.ox.ac.uk/node/view_material/50743 lecture notes, page no. 6.

(b) Approach(1): We first show $(A\cup B)' = A' \cup B'$. Let $x\in (A\cup B)' \Rightarrow \forall U\in \mathcal{N}_x, (U-\{x\})\cap (A\cup B)\neq \phi$. By De Morgan's laws, $[(U-\{x\}) \cap A] \cup [(U-\{x\})\cap B]\neq \phi$. Which means $(U-\{x\}) \cap A$ or $(U-\{x\})\cap B$ or both is non empty. By definition of limit point, $x\in A'$ or $x\in B'$. So $x\in A' \cup B'$. Thus $(A\cup B)'\subseteq A'\cup B'$.
Conversely, $x\in A' \cup B'$. If $x\in A'$, then $\forall U\in \mathcal{N}_x, (U-\{x\})\cap A\neq \phi$. So $(U-\{x\})\cap (A\cup B)= [(U-\{x\}) \cap A] \cup [(U-\{x\})\cap B]\neq \phi$. Thus $x\in (A\cup B)'$. Similarly, if $x\in B'$, then $x\in (A\cup B)'$. Hence $(A\cup B)' = A' \cup B'$. So $\overline{A\cup B}= (A\cup B) \cup (A\cup B)'= (A\cup A') \cup (B\cup B')= \overline{A} \cup \overline{B}$. Is this proof correct? In proof of $(A\cup B)' \subseteq A' \cup B'$ what if, for one neighbourhood of $x$,$(U-\{x\}) \cap A$ is non empty and for some other neighbourhood it's empty?
Approach(2): let $x\in \overline{A\cup B}$. Then $\forall U\in \mathcal{N}_x, U\cap (A\cup B)\neq \phi$. So $(U\cap A)\cup (U\cap B)\neq \phi$. Rest of the proof is similar to approach(1). I'm facing the same problem as approach(1). Is this proof correct?
Approach(3): To show $\overline{A\cup B} \subseteq \overline{A}\cup \overline{B}$. $\overline{A}$ and $\overline{B}$ is closed in $X$. So $\overline{A}\cup \overline{B}$ is closed in $X$. $A\subseteq \overline{A}$ and $B\subseteq \overline{B}$. So $A\cup B\subseteq \overline{A}\cup \overline{B}$. Hence $\overline{A\cup B} \subseteq \overline{A}\cup \overline{B}$.
Approach(4): Since $A\cup B\subseteq \overline{A} \cup \overline{B}$, by part(a) $\overline{A\cup B} \subseteq \overline{ \overline{A} \cup \overline{B} }$. Since $\overline{A} \cup \overline{B}$ is closed, it's equal to it's closure. Thus $\overline{A\cup B} \subseteq \overline{A} \cup \overline{B}$.

(C) Let $x\in \bigcup \overline{A_\alpha}$. $x\in \overline{A}_j$. So $\forall U\in \mathcal{N}_x, U\cap A_j \neq \phi$. Since $A_j \subseteq  \bigcup A_\alpha$, we have $U\cap A_j \subseteq U\cap (\bigcup A_\alpha)$. Since $\exists p\in U\cap A_j$, $p\in U\cap (\bigcup A_\alpha)$. So $U\cap (\bigcup A_\alpha)\neq \phi$. Thus $x\in \overline{\bigcup A_\alpha}$. Hence $\overline{ \bigcup A_{\alpha}} \supset \bigcup \overline{A_\alpha }$.
Comment: Your proof of $(A\cup B)' = A' \cup B'$ is incorrect (your doubt is justified). See in my answer for an inspiration how it can be salvaged: $A' \subseteq (A \cup B)'$ is trivial as $A \subseteq A \cup B$ and ditto for $B$. Use contradiction to show $(A \cup B)' \subseteq A' \cup B'$ as I did directly for closure. Once you have the fact for $A',B'$ the closure fact is immediate: $$\overline{A \cup B}= (A \cup B)\cup (A \cup B)'= (A \cup B) \cup (A' \cup B')= (A \cup A') \cup (B \cup B') = \overline{A} \cup \overline{B}$$
Comment: For completeness - your answer to part (a) is correct. $ B \subseteq \overline{B}$ by definition 1.28 (a) of closure.   $\overline{A} \subseteq \overline{B} $ by 1.28 (b).
Comment: Yes, it's the same reason in essence.
Comment: This (https://math.stackexchange.com/q/3648551/861687) is another way to prove part(b).
Comment: @HennoBrandsma My part(b) incorrect solution is a perfect manifestation of exercise 7.
Answer: So Munkres defines (or shows the equivalence of) three definitions of $\overline{A}$ that section.

The original definition is $\overline{A}$ is the intersection of all closed sets containing $A$ (where closed=complement is open, and the topology is given).

He then goes on to show that $x \in \overline{A}$ iff every neighbourhood of $x$ intersects $A$ which is a handy view to actually find the closure of specific sets in a space.

Finally theorem 17.6 tells us $$\overline{A} =A \cup A'$$
which is added (I think) mainly for historical reasons, it's one of the oldest way of seeing the closure (as $A'$ was already defined way back by Cantor).

Your proof of the exercise alternates between these definitions, which is fine. The limit point one is often the least convenient for proofs though because you're often forced to make separate arguments for points in $A$ and in $A'$, and that's often more work.
(a): your way is fine: $\overline{B}$ is closed and contains $A$ so it's one of the sets in the defining intersection in def. 1 so $\overline{A} \subseteq \overline{B}$ then trivially holds. No "jump" at all: any intersection is trivially a subset of each of its intersectees (to coin a word), so of $\overline{B}$ in particular.
(b):approach 1 is messy, so avoid it; see my comments above though. An approach using def.1 could go:
$\overline{A} \subseteq \overline{A \cup B}$ by part (a). Likewise $\overline{B} \subseteq \overline{A \cup B}$. So for the union too:
$$\overline{A} \cup \overline{B}  \subseteq \overline{A \cup B}$$
and we have one inclusion. OTOH: $\overline{A} \cup \overline{B}$ is closed (finite union) and contains $A \cup B$ so by the same argument as before: $$\overline{A \cup B} \subseteq \overline{A} \cup \overline{B}$$ and we have the second inclusion and equality.
The point based approach using neighbourhoods and def 2:
Suppose $x \in \overline{A \cup B}$. Then $x \in \overline{A}\cup \overline{B}$: because if $x \notin \overline{A}$ and $x \notin \overline{B}$ we'd have $O_1 \in \mathcal N_x$ so that $O_1 \cap A = \emptyset$ and we'd also have $O_2 \in \mathcal N_x$ so that $O_2 \cap B = \emptyset$ (def 2 negated!). But then $O_1 \cap O_2 \in \mathcal N_x$ and moreover $$(O_1 \cap O_2) \cap (A \cup B) \subseteq (O_1 \cap A) \cup (O_2 \cap B)= \emptyset$$ contradicting that $x \in \overline{A \cup B}$, so the claimed inclusion holds. The other inclusion $\overline{A} \cup \overline{B} \subseteq \overline{A \cup B}$ again follows from (a) as before (a union is a superset of each of its unionees etc.).
For (c) use def 1 and note that for each fixed $a'$, $A_{a'} \subseteq \bigcup_{a \in A} A_a$ and so part (a) gives $\overline{A_{a'}} \subseteq \overline{\bigcup_{a \in A} A_a}$ and as this holds for all $a' \in A$ we get again $\bigcup_{a \in A} \overline{A_a} \subseteq \overline{\bigcup_{a \in A} A_a}$ as required.
The approach you do via def 2 is also possible: let $x \in \bigcup_{a \in A} \overline{A_a}$. Then for some $a' \in A$, $x \in \overline{A_{a'}}$. Now let $O \in \mathcal N_x$ be arbitrary. Then $O \cap A_{a'} \neq \emptyset$ and so trivially $O \cap (\bigcup_{a \in A} \overline{A_a}) \neq \emptyset$ too (as $A_{a'}$ is a subset of the union). As $O$ was arbitrary, $x \in \overline{\bigcup_{a \in A} A_a}$ and we're done.
Comment: @user264745 glad it was useful to you!
Comment: @user264745 Do as many exercises as you can, especially the ones about *concrete* spaces and sets; they're good for intuition building. You don't *guess* answers but prove them. You can apply the theorems in the text on real things, always good. Most answers are already on this site. So you can always check afterwards.
Comment: Thank you so much for the answer. You summarize my post very well, especially by specifying three equivalent definition. Your answer give two "new(which is not in my post)" approach and one "clever" way to prove desired result. New approach are (1) $\overline{A} \cup \overline{B}  \subseteq \overline{A \cup B}$ & (2) $\overline{ \bigcup A_{\alpha}} \supset \bigcup \overline{A_\alpha }$. Clever approach is $(A\cup B)'\subseteq A'\cup B'$, use contradiction to prove that inclusion.
Comment: I need your suggestion. Should I do exercise like 14, 16, 17, 18 & 20? These exercise are like examples. I'm not really interested in doing this kind of(examples) problems because I don't known what I have to prove. It involves a lot of guessing(educated). I'm bad at making guess and coming up with counter example, usually I left them.
Comment: For instance, in exercise 14 I can't remotely guess, that sequence converge to every point of $\Bbb{R}$.

Exercise 6, Section 17 of Munkres’ Topology


Cannot open precompiled header file: 'precheader.pch': No such file or directory

Question: I just set up a fresh cocos2d project using the cocos new cli. When I open the project, I am immediately greeted with several errors about files not being able to open the precompiled header. The files don't actually try to include these files though, so I'm guessing it's a CMake setting. Are these files supposed to be automatically generated?
I'm using Visual Studio 2019. Sorry if this a duplicate post, but i've been trying to get this to work for the past 2 hours but with no success...
Comment: Do you really need precompiled headers?  Profile to see if the precompiled headers save you significant time on the builds.  Otherwise turn them off.  Your issue is just one of many reasons not to use precompiled headers.
Comment: I'd love to turn them off but I have no idea how to, I'm a complete beginner with CMake. Disabling them is easy when using visual studio's sln project structure, but I can't find a solution with cmake
Comment: Visual Studio 2017 has the command line "/Yu" to enable precompiled headers.  Check your options passed to the compiler.  You could also search the internet for "MSDN C++ visual studio command line precompiled headers off"
Comment: That only works when using visual studio project files though right? I don't have a "project settings" menu since I'm using cmake
Comment: I didn't say to use the project file.  I said passing command line switches to the compiler.  Big difference.  When using a makefile, you'll be passing command line switches to the compiler (such as the classic `-I` and `-c`).
Answer: You can generate Visual Studio project files:
cd YourGame\proj.win32
cmake .. -G"Visual Studio 16 2019" -A win32

Then open the generated solution file, it should compile without any error.


Configurarion of Alert on Windows Server 2003

Question: I'm trying to configure an alert on low space on disk in Windows Server 2003, I already followed this step by step tutorial of microsoft. I try to execute a bat file created by me, located on the home folder of the user I'm using.
I seted to trigger when the free space is below 6 GB when the disk have lower free space than 6 GB, the "Sample data interval" is the default (5 seconds).
The problem is that the alert isnt triggered.
And another thing, the user that is seted for the alert isnt the root user, but It have administration privileges.
Thanks in advance
Comment: Right - so what's your actual question?
Comment: What errors are you receiving, if any?
Comment: vCole I'm not getting any errors,  It just won't trigger
Answer: Try the following script, it is self explanatory. This script will send an email to email@example.com if the disk space is less than 1 GB. You need to modify the email account details and schedule it as a task.
Calculate free disk space on the server
Const HARD_DISK = 3
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\" & strComputer & "\root\cimv2")
Set colDisks = objWMIService.ExecQuery _
("Select * from Win32_LogicalDisk Where DriveType = " & HARD_DISK & "")
Set objComputer = CreateObject("Shell.LocalMachine")
i = 0
intCharacters = 5
flag = 0
For Each objDisk in colDisks
freespace = objDisk.FreeSpace
drive = objDisk.DeviceID
totalspace = objDisk.Size
totalspace = totalspace/1073741824
totalspace = Left(totalspace, intCharacters)
totalspace = totalspace & " GB"
freespace = freespace/1073741824
freespace = Left(freespace, intCharacters)
if freespace < 1 then
flag = 1
end if
freespace = freespace & " GB"
display = display + Cstr(objDisk.DeviceID) & " " + freespace + display1 &"              "+ Cstr(objDisk.DeviceID) & " " + totalspace + vbNewLine + vbNewLine
computer = "Server: " & objComputer.MachineName + vbNewLine + vbNewLine + "Space Available on each drives: " + vbNewLine + vbNewLine
head = "Free Space              Total Space" + vbNewLine + vbNewLine
Next
if flag = 1 then
Set objEmail = CreateObject("CDO.Message")
<code>        ObjEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 'Send the message using the network (SMTP over the  network).

        ObjEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") ="SMTP SERVER"

        ObjEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25

        ObjEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = False 'Use SSL for the connection (True or False)

        ObjEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60
</code>
'           ObjEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1 'basic (clear-text) authentication
'           ObjEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername") ="firstname.lastname@example.com"
'           ObjEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword") ="EMAIL PASSWORD"       ObjEmail.Configuration.Fields.Update
<code>        objEmail.From = "email@example.com"

        objEmail.To = "email@example.com"

        objEmail.Subject = "YOUR SUBJECT"

        objEmail.Textbody = head + display

        objEmail.Send

        Set ObjEmail = Nothing
</code>
end if


Não consigo fazer conexão com Banco de Dados no Entity Framework

Question: Boa noite,
Não estou conseguindo fazer conexão com o banco de dados para criar as tabelas da pasta Models no .NET. Quando tento fazer as Migrations retorna este erro:
"Não foi possível executar porque o comando ou o arquivo especificado não foi encontrado.
Possíveis motivos para isso incluem:
Você digitou incorretamente um comando de dotnet interno. Você pretendia executar um programa .NET, mas dotnet-ef não existe. Você pretendia executar uma ferramenta global, mas não foi possível encontrar um executável com prefixo de dotnet com esse nome no CAMINHO."
O comando que utilizei para fazer as migrations foi este: dotnet ef migrations add
Já fiz a configuração do DbContext desta forma:
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace APIVirtualCard.Data
{
    public class VCContext : DbContext
    {
        public DbSet<Card> Cards { get; set; }
        public DbSet<Email> Emails { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("server=.;database=myDb;trusted_connection=true;");
        }
    }
}````

Answer: Provavelmente o comando "ef" do dotnet não foi encontrado, ou por não ter sido instalado, ou por não estar no seu PATH.
Para instalar faça: dotnet tool install --global dotnet-ef
Para colocar no PATH, de modo que seja encontrado e possa ser utilizado de qualquer lugar:

No Windows: vá em editar variáveis de ambiente e adicione %USERPROFILE%\.dotnet\tools (ou o local onde as ferramentas do dotnet são instaladas no seu sistema) à variável PATH.
No Linux: Adicione uma linha na configuração do shell export PATH="$PATH:$HOME/.dotnet/tools/"
No MacOS: Adicione uma linha na configuração do shell set path = ($path $HOME/.dotnet/tools/)

ref.: https://stackoverflow.com/questions/56862089/cannot-find-command-dotnet-ef
Depois disso, dotnet ef migrations add NomeDescritivoDaSuaMigracao deve gerar a sua migração e um snapshot no modelo, deixando tudo certo para um subsequente dotnet ef database update


Set a value across all Hashes in an Array

Question: I have a ruby Array full of Hashes. I want to set a specific value for each item to the same value. For example, if I have an Array of Cars (Hash) and each car has a key of wheels. How do I set all the wheels to "square"?
I'm trying array.each.wheel = "square", but it's not working.
Comment: http://ruby-doc.org/core-2.2.0/Array.html#method-i-each
Comment: This is an odd expression, 'array.each.wheel'. I'd recommend looking at the 'each' method.
Answer: Try this:
<code>array = [ {:wheel => "circle"}, {:wheel => "circle"}]
p array
array.each { |dictionary| dictionary[:wheel] = "square"}
p array
</code>
Output:
<code>[{:wheel=>"circle"}, {:wheel=>"circle"}]
[{:wheel=>"square"}, {:wheel=>"square"}]
</code>