text:
Q: Any customized UI in Master viewcontroller in UISplitViewController is lost in landscape orientation As an example, take the Master-Detail Application template project from Xcode, replace the Master UITableViewController with a regular UIViewController and put a label in the center. See images below. In portrait orientation the label appears as expected, but in landscape it is gone. This is not a matter of bad constraints.

If I change the UISplitViewControllerDisplayMode to PrimaryOverlay the label does appear after swiping in landscape.
I first experienced this problem when setting a custom tableview header on the default UITableViewController that is in the template project, so it is not only a problem when using a UIViewController.
Has anyone else experienced this and know a solution?


text:
Q: symbolic variables and vpasolve (MATLAB) for dynamic input I want to find the corresponding outputs for symbolic variables (Tg Tc Tab Tto Tti Tfo) for a dynamic set of inputs (G_in, Vw, Ta). Kindly seeking for probable solutions. Thanks!
(I will attach the code on request since I cant upload it)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Jenkins how to force tasks to run even with failure in one of them? Hi I'm running some tasks using Jenkins. There I have 5 tasks to run sequentially like:
test --tests apptest.WP_RecuperarSenha.testTeste_recuperar_senha_e_logar
test --tests apptest.WP_CadastroInvalido.testTeste_cadastro_campos_invalidos
test --tests apptest.WP_CadastroEmBranco.testedecadastrobranco
test --tests apptest.WP_InteracaoProduto.testeinteracaoproduto

I would like to know how to force Jenkins to keep running the build even, for example, if test --tests apptest.WP_RecuperarSenha.testTeste_recuperar_senha_e_logar fails. How to keep running it?

A: If you're using a free-style job you can use the conditional step plugin for each task and set each of the steps to always run.
If you utilize the pipeline plugin you can surround each task in a try/catch block and then inside the catch write currentBuild.result = 'FAILURE' (or currentBuild.result = 'UNSTABLE' if it's more meaningful to you).


text:
Q: Monkey City Progress I recently managed to have my computer infected by a virus, so I am wanting to do a complete re-install of windows.
One thing I don't want to lose is my progress on Monkey City. I've put a fair few hours in.
I always sign in to play, but I'm not confident that my progress is saved online.
Can someone confirm where my progress is saved, and if it is on my machine how can I back it up?

A: Monkey city data is stored on the server which supplies the game.
After wiping my computer completely my data was still preserved after logging in.


text:
Q: Number of Unique `double`s between Two Values I provide an answer to this question below (I did not find an 'answer own question' button)
Original Question
In Java, we have floating point type double which is encoded as 64 bits in memory. From this we know that it can take on at most 2^64 possible values, minus some special values. We could enumerate all of them.
The routines Math.nextUp(d) and Math.nextDown(d), given a double value d, will compute the one next larger and smaller double, respectively. Now I wonder how I can compute the number of double steps from one double a to b, i.e., my method difference(a,b) should work as follows:
assume a fixed, given a.

            b = ....               | difference(a, b)
===========================================================
   a                               |  0
   Math.nextUp(a)                  |  1
   Math.nextDown(a)                |  1
   Math.nextUp(Math.nextUp(a))     |  2
   Math.nextDown(Math.nextDown(a)) |  2

...and so on.
In the Java OpenJDK, the two mentioned methods are implemented as follows:
public static double nextUp(double d) {
  if( Double.isNaN(d) || d == Double.POSITIVE_INFINITY)
    return d;
  else {
    d += 0.0d;
    return Double.longBitsToDouble(Double.doubleToRawLongBits(d) +
                                    ((d >= 0.0d)?+1L:-1L));
  }
}

and
public static double nextDown(double d) {
  if (Double.isNaN(d) || d == Double.NEGATIVE_INFINITY)
    return d;
  else {
    if (d == 0.0)
      return -Double.MIN_VALUE;
    else
      return Double.longBitsToDouble(Double.doubleToRawLongBits(d) +
                                     ((d > 0.0d)?-1L:+1L));
  }
}

Can I safely do something similar, or does this only work because they only consider increments and decrements of 1, i.e., may I run into trouble with the exponent? I strongly assume the latter case, and wonder what would be the right method to achieve my goal?
Again: I want this to work for arbitrary doubles, i.e., difference(1e-3,3.442e201) should return the number Math.nextUp steps I would need to get from 1e-3 to 3.44e201. Obviously, just iterating and counting Math.nextUp would not do in this scenario.
Many thanks,
  Thomas.
Answer to Question
Thanks to the comments of @Thilo, it turns out that it actually is that easy to calculate the difference. Well, at least it sems to be that easy.
Here is the Java code:
/** Some mathematical utilities */
public final class MathUtils {

  /**
   * The number of unique {@code double} values between {@code a} and
   * {@code b}.
   *
   * @param a
   *          the first {@code double}
   * @param b
   *          the second {@code double}
   * @return the steps between them, or {@code -1} if either value is
   *         {@link Double#NaN} or both are infinities of different signs
   */
  public static final long difference(final double a, final double b) {
    final long bitsA;
    double useA, useB, temp;

    if ((a != a) || (b != b)) { // take are of NaN
      return -1L;
    }
    useA = (a + 0d);
    useB = (b + 0d);
    if (useA > useB) {
      temp = useB;
      useB = useA;
      useA = temp;
    }
    if (useA == useB) {
      return 0L;
    }
    if (useA <= Double.NEGATIVE_INFINITY) {
      return -1L;
    }
    if (useB >= Double.POSITIVE_INFINITY) {
      return -1L;
    }

    if (useA < 0d) {
      bitsA = Double.doubleToRawLongBits(-useA);
      if (useB < 0d) {
        return (bitsA - Double.doubleToRawLongBits(-useB));
      }
      return (bitsA + Double.doubleToRawLongBits(useB));
    }
    return (Double.doubleToRawLongBits(useB)
        - Double.doubleToRawLongBits(useA));
  }
}

and here some rudimentary JUnit test to confirm whether the results are what they should be:
import java.util.Random;

import org.junit.Assert;
import org.junit.Test;

/**
 * A test for math utils
 */
public class MathUtilsTest {

  /** the constructor */
  public MathUtilsTest() {
    super();
  }

  /** test step difference between two values */
  @Test(timeout = 3600000)
  public void testDifferenceBetweenTwoValues() {
    final Random random;
    double start, end;
    int starts, iteration;

    random = new Random();

    for (starts = 333; (--starts) >= 0;) {
      end = start = -(1d / Math.log(1d - random.nextDouble()));
      for (iteration = 0; iteration < 3333; iteration++) {
        Assert.assertEquals(iteration, MathUtils.difference(start, end));
        Assert.assertEquals(iteration, MathUtils.difference(end, start));
        end = Math.nextUp(end);
      }
    }
  }

  /**
   * test the "step" difference of two values, one of which is negative,
   * the other one being positive
   */
  @Test(timeout = 3600000)
  public void testDifferenceBetweenTwoValuesOfDifferentSign() {
    double start, end;
    int iteration;

    end = start = 0d;
    for (iteration = 0; iteration < 333333; iteration++) {
      Assert.assertEquals(
          (MathUtils.difference(start, 0d) + //
              MathUtils.difference(0d, end)),
          MathUtils.difference(start, end));
      Assert.assertEquals(
          (MathUtils.difference(start, 0d) + //
              MathUtils.difference(0d, end)),
          MathUtils.difference(end, start));
      start = Math.nextAfter(start, Double.NEGATIVE_INFINITY);
      end = Math.nextUp(end);
    }
  }

  /** test the border cases of the step difference */
  @Test(timeout = 3600000)
  public void testDifferenceBetweenTwoValuesBorderCases() {
    Assert.assertEquals(0L, MathUtils.difference(0d, 0d));
    Assert.assertEquals(0L, MathUtils.difference(0d, -0d));
    Assert.assertEquals(0L, MathUtils.difference(-0d, 0d));
    Assert.assertEquals(0L, MathUtils.difference(-0d, -0d));

    Assert.assertEquals(1L, MathUtils.difference(0d, Double.MIN_VALUE));
    Assert.assertEquals(1L, MathUtils.difference(Double.MIN_VALUE, 0d));
    Assert.assertEquals(1L, MathUtils.difference(-0d, Double.MIN_VALUE));
    Assert.assertEquals(1L, MathUtils.difference(Double.MIN_VALUE, -0d));

    Assert.assertEquals(1L, MathUtils.difference(0d, -Double.MIN_VALUE));
    Assert.assertEquals(1L, MathUtils.difference(-Double.MIN_VALUE, 0d));
    Assert.assertEquals(1L, MathUtils.difference(-0d, -Double.MIN_VALUE));
    Assert.assertEquals(1L, MathUtils.difference(-Double.MIN_VALUE, -0d));

    Assert.assertEquals(2L,
        MathUtils.difference(Double.MIN_VALUE, -Double.MIN_VALUE));
    Assert.assertEquals(2L,
        MathUtils.difference(-Double.MIN_VALUE, Double.MIN_VALUE));

    Assert.assertEquals((1L << 52L),
        MathUtils.difference(0d, Double.MIN_NORMAL));
    Assert.assertEquals((1L << 52L),
        MathUtils.difference(Double.MIN_NORMAL, 0d));
    Assert.assertEquals((1L << 52L),
        MathUtils.difference(-0d, Double.MIN_NORMAL));
    Assert.assertEquals((1L << 52L),
        MathUtils.difference(Double.MIN_NORMAL, -0d));

    Assert.assertEquals((1L << 52L),
        MathUtils.difference(0d, -Double.MIN_NORMAL));
    Assert.assertEquals((1L << 52L),
        MathUtils.difference(-Double.MIN_NORMAL, 0d));
    Assert.assertEquals((1L << 52L),
        MathUtils.difference(-0d, -Double.MIN_NORMAL));
    Assert.assertEquals((1L << 52L),
        MathUtils.difference(-Double.MIN_NORMAL, -0d));

    Assert.assertEquals((2L << 52L),
        MathUtils.difference(Double.MIN_NORMAL, -Double.MIN_NORMAL));
    Assert.assertEquals((2L << 52L),
        MathUtils.difference(-Double.MIN_NORMAL, Double.MIN_NORMAL));

    Assert.assertEquals(0L, MathUtils.difference(Double.POSITIVE_INFINITY,
        Double.POSITIVE_INFINITY));
    Assert.assertEquals(0L, MathUtils.difference(Double.NEGATIVE_INFINITY,
        Double.NEGATIVE_INFINITY));
    Assert.assertEquals(-1L, MathUtils.difference(Double.POSITIVE_INFINITY,
        Double.NEGATIVE_INFINITY));
    Assert.assertEquals(-1L, MathUtils.difference(Double.NEGATIVE_INFINITY,
        Double.POSITIVE_INFINITY));

    Assert.assertEquals(-1L, MathUtils.difference(Double.NaN, Double.NaN));
    Assert.assertEquals(-1L,
        MathUtils.difference(Double.POSITIVE_INFINITY, Double.NaN));
    Assert.assertEquals(-1L,
        MathUtils.difference(Double.NEGATIVE_INFINITY, Double.NaN));
    Assert.assertEquals(-1L,
        MathUtils.difference(Double.NaN, Double.POSITIVE_INFINITY));
    Assert.assertEquals(-1L,
        MathUtils.difference(Double.NaN, Double.NEGATIVE_INFINITY));

    Assert.assertEquals(-1L,
        MathUtils.difference(0d, Double.NEGATIVE_INFINITY));
    Assert.assertEquals(-1L,
        MathUtils.difference(0d, Double.POSITIVE_INFINITY));
    Assert.assertEquals(-1L, MathUtils.difference(0d, Double.NaN));

    Assert.assertEquals(-1L,
        MathUtils.difference(Double.POSITIVE_INFINITY, 0d));
    Assert.assertEquals(-1L,
        MathUtils.difference(Double.NEGATIVE_INFINITY, 0d));
    Assert.assertEquals(-1L, MathUtils.difference(Double.NaN, 0d));

    Assert.assertEquals(-1L,
        MathUtils.difference(1d, Double.NEGATIVE_INFINITY));
    Assert.assertEquals(-1L,
        MathUtils.difference(1d, Double.POSITIVE_INFINITY));
    Assert.assertEquals(-1L, MathUtils.difference(1d, Double.NaN));

    Assert.assertEquals(-1L,
        MathUtils.difference(Double.POSITIVE_INFINITY, 1d));
    Assert.assertEquals(-1L,
        MathUtils.difference(Double.NEGATIVE_INFINITY, 1d));
    Assert.assertEquals(-1L, MathUtils.difference(Double.NaN, 1d));

    Assert.assertEquals(-1L,
        MathUtils.difference(-1d, Double.NEGATIVE_INFINITY));
    Assert.assertEquals(-1L,
        MathUtils.difference(-1d, Double.POSITIVE_INFINITY));
    Assert.assertEquals(-1L, MathUtils.difference(-1d, Double.NaN));

    Assert.assertEquals(-1L,
        MathUtils.difference(Double.POSITIVE_INFINITY, -1d));
    Assert.assertEquals(-1L,
        MathUtils.difference(Double.NEGATIVE_INFINITY, -1d));
    Assert.assertEquals(-1L, MathUtils.difference(Double.NaN, -1d));
  }
}

I'd be thankful for any counter-indications or issues not yet covered by the code.
Cheers,
   Thomas.

A: It seems you could just take the doubleToRawLongBits of the two values and subtract them (plus some extra logic to take care of the sign, crossing zero, and Inf/NaN).
Since all nextUp does is add one, the results of a subtraction should be consistent with the number of steps.


text:
Q: QT StyleSheet Theme for entire application using attribute selectors Background:
I have a Qt application consisting of multiple dialogs and windows. I am trying to condense all styles into a single stylesheet which I want to load in my main.cpp with the aim of it being applied to my whole application (as I understand one should do). The application should not change styles from this point onwards.
I want to do this as styles can get mixed up, etc if one does this or something simliar for each widget in the QtCreator designer.
Problem:
I will explain a specific problem I face with an example from my application.
I have a couple of variations of simple dialogs, QLabel title, QLabel message (sometimes a QLabel hint), and either a single 'ok' QPushButton or 2 QPushButtons 'positive' & 'negative'.
For my theme, I would like to set styles for specific buttons, labels, etc which I got from here.
Example CSS:
QPushButton {
    font-size: 10pt
    color: #111
}

QPushButton[objectName="btnPostive"][objectName="btnProceed"] {
    font-size: 1pt
    color: #ccc
}

QLabel {
    font-size: 9pt
    color: #111
}

QLabel[objectName="lblTitle"] {
    font-size: 9pt
    color: #111
}

Please note, the [objectName="btnPostive"][objectName="btnProceed"] is intended to apply the style to buttons with the objectName's btnPostive and btnProceed however, it does not.
Is what I intend doing considered best practice, and a sub question (preferred example too) applying the same style to a select group of widgets, how should one best  this.

A: If you want to control the applied stylesheet based on the object name, you can use the ID Selector QPushButton#objectName, see the full documentation.  You separate multiple objects with the same stylesheet with a ,
Your stylesheet should then be this.  Please note that you also need a ; at the end of each line.
QPushButton {
    font-size: 10pt;
    color: #111;
}

QPushButton#btnPositive, QPushButton#btnProceed {
    font-size: 1pt;
    color: #ccc;
}

QLabel {
    font-size: 9pt;
    color: #111;
}

QLabel#lblTitle {
    font-size: 9pt;
    color: #00f;
}


text:
Q: Blazor project's httpClient does not send request to WebApi project I created a custom solution containing a Blazor project, two class libraries and a WebApi project, I configured two different ports for blazor and api projects (since it is not possible to use one port), The api app url is: http://localhost:36855/, I copied a working blazor wasm (standard Microsoft template of 3 projects in a solution) files to these projects and I expected them to work, The Api project runs and I can test its action methods with postman, The Blazor project also runs but it can't send request to webapi projects, for example in the login page I have:
private async void HandleValidSubmit()
{
    AjaxLoading = true;
    DisableLoginButton = true;
    ReturnModel = await genericService.PostModelAsyncOld<LoginModel>("api/Account/Login", Model);
    ...
}

The generic service is a class that httpclient is injected to it and its task is contacting with the server and Get and Post methods (it works in the project that I copied here):
public class GenericService : IGenericService
{
    private HttpClient httpClient;
    public GenericService(HttpClient httpClient)
    {
        this.httpClient = httpClient;
        //this.httpClient.BaseAddress = new Uri("http://localhost:36855/");
    }

    public async Task<AsyncReturn<TModel>> PostModelAsyncOld<TModel>(string uri, TModel model)
    {
        TModel returnModel = default(TModel);

        HttpResponseMessage result =
            await httpClient.PostAsync(uri, new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json"));
        if (result.IsSuccessStatusCode)
        {
            returnModel = JsonConvert.DeserializeObject<TModel>(result.Content.ReadAsStringAsync().Result);                ;
            return new AsyncReturn<TModel>()
            { AsyncSuccess = true, Model = returnModel, StatusCode = System.Net.HttpStatusCode.OK };
        }
        else
        {
            return new AsyncReturn<TModel>()
            { AsyncSuccess = false, Model = default(TModel), StatusCode = result.StatusCode };
        }

    }
 }

The api controller and action method (only works with PostMan not by HttpClient):
[ApiController]
[Route("api/[controller]")]
public class AccountController : Controller
{
    ....
    // inject services and other methods
    ....

    [HttpPost]
    [Route("Login")]
    public async Task<LoginModel> Login(LoginModel model)    //, string returnUrl, string culture)
    {
        if (ModelState.IsValid) // **Breakpoint here, only hits with PostMan not by Blazor App**
        {
          ....

I also went to program.cs and made this change:
public class Program
{
    public static async Task Main(string[] args)
    {
        var builder = WebAssemblyHostBuilder.CreateDefault(args);
        builder.RootComponents.Add<App>("app");

        // The following line is the change:
        builder.Services.AddSingleton(sp => new HttpClient() { BaseAddress = new Uri("http://localhost:36855/") });           //builder.HostEnvironment.BaseAddress) });

        builder.Services
          .AddHttpContextAccessor()
          .AddScoped<HttpContextAccessor>()
          .AddSingleton<ITokenService, TokenService>()
          .AddSingleton<IGenericService, GenericService>()
          .AddSingleton<ViewDataService>()
          .AddBlazoredSessionStorage();

I did everything to make this work and it was not successful, What is the problem here?

A: After seeing Blazor error message through F12 I realized that CORS was causing this issue, So I added these lines of codes in ConfigureServices and Configure methods in startup file that solved the problem:
services.AddCors();

app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());


text:
Q: Summing up over partitions. Confused on notation "Tao Analysis I" Ill first just give some preliminary Definitions I am trying to relate and a bit confused the first definition for summing up a partition.

Definition (Summation over finite sets) Let $X$ be a finite set with $n$ elements let $f:X \rightarrow\mathbb R$ be a function. We define $\displaystyle \sum_{x \in X} f(x)$ as follows. Select any bijection $g$ from {${i \in  N : 1 \leq i \leq n}$} to $X$ we then define:
$\displaystyle \sum_{x \in X} f(x)$ $:=$ $\sum_{i=1}^{n} f(g(i))$

Definition If $I$ is a bounded interval, we define the length of $I$, denoted $|I|$ as follows. If $I$ is one of the intervals $(a,b), [a,b], (a,b], [a,b)$ for some real numbers $a<b$ then we define $|I| := |b-a|$

Definition (Partions) Let $I$ be a bounded interval. A Partition of $I$ is a finite set P of bounded intervals contained in $I$, such that every $x$ in $I$ lies in exactly one of the bounded intervals $J$ in P

He then goes on to state a theorem where
$|I| = \displaystyle \sum_{J \in P} |J|$
and my question is how does the notation:
"$\displaystyle \sum_{J \in P} |J|$" translate into the above definition? Im a bit confused by it when talking about partitions.
For example if we let $P$ be the partition of $(0,1)$ by $\{(0,\frac{1}{2}], (\frac{1}{2},1)\}$
then is it simply:

let $g:\{1,2\} \rightarrow\ P$ by say $g(1) := (0,\frac{1}{2}]$ and $g(2) := (\frac{1}{2},1)$ then we have $\displaystyle \sum_{J \in P} |J| = \sum_{i=1}^{2} |(g(i)|$ ?

or is it this one (following the above definition more precisely)

$f:P \rightarrow\mathbb R$ by $f(J) = |b-a|$ and let $g:\{1,2\} \rightarrow\ P$ by say $g(1) := (0,\frac{1}{2}]$ and $g(2) := (\frac{1}{2},1)$ then we have $\displaystyle \sum_{J \in P} |J| = \sum_{J \in P} f(J)$ $:= \sum_{i=1}^{2} f(g(i))$

A: Both are correct.
Your second version is just introducing a formal "length" function $f$, which is exactly the two bars in your first interpretation.


text:
Q: Pointwise mutual information on text I was wondering how one would calculate the pointwise mutual information for text classification. To be more exact, I want to classify tweets in categories. I have a dataset of tweets (which are annotated), and I have a dictionary per category of words which belong to that category. Given this information, how is it possible to calculate the PMI for each category per tweet, to classify a tweet in one of these categories.

A: PMI is a measure of association between a feature (in your case a word) and a class (category), not between a document (tweet) and a category. The formula is available on Wikipedia:
                  P(x, y)
pmi(x ,y) = log ------------
                  P(x)P(y)

In that formula, X is the random variable that models the occurrence of a word, and Y models the occurrence of a class. For a given word x and a given class y, you can use PMI to decide if a feature is informative or not, and you can do feature selection on that basis. Having less features often improves the performance of your classification algorithm and speeds it up considerably. The classification step, however, is separate- PMI only helps you select better features to feed into your learning algorithm.

Edit:
One thing I didn't mention in the original post is that PMI is sensitive to word frequencies. Let's rewrite the formula as
                  P(x, y)             P(x|y)
pmi(x ,y) = log ------------ = log ------------
                  P(x)P(y)             P(x)

When x and y are perfectly correlated, P(x|y) = P(y|x) = 1, so pmi(x,y) = 1/P(x). Less frequent x-es (words) will have a higher PMI score than frequent x-es, even if both are perfectly correlated with y.


text:
Q: Starting Activity with some `put extra` onClick of a recyclerView Item I want to pass an object from one activity to another on click of Item in Recycler view. Now the thing I have came across for handling item click is:
public static class RecylerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    public RecylerViewHolder(final View itemView) {
        super(itemView);
        itemView.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Context context = itemView.getContext();
        Intent intent = new Intent(context, DetailAct.class);
        context.startActivity(intent);
    }
}

Obviously it is an inner static class. Now I have to call the object which I am inflating in the item to be passed into next Activity. And that object is in its outer class i.e in onBindViewHolder of Adapter class.
So When I researched, I found that We should not call variables of outer class from inner static class. I also thought of creating a constructor in my activity to pass object but then then I might be wrong beacause that way I am not going to create any activity. Now  I am totally confused how to do this. Please help

A: In your onClick() method, you can call getPosition() which will give you the position in you dataset of the clicked item. With that information, you access the properties in your dataset particular item, and pass them to your activity via putExtra() intent method.


text:
Q: Invalid regular expression in HTML5 input pattern in email input I need to use this regular expression in a HTML input (Email Type), I used to create a regex here  to match what we wanted to validate http://regexr.com/3gib9
Regex
/^([A-Z|a-z|0-9](\.|_){0,1})+[A-Z|a-z|0-9]\@([A-Z|a-z|0-9])+((\.){0,1}[A-Z|a-z|0-9]){2}\.(com|net|org|co|org)+((\.[A-Z|a-z|0-9]{2,4})?)$/gm

Pattern
^([A-Z|a-z|0-9](\.|_){0,1})+[A-Z|a-z|0-9]\@([A-Z|a-z|0-9])+((\.){0,1}[A-Z|a-z|0-9]){2}\.(com|net|org|co|org)+((\.[A-Z|a-z|0-9]{2,4})?)$

Element with Pattern
<input type="email" pattern="^([A-Z|a-z|0-9](\.|_){0,1})+[A-Z|a-z|0-9]\@([A-Z|a-z|0-9])+((\.){0,1}[A-Z|a-z|0-9]){2}\.(com|net|org|co|org)+((\.[A-Z|a-z|0-9]{2,4})?)$" name="email" class="form-control" placeholder="email address" value="<%= session("user_email_addr") %>" required="required" title="Please input a valid email">

And now I am getting this error (Invalid Escape) when I input any email in the form
Pattern attribute value ^([A-Z|a-z|0-9](\.|_){0,1})+[A-Z|a-z|0-9]\@([A-Z|a-z|0-9])+((\.){0,1}[A-Z|a-z|0-9]){2}\.(com|net|org|co|org)+((\.[A-Z|a-z|0-9]{2,4})?)$ is not a valid regular expression: Uncaught SyntaxError: Invalid regular expression: /^([A-Z|a-z|0-9](\.|_){0,1})+[A-Z|a-z|0-9]\@([A-Z|a-z|0-9])+((\.){0,1}[A-Z|a-z|0-9]){2}\.(com|net|org|co|org)+((\.[A-Z|a-z|0-9]{2,4})?)$/: Invalid escape

How can I made this work?

A: You need to remove unnecessary escaping backslashes and wrong | inside character classs, and just redundant constructs:
pattern="([A-Za-z0-9][._]?)+[A-Za-z0-9]@[A-Za-z0-9]+(\.?[A-Za-z0-9]){2}\.(com?|net|org)+(\.[A-Za-z0-9]{2,4})?"

See a demo below:

input:valid {
  color: green;
}
input:invalid {
  color: red;
}
<form name="form1">
 <input pattern="([A-Za-z0-9][._]?)+[A-Za-z0-9]@[A-Za-z0-9]+(\.?[A-Za-z0-9]){2}\.(com?|net|org)+(\.[A-Za-z0-9]{2,4})?" title="Wrong email!"/>
 <input type="Submit"/>
</form>

Details

*

*^...$ - the anchors are not necessary in HTML5 pattern since the regex is anchored by default (^(?: and )$ are added to the pattern automatically when translated into a regex)

*[A-Z|a-z|0-9] - the | inside a character class is treated as a literal | symbol, not as an alternation operator

*(\.|_){0,1} - the single char alternation makes little sense when one can use a character class, [._] is a more natural construct here. Besides, {0,1} is more naturally written as ? quantifier.

*\@ - the Culprit! - this char does not have to be escaped, and can't be escaped in an ES6 regex pattern that has a u modifier (this is a regex that HTML5 pattern translates into, e.g. pattern="[A-Z]" will be translated into /^(?:[A-Z])$/u regex)

*(com|net|org|co|org) can be reduced to (com?|net|org): com? matches com and co (thus, co alternative may be removed) and org is repeated twice.

There might be other enhancements here, but you can also just use
type="email"

HTML5 email validation attribute.


text:
Q: How to get the value of the artist name from this JSON object? I have the following JSON object (sorry for the length) which I need to get the name of the artists. It should be under tracks -> items -> album -> artists -> name. I am trying to run this code but I can't grab the artist name. Here is part of the JSON object:
{
  "tracks" : {
    "href" : "https://api.spotify.com/v1/search?query=closer&type=track&offset=0&limit=20",
    "items" : [ {
      "album" : {
        "album_type" : "single",
        "artists" : [ {
          "external_urls" : {
            "spotify" : "https://open.spotify.com/artist/69GGBxA162lTqCwzJG5jLp"
          },
          "href" : "https://api.spotify.com/v1/artists/69GGBxA162lTqCwzJG5jLp",
          "id" : "69GGBxA162lTqCwzJG5jLp",
          "name" : "The Chainsmokers",
          "type" : "artist",
          "uri" : "spotify:artist:69GGBxA162lTqCwzJG5jLp"
        } ],
        "available_markets" : [ "AD", "AR", "AT", "AU", "BE", "BG", "BO", "BR", "CA", "CH", "CL", "CO", "CR", "CY", "CZ", "DE", "DK", "DO", "EC", "EE", "ES", "FI", "FR", "GB", "GR", "GT", "HK", "HN", "HU", "ID", "IE", "IS", "IT", "JP", "LI", "LT", "LU", "LV", "MC", "MT", "MX", "MY", "NI", "NL", "NO", "NZ", "PA", "PE", "PH", "PL", "PT", "PY", "SE", "SG", "SK", "SV", "TR", "TW", "US", "UY" ],

.....
I need to get the line where it says "name" : "The Chainsmokers",, but I can't figure it out. This is what I have so far:
JSONObject jObj;
JSONObject tracks;
JSONArray items;
JSONObject album;
JSONArray artists;
JSONObject aName;
jObj = new JSONObject(json);
tracks = (JSONObject) jObj.get("tracks");
items = (JSONArray) tracks.get("items");
String songName;
Log.d("searchSong", json);
// Return all of the results for the searched song. This will return to a ListView with the song name, uri, and artist name.
for (int i = 0; i < items.length(); i++) {
    try {
        songName = items.getJSONObject(i).getString("name");
        if (!(songName.toLowerCase().contains(query.toLowerCase()))) {
            continue;
        }
        // TODO THIS DOESN'T WORK!!!!
        // How do I get artistname????
        album = (JSONObject) items.getJSONObject(i).get("album");
        artists = album.getJSONArray("artists");    // get the artist name
        String artistsName = artists.getJSONObject(4).toString();
        String artistName = "";
        artistName = artists.getJSONObject(i).getString("name");

        // This stuff works
        id = items.getJSONObject(i).getString("id");
        lViewSearch.setVisibility(View.VISIBLE);
        lView.setVisibility(View.INVISIBLE);
        bNext.setVisibility(View.INVISIBLE);
        bPlay.setVisibility(View.INVISIBLE);
        searchSongs.add(songName + "\n" + id);
        searchAdapter.notifyDataSetChanged();
        svSong.clearFocus();
    } catch (JSONException e) {
        e.printStackTrace();
    }
} // end for loop

This is in a for loop because I need to get all of the songs, here I only posted the JSON object for part of it. Let me know if you see any problems, thanks!

A: What is artists.getJSONObject(4)? Your array only seems to show one object in the array.
Should just be...
artists.getJSONObject(0).getString("name")


text:
Q: How to change values on specific days for report generated from mysql I am generating an attendance report in mysql, by pulling the data from 3 tables like student name and roll no from admissions table, Absent details from absentees table and I have created a calendar table for generating desired output I am able to generate output here is my database and the result I am generating. SQL Fiddle
Now I want to display wherever 'SUN' occurs in Table as 'S' and also if there any holiday dates in the report, should show them as 'H'.
Could anyone tell me what should I do in my query to produce the expected result?
My data:
CREATE TABLE tbl_admission
    (`StudentName` varchar(5), `RollNo` int, `Class` int)
;

INSERT INTO tbl_admission
    (`StudentName`, `RollNo`, `Class`)
VALUES
    ('Naren', 1, 22),
    ('Srinu', 2, 22),
    ('Blah', 3, 22)
;

CREATE TABLE tbl_absentees
    (`Date` datetime, `Status` varchar(1), `RollNo` int, `Class` int)
;

INSERT INTO tbl_absentees
    (`Date`, `Status`, `RollNo`, `Class`)
VALUES
    ('2013-06-01 00:00:00', 'A', 1, 22),
    ('2013-06-02 00:00:00', 'A', 1, 22),
    ('2013-06-03 00:00:00', 'A', 1, 22),
    ('2013-06-04 00:00:00', 'A', 1, 22),
    ('2013-06-05 00:00:00', 'A', 1, 22),
    ('2013-06-06 00:00:00', 'A', 1, 22),
    ('2013-06-07 00:00:00', 'A', 1, 22),
    ('2013-06-08 00:00:00', 'A', 1, 22),
    ('2013-06-09 00:00:00', 'A', 1, 22),
    ('2013-06-10 00:00:00', 'A', 1, 22),
    ('2013-06-11 00:00:00', 'A', 1, 22),
    ('2013-06-12 00:00:00', 'A', 1, 22),
    ('2013-06-13 00:00:00', 'A', 1, 22),
    ('2013-06-14 00:00:00', 'A', 1, 22),
    ('2013-06-15 00:00:00', 'A', 1, 22),
    ('2013-06-16 00:00:00', 'A', 1, 22),
    ('2013-06-17 00:00:00', 'A', 1, 22),
    ('2013-06-18 00:00:00', 'A', 1, 22),
    ('2013-06-19 00:00:00', 'A', 1, 22),
    ('2013-06-20 00:00:00', 'A', 1, 22)
;

CREATE TABLE calendar
    (`Date` datetime)
;

INSERT INTO calendar
    (`Date`)
VALUES
    ('2013-06-01 00:00:00'),
    ('2013-06-02 00:00:00'),
    ('2013-06-03 00:00:00'),
    ('2013-06-04 00:00:00'),
    ('2013-06-05 00:00:00'),
    ('2013-06-06 00:00:00'),
    ('2013-06-07 00:00:00'),
    ('2013-06-08 00:00:00'),
    ('2013-06-09 00:00:00'),
    ('2013-06-10 00:00:00'),
    ('2013-06-11 00:00:00'),
    ('2013-06-12 00:00:00'),
    ('2013-06-13 00:00:00'),
    ('2013-06-14 00:00:00'),
    ('2013-06-15 00:00:00'),
    ('2013-06-16 00:00:00'),
    ('2013-06-17 00:00:00'),
    ('2013-06-18 00:00:00'),
    ('2013-06-19 00:00:00'),
    ('2013-06-20 00:00:00');

CREATE TABLE `tbl_holidays` (
  `id` int(11) NOT NULL auto_increment,
  `Hname` varchar(60) NOT NULL,
  `Htype` varchar(45) default NULL,
  `StartDate` date default NULL,
  `ToDate` date default NULL,
  `Descr` varchar(75) default NULL,
  `status` tinyint(4) default '1',
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `tbl_holidays` (`id`, `Hname`, `Htype`, `StartDate`, `ToDate`, `Descr`, `status`) VALUES (1,'Independence Day','Mandatory','2013-08-15','2013-08-15','It is Mandatory Holiday',1),(2,'Ramzan','Optional','2013-09-09','2013-09-09','It is Optional Holiday',1),(3,'UGADHI','Mandatory','2013-07-01','2013-07-02','efdrvb ',1);

My Current Code:
set session group_concat_max_len= 2048;

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'max(CASE WHEN ca.date = ''',
      date_format(date, '%Y-%m-%d'),
      ''' THEN coalesce(p.status, ''P'') END) AS `',
      date_format(date, '%a %d'), '`'
    )
  ) INTO @sql
FROM calendar
where date>='2013-06-01'
  and date <= '2013-06-12';

SET @sql
  = CONCAT('SELECT ca.studentname,
              ca.rollno,
              ca.class, ', @sql, '
            from
            (
              select c.date, a.studentname, a.rollno, a.class
              from calendar c
              cross join tbl_admission a
            ) ca
            left join tbl_absentees p
              on ca.rollno = p.rollno
              and ca.date = p.date
            where ca.date>=''2013-06-01''
              and ca.date <= ''2013-06-05''
            group by ca.studentname, ca.rollno, ca.class
            order by ca.rollno');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

A: As I suggested in my comments, when you are altering the code for a dynamic SQL solution I would always suggest that you write the SQL query first so you can get the JOINs and logic correct, then convert it to dynamic SQL.
The first thing you need to do to get the result is to incorporate the tbl_Holidays.  I would start the query by joining it to you calendar table, then you can easily identify what dates are holidays:
select c.date,
  case when h.startdate is null then 'N' else 'Y' end holiday
from calendar c
left join tbl_holidays h
  on c.date = h.startdate;

Once you have a list of the dates and holiday, then just like your previous query, you will cross join this result to tbl_admission:
select ch.date, ch.holiday, a.studentname, a.rollno, a.class
from
(
  select c.date,
    case when h.startdate is null then 'N' else 'Y' end holiday
  from calendar c
  left join tbl_holidays h
    on c.date = h.startdate
) ch
cross join tbl_admission a;

See Demo. This will give you a list of all of dates, the holidays and the students that you can then join to your tbl_absentees to determine who was present/absent on each day.
Now, since you want to change the display value in the result based on if the day is a Sunday or a Holiday, then you will need to alter your original CASE expression.  The new code will be similar to the following:
max(CASE WHEN ca.date = '2013-06-01' then
      case
          when ca.holiday = 'Y'  then 'H'
          when dayname(ca.date) = 'SUNDAY' then 'S'
          else coalesce(p.status, 'P') end END) AS `SAT 01`

The new CASE expression does 4 things:

*

*Checks the date

*If the date is a holiday, then display an H

*If the date is a Sunday, then display an S

*if it is not a holiday or a Sunday, then display the A/P that you initially had.

Putting the entire code together you will have a static version of the query that looks like:
SELECT ca.studentname,
  ca.rollno,
  ca.class,
  max(CASE WHEN ca.date = '2013-06-01' then
          case
              when ca.holiday = 'Y'  then 'H'
              when dayname(ca.date) = 'SUNDAY' then 'S'
              else coalesce(p.status, 'P') end END) AS `SAT 01`,
  max(CASE when ca.date = '2013-06-02' then
        case
          when ca.holiday = 'Y'  then 'H'
          when dayname(ca.date) = 'SUNDAY' then 'S'
          else coalesce(p.status, 'P') end END) AS `SUN 02`,
  max(CASE WHEN ca.date = '2013-06-03' then
        case
          when ca.holiday = 'Y'  then 'H'
          when dayname(ca.date) = 'SUNDAY' then 'S'
          else coalesce(p.status, 'P') end END) AS `MON 03`
from
(
  select ch.date, ch.holiday, a.studentname, a.rollno, a.class
  from
  (
    select c.date,
      case when h.startdate is null then 'N' else 'Y' end holiday
    from calendar c
    left join tbl_holidays h
      on c.date = h.startdate
  ) ch
  cross join tbl_admission a
) ca
left join tbl_absentees p
  on ca.rollno = p.rollno
  and ca.date = p.date
where ca.date>='2013-06-01'
  and ca.date <= '2013-06-05'
group by ca.studentname, ca.rollno, ca.class
order by ca.rollno;

See SQL Fiddle with Demo.  Now that you have a static version with working logic you can convert into your dynamic SQL code:
set session group_concat_max_len= 5000;

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'max(CASE WHEN ca.date = ''',
      date_format(date, '%Y-%m-%d'),
      ''' THEN
            case
              when ca.holiday = ''Y'' then ''H''
              when dayname(ca.date)=''Sunday'' then ''S''
              else coalesce(p.status, ''P'') end end) AS `',
      date_format(date, '%a %d'), '`'
    )
  ) INTO @sql
FROM calendar
where date>='2013-06-01'
  and date <= '2013-06-12';

SET @sql
  = CONCAT('SELECT ca.studentname,
              ca.rollno,
              ca.class, ', @sql, '
            from
            (
              select ch.date, ch.holiday, a.studentname, a.rollno, a.class
              from
              (
                select c.date,
                  case when h.startdate is null then ''N'' else ''Y'' end holiday
                from calendar c
                left join tbl_holidays h
                  on c.date = h.startdate
              ) ch
              cross join tbl_admission a
            ) ca
            left join tbl_absentees p
              on ca.rollno = p.rollno
              and ca.date = p.date
            where ca.date>=''2013-06-01''
              and ca.date <= ''2013-06-05''
            group by ca.studentname, ca.rollno, ca.class
            order by ca.rollno');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

See SQL Fiddle with Demo.  A few side notes, since you are adding significantly more characters in the sql string you might have to increase the session length for group_concat_max_len.  Also, you could reduce the number of characters by using MySQL's abbreviated IF() logic to replace the CASE expressions.
This new version of the code will give you a result:
| STUDENTNAME | ROLLNO | CLASS | SAT 01 | SUN 02 | MON 03 | TUE 04 | WED 05 | THU 06 | FRI 07 | SAT 08 | SUN 09 | MON 10 | TUE 11 | WED 12 |
--------------------------------------------------------------------------------------------------------------------------------------------
|       Naren |      1 |    22 |      A |      S |      H |      A |      A | (null) | (null) | (null) | (null) | (null) | (null) | (null) |
|       Srinu |      2 |    22 |      P |      S |      H |      P |      P | (null) | (null) | (null) | (null) | (null) | (null) | (null) |
|        Blah |      3 |    22 |      P |      S |      H |      P |      P | (null) | (null) | (null) | (null) | (null) | (null) | (null) |


text:
Q: Divisibility Proof with Induction - Stuck on Induction Step I'm working on a problem that's given me the run around for about a weekend. The statement:
For all $m$ greater than or equal to $2$ and for all $n$ greater than or equal to $0$, $m - 1$ divides $m^n - 1$.
Using induction over $n$, the base step comes easy since $m^n - 1$ is $0$ when $n = 0$.
My induction hypothesis is letting $k \geq 0$ and assuming that $m - 1$ divides $m^k - 1$. In order to show that $m - 1$ divides $m^{k+1} - 1$, I obviously need to use the induction hypothesis. However, no matter where I try to use the fact that $m^k - 1 = (m-1)a$ for some $a$ in the integers, the expression $m^{k+1} - 1$ always becomes more difficult to get to $m^{k+1} - 1$ being equal to $(m-1)b$ for some $b$ in the integers.
In other words, I can't figure out any actually helpful way to apply the induction hypothesis with the goal of proving the next step.
Any help would be appreciated!

A: It may be of interest to some that the claim in question may be proved by a simple application of double induction where we induct on two variables simultaneously. It is definitely overkill, but I think this proof technique is pretty sexy when it can be applied, and this is certainly one instance. Since using double induction is not too common, I thought I would include a blurb about it from David Gunderson's Handbook of Mathematical Induction before giving the proof.
Blurb: Many mathematical statements involve two (or more) variables, each of which vary independently over, say, $\mathbb{N}$. Some such statements can be proved by induction in different ways. Let $S(m,n)$ be a statement involving two positive integer variables $m$ and $n$. One method to prove $S(m,n)$ for all $m\geq 1$ and $n\geq 1$ is to first prove $S(1,1)$, then by induction prove $S(m,1)$ for each $m$, and then for each fixed $m_0$, inductively prove $S(m_0,n)$ for all $n$. [ p. 44]

Problem: Show that $S(m,n)$ is true where
$$
S(m,n) : (\forall m\in\mathbb{Z^+}\setminus\{1\})(\forall n\in\mathbb{Z^+}\cup\{0\})[(m-1)\mid (m^n-1)].
$$
Proof. First we prove that $S(m,0)$ is true for all $m\geq 2$.
Base step: The statement $S(2,0)$ is true since $(2-1)\mid (2^0-1)$.
Inductive step (inducting on $m$): For some $k\geq 2$, assume that $S(k,0)$ is true; that is, $(k-1)\mid (k^0-1)$. Since $((k+1)-1)\mid ((k+1)^0-1)$ is clearly true for all $k\geq 2$, we can see that $S(k,0)\to S(k+1,0)$, and by mathematical induction, for all $m\geq 2, S(m,0)$ is true.
Now fix an arbitrary $m_0$. Then $S(m_0,0)$ is true and so this is a base step for proving that for all $n, S(m_0,n)$ holds.
Inductive step (inducting on $n$): This step is of the form $S(m_0,\ell)\to S(m_0,\ell+1)$. Let $\ell\geq 0$ be fixed and assume that $S(m_0,\ell)$ is true, that is, $(m_0-1)\mid (m_0^\ell-1)$. Starting with the right-hand side of $S(m_0,\ell+1)$,
\begin{align}
m_0^{\ell+1}-1 &=m_0(m_0^\ell-1)+(m_0-1)\\[0.5em]
               &=m_0[\eta(m_0-1)]+(m_0-1)\tag{by $S(m_0,\ell);\eta\in\Bbb{Z}$}\\[0.5em]
               &=(\eta m_0+1)(m_0-1)\tag{factor}\\[0.5em]
               &=\gamma(m_0-1),\tag{$\gamma=\eta m_0+1$}
\end{align}
which is a multiple of the left-hand side of $S(m_0,\ell+1)$, where $\gamma=\eta m_0+1$ and $\gamma\in\Bbb{Z}$ since $1,\eta,m_0\in\Bbb{Z}$ (closure of addition and multiplication in $\Bbb{Z}$). Since $m_0^{\ell+1}-1=\gamma(m_0-1)$, we can see that, by definition, $(m_0-1)\mid (m_0^{\ell+1}-1)$; hence, by induction, for each fixed $m_0$ and $n\geq 0, S(m_0,n)$ is true, completing the inductive step.
Since $m_0$ was arbitrary, by induction, for all $m\geq 2$ and $n\geq 0$ the statement $S(m,n)$ is proved. $\Box$

A: Hint:
$$m^{k+1}-1=m^{k+1}-m^k+m^k-1$$
Can you take it from there?


text:
Q: Drawing on HTML5 Canvas Is there a putpixel functionality in html5. I have a canvas and want to draw on the canvas using mouse. How should I wright the javascript function for that. How can can I take the coordinate value on mouseclick and change the pixel value as soon as the user clicks.

A: From http://net.tutsplus.com/tutorials/javascript-ajax/canvas-from-scratch-pixel-manipulation/  section "Putting this into practice" using jquery:
$(canvas).click(function(e) {
    var canvasOffset = $(canvas).offset();
    var canvasX = Math.floor(e.pageX-canvasOffset.left);
    var canvasY = Math.floor(e.pageY-canvasOffset.top);

    // do here whatever you want
});

Read the article for a detailed explanation.

A: If you have a intermediate knowledge of Javascript try reading a tutorial like this:
http://www.williammalone.com/articles/create-html5-canvas-javascript-drawing-app/


text:
Q: What concept does an open set axiomatise? In the context of metric (and in general first-countable) topologies, it's reasonably clear what a closed set is: a set $F$ is closed if and only if every convergent sequence of points in $F$ converges to a point also in $F$. This naturally generalises to the definition of a closed set in an arbitrary topological space using the concept of limit points... but limit points are defined in terms of open sets, which are, to me, somewhat more mysterious than closed sets.
I was once told that ultrafilters axiomatise the concept of (sets of) big sets. I'm hoping here to find a similar conceptual picture of topologies defined by systems of open sets, preferably without reference to closed sets. One such explanation I've seen is that open set axiomatise the concept of nearness, which, I suppose, is fair enough at least for metric topologies. Indeed, if something is "happening" at points near $x \in X$, then it's usually the case that every open neighbourhood $U \subseteq X$ of $x$ contains an open subset $V \subseteq U$, $x \in V$, such that the something "happens" at all points in $V$. But what about non-metrisable topologies, particularly the coarse ones where there are no "small" open sets?
Consider, for example, the Zariski topology on affine $n$-space $\mathbb{A}^n$. $\mathbb{A}^n$ is irreducible, so every non-empty open set is dense. It seems reasonable to interpret this to mean that every non-empty open set is "large". Indeed, if we work over the complex numbers, then in the usual metric geometry, Zariski-open sets are unbounded and have full measure, so are very large indeed, so I don't think it's fair to say that open sets are capturing the notion of nearness here.
I'm also curious about the history of point set topology. When were the axioms first written down? What were the first "non-geometric" examples of topological spaces — "non-geometric" here referring to either non-metrisable topologies or topologies on sets other than sets of points of some intuitively geometric object — and were they part of the motivations for creating point set topology?

A: Edit, 7/10/11: The idea below was recently also discussed in this blog post by Michael O'Connor.

This was thoroughly discussed on MathOverflow. The answers that I found most convincing can be summarized as follows: open sets axiomatize the notion of a semidecidable property.
That is, open sets axiomatize the notion of a condition whose truth can be verified in finite time (but whose falsehood cannot necessarily be verified in finite time). A continuous function $f : A \to B$ between two spaces is a function such that the preimage of any semidecidable subset is semidecidable, hence is a computable function in the sense that a decision procedure to verify whether $f(a) \in U \subset B$ in finite time gives a decision procedure to verify whether $a \in V \subset A$ in finite time.
To really make sense of what I just said above you should think of $A$ as the set of possible conditions of some system, $f$ as a measurement of some property of the system, and $B$ as the set of possible values of the property you're measuring. Then $f$ is computable precisely when information about $f(a)$ allows us to deduce information about $a$. In some sense it is the central premise of the scientific method that this is possible.
Note that the above description really brings out the special role of the Sierpinski space $\mathbb{S}$. Indeed, a subset of a topological space $X$ is open precisely when the indicator function $X \to \mathbb{S}$ is continuous.
Onto the axioms:

*

*The union of an arbitrary collection of open sets is open because any decision procedures to verify conditions $U_i, i \in I$ in finite time can be run in parallel to verify condition $\bigcup U_i$ in finite time.

*The intersection of a finite collection, but not necessarily an infinite collection, of open sets is open because a finite number of decision procedures to verify conditions $U_1, ... U_n$ in finite time can be run in parallel to verify condition $\bigcap U_i$ in finite time, but this is not necessarily true of an infinite number of decision procedures, which may take an unbounded amount of time to all complete.

*The empty set and the entire space are open because both of these conditions can be verified in zero time.

Finally, note that it is intuitively possible to verify whether a point in a metric space lies in an open ball in finite time by showing that it lies in an even smaller open ball (which can be done using finite-precision computations), but it is not necessarily possible to do the same for a closed ball because the point may lie on the boundary and we cannot make arbitrarily precise measurements in finite time.
In the particular case of the Zariski topology, it is always possible to verify in finite time whether a polynomial is nonzero at a point by computing with sufficient precision, but without additional information it is not necessarily possible to verify in finite time whether a polynomial is zero at a point.

A: I just want to give an example to the Qiaochu's beautiful answer.
In Jet Nestruev's book there is following physical interpretation of structures on smooth manifold (or rather how physical system can be modeled with smooth manifold):

*

*physical system = manifold $M$

*state of system = point of $M,$ $x\in M$

*measuring device = function on $M,$ $f:M\to\mathbb{R}$ (smooth, but stick to continuous ones)

Connecting this with Qiaochu's answer we get additional interpretation

*

*condition $C$ on system such that verifying if state satisfies $C$ only requires finite amount of measuring devices = open set in $M,$ $U\subset M.$

A: I think it's a mistake to look for meaning in open sets. They are simply an artifact of how topological spaces are commonly axiomatized.
To motivate this axiomatization, consider the high school definition of a continuous function from $\mathbb{R}$ to $\mathbb{R}$: $f$ is continuous at $x$ if for all $\varepsilon > 0$, $\exists \delta > 0$ such that if $x'$ is within $\delta$ of $x$, $f(x')$ is within $\varepsilon$ of $f(x)$. In other words, defining a ball centered at $x$ of radius $r > 0$, $B(x, r)$, to be the points (strictly) within $r$ of $x$, the definition reduces to this: for each ball $B := B(f(x), \varepsilon)$ there is a ball $B(x, \delta)$ that $f$ maps to $B$.
At this point we may see that there is no technical reason to require balls to consist of points within a certain distance of a center. We may simply define the balls in a space explicitly and carry over the definition of continuity to our new notion of spaces. The resulting notion of continuity is a strict generalization of the original definition and turns out to be very useful, allowing all sorts of spaces to be reasoned about similarly.
In other words, open sets make topological spaces work, and topological spaces are a very general notion of a set on which there is a notion of continuous functions.

A: Just wanted to add some clarification to Qiachou Yuan's enlightening answer:

*

*The union of an arbitrary collection of open sets is open because any decision procedures to verify conditions Ui,i∈I
U
i
,
i
∈
I
in finite time can be run in parallel to verify condition ⋃Ui
⋃
U
i
in finite time.

*The intersection of a finite collection, but not necessarily an infinite collection, of open sets is open because a finite number of decision procedures to verify conditions U1,...Un
U
1
,
.
.
.
U
n
in finite time can be run in parallel to verify condition ⋂Ui
⋂
U
i
in finite time, but this is not necessarily true of an infinite number of decision procedures, which may take an unbounded amount of time to all complete.

*The empty set and the entire space are open because both of these conditions can be verified in zero time.

In response to Zhen Lin's comment:

Sorry to resurrect an old question, but I just realised that the analogy is not quite so clear. It's reasonable enough to say that the union of a countable collection of semidecidable sets is again semidecidable, by a standard interleaving argument... but it's not clear that an uncountable union of semidecidable sets should be semidecidable. – Zhen Lin Jun 2 '11 at 17:21
@Zhen: you can run an arbitrary number of decision procedures in parallel. (This is a fairly idealized model of computation.) I'm not sure what you mean by "a standard interleaving argument." – Qiaochu Yuan Jun 2 '11 at 17:23
6
Hmmm. It's more idealised that Turing machines, that's for sure! By interleaving argument, I mean the following: Let P1,P2,P3,…
P
1
,
P
2
,
P
3
,
…
 be decision procedures. Then we can construct a single decision procedure P
P
which halts when some Pn
P
n
 halts in this fashion: First, run the step 1
1
 of P1
P
1
, then run step 1
1
 of P2
P
2
 and step 2
2
of P1
P
1
, and then run step 1
1
 of P3
P
3
, step 2
2
 of P2
P
2
, and step 3
3
 of P1
P
1
, and so on. I'm not entirely certain this is permitted in the Turing machine model, but it seems reasonable enough. – Zhen Lin Jun 2 '11 at 17:30
1
@Zhen: yes, this isn't a Turing machine model. – Qiaochu Yuan Jun 2 '11 at 18:28

Like Qiachou Yuan said, you can verify the openness of the union of arbitrary open sets in finite time by running the decision procedures for each Ui,i∈I in parallel (the total time would be equal to the slowest verification procedure).
However, this is not the case for an arbitrary intersection of open sets. This is because any decision procedure for verifying an intersection requires at least 2 open sets (to calculate the overlap). You could try to run this in parallel by computing the intersections of pairs of open sets, and then computing the intersections of the intersections, and so on. However, for an infinite collection of open sets, this process would have to continue indefinitely (to visualize this, remember that counting the integers by 2's - 0, 2, 4, ... - still produces a countably infinite set).
It's okay to run infinitely many decision processes in parallel (because we are already dealing with infinite spaces), but for infinite intersections even the parallel process wouldn't terminate.

A: I initially think there're some unclear points in the semi-decidability arguments, so I tried to post a question about them. However, I think I somehow resolved them as I was composing the question. So I will just post my questions as well as my answers here in case someone else runs in to the confusion.

Question 1: To compute the result of disjunction property, if we only need to witness the 'yes' answer from one procedure (the one disjunct that causes the whole disjunction to be true), why do other disjuncts even need to be semi-decidable? Can't they just be undecidable?
Answer 1: The semi-decidability assertion concerns only with the truth value of the entire property, rather than the truth values of individual components of the entire property, or how individual components are configured to make the entire property true. That is to say, the semi-decidability has to work with any configuration of the individual property. If one of the disjunct is undecidable, it may entirely be possible that the same disjunct is the only one that causes the whole disjunction to be true. As a consequence, our entire parallel-running procedure cannot yield 'yes' and because that undecidable sub-procedure gets stuck at finding the corresponding disjunct is actually true.

Question 2: If we can run infinite amount of procedure in parallel, why can't we do the same for the conjunction case? If all sub-procedure finishes in finite time, can't we just sum up their results?
Answer 2: Even if all of the sub-procedure terminates in finite time, the collection of infinite number of them doesn't need to terminate in finite time. Imagine there're $\mathbb{N}$ number of procedures, each finishing in $n \in \mathbb{N}$ time. To wait for all of them terminate the overall time is unbounded. Because as long as we say we can finish the observation in $n$ time, there will always be another procedure that requires $n + 1$ time to finish. This is different from the disjunction case, as in that case we only need to wait one of the procedure terminates.


text:
Q: Why do Chrome & Firefox slowly render my home page using MathJax? This is my experimental site using MathJax.
I browse it using Chrome, Firefox, and IE.
I notice that IE renders slowly. But Chrome and Firefox do more slowly. :-)
Is there any secret tip to speed up the rendering?
Edit 1
I am still uploading the MathJax using FileZilla now to the remote server.
It needs much time to complete.
Even I use my development machine as a server with MathJax libraries installed, the result is the same as what I did above in remote server.

A: Your site is returning 404 requests for these files:

*

*http://www.begolu.com/MathJax/fonts/HTML-CSS/TeX/otf/MathJax_Size4-Regular.otf

*http://www.begolu.com/MathJax/fonts/HTML-CSS/TeX/otf/MathJax_Main-Regular.otf-

*http://www.begolu.com/MathJax/fonts/HTML-CSS/TeX/otf/MathJax_Math-Italic.otf

*http://www.begolu.com/MathJax/fonts/HTML-CSS/TeX/otf/MathJax_Size1-Regular.otf

*http://www.begolu.com/MathJax/fonts/HTML-CSS/TeX/otf/MathJax_Main-Bold.otf
Look at the net tab with Firebug


text:
Q: Area below probabilities Let $p$ be probabilities and $D$ is the real
How can I proof that the areas
$$\int p \; d F_{p}(p|D=1) = \int (1-p) \; d F_{1-p}(1-p|D=1)$$
are equal. Where $F_{p}$ is the empirical distribution function of $p$.
Illustration:
par(mfrow=c(1,2))
set.seed(123)
predRisk <- plogis(runif(1000,-1,10))
plot(ecdf(1-predRisk))
plot(ecdf(predRisk))

A: Just use the change of variable $p=1-q$ (don't forget the Jacobian and the use of the correct integration range). Maybe this should be a comment.


text:
Q: AngularJS $http.get not returning fast enough .factory('someFac', function (CONFIG, $injector, $http) {
   return $http.get('url').then(function (response) {
      var temp = response.data.answer;
      var answer = '';
      if(temp == bar){
          answer = barAnswer;
       }
      else if(temp == foo){
          answer = fooAnswer;
      }
      return $injector.get(answer);
   }
}

So my problem is, the $http.get isn't finished getting the response before the factory is finished executing...how should I fix this? I read somewhere I could implement the app.config to inject variables into a provider...could that be a solution?

A: Your factory/service should be what is maintaining the data and the controller should just use it (this way 2-way binding can occur across different controllers).
.factory('someFac', function ($http) {
    var self = this;
    self.init = function() {
        return $http.get('url').then(function(response) {
            self.data = response.data;
        });
    }
}

Now your factory can be injected anywhere and maintains the data, so all of your controllers will be updated real time. To make sure the data is loaded make sure to put the init into a resolve in the route.
resolve: {
    someFac: function (someFac) {
        return someFac.init();
    }
}

Now in a controller you can just use it as so:
.controller('someControleler', function ($scope, someFac) {
    $scope.data = someFac.data;
});

Hope this helps.

A: Usually a factory will just return the promise from calling a method with $http and then the code that called the factory will handle the ".then" when the promise is fulfilled.
.factory('someFac', function (CONFIG, $injector, $http) {
    var fact = {}

    fact.getResponse = function (){

      return $http.get('url');

    }

   return fact;
 }


text:
Q: how to create multiple custom 503 pages in IIS A Temporary down page (e.g. updating your servers SW) should ideally have a response code of 503, but you could get away with 307, but in no case should it be 200 (as google will index this and it will affect your SEO)
In IIS rewrite rules, you have 3 options for implementing a redirect to a down page, rewrite, redirect and customResponse:
 <action type="Rewrite" url="/site1.html" />
 <action type="Redirect" url="/site1.html" redirectType="Temporary" />
 <action type="CustomResponse" statusCode="503" subStatusCode="0" statusReason="Site Unavailable" statusDescription="Down for maintenance" />

The problem is if you want a 503 response, you cant redirect to the required page.
We have 3 websites for different brands using episerver CMS.
When we do maintenance, or just want to take a site down, we have a single azure web app (aka iis) which has 3 holding pages, one for each.
so our site down website has 3 pages:
/site1.html
/site2.html
/site3.html

We use Azure traffic manager to point to the live site or the site down page, and we currently have redirects which work, but incorrectly give 200 response:
<rewrite>
  <rules>
    <rule name="site1" stopProcessing="true">
      <match url=".*" />
      <conditions>
        <add input="{HTTP_HOST}" pattern="mysite" />
      </conditions>
      <action type="Rewrite" url="/site1.html" />
    </rule>
    <rule name="site2" stopProcessing="true">
      <match url=".*" />
      <conditions>
        <add input="{HTTP_HOST}" pattern="myothersite" />
      </conditions>
      <action type="Rewrite" url="/site2.html" />
    </rule>
      etc.
  </rules>
</rewrite>

In order to fix this issue (offer a different site down page per site, and respond with 503), what are the options?
I would guess its possible to setup something like 3 different named virtual hosts, each with nothing except a custom 503 error page + a catch all CustomResponse action?  Any examples of such a config?
To be clear, our app may well be running normally, but we may want to use our traffic manager to point the public at a "down" page which has a 503 respose during maintenance.  The website sorving the down page has nothing to do with the website serving the site/applicaion itself.

A: Sadly, as the Microsoft document describes – there is no way to customize the 503 HTTP error.
Even use rewrite to make it display custom 503 page, In fact the request get into IIS and rewrite successful, then response to client. The whole process is perfect and your web service doesn't stop.
The error is detected by the IIS server as it attempts to hand the incoming request to application. Everything application does is performed in its app pool. Modules like rewrite and custom error page are all executed in this way. 503 handled by the http.sys you cannot create a custom error page at all, as it is processed before it gets to iis. Therefore, both hope that the web server will stop reporting 503, but also hope that the server can process the request to display the page you defined. These two conflicts.
If your application is asp.net, there's another way to custom 503. You can place a text file named "app_offline.htm" in the root of the site, all requests to that website will redirect to that app_offline.htm file. Basically, if you need to take an entire ASP.NET site offline, you can place some nice message in that file. Then, any new requests to a URL, any URL, in that website will redirect to that file allowing you to do maintenance to the site, upgrades, or whatever. It is not really a redirect though. ASP.NET essentially shuts down the site, unloads it from the server, and stops processing any requests to that site. That is, until you delete the app_offline.htm file - then things will continue as normal and your ASP.NET site will load up and start serving requests again.


text:
Q: get source code of escript executable by mistake I deleted the source code of an Elixir escript that I wrote; as a last resort I'm trying to get the source (if possible at all) by decompiling the executable that I deployed on a server.
In case it matters, it was compiled on Ubuntu 16.04 running mix escript.build without additional arguments.
I would appreciate if somebody could give me any pointer how to do this or where to start!
Thanks

A: Here's how you can get the compiled Erlang source of your files back. I don't think it's possible to get the original Elixir source back since it is not present in the escript at all; only the compiled Erlang bytecode is. The decompiled Erlang code should be fairly readable if you know some Erlang (if not, check out this quick Erlang <-> Elixir crash course).
The escript executable starts with #! /usr/bin/env escript followed by some lines and then the embedded compiled files are present as a binary zip file. Open the escript file in an editor and delete everything until the line starting with PK (the start of the zip).
$ mix escript.build
$ head -c 59 m
#! /usr/bin/env escript
%%
%%! -escript main m_escript
PK
$ vim m # remove everything until `PK`
$ head -c2 m
PK

Now you can extract the contents of the file with unzip and get all the compiled .beam files:
$ unzip m -d extracted
Archive:  m
  inflating: extracted/m_escript.beam
  inflating: extracted/Elixir.Version.Parser.DSL.beam
  inflating: extracted/Elixir.Kernel.LexicalTracker.beam
  inflating: extracted/Elixir.IO.ANSI.beam
  inflating: extracted/Elixir.Inspect.NaiveDateTime.beam
  inflating: extracted/Elixir.Protocol.beam
  inflating: extracted/Elixir.Inspect.Any.beam
  ...

Finally you can decompile the modules you want using decompile-beam:
$ decompile-beam extracted/Elixir.M.beam
-compile(no_auto_import).

-file("lib/m.ex", 1).

-module('Elixir.M').

-export(['__info__'/1, main/0, main/1]).

-spec '__info__'(attributes | compile | exports |
         functions | macros | md5 | module |
         native_addresses) -> atom() |
                      [{atom(), any()} |
                       {atom(), byte(), integer()}].

'__info__'(functions) -> [{main, 0}, {main, 1}];
'__info__'(macros) -> [];
'__info__'(info) ->
    erlang:get_module_info('Elixir.M', info).

main() -> main([]).

main(args@1) -> 'Elixir.IO':inspect({args@1, args@1}).

This was the original Elixir source:
$ cat lib/m.ex
defmodule M do
  def main(args \\ []) do
    IO.inspect {args, args}
  end
end


text:
Q: How to throw Exception from WebAPI I have business logic which has throw exception, which I need to transfer to my api controller and show when my webapi fails to read. I have tray catch in all place. In Business Logic`
public static Models.User Login(Models.Login model)
        {
            try
            {
                using (var db = new Data.TPX5Entities())
                {
                    var query = (from a in db.User
                                 where a.UserID == model.UserName || a.UserCode == model.UserName || a.UserName == model.UserName
                                 select new Models.User
                                 {
                                     EMail = a.EMail,
                                     IsUsed = a.IsUsed,
                                     Memo = a.Memo,
                                     MobilePhone = a.MobilePhone,
                                     Password = a.Password,
                                     Telephone = a.Telephone,
                                     UserCode = a.UserCode,
                                     UserID = a.UserID,
                                     UserName = a.UserName
                                 }).ToList();
                    if (query == null || query.Count == 0)
                    {
                        throw new Exception(@LanguageHelper.GetSystemKeyValue(CultureHelper.GetCurrentCulture(), "/resource/Model/BLL_User_MSG_UserNotFound"));
                    }
                    else if (query.Count > 1)
                    {
                        throw new Exception(@LanguageHelper.GetSystemKeyValue(CultureHelper.GetCurrentCulture(), "/resource/Model/BLL_User_MSG_UserCodeRepeat"));
                    }
                    else
                    {
                        if (query[0].Password == model.Password)
                        {
                            return query[0];
                        }
                        else
                        {
                            throw new Exception(@LanguageHelper.GetSystemKeyValue(CultureHelper.GetCurrentCulture(), "/resource/Model/BLL_User_MSG_InCorrectPassword"));
                        }
                    }

            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

then web api controller I use try catch again
 [HttpPost]
        public Models.User Login(Models.Login model)
        {
            Models.User mUser = null;
            try
            {
                mUser = BusinessLogic.User.Login(model);
                if (mUser == null)
                    throw new Exception("Object is null.");
            }
            catch(Exception ex)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent(ex.Message, Encoding.UTF8), ReasonPhrase = "Login Exception" });
            }
            return mUser;
        }

and then I call in my client I use try catch to check again
private void btnLogin_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty( txtUser.Text))
            {
                TPX.Core.MessageBoxHelper.ShowError(Core.LanguageHelper.GetSystemKeyValue(GlobalParameters.Language, "/resource/Message/MS_FormLogin_Error_UserEmpty"));
                return;
            }
            try
            {
                //登录系统
                string md5Password = TPX.Core.Security.MD5.GetMD5(txtPassword.Text);
                TPX.Models.Login mLogin = new TPX.Models.Login();
                mLogin.UserName = txtUser.Text.Trim();
                mLogin.Password = md5Password;
                //Retrieve User Information
                string itemJson = Newtonsoft.Json.JsonConvert.SerializeObject(mLogin);
                string userURL = GlobalParameters.Host + "api/User/Login";

                using (System.Net.WebClient webClient = new System.Net.WebClient())
                {
                    webClient.Headers["Content-Type"] = "application/json";
                    webClient.Encoding = Encoding.UTF8;
                    string sJson = webClient.UploadString(userURL, "POST", itemJson);

                    TPX.Models.User myDeserializedObj = (TPX.Models.User)Newtonsoft.Json.JsonConvert.DeserializeObject(sJson, typeof(TPX.Models.User));

                    ClientContext.Instance.UserID = myDeserializedObj.UserID;
                    ClientContext.Instance.UserCode = myDeserializedObj.UserCode;
                    ClientContext.Instance.UserName = myDeserializedObj.UserName;
                    ClientContext.Instance.Password = myDeserializedObj.Password;
                }
                DialogResult = System.Windows.Forms.DialogResult.OK;
            }
            catch (WebException ex)
            {
                TPX.Core.MessageBoxHelper.ShowException((Core.LanguageHelper.GetSystemKeyValue(GlobalParameters.Language, "/resource/Message/MS_FormLogin_Ex_LoginError")),ex);
            }

        }

When I login with wrong credential need to throw error. Now I am getting error "The remote Server return error:(500)Internal Server Error',  Instead I want to throw exact error which my business logic throw.  Thanks
`

A: Do not throw 500 internal server error but try and communicating using specific http codes. In your case you want to communicate login failure so tell your client that specifically.
Either use:
 throw new HttpResponseException(HttpStatusCode.Unauthorized);

Or, a custom message like this:
 var msg = new  HttpResponseMessage(HttpStatusCode.Unauthorized) {
 ReasonPhrase = "whatever you want it!" };
 hrow new HttpResponseException(msg);

A: your business layer and your api are two different things.
you don't throw errors from your api unless something really bad happened with your own code.
The api always returns meaningful http codes and that's how the clients know what's going on.
Example:
[HttpPost]
    public IHttpActionResult Login(Models.Login model)
    {
        var mUser = BusinessLogic.User.Login(model);
            if (mUser == null)
                return NotFound();

        return Ok(mUser);
    }

you are now returning something meaningful which makes sense to a client and you are actually helping them understand what's going on.
There are multiple ways to return data, this is only one of them.
Avoid throwing errors, it is expensive in terms of resources used and the more users you have the worse it will get.
You can have your business layer return a message in form of a string and then return that as a result of the API call and the other response shows you how.


text:
Q: Visual Studio 2017 compiles in 32bit on 64 bit system? I have a 64bit operating system and an x64-based processor. However, when I compile a visual studio project, with "Any CPU" selected, it compiles as a 32bit executable?
So what is going on here and why isn't it compiling as 64bit?
The reason why I need to compile in 64bit is because I want to interact with a 64bit unmanaged C++ dll.

A: There is a "Prefer 32-bit platform" checkbox on project build configuration page, you should uncheck it.

A: The answer to your question is yes, since .NET 4.5 and Visual Studio 2012, AnyCPU will compile to x86 by default even on 64 bit OSs. The pointer to this is actually what @Alexander Powolozki said in his answer, e.g. the "Prefer 32 bit" flag.
Quoting from this answer

If the process runs on a 64-bit Windows system, it runs as a 32-bit process. IL is compiled to x86 machine code

The reason for this setting maybe be that this default helps you with performance, since

When an application can run fine either in 32-bit or 64-bit mode, the 32-bit mode tends to be a little faster.  Larger pointers means more memory and cache consumption, and the number of bytes of CPU cache available is the same for both 32-bit and 64-bit processes.  Of course the WOW layer does add some overhead, but the performance numbers I've seen indicate that in most real-world scenarios running in the WOW is faster than running as a native 64-bit process

Even Visual Studio isn't 64bit for this reason (and the cost of porting all libraries to 64 bit).
So, unless you uncheck the "prefer 32 bit flag", if you don't have it yet and as you probably know, you should create the x64 platform on your Visual Studio and use it for this particular project.
Get to this window, clicking on the "Any CPU" ComboBox:

And add the x64 bit platform:

Those images are for an older version of Visual Studio, but it works in a similar fashion across all versions.
Here's a written description.


text:
Q: Struct and template template <class T>
struct ListItem
{
   T value;
   ListItem<T> *next;
   ListItem<T> *prev;

   ListItem(T theVal)
   {
    this->value = theVal;
    this->next = NULL;
    this->prev = NULL;
   }
};

Can somebody please tell me what is happening after the prev pointer has  been declared.I mean what kind of structure is it?Sorry for asking what is probably a silly question.Thanks

A: ListItem(T theVal)
{
  this->value = theVal;
  this->next = NULL;
  this->prev = NULL;
}

is an inline constructor definition. It specifies how instances of your ListItem class template are initialized. the value data member is set to theVal and the list's next and prev pointers are set to NULL. You would call such a constructor as
ListItem<int> li(42);

A: ListItem(T theVal)
{
    this->value = theVal;
    this->next = NULL;
    this->prev = NULL;
}

This is a constructor for this struct, with this->value = theVal; the value that is passed in as an argument is assigned to the struct's member value.
If you don't know about constructors yet it would be wise to read up on them.


text:
Q: An example of a sequence of differentiable functions defined on $[0,1]$. Help me to find an example of a sequence of differentiable functions defined on $[0,1]$ that converge uniformly to a function $f$ on $[0,1]$ such that there exists $x \in (0,1)$ such that $f$ is not differentiable at $x$.

A: Any continuous function is a uniform limit of polynomials, so pick your favourite non-differentiable continuous function, and that would work!
In fact, if $f$ is such a function, say $f(x) := |x- 0.5|$, then take the sequence to be the sequence of Bernstein polynomials
$$
B_n(f)(x) := \sum_{k=1}^n {n\choose k} f\left(\frac{k}{n}\right) x^k (1-x)^{n-k}
$$
Then $B_n(f) \to f$ uniformly.
Edit: A simpler example: Take $f(x) = |x-0.5|$ and consider
$$
f_n(x) = \sqrt{\frac{1}{n^2} + f(x)^2}
$$
Then check that $f_n$ is differentiable and
$$
f(x) \leq f_n(x) \leq f(x) + 1/n \quad\forall x\in [0,1]
$$
and so $f_n \to f$ uniformly.

A: Consider the $C^1$-functions
$$f_n(x):=\sqrt{{1\over n^2}+x^2}-{1\over n}\qquad(n\geq1)\ .$$
One has $f_n(0)=0$ for all $n$, and
$$f_n(x)={x^2\over \sqrt{{1\over n^2}+x^2}+{1\over n}}\to |x|\qquad(n\to\infty)$$
for all $x\ne0$. It follows that $\lim f_n(x)=|x|$ for all $x\in{\mathbb R}$, which is not differentiable at $0$.


text:
Q: jqplot and rendering it with asp.net mvc model In my asp.net mvc 3.0 app, I am gonna draw a chart which its X-axis contains date values and y-axis contains views per day. For chart drawing I use jqplot date-axes , and I am passing it json result. here is the model :
 public class MyDateModel
    {
        public string Date { get; set; }
        public int Views { get; set; }
    }

and here is the action :
public ActionResult Index()
        {
            var res = new List<MyDateModel>();

            res.Add(new MyDateModel { Date=DateTime.Now.AddDays(-9).ToString("yyyy-MM-dd hh:mm"),Views=10});
            res.Add(new MyDateModel { Date = DateTime.Now.AddDays(-3).ToString("yyyy-MM-dd hh:mm"), Views = 3 });
            res.Add(new MyDateModel { Date = DateTime.Now.ToString("yyyy-MM-dd hh:mm"), Views = 3 });

            return View(res);
        }

and finally the view:
@model IEnumerable<Chartjquery_jqplot.Models.MyDateModel>
@{
    Layout = null;
}
<!DOCTYPE html>

    <title>Index</title>
    <link href="../../Content/jquery.jqplot.min.css" rel="stylesheet" type="text/css" />

        @Html.Raw(Json.Encode(Model))

But It does not draw any thing on page.
Would you help me please ?
Besides the json result is :
[{"Date":"2012-07-06 12:10","Views":10},{"Date":"2012-07-12 12:10","Views":3},{"Date":"2012-07-15 12:10","Views":3}]

A: I found a way to pass correct json data to chart. Here is the html hepler I wrote :
public static MvcHtmlString GetStrippedJson(this HtmlHelper helper,string json)
        {
            json=json.Replace("\"Date\":", string.Empty);

            json=json.Replace("\"Views\":", string.Empty);

            json=json.Replace('}', ']');

            json=json.Replace('{', '[');

            return MvcHtmlString.Create(json);
        }

but I dont know how to set tick inter val based on daily ticks

A: Not sure if this helps, but my code for passing data was the following.  @Model.data is a List.
$(document).ready(function () {
        var data = @Html.Raw(Json.Encode(@Model.data));
        //debugger;
        //alert(data);
        $.jqplot('chartdiv', data);


text:
Q: Where can I ask about feedback on Cloud Architecture setup? Currently I am thinking a lot about a new architecture for deploying our 2 applications in the cloud (moving from CloudFoundry PaaS to Docker).
I know how we're doing it currently and I have a imho well-defined setup/architecture in my mind.
It's not about choosing a technology, asking for opinions (at least not how I see it) but it's not a pure programming activity of course.
Is it allowed to share a 'logical architecture' with all technologies chosen and ask for feedback whether this is the right approach to go?
Or basically as asking for a right approach is off-topic for sure - is it OK to ask whether the architecture misses any items or contains any obvious issues? And if so, where on StackExchange would I do this?


text:
Q: Attaching JQuery delegate for more than one event to a handler I read that the new delegate method can attach more than one event to a handler however I have not see this in practice. Would anyone type a code for this please.
I tried:
$("body").delegate("input", "mouseup", "mouseover", function() {
            $(this).after("
Another paragraph!
");
        });

and it appended the paragraph only on mouseup. I am confused.

A: Use a space delimiter for events like this:
$("body").delegate("input", "mouseup mouseover", function() {
   $(this).after("
Another paragraph!
");
});

You probably meant to select <input> elements, I changed this above, correct me if you meant otherwise.
Alternatively, use .bind() like this:
$("body input").bind("mouseup mouseover", function() {
   $(this).after("
Another paragraph!
");
});

I find this easier to read, but whatever floats your boat.

A: The reference .delegate() | jQuery says about second parameter:
A string containing one or more space-separated JavaScript event types, such as "click" or "keydown," or custom event names.
Therefore, in your case:
$("body").delegate("input", "mouseup mouseover", function() {
            $(this).after("
Another paragraph!
");
        });


text:
Q: dojox is not defined I am trying to use COMET with dojo and it fails on the first line of the example with the message

dojox is not defined

I must miss something obvious
this is the page (the error is on the first line of the BODY):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
            "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
   <title></title>
   <script src="dojo/dojo.js"
           data-dojo-config="async:true, parseOnLoad:true">
   </script>
   <script>
      require( ["dojox/socket"] );
   </script>
</head>
<body>
<script type="text/javascript">
   var socket = dojox.socket( "/cometd" );
   function send( data ) {
      return socket.send( dojo.toJson( data ) );
   }
   socket.on( "connect", function () {
      // send a handshake
      send( [
         {
            "channel":"/meta/handshake",
            "version":"1.0",
            "minimumVersion":"1.0beta",
            "supportedConnectionTypes":["long-polling"] // or ["callback-polling"] for x-domain
         }
      ] )
      socket.on( "message", function ( data ) {
         // wait for the response so we can connect with the provided client id
         data = dojo.fromJson( data );
         if ( data.error ) {
            throw new Error( error );
         }
         // get the client id for all future messages
         clientId = data.clientId;
         // send a connect message
         send( [
            {
               "channel":"/meta/connect",
               "clientId":clientId,
               "connectionType":"long-polling"
            },
            {  // also send a subscription message
               "channel":"/meta/subscribe",
               "clientId":clientId,
               "subscription":"/foo/**"
            }
         ] );
         socket.on( "message", function ( data ) {
            alert( "message from server " + data )
         } );
      } );
   } );
</script>
</body>
</html>

A: You are mixing AMD and old-style module syntax. The new, AMD style, require will not create a global variable for your namespace, like the old dojo.require did.
Either rewrite the code to fully use the new AMD style or remove the async=true flag you added when loading dojo to re-enable support for the old module style.
Anyway, it should not be hard to rewrite this in AMD style...
require([
    'dojo/_base/json', //_base is for things that used to be in the root dojo namespace.
    'dojox/socket'
],function(
    json,
    dojox_socket
){
    var socket = dojox_socket( "/cometd" );
    function send( data ) {
        return socket.send( json.toJson( data ) );
    }
    // and so on...
});

(BTW, you can also remove the "parseOnLoad" flag if you aren't using any declarative widgets in your original html)


text:
Q: AWS Step Function where Map input comes from Execution Input I'm attempting to create an AWS step function with a Map state whose input (that is, the array to iterate over) comes from the Execution Input. A reduce example JSON step function looks like:
{
    "StartAt": "pass",
    "States": {
        "pass": {
            "Type": "Pass",
            "Next": "map-sleep"
        },
        "map-sleep": {
            "MaxConcurrency": 5,
            "InputPath": "$$.Execution.Input['data']",
            "Iterator": {
                "StartAt": "wait",
                "States": {
                    "wait": {
                        "SecondsPath": "$['length']",
                        "Type": "Wait",
                        "End": true
                    }
                }
            },
            "Type": "Map",
            "Next": "final-wait"
        },
        "final-wait": {
            "Seconds": 10,
            "Type": "Wait",
            "End": true
        }
    }
}

However, when I attempt to create this, I'm greeted by the error:

An error occurred (InvalidDefinition) when calling the CreateStateMachine operation: Invalid State Machine Definition: 'SCHEMA_VALIDATION_FAILED: Value must be a valid JSONPath. at /States/map-sleep/InputPath'

I infer from this that the InputPath is wrong, but I don't quite understand why, or what the correct way to express what I'm trying to do is. (This code was generated using the Python Step Functions SDK, and if it's helpful I can share this code, but I figured reducing it to the JSON would make it easier to consider).

A: Well, I strongly suspect this is not the optimal answer, but it looks like by combining a Pass node using Parameters with a Map node, you can get the desired outcome:
        "map-sleep-pass": {
            "Parameters": {
                "items.$": "$$.Execution.Input['data']"
            },
            "Type": "Pass",
            "Next": "map-sleep"
        },
        "map-sleep": {
            "MaxConcurrency": 5,
            "InputPath": "$.items",
            "Iterator": {
                "StartAt": "wait",
                "States": {
                    "wait": {
                        "SecondsPath": "$['length']",
                        "Type": "Wait",
                        "End": true
                    }
                }
            },
            "Type": "Map",
            "Next": "final-wait"
        },


text:
Q: Python "ModuleNotFoundError:", but module does appear to be installed per Command Prompt I am very new to Python/programming, having recently installed Python 3.10. I have already installed the Openpyxl module, i.e. when I check on CMD I get this:
C:\Users\hadam>pip install openpyxl
Requirement already satisfied: openpyxl in c:\users\hadam\appdata\local\programs\python\python310\lib\site-packages (3.0.9)
Requirement already satisfied: et-xmlfile in c:\users\hadam\appdata\roaming\python\python310\site-packages (from openpyxl) (1.1.0)

I am trying to run some code which I have just copied from here (i.e. I have just edited the file path names):
https://www.geeksforgeeks.org/python-how-to-copy-data-from-one-excel-sheet-to-another/
However, when I try to run this script (via the Mu editor), I get the following error message:
Traceback (most recent call last):
  File "c:\users\hadam\appdata\local\programs\python\python310\scripts\test1.py", line 2, in <module>
    import openpyxl as xl;
ModuleNotFoundError: No module named 'openpyxl'
>>>

Can anyone tell me why the Mu editor cannot find Openpyxl, or what I can do to execute this programme?
Thanks

A: Maybe the error is because Openpyxl does not support Python 3.10 build yet. Check the pypi page for supported versions.

A: Try to open python from the command line, e.g.
 C:\users\you> python

or
C:\users\you> python3

or
C:\users\you> path\to\python

then when python is open
>>> import openpyxl as xl

If the problem is not present anymore, your Mu editor might be using a different python interpreter/environment: check for its configurations and change it to the one you opened from the terminal.

A: The simple way to resolve this problem is to install a module in Mu Editor.
Mu Editor provides its own way to install third-party modules.
How to install third-party modules on Mu editor:
https://codewith.mu/en/tutorials/1.1/pypi
In addition, this kind of problem usually happens when there is more than one version of pythons.
# you can check what version of python will be executed on Prompt by typing:
C:\Users\hadam>python --version

On Mu Editor, there is [REPL] button on the top menu. If you click the button, a new terminal will be open at the bottom. Then, the current version of python will be printed on the terminal. (see https://codewith.mu/en/tutorials/1.1/python)
Or, you can type the same command on the Terminal to check a version of python on Mu Editor.
In [1]: python --version

Now, compare the two versions of python, they might be different from each other. Meaning that the module is installed but for another version of python.


text:
Q: How to use regex in vim to replace with an incrementing number variable I have a file which content like this:
id      phone   name
x'1234' 12345   jack
x'4567' 45678   Jojo
x'7890'  89456  Dio
x'4591'  34872  joseph

and i want to parse it into like this:
id  phone   name
1   12345   jack
2   45678   Jojo
3    89456  Dio
4    34872  joseph

I know basic regular expression could replace all id to any string
like this:
:%s/x'\(\w\+\)'/1/g

and it will become:
id  phone   name
1   12345   jack
1   45678   Jojo
1    89456  Dio
1    34872  joseph

How to replace id to an increment variable ?

A: Mind that you can use an expression as the replacement string in the substitute command (:s). When the replacement string starts with \= it is evaluated as an expression.
Here, one possible solution is
:let i=1 | g/^x'\d\+'/s//\=i/ | let i=i+1

It finds all occurrences (one per line) of the ^x'\d\+' pattern and replaces it with the value if i that is incremented each time the match is found. As has been noted in comments, the | is a part of the g replacing "code", as "|  is used to execute more than one command at a time".
Another solution is using the line() command (taking into account that your file has a header top line, so you should actually subtract 1 from the value returned with line()):
%s/^x'\d\+'/\=line('.')-1/

The ^x'\d\+' regex matches

*

*^ - start of a line

*x' - x' string

*\d\+ - 1+ digits

*' - a ' char.

There are other interesting "increment number in regex" examples at the Using an expression in substitute command page:

*

*Number all the lines in a file (insert line number followed by a tab):
:%s/^/\=line('.')."\t"/

*Number a range of lines (from line 10 to line 20):
:10,20s/^/\=line('.')."\t"/

*Number a range of lines sequentially starting from 1:
:let counter=0|10,20g//let counter=counter+1|s/^/\=counter."\t"

*Number all the paragraphs in range starting from 1 (assuming the paragraphs are separated by one or more blank lines):

:let counter=0|1,20g/^$\n^\s*[^\s]/let counter=counter+1|+1s/^/\=counter."\t"

  Note: The above command does not work for the first paragraph in the file if there is no blank line above it.

A: one-shot
You can declare a variable as the other answer does, or:
:%s/^x'\([^']*\)'/\=line('.')-1/

Replace the last 1 by the line number of your header (id, phone, name) line if it doesn't sit in line 1.
two steps
You can get followings just by replacing 1 into 0 in your codes
id  phone   name
0   12345   jack
0   45678   Jojo
0    89456  Dio
0    34872  joseph

Then you can move your cursor to the first id 0, then press:
ctrl-v G g ctrl-a
It will turn the 0s into a sequence from 1

*

*ctrl-v: column mode

*G : select the 1st col till the last line.

*g+ctrl-a: add

A: Alternatively you could use use awk, column, & Vim's filter command.
:%!gawk 'NR>1 {$1=++i} 1' | column -t

Explanation:

*

*:%!{cmd} will "filter" the range, % (whole file), through command {cmd}

*gawk '..' will run an awk one-liner

*NR>1 {..} will run a "block" for record number greater than 1 (skips header)

*$1=++i will set the first field to variable i (pre-incremented)

*1 is short of {print} which will print out the row

*{cmd1} | {cmd2} will pipe the output from command, {cmd1}, to the input of command {cmd2}

*column -t will pretty print tabular looking data

A: My PatternsOnText plugin has (among many others) a :Renumber command for this; it simplifies the typical solution with :substitute and a replacement expression:
:%Renumber/^x'\d\+'/

A: Nice answers, one trick I use to enumerate large protobuf files:
First search/replace your target with a unique string like %%%%, then use the following:
:let i=1 | g/%%%%/s//\=i/ | let i = i+1
e.g., to replace
[ProtoMember()]
[ProtoMember()]
[ProtoMember()]
with:
[ProtoMember(1)]
[ProtoMember(2)]
[ProtoMember(3)]
First make all into [ProtoMember(%%%%)]
:% s/Member()/Member(%%%%)/g
then use
:let i=1 | g/%%%%/s//\=i/ | let i = i+1


text:
Q: Releasing Python GUI app on GitHub: still use setup.py? First Software Engineering question, so I hope I'm on topic.
I'm an academic scientist working on on Python GUI applications for educational (and eventually research) use. The GUI uses PyQt and pyqtgraph to plot the results of calculations derived from user inputs. I've put a prototype for the first app on GitHub. In addition to the code itself, I've frozen the apps (currently with PyInstaller) as standalone 1-file executables (Windows and OS X), and attached them to a GitHub release—I expect the majority of users just want an app that runs when they click on it.
However, for some users the code itself may be useful for learning how to solve a problem, or for use in their own project. So, a clean way to download the "important" parts of the package (functional code and docs, minus tests and other cruft) is also desirable.
What's not clear to me is what role setup.py and requirements.txt (if any) should play in this type of distribution. Searching online, reading docs at PyPI etc, most tutorials assume that the author is producing a library that would be pip-installed and incorporated into their python library (like numpy, pandas, PyQt etc). My projects are just apps that a user would execute at will, and not want burrowed into their computer's python libraries. It doesn't seem like something you'd actually upload to PyPI and make installable from there. So, it's unclear to me how such a distribution should be properly structured and implemented.
Should I still be using setup.py and requirements.txt, somehow, to produce an easy way to download a clean subset of the code and necessary requirements, separate from their system's Python installation? If so, any pointers on how to go about this? This aspect of deployment is still very mysterious to me.
I think links to GitHub are frowned upon because of their time impermanence, but I could offer a link to the project if it's helpful and on topic.

A: A typical user would create a virtualenv to run a particular program, or related set of programs, like yours. So yes, requirements.txt is definitely useful to get the dependencies installed quickly; setup.py is likely not.

A: Taking 9000's suggestion further: this blog post was very helpful in distinguishing between the two ways to list requirements, and the best ways to go about it:
https://blog.miguelgrinberg.com/post/the-package-dependency-blues
Basically, if users aren't going to use a pip install, I should just use a requirements.txt that specifies which versions of the required packages will work.


text:
Q: Handling multiple exceptions in java My abandon() may throw AbandonException.
While handling the exception I have to recall the same method if there some element left in the Vector.
How should I proceed? And if I am not thinking straight, what would be the best solution?
   if (i + 1 < lc.size()) {
    try {
        lc.get(i + 1).abondon();
    }
    catch (AbandonException e1) {
lc.get(i+2).abandon();}}

A: following is some pseudo-code:
List errorIndexList = new ArrayList();

for(...) {
    if (i + 1 < lc.size()) {
        try {
            lc.get(i + 1).abondon();
        } catch (AbandonException e1) {
            errorIndexList.add(i+1);
            // do some error handle work ..
            // print error log/info if need,
            continue; // this is optional, in case it's the last statement,
        }
    }
}

// use errorIndexList to handle your errors, if need,

A: You could use finally here.
try {
      lc.get(i + 1).abondon();
}
catch (AbandonException e1) {

} finally {
   your code
}