Couldn't use Get-WinEvent from remote computer in VLAN

Question: The remote computer are Win-10 VM in a VLAN.
We only have a few ports open in VLAN, including 3389 for Remote Desktop, 5985 & 5986 for powershell.
Remote Desktop works well.
But I couldn't to use powershell to remote debug on those computers,
If I run
Get-WinEvent -LogName System -Credential domain\test_user -ComputerName 10.100.155.1

I get this error
Get-WinEvent : The RPC server is unavailable

If I use invoke-command to execute the same script,
Invoke-Command -ComputerName 10.100.155.1 -Credential domain\test_user -ScriptBlock {Get-WinEvent -LogName System -Credential domain\test_user -ComputerName 10.100.155.1}
I will get another error:
[10.100.155.1] Connecting to remote server 10.100.155.1 failed with the following error message : Access is denied.

I have tried many solutions on internet, unfortunately, none is working. For example, I have checked if the services are running,  if the firewall allows remote event management on remote computer, they looks alright.
Any idea where could be wrong?
Comment: Have you tried passing a credential object into -Credential? $x = Get-Credential
Comment: RPC != WinRM...
Comment: Possible duplicate of [Powershell remoting with ip-address as target](https://stackoverflow.com/questions/6587426/powershell-remoting-with-ip-address-as-target)
Answer: Your problem is two-fold.

You cannot use WinRM (Invoke-Command) with an IP address.  It uses Kerberos and Kerberos requires a DNS name.
You're passing your credentials and computername twice.

This should work without a problem:
$InvokeArgs = @{
    ComputerName = 'Computername.domain.com'
    Credential   = (Get-Credential -Credential domain\test_user)
    ScriptBlock  = { Get-WinEvent -LogName System }
}
Invoke-Command @InvokeArgs

Comment: Thanks.  But we don't use DNS for those machines, so they don't has DNS name. Outside VLAN,  I can only access them by IP address.  Any solution to this scenario?
Comment: I also tried to use Authentication = Negotiate, but I still get **Access Denied** Error
Comment: @Jim: psexec from sysinternals
Answer: Access Denied is an Authentication Issue, double check your username and password.
I was working on a similar problem, trying to fetch count of system logons. Here's what worked for me:
$fetchEvents = { Get-WinEvent -FilterHashtable @{
Logname='system'
ProviderName='Microsoft-Windows-Winlogon'
StartTime=(get-date).AddDays(-10)
ID = 7001
} | Format-Table -Property TimeCreated, UserID, ID, MachineName }

Invoke-Command -ComputerName $ServerList -Credential $creds -ScriptBlock $fetchEvents


Braess's paradox

Question: Let's consider the Braess's paradox.
I have question how were computed the Nash Equilibrium points with values $80$ and $85$ before an after adding the route with the value $0$ from $C$ to $D$, respectively here on the page $4$.  I mean, what and why we are summing to get the values $80$ and $85$ on the page 4 in the figure $8.2$.
Answer: The Nash equilibrium for the picture $8.2$ without the route from $C$ to $D$ is when
both routs from $A$ to $C$ and $A$ to $D$ are loaded with 2000 cars which results in $2000/100+45=65$ time in average. When we add the $0$ route form $C$ to $D$ this route becomes a dominant strategy: any other route would now take $85$ minutes (and therefore will be in any NE) with load $4000/100+0+4000/100=80$ time in average.

Braess's paradox


Using LOOCV, AIC for Weighted Multiple Regression Model Selection?

Question: I am currently attempting to determine the most predictive weighted multiple linear regression model to use and am trying to figure out the best combination of variables to use in the model.
My first idea was to use take the weighted mean of errors from LOOCV for all possible variable combinations. However, being that my data has 20 variables, this would forever for my computer to run all of these regressions. After doing a bit of research, my impression is that using LOOCV for model selection is similar to comparing the AIC of each run of the regression. Is this true? If so, would another method for determining the best model be by running a single regression using all observations for each variable combination and then choosing the model with the lowest AIC? Would the results be impacted by the fact that the observations in my model are weighted differently?
Any help would be greatly appreciated!
Comment: See [Algorithms for automatic model selection](http://stats.stackexchange.com/q/20836/17230) for problems with what you're suggesting. A sensible first step would be to validate your twenty-predictor model  & see if it is even over-fitting. If variable selection seems like a good idea (alternatives include data reduction of the predictors or shrinkage without selection) @MikeHunter's answer gives sound advice
Comment: LOOCV for linear regression is very cheap though, even at 20 variables. Why would it take forever?
Answer: Why not make your life much simpler and use the Lasso or LARS for first-pass variable selection? Tibshirani's Lasso technique has been widely vetted, is ranked as one of the top statistical contributions of recent years on NormalDeviate.com and its approach to L1 normed regularization is solid.
Comment: Thanks for the help. I just ran my data through the `lasso()` function in MATLAB, though I am a bit unsure about how to interpret the results. Is there a rule of thumb for choosing Lambda? Which model of those provided is the 'best'? Once I have found the model that tells me which combination of coefficients are most predictive, do I use the coefficient results provided by the lasso function to use for the regression, or do I re-run a multiple linear regression using the remaining variables and use those coefficients?
Comment: I don't know how Lasso works in Matlab but you can play around with Lambda. And, yes, if you get a subset of regressors, I would rerun that subset in a regression module and, after checking that the results are as expected, use those coefficients, not Lasso's.


What does it mean when an integrand is singular at x = 0?

Question:
the integrand $f(x) = x^{−1}sin(x^{−1}log(x))$ has infinitely many oscillations in the interval [0, 1] and is also singular at x = 0.
What does it mean "singular at x = 0"?
Answer: In this context, "singular at $x=0$" refers to the fact that the integrand has a singularity at $x=0$. In particular, our function fails to be defined at $x=0$.


Java 8 Supplier Exception handling with CompletableFuture

Question: Consider the following code
public class TestCompletableFuture {

    BiConsumer<Integer, Throwable> biConsumer = (x,y) -> {
        System.out.println(x);
        System.out.println(y);
    };

    public static void main(String args[]) {
        TestCompletableFuture testF = new TestCompletableFuture();
        testF.start();
    }

    public void start() {
        Supplier<Integer> numberSupplier = new Supplier<Integer>() {
            @Override
            public Integer get() {
                return SupplyNumbers.sendNumbers();
            }
        };
        CompletableFuture<Integer> testFuture = CompletableFuture.supplyAsync(numberSupplier).whenComplete(biConsumer);
    }
}

class SupplyNumbers {
    public static Integer sendNumbers(){
        return 25; // just for working sake its not  correct.
    }
}

The above thing works fine. However sendNumbers could also throw a checked exception in my case, like:
class SupplyNumbers {
    public static Integer sendNumbers() throws Exception {
        return 25; // just for working sake its not  correct.
    }
}

Now I want to handle this exception as y in my biConsumer. This will help me in handling the result as well as exception (if any) inside a single function (biConsumer).
Any ideas? Can I use CompletableFuture.exceptionally(fn) here or anything else?
Comment: Here is a solution that allows you to use checked exceptions without reducing the readability of your code: https://stackoverflow.com/a/49705336/14731
Answer: The factory methods using the standard functional interfaces aren't helpful when you want to handle checked exceptions. When you insert code catching the exception into the lambda expression, you have the problem that the catch clause needs the CompletableFuture instance to set the exception while the factory method needs the Supplier, chicken-and-egg.
You could use an instance field of a class to allow mutation after creation, but in the end, the resulting code isn't clean and more complicated that a straight-forward Executor-based solution. The documentation of CompletableFuture says:

All async methods without an explicit Executor argument are performed using the ForkJoinPool.commonPool() …

So you know the following code will show the standard behavior of CompletableFuture.supplyAsync(Supplier) while handling checked exceptions straight-forward:
CompletableFuture<Integer> f=new CompletableFuture<>();
ForkJoinPool.commonPool().submit(()-> {
  try { f.complete(SupplyNumbers.sendNumbers()); }
  catch(Exception ex) { f.completeExceptionally(ex); }
});

The documentation also says:

… To simplify monitoring, debugging, and tracking, all generated asynchronous tasks are instances of the marker interface CompletableFuture.AsynchronousCompletionTask.

If you want to adhere to this convention to make the solution even more behaving like the original supplyAsync method, change the code to:
CompletableFuture<Integer> f=new CompletableFuture<>();
ForkJoinPool.commonPool().submit(
  (Runnable&CompletableFuture.AsynchronousCompletionTask)()-> {
    try { f.complete(SupplyNumbers.sendNumbers()); }
    catch(Exception ex) { f.completeExceptionally(ex); }
});

Comment: @Jasonw: It's a cast to an *intersection type*. In other words, the object must implement both types, `Runnable` *and* `CompletableFuture.AsynchronousCompletionTask`. Since type casts provide a context type for lambda expressions, this implies that the generated lambda instance will implement both interfaces. See also [here](http://stackoverflow.com/a/22808112/2711488)
Comment: could you explain what does this means?  (Runnable&CompletableFuture.AsynchronousCompletionTask)
Answer: You are already catching the exception in y. Maybe you did not see it because main exited before your CompletableFuture had a chance to complete?
The code below prints "null" and "Hello" as expected:
public static void main(String args[]) throws InterruptedException {
  TestCompletableFuture testF = new TestCompletableFuture();
  testF.start();
  Thread.sleep(1000); //wait for the CompletableFuture to complete
}

public static class TestCompletableFuture {
  BiConsumer<Integer, Throwable> biConsumer = (x, y) -> {
    System.out.println(x);
    System.out.println(y);
  };
  public void start() {
    CompletableFuture.supplyAsync(SupplyNumbers::sendNumbers)
            .whenComplete(biConsumer);
  }
}

static class SupplyNumbers {
  public static Integer sendNumbers() {
    throw new RuntimeException("Hello");
  }
}

Answer: I am not quite sure what you are trying to achieve. If your supplier throws an exception, when you call testFuture .get() you will get java.util.concurrent.ExecutionException caused by any exception that was thrown by the supplier, that you can retrieve by calling getCause() on ExecutionException.
Or, just as you mentioned, you can use exceptionally in the CompletableFuture. This code:
public class TestCompletableFuture {

    private static BiConsumer<Integer, Throwable> biConsumer = (x,y) -> {
        System.out.println(x);
        System.out.println(y);
    };

    public static void main(String args[]) throws Exception {
        Supplier<Integer> numberSupplier = () -> {
            throw new RuntimeException(); // or return integer
        };

        CompletableFuture<Integer> testFuture = CompletableFuture.supplyAsync(numberSupplier)
                .whenComplete(biConsumer)
                .exceptionally(exception -> 7);

        System.out.println("result = " + testFuture.get());
    }

}

Prints this result:
null
java.util.concurrent.CompletionException: java.lang.RuntimeException
result = 7

EDIT:
If you have checked exceptions, you can simply add a try-catch.
Original code:
Supplier<Integer> numberSupplier = new Supplier<Integer>() {
    @Override
    public Integer get() {
        return SupplyNumbers.sendNumbers();
    }
};

Modified code:
Supplier<Integer> numberSupplier = new Supplier<Integer>() {
    @Override
    public Integer get() {
        try {
            return SupplyNumbers.sendNumbers();
        } catch (Excetpion e) {
            throw new RuntimeExcetpion(e);
        }
    }
};

Comment: OP was hoping to be able to handle the exception in the code that invokes the supplier, rather than within the supplier itself.  If you are always going to handle the exception in a consistent way, it's clunky to be forced the try/catch in every supplier you write.
Answer: Perhaps you could use new Object to wrap your integer and error like this:
public class Result {

    private Integer   integer;
    private Exception exception;

    // getter setter

}

And then:
public void start(){
    Supplier<Result> numberSupplier = new Supplier<Result>() {
        @Override
        public Result get() {
            Result r = new Result();
            try {
                r.setInteger(SupplyNumbers.sendNumbers());
            } catch (Exception e){
                r.setException(e);
            }
            return r;

        }
    };
    CompletableFuture<Result> testFuture = CompletableFuture.supplyAsync(numberSupplier).whenComplete(biConsumer);
}

Answer: Just wrap the checked exception into a CompletionException
Another point to take into account with exception handling in CompletableFuture when using completeExceptionally() is that the exact exception will be available in handle() and whenComplete() but it will be wrapped in CompletionException when calling join() or when it is forwarded to any downstream stage.
A handle() or exceptionally() applied to a downstream stage will thus see a CompletionException instead of the original one, and will have to look at its cause to find the original exception.
Moreover, any RuntimeException thrown by any operation (including supplyAsync()) is also wrapped in a CompletionException, except if it is already a CompletionException.
Considering this, it is better to play it on the safe side and have your exception handlers unwrap the CompletionExceptions.
If you do that, there is no point anymore to set the exact (checked) exception on the CompletableFuture and it is much simpler to wrap checked exceptions in CompletionException directly:
Supplier<Integer> numberSupplier = () -> {
    try {
        return SupplyNumbers.sendNumbers();
    } catch (Exception e) {
        throw new CompletionException(e);
    }
};

To compare this approach with Holger's approach, I adapted your code with the 2 solutions (simpleWrap() is the above, customWrap() is Holger's code):
public class TestCompletableFuture {

    public static void main(String args[]) {
        TestCompletableFuture testF = new TestCompletableFuture();
        System.out.println("Simple wrap");
        testF.handle(testF.simpleWrap());
        System.out.println("Custom wrap");
        testF.handle(testF.customWrap());
    }

    private void handle(CompletableFuture<Integer> future) {
        future.whenComplete((x1, y) -> {
            System.out.println("Before thenApply(): " + y);
        });
        future.thenApply(x -> x).whenComplete((x1, y) -> {
            System.out.println("After thenApply(): " + y);
        });
        try {
            future.join();
        } catch (Exception e) {
            System.out.println("Join threw " + e);
        }
        try {
            future.get();
        } catch (Exception e) {
            System.out.println("Get threw " + e);
        }
    }

    public CompletableFuture<Integer> simpleWrap() {
        Supplier<Integer> numberSupplier = () -> {
            try {
                return SupplyNumbers.sendNumbers();
            } catch (Exception e) {
                throw new CompletionException(e);
            }
        };
        return CompletableFuture.supplyAsync(numberSupplier);
    }

    public CompletableFuture<Integer> customWrap() {
        CompletableFuture<Integer> f = new CompletableFuture<>();
        ForkJoinPool.commonPool().submit(
                (Runnable & CompletableFuture.AsynchronousCompletionTask) () -> {
                    try {
                        f.complete(SupplyNumbers.sendNumbers());
                    } catch (Exception ex) {
                        f.completeExceptionally(ex);
                    }
                });
        return f;
    }
}

class SupplyNumbers {
    public static Integer sendNumbers() throws Exception {
        throw new Exception("test"); // just for working sake its not  correct.
    }
}

Output:
Simple wrap
After thenApply(): java.util.concurrent.CompletionException: java.lang.Exception: test
Before thenApply(): java.util.concurrent.CompletionException: java.lang.Exception: test
Join threw java.util.concurrent.CompletionException: java.lang.Exception: test
Get threw java.util.concurrent.ExecutionException: java.lang.Exception: test
Custom wrap
After thenApply(): java.util.concurrent.CompletionException: java.lang.Exception: test
Before thenApply(): java.lang.Exception: test
Join threw java.util.concurrent.CompletionException: java.lang.Exception: test
Get threw java.util.concurrent.ExecutionException: java.lang.Exception: test

As you'll notice, the only difference is that the whenComplete() sees the original exception before thenApply() in the customWrap() case. After thenApply(), and in all other cases, the original exception is wrapped.
The most surprising thing is that get() will unwrap the CompletionException in the "Simple wrap" case, and replace it with an ExecutionException.
Comment: Throwing a `CompletionException` wrap is the key here, and makes everything run closer to the "`Future` spirit"...


How can I load a view inpage using AJAX when a node is flagged?

Question: I have a view that gives the users the option to flag nodes.  Below this view I need another view listing the results of flagged nodes to show up without the page needing a reload.  My skills are limited to Front end development so I'm unsure how I can do this via AJAX.
I did find this module:
https://drupal.org/project/jquery_ajax_load
I'm not sure how to implement this module since I need this view to commence upon the first flag event(?)
Would someone be able to help me find a solution?
Cheers!
Answer: This is actually a pretty common functionality and there is a module for it, Views Flag Refresh:

Views Flag Refresh allows site administrators to configure which views are refreshed automatically via AJAX when certain flags are selected. This is useful when you have a view that filters by flagged content and you want the view to be refreshed automatically when content is flagged or unflagged elsewhere on the page.

If this doesn't fit your exact needs, there are lots of code snippets in the Flag Javascript API Documentation that might set you in the right direction.
Comment: Thanks Jim, but I already have Flag Refresh implemented.  What I need is for Ajax to load a new view in-page with the results of the flagged contents.  Cheers.
Comment: I guess I don't understand your question then as the module I mentioned will reload a View on the page via ajax whenever a flag is clicked on the same page elsewhere.
Comment: Sorry Jimma, I mean I need to load a separate view(id2) in the page with the results the moment an item is flagged in view (id1).
Comment: Right.  So when you click on a flag link anywhere on the page, this module can reload a View elsewhere on the page.  It really doesn't matter if that flag link (or js toggle) is in view id1, this module will see that event and reload view id2...


Typeset whole note as full measure in 6/8 time in Lilypond

Question: I'm trying to copy a song from a book in which they were using a whole note to represent a full measure in 6/8 time.
If I try to use the whole note duration in Lilypond (1), it lasts 8/8 and everything gets unaligned. So far I could only replicate the song using half + quarter notes with a tie, but if I could replace it by a whole note it would be much cleaner.
I've also tried to do a half note + space and hide the stem, but it doesn't look very good.
Is there a way to simply change the length of the whole note to match 6/8?
Comment: Exercise your prerogatives as an editor: replace them with dotted minims (half notes), and you'll have the standard notation for 6/8 meter. Semibreve (whole note) lengths are only used for whole-measure rests in 6/8. I see no good reason to perpetuate a bad and somewhat confusing notational quirk.
Comment: Sure, you can just say `c1*6/8` to get a note that *looks* like a whole note but *sounds* for 6/8. But I agree that simply correcting the score is the better option.
Answer: LilyPond offers the choice between full-bar and normal rests as R and r.  The same for notes is not available.  As mentioned in the comments, c1*6/8 will take you half the way to your wish.  However, this kind of full-bar note is almost only employed for baroque bordun notes (usually a breve instead of a semibreve head) and then, like full-bar rests, the placement of the note is in the middle of the bar rather than at its start.
It does not sound like what you are having here, so it would be musically advisable to use c2. instead, namely the musically correct duration.  Or possibly c4.~c4. depending on how strong the subdivision of the bar is rhythmically.
Answer: If you start with a note (or rest), add a time value, then add a multiplication symbol with the fraction of rhythmic value, you will arrive at your desired note.
a1*6/8
So, for instance, a1 means "the note A at the full value of a whole note." But a1*6/8 means "the note A, written as a whole note, but taking up only sixth-eighths of the value of a whole note." This fraction may incidentally be whatever you want.
I've more often used a whole note to indicate a note lasting the entire measure when it's longer than usual (e.g., a1*11/8 to make a whole note fill a measure of 11/8 time; or s1*24 to mean "make an invisible spacer rest that lasts the length of twenty-four whole notes"), but marking a whole note to mean less than the normal value seems out of the ordinary. For 6/8 time, a dotted half note is normal to fill in the measure.
One last note about rests. You do see a "whole" rest fill a measure of any time signature. In Lilypond, that is not represented by r1 --- that will still get you the whole rest taking up its normal value --- but rather by R1 which denotes a "MultiMeasureRest," which will always appear as a whole note, but also be directly centered in the measure.
As found in the documentation on full-measure rests, the number after an uppercase R will denote such a rest. Therefore, since 2. fills the entirety of a 6/8 time signature (as well as 3/4), use R2.. You will end up seeing something that looks more like what you normally would encounter.


Flex item width is being respected instead of shrinking

Question: I'm self-teaching myself CSS using The Odin Project.
See here for the code I'm working on:
https://codepen.io/Ashwin-Parcha/pen/JjxxJJq
Problem
I've set a width on the flex items cards (.card) that is too wide on purpose at 400px. These cards have default flex values of 0 1 auto. From my understanding, when the flex-basis is auto, the width is considered, but if the total width of the flex items is bigger than the parent and flex-shrink = 1, then the width isn't respected and the items will shrink to fit the container. But as you can see, the width IS being respected here for some reason.
Expected Outcome
The width shouldn't be respected and cards should shrink.
Thanks for your help!

body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  margin: 0;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  height: 72px;
  background: darkmagenta;
  color: white;
}

.footer {
  height: 72px;
  background: #eee;
  color: darkmagenta;
}

.sidebar {
  width: 300px;
  background: royalblue;
  box-sizing: border-box;
  flex-shrink: 0;
}

.card {
  border: 1px solid #eee;
  box-shadow: 2px 4px 16px rgba(0,0,0,.06);
  border-radius: 4px;
  width: 400px;
}

ul {
  margin: 0;
  list-style-type: none;
  padding: 0;
}

a {
  text-decoration: none;
  color: white;
}

.hoflex {
  display: flex;
  margin: 16px;
  gap: 12px;
}

.fullflex {
  flex-grow: 1;
  display: flex;
}

      MY AWESOME WEBSITE

⭐ - link one

♂ - link two

 - link three

 - link four

Lorem ipsum dolor sit amet consectetur adipisicing elit. Tempora, eveniet? Dolorem dignissimos maiores non delectus possimus dolor nulla repudiandae vitae provident quae, obcaecati ipsam unde impedit corrupti veritatis minima porro?

Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quasi quaerat qui iure ipsam maiores velit tempora, deleniti nesciunt fuga suscipit alias vero rem, corporis officia totam saepe excepturi odit ea.

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Nobis illo ex quas, commodi eligendi aliquam ut, dolor, atque aliquid iure nulla. Laudantium optio accusantium quaerat fugiat, natus officia esse autem?

Lorem ipsum dolor sit amet consectetur adipisicing elit. Necessitatibus nihil impedit eius amet adipisci dolorum vel nostrum sit excepturi corporis tenetur cum, dolore incidunt blanditiis. Unde earum minima laboriosam eos!

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Nobis illo ex quas, commodi eligendi aliquam ut, dolor, atque aliquid iure nulla. Laudantium optio accusantium quaerat fugiat, natus officia esse autem?

Lorem ipsum dolor sit amet consectetur adipisicing elit. Necessitatibus nihil impedit eius amet adipisci dolorum vel nostrum sit excepturi corporis tenetur cum, dolore incidunt blanditiis. Unde earum minima laboriosam eos!

      The Odin Project ❤

Comment: You're running into "Nested Flex Containers" situation described in https://stackoverflow.com/a/36247448/681070. It's confusing. Put `min-width: 0px` on `.hoflex`.
Answer: Your parent div .hoflex is not assigned with overflow property. So by default it will take use overflow: visible. You can add overflow: auto inside your .hoflex {overflow: auto;} property and you will find desired output.
Here is more details on overflow

https://www.w3schools.com/css/css_overflow.asp#:~:text=The%20overflow%20property%20has%20the,renders%20outside%20the%20element's%20box
https://developer.mozilla.org/en-US/docs/Web/CSS/overflow

The overflow property has the following values (reference w3schools):

visible - Default. The overflow is not clipped. The content renders outside the element's box
hidden - The overflow is clipped, and the rest of the content will be invisible
scroll - The overflow is clipped, and a scrollbar is added to see the rest of the content
auto - Similar to scroll, but it adds scrollbars only when necessary

Try it out here.

body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  margin: 0;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  height: 72px;
  background: darkmagenta;
  color: white;
}

.footer {
  height: 72px;
  background: #eee;
  color: darkmagenta;
}

.sidebar {
  width: 300px;
  background: royalblue;
  box-sizing: border-box;
  flex-shrink: 0;
}

.card {
  border: 1px solid #eee;
  box-shadow: 2px 4px 16px rgba(0,0,0,.06);
  border-radius: 4px;
  width: 400px;
}

ul {
  margin: 0;
  list-style-type: none;
  padding: 0;
}

a {
  text-decoration: none;
  color: white;
}

.hoflex {
  display: flex;
  margin: 16px;
  gap: 12px;
  overflow-x: auto; /* Add this css */
}

.fullflex {
  flex-grow: 1;
  display: flex;
}

      MY AWESOME WEBSITE

⭐ - link one

♂ - link two

 - link three

 - link four

Lorem ipsum dolor sit amet consectetur adipisicing elit. Tempora, eveniet? Dolorem dignissimos maiores non delectus possimus dolor nulla repudiandae vitae provident quae, obcaecati ipsam unde impedit corrupti veritatis minima porro?

Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quasi quaerat qui iure ipsam maiores velit tempora, deleniti nesciunt fuga suscipit alias vero rem, corporis officia totam saepe excepturi odit ea.

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Nobis illo ex quas, commodi eligendi aliquam ut, dolor, atque aliquid iure nulla. Laudantium optio accusantium quaerat fugiat, natus officia esse autem?

Lorem ipsum dolor sit amet consectetur adipisicing elit. Necessitatibus nihil impedit eius amet adipisci dolorum vel nostrum sit excepturi corporis tenetur cum, dolore incidunt blanditiis. Unde earum minima laboriosam eos!

Lorem ipsum dolor sit amet consectetur, adipisicing elit. Nobis illo ex quas, commodi eligendi aliquam ut, dolor, atque aliquid iure nulla. Laudantium optio accusantium quaerat fugiat, natus officia esse autem?

Lorem ipsum dolor sit amet consectetur adipisicing elit. Necessitatibus nihil impedit eius amet adipisci dolorum vel nostrum sit excepturi corporis tenetur cum, dolore incidunt blanditiis. Unde earum minima laboriosam eos!

      The Odin Project ❤


Show that each of the following is an isomorphism

Question: Verify that each of the following is an isomorphism:
1) $T: \mathbb{R}^3 \to \mathbb{R}^3$ defined by $T(x,y,z)=(x+y,y+z,z+x)$.
2) $T: M_{2,2} \to \mathbb{R}^4$ defined by $T\left(\begin{bmatrix}a & b\\ c & d \end{bmatrix}\right) = (a+b, d, c, a-b)$.
For the 1), should we find $S: \mathbb{R}^3 \to \mathbb{R}^3$ such that $S(x,y,z)=(x, y, z)$ first? And in general do we have to show that each of them is linear.
Answer: I will leave you to check that these are actually linear transformations. However, the fact that I am about to express them as matrices implies that they are linear transformations.

1) We can represent $T$ by the matrix $$A = \begin{pmatrix} 1 & 1 & 0 \\ 0 & 1 & 1 \\ 1 & 0 & 1\end{pmatrix}_.$$
By this I mean that $T(v) = Av$.
Then $T$ is invertible if and only if $\det(A) \neq 0$.
Since $\det(A) = 2$, we have that $T$ is invertible.

2) Let $$e_{1,1} = \begin{pmatrix} 1 & 0 \\ 0 & 0 \end{pmatrix}, \  e_{1,2} = \begin{pmatrix} 0 & 1 \\ 0 & 0 \end{pmatrix}, \ e_{2,1} = \begin{pmatrix} 0 & 0 \\ 1 & 0 \end{pmatrix}, \ e_{2,2} = \begin{pmatrix} 0 & 0 \\ 0 & 1 \end{pmatrix}_.$$
These form a basis of $M_{2,2}$. If we use the standard basis for $\mathbb{R}^4$, the matrix of this transformation becomes:
$$A = \begin{pmatrix} 1 & 1 & 0 & 0\\ 0 & 0 & 0 & 1 \\ 0 & 0 & 1 & 0 \\ 1 & -1 & 0 & 0\end{pmatrix}_.$$
Since $\det(A) = 2 \neq 0$, we have that $T$ is invertible.
Comment: Thank you. So since they are invertibles, are they isomorphic? I'm asking because our professor told us to find if they are one to one or onto. So I'm lost. Your reasoning looks easier.
Comment: For a linear transformation, being invertible and being an isomorphism is equivalent.


Best approach for redirecting a large number of old URLs to new URLs?

Question: We are re-platforming for a client, and they are concerned about SEO. Their current site supports SEO friendly URLs, and so does the new platform. So for those, we are just going to create the same URL mapping. However, they have a large number of other URLs that are not SEO friendly that they want to permanently redirect. These do not follow a similar pattern, so one regex in an .htaccess won't cut it. What is the best way to handle this on a LAMP stack? The application has a front controller too, so I need to make sure that works along with the hard redirects.
Answer: One approach (the one I chose) was to create a simple table of old urls and new ones, and then use mod_rewrite to read the table and perform redirects.  The table can live in a file external to the Apache config.
Alternatively, you could write a script to query a database if you wanted the table to live in a database.
This means you either need to manually create the mapping, or write some script to output this mapping file.
Answer: You could use PHP to redirect old URLs to new ones.
<code>header("Location: /new.html",TRUE,301);
</code>
You will still need to redirect requests to this PHP script, but you may find this more flexible and easier
to debug than exclusively using mod_rewrite.
Comment: PHP is more convenient for most users and offers more flexibility, but you're trading speed for convenience in most cases. That may not be a showstopper but is worth taking into consideration.


Jade variable interpolation - default value if a property is undefined?

Question: I've got a form for updating user data that populates each input with the existing field value as it is stored in the database. However, in the case of new users, certain values haven't yet been committed to the database and so I'd like the input boxes to be blank.
In order to display the user data, I'm using Jade's interpolation functionality to look at the #{user.local} object passed in via the routes.js file.
It looks like this (snippet):
input(type="text", name="firstname", value="#{user.local.firstName}")

This works well when the property is defined, but it (correctly) inserts undefined as the text in an input where the property has not been defined.
Is there a way for me to set a variable to default to something if it hasn't been set?
Something like:
input(type="text", value="#{user.local.firstName || 'Default Text'"})

Comment: Using jade ~1.9.2, ```input(type='text' class='form-control' id='line6Name' name='param6' value='#{device.param6||""}')``` gives a default of an empty string for undefined values when I do it. I'm willing to be the code you have there would work if you shifted where the closing double quote is.
Comment: Have you found a solution for this? I have the exact same problem currently and searching for a solution.
Comment: Not in Jade, per se. I'm thinking I just need to add some logic to my controller so that, when it retrieves data, it replaces `undefined` with any empty string or whatever. Then that data would be passed to the view via the router.
Comment: I'll try that - why don't you write that as an answer so I can accept it if it works! Thanks @ZacharyJacobi
Answer: Using jade ~1.9.2, I tried
input(type='text' class='form-control' id='line6Name' name='param6' value='#{device.param6||""}')

in a form I'm writing. It gives a default of an empty string for undefined values.
I'm willing to bet the code you have there would work if you shifted where the closing double quote is.
From:
input(type="text", value="#{user.local.firstName || 'Default Text'"})

To:
input(type="text", value="#{user.local.firstName || 'Default Text'}")

Comment: This works like a charm. Turns out you were right - my curly brace should have terminated before the final quotation mark.


Network Link Conditioner seems to have no effect on network behavior on Lion, Mountain Lion

Question: The Network Link Conditioner preference pane (installed from the "Hardware IO Tools for Xcode - Late July 2012" DMG on the Apple developer site) doesn't appear to have any effect when turned on. The original author of this question reported the symptoms on Mountain Lion. A later editor experienced the same symptoms and lack of expected network behavior change on Lion, with Xcode 4.5.1 installed.
When enabled, /var/log/system.log shows:
<code>Jan 17 17:36:14 matt-mmf-macbook [0x0-0x1d01d].com.apple.systempreferences[371]: System Preferences(371,0x10fac7000) malloc: *** auto malloc[371]: error: GC operation on unregistered thread. Thread registered implicitly. Break on auto_zone_thread_registration_error() to debug.
Jan 17 17:36:18 matt-mmf-macbook System Preferences[371]: process command (simulate) failed
Jan 17 17:36:18 matt-mmf-macbook [0x0-0x1d01d].com.apple.systempreferences[371]: _nlc_start_simulation: (os/kern) failure
Jan 17 17:36:18 matt-mmf-macbook System Preferences[371]: Starting Network Link Conditioner
</code>
And the network connections do not exhibit the behavior specified by the selected profile.
Has anyone successfully gotten it to work, or figured out what the error in system.log might mean? As of 2013-01-17, the "accepted/correct" answer does not work for everyone experiencing the symptoms.
Comment: I have the same issues. Did anyone managed this?
Comment: If anyone's curious, there's now an Oct 2013 version of Hardware IO which seems to work on Mavericks
Answer: i just had the same problem. Installed the Conditioner pane on Lion and after updating to Mountain Lion, it still was available in the settings pane, but had no effect when turned on.
i fixed that by just removing the Conditioner (right click in the settings pane -> Remove "Network...") and reinstalling it from the Hardware IO Tools Image (Late July 2012).
Hope it works too for you. i think the os x update must have overwritten something.
Comment: Thanks maaalex. I had tried that before, but this time I rebooted after uninstalling, and that did the trick.
Comment: I tried rebooting, reinstalling, etc.  This tool does not work for me on Lion.
Comment: I'm running Xcode 4.5.2 and Harware IO Tools for Xcode - Jan 2013 and same issue for me.
Comment: From another question I just got this tip and it works !

uninstall pref pane, restart mac, install new perf pane, restart mac. only then it worked properly.
Comment: This answer does not work for me. I see the symptoms described in the question on Lion, with Xcode 4.5.1 and Hardware IO Tools for Xcode - Late July 2012.
Comment: On MacOS X 10.7.5: I installed the tool from the Hardware IO Tools Image. It has no effect.
Comment: Doesn't work for me on OSX 10.9. Installed and restarted, still nothing.
Comment: The Network Link Conditioner had no effect for me either on Mavericks OSX 10.9.4. I removed it as @maaalex suggested from the Settings pane and then installed the latest version (at the moment "Hardware IO Tools for Xcode - June 2, 2004") and then it worked perfectly. No reboot needed. You can take the image from http://developer.apple.com/downloads
Answer: I'm having this problem on Lion. None of the methods in here worked. I found another tool called SpeedLimit (it's a free preference pane) and it works fine. http://mschrag.github.io/


Formatação de número

Question: Gostaria de saber se poderiam me ajudar com a formatação do número impresso.
Erro:

Quantidade_dia.js:17 Uncaught TypeError: num.toFixed is not a function

Como está saindo: 12.0
Gostaria que mostrasse somente o 12

$(document).ready(function teste(){
 $('#tabela').empty(); //Limpando a tabela
    $.ajax({
  type:'post',  //Definimos o método HTTP usado
  dataType: 'json', //Definimos o tipo de retorno
  url: 'quantidade_dia_tele.php',//Definindo o arquivo onde serão buscados os dados
  success: function montaTabela(dados){
            for(var i=0;dados.length>i;i++){
                // formatacao da data
                var dataform = new Date(dados[i].data);
                var dia = dataform.getDate();
                var mes = dataform.getMonth();
                var ano = dataform.getFullYear();
                dataform = dia + '/' + (mes+01) + '/' + ano;
                //formatacao da quantidade
                var num = dados[i].quantidade;
                var numform = num.toFixed();
                console.log(numform);
    //Adicionando registros retornados na tabela
    $('#tabela').append('
'+dados[i].id+'	'+dados[i].nome+'	'+dados[i].quantidade+'	'+dataform+'
');
   }

  }
 });
});

Answer: O .toFixed() só funciona em dado do tipo número. O valor em dados[i].quantidade provavelmente é um número em forma de string, por isso gera o erro citado.
Neste caso você deve converter a string em número. Você pode adicionar um sinal de + antes de dados[i].quantidade para converter a string em número. Exemplo:

var dados = [
   {
      quantidade: "12.0"
   }
]
for(var i=0;dados.length>i;i++){
   var num = +dados[i].quantidade;
   var numform = num.toFixed();
   console.log(numform);
}
Answer:

Formatação de número


Limit for a sequence with n as an exponent

Question: I'm having trouble with this problem because it has $n$ as an exponent. Which I'm not really sure on how to deal with.
$$\lim_{n \to \infty} \frac{4+(-1)^n}{n^2}$$
Comment: Write down the first few terms explicitly: $$\frac39,\quad \frac{5}{16},\quad \frac{3}{25},\quad \frac5{36},\quad \frac3{49},\quad \frac5{64},\quad \frac3{81},\quad \frac5{100},\quad \ldots$$ where does this seem to go?
Answer: Hint: $\lim_{n \to \infty } \frac{3}{n^2} \leq \lim_{n \to \infty } \frac{4+(-1)^n}{n^2} \leq \lim_{n \to \infty } \frac{5}{n^2}$
Which gives:
$0 \leq \lim_{n \to \infty } \frac{4+(-1)^n}{n^2} \leq 0$
Answer: Hint: $n^2$ is much greater when it tends to infinity than $(-1)^n$; what will be if $(-1)^n$ is divided by $n^2$?
Comment: does this mean the denominator will be much greater than the numerator, resulting in a small number?
Comment: yes and which are the smallest dumbers near 0?
Comment: I would have to assume decimals?
Answer: Hint: compute the limits of the subsequences with odd indices, and those with even indices.


Is there some capture filter (or alternatives) that is especially useful for wireless capture?

Question: I'm capturing wireless traffic in monitor mode with Wireshark. I want to capture traffic only for a certain BSS.
While wlan.bssid == xx:xx:xx:xx:xx:xx works well as a display filter, I don't want my data cluttered with useless traffic that I'm not interested in (the air is quite cluttered in every channel).
The questions here:

Are there some especially useful capture filters for wireless capture?
What's the best way to capture traffic to or from an AP only?
Answer: Capturing wireless traffic can be a proper bitch, as not all Wireless adapters will enter promiscuous mode as you might expect.
You might need an AirPcap device
As far as filters are concerned, I don't see why you can't use that as a display filter, export marked packets to a different pcap file, and then re-open that.  I'm not sure that the same kind of filter for display works as a filter in capture mode.  I'd just filter and export.
Comment: The wireless capturing part is already working. Maybe I'll have to filter and export. Display filter does not work as capture filter.
Answer: Here are some more useful capture filters:
wlan sa (source address):
wlan src XX:XX:XX:XX:XX:XX
wlan da (destination address):
wlan dst XX:XX:XX:XX:XX:XX
wlan ra (receiver address):
wlan addr1 XX:XX:XX:XX:XX:XX
wlan ta (transmitter address):
wlan addr2 XX:XX:XX:XX:XX:XX
wlan host XX:XX:XX:XX:XX:XX
Thanks to Guy Harris.
Comment: The filter `wlan.sa == 8a:07:9d:74:ad:31` worked for me in the Wireshark GUI.
Answer: How about using the cmdline version of wireshark where you can specify all kinds of parameters.

root@kali-raspberry-pi1:~# tshark -tad -nni wlan0mon -f 'ether host d2:9e:43:xx:xx:xx and not broadcast'
Running as user "root" and group "root". This could be dangerous.
Capturing on 'wlan0mon'
** (tshark:8789) 16:41:26.778825 [Main MESSAGE] -- Capture started.
** (tshark:8789) 16:41:26.790889 [Main MESSAGE] -- File:
"/tmp/wireshark_wlan0monC2BKW1.pcapng"
1 2022-11-26 16:41:50.389080784 d2:9e:43:xx:xx:xx → da:f7:ec:xx:xx:xx 802.11 450 Probe Response, SN=424, FN=0, Flags=....R...C, BI=108, SSID="xxx"
2 2022-11-26 16:41:53.973077782 d2:9e:43:xx:xx:xx → 00:27:22:xx:xx:xx 802.11 450 Probe Response, SN=425, FN=0, Flags=....R...C, BI=108, SSID="xxx"
3 2022-11-26 16:41:53.978267971 d2:9e:43:xx:xx:xx → 00:27:22:28:ea:c2 802.11 450 Probe Response, SN=425, FN=0, Flags=....R...C, BI=108, SSID="xxx"
^Ctshark:
3 packets captured
root@kali-raspberry-pi1:~#

(xxx just in case you're one of my neighbors).


XMLSchema: Is it possible to calculate how valid an invalid document is (eg. as a percentage)?

Question: I'm using lxml in Python to validate a number of XML documents against an XML Schema definition. A good number of these documents do not validate -- and at the moment they're not expected to -- but it would be useful if I could calculate how valid they are, as a percentage, for reporting purposes. I have the ability to use xmllint or other command line tools, should those be able to provide a useful statistic.
Answer: lxml parsers provide a way to get a list of the errors that occurred while trying to parse the document.  Combine this with the parser's recover keyword argument and you get something like this:
# Warning, untested, may not work
parser = etree.XMLParser(recover=True)
it_would_be_a_tree = etree.parse(your_xml_data, parser)
total_errors = len(parser.error_log)

Then you can calculate the percentage of the file that total_errors represents. You could use a naive measure, like errors per line or errors per character without any trouble.  More sophisticated measures are also possible if it_would_be_a_tree is actually a tree structure (total_elements / total_errors, for example).
Comment: It's not the parsing that's the problem; the files parse fine, as they're well-formed xml. They're just not *valid* in relation to the XMLSchema.


email problems with directing to local ip

Question: I am trying to direct emails to a local ip address and using another ip for website. The local guy told me to set it up like this
but it is not working . It is still going to the local webmail on my cPanel
Zone File Records
<Name   TTL Class   Type    Record  Action>
<odomnursery.com.   14400   IN  A   188.8.131.52>
<localhost.odomnursery.com. 14400   IN  A   127.0.0.1>
<www.odomnursery.com.   14400   IN  CNAME   odomnursery.com>
<ftp.odomnursery.com.   14400   IN  CNAME   odomnursery.com>
<odomnursery.com.   14400   IN  TXT "v=spf1 a mx include:websitewelcome.com ~all">
cpanel.odomnursery.com. 14400   IN  A   220.127.116.11>
<whm.odomnursery.com.   14400   IN  A   22.214.171.124>
<webmail.odomnursery.com.   14400   IN  A   22.214.171.124>

Comment: I can't see any `MX` record in the posted DNS records.
Comment: Whatever you tried to cut and paste didn't work well.  Maybe try again and use the Blockquote formatting button.
Comment: @Khaled Which isn't necessary as long as you have A records.
Comment: But that is the question - to separate web and email servers.
Comment: odomnursery.com.    14400   IN  A   184.108.40.206
localhost.odomnursery.com.  14400   IN  A   127.0.0.1
www.odomnursery.com.    14400   IN  CNAME   odomnursery.com
ftp.odomnursery.com.    14400   IN  CNAME   odomnursery.com
odomnursery.com.    14400   IN  TXT "v=spf1 a mx nclude:websitewelcome.com ~all"
cpanel.odomnursery.com. 14400   IN  A   18.104.22.168
whm.odomnursery.com.        14400   IN  A   22.214.171.124
webmail.odomnursery.com.    14400   IN  A   184.108.40.206
webdisk.odomnursery.com.    14400   IN  A   220.127.116.11
mail.odomnursery.com.       14400   IN  A   188.8.131.52
Answer: Just add the following record
odomnursery.com 14400 IN MX 10 webmail.odomnursery.com

(Assuming your mail is like email@example.com, and the host that runs SMTP is webmail.odomnursery.com)
Comment: firstname.lastname@example.com
Comment: the mail was setup on 126.96.36.199   and the odomnursery.com is 22.214.171.124
Comment: Mark: replace mail.odomnursery.com with whatever hostname that have A record of 220.127.116.11 (like webmail.odomnursery.com)


Invalid operation the connection is closed

Question:
this error shows up while creating a new record,  ? As far as i think, it's kind of memory leakage problem, i did open connection and forgot to close it , transaction manager has locked it i suppose, but how to fix it :-? I have tried different settings but nothing worked. This type of errors makes my work slow
Comment: Was this resolved? How?
Answer: <code>You can use activity manager to solve this problem
using activity manager close the open connection for the user
</code>


Showing a node with a Views?

Question: I have a bundle "Text" and bundle "Protocol". The "Protocol" bundle has a field of Entity Reference type which links the "protocol" node with texts that were accepted during that protocol. (I.e. the join is somewhat like "Protocol"->"Text") Also Protocol has following fields: a protocol number (integer) and a date (date-iso)
While viewing "Text"-type node there will be shown information about the corresponding protocol:its number and acceptance date (mention them above).
So the question is: is it a good practice to show this pages via Views? Owing to its Relations feature, obtaining of information related to the corresponding protocol is really easy. But idea itself seems to me being of kinda "bad Drupal way", because there is a standard way of displaying nodes in Drupal.
If the Views is really bad idea, then how should I obtain the protocol's number and date, from tpl.php (or preprocessor function)? Any variants?
Answer: Views can be a little heavy, and if you don't need the module it's lighter just to drop it.
If you just want to grab some info for a template, you could also do it with Entity Field Queries.

Showing a node with a Views?


Lambda Expressions and Method calls

Question: Hi I have a collection of Objects in a Listview and i need to know if i can iterate through them with a lambda expression. and call a method on it in the expression.
Lets say i need to save a group of people to a database.
List<People> someList;
someList.Select(person => person.Save());

is this possible to do? so far i have not been able to get it working.
thanks
Answer: You can use the ForEach method of a generic list:
List<People> someList;
someList.ForEach(person => person.Save());

Comment: Yeah this sounds like the perfect solution.
Comment: ForEach has always been a method of a generic List (see [link](http://msdn.microsoft.com/en-us/library/bwabdf9z(v=VS.80).aspx)) - it's not a Linq extension.  Although you'd have to use a delegate rather than a lambda expresssion in .net 2.0.  Which version of the .net Framework are you using?
Comment: ah i found it. turns out i was using a BindingList. but i casted to generic List and it showed up correctly.
Answer: someList.ForEach(p => p.Save());

Answer: Sounds like you want a foreach statement:
foreach(People p in someList)
{
    p.Save();
}

But if you really want to do it in lambda expressions and LINQ, then your problem with the above code is that .Select(...) returns an IEnumerable/IQueryable, which creates a new query but doesn't execute your lambda expressions.
You could force the lambda to evaluate by calling an extension method that forces an enumeration of the data the IEnumerable/IQueryable represents. For instance by doing:
someList.Select(person => person.Save()).Count();

but this also assumes your Save() method returns non-void.
Edit:
As others have pointed out, if you're working specifically with a List<>, then you can also do:
someList.ForEach(person => person.Save());

Comment: You select statement will be problematic in case that `Save` returns `void`.
Comment: thx. was using OP's code but added an additional note about that.
Comment: the Save did indeed return a void, but i guess thats not always going to be true.

Lambda Expressions and Method calls


Probability of rolling a 1 before you roll two 2's, three 3's, etc

Question: This is a question my father-in-law asked. I found it interesting but haven't been able to answer it.
Suppose you have an $N$ sided die. You conduct an experiment as follows: roll the die until the first time you have rolled one 1, two 2's, three 3's etc. For example, you roll 2,3,4,3,6,5,3 the experiment ends because you have rolled three 3's. Of course, the most times you can roll the die is $1+\sum_{k=1}^{N-1}k = 1 + \frac{(N-1)N}{2}$. This is because the maximum number of rolls you can do is to roll one 2, two 3's, three 4's and so on, and then one more roll to complete the experiment. In particular, the experiment always ends in a finite number of rolls.
Observe that the experiment ends when you roll a $1$. If you have a one-sided die the experiment always ends after the first roll and so you end on $1$ with probability 1. If you have a two sided die (i.e. a coin) then the probability of rolling a $1$ on the first roll is $1/2$; the probability of rolling a 2 first and a 1 second is $1/4$ and so the probability of ending the experiment on a $1$ is $3/4$.
Let $P_N$ be the probability that you end the experiment on a $1$. What is $\lim_{N\to\infty}P_N$?
$P_N$ is decreasing and of course $0\leq P_N$ so the limit exists. I tried taking the limit along ``easy'' sequences like $2^N$ hoping the the extra structure would lend itself to easier analysis, but I couldn't.
I imagine I am not the first to ask this question, but I couldn't find it on MSE any other place. Any references to similar questions are also appreciated.
Comment: For $2\leq k\leq N$, the probability you roll $k$ $k$'s before a $1$ is $2^{-k}$ (of the first $k$ times the roll is in $\{1,k\}$, each of those rolls must be $k$). This implies that $P_N > \lim > P_N-\sum_{k=N+1}^{\infty}2^{-k}=P_N-2^{-N}$. Using this and a computer computation, I found that the limit is between $0.687$ and $0.688$.
Comment: A less ambitious assignment would be to figure out if the limit is positive or not.
Comment: @JulianRosen; excellent. I was not thinking along these lines but this seems like a good approach.
Answer: I doubt that a "closed form" for their limit will be forthcoming, but the probabilities can be written
$$P(n) = \sum_{k=0}^{T_{n-1}}\frac{a(k,n)}{n^{k+1}}$$
where $T_{n-1}=\frac{(n-1)n}{2}$ is the $(n-1)$th triangular number, and $a(k,n)$ is the number of $k$-long words that can be formed using $k$ elements from the string $S_n=1^02^13^2...n^{n-1}$ such that no element is used more often than it appears in $S_n$. (The string notation $c^i$ denotes $i$ concatenated copies of the symbol $c$.)
Now, $a(k,n)$ is readily computed, as it is just $k!$ times the coefficient of $x^k$ in the following exponential generating function:
$$\left(1+x\right)\,\left(1+x+\frac{x^2}{2!}\right)\,\left(1+x+\frac{x^2}{2!}+\frac{x^3}{3!}\right)\,...\,\left(1+x+\frac{x^2}{2!}+...+\frac{x^{n-1}}{(n-1)!}\right).
$$
(A simple explanation of this type of generating function is in the accepted answer to the MSE question 6-letter permutations in MISSISSIPPI.)
Computations produce the following values:
n     P(n)
--    -----------------
 1    1.000000000000000
 2    0.750000000000000
 3    0.703703703703704
 4    0.692138671875000
 5    0.689010688000000
10    0.687835012279842
15    0.687833655173612
20    0.687833654277303
25    0.687833654276930
30    0.687833654276930

The online Inverse Symbolic Calculators found no closed form for this apparent limit of 0.687833654276930....

For reference, here's the (Sage) program I used:
def P(n):
    return sum( a(k,n)/n^(k+1) for k in [0..n*(n-1)/2] )

def a(k,n):
    R.<x> = PowerSeriesRing(ZZ)
    f = prod( sum( x^j / factorial(j) for j in [0..i] ) for i in [0..n-1] )
    return factorial(k)*f[k]

for n in [1..50]:
    print n, P(n).n()


Integral $\int_{\mathbb{R}^n} \frac{1}{(2 \pi)^{\frac{n}{2}}} e^{-\frac{\| x-\mu\|^2}{2}} dx$ using Spherical coordiantes

Question: I know that, the inetegral
\begin{align}
\int_{\mathbb{R}^n} \frac{1}{(2 \pi)^{\frac{n}{2}}} e^{-\frac{\| x-\mu\|^2}{2}} dx
\end{align}
integrates to $1$.
This can be shown as follows
\begin{align}
\int_{\mathbb{R}^n} \prod_{i=1}^n \frac{1}{\sqrt{2 \pi}} e^{-\frac{( x_i- \mu_i)^2}{2}} dx
\end{align}
and see that every inetegral is equal to $1$.
My question is how to do this by using spherical coordinates?
Thanks.
Answer: Obviously $\mu$ is completely irrelevant: it can be removed by a suitable translation.
By Fubini's theorem
$$ \int_{\mathbb{R}^n}\exp\left(-\|x\|^2\right)\,dx = \left(\int_{-\infty}^{+\infty}e^{-x^2}\,dx\right)^n = \pi^{n/2} $$
and the claim readily follows. Have a look at the first pages of Keith Ball, An Elementary Introduction to Modern Convex Geometry. If you want to use spherical coordinates, well, just use them by computing the determinant of the involved jacobian matrix.
Comment: I know $\mu$ can be dropped. The reason I kept it to to see, how to works with spherical coordinates when the function is shifted. Thank you for the reference. I am reading it right now. It is very good.
Comment: The reason, I was interested in this question. Is the question I posted here: https://math.stackexchange.com/questions/2240910/set-of-on-which-a-certain-function-is-negative
Answer: We can write the integral of interest as
$$\begin{align}
I&=\frac{1}{(2\pi)^{n/2}}\int_{\mathbb{R}^n} e^{-\frac12||\vec x-\vec \mu||^2}\,d^n\vec x\\\\
&=\frac{1}{(2\pi)^{n/2}}\int_{S_{n-1}} \color{blue}{\int_0^\infty e^{-\frac12r ^2}\,r^{n-1}\,dr}\,dS_{n-1}\\\\
&=\frac{1}{(2\pi)^{n/2}}\int_{S_{n-1}} \color{blue}{\left(\frac12 2^{n/2}\Gamma(n/2)\right)}\,dS_{n-1}\\\\
&\frac{1}{(2\pi)^{n/2}}\color{blue}{\left(\frac12 2^{n/2}\Gamma(n/2)\right)}\color{red}{\int_{S_{n-1}}(1)\,dS_{n-1}}\\\\
&\frac{1}{(2\pi)^{n/2}}\color{blue}{\left(\frac12 2^{n/2}\Gamma(n/2)\right)}\color{red}{\frac{2\pi^{n/2}}{\Gamma(n/2)}}\\\\
&=1
\end{align}$$
as was to be shown!

A good summary for analysis of the $n$-Sphere in spherical coordinates can be found HERE.
Comment: Thanks for your answer. The motivation for this question what something that I asked here: https://math.stackexchange.com/questions/2240910/set-of-on-which-a-certain-function-is-negative


How to test new nameserver before to make it live

Question:
Possible Duplicate:
Testing nameserver configuration using it

I'm thinking of changing from my hosting provider nameservers to Route53 (Amazon's distributed nameserver) for several reasons.
I'm currently setting all records like they are on my current host page (I can see my DNS settings but I cannot change them). Since I'm not used to working with Route53's hosted zones, is there a way I can test the new nameserver resolution settings before updating the domain to point to the new nameserver?
For example, I'm not sure if the last dot in CNAME records is necessary or not...
Answer: Use dig
dig mydomainname.example @mynewnameserver.example

Answer: You can easily do that using nslookup, the process is next:

1) Enter nslookup

2) Run server $YourDNSServerName where $YourDNSServerName is the one of the DNS servers responsible for your zone at Route53 like nslookup ns-131.awsdns-16.com

3) From there just enter your records and see the responses.
Comment: Use dig and not nslookup for any serious DNS debugging.  nslookup has many known flaws and has been depreciated.  http://veggiechinese.net./nslookup_sucks.txt
Comment: Thanks, it works!!
Can you please help me to understand what should i set for these records?
@ IN MX 1 aspmx.l.google.com.
@ IN MX 5 alt1.aspmx.l.google.com.
@ IN MX 5 alt2.aspmx.l.google.com.
@ IN MX 10 aspmx2.googlemail.com.
@ IN MX 10 aspmx3.googlemail.com.
I should leave the domain blank, am I right?
Comment: yes if you're setting MX records for the domain, the domain should be blank.
Answer: Set up your name server and then configure a test machine to use it for DNS.  I'm not sure what client system you're using, but since I'm on a Windows box, at the moment, a screenshot of where you'd put that new nameserver value on a Windows machine.

Apply those DNS settings to a number of machines for testing purposes, use as normal, and ensure nothing's broken.
Comment: This will not work. This screen allows you to enter the **recursive** nameservers you want to use. This is certainly not the way to test new **authoritative** nameservers (a lot of things will start to break as you will get DNS replies for only a very small subset of names, or even none at all).
Comment: Why wouldn't that work? The flow goes: 1. Change Windows to use new authoritative nameservers. 2. Test resolution of relevant domain names. 3. Change back to some recursive nameservers. - During number 2 you won't be able to resolve most other domain names so you might want to be aware if you're testing a website that some content such as from a CDN may not load but apart from that it seems fine to me.


uniform integrability of a squared sum of iid variables

Question: I'm trying to prove that if $X_i$ are independent, identically distributed random variables such that $E X_i = 0$ and $E X_i^2 < \infty$ then the sequence $\frac{(\sum_{i=1}^{n} X_i)^2}{n}$ is uniformly integrable. Actually I've been told that even something stronger holds, namely that
$$\frac{\max_{k\leq n}(\sum_{i=1}^{k} X_i)^2}{n}$$
is uniformly integrable. Can someone please give me a hint or a reference to some proof? I've been told that the Hoffmann-Jorgensenn inequality might come in handy, but I suppose that's just for the generalization with $\max$. I know this would be trivial if we had $\frac{\sum_{i=1}^{n} X_i^2}{n}$, but the problem is that the whole sum is squared, not each variable separately.
Thank you very much for your help.
Comment: Do you mean to assume $E X_i^2 < \infty$?
Comment: yeah, you're right, thanks!
Answer: I think there are two ways.

Assume you know that $S_n/\sqrt{n}$ converges in distribution to $N(0,1)$ (that is, you know that central limit theorem holds). Then $P(S_n^2>nR)\to P(N^2>R)$ for all $R>0$.
Conclude using a $2\varepsilon$-argument and the fact that for a non-negative random variable $Y$,
$$E(Y\chi_{\{Y>R\}})=R\cdot P(Y>R)+\int_R^{+\infty}P(Y>t)dt$$
Using a truncation argument and a fourth-moments inequality. Such a method gives the wanted uniform integrability for max after having used Kolmogorov inequality for example.
Comment: thanks! I'll try the second approach and post my results here. I'm trying to avoid using the CLT argument, because I actually want to use this to prove CLT in a slightly different setting
Comment: hey, I couldn't fit my comment in the character limit here, so I posted it as an answer (which it partially is), could you please take a look at it? it uses a part of your first idea, but deosn't use the CLT and there's a tiny hole in it (estimate on $ P (\max_{k \leq n} |X_k| \geq \sqrt{sn})$. Thanks!
Comment: If you don't know that $X_1$ is in $L^4$, but only in $L^2$, how would you prove the result using method 1? From what you wrote, I dont see how to prove that $\int_R^{+\infty}P(Y>t)dt \to 0$. can you help me out here?
Answer: ok, here's what I got so far:
Davide - I didn't really know how to follow your truncating idea - I tried to do it, but I can't figure how to use fourth moment inequality in a sensible way, but instead I tried using the first approach, although slightly modified so that I'd get uniform integrability with max, I'd be grateful if someone took a look at it:
I'm using Kolmogorow's inequality
$$ P (\frac{1}{n}\max_{k \leq n} S_k^2 \geq M) =  P(\max_{k \leq n} |S_k| \geq \sqrt{Mn}) \leq \frac{1}{M} \sigma^2$$
and the following Hoffmann-Jorgensen inequality - if $X_i$'s are independent then for all nonnegative s, r, t we have
$$P(\max_{k \leq n} |S_k| > s + r + t) \leq P(\max_{k \leq n} |X_k| > s) + 2P(\max_{k \leq n} |S_k| > t)P(\max_{k \leq n} |S_n - S_k| > r/2)
$$
taking s = t = r/2 and by stationarity (same distribution) $S_n - S_k \sim S_j$ we get
$$P(\max_{k \leq n} |S_k| > 4s) \leq P(\max_{k \leq n} |X_k| > s) + 2[P(\max_{k \leq n} |S_k| > s)]^2
$$
so by using
$$P (\frac{1}{n}\max_{k \leq n} S_k^2 \geq s) =  P(\max_{k \leq n} |S_k| \geq \sqrt{sn})$$
we obtain
$$ P (\frac{1}{n}\max_{k \leq n} S_k^2 \geq s) \leq P(\max_{k \leq n} |X_k| > \sqrt{sn}) + 2[P(\max_{k \leq n} |S_k| > \sqrt{sn})]^2
$$
by using Kolmogorov on the second summand
$$P (\frac{1}{n}\max_{k \leq n} S_k^2 \geq s) \leq P(\max_{k \leq n} |X_k| > \sqrt{sn}) + \frac{2}{s^2} \sigma^4
$$
which is cool because the part with $1/s^2$ is nice and integrable, so we could use the formula for expectation suggested by Davide and this ingredient would be less than $\epsilon$ for R sufficiently large, now (if I didn't make a mistake along the way) we just need a sensible estimate on $P(\max_{k \leq n} |X_k| > \sqrt{sn})$ which shouldn't be that hard. I thought about writing something like
$$P(\max_{k \leq n} |X_k| > \sqrt{sn}) = 1 - [P(|X_1| \leq \sqrt{sn})]^n$$
$$P(|X_1| \geq \sqrt{sn}) \leq \frac{\sigma^2}{ns}$$ so
$$P(\max_{k \leq n} |X_k| > \sqrt{sn}) \leq 1 - (1 - \frac{\sigma^2}{ns})^n$$
and I guess we could work with it, but I was hoping for something nicer. Does anyone have an idea?


How to create synthetic data for this case?

Question: Some weeks ago, I ran an experiment with 30 participants. For each participant two microphones were recording them while they were reading a phrase in 3 different simulated emotions (Happy, Neutral and Sad). So, I have 180 observations (6 observations for each participant). The data would look something like this:

Microphone mode
Emotion
Amplitude
ID
Gender

Omni
Happy
64.1
1
Female

Uni
Happy
60.7
1
Female

Omni
Sad
59.9
1
Female

Uni
Sad
56.4
1
Female

Omni
Neutral
62.2
1
Female

Uni
Neutral
59.7
1
Female

…
…
…
…
…

Omni
Happy
62.7
30
Male

Uni
Happy
61.2
30
Male

Omni
Sad
58.8
30
Male

Uni
Sad
57.6
30
Male

Omni
Neutral
60.3
30
Male

Uni
Neutral
59.7
30
Male

I would like to generate three simulated data sets given this data, each with 300 participants but each with different proportion of microphone modes (i.e., one with 50% omni and 50% uni, another with 30% omni and 70% uni and another with 70% omni and 30% uni).
Does any of you know any easy way to achieve that on R or Python?
I already tried the 'synthpop' R package, but it doesn't seem to allow to define the class proportion (microphone mode) that I would like to generate, and it doesn't seem to generate new IDs (all the IDs are created between 1 and 30, not sure if that would be a problem or it would be normal. But I didn't find anyway to control by subjects and at the same time create new subjects).
Comment: A couple of `expand.grid()` commands will populate your independent variables, but that part is purely programming and thus off-topic here. Should your Amplitude depend on the IVs, and if so, how? If not, you can simply fill it with `rnorm()`.
Comment: Also: what do you mean by "30% omni and 70% uni"? Right now, every participant has half of each. Do you want each participant to have about 30%*6=1.8 omni trials (sometimes rounding up, sometimes down, perhaps not getting exactly 30% overall)? Or do you want 30% of participants to have all omni, the others all uni?
Comment: Thanks for your comments. Yes, amplitude depends on the other variables. For example, the happy state usually has higher amplitude than neutral, and sad states, while neutral has higher amplitude than the sad state.

And yes, right. Now each participant has one observation for each microphone mode. What I meant by 70% omni and 30% is to have some participants having all omni and the others all uni.
Comment: OK. Do you then want 3 observations for each ID, one each of happy, sad and neutral?
Comment: Exactly, the idea in that case would be to have 3 observations for each subject, one for happy, one for sad and one for neutral
Answer: Here is R code:
emotions <- c("Happy","Sad","Neutral")

Set control parameters (I'll assume you want gender balance):
n_participants <- 100
proportion_omni <- 0.30
proportion_female <- 0.5

Assign your IDs to modes and genders (shuffling both, so we don't have the first $k$ IDs both Female and Omni):
modes <- structure(
    sample(c(rep("Omni",n_participants*proportion_omni),
        rep("Uni",n_participants*(1-proportion_omni))),
      size=n_participants,replace=FALSE),
    .Names=1:n_participants)
genders <- structure(
    sample(c(rep("Female",n_participants*proportion_female),
        rep("Male",n_participants*(1-proportion_female))),
      size=n_participants,replace=FALSE),
    .Names=1:n_participants)

Expand the emotion by ID grid:
dataset <- expand.grid(list(Emotion=emotions,ID=1:n_participants))

Add the information about modes and genders, as per the settings above:
dataset$Microphone_mode <- modes[as.character(dataset$ID)]
dataset$Gender <- genders[as.character(dataset$ID)]

Finally, add an amplitude. This simply models an influence of emotion, none of mode or gender. It's not the most elegant way of simulating this, but it's definitely the easiest to understand, and to extend if you want to simulate a more complex influence:
dataset$Amplitude <- NA
set.seed(1) # for replicability
index <- dataset$Emotion=="Sad"; dataset$Amplitude[index] <- rnorm(sum(index),60,3)
index <- dataset$Emotion=="Neutral"; dataset$Amplitude[index] <- rnorm(sum(index),65,3)
index <- dataset$Emotion=="Happy"; dataset$Amplitude[index] <- rnorm(sum(index),70,3)

Result:
> head(dataset)
  Emotion ID Microphone_mode Gender Amplitude
1   Happy  1             Uni   Male  71.22821
2     Sad  1             Uni   Male  58.12064
3 Neutral  1             Uni   Male  63.13890
4   Happy  2             Uni Female  75.06662
5     Sad  2             Uni Female  60.55093
6 Neutral  2             Uni Female  65.12635


Does singular values have anything to do with eigen-values of a square matrix?

Question: We know from linear-algebra, how to calculate the singular values $\sigma_{n(A)}$ of a square-matrix, $A$ by square-rooting the eigen-values of $A^*A$ i-e $\sigma_{n(A)}=\sqrt{\lambda_{n(A^*A)}}$.
But, I need to know that does singular-values, $\sigma_{n(A)}$, of a square-matrix have anything to do with eigen-values, $\lambda_{n(A)}$, in principle ?
thanks
Comment: Note thet a non-square matrix does NOT have eigenvalues, but it does have singular values, so the question does only make sense for square matrices.
Comment: Relate d to  http://math.stackexchange.com/questions/33089/majorization-relation-between-the-absolute-values-squared-of-the-entries-of-a-ma
Comment: @kjetilbhalvorsen I'm asking only about square-matrices. Question edited. thanks for pointing out.
Comment: The following paper contains (much) information related to your Q: www.scirp.org/journal/PaperDownload.aspx?paperID=41122          See also the book Marshall, Olkin, Arnold:  "Inequalities: Theory of majorization and its applications. second edition" Springer
Answer: Marshall, Olkin, Arnold: "Inequalites: Theory of majorization and its applications (second edition)", (Springer), page 317, gives the following theorem (Weyl, 1949).
For any $n \times n$ complex matrix $A$, where the eigenvalues $\lambda_i$ are ordered such that
$$
    |\lambda_1| \ge |\lambda_2| \ge \dots \ge |\lambda_n|
$$
and the singular values $\sigma_i$ are in decreasing order, we have:
$$
\prod_1^k |\lambda_i| \le \prod_1^k \sigma_i, \qquad k=1,2,\dots,n-1
$$
and with equality above for $k=n$. In the case with no zero eigenvalues, this corresponds to log-majorization.
The reference above contains a proof.
Comment: +1 vote. Thanks for coming up with more elaborative relation than mine.
Answer: $$|\prod_{i=1}^n\lambda_i|=\prod_{i=1}^n\sigma_i    \quad\quad for \quad  A^{n\times n}.$$
Where $\lambda$ and $\sigma$ are eigenvalues and singular values of $A$, respectively.
Comment: Do you have a reference (or proof) for that? Seems highly unlikely!    For instance, the nilpotent matrix $\begin{smallmatrix} 0 & 1 \\ 0 & 0 \end{smallmatrix}$ have both eigenvalues zero and one singular value zero, the other 1, so is an counterexample.
Comment: so what ? $|0 \times 0| = 0 \times 1$.
Comment: @kjetilbhalvorsen Now, after proving  by yourself, it proves that equality $|\prod_{i=1}^n\lambda_i|=\prod_{i=1}^n\sigma_i$ is correct for any arbitrary square matrix. So ... Still -1 vote?
Comment: My vo|te is locked-in (after one hour, it seems). To change, you must first edit your answer, such as putting in some proof or reference.


Como pegar a primeira linha de tabela estrangeira com entity framework core?

Question: Tenho uma tabela de imóveis e Fotos imóveis, com os respectivos modelos:
Imóveis
[Key]
public int ImovelId { get; set; }
public int? CategoriaId { get; set; }
public string Endereco { get; set; }
public string Numero { get; set; }

ImoveisFotos
[Key]
public int Id { get; set; }
public int ImovelId { get; set; }
public string Foto { get; set; }

No Controller tenho esse código:
IList<Imoveis> imoveisLista = new List<Imoveis>();
var imoveis = _context.Imoveis
                        .Where(i => i.LocacaoVenda == "L")
                        .Where(i => i.Bairro == bairro)
                        .Where(i => i.VisivelAluguel == 1)
                        .ToList();

                foreach (var item in imoveis)
                {
                    imoveisLista.Add(item);
                    var foto = _context.ImoveisFotos
                        .Where(x => x.ImovelId == item.ImovelId)
                        .Select(x => x.Foto).Count();
                    if (foto == 0)
                    {
                        ViewBag.Foto = "img_padrao.jpg";
                    }
                    else if(foto >= 1)
                    {
                        ViewBag.Foto = _context.ImoveisFotos
                        .Where(x => x.ImovelId == item.ImovelId)
                        .Select(x => x.Foto).First();
                    }
                }
                ViewData["ListaImoveis"] = imoveisLista;

E na View
@foreach (var item in ViewData["ListaImoveis"] as IList<Imoveis>)
                    {

                                        @item.Bairro
                                        -
                                        @item.Endereco,
                                        @item.Numero
                                        -
                                        @item.Complemento

A lista de imóveis vem direito, mas toda a lista repete a mesma foto, ao invés da sua tabela primaria. Meu objetivo era pegar a primeira foto de cada imóvel e exibir. Abaixo como fica:

Como resolver isso?
Answer: Está setando uma única referência na ViewBag (Viewbag.Foto) a cada iteração no laço foreach, por isso todos os registros ficam com a mesma imagem, pois sempre substitui a foto a cada passo.
Minha sugestão é criar uma ViewModel que receba todos os dados que quer apresentar na view:
public class ImoveisViewModel
{
    public int ImovelId { get; set; }
    public int? CategoriaId { get; set; }
    public string Endereco { get; set; }
    public string Numero { get; set; }
    public string Foto { get; set; }
}

List<ImoveisViewModel> listaImoveis = new List<ImoveisViewModel>();

No foreach crie um novo objeto ImoveisViewModel e no lugar de setar a ViewBag adicione na listaImoveis:
foreach (var item in imoveis)
            {
                var imovel = new ImoveisViewModel() {
                   ImovelId = item.ImovelId,
                   CategoriaId = item.CategoriaId,
                   Endereco = item.Endereco,
                   Numero = item.Numero
                };
                var foto = _context.ImoveisFotos
                    .Where(x => x.ImovelId == item.ImovelId)
                    .Select(x => x.Foto).Count();
                if (foto == 0)
                {
                    imovel.Foto = "img_padrao.jpg";
                }
                else if(foto >= 1)
                {
                    imovel.Foto = _context.ImoveisFotos
                    .Where(x => x.ImovelId == item.ImovelId)
                    .Select(x => x.Foto).First();
                }
                listaImoveis.Add(imovel);
            }
ViewData["ListaImoveis"] = listaImoveis;

Depois na View mudar o foreach:
@foreach (var item in ViewData["ListaImoveis"] as List<ImoveisViewModel>)

E depois na imagem:

Bem tem várias formas de resolver, mas o principal problema foi setar a string de foto na mesma ViewBag dentro do laço, no lugar de estar em lista.
Abraços
Comment: @MJSlasher, vlw mesmo. A chave de tudo era usar ViewModel. Depois no foreach como vc falou, usei um Count para percorrer a qtde de fotos, se retornasse nula, especificava uma string privada como a foto padrão, caso tivesse, pegava a primeira da lista com First(), e por fim jogava na propriedade Foto da ViewModel.


android development chart graphs just like analytics app

Question: I am developing an application which will be using some graphs and charts. that been said I saw Google Analytics app you can choose view by hourly, daily, weekly and monthly, also set date range, things like that. can anyone give an example or how to start this also what kind of data does it read json xml what format or structure does it read.
Answer: The are a lot of diffrent jar plugins you can use, from a quick Google search:

Iguana
RChart
AChartEngine
GraphView

And take a look at this post:
https://stackoverflow.com/questions/424752/any-good-graphing-packages-for-android
Comment: too many choices, don't know which to use. any recommendations.
Comment: actually I didn't had the time to try them out yet... but why don't you choose the one that you see most suitable for your needs. I think that the Iguana has the best looks and for a project I will have to develop soon I will definitely go with it.


Show that for $\xi>1,$ $A \text{ is } \Delta_{\xi+1}^0 \iff A=\lim_nA_n\text{ for some } A_n\in\Delta_\xi^0.$

Question: Problem below (kuratowski) is taken from Kechris's Classical Descriptive Set Theory, page $173.$

Definition: Given any sequence of sets $(A_n),$ $A_n\subseteq X,$ let
$$\overline{\lim_n} \, A_n = \bigcap_n\bigcup_{m\geq n} A_m = \{x:x\text{ belongs to infinitely many } A_n\},$$
$$\underline{\lim}_n \, A_n = \bigcup_n\bigcap_{m\geq n} A_m = \{x:x\text{ belongs to all but finitely many } A_n\},$$
It is clear that $\underline{\lim}_n \, A_n \subseteq\overline{\lim_n} \, A_n.$
If they are equal, let
$$\lim_n A_n= \overline{\lim_n} \, A_n = \underline{\lim}_n \, A_n .$$
Assume now that $X$ is metrizable, so that every closed set is a $G_\delta$ set.
Let $\omega_1$ be the first uncountable ordinal, and for $1\leq \xi<\omega_1,$ define by transfinite recursion the classes $\Sigma_\xi^0,\Pi_\xi^0$ of subsets of $X$ as follows:
$$\Sigma_1^0=\{U\subseteq X: U \text{ is open}\},$$
$$\Pi_\xi^0 =\sim\Sigma_\xi^0,$$
$$\Sigma_\xi^0=\bigg\{ \bigcup_n A_n: A_n\in \Pi_{\xi_n}^0, \xi_n<\xi, n\in\mathbb{N} \bigg\}, \text{ if } \xi>1,$$
where $\sim$ refers to set complement.
In addition, let
$$\Delta_\xi^0 = \Sigma_\xi^0\cap \Pi_\xi^0.$$
For example, $\Sigma_1^0$ is a topology on $X$ where $\Pi_1^0$ is the collection of closed sets of $X.$
$\Sigma_2^0$ is the collection of all $F_\sigma$ sets while $\Pi_2^0$ is the collection of all $G_\delta$ sets.
Note that $\Delta_1^0$ is the collection of all closed and open sets while $\Delta_2^0$ is the collection of all $F_\sigma$ and $G_\delta$ sets.

Question (Kuratowski) : Show that for $\xi>1,$
  $$A \text{ is } \Delta_{\xi+1}^0 \iff A=\lim_nA_n\text{ for some sequence } (A_n) \text{ with } A_n\in\Delta_\xi^0.$$

For $(\Leftarrow)$ direction, by definition,
$$A = \bigcap_n\bigcup_{m\geq n} A_m = \bigcup_n\bigcap_{m\geq n} A_m.$$
If $A_m\in\Delta_\xi^0 = \Sigma_\xi^0\cap \Pi_\xi^0,$ then
$$\bigcup_{m\geq n}A_m\in \Sigma_{\xi}^0\quad \text{and}\quad \bigcap_{m\geq n}A_m\in\Pi_\xi^0.$$
Then by definition of $\Sigma_{\xi+1}^0$ and $\Pi_{\xi+1}^0,$ we have
$$ \bigcap_n\bigcup_{m\geq n} A_m\in \Pi_{\xi+1}^0\quad\text{and}\quad \bigcup_n\bigcap_{m\geq n} A_m\in\Sigma_{\xi+1}^0.$$
I have no idea on how to start $(\Rightarrow)$ direction.
Comment: You know, the lim inf and lim sup are very common and pretty easy to recognize, even when you are using a less common symbol for them. But the $\Delta, \sum, \prod$ notations you are using are far less common. I suggest explaining them instead of lim inf and lim sup.
Comment: @PaulSinclair: Thanks for mentioning the unusual symbols. I have included their definitions in my question.
Comment: @Paul Sinclair Those notations are pretty common as well in descriptive set theory and in logic.
Comment: @Régis Do you know how to answer my questions?
Comment: I used to but I forgot.
Answer: Note:
This only holds if $\xi$ is successor ordinal.
To prove ($\Leftarrow$), first since $A \in \Delta_{\xi+1}^0, A\in\Sigma_{\xi+1}^0$ and $A\in\Pi_{\xi+1}^0$. So
$$
A=\bigcup_nB_n=\bigcap_nC_n, \quad B_n\in \Delta_{\xi}^0,\: C_n\in\Delta_{\xi}^0
$$
Where $B_n\subset B_{n+1}\subset \cdots\subset A\subset \cdots\subset C_{n+1}\subset C_{n}$. Thus there is $A_n\in \Delta_{\xi}^0$ that $B_n\subset A_n\subset C_n$. Clearly
$$
\overline{\lim_n} \, A_n = \bigcap_n\bigcup_{m\geq n} A_m \subset \bigcap_n\bigcup_{m\geq n} C_m =\bigcap_n C_n=A
$$
And
$$
\underline{\lim}_n \, A_n = \bigcup_n\bigcap_{m\geq n} A_m \supset \bigcup_n\bigcap_{m\geq n} B_m=\bigcup_n B_n =A
$$
Thus $A=\lim_{n}A_n$.


Why is there no output shown in the logs for this simple Lambda function

Question: This is a lambda function with Node.js 14.x
The only log I am seeing is this one : console.log(event); None of the ones after it show up. The response is also returned as null. Waht is wrong with my code?
    var AWS  = require("aws-sdk");
    var lambda = new AWS.Lambda();

    exports.handler = async function(event, context, callback) {

    var params = {
            FunctionName: 'Myfunction',
            Qualifier: 'v1'
    };
    console.log(event);

    var x =lambda.getProvisionedConcurrencyConfig(params, function(err, data) {
        console.log('entered call');
        if (err){
            console.log('error occured');
            console.log(err, err.stack);
            response = {
                statusCode: 200,
                body: JSON.stringify(err),
            };
        }
        else{
            console.log('Success');
            response = {
                statusCode: 200,
                body: JSON.stringify(data),
            };
        console.log(data);

        }
    });
    return response;
};

Answer: Your function finish immediately, before getProvisionedConcurrencyConfig finish. You use callback style for your function async function(event, context, callback), but the callback function never be called.
The first solution is keeping the callback style, and you have to call the callback function:
var AWS = require("aws-sdk");
var lambda = new AWS.Lambda();

exports.handler = function (event, context, callback) { // dont mix callback with async

  var params = {
    FunctionName: 'Myfunction',
    Qualifier: 'v1'
  };
  console.log(event);

  lambda.getProvisionedConcurrencyConfig(params, function (err, data) {
    console.log('entered call');
    if (err) {
      console.log('error occured');
      console.log(err, err.stack);
      callback(null, { // the function will finish with success status
        statusCode: 200,
        body: JSON.stringify(err),
      });
    }
    else {
      console.log('Success');
      console.log(data);
      callback(null, {
        statusCode: 200,
        body: JSON.stringify(data),
      });
    }
  });
};

The second solution is using Promise style for the function(recommendation):
var AWS = require("aws-sdk");
var lambda = new AWS.Lambda();

exports.handler = async function (event) { // keep as async

  var params = {
    FunctionName: 'Myfunction',
    Qualifier: 'v1'
  };
  console.log(event);

  try {
    console.log('entered call');
    // wait until it completed
    const data = await lambda.getProvisionedConcurrencyConfig(params).promise(); // convert to a promise
    console.log('Success');
    console.log(data);
    return {
      statusCode: 200,
      body: JSON.stringify(data),
    };
  } catch (err) {
    return { // the function will finish with success status
      statusCode: 200,
      body: JSON.stringify(err),
    };
  }
};

Comment: @user20358 the second one.
Comment: Which of the two styles is more common or more efficient?


angular 1 - routing and api

Question: Trying to write a simple SPA. Using MEAN.
API through node are all working.
Have set up routes in my main controller
    // create the module and name it
var boardingApp = angular.module('boardingApp', ['ngRoute']);

boardingApp.config(function($routeProvider) {

    $routeProvider

        // route for the home page that lists all tenants
        .when('/', {
            templateUrl : 'js/templates/tenants.html',
            controller  : 'tenantsController'
        })
        // route for a specifc tenant
        .when('/tenant/:id', {
            templateUrl : 'js/templates/tenant.html',
            controller  : 'tenantController'
        })

});

boardingApp.controller('tenantsController', ['$scope','$http','$log', function($scope, $http,$log) {

        $http.get(URL + "/api/tenants")
            .then(function(response){ $scope.details = response.data; });

}]);

 boardingApp.controller('tenantController', ['$scope','$http','$location','$log', function($scope, $http, $location, $log) {

        if ( $location.search().hasOwnProperty( 'id' ) ) {
            var myid = $location.search()['id'];
            console.log(myid)

            myURL = URL + "/api/tenants/"+myid
            console.log(myURL)

            $http.get(myURL)
            .then(function(response){ $scope.tenant = response.data; });
            console.log($scope.tenant)
        }

}]);

 boardingApp.controller('readmeController', function($scope, $http) {

        $scope.message = "This is the message"

});

the root route work finds calls the API generates a table. All good
then main part of that template is this

                        View
                        {{tenant.roomNumber}}
                        {{tenant.firstName}}
                        {{tenant.lastName}}
                        {{tenant.paymentFrequency}}
                        ${{tenant.rentAmount}}
                         {{tenant.leaseEnd | date: 'dd MMM yyyy'}}

I want to click on the "View" link and pull data from DB for each tenant through and API call that just needs the Tenant id - standard stuff.
My controller is not picking up the request and when i click on the link on the Tennants page it just ends up blank.
what am i missing here? the api call s are all good and working fine
Answer: You anchor tab is incorrect, it should be in correct pattern like "#/tenant/{{tenant._id}}"
ng-href="#/tenant/{{tenant._id}}"

Additionally you should retrieve a route parameter inside tenantController by using $routeParams.id API instead of $location.search() which would be look for query parameter.
Comment: Thank you.. was staring at this for a long time. Will need to research the $routeParams, have missed that
Comment: @ScottS just inject `$routeParams` in your controller & do `$routerParams.id` to retrieve parameter value'

angular 1 - routing and api


Multi-core processor for multiple data containers

Question: I have a dual core Intel processor and would like to use one core for processing certain commands like SATA writes and another for reads, how do we do it? Can this be controlled from the application(with multiple threads) or would this require a change in the kernel to ensure the reads/writes dont get processed by the the 'wrong' core?
Answer: This will be pretty much totally up to your operating system, which you haven't specified.
Some may offer thread affinity to try and keep one thread on the same execution engine (be that a core or a CPU), but that's only for threads. If two threads both write to disk, then they may well do so on different engines.
If you want that sort of low level control, it's probably best to do it at the kernel level.
My question to you would by "Why?". A great deal of performance tuning goes into OS kernels and they would generally know better than any application how to efficiently do this low level stuff.
Comment: Thank you for your reply. We are thinking about using Linux.And the reason I want to do low level control is per some security specifications to keep certain operations contained to a particular engine.


On univariate outlier tests (or: Dixon Q versus Grubbs)

Question: In (most of) the analytical chemistry literature, the standard test for detecting outliers in univariate data (e.g. a sequence of measurements of some parameter) is Dixon's Q test. Invariably, all the procedures listed in the textbooks have you compute some quantity from the data to be compared with a tabular value. By hand, this is not much of a concern; however I am planning to write a computer program for Dixon Q, and just caching values strikes me as inelegant. Which brings me to my first question:

How are the tabular values for Dixon Q generated?

Now, I have already looked into this article, but I'm of the feeling that this is a bit of cheating, in that the author merely constructs a spline that passes through the tabular values generated by Dixon. I have the feeling that a special function (e.g. error function or incomplete beta/gamma) will be needed somewhere, but at least I have algorithms for those.
Now for my second question: ISO seems to be slowly recommending Grubbs's test over Dixon Q nowadays, but judging from the textbooks it has yet to catch on. This on the other hand was relatively easy to implement since it only involves computing the inverse of the CDF of Student t. Now for my second question:

Why would I want to use Grubbs's instead of Dixon's?

On the obvious front in my case, the algorithm is "neater", but I suspect there are deeper reasons. Can anyone care to enlighten me?
Answer: Really, these approaches have not been actively developed for a very long time. For univariate Outliers, the optimal (most efficent) filter is median+/-$\delta \times$ MAD, or better yet (if you have access to R)
median+/-$\delta \times$ Qn (so you don't assume the underlying distribution to be symmetric),
The Qn estimator is implemented in package robustbase.
See:
Rousseeuw, P.J. and Croux, C. (1993) Alternatives to the Median
     Absolute Deviation, Journal of the American Statistical
     Association *88*, 1273-1283.
Response to comment:
Two levels.
A) Philosophical.
Both the Dixon and Grub tests are only able to detect a particular type of (isolated, single) outlier. For the last 20-30 years the concept of outliers has involved unto "any observation that departs from the main body of the data". Without further specification of what the particular departure is. This characterization-free approach renders the idea of building tests to detect outliers void. The emphasize shifted to the concept of estimators (a classical example of which is the median) that retain there values (i.e. are insensitive) even for large rate of contamination by outliers -such estimator is then said to be robust-  and the question of detecting outliers becomes void.
B) Weakness,
You can see that the Grub and Dixon tests easily break down: one can easily generated contaminated data that would pass either test like a bliss (i.e. without breaking the null).
This is particularly obvious in the Grubb test, because outliers will break down the mean and s.d. used in the construction of the test stat. It's less obvious in the Dixon, until one learns that order statistics are not robust to outliers either.
I think you will find more explanation of these facts in papers oriented towards the general non-statistician audience such as the one cited above (I can also think of the Fast-Mcd paper by Rousseeuw). If you consult any recent book/intro to robust analysis, you will notice that neither Grubb nor Dixon are mentioned.
Comment: I see no reason to say that these test have been discredited.  If you are trying to detect a single outlier when the population distribution (without the outlier) normal.  In fact Grubbs' test satisfies some optimality property.  There are always problems with outlier tests such as the masking effect when there are multiple outliers but that does not discredit the methods! The robustness methods use all the data and downweight the outliers so that the outliers will not unduly influence the estimation.
Comment: If you want to learn more about Dixon's test see my other posts on this site regarding questions on outliers and my 1982 paper "On the Robustness of Dixon's ratio Test in Small Samples."
Comment: I guess people must not think I am an expert on outliers because i believe Dixon's test is not discredited.  I think that those that think dixon's test is discredited probably don't understand what outlier detection and robust estimation is about.
Comment: @user603 Yes. The first sentence in your post looks so much better! now I am more inclined to listen to your argument which is sensible. I was so turned off by that first sentence that I didn't read the rest of it at first.
Comment: Interesting... I guess analytical chemists are very much behind the times! Mind telling me how both of these became discredited? I will look into your reference and see how the algorithms for these look like.
Comment: The robustness approach is to accomodate for outliers without having to detect them.  The outlier detection approach detects the outliers through legitimate hypothesis testing and give the user the opportunity to assess them and remove them if they are found to be errors.
Comment: @MichaelChernick: i concur that in samples with only a single outlier, outlier detection approaches will generally do as well as robust estimation.
Comment: Thank you user603.  But why did you say that they were discredited?
Comment: @MichaelChernick: You are correct. I have changed that section. Is this a fair characterization?


What exactly does the space average in the ergodic theorem mean?

Question:
Space Average: If μ(X) is finite and nonzero, we can consider the
  space or phase average of ƒ:

(from http://en.wikipedia.org/wiki/Ergodic_theory#Ergodic_theorems)
But is it comparable to the time average?
Shouldn't the space average of f be compiled for a particular time, seeing that f is dependent on t (or T^k)? Or would the space average of f be equal for all values of time t?
(hmm, f is integrated and averaged across time, and then f is integrated and averaged across space...)
Answer: $f$ is just a function $X \rightarrow X$, there is no dependence on time. The "time" comes from composing $f$ with iterations of $T$. The strong ergodic theorem (as described in the Wikipedia article) says that if $(T,\mu)$ is an ergodic system, then
$$ \frac{1}{\mu(X)} \int f \, d\mu = \lim_{n \rightarrow \infty} \frac{1}{n} \sum_{k=0}^{n-1} (f \circ T^k)(x),$$
for $\mu$-almost-every $x \in X$. So the LHS is the space average of $f$, and the RHS is the time-average of the maps $f \circ T^k$ applied to the point $x$. So, in other words, we are looking at the orbit $\{f(x), f(Tx), f(T^2x), \ldots\}$, and for almost every $x$, averaging these points is simply equal to averaging the values of $f$ across the whole domain $X$. Intuitively, this means that ergodicity tells you that the orbit of $x$ under $T$ visits everywhere in $X$ in some uniform fashion.
Please comment if you have further questions.


Use an icon in editActionsForRowAtIndexPath Title (swift)

Question: I have the neccessary code for the swipe Actions and they display properly, but I am having a hard time getting icons instead of the title text.
I have attempted using FontAwesome for iOS, but  it isn't a label it is a title attribute...
I attempted using
deleteAction.backgroundColor = UIColor(patternImage: UIImage(named:"sample")!)
But I don't see how that will ever display right as it tiles the image, if I make the image the correct size then wont it be wrong on a different screen size?
Answer: UIImage(named:"sample")! automatically takes the @1, @2 and @3 variant of an image. So if you create the images in the correct size it will work.
However, keep in mind that putting an image as background is not the way Apple designed it to work (and it may not be working in the future). If you want total control, find a library which does exactly what you want like MCSwipeTableViewCell or build something like that yourself.