How to create virtual subdomains by using DNS with wildcard

Question: I want to create many virtual subdomains e.g my original site is www.Test.com but I want that my site users can open my site with the given pattern username.Test.com
Can you please help me for this issue?
Answer: There will be a couple of things that you need to do in this situation.  First, you will need to create a wildcard DNS entry.  Most DNS server software will allow you to create an A record called * which you can direct to the IP address of your web server.  This will cause the DNS server to resolve anything.example.com to the IP address specified.  If you have other hostnames, such as www.example.com specifically defined, those records will override the wildcard (i.e. the wildcard will not negate your existing records or any other record specifically defined).
Second, you will need to configure your web server (I'll presume IIS since you tagged the question with asp.net) with a binding to the same IP address specified in the DNS record.  Do not specify a hostname on this binding.  This will cause IIS to catch any request for that IP address which isn't specifically bound to another website entry by its IP/name combination (again, you can have a site bound to the same IP with specific hostnames which will override this one).
Next, in your application code, you will need to handle the incoming request by looking at the variables coming from the server, specifically the SERVER_NAME or HTTP_HOST server variables as they will contain the hostname the user is attempting to access.  The code would then reference this hostname back to a user's account and serve up the appropriate content for the hostname in question.


How to run basic test using karma (testacular)

Question: I've been playing with jasmine recently in order to start incorporating tests in my projects.
All seemed to work fine until, I wanted to automate the workflow with karma (previously Karma).
In my src directory, I have simple Calculator Object with a couple of simple methods:
function Calculator() { };
var current = 0;
Calculator.prototype.add = function() {
if (arguments.length < 2) {
    // we only have one arguments
    current += arguments[0];
    return current;
} else {
    // more than one arguments
    for( var i in arguments )
        current += arguments[i];
    return current;
}
};

Calculator.prototype.substract = function() {
var currentValue = arguments[0];

for ( var i = 1; i < arguments.length; i++ )
    currentValue -= arguments[i];
return currentValue;
};

Calculator.prototype.reset = function() {
window.current = 0;
}

Then in my spec file, I do have the following ( all tests passes without Karma ):
var calculator = new Calculator();
describe('Calculator', function() {
beforeEach(function() {
    window.current = 0;
});

describe('When adding numbers', function() {
    it('should store the current value at all times', function() {
        expect(window.current).toBeDefined();
    });

    it('should add numbers', function() {
        expect(window.calculator.add(5)).toEqual(5);
        expect(window.calculator.add(10)).toEqual(15);
    });

    it('should add any number of numbers', function() {
        expect(calculator.add(1, 2, 3)).toEqual(6);
        expect(calculator.add(1, 2)).toEqual(9);
    })
});

describe('When substracting numbers', function() {
    it('should substract any number of numbers', function() {
        expect(calculator.substract(5, 3)).toEqual(2);
    });
});

it('should reset the current value back to zero', function() {
    window.current = 20;
    calculator.reset();

    expect(window.current).toEqual(0);

    calculator.add(5);
    calculator.add(20);
    expect(window.current).toEqual(25);

    calculator.reset();
    expect(window.current).toEqual(0);
});
});

When I run karma start, I get the following:
Chrome 28.0 (Mac) ERROR
    Uncaught ReferenceError: Calculator is not defined
    at /Users/roland/learning/jasmine/jasmine-standalone-1.3.1/spec/calculator_spec.js:1
Thank you for the help!
Answer: It seems like you're not loading the file that has Calculator or perhaps it's being loaded after the spec file. In your Karma configuration file, you'll want to do  something like this:
files = [
  'path/to/calculator.js',
  JASMINE,
  JASMINE_ADAPTER,
  'path/to/calculator_spec.js'
];

Comment: Yep, that was it! I was just watching the spec folder! thanks!


Adding to a div after jquery ui dialog

Question: I have a table that has data in it and when you click on certain items a jquery ui dialog box appears to make sure you want to add that specific item. My question is how do I actually add the item (just the item name) that was clicked on after they hit yes on the dialog box?
my html is just a table (it has to be a table) with a button on the left side and then the name in the second column and information in the third column so

    <button class="itemButton">
     item1
     description

and I want to add it to a div called cart

here is my jquery
$(document).ready(function () {
    var dialogDiv = $('#dialog');

    $('.itemButton').click(function () {
        dialogDiv.dialog('open');
    });

     dialogDiv.dialog({
         autoOpen: false,
         modal: true,
         buttons: {
            'Add': function () {
                 HELP HERE!!!!!!
                 dialogDiv.dialog('close');
             },
            'Cancel': function (){
                dialogDiv.dialog('close');
          }
      }
   });
});

for the other ones that don't need a pop up i have this for my jquery
$('.add').click(function(){
    $(this).parent().next().clone().appendTo('p').after('
');
});

and that works fine.
thank you.
Comment: You are looking for the `append` or `appendTo` function.
Answer: One way is to mark the button clicked with a class, and use that class to move the correct row to the cart when confirmed.
This example leaves the Add Button when added to the cart for expediency.
Edit:  update to move only the item name [Cell 2]

$(document).ready(function() {
  var dialogDiv = $('#dialog');

  $('.itemButton').click(function() {
    $('.itemButton.debating').removeClass("debating"); //remove any old marker
    $(this).addClass("debating"); //mark this button
    dialogDiv.dialog('open');
  });

  dialogDiv.dialog({
    autoOpen: false,
    modal: true,
    buttons: {
      'Add': function() {
        $("
").text($('.itemButton.debating').closest("tr").find("td:nth-child(2)").text()).appendTo($("#cart")); //move the marked text
        dialogDiv.dialog('close');
      },
      'Cancel': function() {
        dialogDiv.dialog('close');
      }
    }
  });
});

<link type='text/css' href='https://code.jquery.com/ui/1.12.1/themes/black-tie/jquery-ui.css' rel='stylesheet' />

Are you sure?

    <button class="itemButton">Add</button>
     item1
     description

    <button class="itemButton">Add</button>
     item2
     description 2

    <button class="itemButton">Add</button>
     item3
     description 3

Answer: Not entirely sure why you would want to move the entire row in the cart with the button and all so here's an answer for adding a DIV with just the item's info in the cart. Here's a fiddle
$(document).ready(function () {
    var dialogDiv = $('#dialog'),
    itemName = '';

    $('.itemButton').click(function () {
        dialogDiv.dialog('open');
        itemName = $(this).closest('tr').find('td:nth-child(2)').text();
    });

     dialogDiv.dialog({
         autoOpen: false,
         modal: true,
         buttons: {
            'Add': function () {
                $('
' + itemName + '
').appendTo('#cart');
                 dialogDiv.dialog('close');
             },
            'Cancel': function (){
                dialogDiv.dialog('close');
          }
      }
    });
});

You also need to fix the markup for that button. It is missing it's closing tag
<button class="itemButton">Add to Cart</button>

Comment: Sorry I will edit. I don't want to add the entire row just the item name!
Comment: Edited my answer for just the item name.

Adding to a div after jquery ui dialog


Alternative to CSV?

Question: I intend to build a RESTful service which will return a custom text format.  Given my very large volumes of data, XML/JSON is too verbose.  I'm looking for a row based text format.
CSV is an obvious candidate.  I'm however wondering if there isn't something better out there.  The only I've found through a bit of research is CTX and Fielded Text.
I'm looking for a format which offers the following:

Plain text, easy to read
very easy to parse by most software platforms
column definition can change without requiring changes in software clients

Fielded text is looking pretty good and I could definitely build a specification myself, but I'm curious to know what others have done given that this must be a very old problem.  It's surprising that there isn't a better standard out there.
What suggestions do you have?
Answer: I'm sure you've already considered this, but I'm a fan of tab-delimited files (\t between fields, newline at the end of each row)
Comment: Could you please show me the official spec for this. How to encode unicode? How to quote a tab in tab-delimited files? How to encode binary data like PDF/PNG in tab-delemited files?
Comment: @guettli It known as [tab-separated values (TSV)](https://en.wikipedia.org/wiki/Tab-separated_values).
Answer: I would say that since CSV is the standard, and since everyone under the sun can parse it,  use it.
If I were in your situation, I would take the bandwidth hit and use GZIP+XML, just because it's so darn easy to use.
And, on that note, you could always require that your users support GZIP and just send it as XML/JSON, since that should do a pretty good job of removing the redundancy accross the wire.
Comment: Or rather, no one under the sun can parse it.
Comment: Could you please show me the official spec for csv. How to encode unicode? How to quote a comma in csv files? How to encode binary data like PDF/PNG in csv?
Answer: You could try YAML, its overhead is relatively small compared to formats such as XML or JSON.
Examples here: http://www.yaml.org/
Surprisingly, the website's text itself is YAML.
Comment: AFAIK YAML is not tabular. Every row can have different attributes/columns.
Comment: @guettli It could be said that YAML is a superset of tabular formats, as everything which can be stored in CSV can also be stored in YAML. The opposite is of course not true. (example: https://gist.github.com/noirotm/e2eaa5f40a346910901285584dca75c2)
Comment: YAML has a ton of issues, this is discussed [here](https://noyaml.com/) in detail. The Implicit conversion of "NO" to boolean for example (could also mean Norway.)
Answer: I have been thinking on that problem for a while. I came up with a simple format that could work very well for your use case: JTable.
<code> {
    "header": ["Column1", "Column2", "Column3"],
    "rows"  : [
                ["aaa", "xxx", 1],
                ["bbb", "yyy", 2],
                ["ccc", "zzz", 3]
              ]
  }
</code>
If you wish, you can find a complete specification of the JTable format, with details and resources. But this is pretty self-explanatory and any programmer would know how to handle it. The only thing necessary is, really, to say, that this is JSON.
Answer: Looking through the existing answers, most struck me as a bit dated. Especially in terms of 'big data', noteworthy alternatives to CSV include:

ORC : 'Optimised Row Columnar' uses row storage, useful in Python/Pandas. Originated in HIVE, optimised by Hortonworks. Schema is in the footer. The Wikipedia entry is currently quite terse  https://en.wikipedia.org/wiki/Apache_ORC but Apache has a lot of detail.

Parquet : Similarly column-based, with similar compression. Often used with Cloudera Impala.

Avro : from Apache Hadoop. Row-based, but uses a Json schema.  Less capable support in Pandas. Often found in Apache Kafka clusters.

All are splittable, all are inscrutable to people, all describe their content with a schema, and all work with Hadoop. The column-based formats are considered best where cumulated data are read often; with multiple writes, Avro may be more suited. See e.g. https://www.datanami.com/2018/05/16/big-data-file-formats-demystified/
Compression of the column formats can use SNAPPY (faster) or GZIP (slower but more compression).
You may also want to look into Protocol Buffers, Pickle (Python-specific) and Feather (for fast communication between Python and R).

Alternative to CSV?


Use the Mean Value Theorem to proof the inequality

Question: Need to prove that $57/8 < \sqrt{51}$ using the mean value theorem. The hint given in the question is to use the $\sqrt{x}$ function. I have used the interval $51 < c < 64$.
Therefore I have: $f(64)-f(51)=f'(c)(64-51)=8-\sqrt{51}=13/2\sqrt{c} $
What I have trouble here is isolating $\sqrt{51}$ into an inequality. Have I used a correct interval to use the Mean Value Theorem? Is there a trick I'm missing? Thanks in advance.
Answer: Your method is correct. Choose the interval to be $[49, 51]$. That would work.
Answer: Hint: Use the fact that $51<c<64$ to get $\frac{1}{2\sqrt 64}< \frac{1}{2\sqrt c}<\frac{1}{2\sqrt 51}$ and the result follows.


Replace reST document with entire directory using Sphinx

Question: My primary documentation for a project is Sphinx. I also have a large amount of JavaDocs that I'd like to integrate. The basic setup is:
sphinx_source/
javadocs_built/
Before building the Sphinx documents, I can copy the JavaDocs into a directory under sphinx_source.
How can I reference this directory with non-reST files in it from within Sphinx and have them be brought along during the build process?
Answer: You probably need to reference the files using the :download: directive.
See: here.
Note that you'll need to reference the files individually, so you may want to set up some kind of script to generate the references for you.


Second difficulty in understanding the proof of theorem 1.14 in Hungerford.

Question: The theorem and part of its proof is given in the following pictures:

But I do not know why the author divide the proof of the first implication into these 2 steps: (1) when $A=A_1 \oplus\cdots\oplus A_n$ and when (2) $A \cong A_1 \oplus \cdots \oplus A_n$, could anyone explain this for me please?
Answer: For ease of understanding. It is clearer what happens in the case $A = A_1 \oplus \cdots \oplus A_n$, so that gets explained first. Then the slight generalization $A \cong A_1 \oplus \cdots \oplus A_n$ via the isomorphism $f$ is discussed; the special case is recovered when $f = \mathrm{id}_A$.


About the definition of variation.

Question: If $f$ is a function of bounded variable on $[a,b]$.Then:
$$V_a^b(f)=\sup_{\pi}\sum_{i=0}^n|f(x_{i+1})-f(x_i)|$$ where $\pi$ is a partition of $[a,b]$.
I wonder if$$V_a^b(f)=\lim_{\|\pi\|\to 0}\sum_{i=0}^n|f(x_{i+1})-f(x_i)|$$
if the limit exist.where $\|\pi\|$ means :$\max_{i}|x_{i+1}-x_i|$
(I got the inspiration from the definition of quadratic variation in the stochastic analysis)
Comment: maybe you could try the triangle inequality.
Answer: No, in general the equality
$$V_a^b(f) = \lim_{\|\pi\| \to 0} \sum_{i=0}^n |f(x_{i+1})-f(x_i)|$$
does not hold. In order to see this, consider the function
$$f(x) := \begin{cases} 1 & x \neq \frac{\pi}{4} \\ 0 & x = \frac{\pi}{4} \end{cases}$$
on the interval $[a,b] := [0,1]$. Obviously, $V_0^1(f)=2$. On the other hand, if we define a sequence of partitions $\pi^n$, $n \in \mathbb{N}$, by
$$x_{i}^n := \frac{i}{n}, \qquad 0 \leq i \leq n,$$
then it is not difficult to see that
$$V^{\pi_n}(f) := \sum_{i=0}^{n-1} |f(x_{i+1}^n)-f(x_i^n)| = 0.$$

About the definition of variation.


How do I "freeze" the variable in place? (discord.py)

Question: Don't really know if I asked the question correct, since I don't really know what causes it here but let me show.
<code>                unscrambled = random.choice(wordshack)
                scrambled = scramble(unscrambled)
                twork = await ctx.send(f"You have 120 seconds and 1 try to unscramble: {scrambled}")

                try:
                    msg = await self.client.wait_for(
                    "message",
                    timeout=120,
                    check= lambda message: message.author == ctx.author
                    and message.channel == ctx.channel
                    )
                    if msg == unscrambled:
                        await ctx.send(f"You worked as hacker and earned {hack}$")

</code>
Read the last two lines, the msg == unscrambled just doesn't function at all, I probably know why, but I don't know how to solve this so my bot works fast enough
Comment: Does it work if you replace it with `msg.content`?
Comment: @duckboycool it does! thank you alot.
Answer: User duckboycool helped me with this. Just replace msg -> msg.content and it will work!


Volume with a Cubic

Question: Find the volume of the solid of revolution formed when the curve $y=x^3+1$ is rotated around the $y$-axis from $y=1$ to $y=9$.
I understand the rule to find the volume when it is rotated around the $y$-axis; however, how do I make the subject and squared when it is cubed?
Does that make sense?
Comment: You can use the method of BRICS-Fan, or use Cylindrical Shells, $\int_0^2 2\pi x(x^3+1)\,dx$.
Answer: Make cylindrical shells of radius $x$ $\>(0\leq x\leq2)$, height $9-(x^3+1)=8-x^3$, and thickness $dx$. The volume $V$ in question then appears as
$$V=\int_0^2 2\pi x(8-x^3)\>dx=2\pi\left(4x^2-{x^5\over5}\right)\Biggr|_0^2={96\over5}\pi\ .$$
Answer: We're working on the $y$ axis, so let's change orientations first.
$$x = (y-1)^{1/3}$$
Since we're asked to find the volume of revolution, we need to determine the radius and area of the revolution at each point along the given interval $y \in [1, 9]$. The radius is simply given by the "height" of the function $x$, so the area is given by $\pi x^2 = \pi (y-1)^{2/3}$. Integrating along the interval, we find
$$ \int_{y=1}^9 \pi (y-1)^{2/3} \,\mathrm{d}x = \left.\frac{3\pi}{5}(y-1)^{5/3}\right|_{1}^{9} = \frac{96\pi}{5} $$
Comment: There is no reason to swap the $x$ and $y$. It has only served to confuse things. Upon changing the orientation, the area is given by $\pi y^2=\pi(x-1)^{2/3}$ and the integral should be $$\int_{\color{#C00000}{x}=1}^9\pi(\color{#C00000}{x}-1)^{2/3}\,\mathrm{d}x$$
Answer: Since $y=x^3+1$, we have $\mathrm{d}y=3x^2\mathrm{d}x$. Therefore, using the Disc Method for finding the volume of rotation, we get
$$
\begin{align}
\int_1^9\pi x^2\,\mathrm{d}y
&=\int_0^2\pi x^2\,3x^2\,\mathrm{d}x\\
&=\left[3\pi\frac{x^5}5\right]_0^2\\[4pt]
&=\frac{96\pi}5
\end{align}
$$
Comment: I don't know if the downvote was because I gave a hint, but since there are now two complete answers, I might as well complete the answer to demonstrate the whole idea.
Answer: hint: $V = \displaystyle \int_{1}^9 \pi(\sqrt[3]{y-1})^2dy$

Volume with a Cubic


Thymeleaf ocultar botão

Question: Tenho um único modal que chamo em duas páginas.
quero que o botão ALTERAR CLIENTE apareça no modal da página "A" e na página "B" este botão desapareça.
Como disse é o mesmo modal para duas páginas diferentes e gostaria de ocultar o botão apenas em uma das páginas.
Answer: Boa tarde, você pode colocar uma flag booleana no controller que leva os usuários para estas páginas e usar o th:if para mostrar ou não o botão. Por exemplo:
<button th:if="${podeAlterarCliente} type="button" class="btn btn-secondary">Alterar Cliente</button>

Espero ter ajudado!

Thymeleaf ocultar botão


Open two ports connection with one server on java

Question: I would like to launch a server who listens simultaneously to two different ports and with a different treatment to incoming connections (I launch a differnet slave depending on port). I did something like this:
public class ServeurMaitre {
public static ServerSocket serverSocket = null;
int poolSize = 15;
private ExecutorService pool = null;
ServeurMaitre(int port, int size){
    try {
        serverSocket = new ServerSocket(port, size);
        pool = Executors.newFixedThreadPool(poolSize);
        System.out.println("Serveur en marche. En attente des clients");

    } catch (IOException ex) {
        Logger.getLogger(ServeurMaitre.class.getName()).log(Level.SEVERE, null, ex);
    }
}

void ConnexionServeur() throws IOException {
    while(true) {
        Socket cnx = serverSocket.accept();
        if (cnx.getLocalPort()==3333) {
            pool.execute(new EsclaveXML(cnx, this));
        }
        if(cnx.getLocalPort()==8000) {
            pool.execute(new EsclaveHTTP(cnx, this));
        }
    }
}

public class Main{
public static void main(String[] args) throws IOException {
    ServeurMaitre serveur = new ServeurMaitre(8000, 1);
    ServeurMaitre serveur1 = new ServeurMaitre(3333, 1);
    serveur.Initialisation();
    serveur.ConnexionServeur();
    serveur1.ConnexionServeur();

}}

Problem: connexions that arrive on port 3333 are well treated but those who are on 8000 don't.
Any help please? Thank you.
Answer: I think, cause of the problem is "static serverSocket" variable.
You can change this line
   public static ServerSocket serverSocket = null;
to
public ServerSocket serverSocket = null;


Alamofire Swift 2.0 json response

Question: I keep getting this error:
<code> '(_, _, _, _) -> Void' is not convertible to 'Response<AnyObject, NSError> -> Void'
</code>
I looked in a lot of places, and tried the changes but it gives me errors else where.
<code>    Alamofire.request(.GET, "http://example.com/test.php", parameters: ["username": usernamep]).responseJSON { (request, response, json, error) in
        if (json != nil) {
            var jsonObj = JSON(json!)
            if let data = jsonObj["flist"].arrayValue as [JSON]?{
                datasMentions = data
             ....
            }
        }
</code>
Comment: Well you shouldn't have `(_, _, _, _ )`, they should be `(respond, json, error, _)` these are the responses.
Answer: With a couple of trials, I got it.
<code>    Alamofire.request(.GET,"http://example.com/test.php", parameters: ["username": usernamep])
        .responseJSON { response in

            if let json = response.result.value {
        var jsonObj = JSON(json!)
        if let data = jsonObj["flist"].arrayValue as [JSON]?{
            datasMentions = data
         ....
        }
            }
    }
</code>

Alamofire Swift 2.0 json response


create intersection points of paths on edge of mask. Adobe illustrator

Question: The "A" in the following image is a compound path.
The lines are paths with a white stroke.
The A is a clipping mask that is clipping the white strokes.
I want to create anchor points for each path at the edge of the clipping mask.

This is what I want to Achieve:

I did this three years ago and can't remember how I did it. It's driving me crazy...
Answer: It can be done via Erase mode of the  Shape Builder tool:

select all objects (the "A" must be a simple object, not a clipping mask)
select Shape Builder Tool (Shift M) and pressing Alt erase outers and internals unnecessary parts of lines.
Comment: That is very time consuming. Can you think of a method that will do this automatically?


Determine whether $\sum_{k=2}^\infty\frac1{(\ln k)^{\ln k}}$ is convergent or divergent.

Question: I have the series
$$\sum_{k=2}^\infty\frac1{(\ln k)^{\ln k}}$$
and am trying to find whether it is convergent or divergent. Along with the question, I received a hint stating that
$$\ln k=e^{\ln\ln k}$$
I simplified to make
$$\sum_{k=2}^\infty \frac1{e^{\ln\ln k\ln k}}$$
given the hint. I am unsure of what series test to use in order to proceed, due to the unique nature of the question.
Answer: Since $e^{\ln k}=k$ for $k>0$:
$$\sum_{k=2}^\infty\frac1{e^{\ln\ln k\ln k}}=\sum_{k=2}^\infty k^{-\ln\ln k}$$
$\ln\ln k$ is a strictly increasing function for $k>1$, so there exists an integer $n$ with $\ln\ln m>2$ for all $m\ge n$. Thus, the series splits into a finite head and a tail that can be shown convergent by the limit comparison test:
$$\sum_{k=2}^\infty k^{-\ln\ln k}=\sum_{k=2}^{n-1} k^{-\ln\ln k}+\sum_{k=n}^\infty k^{-\ln\ln k}\le\sum_{k=2}^{n-1} k^{-\ln\ln k}+\sum_{k=n}^\infty k^{-2}<\sum_{k=2}^{n-1} k^{-\ln\ln k}+\frac{\pi^2}6<\infty$$
Therefore the original series converges.
Answer: The easiest is to use the condensation test, $\sum a_n$ converges iff $$\sum 2^na_{2^n}$$ converges. In this case you get
$$\sum \frac{2^n}{n^n}$$ which converges, by root test or others.
Answer: Using Ermakoff's test:
$$\lim_\limits{x\to\infty} \frac{e^xf(e^x)}{f(x)}=\lim_\limits{x\to\infty} \frac{e^x\cdot \frac{1}{x^x}}{\frac{1}{(\ln x)^{\ln x}}}=\lim_\limits{x\to\infty} \frac{e^x\cdot (\ln x)^{\ln x}}{x^x}=0<1.$$
So it converges.
Answer: More generally,
generalizing
Parcly Taxel's proof,
if
$f(k)$
is positive,
strictly increasing,
and eventually $> e$,
then
$\sum_{k=2}^\infty\frac1{f(k)^{\ln k}}
=\sum_{k=2}^\infty\frac1{e^{\ln(f(k))\ln k}}
=\sum_{k=2}^\infty\frac1{k^{\ln(f(k))}}
$
and this converges
by comparison with
$\frac1{k^p}$
with
$\ln(f(k)) > 1$.


"unrecognized selector sent to class" when calling category method from a library

Question: Problem
This question may seem a bit long, but I try to give as much information as possible, since I am really staggered by this.
I am currently working an a library which should automate XML document parsing. But I am running into a problem now testing the library for the first time.
I have a library class called CSXDocumentLayout which represents the layout of a document. This class contains the private method - (NSError *)readLayoutDocument:(NSString *)fpath called from an init method.
/* MARK: Reading in Layouts */
- (NSError *)readLayoutDocument:(NSString *)fpath {
    CSXDocumentLayout *layout;
    CSXXMLParser *parser;
    BOOL state;

    layout = [CSXDocumentLayout layoutDocumentLayout];

    parser = [[CSXXMLParser alloc] initWithDocumentLayouts:
              [NSArray arrayWithObject:layout]];
    parser.file = fpath;

    state = [parser parse];

    if(state == NO || parser.error != nil) {
        return parser.error;
    }
    return nil;
}

This method will read in an XML document representing the layout of an other XML document. It is parsed by the class CSXXMLParser, which I want to test.
I create an object representing a layout document with +[CSXDocumentLayout layoutDocumentLayout]. This method is implemented in the category CSXDocumentLayout (CSXLayoutObject).
Below is my test file:
#import <Foundation/Foundation.h>
#import <CeasyXML.h>

int main(int argc, const char **argv) {
    NSAutoreleasePool *pool = [NSAutoreleasePool new];

    NSString *file;

    file = [NSString stringWithUTF8String:__FILE__];
    file = [file stringByDeletingLastPathComponent];
    file = [file stringByAppendingPathComponent:@"Layout.xml"];

    CSXDocumentLayout *layout;
    NSError *error;

    layout = [[CSXDocumentLayout alloc] initWithLayoutDocument:file
                                                         error:&error];
    if(layout == nil) {
        NSLog(@"Could not create layout: %@", error);
        exit(0);
    }

    NSLog(@"Layout:\n%@", layout);

    [pool release];
    return 0;
}

This file compiles to a separate executable linked to my static library libceasyxml.a. Everything compiles just fine without any warnings.
But when I run it I get a unrecognized selector sent to class exception:
2012-05-02 16:59:47.620 TestApp[1887:a0f] +[CSXDocumentLayout layoutDocumentLayout]: unrecognized selector sent to class 0x1000064c8
2012-05-02 16:59:47.791 TestApp[1887:a0f] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[CSXDocumentLayout layoutDocumentLayout]: unrecognized selector sent to class 0x1000064c8'
*** Call stack at first throw:
(
    0   CoreFoundation                      0x00007fff83e47784 __exceptionPreprocess + 180
    1   libobjc.A.dylib                     0x00007fff84604f03 objc_exception_throw + 45
    2   CoreFoundation                      0x00007fff83ea11a0 __CFFullMethodName + 0
    3   CoreFoundation                      0x00007fff83e198ef ___forwarding___ + 751
    4   CoreFoundation                      0x00007fff83e15a38 _CF_forwarding_prep_0 + 232
    5   TestApp                             0x0000000100001512 -[CSXDocumentLayout(Private) readLayoutDocument:] + 49
    6   TestApp                             0x00000001000010d4 -[CSXDocumentLayout initWithLayoutDocument:error:] + 96
    7   TestApp                             0x0000000100001017 main + 179
    8   TestApp                             0x0000000100000f5c start + 52
    9   ???                                 0x0000000000000001 0x0 + 1
)

I find it very disturbing that I cannot call the class method +[CSXDocumentLayout(CSXLayoutObject) layoutDocumentLayout], though I can call both -[CSXDocumentLayout initWithLayoutDocument:error:], and -[CSXDocumentLayout(Private) readLayoutDocument:].
Research
I checked if the method is defined in the output files by running nm file and it is, well partly:
In libceasyxml.a, it is defined (nm libceasyxml.a)
...
libceasyxml.a(CSXDocumentLayout+CSXLayoutObject.o):
0000000000000100 t +[CSXDocumentLayout(CSXLayoutObject) classAttributeLayout]
00000000000020e0 s +[CSXDocumentLayout(CSXLayoutObject) classAttributeLayout].eh
000000000000056b t +[CSXDocumentLayout(CSXLayoutObject) documentElementLayout]
0000000000002180 s +[CSXDocumentLayout(CSXLayoutObject) documentElementLayout].eh
0000000000000402 t +[CSXDocumentLayout(CSXLayoutObject) layoutDocumentLayout]
0000000000002148 s +[CSXDocumentLayout(CSXLayoutObject) layoutDocumentLayout].eh
0000000000000200 t +[CSXDocumentLayout(CSXLayoutObject) layoutElementLayout]
0000000000002110 s +[CSXDocumentLayout(CSXLayoutObject) layoutElementLayout].eh
0000000000000000 t +[CSXDocumentLayout(CSXLayoutObject) nameAttributeLayout]
00000000000020b0 s +[CSXDocumentLayout(CSXLayoutObject) nameAttributeLayout].eh
0000000000002098 s EH_frame1
0000000000001c49 s LC0
...

In TestApp, it is NOT defined (nm TestApp), actually I can't find any method with the category name CSXLayoutObject.
...
0000000100001271 t -[CSXDocumentLayout setDocumentClassString:]
00000001000013a8 t -[CSXDocumentLayout setElements:]
0000000100001490 t -[CSXDocumentLayout setName:]
00000001000014db t -[CSXDocumentLayout(Private) readLayoutDocument:]
0000000100004060 t -[CSXElementList dealloc]
00000001000040b0 t -[CSXElementList elements]
...

Answer: EDIT: Fixed broken link
I suspect you have run into a known problem of categories embedded in static libraries.
If I am right, try to compile with the linker flags -ObjC (and if that is not enough, also -all_load) and your problem should disappear.
Comment: For future readers, I had to add the flag to 'other linking flags' under the 'linking' menu. (ios 6.1, xcode 4.3)
Comment: While this answer is often the solution, the other one, provided by Ace, is a great complimentary one, and covers another possible case.
Comment: The link is broken now, is there an archive of it?
Answer: Even though the answer is already selected, I wish the solution to my issue was here, as simple as it may be. Be sure to check that your class is properly checked in the Target Membership field under the File Inspector pane. If you fail to do so then it's only natural to receive the unrecognized selector sent to class error.
Comment: That was it for me! Thank you kind stranger!


Determine the vaues $p$ such that the following series converge?

Question: Let $a_{n}\geq 0$ and $\sum_{1}^{\infty}a_{n}$ be a convergent series. Determine the values $p$ such that $\sum_{1}^{\infty}\frac{\sqrt{a_{n}}}{n^{p}}$ converge?
Comment: What have you done about finding $p$, aliakbar?
Comment: I know that $\sum\frac{\sqrt{a_{n}}}{n}$ converge
Answer: Hint: $(1)$ Use the Schwarz Inequality, $x_i=\sqrt{a_i}$, $y_i=\frac{1}{i^p}$ to show that there is convergence if $p\gt \frac{1}{2}$. $(2)$ Show we cannot do better by using $a_n =\frac{1}{n\log^a n}$ for suitable $a$.


removing ? and = from php get method

Question: well wat im trying to do is to remove the Question mark from the url like, im using a form and the action of it is lets say city.php depending on wat u enter on the form the url will be like http://mysite/city.php?city=newyork the thing is how can i remove the question mark from the link using .htaccess
Comment: If you remove the city from the link, how will you know what it was? Are you planning on rewriting it to /newyork.php or something like /city.php/newyork?  It might break caching but maybe you're thinking of ``?
Comment: @DerfK ummm no im not trying to use post because the link then wont be able to be bookmarked, a little more explanation: wat im trying to do is to have a dynamic .php page , how the thing works is when i click on a static image the image is send to the .php page, an the php page gets the image title and the image url and displays it on that page, and the get method builds a url with the name of the image etc in other words is like creating links on the fly... but im having dificult on removing the question mark so the link would be clean...
Answer: In your .htaccess file or virtual host configuration do something like this:
RewriteEngine On
RewriteRule ^city/(.*)$ /city.php?city=$1 [P]

This will transparently proxy requests from http://mysite/city/newyork to the server as http://mysite/city.php?city=newyork.
Comment: i try this but doing this the city.php wont work it kinda hides it or doesn't send anything that was submitted...
Comment: Check your log files to see what's happening. Perhaps you don't have mod_rewrite installed? Or you don't have permission to activate it from .htaccess? Or a typo? The log files will tell you how far the request is getting and what errors it encounters.
Answer: I believe you are looking for URL rewriting. http://httpd.apache.org/docs/2.2/rewrite/

removing ? and = from php get method


phpBB 3.0.10 to drupal 7

Question: I have a phpBB 3.0.10 site i want to migrate all the contents of the site to drupal 7.
I want all my users to import from phpBB 3.0.10 to users of drupal 7.
All the forums should be migrated to drupal forums along with their groups and access rules in the phpBB forum.
The users groups should be mentioned.
All the posts and comments should also be imported.
I have tried modules phpbb2drupal and phpbbforum but i was not able to completely migrate it to drupal.
After the migration i will be leaving phpBB 3.0.10 and only be working on drupal 7.
Is there a solution, i have been searching but couldn't find the right solutions.
Thanks for the help...
Answer: use the module migrate, be sure you studied the example and modules like TYPO3_migrate or Wordpress migration.
Migrate has a learning curve, but it is worth it.

phpBB 3.0.10 to drupal 7


Properties of a strange function

Question: Def: $$f(x)=0,\ x\neq 0$$
$$f(x)=\lim_{a\to\infty}\frac 1a, f(x)\neq 0, \ x=0 $$
Is $f(x)$ a legal function? Is $f(x)$ continuous and differentiable?
Comment: $f(x)=1-\frac xx$ has the required properties, it is not continuous but it is differentiable.
Comment: You should find $f(0)$ yourself.
Comment: It's legal.  But it's the constant function f (x)=0.  A function is determined by its values; not by how we choose to describe it.
Comment: That's not a well defined function.  You have not defined what f (0) is.  Just that it isn't 0.  This *is* continuous if 0 is *not* in the domain and f (0 is not defined.  But if f (0) is something other than 0, f is not continuous.
Comment: Edit completed/ Thank you.......
Comment: You really shouldn't make an edit that greatly changes the meaning of the question you posted; you should ask your new question in a separate post.
Answer: Yes. Since
$$\lim_{a\to\infty} \frac{1}{a}=0$$
we have that
$$f(x)=0$$
for all values of $x$. Since $f(x)$ is a constant function, it is both continuous and differentiable.
Answer: Since $\lim_{a \to \infty} 1/a = 0$, your function is simply $0$ for all $x$.
Answer: A function is determined by its values.  It can be described by a human being any way one likes.  This function is nothing more or less than the constant function $f (x)=0$.  You described it in an obtuse (but legitimate) way.  But basically it is the constant function.
It is continuous and differentiable.
Answer: Continuity of a function at a point is when the limit of the function approaching that point is equal to the value of the function at that point. For $x \neq 0$, the function is continuous - however you approach $x$, the limit will be 0, same as $f(x)$. However, for $x = 0$, you have specifically defined the function in a way that it cannot be continuous. Since the function has a discontinuity, it is not everywhere continuous.
Differentiability of a function is similarly defined at individual points, and again your function is differentiable for any $x \neq 0$. But again, your function is not differentiable at $x = 0$, so it is not everywhere differentiable.
That said, for many purposes, a mathematician could work in $\mathbb{R} \setminus \{0\}$ and then treat the function as continuous and differentiable with no problem.
EDIT BASED ON LATEST QUESTION EDIT:
Your latest definition of the function is (copied for posterity): $$f(x)=0,\ x\neq 0$$
$$f(x)=\lim_{a\to\infty}\frac 1a,\ x=0 $$
But you have literally just defined a function that is zero everywhere. The limit that you are using to define $f(0)$ is one that is exactly equal to zero, by any meaningful interpretation of limits.
Comment: "you have specifically defined the function in a way that it cannot be continuous"  I am going to quibble.  The function has not been defined at x= 0 at all.  As such there is nothing to indicate that $f$ has all of $\mathbb R$ as its domain.  As a function $f: (-\infty, 0)\cap (0, \infty) \rightarrow \{0\}$ so that $f(x) = 0$ for all $x\in  (-\infty, 0)\cap (0, \infty)$ and $0$ simply not in the domain at all, then $f$ indeed *is* continuous for all points that *ARE* in its domain.  ... But that is a quibble.
Comment: I suppose it depends on whether $f(x) \neq 0$ implies that $f(x)$ has a value at all. But yes, it's a quibble. And it doesn't matter, because OP has changed what the question actually is, anyway.
Comment: She changed it back?  Okay.  yeah.  It's ambiguous.  But if you you specify f (x) *doesn't equal something, it's not complete unless you indicate what it *does* equal.  Or at least that it equals something.
Answer: Definitely not continuous, since $\lim_{x \to 0} f(x) = \lim_{x \to 0} 0 =0$. Since differentiability implies continuity, it also can't be differentiable.
Comment: Huh.  Definitely *is* continuous.  lim f (x)= lim 0=0 =f (0) so this is compatible with being continuous.
Comment: Ugh.  Sorry.  The question was changed.
Answer: Always use the definitions. If $f(0)\ne 0$ and $f(x)=0$ for all $x\ne 0,$ does $f(x$) satisfy the necessary criterion for continuity at $x=0$? No.
Comment: But f (0) *does* equal 0.  So yes it does satisfy the nescessary condition.
Comment: Argh.  The question was changed.  Sorry.
Comment: June 13/17.Fleablood: If it is your -1 vote then would you do me the courtesy of undoing it?  I see another answer that doesn't match the Q, which was clearly not just amended, but completely changed.
Comment: Can you do a "dummy" edit.  I can't seem to upvote unless the answer gets editted.  You are right.  Your answer is correct for how the question is *now* worded.

Properties of a strange function


Spree Could not find table 'spree_countries'

Question: I have cloned a existing Spree project on Rails 3.2.17.
Rake db:create works but when running migrate, seed or rails s I run into this error.
Could not find table 'spree_countries'

I have tried
rake db:reset

and various spree generators but all give back the same error.
Comment: There's probably an initializer using `Country` model. Check error backtrace and disable this initializer temporarily.
Comment: Solved: There was a custom class calling spree_countries and config was initialising it.
Answer: The Error
This is the error I got when like OP I did anything with Rake:
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:
  relation "spree_countries" does not exist

The Problem
The most common solution for setting the country in Spree is the following:
config/initializers/spree.rb
Spree.config do |config|
  country = Spree::Country.find_by_name('Mexico')
  config.default_country_id = country.id if country.present?
end

This will work fine until you drop the database and try to recreate it - and do not overwrite config/initializers/spree.rb.
Overwrite .../config/initializers/spree.rb? (enter "h" for help) [Ynaqdh] n

While recreating the database the Country table is not available and you hit the Could not find table 'spree_countries' error. It's nasty because the initialization code that causes the bug works for a while and it is only much later the error arises when you decide to drop the database.
The Solution
The code suggested on google groups was to find the country_id and assign it - you can puts the id out or use an SQL query on spree_countries.
config/initializers/spree.rb
Spree.config do |config|
  # Sets default country to Mexico
  config.default_country_id = 157
end


Synchronous child process calls for shell scripting (including CLI) in Node.js 0.10.x

Question: Synchronous child process calls are now available in the versions of Node.js that are under development (i.e. unstable). This is great news for writing shell scripts, as it will allow code like this:
var history = child_process.execSync('git log', { encoding: 'utf8' });
process.stdout.write(history);

However, for code aimed at the current stable version of Node.js (v0.10.30), synchronous child process calls are not available except via external  libraries. The two most popular such libraries appear to be shelljs and exec-sync.
For shell scripts intended for use with v0.10.x, and which must call binaries or other executables and process their output, what are the relative pros and cons of these two libraries or other comparable libraries? Please provide code samples for illustration, if appropriate.
Comment: Well, I'm not asking for opinions, I'm asking for concrete advantages/disadvantages to two precisely specified alternative programming strategies (in this case, using one library vs using another, for the same task). This sort of question has been asked and answered on SO for years. In any case, there's room for [inclusionism](https://en.wikipedia.org/wiki/Wikipedia:WikiProject_Inclusion) on SO/SE :)
Comment: While it's a well-written question, this will probably be closed as too opinion-based :-/
Comment: Thanks. I hope it won't be closed, as it seems perfectly appropriate: essentially a refinement of [this question](http://stackoverflow.com/q/14458508/82216) . However, do say if you think I should flag it for migration to softwarerecs.stackexchange.com or similar
Comment: Hm, I don't know whether it's [on-topic there](http://softwarerecs.stackexchange.com/help/on-topic) either.
Answer: Let's look at three options: the two mentioned in the question, plus execsync.
shelljs
shelljs is much more than a library for calling child processes. Primarily, it is a cross-platform JavaScript implementation of several POSIX utilities and shell builtins: >, cat, cd, chmod, cp, dirs, echo, env, exec, exit, find, grep, ln, ls, mkdir, mv, popd, pushd, pwd, rm, sed, test, which. It also provides a couple of useful functions of its own: error() and tempdir().
Its exec function can be used to run an external executable synchronously.
Syntax example
Using global namespace:
require('shelljs/global');
var version = exec('node --version', {silent:true}).output;
console.log('version ' + version);

Alternatively, using local namespace:
var sh = require('shelljs');
var version = sh.exec('node --version', {silent:true}).output;
console.log('version ' + version);

Key stats/specs

Dependencies: 0
Dependents: 411
Downloads this month: 957851
License: BSD*

Pros

No dependencies.
Can be used via global or local namespace at developer's discretion.
Huge number of dependent packages and users, so likely to remain in use for some time.

Cons

Cannot distinguish a called executable's output to stderr from its output to stdout. Bug?
The shelljs documentation warns, "For long-lived processes, it's best to run exec() asynchronously as the current synchronous implementation uses a lot of CPU. This should be getting fixed soon."

exec-sync / execSync
exec-sync has been retired in favour of execSync. The rest of this section therefore refers to the latter.
The execSync library consists of a JavaScript wrapper around a C++ core. During the installation of execSync, the C++ core is compiled into a platform-appropriate NodeJS binary module.
Syntax example
var sh = require('execSync');
var version = sh.exec('node --version').stdout;
console.log('version ' + version);

Key stats/specs

Dependencies: 1
Dependents: 91
Downloads this month: 20525
License: MIT

Pros

Straightforward once installed.
Large number of dependent packages and users, so likely to remain in use for some time.

Cons

Not dependency-free.
Installation requires the presence of a C++ compiler.
Cannot distinguish a called executable's output to stderr from its output to stdout. Bug?

execsync
Worth mentioning here as it is easily confused with execSync (see above) by any case-insensitive search engine, other algorithm, or human. Confusing matters further, the author of execsync has used the orthography "execSync" at a few points in execsync's code and documentation.
Like execSync above, the execsync library consists of a JavaScript wrapper around a C++ core. During the installation of execsync, the C++ core is compiled into a platform-appropriate NodeJS binary module.
Syntax example
var sh = require('execsync');
var version = sh('node --version');
console.log('version ' + version);

Key stats/specs

Dependencies: 0
Dependents: 3
Downloads this month: 20233
License: NYSL

Pros

No dependencies.

Cons

Inconsistent internal orthography.
Installation requires the presence of a C++ compiler.
Documentation is in Japanese (not a "con" for everyone, admittedly).
Cannot distinguish a called executable's output to stderr from its output to stdout.
Small number of dependents, so presumably less entrenched in Node.js community.
Comment: Thanks :) I've added the text "or other comparable libraries" to the question.
Comment: +1 for answering this yourself. You might even remove the specific packages from the question, to make it more open-ended :-)
Comment: why do we need a library to do this, doesnt spawnAsync do it?
Comment: @SuperUberDuper, no it doesn't. It is for asynchronous use.


c statements to assembly

Question: for a assigment i need to translate some C declarations to assembly using only AVR directives.
I'm wondering if anyone could give me some advice on learning how to do this.
For example:
translate 'char c;' and 'char* d;' to assembly statements
Please note, this is the first week im learning assembly,
Any help/advice would be appreciated
Comment: What advice did your teacher(s) already give you ?  How far have you got with that advice and your own efforts ?
Comment: `char c;` is a variable definition; it's not a statement (it doesn't actually **do** anything).   `a = b + c;` would be a statement.
Comment: Im sorry, changed it to declarations. My teacher didn't really gave any advice, and i won't be able to ask for any either since we are having a week vacation.. The assignments only includes declarations that have to be translated into assembly
Comment: What is going on with these -1's. I have been seeing an increasing number of them for no apparent reason.  How is this bad question?
Comment: @linuxuser27 same here. But we can always vote up to correct.
Answer: First, char c; and char* d; are declarations not statements.
What you can do is dump the assembly output of your C program with the avr-gcc option -S:
# Dump assembly to stdout
avr-gcc -mmcu=your_avr_mcu -S -c source.c -o -

Then you can reuse the relevant assembly output parts to create inline assembler statements.
Look here on how to write inline assember with avr-gcc:
http://www.nongnu.org/avr-libc/user-manual/inline_asm.html
Comment: @Brainscrewer the whole idea is you have to write the C statements in the `source.c` and see how they are translated so you can reuse them...
Comment: I do not have any c program available to dump. I only have statements on paper
Answer: Without a compiler that you can disassemble from (avr-gcc is easy to come by), it may be difficult to try to understand what happens when a high level language is compiled.
you are simply declaring that you want a variable or an address when you use declarations like that.  that doesnt necessarily, immediately, place something in assembly.  often dead code and other things are removed from code by the compiler.  Other times it is not until the very end of the compile process that you know where your variable may end up.  Sometimes a char only ever lives in a register, so for a short period of time in the program that variable has a home.  Sometimes there is a longer life the variable has to have a home the whole time the program is running and there are not enough registers to keep it in one forever so it will get a memory location allocated to it.
Likewise a pointer is an address which also lives in registers or in memory locations.
If you dont have a compiler where you can experiment with adding C code and seeing what happens.  And even if you do you need to get the instruction set documentation for the desired processor family.
http://www.atmel.com/Images/doc0856.pdf
Look at the add operation for example add rd,rr, and it shows you that d and r are both between 0 and 31 so you could have add r10,r23.  And looking at the operation that means that r10 = r10 + r23.  If you had char variables that you wanted to add together in C this is one of the instructions the compiler might use.
There are two lds instructions a single 16 bit word version and one that takes two 16 bit words. (usually the assembler chooses that for you).  rd is between 0 and 31 and k is an address in the memory space.  If you have a global variable declared it will likely be accessed using lds or sts.  So K is a pointer, a fixed pointer.  Your char * in C can turn into a fixed number at compile time depending on what you do with that pointer in your code.  If it is a dynamic thing then look at the flavors of ld and st, that use register pairs.  So you might see a char * pointer turn into a pair of registers or a pair of memory locations that hold the pointer itself then it might use  the x, y, or z register pairs, see ld and st, and maybe an adiw to find an offset to that pointer before using ld or st.
I have a simulator http://github.com/dwelch67/avriss.  but it needs work, not fully debugged (unless you want to learn the instruction set through examining a simulator and its potentinal bugs).  simavr and some others are out there that you can use to watch your code execute.  http://gitorious.org/simavr

c statements to assembly


The ratio, needed to prove a whole number.

Question: If $m,n \in \mathbb{W}=\{0,1,2,3,...\}$ prove that $$\frac{(2n)!(2m)!}{n!m!(m+n)!}\in \mathbb{W} $$
 I tried to divide into cases $$(1)
:m=n\\(2):n>m\\(3):m>n $$ (2),(3) are the same .
(1):$$m=n \to\frac{(2n)!(2n)!}{n!n!(n+n)!}=\frac{(2n)!}{n!n!}=\begin{pmatrix}
 2n \\ n
 \end{pmatrix} \in \mathbb{W} $$
(2):$$n>m \to \frac{(2n)!(2m)!}{n!m!(m+n)!}=\\
\frac{(2n)!(2m)!}{n!m!(m+n)!} $$ at this step ,i get stuck to show $ \in \mathbb{W}$ how can I conclude ?
Is there another idea to prove (like combinational proof) ?
thanks for any help in advance .
Comment: I'm not sure if this is an exact duplicate of [this](https://math.stackexchange.com/questions/215355/prove-that-for-all-non-negative-integers-m-n-frac2m2nmnm-n?rq=1) or not since yours demands that it needs to be a non-negative integer.
Comment: if $m$ and $n$ are non-negative, that expression will never be negative, so it is a duplicate
Comment: Is there some particular reason for renaming $\mathbb{N}$ as $\mathbb{W}$?
Answer: For any prime $p$, by Legendre's Theorem
$$ \nu_p\left(\frac{(2n)!(2m)!}{n!m!(n+m)!}\right)=\sum_{h\geq 0}\left(\underbrace{\left\lfloor\frac{2n}{p^h}\right\rfloor+\left\lfloor\frac{2m}{p^h}\right\rfloor-\left\lfloor\frac{n}{p^h}\right\rfloor-\left\lfloor\frac{m}{p^h}\right\rfloor-\left\lfloor\frac{n+m}{p^h}\right\rfloor}_{\color{red}{\geq 0}.}\right)$$
Comment: It might be good to prove the inequality.


Need windows script to run simple for loop across all the parameters listed in a text file

Question: I need to run windows "net view" command against each of these values in test.txt file.
test.txt contains a list of servers as below:
\\LB042073
\\LB042425
\\LB042507
\\LB045196

I need to run "net view" command against each of these servers.
Below command does not work:
Get-Content test.txt | %{& net view}

Thanks in advance.
Answer: In PowerShell:
Get-Content test.txt | %{net view $_}

Get-Content - read the file outputting each line individually
| - Pipeline character. It works the same in windows and *nix. It passes the output of one command to the input of the next command
% - Alias for ForEach-Object. This is a loop construct that will do some code for each object in a list
{ - Beginning of the code block
net view $_ - runs the net.exe program passing it two parameters view and the contents of the special $_ variable. The $_ variable in a ForEach-Object loop holds the input item for the current iteration of the loop.
} - End of the code block
Comment: Can you please explain it a bit?
Comment: This helps but I need to run a command against each of these values.

test.txt contains a list of servers as below:

    \\LB042073
    \\LB042425
    \\LB042507
    \\LB045196

I need to run "net view" command against each of these servers.
Comment: Above command list only the servers multiple times and does not really run "net view" against each line.

PS C:\Users\a549145> Get-Content test.txt | %{& net view}
Server Name            Remark
---------------------------------------------------------------
\\FSIFAXA930892
\\LA909831

The command completed successfully.

Server Name            Remark
----------------------------------------------------------------
\\..
\\..
command completed successfully.

Server Name            Remark
----------------------------------------------------------------
\\..
\\..
command completed successfully.
Comment: Aaaah...now that you completely changed the question that you were asking, I will change my answer.


Probabilistic interpretation of sum of quantile functions

Question: We know that the weighted sum of CDF
$$
F(x) = w_1 F_1(x) + w_2 F_2(x), \,\, w_1 + w_2 = 1
$$
is the CDF of the mixture distribution.
Is there a probabilistic interpretation for weighted sum of quantile functions below?
$$
Q(p) = v_1 Q_1(p) + v_2 Q_2(p) = v_1 F_1^{-1}(p) + v_2 F_2^{-1}(p), \,\, v_1>0 , v_2 > 0,p\in[0,1]
$$
Answer: It's always hard to prove a negative. However, I have never seen such an interpretation. The naive idea that the weighted sum of quantiles would be the corresponding quantile of the mixture distribution is of course false.
I would be interested in being proven wrong and look forward to downvotes (and actual such interpretations).


Introduction to Gaussian mixture models

Question: First of all, I am sorry if this question is not acceptable by some of the readers. However, I really read many, many sources about Gaussian mixture models, but all what I found was a short tutorial or even strong mathematical book. I do not have a problem with math, however, I really would like to read some introductory textbook about Gaussian mixture models. These books are very easy for deep understanding and keep reading. I just wonder if someone can advise me with some helpful books about Gaussian mixture models. How would these book rank, for example, difficult, suitable for beginner or very advanced and so on?
Again, I am sorry if this is not an appropriate question.
Answer: Well I came here because I had the same question, but perhaps my few results could be helpful. Mostly we are talking about some standards here, but I will point out some of the GMM specific content.
The best practical online example I could find in my non-exhaustive search was this Kaggle contest winner and his github. The MATLAB docs have an okay summary, plus MATLAB code if you like that.
The following are math/theory textbooks (for the most part), sprobably none of these will make much sense without some formal education in the subject or incredible motivation, it seems the tutorial writers have no love for GMMs.
I'm guessing you've looked at Elements of Statistical Learning before. There is good material on GMM, but it's sort of scattered throughout the book. Unfortunately, An Introduction to Statistical Learning by the same authors has nothing that I can find about GMMs, or mixture models of any kind.
Pattern Recognition and Machine Learning by Christopher Bishop has a presentation of the math behind GMM and the EM algorithm that was just a little easier for me to read than Elements. Where this text really shines is a much deeper exploration of the EM algorithm, applying it to various other cases.
Machine Learning: A Probabilistic Perspective by Kevin P. Murphy has some nice content on other types of mixture models and the general concept of clustering with a mixture model.

Introduction to Gaussian mixture models


Prove that $\lim\limits_{n \to \infty}\frac{a_1b_1+\cdots+a_nb_n}{b_1+b_2+\cdots+b_n}=a$

Question:
Suppose $(a_n)$ and $(b_n)$ are two given sequences for which $b_n>0$ and $\lim\limits_{n→∞}(b_1+\cdots+b_n)=\infty$ and $\lim\limits_{n\to\infty}a_n=a$. Prove that$$\lim_{n\to\infty}\frac{a_1b_1+\cdots+a_nb_n}{b_1+\cdots+b_n}=a.$$

try:
let $\epsilon > 0$
Let $B_n = \sum_{i=1}^n b_i $ and given it is that for any $\alpha > 0$ we can choose $N$ so that  $n > N$ implies $B_n > \alpha $. And since $a_n \to a$,  take $M > 0$ such that for all $n > M$ one has $|a_n - a| < \epsilon/b_n $.
${\bf one \; can \; take \; \alpha = n } $ in the first line:
Now, note that
$$ | \dfrac{ a_1 b_1 + ... +a_n b_n }{b_1+... b_n } - a | = | \dfrac{ a_1 b_1 + ... + a_n b_n - a B_n }{B_n} | = \dfrac{1}{B_n} |(b_1 (a_1 - a ) + ... + b_n (a_n -a ) |  < \dfrac{ n \epsilon }{ n } = \epsilon$$
for any $n > \max(N,M)$
Is this a correct proof?
Comment: You may not find such $M$ such that $\mid a_n -a \mid < \epsilon/b_n$.
Comment: You could also use [Stolc-Cesaro theorem](https://math.stackexchange.com/questions/100338/limit-of-quotient-of-two-series/100542#100542). BTW if the main question is to check your proof, you can add ([tag:solution-verification]) tag to mark this.
Comment: Where is this question from?
Comment: Yes. For a single $n>M$ such $\epsilon$ can exist, but not for all $n>M$. Then $\epsilon$ shall vary with $n$.
Comment: Martin, that very nice link, thanks! I just wanted to see whether I was working correctly and in general feedback for my solution and how to improve... I certainly dont look for solutions but for understanding
Comment: @Theoneandonly add *solution-verification* tag when you want your solution to be validated.
Answer: Almost correct. You may not find such $M$ for $\mid a_n -a \mid < \epsilon /b_n$ since the LHS depends on $n$ also. But you just need $\mid a_n - a \mid < \epsilon$ and do the almost same thing. You choose $M$ first then you choose $N$ such that $B_n > \dfrac{|(b_1 (a_1 - a ) + ... + b_K (a_K -a ) |}{\epsilon}$
Now let $K=\max \{M,N\}$ then for any $n>K$
$| \dfrac{ a_1 b_1 + ... +a_n b_n }{b_1+... b_n } - a | = | \dfrac{ a_1 b_1 + ... + a_n b_n - a B_n }{B_n} | = \dfrac{1}{B_n} |(b_1 (a_1 - a ) + ... + b_n (a_n -a ) |  \leq \dfrac{1}{B_n} |(b_1 (a_1 - a ) + ... + b_K (a_K -a ) |+\dfrac{1}{B_n} |(b_{K+1} (a_{K+1} - a ) + ... + b_n (a_n -a ) |< \epsilon + \epsilon\dfrac{b_{K+1}+\cdots+b_n}{B_n}<2\epsilon$.
Comment: perfect1 thanks a lot !
Comment: You're welcome. ^^


Flood protection - FloodFill or is there a better way?

Question: I am doing tasks for practicing and improving skills, but I'm having hard time solving this one:

You have a map with size w * h. On each box of this map is wall(flood
  protection) or nothing.   Water can flow in eight directions and flows
  on each box at the edges of  the map. Of course, water can not flood
  the box where is built flood protection. You will get size of the map,
  number of walls and position of each wall.
At the beginning the map is empty. Your task is after placing  each
  piece of the wall tell how big area is protected from water.

So, I have code that works. But too slow. Limits are : size of the map w and h (1≤w,h≤2000)
number of walls : n (1≤n≤w×h)
I tried 8-way FloodFill algorithm and then I improved it to 8-way ScanlineFill. It is just too slow, it runs out of time in half of the test entries. I will post my code if you will want it.
So my question is: How can I improve my algorithm to be even faster? Or am I completely wrong with my choice of algorithms and there is a better way? Thanks for your suggestions.
Test entry:
<code>Input:

4 4  //size w and h
10   // number of walls
1 1  //position of wall - first x, second y  coordinate;
1 2
1 3
2 1
2 3
3 1
3 2
3 3
2 2
3 4

Output:

1  //how big are is covered against flood
2
3
4
5
6
7
9
9
10
</code>

Explanation of example input: The first 8 part of the wall of flood
  protect area size 3 x 3. The ninth part has absolutely no effect,
  because the box (2,2) has already been protected. The tenth part does
  not conclude any territory and therefore would contribute only its
  surface(add only 1).

My code:
<code>#include<iostream>

using namespace std;
int **ostrov;
int area;

#define stackSize 16777216
int stack[stackSize];
int stackPointer;
int h, w;

bool pop(int
    &x, int &y)
{
    if (stackPointer > 0)
    {
        int p = stack[stackPointer];
        x = p / h;
        y = p % h;
        stackPointer--;
        return 1;
    }
    else
    {
        return 0;
    }
}

bool push(int x, int y)
{
    if (stackPointer < stackSize - 1)
    {
        stackPointer++;
        stack[stackPointer] = h * x + y;
        return 1;
    }
    else
    {
        return 0;
    }
}

void emptyStack()
{
    int x, y;
    while (pop(x, y));
}

//The scanline floodfill algorithm using our own stack routines, faster
void floodFillScanlineStack(int x, int y, int newColor, int oldColor)
{
    if (oldColor == newColor) return;
    emptyStack();

    int y1;
    bool spanLeft, spanRight, spanDDLeft, spanDDRight, spanDULeft, spanDURight;

    if (!push(x, y)) return;

    while (pop(x, y))
    {
        y1 = y;
        while (y1 >= 0 &&ostrov[x][y1] == oldColor) y1--;
        y1++;
        spanLeft = spanRight = spanDDLeft = spanDDRight = spanDULeft = spanDURight = 0;
        while (y1 < h && ostrov[x][y1] == oldColor)
        {
            if (ostrov[x][y1] == oldColor)
                pocet++;
            ostrov[x][y1] = newColor;
            if (!spanLeft && x > 0 && ostrov[x - 1][y1] == oldColor)
            {
                if (!push(x - 1, y1)) return;
                spanLeft = 1;
            }
            else if (spanLeft && x > 0 && ostrov[x - 1][y1] != oldColor)
            {
                spanLeft = 0;
            }
            if (!spanRight && x < w - 1 && ostrov[x + 1][y1] == oldColor)
            {
                if (!push(x + 1, y1)) return;
                spanRight = 1;
            }
            else if (spanRight && x < w - 1 && ostrov[x + 1][y1] != oldColor)
            {
                spanRight = 0;
            }
            if (!spanDDLeft && x > 0 && y1 + 1 < h && ostrov[x - 1][y1 + 1] == oldColor)
            {
                if (!push(x - 1, y1 + 1)) return;
                spanDDLeft = 1;
            }
            else if (spanDDLeft && x > 0 && y1 + 1 < h && ostrov[x - 1][y1 + 1] != oldColor)
            {
                spanDDLeft = 0;
            }
            if (!spanDDRight && x + 1 < w && y1 + 1 < h && ostrov[x + 1][y1 + 1] == oldColor)
            {
                if (!push(x + 1, y1 + 1)) return;
                spanDDRight = 1;
            }
            else if (spanDDRight && x + 1 < w && y1 + 1 < h && ostrov[x + 1][y1 + 1] != oldColor)
            {
                spanDDRight = 0;
            }
            if (!spanDULeft && x > 0 && y1 > 0 && ostrov[x - 1][y1 - 1] == oldColor)
            {
                if (!push(x - 1, y1 - 1)) return;
                spanDULeft = 1;
            }
            else if (spanDULeft && x > 0 && y1 > 0 && ostrov[x - 1][y1 - 1] != oldColor)
            {
                spanDULeft = 0;
            }
            if (!spanDURight && x + 1 < w && y1 > 0 && ostrov[x + 1][y1 - 1] == oldColor)
            {
                if (!push(x + 1, y1 - 1)) return;
                spanDURight = 1;
            }
            else if (spanDURight && x + 1 < w && y1 > 0 && ostrov[x + 1][y1 - 1] != oldColor)
            {
                spanDURight = 0;
            }
            y1++;
        }
    }
}

int main()
{

    cin >> h >> w;
    h += 2;
    w += 2;
    ostrov = new int*[w];
    for (int i = 0; i < w; i++) {
        ostrov[i] = new int[h];
        for (int j = 0; j < h; j++)
            ostrov[i][j] = 1;
    }
    int n;
    cin >> n;
    int color = 1;
    int act = 0;  //actual color
    int prev = 0; //last color
    for (int i = 0; i < n; i++) {
        color++;
        suc = color % 2;
        prev = (color - 1) % 2;
        int x, y;
        cin >> x >> y;
        if (ostrov[y][x] == act) {
            cout << (w * h) - area << endl;
            color--;
            continue;
        }
        area = 0;
        ostrov[y][x] = 5;
        floodFillScanlineStack(0, 0, act, prev);
        cout << (w * h) - area << endl;
    }
}
</code>
EDIT:
Now I realized that this enclosed area doesn't need to be rectangle or square, it could be polygon. Also, there could be more polygons in the map. And after I get a coordinates of part of the wall I must tell:
1.) if it make some polygon(enclosed area) - if yes, how big area which was't enclosed before I must add to are which was enclosed;
2.) if it doesn't make some polygon and it isn't in area which was already enclosed, add to enclosed area number 1(because this box of map water can't flood);
   3.) if it is in area which was already enclosed, add nothing, because it doesn't enclose any more area.
Comment: @Let_Me_Be except the #1 most important criteria for anything to be on-topic on [codereview.se], is that the *code to be reviewed must be included in the question*.
Comment: If the boundary is a barrier and the flood starts at (0, 0), couldn't you just wall off (0, 0) with three walls at (1, 0), (0, 1) and (1, 1) and prevent the water from flooding the remaining O(w*h) of the map? If you have only two or fewer walls to place, you can't prevent any non-wall areas from being flooded.
Comment: Well, you didn't provide your code, so it's kind of impossible to help. Also this sound like it would fit more on https://codereview.stackexchange.com/
Comment: I do not think that this would fit more on codereview, because I want some idea to solve task faster than with Floodfill, not review of my code
Comment: @JozefBugoš Where did you find this question ?
Comment: @fjardon - there is a website from my country (Slovakia), where are some tasks to help you to improve your skills, when you are beginner at programming. I have done a lot of these tasks, but now I found 3 tasks, which I can't  do and this is one of them.
Comment: @JozefBugoš Can you provide a link ? There may be more info on the original website and I'd like to review the other testcases to better understand what complexity is expected.
Comment: @fjardon - link is here : [this particular task](https://www.ksp.sk/ulohy/zadania/1042/);    [archive of tasks](https://www.ksp.sk/ulohy/)  but it is in Slovak language, so I don't know if it will be helpful for you.
Comment: @fjardon from this [archive](https://www.ksp.sk/ulohy/14/) I have done tasks from 1 to 5, and I've problem solving 6.,7. and 8. task
Comment: @JozefBugoš: Have you tried to find a way to update the result, instead of recomputing from scratch for every new wall segment?  Probably a data structure other than just the grid will be useful, but I don't have any specific suggestions for that.  For speeding up your existing code, don't emulate 2D arrays with an array of pointers.  Make a single large array, and index it with `a[ h * max_w + w ]` or similar.  Looking up a value in your `ostrov` global variable requires a load from memory to get the pointer for that row's storage array, then another load within the row.
Comment: Also, pass things as function arguments.  Having many global data structures makes it harder to keep tracks of which functions look at / modify what.  When you say your code is too slow, did you compile with optimization on?  How slow is it?  How fast are you hoping it could be?
Comment: Using a single array, instead of pointers to arrays, should be a big speedup.  Then the addresses of the neighbouring elements are all easy to determine from the pair you pop off the stack (already compressed into x*h + y form!)  For your current data structure, it'd be better to store pairs on the stack, rather than having to compress and decompress them with integer division.
Comment: @Peter Cordes I will try it, but I don't think it will be enough. There must be another way, probably FloodFill isn't good choice... It is too slow for 6th test entry and there 4 more with bigger size of the map. I tried to find a way to update the result, but it is impossible, at least i think so, because I just can't use FloodFill on some selected area, because then the map would have lot of different values in the array and it would be impossible to apply FloodFill again, 'cause it needs just one old color and one new color
Comment: (1) Where does the flood fill start from? (2) Is the boundary of the map a barrier, or does the water wrap around the edges?
Comment: @Patrick87 I added one extra layer to every side of array, so flood fill starts now on coordination [0,0]  and the boundary of map is a barrier, if I understood you correctly.
Comment: @Patrick87 You don't understand the task. At the beginning the map is empty. But I wiil get position of part of wall and after placing this part to the map I must print number of area which water can't flood. Also, Flood start from every box on edges, so at (0,0), (0,1) (0,...w); (1,0), (1, ...h); etc
Comment: I see. Well then, are you looking for proof of the following logical argument? Only a closed path of walls will enclose more area than the walls themselves occupy; the optimal closed path will be convex, since any concave path could be changed to a convex one that encloses more area; when choosing points on a discrete lattice, "convex" is going to imply a rectangle of some kind; and of all rectangles, the one enclosing the most area will be the longest, most square, shape that fits on the map. That last condition leaves some room to search but searching that is vastly more efficient than
Comment: @Patrick87 I am not sure if this is it. Now I realized that this enclosed area doesn't need to be rectangle or square, it could be polygon. Also, there could be more polygons in the map. And after I get a coordinates of part of the wall I must tell: 1.) if it make some polygon(enclosed area) - if yes, how big area which was't enclosed before I must add to are which  was enclosed; 2.) if it doesn't make some polygon and it isn't in area which was already enclosed, add to enclosed area number 1(because this box of map water can't flood); 3.) if it is in area which was already enclosed, add
Comment: nothing, because it doesn't enclose any more area;                                                   I will edit my question with explanation of input which I gave as example.
Comment: Based on your edit and a closer reading of the question - it sounds like you're not placing the walls at all. The input file describes where the walls are, and your only job is to say for each line how many squares aren't flooded. If that's right, I have an idea I'll put in an answer.
Comment: @Patrick87 Yes, I'm not placing the walls, they are part of input. You are completely right. I'm sorry if it wasn't clear enough, it was just my translation of the task and English isn't my native language. If you have an idea I will be very grateful.
Answer: Here's a thought that might help. The only way to enclose more space than is occupied by the walls themselves is to create a closed path of some kind. Consider what performing a 4-way flood fill starting at the point a new wall segment is placed would accomplish. It would (with minor modification) allow you to detect a closed path - and alert you to the fact that there are non-wall spaces which are safe from flooding.
Really, this will probably be better to think about as a sort of depth-first search where you're looking for the original point to appear a second time. You'll want to continue the search as one new wall segment may complete a number of closed paths (actually, this is probably not true; to be a barrier against 8-way floodfill, the last required piece of wall would only belong to one new loop formed (unless you were placing it inside some other shape already formed).
Once you have detected a closed loop, you need only fill in the interior squares with some other color (if white is blank and black is walls, maybe red or something); any future walls on red squares don't help. Figuring out how to fill the interior is now the only problem - and it's an easy one at that. Simply check squares all around the new wall. Once you find a square, scan either horizontally or vertically (depending on your direction from point) and see if you cross over the path again. If you cross through an odd number of times, you're inside the shape; if an even number of times, you're outside. There will be some blank space(s) around the new wall piece that completes a closed path, since otherwise, any loop must already have been closed.
Phew. I think that should be significantly faster than flood-filling at each iteration. Still not a walk in the park, but some food for thought.
Comment: Thanks! I will look at it and try it. I'll notice you then.
Comment: @Patrik87 I was thinking about your idea and my conclusion is that original DFS which detect cycle won't work for one reason, it detect only one cycle, while there may be longer cycle - and I need the longest cycle. If I find it, I will check where is the closed area and fill it with my FloodFill algorithm,but I need the longest cycle. I've found this [article](http://stackoverflow.com/questions/12367801/finding-all-cycles-in-undirected-graphs), but I don't understand code given by Alex Kemper. Could you explain it to me, or rewrite it to C++? Also I need to check the cycle only for one vertex


Android detect missed call

Question: I am attempting to have my application recognize when there is a missed call. I have created a BroadcastReceiver that detects when the phone's state has changed. Here is my onReceive() method:
public void onReceive(Context context, Intent intent) {
    boolean ringing = false, callReceived = false;
    String callerPhoneNumber = "";
    String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);

    if (TelephonyManager.EXTRA_STATE_RINGING.equals(state)) {
        ringing = true;
        Bundle bundle = intent.getExtras();
        callerPhoneNumber= bundle.getString("incoming_number");

        if (ringing) {
            Toast.makeText(context, "Phone call from: " + callerPhoneNumber, Toast.LENGTH_LONG).show();
        }
    }

    if (TelephonyManager.EXTRA_STATE_OFFHOOK.equals(state)) {
        callReceived = true;
        Toast.makeText(context, "Call received.", Toast.LENGTH_LONG).show();
    }

    if (TelephonyManager.EXTRA_STATE_IDLE.equals(state)) {
//          Toast.makeText(context, "Phone is idle", Toast.LENGTH_LONG).show();

        if (ringing) {
            Toast.makeText(context, "ringing is true", Toast.LENGTH_LONG).show();
        }

//          if (ringing && !callReceived) {
//              Toast.makeText(context, "It was A MISSED CALL from : " + callerPhoneNumber, Toast.LENGTH_LONG).show();
//          }
    }

The issue I am having is the application detects when the phone is ringing, sets ringing to true, and shows the appropriate toast message. However, when the phone's state is idle, it does not enter the if (ringing) statement to show the ringing is true toast message. However, if I comment in the toast message just above it, it will correctly print that the Phone is idle.
Is it possible that ringing is being reset to false somewhere between the phone ringing and the phone becoming idle again?
Answer: You can not store any "state" information in a broadcast receiver. If you want to do a comparison old state / new state, I think you can use a service.
Comment: I strongly suggest you to NOT use static variable. The OS can unload your class from memory and you can loose the information anyway. Use a service to keep your data around.
Comment: exact, when onReceive is called it's a new instance, so no previous values are keep. You can keep this on preferences between BroadcastReceiver calls
Comment: Thanks, I made it a static variable and it is working well now.
Comment: @greywolf82 is right. I am also experiencing the same problem with BroadcastReceiver.

Android detect missed call


Is the idea of "Zeno's Paradox" indirectly assumed in every statistical model?

Question: I have more of a philosophical question :  Is the idea of "Zeno's Paradox" indirectly assumed in every statistical model?
In philosophy, there is an old concept first attributed to the Ancient Greek philosopher Zeno of Elea called "Zeno's Paradox". As I understand, this actually includes several similar paradoxes - each one of them being loosely related to the other. In short, they can be summarized as such:

In other words - if a man running a 10 KM race, he first needs to run the first kilometer. Before he can the first kilometer, he must first run the first meter - and before he can run the first meter, he must first run centimeter. And of course, before he can run the first centimeter, he must run the first millimeter - and this is an endless cycle. But by this logic - shouldn't the runner (paradoxically) be stuck in the same position forever, since he has infinite denominations of a meter to complete?
I have always wondered if this above paradox is implicitly assumed in statistical modelling - for example, if you take the decision boundary "learned" by any statistical model (e.g. random forest):

Do we assume that if the covariate values of some data point (e.g. the black point in the second picture) are "so infinitesimally close" to another "neighboring" data point - Zeno's Paradox would "ensure" that the response value for both of these data points must be the same (i.e. "immobilize them")? For example, the points (0.543, 0.677, "Orange") and (0.543331, 0.677771, "Orange") are so similar - they "must" share the same response value? On the other hand, both of these points might suffer from the "Omitted Variable Bias" (OVB), and actually have differing values of other variables which make them different.
Similarly, if two neighboring data points are "too close" (e.g. Euclidean Distance) to one another, do we assume that they are in essence the same point?
I know on one hand this is a silly question, and on the other hand it's strikingly evident - but is this idea of "Zeno's Paradox" in the background of every statistical model, and  thereby we have reasons to believe that Zeno's Paradox is fundamentally engrained within the nature of physical objects and phenomena and the universe itself? If the measurements of one data point infinitesimally digress away from the measurements of another data point - are they still the same data point?
For example, is the likelihood of "infinitesimally different observations" the same? Using the R programming language, I showed an example where the likelihood of observing similar points is calculated (using the "dnorm()" function) given a Normal Distribution with Mean = 11 and Standard Deviation = 0.1 *:

In the end, is Zeno's Paradox something so universally evident, that nature (and data produced from nature) can not escape this paradox? If two data points are very close to each other, do statistical models treat them as basically identical?
*** Note**: I can provide the R code for this graph if someone is interested
Comment: Are you considering continuity of the likelihood function wrt the data a paradox?
Answer: Frame challenge: Zeno's Paradox is an illusion, or plausible yet invalid line of reasoning which results by ignoring or failing to recognize the fact that the runner requires successively decreasing time to cover the infinitely decreasing denominations of distance and can reach the goal in finite time at some constant speed measurable with finite distance per unit of finite time.
Therefore, there is no "universally evident" phenomenon which Zeno's Paradox represents.
Comment: @ Alexis: Thank you so much for your answer! Maybe Zeno's Paradox was the wrong metaphor for my question - I was trying to ask the basic question : if two data points are very close to each other, do statistical models treat them as basically indentical?
Comment: @stats555 That sounds a good separate question to ask! :)


EF6 erro de EntityValidationErrors em propriedade preenchida

Question: Estou com um problema semelhante em duas aplicações ASP.NET com Entity Framework.
Quando tento atualizar uma entidade que já possui todos os atributos obrigatórios preenchidos recebo uma exceção de EntityValidationErrors, no entanto essa propriedade que esta descrita no validarion esta preenchida.
O mais estranho é que se coloco o breakpoint e verifico os atributos do objeto eles estão todos preenchidos e não causa o erro.
Em uma das aplicações estou contornando esse problema fazendo a propriedade receber ela mesma ou simplesmente acessando a propriedade e jogando seu valor em uma variável qualquer:
ComentariosBlog model = _comentariosBlogNegocios.GetById(idComentatio.Value);

if (model == null)
    return HttpNotFound();

model.Ativo = status.Value;
var teste = model.Publicacao; //<----Contorno
idPost = model.PublicacaoId;
_comentariosBlogNegocios.Salvar(model);

Já tenho um bloco de Try Catch que trata esse erro, o problema é que o objeto esta com todas as propriedades obrigatórias preenchidas e tenho que fazer uma "gambi" para que ele não gere erros como esta no código acima! O simples fato de acessar a propriedade e jogar ela em uma variavel qualquer já para de dar erro, mas preciso de uma solução mais correta para esse problema, como falei isso é somente um "gambi"!
Segue abaixo os detalhes do erro que é gerado:

Nesta imagem podemos ver que a propriedade mencionada já esta preenchida:

Aqui é a mensagem de erro dentro do try catch:
Comment: possível duplicata de [Como corrigir o EntityValidationErrors](http://pt.stackoverflow.com/questions/17644/como-corrigir-o-entityvalidationerrors)
Comment: Já existe um tratamento de erro para saber qual a propriedade que o EF diz que não esta preenchida. O problema é que essa propriedade já esta preenchida e não é um simples problema de tratamento de EntityValidationErrors.
Comment: Preciso que você explique na sua pergunta como é feito este tratamento de erros. Há diversos tipos de validação que são feitos pelo `DefaultModelBinder`, não apenas o do campo preenchido ou não.
Comment: Boa tarde @CiganoMorrisonMendez, desculpe a minha ignorância no assunto mas eu já havia feito a validação como foi recomendado na publicação [link]http://pt.stackoverflow.com/questions/17644/como-corrigir-o-entityvalidationerrors[link]. No entanto quando coloco o breakpoint e verifico as propriedades do objeto que estou tentando salvar, a propriedade que é apontada pelo DbEntityValidationException é uma propriedade que possui valor, mas se antes do SaveChanges() eu colocar uma variável teste recebendo o valor da propriedade o código não gera exceção.
Comment: Qual o erro que aparece em `ve.ErrorMessage`, na solução já mencionada?
Comment: @CiganoMorrisonMendez fiz uma edição na pergunta com os prints dos erros, não sei se isso ajuda?
Comment: Coloque por favor o seu `Model` na pergunta. Me chamou a atenção uma coisa na sua tela.
Comment: @CiganoMorrisonMendez você diz a minha entidade conforme print que inseri agora?
Answer: Seu Model está errado. A propriedade de navegação:
public virtual PublicacaoBlog Publicacao { get; set; }

Não pode ser decorada com [Required] porque ela não será salva. O correto é PublicacaoId receber a decoração, porque este sim será salvo.
Já este preenchimento:
var teste = model.Publicacao; //<----Contorno

Atesta como tem coisa errada no seu projeto inteiro. É fácil de ver por aqui:
ComentariosBlog model = _comentariosBlogNegocios.GetById(idComentatio.Value);
...
_comentariosBlogNegocios.Salvar(model);

O Entity Framework já implementa um repositório e NÃO é necessária a implementação de uma camada de "serviços", "negócio" ou qualquer coisa que seja, porque isso é papel do Controller fazer. Eu escrevo extensivamente sobre isso há tempos, então vou mencionar de novo:

Entity Framework DDD Infra repositório Genérico
Unidade de trabalho (Unit of Work) com repositório
Lugar em que devem ficar métodos de interação do CRUD com o banco em ASP.NET MVC
problema com update Entity Framework 6
Camada de Aplicação

Não adianta falar que "o MVP tal falou que é boa prática". Não, não é.

Aplicar DDD no MVC não é boa prática;
Aplicar camada Service em projeto MVC não é boa prática;
Isolar Controllers e Models em DLL's diferentes não é boa prática;

O que você faz na linha que marquei é fazer o proxy dinâmico virar um objeto, que preenche corretamente a chave estrangeira do objeto, e que portanto salva. Para resolver, coloque o [Required] no campo correto para ele, ou seja:
[Required]
public int PublicacaoId { get; set; }

Comment: Muito obrigado @CiganoMorrisonMendez, muito obrigado mesmo! Isso explica vários problemas que estou tendo no outro projeto. Eu imaginava que estava fazendo tudo corretamente e nem imaginava que estava cometendo um grande erro na arquitetura. Gostaria de agradecer também pelos links esta ajudando muito a esclarecer algumas outras dúvidas!!!


Which Algorithms for predictive recommendation?

Question: I have a training data set with 10m user ratings of movies, (expanded MovieLens) and 25 features (movie information, release, genre etc).
I want to design and build a recommendation system that will predict user ratings on movies, and recommend their "top x unseen movies".
What algorithms shall I use to predict user ratings on items, they take a set scale from 0.5 to 5.
I've read a lot of literature amount techniques, SVD, Decision Trees, Collaborative Filtering etc, but I'm finding it hard to choose a specific model.
Answer: I recommend you to have a look at ALS (alternating least squares) algorithm, a great implementation can be found in Spark's MLLib library.
It is based on the Collaborative filtering (CF) recommendation algorithme family.
With a model-based approach that aim to fill in the missing entries of a user-item association matrix.Users and products are described by a small set of latent factors that can be used to predict missing entries.
MLlib uses the alternating least squares algorithm to learn these latent factors. And it support explicit and implicit feedback for user preferences.
A complete exemple for implementing a recommending system using Spark (PySpark) and MLib can be found here.
Comment: This looks great! I had already looked into ALS but this animation is fantastic. Is this implementation going to be able to handle a matrix that has 28k columns (items) and 140k rows (users), with around 99.5% sparsity?
Comment: The implementation is based on spark, this is the point ... we are talking about big data.
Comment: Yeah I was a bit naive and didn't look at the implementation enough. It's using the same data set as I am so it should be fine!
Comment: Please mark the answer as correct, If you like it.
You should appreciate the effort that somebody puts into answering,This discourage people to help you in the future.


Suppose Kn decomposes into edge-disjoint triangles. Prove that 6 | n − 1 or 6 | n − 3.

Question: My problem is finding a way to prove this. I was thinking that any Kn graph could have at least one triangle as long as n is 3 or higher. Other than that I do not know where to go with proving this is true.
Comment: Hint: Count the edges in two different ways.
Comment: I'm not familiar with the notation $K_n$.  Would you mind explaining?
Comment: The notation $K_n$ means that a graph of n vertices is created with a clique on n vertices. For example, if we have $K_4$ then a graph is created with 4 vertices with each vertice having an edge connecting to every other vertice.
Answer: Every vertex $v$ must have even degree, as each triangle will account for two edges with vertex $v$, and every edge belongs to a triangle.  Thus $n$ is odd.
Combining with $3|\frac{n(n-1)}2$ we get the result.
Answer: Hint: To show this, you want to show that $n$ is odd and that $n$ is not equivalent to $2\bmod 3$. It's good to do those separately.
For each part, it's useful to look at some examples. Why can't you split the edges of $K_4$ into three edge-disjoint triangles? How about $K_5$? Try counting things, like degrees or the total number of edges.