install imagemagick and PECL/imagick on XAMPP on windows

Question: i'm trying to install imagemagick under windows with XAMPP and PHP 5.6.3
i have download and installed imagemagick ( ImageMagick-6.9.1-0-Q16-x64-dll.exe ) yet. In command window (cmd) i try to use convert ecc... and work correctly (then PATH is correct).
Next i download DLL from PECL/package/imagick in version 3.2.0b2 x64 TS for php 5.6 ( http://windows.php.net/downloads/pecl/releases/imagick/3.2.0b2/php_imagick-3.2.0b2-5.6-ts-vc11-x64.zip )
i have set php.ini for load extension (retrive in before zip package and copyi it in c:\xampp\php\ext\ folder), i have copy all CORE_RL_*.DLL (retrive in before zip package) in c:\xampp\apache\bin\
restart PC and resstat apache/php server.
When apache/php start i have 2 warning msgbox (i think one for each PID(s) port 80 and port 443 ) than explain: "PHP Startup:" and i can press only ok.
in Xampp control panel Apache module and Mysql module are green but if i visited phpinfo.php i don't see imagemagick or imagick extension!
what's wrong???
what can i do it?
help me please
Answer: Include the extension in php.ini file if not done.
<code>extension=php_imagick.dll
</code>
And restart apache.
Comment: Okay, I think you should start from scratch again with this tutorial http://www.kobashicomputing.com/installing-imagemagick-with-php-and-windows
Comment: i just do it, but nothing
Comment: You dont have to create folder in php ext. Just paste all in c:\xampp\php\ext\
Comment: Also please check you have 64bit or 32bit windows.
Comment: i try with bot version (32 x86 e 64bit) but nothing, when start load libraries and the mex is show :(
Comment: Try installing xampp from fresh as you have done many changes and then follow this tutorial. I've installed imagick through this yesterday only. Download imagick from this link http://php.net/manual/en/imagick.installation.php
Comment: Thank you tiGer, as soon possible i try your tutorial link, my installation is clean, i have installed xampp on Virtual Machines
Comment: Great.. If you get into any problem then let me know if i can help.
Comment: i try your linked tutorial but when i start apache an error VCOMP110.DLL is missing. I try to reinstall Visual C++ Redistributable Packages any version 32 64 bit from 2008 to 2013 but nothing, always this error
Comment: i found it on my computer and i copy it on c:\ImageMagick with other dll files, than apache start with my first message "PHP startup", but nothing about imagick in php_info()
Comment: Check your php version and windows bit(32/64) and download imagick accordingly from above link..
Comment: Then unzip it in php/ext without creating any folder.
Comment: i follow your istructions but nothing, i try it all for x86 and for x64, i try to remove and reinstall all but every time i have this error
Comment: Give a try to download this http://windows.php.net/downloads/pecl/releases/imagick/3.1.2/php_imagick-3.1.2-5.5-ts-vc11-x86.zip   and extract in php/ext
Comment: And use this  http://ftp.sunet.se/pub/multimedia/graphics/ImageMagick/binaries/ImageMagick-6.6.5-10-Q16-windows-dll.exe  as imagemagic installation
Comment: with the first link from windows.php.net i have always this error:
http://picpaste.com/Cattura.PNG

with second link i have this warning
http://picpaste.com/Cattura2-TfzoU46g.PNG
Comment: Whats your xampp version?
Comment: last version, any package will be new download more and more time...it's all last version, or your version INDICATE by you in tutorial.


RNN text classification using keras

Question: I have wrote this RNN text classification system in keras with the tutorials available in the web. it is working fine and show output also. But can some one check my code and tell me whether my implementation is correct or not?
# LSTM with dropout for sequence classification
import numpy
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.layers import LSTM
from keras.preprocessing import sequence,text
from keras.layers.embeddings import Embedding
import pandas as pd

# fix random seed for reproducibility
numpy.random.seed(7)

#fetching sms spam dataset
url = 'https://raw.githubusercontent.com/justmarkham/pydata-dc-2016-tutorial/master/sms.tsv'
sms = pd.read_table(url, header=None, names=['label', 'message'])

#binarizing
sms['label_num'] = sms.label.map({'ham':0, 'spam':1})
sms.head()

X = sms.message
y = sms.label_num
print(X.shape)
print(y.shape)

###################################
tk = text.Tokenizer(nb_words=200, lower=True)
tk.fit_on_texts(X)

x = tk.texts_to_sequences(X)

print len(tk.word_counts)

###################################
max_len = 80
print "max_len ", max_len
print('Pad sequences (samples x time)')

x = sequence.pad_sequences(x, maxlen=max_len)

max_features = 200
model = Sequential()
print('Build model...')

model = Sequential()
model.add(Embedding(max_features, 128, input_length=max_len, dropout=0.2))
model.add(LSTM(128, dropout_W=0.2, dropout_U=0.2))
model.add(Dense(1))
model.add(Activation('sigmoid'))

model.compile(loss='binary_crossentropy', optimizer='rmsprop')

model.fit(x, y=y, batch_size=500, nb_epoch=1, verbose=1, validation_split=0.2, show_accuracy=True, shuffle=True)

Comment: I'm voting to close this question as off-topic because it belong to codereview.stackexchange.com
Comment: Try https://codereview.stackexchange.com/
Comment: how to determine max_features, input_length and what is 128?
Answer: Your implementation is good, however, the feature "show_accuracy=True" is deprecated. If you want to monitor the accuracy during training and test, please use it as a metric. Metrics can be custom but some of them like accuracy are preimplemented. Use it like thise :
model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])

if you define a custum metric :
def my_metric(y_pred, y_true):
    ....
    return metric_computed

you can use it like this and it will be computed at the same time as the accuracy (and the loss by default) during training :
model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy',my_metric])

Otherwise the implementation seems good :)

RNN text classification using keras


Silverlight CliptoBound property issue

Question: I am working on a Silverlight application and my problem is like this: I have a WrapPanel
and inside the WrapPanel I am adding a number of images. Then, I rotate these images either
by 90 degrees or -90 degrees.
So if my image size is 200 by 250, when I rotate it it will go out of the WrapPanel by 50 pixels. Is there a way to clip this image to the WrapPanel's actual bounds?
Comment: I am looking also measurement of hieght and width let say if I have hieght 600 and width 600 then it will give me space 600*600 how i can measure.
Comment: Are all the images in the panel the same size?
Answer: Sounds to me like you are using the RenderTransform to rotate the image.  The problem is the transform is applied after the size and position of the image has been allocated hence the rotated image bleads outside of its original rectangle.
One solution is to use the LayoutTransfomer to effect that transform instead.  This would cause the WrapPanel to re-flow the elements even moving the image to the next row. Here is an example using rectangles for simplicity:-
    <ScrollViewer HorizontalScrollBarVisibility="Disabled">
        <ItemsControl ItemsSource="{StaticResource TestData}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <toolkit:WrapPanel />
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <toolkit:LayoutTransformer RenderTransformOrigin="0.5, 0.5" Margin="5">
                        <toolkit:LayoutTransformer.LayoutTransform  >
                            <RotateTransform Angle="0" />
                        </toolkit:LayoutTransformer.LayoutTransform>
                        <Rectangle Width="100" Height="150" Fill="Blue" MouseLeftButtonUp="Rectangle_MouseLeftButtonUp"  />
                    </toolkit:LayoutTransformer>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </ScrollViewer>

I've added code-behind:-
    private void Rectangle_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        LayoutTransformer lt = ((FrameworkElement)sender).Parent as LayoutTransformer;
        RotateTransform rt = (RotateTransform)lt.LayoutTransform;
        rt.Angle += 90;
        lt.ApplyLayoutTransform();
    }

My TestData items source is an arbitary List<T>, doesn't really matter what is in the list just that it contains a few items.
Using the ScrollViewer as dynamic clipping region
Note that its normal to place a WrapPanel in a ScrollViewer which naturally clips its content anywar.
Perhaps you really do want to clip the WrapPanel and you don't want any scrolling.  Obviously you could apply a RectangleGeometry its Clip property but you would have to ensure the clip rectangle always matched the actual size of the WrapPanel.  You could do that by monitoring its SizeChanged event and using a bit of code.
Another approach is to put it in a ScrollViewer then disable both scroll bars.
Comment: +1 good answer, plus see my additional answer below to simplify the clipping.
Comment: Dear AnthonyWJones I have one usercontrol and this user control I am adding as image into wrappanel.select image And I am click on vertical and horizontal button at that time it will ratote. so how I can implement this.
Comment: @Jitendra:  I'm not sure how much of that you want me to describe how to implement.  I'm also not sure how the terms "vertical" and "horizontal" apply to rotation,  are you sure you don't mean rotate clockwise and anti-clockwise?  You could use the `MouseLeftButtonUp` as in my example but instead of rotating you could simple store the `LayoutTransformer` in a field.  Then the clicks on your buttons could modify the `LayoutTransform` property of the field as you see fit.
Answer: Just to add to AnthonyWJones answer above, which is entirely correct, you need to rotate during layout rather than render. Silverlight Panels do not clip their contents, in order to perform clipping you must set their Clip property to the required geometry manually.
The following blog post provides an attached behaviour that will automatically clip the bounds of a panel:
http://www.scottlogic.co.uk/blog/colin/2009/05/silverlight-cliptobounds-can-i-clip-it-yes-you-can/
You simply set the property as follows:
    <Canvas util:Clip.ToBounds="true"
            Grid.Column="1"  Background="Aqua" Margin="20" >
        <Ellipse Fill="Red" Canvas.Top="-10"
                 Canvas.Left="-10" Width="130" Height="130"/>
    </Canvas>

Silverlight CliptoBound property issue


Digital Nirvana: Where does a callvirt of a non-existent method end up?

Question: I call a property set-accessor on a library class which in its base class is marked as abstract. Now at runtime I force the application to run against another version of the library where the class implements only the underlying interfaces of the base class, but isn't derived from it.
Interestingly, .NET will run the code, but setting the property has no effect. What's going on behind the scenes?
Offending Code:
MyDbParameter param = new MyDbParameter();
param.ParameterName = "p";
Console.Out.WriteLine("ParameterName: " + param.ParameterName);

Library 2.0 (compiled)
public sealed class MyDbParameter : System.Data.Common.DbParameter
{
    public override string ParameterName
    {
       get { return _name; }
       set { _name = value; }
    }
    //...
}

Library 1.0 (run)
public sealed class MyDbParameter : MarshalByRefObject, IDbDataParameter, IDataParameter
{
    public string ParameterName
    {
        get { return _name; }
        set { _name = value; }
    }
    //...
}

Looking at the MSIL of the calling code I suppose the virtual call is resolved via the MetodTable of the base class:
IL_0001: newobj instance void [Library]Library.MyDbParameter::.ctor()
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldstr "p"
IL_000d: callvirt instance void [System.Data]System.Data.Common.DbParameter::set_ParameterName(string)

But the base class does not exist when running the code - neither does DbParameter.set_ParameterName(). How is it possible that .NET doesn't complain about that? Which method actually gets called?

UPDATE:
As suggested by Samuel I've decompiled the class System.Data.Common.DbParameter and adopted it in both of my libraries. The behavior reproduces regardless of wherher I derive from MarshalByRefObject or comment all of it out - hereby I believe I have falsified Mason's answer.
But during the process I've discovered what happens: In reality it is the setter/getter of some other property of MyDbParameter in Library 1 what is called, e.g. Size (which is of type  int!) - it depends on the property order in code. In the previous case I implemented the setters of other properties so that I ignored the supplied values, therefore I could see no effect. Now if all of them have automatic getters/setters, the output of my code is actually correct.
The question remains: Why doesn't .NET complain about the missing method at runtime?
Comment: Can you reproduce this with a user-defined base class?
Answer: I believe your nirvana is filled with MarshalByRefObjects. They are handled uniquely by the framework, as it instruments all access to them in order to treat them as proxies for remote objects. The MBRO can't actually fulfill the offending code's request (since your v1 class doesn't support DbParameter::set_ParameterName), so it is taking the long road to nowhere. It isn't treated as a MissingMethodException since MBRO's are usually missing requested members, so the runtime is far more lenient.
However, if you tried changing your offending code to cast param as an IDbDataParameter before setting the property, I imagine it would work, since both v1 and v2 support that interface.
Comment: @Mason I reproduced the sample without `MarshalByRefObjects`, see the updated question
Comment: I would guess this is the case as well; MBROs are one of the strangest things out there - you can even use them to intercept the `new` operator, if you can believe that.


Javascript events and recursion issue

Question: I am using jQuery Dialog to load other pages into a dialog on the main page.  The other pages may have anchor tags, and I am using the completed event of the load function to select all of the anchor tags in the div into which the content was loaded.  I then  wire up the anchor tags click event handler so that the content is loaded into the div which is contained on the main page.  This works, however only twice.  When you run the sample code below, Partial1 appears in the dialog.  When I click on the Partial2 link in the dialog, Partial1 is loaded into the dialog, however, this time when I click on the Partial2 link, it loads in the main page.  What am I doing wrong and/or failing to grasp?
Home/Index:
Partial 1

Home/Partial1
This is a sample partial view, which has a link back to Partial2.

Home/Partial2
This is a sample partial view, which has a link back to Partial1.

Answer: The problem is that this line:
$("#dialog").load($(this).attr("href"), adjustNestedAnchors($(this)));

will call adjustNestedAnchors on the link before calling load on the div, so there's nothing that adjusts the nested anchors after the content has been loaded.
Instead, I believe what you want is something like this:
Partial 1

(Disclaimer: not tested.)
Note that I've renamed adjustNestedAnchors to loadDialog, which I think is a more accurate description of its primary function.
Comment: This works great!  Thank you for pointing out my error and the function name suggestion!

Javascript events and recursion issue


iptables port forwarding from public ip but not from 127.0.0.1

Question: i have an issue with my network setting and i need a port forwarding a bit advanced.
I need :
- All packets that arrive on my public_ip on port 54321 to be forward on port 12345 but i don't want any translation when it come from localhost.
Thanks
Comment: add a "! -i lo"  ? From the man : [!] -i, --in-interface name
              Name of an interface via which a packet was received (only for packets entering the INPUT, FORWARD and PREROUTING chains).  When the "!" argument  is  used  before  the
              interface  name, the sense is inverted.  If the interface name ends in a "+", then any interface which begins with this name will match.  If this option is omitted, any
              interface name will match.
Comment: Post what you tried.
Answer: Try using REDIRECT of iptables.
    iptables -t nat -I PREROUTING -d <public ip> -p tcp --dport 54321 -j REDIRECT --to-port 12345

If you need udp, just change the protocol.


How to sort a view so that, say, all the nodes with stock=0 come last, and not sort by stock?

Question: I want to sort an output of a view so that the elements with a filed value of "0" be at the end of the list, but all the others are to be treated equally. In fact, it's an Drupal Commerce site, and I want all products with stock >0 to appear first in the lists, regardless of the stock quantity, so that the unavailable stuff get at the end, but still be in the view (after that, I sort alphabeitcally).
Any ideas how to do that?
That means making the output of a boolean forumla stock=0 the sorting criterion
Answer: You could do this if you use something like the Views php module, because that will allow you to use php code to sort by.  I know that module is currently looking for additional maintainers, I just can't think of an alternative.
Once you've enabled it, and added a php field to sort by, I'd have it return something like:
<code>min([commerce_stock], 1);  // replace [commerce_stock] with whatever your available stock variable is.
</code>
What that code will do is return 1 (the minimum) if you have any stock more than 1, but it will return 0 if the product is all out.
So it will only return 1 (there are items) or 0 (there are none), which is exactly what you want.  Next, you can add a sort by name or whatever you want to sort these two groups further.
Let us know if it works.  I was having a bit of problems getting this rolling, since my stock variable is just returning my product ID, and I'm not sure if I'm just running slightly out-of-date modules or what.  So let us know if a similar approach works when you try it!!
Comment: that sounds promising. I have some trouble identitying the the stock variable used by  Drupal Commerce / DC stock.
I had some big problems in the meantime, regarding the availability of a view where nodes (commerce product displays) are sorted by a filed form an entity tied by a relationship (DC product). If the user category does not have the permission to view the products, it would not see the nodes.
Comment: Searching for the variable, i just a discussion of my the problem I mentioned above: http://drupal.org/node/1276450
Comment: Using just the code @Boriana mentioned did not bring the intended results :-(
Answer: May not be the right answer but it works. On main view (filter stock>0), add a view block, add a filter by stock=0, on main view, insert the new block view as a footer, you can inherit url data on settings.
Make CSS as needed.
Answer: I have not implemented this idea but this might help you.Add a hidden field to your product and give it a text value like A for those on stock and value B for those not in stock. Now u can sort by this field and i guess you might get what you wanted.I guess this might work.


Do these confidence interval plots really have no width?

Question: I see there are some methods of generating 'confidence interval' plots for some types of regression that are pinched in one or more places and the CI width seems to be zero. Can that be right (for finite data sets my expectation is that a CI width is always non zero)?
For example, here's one for hazard ratios from this publication:
. You can find many other example if you perform a google image search
Here's another one from here

which looks very common in many other Gaussian process confidence interval plots.
Are these really upper and lower confidences intervals? What's the cause of the pinching and does the interval width really go to zero?
Suspicious.
Answer: Regression spline example
The first example uses splines, which involve a basis expansion of each covariate. There is generally a basis function in the spline basis that is confounded with the model intercept term. Unless some form of identifiability constraint is imposed on the spline, we could add a constant to the effect of the spline and subtract it from the model intercept and not change the fit of the model. There is then an infinite set of solutions to the model, which isn't helpful. To make progress some constraint is required. Typically that constraint takes the form of a summation to zero constraint; summed over the range of the covariate, the effect, or value, of the spline sums to zero. This has the undesirable effect of forcing the confidence interval to be zero at the point at which the spline cross zero on the y-axis. Note that I suspect in the figure, some transformation of the y-axis has been performed (say by adding the intercept) so that the zero-width point doesn't occur at y = 0.
Clearly this interval is wrong in that it's coverage properties are not 95% around the narrow area. There are solutions to this problem. For the penalized likelihood generalised additive models in the mgcv package for R by Simon Wood and he and his collaborator's research, they show that you can achieve good coverage properties by putting the identifiability constraints on all the other splines except the spline of interest, and then compute the confidence interval. This solves the problem of interval shrinking to zero at y = 0, but otherwise makes little difference to the interval if the spline lies somewhat away from the null space of the spline penalty (i.e. in the default setting of a spline with second order derivative penalty, the null space is a linear function, hence if the spline is somewhat more wiggly than a linear fit). If the fitted spline is close to the penalty null space (i.e. it is close to being linear) the adjustment can widen the intervals markedly.
Gaussian process example
For the second example, I think this is an case where there is no noise or error in the simulated data. Hence the GP is setup to pass through the data points, and, as there is no noise/error the uncertainty about the function at the observed points is zero. It is very common in the GP world to introduce the basic concepts with known example data that have no error.


NPM Request not get html from thai url. (Web Scraping)

Question: This code will not show html in console it show error
var request = require('request');
var thai_url = "http://pantip.com/tag/Honda_(มอเตอร์ไซค์)";

request(thai_url, function (error, response, html) {
        if (!error && response.statusCode === 200) {
            console.log(html);
        } else {
            console.log("Error");
        }
});

But I change thai_url from มอเตอร์ไซค์ to %E0%B8%A1%E0%B8%AD%E0%B9%80%E0%B8%95%E0%B8%AD%E0%B8%A3%E0%B9%8C%E0%B9%84%E0%B8%8B%E0%B8%84%E0%B9%8C
Like This
var request = require('request');

var thai_url = "http://pantip.com/tag/Honda_(%E0%B8%A1%E0%B8%AD%E0%B9%80%E0%B8%95%E0%B8%AD%E0%B8%A3%E0%B9%8C%E0%B9%84%E0%B8%8B%E0%B8%84%E0%B9%8C)";

request(thai_url, function (error, response, html) {
        if (!error && response.statusCode === 200) {
            console.log(html);
        } else {
            console.log("Error");
        }
});

The second code working right. Can I change มอเตอไซค์ to %E0%B8%A1%E0%B8...(more)? Or If it's possible, How am I doing for http://pantip.com/tag/Honda_(มอเตอร์ไซค์) working with npm request ? Thank you for any help.
Answer: First one is working fine. Just log the error instead of "error" string.
Make sure your IDE supports utf character. otherwise on saving it might be changing it. That why you might get error.
Comment: I use Netbean. I change console.log("Error"); to console.log(error); . It show null. I open this file with notepad++ & notepad. it use utf-8 encode for this file.
Comment: Actually i tried with Webstrom and it prints HTML. So no problem in the code.
Answer: Update. Now I can solve this problem by this
var thai_url = encodeURI("http://pantip.com/tag/Honda_(มอเตอร์ไซค์)");

Use encodeURI. http://www.javascripter.net/faq/escape.htm


How i can make a animation transition that start from a button to a new activity?[Android Studio]

Question: Hi I'm Stefan and I'm working on a project now and I would like to introduce the following functionality.The functionality consists of an animated transition that starts from the button that expands into a new activity.
I drew to explain better:

Theoretically I want to make an animated transition from one activity to another in which I want to search (editText) data and go back with the result, this can be found in applications such as Waze, Youtube, etc.
How would you do in Android Studio Java [code]? Thanks in advance.
Answer: In order to add animation between the transition from Activity A to Activity B, you need to follow below steps:
Step 1: Create animations inside directory res/anim folder.
A sample Fade In animation looks like below:
FileName: fade_in.xml
<?xml version="1.0" encoding="utf-8"?>

<set xmlns:android="http://schemas.android.com/apk/res/android">
   <alpha
       android:duration="@android:integer/config_mediumAnimTime"
       android:fromAlpha="0.0"
       android:toAlpha="1.0" />
</set>

Step 2: Add the above animation in your code, while navigating to another activity
startActivity(new Intent(MainActivity.this, NameOfSecondActivity.class));
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);

Please refer to this link, which consist of an already answered question on  various ways to add animation.
Please go through all the answers to get fair understanding of the concept.
Add Animation While Navigating to Another Activity


Javascript Form Submission Not Working. What could it be?

Question: The form won't submit

button {
    right: 10px;
    bottom: 10px;
    position: absolute;
}
p {
    font: 22px Helvetica, Arial, Sans-Serif;
    text-shadow: 0px 1px 1px #040607;
}
q {
    padding-bottom: 15px;
    font: 24px Helvetica Bold, Arial, Sans-Serif;
}
textarea {
    padding: 12px;
    font: 16px Helvetica Bold, Arial, Sans-Serif;

    width: 300px;
    height: 120px;
}
.quote {
    top: 20px;
    margin: auto;
    position: relative;

    width: 436px;
    height: 270px;
}

a {
    color: #FF9C00;
}
button {
    color: #FFFFFF;

    background: #FFAF30;
    box-shadow: inset 0px 4px 8px #FF9C00;

    border-style: solid;
    border-radius: 16px;
    border-color: #FF9C00;

    padding: 3px;
    padding-left: 16px;
    padding-right: 16px;
}
button, a{
    text-align: center;
    letter-spacing: 1px;
    text-decoration: none;
    text-transform: uppercase;
    text-shadow: 1px 1px 1px #040607;

    font-weight: bold;
    font: 22px Monaco, Sans-Serif;
}
fieldset{
    width: 436px;
    height: 270px;
    position: relative;

    line-height: 50px;
    border-radius: 12px;
    border-color: #040607;
    font: 22px Helvetica, Arial, Sans-Serif;
}
footer {
    width: 100%;
    height: 60px;
    padding-top: 35px;

    left: 0px;
    right: 0px;
    bottom: 0px;
    position: fixed;

    text-align: center;
    text-transform: uppercase;
    text-shadow: 0px 0px 10px #0851A8;

    color: #FFFFFF;
    font-weight: bold;
    font: 15px Monaco, Sans-Serif;

    background: #3780D8;
    box-shadow: inset 0px 10px 20px #0851A8;
    opacity: .95;
}
legend{
    font-weight: bold;
    letter-spacing: 2px;
    font: 30px Helvetica Bold, Arial, Sans-Serif;

    color: #3780D8;
    text-align: left;
    text-shadow: 0px 2px 1px #040607;
}
li{
    list-style-type: none;

    line-height: 25px;
    padding-bottom: 1px;

    color: #040607;
    text-shadow: 0px 1px 1px #2E3845;
    font: 22px Helvetica Bold, Arial, Sans-Serif;

    text-align: center;
}
textarea {
    margin: auto;
    position: absolute;
    resize: none;

    width: 270px;
    height: 166px;

    top: 0px;
    left: 0px;
    right: 0px;
    bottom: 0px;

    border-radius: 6px;
    box-shadow: 1px 2px 4px #040607;
}
q {
    display: block;

    font-weight: bold;
    font: 26px Helvetica Bold, Arial, Sans-Serif;

    text-align: center;
    text-decoration: none;

    color: #040607;
    text-shadow: 0px 1px 1px #2E3845;
}
.content {
    top: 0px;
    left: 0px;
    right: 0px;
    bottom: 0px;
    position: fixed;

    width: 100%;
    min-height: 100%;

    background: #FFFFFF;
}
.left {
    left: 5%;
    top: 120px;
    float: left;
    margin: auto;
    position: relative;

    width: 40%;
}
.right {
    right: 5%;
    top: 120px;
    float: right;
    margin: auto;
    position: relative;

    width: 40%;
}
.italic {
    font-style: italic;
}
<!DOCTYPE html>

<meta charset="UTF-8">
<title>SMPentest Challenge</title>
<link rel="stylesheet" href="/static/css/final.css" />
<link rel="stylesheet" href="/static/css/style.css" />

            <q class="normal">Submit the form.</q>
            <q class="italic">Test</q>
            <q class="normal">Test</q>
            <q class="italic">Test</q>
            <q class="normal">Test</q>

        <form method="POST" onsubmit="return validateForm();" action="#">
            <fieldset>
                <legend>Contact Info</legend>

                        name
                        <input name="name" id="name" type="text" size="20" maxlength="30" required autocomplete="off" placeholder="Required"/>

                        email
                        <input name="email" id="email" type="text" size="20" maxlength="2" required autocomplete="off" placeholder="Required"/>

Preferred Choice:

                    <input name="summer" id="summer" type="checkbox"/>
                    #1

                    <input name="winter" id="winter" type="checkbox"/>
                    #2

                    <input name="fall" id="fall" type="checkbox"/>
                    #3

                <input name="i_know" type=hidden value="KungFu!"/>
                <button name="submit" type="submit">Submit</button>
            </fieldset>
        </form>

Test Page

Comment: Any errors in console? Seems to be working for me.
Comment: I get an alert that says it's successful. What else are you expecting? If you mean that the form isn't being processed, then why are you using `action="#"`?
Comment: You might want to read [*How to create a **minimal**, complete and verifiable example*](http://stackoverflow.com/help/mcve). Often the process of creating the example will highlight your issue so you don't need to ask.
Comment: It works here: https://jsfiddle.net/498xmoxq/
Answer: The action field should be set to where you want the form to be submitted to. It is currently set to nothing.
    action="#"

I would also advise against the use of inline Javascript, even for such a small function.
Comment: What is wrong with inline Javascript?, At least explain why you would recommend against it, rather than basing it on your recomendation with no factual evidence as to why?
Comment: Its not wrong for a testcase ... but to structre your applications its better to have a clean named files instaed of to much inline code  ..  .. also for 'dry' code ... so you can reuse your functions also in other html files and you can look into your 'js' folder into your 'formHandle.js' file into your validateXyForm function if you need to make changes


Salesforce Activities - Task and Events - Reporting

Question: When building a report on Activities (Tasks and Events), I had a Subject of Introduction.
I know that I have hundreds, but when I create a Report, it is only returning 8.
I removed all other fields from the report, made sure the filters were All Activities.  Date: All Time, and all other filters were set to show me all data, not just my data.
Any advice on what I might be missing in my report?
Thanks,
Jason
Created the report using Lighting and Searched Activities, then selected Tasks and Events.
Expecting to see more than 8 items with the Subject of Introduction.
Answer: You may be a victim of archived activities. Can you see these Tasks/Events all right on the record itself just like that or are they "below the fold", you need to click "view all"?
https://help.salesforce.com/s/articleView?id=sf.activities_archived.htm&type=5

Events that ended more than 365 days ago,
Closed tasks due more than 365 days ago ,
Closed tasks created more than 365 days ago (if they have no due date)

If that's the case - you can contact SF support to increase the limit: https://help.salesforce.com/s/articleView?id=000385669&type=1
If you're after an one-off export - maybe API access will be faster than support route, check https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_guidelines_archive.htm and https://help.salesforce.com/s/articleView?id=000385173&type=1 out.


Inequality in non-decreasing sequence

Question: Let $a, b$ be two sequences of real numbers such that $a_1 \le a_2 \le \dots \le a_n$ and $b_1 \le b_2 \le \dots \le b_n$. Prove (or disprove) that
$$\left(\frac{1}{n}\sum_{i=1}^{n}{a_i}\right)\left(\frac{1}{n}\sum_{i=1}^{n}{b_i}\right) \le \left(\frac{1}{n}\sum_{i=1}^{n}{a_ib_i}\right)$$
Now obviously, I have no idea from where to even start attacking this monster. I tried Cauchy-Schwarz (square roots of $a_i$ and $b_i$), and by using AM-GM on the left side, but realized that they are not necessarily non-negative.
Comment: This is Chebyshev's inequality. Hint: use rearrangement to prove.
Answer: It is a standard Inequality and there are numerous proofs if I am not mistaken. I'll give you two options. One I'll give you a hint and you can pursue a solution on your own which will help you. But if you have a million exercises following this and using this inequality then you can choose to just refer this Wikipedia page which contains a simple proof.
Hint: Consider the sum $$ \sum_{i = 1}^n \sum_{j = 1}^n(a_i - a_j)(b_i - b_j) $$
Since we know that $\{a_k\}$ and $\{b_k\}$ are monotonically increasing and since either $i \le j$ or $ i \gt j$ the signs of the two facotrs $ (a_i - a_j) $ and $ (b_i - b_j)$ will always be the same and hence the iterated sum will be non-negative. Now you have an inequality. Expand and continue.
Comment: Splendid. I am absolutely embarrassed for being unable to get any results from google on this inequality. Thanks!

Inequality in non-decreasing sequence


Save tags in parent and children of vocabulary with shs module

Question: How can I save my tags in parent and children of vocabulary with the shs module?
When I save my tag in children with the shs module, I want to show my content in parent and children path.
Answer: on taxonomy/term/% view, enter contextual filter

"Has taxonomy term ID (with depth)"

and change the depth settings to -1 and children view will take parent tag nodes too.


PHP Sessions variables

Question: I have 3 pages, one HTML page (session.html) and 2 PHP pages (session.php & sessiona.php). The html page has a form on it with only 2 fields, one being a text box (customername) and other being a selection list (hobby). The action on the HTML page is to send to session.php in which i store the variables in this manner :

<?php
session_start();

$_session['name'] = $_POST['customername'];
$_session['hobby'] = $_POST['hobby'];

$name = $_session['name'];
$hobby = $_session['hobby'];

?>

Sessiona

The point of session.php is only to store the variables and only display a link to sessiona.php which i want to retrieve the stored variables from sesssion.php and diplay them. Is there a way to do this?
Comment: You cannot have *any* output before `session_start()` or it won't work and will generate an error.
Comment: one way is to use cookies.
Comment: It's not $_session[] it's $_SESSION[]
Comment: Excuse me, but `$_session` is the same as `$_SESSION`?
Comment: @sgroves : storing data in cookies is a bad habit. It's better to store an ID (such as SESSION ids).
Comment: `echo $_SESSION['name']`, `echo $_SESSION['hobby']`
Comment: @Dawson i have tried that but nothing was displayed
Comment: @mimipc i have changed all my $_session to $_SESSION, thank you for the tip.
Answer: It should suffice to set
session_start();

in your sessiona.php where you can get the variables in the manner you suggested:
$name = $_SESSION['name'];
$hobby = $_SESSION['hobby'];

Answer: Any page to start the session variable's creation
<?php session_start();
$_SESSION['name'] = $_POST['customername'];
$_SESSION['hobby'] = $_POST['hobby'];
?>
...

Any page to retrieve that session data after it's created
<?php
if(isset($_SESSION['name'])) { $name = $_SESSION['name'] }
if(isset($_SESSION['hobby'])) { $hobby = $_SESSION['hobby'] }
?>
...<?php echo($name) ?>...or...<?php echo($_SESSION['name'])?>...

Note: you will want to check for that session variable to ensure you don't throw an error on echo. isset(), !empty(), etc.

PHP Sessions variables


Using Gradle to publish jars to MavenLocal

Question: I'm using Gradle to manage the build of a product using multiple eclipse projects.
Several of those projects use jar files that are not available from a central repository (like MavenCentral).
I'd like to have an eclipse project that I just place those jars into, and a build.gradle that will place those jar files into mavenLocal using the groupId, artifactId and version that I specify.
This way I can just add mavenLocal() to other projects and specify the dependency.
I have the following build.gradle:

apply plugin: 'maven-publish'

publishing {
    publications {
        maven(MavenPublication) {
            groupId 'myGroupId'
            artifactId 'myArtifact'
            version '1.2.3'
            from  <how to reference jar>
        }
    }
}

I've tried file('myJar.jar'), but that isn't accepted.  It appears that Gradle wants an artifact for the from value, but I can't seem to find how to specify a prebuilt jar file as that artifact.
Seems like it ought to be pretty simple, but I'm not finding it.
Answer: Currently, 'from' can only accept components.java and components.web. To include a jar, use 'artifact', for example:
publishing {
    publications {
        maven(MavenPublication) {
            groupId 'myGroupId'
            artifactId 'myArtifact'
            version '1.2.3'
            artifact <path to file>
        }
    }
}

'artifact' can also accept output of archive tasks:
publishing {
        publications {
            maven(MavenPublication) {
                groupId 'myGroupId'
                artifactId 'myArtifact'
                version '1.2.3'
                artifact getlibrary
            }
        }
    }

task getlibrary(type:Jar){
    from <directory>
    classifier='lib'
}

Comment: Thanks!  I didn't see anything that indicated you could specify an artifact as a file location.  Works like a charm.


Como somar um valor num array de objetos com reduce

Question: Eu tenho um array de objetos que segue esse formato:
[
  {
    name: 'Batata',
    points: 23,
  },
  {
    name: 'Pizza',
    points: 50,
  },
  {
    name: 'Tacos',
    points: 60,
  },
];

Eu quero percorrer esse array e obter a soma de todos os points em cada item do vetor. Como eu faço isso usando o reduce do Javascript??
Answer: Assim:
array.reduce((a, b) => a + b.points, 0)

Basicamente, o que acontece é que a função que você passa por parâmetro para o reduce (a + b.points) será executada para cada item do array.
O parâmetro a receberá o valor do resultado da última chamada (se for a primeira chamada ele receberá o valor do segundo parâmetro da função reduce - aquele 0).
O parâmetro b receberá cada item do array.
Algo assim:
1. Item do Array
a = 0
b = { name: 'Batata', points: 23 }
Retorno da função: 0 + 23

2. Item do array
a = 23
b = { name: 'Pizza', points: 50 }
Retorno da função: 23 + 50

3º Item do array
a = 73
b = { name: 'Tacos', points: 60 }
Retorno da função: 73 + 60

A função que você
Veja funcionando:

var array = [
  {
    name: 'Batata',
    points: 23,
  },
  {
    name: 'Pizza',
    points: 50,
  },
  {
    name: 'Tacos',
    points: 60,
  },
];

var soma = array.reduce((a, b) => a + b.points, 0)
console.log(soma)
Answer: Dessa forma retornaria um objeto com a soma:

var items = [
  {
    name: 'Batata',
    points: 23,
  },
  {
    name: 'Pizza',
    points: 50,
  },
  {
    name: 'Tacos',
    points: 60,
  },
];
const reducer = (a, b) => {
  return a.points += b.points, a;
}
const soma = items.reduce(reducer, {points: 0});

console.log(soma);

Outra forma utilizado map para criar somente um array simples com os valores e utilizado reduce para somar:

var items = [
  {
    name: 'Batata',
    points: 23,
  },
  {
    name: 'Pizza',
    points: 50,
  },
  {
    name: 'Tacos',
    points: 60,
  },
];

const i = items
  .map(x => x.points)
  .reduce((a, b) => a + b, 0);
console.log(i);


Correct way to play Mozart K331 Trio Measure 11?

Question: I just started to learn the Trio movement of Mozart's K331. It sounds really nice but is the hardest movement of this piece for me. (By the way, why are the Menuetto and the Trio often counted together as one movement, sometimes just "Menuetto"?).
For the measure 11 of the Trio, my understanding is, E, A, G# with the left-stems are each 1/4 beat and should be held longer while E2-A, C#2-E, B-E, each note being 1/8 beat, are being played, respectively, am I right?
I'm asking because in the following two linked videos, both pianists released the 1/4 beat E, A, G# while holding the E2, C#2, B which are supposed to be only 1/8 beat. Are they both wrong or did I miss something?

Video 1: @1:32

Video 2: @6:10
Comment: [What is the "Trio" in a march?](https://music.stackexchange.com/a/90840/70803) should answer your question about the Menuetto/Trio.
Comment: In case it doesn't, the answer is that the Trio is part of the Minuet.
Answer: From measures 1 to the first beat (A) of measure 14 we hear 2 voices, a soprano+alto duet.  If you play JUST the 2 voices to simulate singing, the phrases in each voice need to be connected as an implicit legato; sometimes it's quarter note duration (like in measures 1, 3, 5), sometimes it's 8th note duration (like in measures 2, 4, 6), but always together in duration separated by a 3rd or 6th interval.
The rest are fillers for harmonic, rhythmic movement, flourish, and cadence functions.  For example:

the repeated 8th notes A in measures 1-2 are fillers for a sense of rhythmic movement
the doubling of the soprano voice in the upper register (ex. where the left hand crosses over in measures 4-5 including the cute grace notes in measure 9) are flourishes to add character
the notes in the bass clef are mostly cadence highlights (such as measures 3-4, 7-8, 11).

Mozart is creative in that in measure 10 he transposed the alto voice to the lower register while the usual 8th note rhythmic filler stops into the half note E to let the soprano and Alto have the focus as well as preparing us for the cadence in measure 11.
Within this passage context, it's then clear that we have to analyze measure 11 as follows:

First voice (implicit quarter duration): E2, C#2, B which resolves to A in the next measure
Second voice (implicit quarter duration): C# (in bass clef), A1, G#1 which also resolves to A in the next measure
Cadence highlight: E in beats 2 and 3 in the bass clef, resolving to A in the next measure
Rhythmic filler (off-beat 8th notes): A1, E1, E1

I think in measure 11 the alto is notated in quarter notes because the voices at this point have quarter duration, and Mozart (or the editor) helps us identify A1 and G#1 as the 2nd voice continuing the first beat C# in the bass clef.  Since the character of the 2 voices in this passage moves together in duration as well as in melodic contour, the alto needs to be heard with the same duration as the soprano.  Although in the notation there is a common beam for the 8th notes, it's very important to identify and to play the off-beat 8th notes A1, E1, and E1 as filler, not as part of the soprano.
A side note about the primacy of highlighting voices vs. actual notation
Highlighting the voices is more important than how long you actually hold the notes.  In the first video we can hear a good rendition of the 2 voices performed according to the analysis above. Even though in measure 11 she plays the 2 voices about 1/8 duration, we hear it as a connected phrase (each note 1/4 duration).  It's the effect that counts, after taking into account the room's acoustics and the decay curve of a note of a specific piano (remember, piano is by nature a percussive instrument), so pianists need to constantly adjust the actual length of holding the notes through feedback mechanism from what we hear.
This is especially true in Mozart's repeated notes (such as the left hand in the first few measures in Sonata Facile) where despite all are 8th notes, no artist would play those notes exactly the same duration. Otherwise, it will sound robotic as the "Play" button in MuseScore will demonstrate.  I bet you that the MIDI duration values of Ms. Mitsuko Uchida's playing it will be very different for each note since she's holding the Cs and Ds much longer than the other 8th notes to highlight the bass line.  The same goes for the right hand scale runs in measures 5 to 10 as Lang lang demonstrates various options we can play it.
Comment: @GrandAdagio It's possible, but that's where interpretation comes in after considering many factors: notation convention and how Mozart would do it (compared to other composers from different period), the function of that voice line, and thirdly how it should be rendered because after all, what matters is beautiful sounding piece that preserves all the nuances the composer would have had in his mind.
Comment: @GrandAdagio Also to consider is that [Mozart's fortepiano](https://www.classicfm.com/composers/mozart/mozart-piano/) has a lot shorter decay than a 9' Steinway concert grand.  So he MAY played it full duration quarter notes and he MAY meant that for fortepiano players in his time.   But unless we play that in a fortepiano, we have to adjust the way we play to modern piano, and make MORE beautiful sound using the new potentialities.  This is especially true when playing Bach's harpsichord pieces.
Comment: @GrandAdagio Here's Mozart's [Sonata in A K.331 played on Mozart era instrument](https://www.youtube.com/watch?v=p3MKwIHdQbk) (fortepiano made by Silbermann) by fortepianist Mako Kodama, the Trio passage starts at minute 14:16, measure 11 at 14:30.  Since fortepiano decays a lot faster and has less dynamic & tonal range, you can see how she has to play a lot more legato, hold the notes longer in general and fingers keeping close to the keys (like an organist).  I cannot really tell how long she holds E2, C#2, and B, but I can clearly hear those are connected in a phrase as a subsidiary voice.
Comment: @GrandAdagio After I played the passage at the piano myself, it becomes clear that the passsage from the Trio is a duet.  So I tweaked my answer accordingly.
Comment: Thanks for the explanation. So what if the score were written to reflect how it's played, i.e., making the E2, C#2, B quarter notes, and the E, A, G# eighth notes,  maybe also changing the stem directions accordingly?
Comment: Thank you so much for the answers, and for that Mako Kodama video.  I did find the fingers feel more awkward if played in exactly the way it's written.
Answer: In a comment on another answer, you ask

what if the score were written to reflect how it's played

Mozart could not have written the score to reflect how these two performers play the piece.
In the question, you ask

Are [these performers] both wrong?

There's no "right" or "wrong" here.  The notation is the composer's means to communicate with the performer.  These performers are playing instruments that use technology developed decades after Mozart.  Some interpretation is necessary.
Piano scores do not generally dictate such minutiae as how much space to place between notes.  You can always add a little more or less space; it is one of the parameters that pianists use to shape the phrasing.  If there's some space between the notes then you can use the same finger on both.  If you have to use the same finger on both, well, then, that will affect your phrasing choices.
If adding space between these notes bothers you, then by all means see if you can work out a way of playing the A with the 3rd finger and the G♯ with the second.  Mozart may indeed have intended that.  But the Firefly Piano video is elegant and graceful, and the alto voice has a definite presence and identity as a distinct voice; it's really a fine performance, certainly not "wrong."  If you can learn how to achieve all of those things while also connecting the alto voice in a legato phrase, then by all means, go for it.
But keep in mind:

Daniel Gottlob Türk writing in his Clavierschule (1789) says that:

"...when notes are to be played in the usual manner, that is to say, neither staccato nor legato, the finger should be raised from the key a little earlier than the value of the note requires."

Source: https://www.dolmetsch.com/musictheory21.htm
I believe I've seen that an earlier treatise recommend holding "normal" notes for half their nominal value, as many modern writers recommend for staccato, but I can't find the reference just now.  Anyway, Türk is contemporary with Mozart, so more relevant.
Comment: Thanks, points well taken. Now I begin to understand why I can't get that nice melody out as the Firefly pianist does (not just in this measure).
Answer: "What you're missing" is that the E-C#-B-A constitutes the melody, which is made clear by its immediate repetition an octave higher. This is implied earlier, in measures 3 and 4, when the upper notes of the "detached" eighth-note melody are repeat at the octave in quarter notes.
Comment: Could you please extend your answer and explain, why the fact that these notes constitute the melody implies that they (and the the accompanying notes) are not played as long as written in the score?
Comment: @Arsak it's always permissible to insert spaces between notes in the name of phrasing.  If it weren't, there'd be no need for legato markings.  In fact, earlier in the 18th century you have treatises saying that by default every note should be held for half its nominal value.


Why does the submit button display my php file?

Question: I need to setup this website to A(save the input to a dataset) and B(display the immediate input to the same page. I got it all set up, but everytime I click submit, my page displays my .php file. How do I fix this?
    <!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Newsletter Signup</title>
    <link rel="stylesheet" type="text/css" href="style.css" />

        <form id="Signup" action="membersList.php" method='post'>

Sign-Up

            Name: <input type="text" name="name" id="name">

            E-mail: <input type="text" name="email" id="email">

             <input type="submit" name="submit" onclick="display()" value="submit"/>

        </form>

Welcome

my php file
<?php
if(isset($_POST['submit']))
{
    $xml = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\" ?><member></member>");

    $xml->addChild('name', $_POST['name']);
    $xml->addChild('email', $_POST['email']);

    $asXML = $xml->asXML();
    $file = fopen("data.xml","w+");
    fwrite($file,$asXML);
    fclose($file);
    print_r(error_get_last());

    if(file_exists('./data.xml'))
    {
        $myXML = file_get_contents('./data.xml');
        $xml = new SimpleXMLElement($myXML);
        $xmlpretty = $xml->asXML();

        // pretty print the XML in browser
        header('content-type: text/xml');
        echo $xmlpretty;
    }

}
?>

Any sort of advice to improve the code will also be appreciated.
Comment: Is PHP installed on your server?
Comment: What server are you running this on?  It sounds like it isn't setup to correctly process .php files.
Comment: if you see the literal PHP code on the screen, then it means your webserver isn't setup to execute PHP properly. Either that or you didn't access it correctly (e.g. you used `file://` or something to load the HTML page). If the PHP is executing correctly, you should see some XML instead.
Answer: If the code of the PHP file is shown, normally is because your web server is not processing the PHP code. It interprets it as text.
Try creating a info.php file in the root of your web directory, with this content and check if is correctly rendered:
<?php phpinfo(); ?>

Then call it with http://myserver/info.php It should display a long page with information about your php environment.


Pushforward and sheaf-hom

Question: If $S$ is a surface over the complex numbers $\mathbb{C}$, and $C$ is a curve in $S$, and $i:C\longrightarrow S$ is the inclusion morphism. If $A$ is a line bundle over $C$, then is it true that $Hom_{\mathcal{O}_S}(i_*A,i_*A)=Hom_{\mathcal{O}_C}(A,A)$?
Clearly they are both supported on $C$. But are the sheaves the same too?
Answer: If your curve is a local complete intersection, then one can show in general:
Assume $Z$ is a local complete intersection of codimension $m$ in an algebraic variety $Y$. Let $F$ and $G$ be coherent sheaves on $Z$ and assume that $F$ is locally free, then one has:

$\mathcal{E}xt^k(i_{*}F,i_{*}G)=i_{*}(\Lambda^k N_{Z/Y}\otimes F^{\vee}\otimes G)$ for $0\leq k \leq m$
$\mathcal{E}xt^k(i_{*}F,i_{*}G)=0$ otherwise

Here $N_{Z/Y}$ is the normal bundle of $Z$ in $Y$.

Pushforward and sheaf-hom


The best way to render field content without any  wrapper

Question: I have a content type with filefield "ttf" wich I want to render as Url to the file .
with this url to file I want to create an link :
<a href="<?php print render($content["field_ttf"]); ?>">Download

But this output a wrapper around the url
I know that there is a function field_view_field() that do the Job but I'm looking for a better solution
Answer: Look in the core modules/field/theme/ folder, copy the field.tpl.php file to your theme then rename it to whatever the system name for the field is. i.e field--body.tpl.php
Edit the file to remove the surrounding divs and anything else you don't want. All you actually need is the foreach and the render($item);
Don't forget to clear the cache so it will pick up the new file, hope that helps.
Answer: You can do this with the combination of 2 contrib modules :

No field markup which allows you to remove all the div wrapping
the data.
Image URL formatter which will render only the url
(should work with files as well).
Answer: The proper solution for controlling rendering of a field, is a formatter. You can change the formatter and it's settings under the content types "Display settings". I believe file fields come with a formatter for rendering as direct links.
It looks to me like you are attempting to do this to late in the page cycle, but if you need to hack it together, provide some more context on where you are doing the rendering, and I'll try to be more specific.
Comment: unfortunately the url formatter provide wrappers by default and the link as a text. I'm doing this rendering in a note.tpl.php file


Question about basketball traveling

Question: I have a question about the play at 6:46 when Pippen seems to do a little pass to himself:
https://www.youtube.com/watch?v=R_tz29TWNdM
Here does it again here at 3:23,
https://www.youtube.com/watch?v=RWqspeetGPc
Isn't this traveling? If not, can someone clarify for me traveling rules and how this doesn't break them? Thanks.
Answer: The basic answer is that he only takes two steps between him stoping his dribble and him taking a layup. Throwing the ball up and catching it  is only a problem if you travel and Scottie didn't travel.

Question about basketball traveling


dot product equal for all $y$, then the two functions are equal

Question: Let's say we have two functions : $f, g : A \rightarrow B$, where $A, B$ are finite vector spaces with scalar product $ \langle , \rangle$ (so $A, B$ are euclidian spaces), and such that $\forall x$ :
$$\langle f(x), y \rangle = \langle g(x), y \rangle$$
Then do we have : $f(x) = g(x)$, $\forall  x \in A$ ?
According to me, there is a link with Riesz theorem but I am not sure, also if $f, g$ are not continuous I don't think this is in true.
On the other hand, if instead of $\forall x$, if we have $\forall x, y \in A$, then it might be true, but I am not sure. Any ideas ?
Answer: This is equivalent to asking if $f \equiv 0$ whenever $\langle\ f(x),y \rangle=0$, $\forall x \in A$. This is false if, for example, $y$ is orthogonal to the subspace spanned by $\{f(x) \ : \  x \in X\}$.
Now if you include the condition $\forall y \in B$, then it is true. Just take $y=f(x)$ to conclude that $\langle\ f(x),f(x) \rangle=0 \, \ \forall x $ and thus $f \equiv 0$.
Comment: Ok, also if $f, g$ aren't linear maps then it's also false right ?
Comment: Exactly. You could take $y=0$ for example or any $y$ orthogonal to $\{f(x) \ : \ x \in X \}$ as long as this set doesn't span $B$.


Best machine learning approach for recommendation engine?

Question: I am given a dataset where there are people profiles and the types of beer each person likes, given in a list. What is the best way to find relevant beers given a specific beer based on this data?
edit: I researched my question more and found that it is in the realm of collaborative filtering.
From my research, the examples that are currently given involve ratings or other metrics, but my dataset is very minimal. It includes the beers bought by a person. Therefore The only data we have is weather or not a person bought a specific beer.
The format is as such:
Person | Beers bought
1         A,B,C,R,G,S
2         A,F,U,I,T
3         B,C
4         J,R

From what I think, it appears to be an implicit item-based collaborative filter. My question, is, given one Beer say A, give the best recommendation of 3 beers.
My current attempt is given 1 beer, find all the users that bought it, then look at all the beers that they bought and find the 3 most common ones.  I believe that that is too naive so what other methods are possible? I am thinking of having a weighting function but I am not sure how to go about it.
Answer: I would generally consider this an over-broad question, but here's a tutorial specifically on building a beer recommendation engine in R based on a dataset of user reviews from BeerAdvocate.com: http://blog.yhathq.com/posts/recommender-system-in-r.html
Comment: Try a NN approach to collaborative filtering. Consider adding weight to the beers around which users cluster. Building a recommendation system is an art, and your dataset only has one variable. You're going to need to play around with this and see what works best with your data.
Comment: I actually looked at that dataset before but that example involved characteristics of the beer such as flavor. My dataset is solely the sets of beers that specific users bought. A lot of examples online involve more complexity, however I have a minimalist dataset.
Answer: One way is to find beers 'associated' with a given beer A, in the sense: "Users who bought beer A also bought beer X." A similarity measure that directly gives this association is: For a beer X, (Users who bought X and A)/(Users who bought A). Beers which have the highest similarity with A can be recommended to users who bought A.
This is only one possible nearest-neighbour approach, and as @david-marx mentioned, you have to try out a few options on your data.
Answer: Here is a quick example of how to use SVD in R for recommendations.
First create a 0/1 matrix indicating which person drinks which beer.
Next, use SVD to decompose the matrix, and recreate it with the K most significant factors.
Next, find the combinations in which the person did not drink the beer - but should have, using the model.
Beers= data.frame(Client=c(1,1,1,1,1,1,2,2,2,2,2,3,3,4,4),
              Beer=c("A","B","C","R","G","S","A","F","U","I","T","B","C","J","R"),
              idx=c(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1))

Beers_tbl = dcast(Beers, Client ~ Beer, value.var="idx", fun.aggregate=sum)
rownames(Beers_tbl)=Beers_tbl[,1]
Beers_tbl=Beers_tbl[,-1]

my_svd=svd(Beers_tbl)
K=2
Beers_tbl_pred=my_svd$u[,1:K] %*% diag(my_svd$d[1:K]) %*% t(my_svd$v[,1:K])

Recommend=apply(Beers_tbl_pred-Beers_tbl,2,function(x) {ifelse(x>0.2,1,0)})*(1-Beers_tbl)

Answer: Could you build a recommender system with the frequency of purchase as the value? Is it possible to derive frequency of purchase?
You could build an item-based model with user_name, beer_id, frequency_of_purchase (the total count of their purchases). You would take the matrix of users/beers/frequency, call it Matrix  A, and the matrix of similarity between beers in Matrix B, and multiply the two matrices to get the resulting recommendation in matrix C.
You could also use association rules to determine the probability of someone buying a beer, if they've bought a set of other beers,
beer1, beer2, beer3 --> beer6.
With association rules, you could create a binary matrix that contains all of the users and all of the possible beers with a 0/1 for each of the possible beers, depending on whether a user has purchased a beer or not. There is a fair amount of literature on this on the web, including a decent package in R (arules).
Answer: You can build the recommendation system based on binary data of purchase / non-purchase and experiment with different approaches (content - or user -based). Essentially, you start with the matrix / data frame that lists users in rows and products (beer brands) in columns, where 1's indicate purchase and 0's no purchase and you take it from there.
What language are you using? Here are some useful tutorials in R/ Python to start with:
MovieLense Recommendation System in R
Collaborative Filtering with R
Collaborative Filtering with Python
Answer: It has been over 4 years since you asked this question and probably you have conquered this problem efficiently. However, being a data mining student currently, I would still love to answer this question.
If your requirement is bound to recommendation engine based on a training data set, you could go for a simpler approach. FP Growth from frequent-pattern tree (FP-tree), will mine frequent data items and make your engine faster and more efficient.
Also, as I mentioned, I am also a student. If there is a better approach than mine, please let me know! :)
Comment: Could you make your answer clearer by explaining what you mean by FP Growth?
Comment: @mkt Frequent Pattern Growth (FP-Growth) is an algorithm which helps in mining frequent data items. I attached a link in the text which explains the algorithm. You can also read many articles and research on the algorithm from Google.


Weak Reference and Soft Reference

Question: Weak references allows GC to collect the references in next GC Cycle whereas Soft Reference will keep the reference until memory is full and before throwing out of memory error,it will remove soft references.
Where we will be using these references?
Which reference will be best for implementing caching?
For eg:If I use soft reference for caching,then it will be cleared when memory is full.
But lets suppose,I have fetched some database details and put that in memory and cached that detail in soft reference and now if i removed some key value from memory,it will still be there in cache.Do we need to use weak reference in this case?How the decision should be made.
Comment: "now if i removed some key value from memory,it will still be there in cache" Why do you say that?  Most caching frameworks that support weak/soft references will take care of that for you.
Comment: Have you looked at the many, many free solutions out there which do this sort of caching already?  How will your solution be better/different?
Answer: Soft References are used for caching in most cases. You want to keep data in  RAM as long as it possible, but it is better to purge cache than die with OOM.
Weak references can be used (for example) to keep extra info about your class. You have class User and you want to store some additional info, which should be deleted at the moment when user is deleted (you do not want to do it manually since it is bolierplate code). So, you use WeakHashMap using User as key, and when there is no reference to user, it is deleted from this map as well.
By the way: in languages with references counting weak references are used to prevent reference cycles, but java GC removes "islands of isolation", so this usage of weak reference is not for java.
Answer:
Weak references allows GC to collect the references in next GC Cycle whereas Soft Reference will keep the reference until memory is full and before throwing out of memory error,it will remove soft references.

You are reading more into the docs than they actually say.  All objects that are softly reachable (which precludes them being strongly reachable) will be cleaned up and released before the VM throws an OutOfMemoryError, but the VM is in no way required to preserve them past the point when they are initially determined to be softly reachable.  The docs do not forbid that they be reclaimed in the same GC cycle in which they are found to be softly reachable.
Generally speaking, however, you can suppose that the GC will prefer to process phantom reachable and weakly reachable objects first.

Where we will be using these references? Which reference will be best for implementing caching?

The docs say this:

Soft references are for implementing memory-sensitive caches, weak references are for implementing canonicalizing mappings that do not prevent their keys (or values) from being reclaimed, and phantom references are for scheduling pre-mortem cleanup actions in a more flexible way than is possible with the Java finalization mechanism.

You go on to ask:

For eg:If I use soft reference for caching,then it will be cleared when memory is full. But lets suppose,I have fetched some database details and put that in memory and cached that detail in soft reference and now if i removed some key value from memory,it will still be there in cache.Do we need to use weak reference in this case?How the decision should be made.

If you want to build a cache that can discard entries whose keys cease to be strongly reachable (which may mean that those entries can no longer be retrieved), that is squarely in the center of the intended purpose for weak references.  The cache internally holds only a weak reference to the key of each entry, and it registers those references with a ReferenceQueue that lets it know when they should be discarded.  This is precisely how WeakHashMap works.
If you want to build a cache that can respond to high memory demand by discarding entries, then that is the intended purpose of soft references (to the values); such a cache would work similarly to WeakHashMap, but with use of soft references to the values instead of weak references to the keys.  The two could be combined, of course.
Note, by the way, that Reference objects become relevant to GC only when their referents cease to be strongly reachable.  In particular, having a SoftReference to an object does not in itself guarantee that that object will ever be reclaimed, no matter what the demand is on memory.  No object that is strongly reachable is ever eligible for finalization or reclamation.
Answer: If you are implementing your own cache, use a Soft Reference.
I once maintained a legacy system that used a cache of Weak References to store large objects that were very expensive to create.  Almost every time a thread tried to fetch an object from that cache, it had already been GC'ed so the objects had to be expensively recreated a lot! It was practically like the cache wasn't there.

But lets suppose,I have fetched some database details and put that in memory and cached that detail in soft reference and now if i removed some key value from memory,it will still be there in cache.  Do we need to use weak reference in this case?How the decision should be made.

I'm not sure I understand your question.  When the original "hard" reference to those details is GC'ed it can still be in the cache of soft references.  If you remove the item from the cache then there are no more references to the details at all so it will be GC'ed next time no matter what kind of reference used to point to it.
There are very few times when a WeakReference is useful. See Weak references - how useful are they? for some examples
Answer:
Which reference will be best for implementing caching?

for caching use SoftReference class, the whole point of caching things is to keep it prepared for quick use - if memory is available. So when there is little memory ten its ok to flush your cache.
WeakReference are perfect for avoiding reference leaks, it happens when you have some static object or thread which keeps reference to object whose lifetime is shorter that this object/thread. I use a lot of WeakReference - s in android development, especially with AsyncTask's whose lifetime is often longer than of Activity-s lifetime which created them.

... Do we need to use weak reference in this case?

once you remove such entry from your cache collection it will be garbage collected, so no need for WeakReference.
I have never used SoftReferences - but thats because I mostly code under android platform, and acording to its docs http://developer.android.com/reference/java/lang/ref/SoftReference.html, they are useless for caching - at least under this platform.

Weak Reference and Soft Reference


Efficient way to compute the ninth order Maclaurin polynomial of $\sin(\arctan(x^2))$

Question: Substitution is a favourite of mine but this really gives me an headache. We had a discussion in class about the Maclaurin evaluation up to degree 9 on this function:
$$f(x) = \sin(\arctan(x^2))$$
There are endless possibilities. What would be your best shot?
Comment: What's the actual question?
Comment: Solve what? I don't see what the problem is.
Comment: How would you solve it?
Comment: The problem is to find the Maclaurin Series Expansion to degree 9 for the function. Sorry if I'm not very good at explaining.
Comment: Edited: grade $\ne $ degree.
Comment: @Terry  If you are ok, you can accept the answer and set as solved. Thanks!
Comment: @gimusi Sure! If possible, can you show the first step of the composition?
Comment: @Terry I've just plugged into the expansion for $\sin t$ for $t\to0$ the expansion for $\arctan x^2\to0$
Comment: @Terry I've edited the answer in order to be more clear
Answer: Hint: $$\sin(\arctan(x^2))=\frac{x^2}{\sqrt{1+x^4}},$$ using elementary trigonometric identities. Then use the binomial expansion
$$(1+x^4)^{-1/2}=1+\binom{-1/2}{1}x^4+\binom{-1/2}{2}x^8+\ldots$$
Comment: How would you decide to continue? I get stuck in long-step evaluations for degree 9.
Answer: You need simply to compose the expansions
$$\arctan x = x -\frac{x^3}{3}+o(x^{\frac92})$$
$$\arctan x^2 =x^2 -\frac{x^6}{3}+o(x^9)$$
$$\sin t = t -\frac{t^3}{6}+o(t^3)$$
Thus for $t= \arctan x^2 =x^2 -\frac{x^6}{3}+o(x^9)$
$$\sin (\arctan x^2) = x^2 -\frac{x^6}{3}-\frac16\left(x^2 -\frac{x^6}{3}\right)^3+o(x^9)=\\=x^2 -\frac{x^6}{3}-\frac{x^6}{6}+o(x^9)=x^2 -\frac{x^6}{2}+o(x^9)$$
Comment: @gimusi I think you have a typo in your second last line; you've got $\sin\arctan x$ on the LHS but $\sin\arctan x^2$ on the RHS
Comment: ops yes of course, just a typo thanks!
Comment: Interesting, thank you. Will bring this to my friends.


proving a statement on ranges of linear operators

Question: Given a linear operator $K$ on $W,$ and that for a non-negative n range $K^n = $ range $K^{n+1}$ how do I prove that range $K^p = $ range $K^n$ for all $p > n?$ The first direction is trivial, the second I stumble on!
Comment: you are trying to prove the first statement if and only if the second statement?
Comment: What is $m$? The same as $n$?
Comment: @lhf: Sorry, corrected. I am trying to prove the second statement given that I know it's a linear operator and that for nonnegative powers the equality I gave holds.
Answer: If you know that for some $n \in \mathbb{N}$, $range K^n = range K^{n+1}$, and want to prove that for all $p \in \mathbb{N} (p>n), range K^p = range K^n$ then induction will certainly work.
To make it easier to see the argument, let $U = range K^n$; then since $range K^{n+1} = range KK^{n}$, the statement $range K^n = range K^{n+1}$ becomes $U = range K(U)$. Intuitively, we see that repeated applications of the linear operator $K$ do not change the range, so we should be able to prove the desired result.
Comment: I have n as one single non-negative integer for which I know this holds, sorry if I miswrote. Would induction still work on given that it's a specific n we know about?
Comment: @ranges: Yes; the same statement as discipulus writes, except that instead of being arbitrary natural numbers, $a$ and $b$ are arbitrary natural numbers greater than or equal to $n$. That is, do "bounded induction".


Understanding why the Uniform distribution does not make a good prior.

Question: I'm reading a book about Bayesian statistics and in this book is being explained why the Uniform distribution does not make for a good prior. The following example is given:
Example: Suppose that $X|\Theta = \theta \sim \operatorname{Bin}(n,\theta)$ and take the uniform prior over the parameter set: $\Theta\sim \operatorname{Unif}(0,1)$. The prior is supposed to express ignorance about $\theta$.  However, if we are ignorant about $\theta$, we are ignorant about $\theta^2$ as well (for example).  If we define $\Psi= \Theta^2$, then $$f_\Psi(\psi) = f_\Theta(\sqrt{\psi})\dfrac{1}{2\sqrt{\psi}} = \dfrac{1}{2\sqrt{\psi}}\mathbb{1}_{(0,1)}(\psi)$$
this implies that small realisations of $\Psi$ are more probable than large realisations and we are no longer ignorant about $\Psi$.
Question: Why is $f_\Psi(\psi)$ the correct density function of $\psi$, the way it's given in the example? Isn't the density function of the uniform distribution supposed to be a constant? I understand why the uniform distribution would not work if this is in fact the correct density, I don't know why it is though.
Thanks in advance!
Answer:
Question: Why is $f_\Psi(\psi)$ the correct density function of $\psi$, the way it's given in the example? Isn't the density function of the uniform distribution supposed to be a constant?

Indeed, but it is $\Theta$ that is supposedly uniformly distributed, not $\Theta^2$, and we have definied $\Psi$ as being $\Theta^2$.   So by the chain rule we have: $$\begin{split}f_\Psi(\psi) &=\left\lvert\dfrac{\partial~\mathsf P(\Theta^2\leqslant \psi)}{\partial~\psi\hspace{9.5ex}}\right\rvert\\[1ex] &= \left\lvert\dfrac{\partial~F_\Theta(\surd \psi)}{\partial~\psi\hspace{7.5ex}}\right\rvert \\[1ex] &=\left\lvert\dfrac{\partial~\surd \psi}{\partial~\psi~~~~}\right\rvert~ f_\Theta(\surd\psi)\\[1ex] & = \dfrac 1{2\surd\psi}~\mathbf 1_{(0;1)}(\psi)\end{split}$$
Comment: Thanks for your answer! However, why does one take the derivative here?
Comment: It is the chain rule: $[f\circ g]' = g' \cdot [f'\circ g] $
Comment: Sorry, I think my question wasn't clear enough. I understand that if you want to take the derivative of $f$ to $\psi$, you get the given results using the chain rule. However, why is the derivative taken in the first place? Is there a rule/theorem that says that if $\psi = \theta^2$ then the density function $f(\psi)$, is equal to the derivative of $f(\theta)$ w.r.t. $\theta$?
Comment: This is an application of the general change of variables formula. -- that is, the formula that lets us figure out the distribution of $g(X)$ for some function $g$ and random variable $X$ when we know the distribution of $X$. See [Wikipedia.](https://en.wikipedia.org/wiki/Probability_density_function#Dependent_variables_and_change_of_variables).
Comment: A probability density function is the unsigned derivative of the cumulative distribution function.$$f_{\Theta^2}(\psi) = \left\lvert\dfrac{\partial \mathsf P(\Theta^2\leqslant \psi)}{\partial \psi}\right\rvert$$


In Diffie Hellman key exchange using Elliptic Curve cryptography, how are the public keys calculated?

Question: While calculating the public key, $d * G = (X_a, Y_a)$ and similarly for $(X_b, Y_b)$, where $d$ is the private key. If calculating $d * G$ means adding $G$ to itself $d$ times, why can't the same be done to guess the private key '$d$' by an intruder - adding $G$ to itself until he gets the public key and hence find the private key? How is the calculation of public key efficient and guessing it computationally infeasible?
Comment: That is the elliptic curve discrete logarithm problem, look it up. As an analogy, the fact that you can quickly multiply integers does not mean you can quickly do the reverse, i.e. to factorize an integer. This is similar ...
Comment: It's not abou that (integer factorization is unique for example), it's that just by adding the point until you hit the one you want would take you too long for it to be of any use.
Comment: I found out that there are faster ways to multiply other than simply adding, but again I don't understand how that makes it impossible for the intruder to guess the private key using the same method?
Comment: @Sil So does that mean there is a huge number of 'd's producing the same product d*G. So checking all of them is infeasible?
Answer: Current day elliptic curve cryptosystems use keys 200+ bits long. In this context it means that your group has size $2^{200} \approx 10^{60},$ so on average you will need to compute $G,2G,\ldots,dG$ until $d \geq 5\times 10^{59}$ until you hit the point $(X_a,Y_a)$ and discover the discrete logarithm $d.$
Comment: (a)if the device is really weak they can be computed centrally and loaded on to the device during customisation, or more importantly,  (b) since $d$ is known to the device a square and multiply type algorithm can be used to do the addition. It is the discrete log that is hard, the other direction is easy, if you have the trapdoor information, i.e., $d.$
Comment: How are the public keys (Xa, Ya) calculated in the first place in small devices, if they require so much computation?


How to prevent re-triggering methods from continuous data?

Question: I have this app that is using the iBeacon stuff.
Building upon AirLocate, I'm listing the beacons in my neighborhood.
This is done in a UITableView as follows:
    - (void)locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray *)beacons inRegion:(CLBeaconRegion *)region
{
    self.rangedRegions[region] = beacons;
    [self.beacons removeAllObjects];

    NSMutableArray *allBeacons = [NSMutableArray array];

    for (NSArray *regionResult in [self.rangedRegions allValues])
    {
        [allBeacons addObjectsFromArray:regionResult];
    }

    for (NSNumber *range in @[@(CLProximityUnknown), @(CLProximityImmediate), @(CLProximityNear), @(CLProximityFar)])
    {
        NSArray *proximityBeacons = [allBeacons filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"proximity = %d", [range intValue]]];
        if([proximityBeacons count])
        {
            self.beacons[range] = proximityBeacons;
        }
    }
    [self.tableView reloadData];
}

from there on,
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

is called.
Here I call a method, that queries an online database for a value, specific to a cell.
The problem is, that the Location Manager is sending virtually continuous updates, forcing me to repeatedly send requests to the database for information that is not changing after the first query. After which I have to update the UI again.
What is the best approach to avoid this redundant query?
I hope this makes sense
thanks in advance
S

Here are the tableView delegates :
- (UITableViewCell *)tableView:(UITableView *)tView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"Cell";
    myCell *cell = [tView dequeueReusableCellWithIdentifier:identifier];

    NSNumber *sectionKey = [self.beacons allKeys][indexPath.section];
    CLBeacon *beacon = self.beacons[sectionKey][indexPath.row];

    User * myBuddy = [self retrieveDataFromUserwithMajor:[beacon.major shortValue] andMinor:[beacon.minor shortValue]];
    NSString *path=[NSString stringWithFormat:@"http://www.myplace.com/%@.png", myBuddy.userID];
    NSURL *url = [NSURL URLWithString:path];

    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
    cell.userSelfie.image=image;
    cell.userName.text=myBuddy.userName;
    cell.userSetting2.text=myBuddy.userSetting2;
    cell.userSetting3.text=myBuddy.userSetting3;
     }

    return cell;

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.beacons.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *sectionValues = [self.beacons allValues];
    return [sectionValues[section] count];
}

Answer: Your "irrelevant logic" is actually relevant because chances are it changes your table's data source array and knowing the changes to your data source array could have helped in formulating an answer...
But generally speaking, if didRangeBeacons is in fact where you are changing your data source, what you can do is (1) save a copy of your current data array at the top of the didRangeBeacons method, (2) change your data array using the "logic," then (3) only reload the data if the data source array has changed.
Edit: From your code it looks like self.beacons is your table's data source, so I've updated the code accordingly.
- (void)locationManager:(CLLocationManager *)manager didRangeBeacons:(NSArray *)beacons inRegion:(CLBeaconRegion *)region
{
    // Save a copy of the original self.beacons dictionary
    NSMutableDictionary *originalDataSource = [self.beacons copy];

    self.rangedRegions[region] = beacons;
    [self.beacons removeAllObjects];

    NSMutableArray *allBeacons = [NSMutableArray array];

    for (NSArray *regionResult in [self.rangedRegions allValues])
    {
        [allBeacons addObjectsFromArray:regionResult];
    }

    for (NSNumber *range in @[@(CLProximityUnknown), @(CLProximityImmediate), @(CLProximityNear), @(CLProximityFar)])
    {
        NSArray *proximityBeacons = [allBeacons filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"proximity = %d", [range intValue]]];
        if([proximityBeacons count])
        {
            self.beacons[range] = proximityBeacons;
        }
    }

    // If the original dictionary has changed, reload the data
    if (![originalDataSource isEqualToDictionary:self.beacons] {
        [self.tableView reloadData];
    }
}

Comment: Thanks, Lyndsey! Since I'm not sure how to get to the
self.tableDataSourceArray
I included the 'irrelevant logic' into the question......potentially making a fool out of myself.
Comment: @Sjakelien Is self.beacons a dictionary or an array?
Comment: @Sjakelien OK, updated. I'm assuming self.beacons is your table's data source, but I can't be sure unless I see your table view delegate methods...
Comment: Bear with me, I'm dealing with several devices interacting with each other while sharing the same code. My initial findings are, that
[self.tableView reloadData];
is still being called continuously. Apparently, the dictionary is changing.
Comment: @Sjakelien Is self.beacons your data source? Meaning is that the data that populates your table?
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/69776/discussion-between-sjakelien-and-lyndsey-scott).


How to calculate the area between $y=e^{-x}$, $y=x$ and $x=0$

Question: My problem is that little point that comes from the equation $$e^{-x} = x$$
I can't solve that one. Is there another way without knowing that point or a way to calculate it?
Thanks in advance!
Comment: Unfortunately the upper bound is that red point there. But I cannot calculate it by the equation $e^{-x} = x$
Comment: My professor gave me that problem..
Comment: This is a numerical problem, I suppose, right?
Answer: We want to figure out when $e^{-x} = x$. Multiplying by $e^x$ gives
$$
xe^x = 1
$$
The solution to this equation is defined as the $\Omega$-constant, and shares many interesting properties. So we have $\Omega e^\Omega=1$ or $e^{\Omega} = 1/\Omega$ or $\Omega=e^{-\Omega}$. Several fast approximations can be found at the link above. The integral is then
\begin{align*}
A
= \int_0^\Omega x\,\mathrm{d}x + \int_\Omega^\infty e^{-x}\,\mathrm{d}x
= e^{-\Omega} + \frac{1}{2}\Omega^2 = \Omega\left( 1+\frac{\Omega}{2}\right)\tag{1}
\end{align*}
Where we used that $e^{-\Omega}=\Omega$. For simplicity let us assume that $\Omega \approx \frac{5}{6}\log 2$ then
$$
A \approx \frac{25}{72}(\log 2)^2+\frac{1}{2}2^{1/6}
$$
If we really want to be fancy we can now use that $\log 2 \approx \frac 7{10}$ and $\frac{1}{2}2^{1/6}\approx \frac{1}{2}\left(1+1\cdot\frac{1}{6} \right)$. Where the last approximation comes from $(1+x)^{a} \approx 1 + ax$ where $|x|\leq 1$ and $a<1$. I will leave the rest to you
EDIT: The continued fraction expansion of $\Omega$ is given as
$$[0; 1, 1, 3, 4, 2, 10, 4, 1, 1, 1, 1, 2, 7, 306, 1, 5, 1, 2, 1, 5,\ldots]$$
Hence
$$
\Omega = \frac{1}{1 + \cfrac{1}{1 + \cfrac{1}{3+\cfrac{1}{4+\cfrac{1}{1+\frac{1}{\cdots}}}}}} \approx 38/67
$$
Inserting this into $(1)$ and using $e^{-\Omega}\approx 1/\Omega$ we have
$$
    A \approx \exp\left(-\frac{38}{67}\right) + \frac{1}{2}\left(\frac{38}{67}\right)^2
$$
Which is correct to about $10$ digits. Now $e^{-\Omega}=\Omega$ only holds for the exact Omega constant. Otherwise it is an approximation. Hence a tad worse version would have been
$$
    A \approx \frac{38}{67} + \frac{1}{2}\left(\frac{38}{67}\right)^2 = \frac{3268}{4489}
$$
Which is only correct for a handful digits ($3$).


Why does my SetEnvIfNoCase directive does not match requested URI?

Question: I'm attempting to set up Apache such that various error pages display with headers/footers appropriate to the context of the error. If the user was requesting a corporate page, I want to show the error with the corporate look and feel. If the error occurs in our application, I want to show it with the application look. Unfortunately, Apache does not want to play along.
In my testing, I've setup Apache to use a particular document when displaying an HTTP 503 error:
# Service Unavailable
ErrorDocument 503 /errors/error_503.shtml

In that document, using SSI directives and environment variables, I have constructed some if/else logic, which could conditionally include this or that header based on the content of an environment variable. This is is my test file:

corporate here.

I'M NOT CORPORATE.

This is a 503 error message! Check it out!

However, I can't seem to match the request URI using SetEnvIf in the apache config, for no reason that I can understand.
   <Location />
      # Allow error documents to use the application or corporate header as appropriate
      SetEnvIfNoCase Request_URI /corporate/home/ is_corporate   # this does not match
      SetEnvIfNoCase Request_URI ^/$ is_corporate                # this does not match
      SetEnvIfNoCase Request_URI ^/c is_corporate                # this does not match
      SetEnvIfNoCase Request_URI ^/C is_corporate                # this does not match
      SetEnvIfNoCase Request_URI .*/ is_corporate                # this matches
      SetEnvIfNoCase Request_URI .*  is_corporate                # this matches
    </Location>

In this particular case, my error document, printing the contents of REQUEST_URI displays: /Corporate/Home/, and always indicates that is_corporate is empty. Using SetEnvIfNoCase should make this a case insensitive match, but trying uppercase/lowercase doesn't seem to make a difference.
Since the SetEnvIf regex is supposed to be pcre compatible, I tested the regex in perl, just to make sure my regex was legit, and should work the way I intend:
vezult@zapazoid:~$ echo '/Corporate/Home' |perl -e 'while(<>) { if (/^\/c/i) { print("match!!: $_\n");} else { print("no match: $_\n"); }}'
match!!: /Corporate/Home

It does. Anyway, so I'm stumped. What might I be missing that is preventing my SetEnvIf statement to behaving as I expect?
Comment: I can't test right now, but I wonder if `Request_URI`'s value changes to `/errors/error_503.shtml` when serving the error page?
Comment: @Shane Madden: That seems to be exactly it. Turn that into an answer, and I'll award you the points.
Answer: SetEnvIf's Request_URI parameter seems to be updated with the path of the error document when it's in the process of serving one.
One workaround would be to match against something else that would have the parent path present, such as the Referer header.


Nilpotent Matrix is Similar to a block diagonal matrix

Question: Prove that any nilpotent matrix is similar to a block diagonal matrix whose blocks are matrices with 1's along the first super diagonal and 0's elsewhere.
I'm not sure where to start exactly. Any guidance would be helpful!
Comment: Can you use Jordan canonical form?  Combine with the fact that the eigenvalues of a nilpotent matrix are all $0$.
Comment: I think this is sometimes a stepping-stone to the full Jordan canonical form theorem. It doesn't matter what the base field is. You can build up a basis of the vector space with the required properties. Take $x\not=0$; there is some minimal $k$ such that $N^k x=0$. It's easy to prove that $\{x,Nx,N^2x, \dots,N^{k-1}x\}$ is LI, and action of $N$ on these is "right". Now take $x_2$ outside the span of these and repeat.
Comment: I am assuming over $\mathbb C$?
Comment: Do you know about quotient spaces?
Comment: Check Daniel's answer here: http://math.stackexchange.com/questions/809473/generalization-of-the-jordan-form-for-infinite-matrices/918339#918339
Answer: My answer is based on Wikipedia articles "Nilpotent matrix" and "Jordan normal form."
Every square matrix A over an algebraically-closed field has a Jordan canonical form J, which has zeros everywhere except A's eigenvalues as diagonal entries and possibly ones on the super diagonal. A is similar to J because there exists an invertible matrix P such that A = P J P ⁻¹.  Because zero is the only eigenvalue of a nilpotent matrix, J has the form you want.


Find the distance to the centre of the grid

Question: I am trying to find a length from the centre of a grid to points in a circular pattern around that centre point and the procedure escapes me. Going up/down/left/right is easy enough, but how do I calculate the angles and where to place points?
Here is an example to help visualize what I am asking:
Comment: The picture really doesn't help very much. Are you trying to find all the points less than, say, 10 units from the center?
Comment: Are you familiar with [polar coordinates](http://en.wikipedia.org/wiki/Polar_coordinate_system)?
Comment: @GerryMyerson Yes, I am trying to find all the coordinates within a set distance from the center.
Comment: @ja72 I am not, but I will definitely read up on that. Thanks!
Comment: OK, Sean, but I take it you are happy with the answer ja72 has posted.
Answer: If two points are $X$ grids apart horizontally and $Y$ grids apart vertically then use the following
$$ {\rm distance} = \sqrt{X^2+Y^2} \\
   {\rm angle} = {\rm atan2}(Y,X)
$$
NOTE: The Atan2 function is common on computer languages.
Comment: That is exactly what I was looking for, thanks!


Qual diferença entre ToListAsync() e ToList()?

Question: Qual diferença entre ToListAsync() e ToList()?
Como no exemplo abaixo, qual a diferença entre um e outro?
using Modelo.Classes.Contexto;
using System.Data.Entity;
using System.Linq;

namespace AppConsoleTestes
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var ctx = new dbContexto())
            {
                var ListaUsuario1 = await ctx.Usuarios.ToListAsync();
                var ListaUsuario2 = ctx.Usuarios.ToList();
            }
        }
    }
}

Answer: ToListAsync() é o ToList assíncrono. Métodos assíncronos podem ser executados sem travar a linha de execução principal da aplicação. Ex.: numa aplicação WinForms, não travar a GUI em operações longas.
Para o método ser executado assincronamente deve ser chamado com await antes dele e o método que o chama precisa estar marcado como async.
Se for usado da forma que mostra a pergunta, ele vai retornar um Task<T> e você vai ter que se preocupar em como resolvê-lo. Se usar await ctx.Usuarios.ToListAsync() o trabalho de "resolver" este Task<T> será automático.

Não vou dar mais detalhes sobre o uso de async/await porque já tem bastante sobre isso no site.
Em C#, para que serve a palavra chave await?
Utilização correta do async and await no Asp.Net
Comment: Pode postar, não tem nada a perder, bem pelo contrário, se a resposta estiver certa, meu upvote é garantido. Essa pergunta vai servir pra mais gente no futuro, é bom termos várias respostas, desde que todas estejam corretas e nenhuma seja cópia da outra.
Comment: Droga, estava terminando de escrever :(
Answer: O método com Async no nome é assíncrono, ou seja, ele tem capacidade de ser executado sem travar a linha de execução atual, então se ele tivesse sido chamado da forma correta logo após seu início o código já poderia partir para a próxima linha, e provavelmente o ToListAsync() executaria em paralelo.
Para que a assincronicidade ocorra de fato precisaria de um await.
Coloquei no GitHub para referência futura.
Answer: Existem diversos métodos com 'async' no nome, indicando que o mesmo é assincrono.
Porém como foi dito, é necessário utilizar as keywords async/await em conjunto.
Tu mesmo pode criar seus métodos asyncronos, e por padrão utilize no nome do método a palavra 'async', é uma boa prática. Pesquise pois existe muito artigo sobre isso.


Android Menu Shown Where User Clicked

Question: I wanted to achieve the same sort of functionality found in Google Now where you can tap the cards overflow icon and a menu appears next to it with options (shown here).
Does anyone know how to implement this sort thing to achieve the same style etc?
Answer: I think you can do this by placing a listview under your button, and set its visibility to invisible.
Then place an onclicklistener on your button to turn your visibility to visible.

Android Menu Shown Where User Clicked


Is $S_i(1,2,\dots,p-2) \equiv 1 \pmod{p}$ for all values of $i$ whenever $p$ is prime?

Question: Let $S_i(x_1,x_2,\dots,x_n)$ denote the $i$th elementary symmetric polynomial in $n$ variables. Is $S_i(1,2,\dots,p-2) \equiv 1 \pmod{p}$ for all values of $i$ from $0$ to $(p-2)$ whenever $p$ is prime?
Since $$\sum_{0}^{p-2} S_i(1,2,\dots,p-2) = (p-1)!,$$ it's obvious that  $$\sum_{0}^{p-2}S_i(1,2,\dots,p-2)\equiv -1 \pmod{p}$$ I don't know, however, if this sum can ever be different from $(p-1)$.
Answer: (There's no need for the superscripts on elementary symmetric polynomials $e_i$.)
As Vieta's formula states, $e_i(x_1,\cdots,x_n)$ will be the $i$th coefficient of $(T+x_1)\cdots(T+x_n)$.
According to Euler's theorem, $x^{p-1}\equiv 1$ mod $p$ for all $x$, so the polynomial $T^{p-1}-1$ has every integer residue $1,\cdots,p-1$ as a zero. Since the integers mod $p$ form a field, zeros correspond to linear factors in any polynomial's factorization, hence $T^{p-1}-1\equiv (T-1)\cdots(T-(p-1))$.
Therefore mod $p$:
$$\begin{array}{ll} (T+1)\cdots(T+(p-2)) & \equiv(T-(p-1))\cdots(T-2) \\ & \equiv(T^{p-1}-1)/(T-1) \\ & \equiv T^{p-2}+\cdots+T^2+T+1.\end{array}$$
Evidently all the coefficients are $1$ mod $p$.
Comment: @LucasDaSilvaPereira A variable that makes up a polynomial. For example mod $5$, $$(T-1)(T-2)(T-3)(T-4)\equiv T^4-1.$$
Comment: @Lucas Um, how do you know $T^{p-1}-1$ factors as $(T-1)\cdots(T-(p-1))$ if you don't know about the things you're asking and think $\pm1$ are the only zeros? Anyway, $x^{p-1}-1\equiv 0$ mod $p$ for a given value of $x$ is precisely what it *means* for $x$ to be a "zero of the polynomial $T^{p-1}-1$." Since every $x\equiv 1,\cdots,p-1$ satisfies $x^{p-1}\equiv1$, every such residue is a zero of the polynomial, and hence the factorization. No, of course $\pm1$ are not the only roots mod $p$ (they are the only roots in the real number system as $p-1$ is even is probably what you're thinking).
Comment: As for what happens when $p$ is composite, go ahead and expand out $(T+1)\cdots(T+p-2)$ mod $p$ for $p=4$ and $p=6$ to see for yourself.