Evaluate the triple integral $\iiint (x^2+y^2+z^2)\,dx\,dy\,dz$

Question: I have to evaluate this integral. It is enough for me to know the correct limits to integration.
$$ \iiint_W  (x^2 + y^2 + z^2) \,\mathrm dx\,\mathrm dy\,\mathrm dz$$
Conditions:
$$x\ge 0,\quad y \ge 0 ,\quad z \ge 0,\quad 0 \le x + y + z \le a,\quad (a>0)$$
My ideas:
As I have
$0 \le x + y + z \le a$,
I can say that $$0 \le x + y + z$$
$$x \le - z - y $$
so my limits to integration could be:
$$\int _{ z }^{ a }{  } \int _{ -z-y }^{ y }{  } \int _{ 0 }^{ -z-y }{ (x^2 + y^ 2+ z^ 2) \,\mathrm dx\,\mathrm dy\,\mathrm dz } $$
Can somebody help/correct me?
Comment: Somethings wrong. Note that your *outer* integral is over $\mathrm dz$ and yet the lower bound depends on $z$?! Similarly for the medium integral ...
Answer: Your integral should be of the form
$$\int_{z_0}^{z_1}\int_{y_0(z)}^{y_1(z)}\int_{x_0(y,z)}^{x_1(y,z)}(x^2+y^2+z^2)\,\mathrm dx\,\mathrm dy\,\mathrm dz $$
By the conditions, we find $0\le z\le a$, and for given $z$, $0\le y\le a-z$, and for given $z$ and $y$ $0\le x\le a-y-z$. So in the end it should be
$$\int_{0}^{a}\int_{0}^{a-z}\int_{0}^{a-z-y}(x^2+y^2+z^2)\,\mathrm dx\,\mathrm dy\,\mathrm dz $$
Answer: first for $x$:
$$0<x+y+z<a$$ implies $$0<x<a-y-z$$
Now x is dead :-) hence $$0<y+z<a$$ implies $$0<y<a-z$$
Now y is also dead hence $$0<z<a$$ therefore $$\int_0^a \int_0^{a-z}\int_0^{a-y-z}(x^2+y^2+z^2)dxdydz$$
Comment: Thank you so much too :-) So well my basic idea wasn't 100% wrong... I will post a new question in a few minutes, it's a "limits" question again :-)
Answer:
Your manipulation of the inequality is wrong: $0\leq x+y+z$ implies $x\geq-y-z$, not $\leq$.
As @Hagen pointed out, you should NOT have bounds that depend on the variable of integration. Perhaps you meant to order the $d$s differently?
Again as @Hagen pointed out in his answer, the bounds are much easier.

Here is how to find the bounds:

$z\geq0$, but since all other variables are surely $z\leq a$, so $0\leq z\leq a$ for the outer integral.
$y\geq0$, and $x+y+z\leq a$ surely implies $x+y\leq a-z$, but $x\geq0$ so you must have $y\leq a-z$.
$x\geq0$, and $x+y+z\leq a$ equates to $x\leq a-y-z$.

So your integral becomes:
\begin{align*}
\int\limits_0^a\int\limits_0^{a-z}\int\limits_0^{a-z-y}(x^2+y^2+z^2)dxdydz={}&\int\limits_0^a\int\limits_0^{a-z}\left[(y^2+z^2)(a-z-y-0)+\frac{(a-z-y)^3}{3}\right]dydz={} \\
{}={}&\int\limits_0^a\int\limits_0^{a-z}\left[ay^2+az^2-y^2z-z^3-y^3-yz^2+\frac{(a-z-y)^3}{3}\right]dydz={} \\
{}={}&\int\limits_0^a\left[a\frac{(a-z)^3}{3}+a(a-z)z^2-\frac{(a-z)^3}{3}z-(a-z)z^3\right.-{} \\
&{}+\left.\frac{(a-z)^4}{4}-\frac{(a-z)^2}{2}z^2-\frac{(a-z-(a-z))^4}{12}+\frac{(a-z)^4}{12}\right]dydz={} \\
{}={}&-\frac{a}{12}(a-z)^4\Bigg|_0^a+\frac{a^2}{3}z^3\Bigg|_0^a-\frac{a}{4}z^4\Bigg|_0^a+\frac{z}{12}(a-z)^4\Bigg|_0^a-{} \\
&{}+\int\limits_0^a\frac{(a-z)^4}{12}dz-\frac a4z^4\Bigg|_0^a+\frac{z^5}{5}\Bigg|_0^a+\frac{(a-z)^5}{20}\Bigg|_0^a+{} \\
&{}+\frac{(a-z)^3}{6}z^2\Bigg|_0^a-\int\limits_0^a\frac{(a-z)^3}{3}zdz-\frac{(a-z)^5}{60}\Bigg|_0^a={} \\
{}={}&\frac{a^5}{12}+\frac{a^5}{3}-\frac{a^5}{4}+\overline{\frac{(a-z)^5}{60}\Bigg|_0^a}-\frac{a^5}{4}+\frac{a^5}{5}-\frac{a^5}{20}+{} \\
&{}+\frac{(a-z)^4}{12}z\Bigg|_0^a-\int\limits_0^a\frac{(a-z)^4}{12}dz-\overline{\frac{(a-z)^5}{60}\Bigg|_0^a}={} \\
{}={}&a^5\left(\frac{1}{12}+\frac13-\frac14-\frac14+\frac15-\frac{1}{20}\right)+\frac{(a-z)^5}{60}\Bigg|_0^a={} \\
{}={}&a^5\left(\frac{1}{6}-\frac{1}{10}+\frac{1}{60}\right)=\frac{a^5}{12}.
\end{align*}
I hope I didn't get lost in the calculations.
Answer: By symmetry, the required integral is
$$3\int_{0}^a z^{2} \underbrace{\int\int dx\,dy}_{\mbox{area of }T} \, dz
={3\over 2}\int_{0}^a z^{2}(a-z)^2\,\,dz={a^5\over 20}.$$
Here, $T$ is the triangle $\{(x,y): x>0,\, y>0,\, x+y<a-z\}.$


Kendo UI Scheduler connection to database

Question: I'm currently developing a web app using the open source Kendo UI Scheduler with ASP.NET MVC Visual Studio 2012. But i'm experiencing some trouble while trying to connect my scheduler with a local database to store the bookings made by users of my application.
I've been looking for documentation to help me with this but I haven't been able to set this up entirely...
I followed instructions about this on: http://docs.telerik.com/kendo-ui/getting-started/using-kendo-with/aspnet-mvc/helpers/scheduler/ajax-editing
I've added the Entity Framework Data Model and necessary code in Models like TaskViewModel but the problem occurs in my Controllers.
    public ActionResult Tasks_Read([DataSourceRequest]DataSourceRequest request)
    {
        using (var sampleDB = new SchedulerEntities())
        {

            IQueryable<TaskViewModel> tasks = sampleDB.Tasks.ToList().Select(task => new TaskViewModel()
            {
                TaskID = task.TaskID,
                Title = task.Title,
                //Specify the DateTimeKind to be UTC
                Start = Convert.ToDateTime(task.Start),
                End = Convert.ToDateTime(task.End),
                Description = task.Deschription,
            }).AsQueryable();

            return Json(tasks.ToDataSourceResult(request));
        }

    }

I get an error on the DataSourceRequest: the type or namespace DataSourceRequest could not be found. But I can't find to narrow down which module I'm missing or what else I'm doing wrong...
Besides that I also get the following error System.LinqIQueryable doest not contain a definition for ToDataSourceResult. on the code:
return Json(tasks.ToDataSourceResult(request));
Anyone who can help me here or has an other/better solution to make a connection to a local database using the open source Kendo UI Scheduler?
Any help would be really appreciated!
Answer: You need to specify the allow get behavior.
return Json(tasks.ToDataSourceResult(request), JsonRequestBehavior.AllowGet));

Comment: Seems to be a problem cause I'm using the open source version.
Comment: The .ToDataSourceResult is from an extension class found in of Kendo.Mvc.dll. I assume this means the mvc support in kendo is not included in the free version.
Comment: Yes, it's due to the open source version but this still can be accomplished using Javascript thats why I opened this new thread: http://stackoverflow.com/questions/23541079/javascript-local-database-binding-of-the-kendo-ui-scheduler


interrupted time series with binary outcome in R (specific impact models)

Question: I want to fit an interrupted time series model in R. My outcome variable is binary, so I would want to fit a glm model and I know the exact time point of my intervention.
How would I specify a certain impact model in R?
Let's say I want to fit a model where the level but not the slope changes and another model for which the slope but not the level changes before and after intervention, how do I actually specify this difference in my glm?
I'm basing this on the Bernal et al. (2016) paper  (see page 4)...
I'm particularly interested in the models shown in Figure 2a, 2b, 2c and 2d and how to model these in R when my outcome is binary.
Comment: Welcome to [stats.se]!  Please take a moment to view our [tour].
Answer: I think if you use glm you do not take advantage of any pattern which might be present in the series, in the form of autocorrelation, seasonality, etc. There is no provision for that in glm. I think state-space models are a suitable alternative; see for instance
MENÉNDEZ, P., TUSELL, F. y WEATHERBURN, D. (2015) The effects of liquor licensing restrictions on alcohol related violence in NSW, 2008-2013, Addiction, vol. 110, 1574-1582, DOI:10.1111/add.12951.
In that particular example the outcome is not binary, but assumed normal. But you can fit the same kind of models with discrete responses (see the R package KFAS for instance).
If you tell us more about your problem, we might be able to give further help.


Mod_rewrite display subdomain.domain.com and call domain.com/subdomain/ for SSL

Question: I have a website secured by a standard SSL certificate, securing a few different shops under different subdirectories. Ex. domain.com/shop1/  The shops are also accessible via a subdomain  e.g. shop1.domain.com.
What I'm trying to accomplish:  display shop1.domain.com to the user, while keeping all of the actual server calls as domain.com/shop1, so that the secure pages will continue to work properly. (Not sure if I'm using the proper language, exactly, I hope my point is clear.)
To be clear: my SSL is working fine, and I don't need help with that, and I don't need or want to purchase a UCC cert.
It can't be that difficult for anyone with experience with Apache. (I've spent 3 hours trying to learn about mod_rewrite. It's just not clicking.)  I'm on a GoDaddy secure shared server, so please keep in mind that I'm not able to reset the server or anything.
Answer: You do in fact need to purchase a more flexible SSL certificate for this to work.
The domain name that a user's browser validates the certificate against is the one that is "displayed to the user" - if their address bar says "shop.domain.com", then the certificate must cover that domain.
Comment: Ah, well bugger.  Can I do a simple redirect from, for example, shop1.domain.com to domain.com/shop1 that will work whether or not SSL is invoked by a particular page?
Comment: I'd 'Vote Up' your answer, but apparently I don't have the reputation to do so.
Comment: You can redirect from the HTTP version of the subdomain, but users would get a browser warning from the subdomain before the redirect kicks in if they visit `https://subdomain.domain.com`.  You can't upvote yet, but you should be able to mark the answer as "accepted" which awards rep by clicking the gray check mark under the voting buttons.


Java Simple Program

Question: I am Getting Error Can You tell ME where Is the Error In This File ?
public class IfSample {

    public static void main(String[] args) {
        int x,y;
        x=10;
        y=20;
        if(x<y) System.out.println("x is less than y");
        x=x*2;
        if(x==y) System.out.println("x now equal to y");
        x=x*2;
        if(x>y) System.out.println("x is greater than y");
        // this won't display anything.
        if(x==y) System.out.println("you won't see this");
    }
 }

Comment: What error are you getting?
Comment: Copy -- paste problem ?? Change the quotes... will work...
Comment: need a lend of some brackets lol?
Answer: You are using these quotes "". That is why you're getting the error. Use the standard double quotes for Strings.
if (x < y)
    System.out.println("x is less than y"); // standard double quotes
x = x * 2;
if (x == y)
    System.out.println("x now equal to y");
x = x * 2;
if (x > y)
    System.out.println("x is greater than y");
// this won't display anything.
if (x == y)
    System.out.println("you won't see this");

Java Simple Program


How do I exclude an imported list of directories from a Get-ChildItem list?

Question: Our online backup software is skipping files and directories when uploading. It seems random, but I'd like to see if I can compare a list of files in the selection to the list of files in the cloud to look for a pattern.
The items in the cloud are available in a .csv, but I'm having difficulty generating a list of files in the backup selection while excluding other directories. Here's what I have so far.
$colSelection = get-content "c:\scripts\selection.txt"
$colExclusion = get-content "c:\scripts\exclusion.txt"
foreach ($folder in $colSelection) {
            $colItems = (Get-ChildItem $folder -recurse -force | where-object {(-not $_.PSIsContainer) -and ($_.FullName -notlike $colExclusion)})
            foreach ($item in $colItems) {
                Add-Content -Path c:\scripts\testlist.txt -Value $item.FullName
            }
        }

The .txt files are lists of directories. The best way to do this seems to be to use regex, but I don't know that I can dynamically create the expression from a .txt file.
Comment: You might be able to get away with something like `$colExclusion = "($((get-content "c:\scripts\exclusion.txt") -join '|' ))"` and then `($_.FullName -notmatch $colExclusion)`, to make a regex pattern of `(c:\folder1|c:\folder2|c:\folder3|...)`.  Otherwise it'll probably need an inner loop over the contents of `$colExclusion`. (This is a comment not an answer because I don't want to put something together to test it)
Comment: You are correct. I posted an answer to my own question with the code that worked using your idea. This is my first question, so hopefully that is the correct way to do things.
Answer: Since Get-Content by default returns a collection (or an array, if you will) of strings, you're comparing the $_.FullName string to a collection of strings.
You can look at the parent directory against the entire array with -notcontains:
$childItems = Get-ChildItem $folder -Recurse -Force
$childItems | Where-Object {$colExclusion -notcontains $_.Directory.FullName -and (-not $_.PSIsContainer)}

or you can compare each item in the $colItems to the beginning of each path with a ForEach-Object call inside the Where-Object filter:
$childItems | Where-Object {$(
    $path = $_.FullName
    $colItems | ForEach-Object {
        if($_ -notlike "$path*"){ return $true }
    }
)}

Comment: But the `$_.FullName` will include a filename, and the `$colExclusions` is a list of folders, it will never contain the FullName. The check needs to be a partial match check of the beginning of the file path.
Comment: @TessellatingHeckler Spot on, thanks for pointing it out. Added suggestion for partial matching against start of string
Comment: `$colExclusion -notcontains $_.Directory.FullName` is still risky; if the file is `c:\data\music\artists\group\1.mp3` and the exclusion is `c:\data\music` then the file will wrongly be included. I think the only way is to do a substring match (or maybe to do something with the get-childitem -exclude property to avoid going into those folders at all?)
Answer: TesselatingHeckler was right.
I can create the expression on the fly, and the following is working. I did need to escape all the slashes in the list of directories though.
$colSelection = get-content "c:\scripts\selection.txt"
#$colExclusion = get-content "c:\scripts\exclusion.txt"
$colExclusion = "($((get-content "c:\scripts\exclusion.txt") -join '|' ))"
foreach ($folder in $colSelection) {
    $colItems = (Get-ChildItem $folder -recurse -force | where-object {$_.FullName -notmatch $colExclusion})
    foreach ($item in $colItems) {
        Add-Content -Path c:\scripts\testlist.txt -Value $item.FullName
    }
}


Proving limit of a 2D sequence using $\epsilon-N$ definition

Question: I'm practicing proving a limit of a sequence $a_n:\mathbb{N}\to\mathbb{R}^2$ and I would like to know if I'm doing things correctly. The original limit is
$$\lim_{n\to\infty}\left\langle\frac{1}{2^n},\frac{n^2+4n+5}{n^2+1}\right\rangle=\langle0,1\rangle$$
I have already dealt with the first component, which suggests that $N=\lceil 1-\log_2\epsilon\rceil$ is sufficient, since we have
$$\left|\frac{1}{2^n}-0\right|=2^{-n}<\frac{\epsilon}{2}~~\implies~~1-n<\log_2\epsilon~~\implies~~N=\left\lceil1-\log_2\epsilon\right\rceil$$
I'm having just a bit of trouble with the second component. Here's my preliminary analysis for it.
$$\begin{align*}
\left|\frac{n^2+4n+5}{n^2+1}-1\right|&=4\left|\frac{n+1}{n^2+1}\right|\\
&\le4\left|\frac{n+1}{n^2}\right|\\
&\le4\left(\frac{1}{n^2}+\frac{1}{n}\right)\\
&<\frac{\epsilon}{2}
\end{align*}$$
Since I can't solve the inequality for $n$ directly, would I have to split this up to establish something like $\dfrac{1}{n^2}+\dfrac{1}{n}<\dfrac{\epsilon}{16}+\dfrac{\epsilon}{16}=\dfrac{\epsilon}{8}$?
If this is right, then it would seem to me that choosing $N=\max\left\{\left\lceil1-\log_2\epsilon\right\rceil,\left\lceil\dfrac{16}{\epsilon}\right\rceil,\left\lceil\dfrac{4}{\sqrt\epsilon}\right\rceil\right\}$ will suffice for the proof. Can anyone confirm? Help is appreciated!
Edit: I forgot to include one quick question I had. Before using $\dfrac{n+1}{n^2+1}\le\dfrac{n+1}{n^2}$ I elected to try $\dfrac{1}{n}\le\dfrac{n+1}{n^2+1}$. Does this also work for a proof like this?
Answer: This doesn't directly answer your question but I think you are making things more complicated than it needs to be for the proof.  $1/n^2 < 1/n$ for any $n > 1$ so the second to last inequality is $< 4(1/n + 1/n)$.  i.e. $8/n$.  Then given an $\epsilon$ chose $n > 8 / \epsilon$.
Comment: It definitely helps making the proof more streamlined. Thanks for the suggestion. It actually does answer the first question I posed, but I'm still wondering if my second comparison is also valid.
Comment: Fair enough.  The latter two values in the maxima seem sufficient to make the statement.  Why do you require $1 - \log_2\epsilon$ ?
Comment: I see, for the other component.  Then yes, I agree that is sufficient.
Comment: Sorry, I was referring to the one in the edit. The difference here is that I would compare to a sequence that is smaller $(\frac{1}{n})$ as opposed to a larger one. $(\frac{n+1}{n^2})$ I've consulted a professor who agreed with the latter, but I didn't get a chance to bring up this second sequence.


Why doesn't loading a form in the view header work?

Question: I've been checking for the past 2 days on how to do a drupal_get_form() for Drupal 8 and everyone seems to give me the following answers which don't seem to work. Let's just say I want to take the following Basic Page creation form and embed it into a Views header:

The ID of the form is: node-page-form or node_page_form if we were using drupal_get_form() from Drupal 7. But this time its the following:
$form = \Drupal::formBuilder()->getForm(Drupal\user\Form\NodePageForm::class);
I'm assuming "NodePageForm" is the parameter I'm suppose to use. If not how can one find this out from viewing the source of that page?
I then put the following PHP code in the Views header of my page like this:

I click save and update... my header is blank. What did I do wrong?
I'm trying to be as descriptive as I can explaining this problem. End result I just want to be able to take ANY form from any D8 page and be able to render it anywhere that takes PHP. That's my end goal. So no 3rd party modules as a solution.
Comment: Should not the PHP code exclude the `` tag?
Comment: I started writing an answer to this but it's getting out of hand, there's quite a bit of info to get across. Here's the first bit at least, hope it helps clear that part up: http://pastebin.com/hu2SrZiX
Comment: The first part of the second part included this:  _there isn't a way to identify the class that implements a form from its markup alone; you need to dig into the code._ I'm pretty sure that holds true
Comment: So for Drupal 8 every time I see a form I'd like to render somewhere else I would need to do a grep in the codebase to find that form then look for the form_id? What would I need to grep for if thats the case?
Comment: @LittleCoding I did that if you looked at my code above. It doesn't work. I don't understand why its so difficult. All I want to do is find a form somewhere on the site and output it elsewhere in a PHP enabled text field. That is all. Apparently its more difficult that just D7's drupal_get_form() function method.
Comment: That's what I've been trying to explain (maybe not very well), it's not that simple any more. You can't look at the markup for the form and know what to grep for, definitely not for entity forms. But that's because those are built up with the `EntityFormBuilder` service, and an instance of an entity which you set up manually. See [this](https://api.drupal.org/api/drupal/core%21tests%21Drupal%21Tests%21Core%21Entity%21EntityFormBuilderTest.php/class/EntityFormBuilderTest/8.2.x) for an example. I'm not being obtuse; the simple, catch-all, generic solution you want doesn't exist as far as I know
Comment: Ok so let me get this straight. Just looking at **ANY** form on Drupal 8 and wanting to render it else where by trying to find a **form_id** of some sort isn't going to work anymore. So can we safely say in order for us as a dev to find these forms to render elsewhere we'd have to at least know  which module to look in. Say in my case its has to do with rendering the node creation form. So I goto the **node module** folder and grep for **EntityFormBuilder** and find the class name? And I'm assuming if there are multiple class names, we'd have to trial and error it. Is that correct?
Comment: Many times I have to render forms from other parts of the site and it would be great if we can document a STEP by STEP tutorial for others to follow when needing this setup something like this. In D7 it was just finding the form_id which was simple enough and just doing a drupal_get_form(). It's okay if its more steps in D8, but we should at least figure out a **universal** step by step guide on rendering forms from other parts of the site.
Comment: I'll give it one more go, I'm running out of different ways to say it: **there isn't a universal, step by step guide**. Different forms come from different parts of the system, and so require different knowledge to locate. You don't have to agree that it's a good thing, you dont have t like it, but you can't keep on ignoring what I've said to you in three or four different ways now. What you want doesn't exist, please accept it and move on!
Answer: sEntity forms should be built using the entity.form_builder service. You'll need an entity to work with, for a node your code might change to something like this:
$node = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->create(['type' => 'page']);

$form = \Drupal::service('entity.form_builder')->getForm($node);

print \Drupal::service('renderer')->render($form);

As noted in the comments, this won't actually work in the context you're using it, regardless of how you render the form. The views_php area handler renders the output of the custom PHP using #markup, which will strip out the <input> and other form tags. You'll need a custom or contributed module, or to alter the views_php module directly, to make this work.
Here's a simple area handler that adds support for common form tags:
<?php

namespace Drupal\foo\Plugin\views\area;

use Drupal\Component\Utility\Xss;
use Drupal\views_php\Plugin\views\area\ViewsPhp;

/**
 * Views area PHP text handler with support for common form tags.
 *
 * @ingroup views_area_handlers
 *
 * @ViewsArea("foo")
 */
class ViewsPhpForm extends ViewsPhp {

  public function render($empty = FALSE) {
    if (!$empty || !empty($this->options['empty'])) {
      $content = $this->renderViewsPhp($this->options['content']);
      $form_tags = ['form', 'input', 'select', 'fieldset', 'option', 'button', 'textarea', 'optgroup'];
      $allowed_tags = array_merge(Xss::getAdminTagList(), $form_tags);

      return [
        '#type' => 'inline_template',
        '#template' => Xss::filter($content, $allowed_tags),
      ];
    }

    return [];
  }

}

This code should be in src/Plugin/views/area/ViewsPhpForm.php and will need updating for the name of your module.
You'll also need to make views aware of it with a hook either in your .module file, or foo.views.inc:
/**
 * Implements hook_views_data().
 */
function foo_views_data() {
  $data['views']['php_with_form'] = [
    'title' => t('PHP with form'),
    'help' => t('Use PHP code with support for form tags.'),
    'area' => [
      'id' => 'foo',
    ],
  ];

  return $data;
}

After a cache rebuild you'll be able to add a new area handler, PHP with form, and your form should be rendered.
Comment: It works it out from the entity, it's been set up with `->create(['type' => 'page'])`, that could just as easily by `->create(['type' => 'article'])`, and so on. I tested this by returning it from a controller (don't like turning on the PHP filter on principal!), where it works fine. But it makes sense that Views might push the output of the global header through a filter format. In fact that might be where this could be attacked, but it might mean making the default format more permissive. Not sure
Comment: It worked fine for me placing the code on a regular block. Looks like you're right, there is some sort of views filtering going on. I guess the OPer will have to use a regular block and place it before his view. **PS:** I also condone using/enableing PHP Filter on anything.
Comment: Turns out it's the views_php module itself that's responsible, not Views @NoSssweat, I added a bit to the answer
Comment: I tested your answer, but didn't work properly, this is what I got https://drt5a.ply.st/test
Comment: Works well for me @NoSssweat: http://imgur.com/SM8uKIq, how are you rendering it?
Comment: like OPer wants it, at the header of a View Page.
Comment: The fact that the button text is "asdf" makes me think you have something altering that form...
Comment: I just gave anonymous all permissions, see https://drt5a.ply.st/test again, and edit view if you like.
Comment: But the submit button for a node form isn't "sadf"...so you have some code altering that form somehow, which might be causing the problem?
Comment: asdf is the title of a random node I created (comes from field title of the view). https://drt5a.ply.st/admin/structure/views/view/test/edit/page_1?destination=test
Comment: Oh wait, you're probably right, the global text header may be run through a filter, removing the `` tags. Not sure if Views has an option to disable that filtering
Comment: it might be because views doesn't know which content type form to load, Article? Basic Page? how would **Views Page** know? I gonna try with block.
Comment: Thanks Clive. I can confirm the first block of code does indeed work when I copy and paste it to my custom module code. It does indeed render the node creation form, but I still have a question after that: http://drupal.stackexchange.com/questions/210496/what-are-the-variables-does-one-search-for-when-trying-to-render-a-custom-form-o
Answer: See How to render form in drupal 8. Also has a link to the Change Record over on Drupal.org
Comment: Thats not the point. All I'm looking for is what is the exact code you need to just output / print a form that resides somewhere else on the site. Thats it. I've already checked that link. It doesnt work.
Comment: Then how about go at this from the opposite direction. Try `hook_form_FORM_ID_alter` to render your view as part of the form.


Independent paired t-test -> Mann Whitney U

Question: Just a quick introduction, I'm rubbish at stats.
I asked a question before which was very well answered but I have since modified the experiment in a way that confuses me as to which test I should use.
So in the previous question we finished concluding that an independent t-test would be suffice as I am comparing the effect of irradiation on each leaf so, one half would be the control or the "before", and the irradiated half would be the "after" treatment. Well, I got my results, but I didn't map out which irradiated half went with what control as it was very difficult to keep track so I ended up with a jumbled set of controls to a jumbled set of irradiated.
So I made the following changes to my experiment:
1) Instead of having 5 circles per half of leaf, I instead opted for just 1. This meant it was quicker to get results as things like overlapping circles reducing light intake for the leaf discs on bottom didn't happen. So I would initially cut all my leaves in half. take one sample from one half, and whilst waiting for photosynthesis to take place I would irradiate the other halve(s), which brings me on to my second change..
2) I did 3 syringes at the same time instead of just 1 quadrupling my speed. (That's what I meant when I said I did four at the same time), so 4 control, whilst waiting, irradiate other halves of leaves for a minute and switch once photosynthesis finished, then switch again to another batch of 4 leaves and repeat. I ended up with 16 results either side
Comment: If you have jumbled control and treatment labels, nothing can rescue it. On your last sentence - standard deviation of *what*?
Comment: Oh damn :L Ok, well I'll explain what I did in further detail. So I have to work out "If applicable" things like mean and Standard Deviation. So can I do that with my results? All my values are above 0 (since I'm using a stopwatch to measure). Again, so that means I can't do a statistical test? Surely if I've got n number of results for non-irradiated with an equal n number of control, there can be another test I can do??
Comment: I didn't really follow your explanation in further detail, sorry, perhaps you can explain in more detail in an edit to your question. Where you say - "*surely if I've got n number of results for non-irradiated with an equal n number of control*" - you can compare them only if you know which is which. It's possible I misunderstood something, I suppose. Do you have some of each group where you do know which treatment group they're from?
Comment: Ohh yes yes, I 100% know which is control and which is irradiated. It's just, for my test I would have had to compare a before and after for EACH INDIVIDUAl leaf (paired t-test). But I didn't keep track of which control/irradited was for which leaf (as I did 4 at a time). So what's a broad statistical test I could use to compare the difference between the control and irradiated (Again I can explain if it's not clear. It is difficult to describe, sorry).
Comment: Oh, you mean you just lost the pairing? Then you do a two-sample test instead of a paired. You'll lose some power but all is not lost. I can probably give an answer now. Still not clear about computing standard deviation *from* a Mann-Whitney. Why not compute them from the samples?
Answer: It sounds like you've lost the information that would let you identify the inherent pairing in your data. This is unfortunate and will likely cost you power, but you can still do a test.
With the loss of pairing, you're in a two-sample situation.
You seem to suggest you're thinking of a Mann-Whitney test. That may well be suitable depending on the specific hypothesis you're interested in testing and the specific additional assumptions you may be willing to make.
If you're willing to assume identical shapes apart from possible location shift, you can use a Mann-Whitney to test means, for example. If you want a more general location test, you don't necessarily need to assume identical shape. It sounds like your data are potentially fairly discrete - are you likely to have lots of ties?
Another possibility is - especially with such small samples - to consider a permutation test of whatever is quantity is of interest.
Comment: Yes, I agree, _if_ by "equal shape" to mean `identical distribution apart from ... shift` Then of course, the test is just the test of that shift (and hence of any quantile, including that one corresponding to mean).
Comment: The link I gave you was a little wrong. So I initially was going to do the technical replicates thing, but I realised that would take a long long time. So instead, I made the following changes:
Comment: Perhaps you should edit the information into your question.
Comment: I think I've lost you >.<
Comment: Thanks for the extra info. What would be the null and alternative hypothesis you'd be most interested in testing - in plain words rather than formal notation. (Are you able to put up the data, by the way?) There are several further questions in my partial answer.
Comment: The alternative is very general - do you want to reject the null if one sample is more variable than the other? Or are you really trying to find out if it maybe increases or decreases? Which values are those 16?
Comment: Assuming you only care about a location difference, your data would be fine to use either a t-test or a Mann-Whitney (with adjustment for ties), or indeed a permutation test; the assumptions don't look like a big issue for any of them. None of your results will be significant, however (I didn't test it; you can tell by looking).
Comment: That's a lot of stuff being asked for... Briefly - what "*..."smallest U-value of 116.5" and "a critical value of U of 75*" means *exactly* depends on the specific definition of U being used. In this case it seems that it's taking the sum of the ranks in first sample minus the minimum possible sum of ranks, or perhaps (given the 'smallest' phrasing) it computes that for both samples and takes the smaller. You don't have a p-value of 0.05. A t-value is the value of a t-statistic, such as in a [two-sample t-test](http://en.wikipedia.org/wiki/Student%27s_t-test#Independent_two-sample_t-test).
Comment: I can't guess all of what you are seeing. Telling you the value of the test statistic and the critical values is not "just there to confuse you". Personally, I'd state at least the p-value (if your software is giving that). Failing that, I'd state a rejection rule in terms of a 5% critical value (for a 5% test - with the rejection rule stated after the hypotheses but before the observed value of the statistic). As for what you're "supposed" to do, that would depend on your audience - I am no mindreader as to what they expect from you.
Comment: `If you're willing to assume identical shapes [i.e. the populations' shapes are identical], you can use a Mann-Whitney to test means` Do you insist on means? Why not medians? (knowing that _samples_ shapes won't be exactly identical and can be skewed, but ranking data erases any remembrance of the means)
Comment: @ttnphns I don't know whether the OP insists on means or not, but *if* identical shapes (identical distribution apart from location shift\*) are assumed, *then* a rank test like a Mann-Whitney is not only completely valid as a test for difference in means, it *can even provide a consistent estimator of that location shift*. The fact that the rank transformation *itself* doesn't 'remember' where the mean is, is beside the point being made here. [\* with the proviso that if you're testing means, the common distribution is one whose mean exists, and perhaps some additional regularity conditions]


GoogleMaps API can't get current latitude and longitude

Question: I'm trying to get the coordinates but without success. The result is 0 . But when I write:
googleMap.setMyLocationEnabled(true);

I can see the blue dot. I'm trying to get these values with this code:
lat = googleMap.getMyLocation().getLatitude();
lng = googleMap.getMyLocation().getLongitude();

After that, lat and lng are 0.
My whole code:
public class GPS_maps extends Activity {
    // Google Map
    private GoogleMap googleMap;
    static Location currentLocation;
    static double lat , lng;
    TextView coordinates;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.map);
        coordinates = (TextView) findViewById(R.id.txt_coordinates);
        try {
            // Loading map
            initilizeMap();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initilizeMap() {
        if (googleMap == null) {
            googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
            // googleMap.setMyLocationEnabled(true);
            lat = googleMap.getMyLocation().getLatitude();
            lng = googleMap.getMyLocation().getLongitude();
            coordinates.setText(String.valueOf(lat) +" , " +String.valueOf(lng));
            LatLng coordinate = new LatLng(lat, lng);
            CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 5);
            googleMap.animateCamera(yourLocation);
            if (googleMap == null) {
                Toast.makeText(getApplicationContext(),
                    "Unable to create maps", Toast.LENGTH_SHORT)
                    .show();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
       initilizeMap();
    }}
}

I don't get any errors. Where is my mistake?
Comment: The map may not have your location at that point in time. Try adding an `onMyLocationChangeListener` to your map and set your location on the first call.
Answer: Try the following:
Remove static modifier from the declaration of lat, lan.
Make sure you are sending in the correct syntax to setCoordiante.
To make sure the lat and lan are right, print them out right after you get them.
Comment: removed the static but theres no diffrent still 0
Comment: Print out the vars right after you obtain them. What does it say?
Comment: Also print out the googleMap object to make sure it exists like u want it
Comment: What do you mean with print googleMap object ? And I am printing the vars after I obtain them or not ? What is for you after obtaining ? Where ?
Comment: System.out.println(lat) - do same for long
Comment: Then, also print something that you know is unique about this googleMap object, just to make sure it exists properly


About the stationarity of a sine wave

Question: I generated two sine wave time series and want to check the stationarity of them.

(1) The first time series is short. kpss.test() thinks it is stationary. PP.test() doesn't reject the null of unit root.
n=120
t=1:n
x=sin(t/(n-1)*6*pi)+rnorm(n)*0.2
par(mfrow=c(2,1))
plot(x,ty='l',xlab='',ylab='x',main='Sine')

# stationary test (H0:stationary)
kpss.test(x)$p.value
#[1] 0.1

# unit root test (H0: unit root)
PP.test(x)$p.value
#[1] 0.4937582

(2) The second one is much longer. kpss.test() says it is non-stationary while PP.test() tells it is stationary.
n=1000
t=1:n
x=sin(t/(n-1)*6*pi)+rnorm(n)*0.2
plot(x,ty='l',xlab='',ylab='x',main='Sine')

# stationary test (H0:stationary)
kpss.test(x)$p.value
#[1] 0.01

# unit root test (H0: unit root)
PP.test(x)$p.value
#[1] 0.01

While kpss.test() is more powerful for small samples (please see this Q&A), the first instance is understandable. However, I am really confused why kpss.test() fails for the second larger-sample time series. Anyone have any comments or answers please?
Comment: a sine wave is not stationary but unless I missed something, I don't think it has a unit root (which is a particular kind of nonstationarity). But in any case, failure to find a unit root doesn't imply stationarity.
Answer: We can classify trend part of time series in two parts: 1) Deterministic; 2) Stochastic. Most of the tests around stationarity is to test the unit root (deterministic trend).
In your case it is clearly deterministic trend. The trend part one can write as a function of time. Regarding the kpss test, null hypothesis of kpss test is the series is level or trend stationary. Kpss test accept H0 in your case. (In your second case, if you increase your frequency the test may fail to rejct the H0, x=sin(t/(n-1)*60*pi)+rnorm(n)*0.2).
Usually in time series modelling  first step is to eliminate (remove or by adding deterministic part) deterministic part in the time series. So practically this cases will not arise.
Comment: Surely you meant that the tests for stationarity test for stochastic trend?
Comment: @mpiktas, let me know if I am missing something.
Comment: Well the tests for stationarity usually test or test against unit root, hence stochastic trend, not deterministic.
Comment: Agreed. I will add this and avoid the confusion.
Comment: I agree with @mpiktas that unit root test is for stochastic trend. But the null hypothesis of kpss test if level or trend stationary. The 'Trend' here means linear trend instead of any deterministic trend.
Comment: Yes when the frequency increases to some extent, both tests will say it is stationary. The question is the two plots above have the same frequency, but they are not the same regarding stationarity. The only difference is their sample numbers.
Comment: don't get confused by the my mention about frequency.  In first kpss is failed to reject null (pvalue >0.05). In  second case I guess it is because of large data it not giving the right conclusion.
Comment: @vinux But in the second case if I twice the frequency with the length of time series unchanged, I get $p>0.05$.
Comment: If you increase the frequency, I guess the test is able to account the seasonal pattern (deterministic trend).
Comment: @vinux doesn't kpss test only recognise linear trend?
Comment: I am not sure about the theory behind kpss test. I rarely used this test. I guess experts in this forum can help you on this.
Answer: The Kwiatkowski–Phillips–Schmidt–Shin 1992 paper proved an influential contribution to time-series analysis, because it was the first well-recognized test that tested for non-stationarity by taking as null-hypothesis that the series is (linear determinisitic) trend-stationary -contrary to the Dickey-Fuller (or Phillips-Peron) family of tests that have as null that a unit root exists (i.e. that the series contains a stochastic trend).
The reasoning behind the KPSS  test is that unit-root tests of the DF/PP variety have low power especially when the root may be close to but below unity.  Most researchers advise that one should run both kinds of tests, and if they give conflicting results as regards the kind of trend detected, one should conclude that the data are not informative enough to provide an answer.
In the original KPSS test, a time series is modeled as being comprised of a linear deterministic trend, a random walk (the stochastic trend), and a white noise:
$$y_t = at+r_t+u_t, \qquad r_t=r_{t-1}+\varepsilon_t,\; \\u_t, \varepsilon_t\sim\operatorname{white noise and independent}$$
The null hypothesis is that $$\operatorname{Var}(\varepsilon_t)=0$$
which effectively eliminates the existence of the random walk (since it turns it into a constant, supplying the series with a drift). Under this null, the time-series is trend-stationary (i.e. it is stationary around a linear deterministic trend).
The test can also be used to test level-stationarity by not including the deterministic-trend part in the specification.
Under the additional assumption of normally distributed $\varepsilon_t$, the test statistic is a one-sided Lagrange Multiplier one. If the normality assumption is dropped, and if we further weaken the white-noise assumption and assume that $\{\varepsilon_t\}$ forms a mixing process, then the test-statistic has a non-standard distribution, which has special critical values.
As for a sine wave, does it look like it may contain a linear deterministic trend? Seasonality is what happens here. One of the original authors of the KPSS test (Peter C.B. Phillips) shows in this paper that the KPSS test statistic has the same limiting distribution when the data exhibit seasonality.
But here comes the critical point: the KPSS statistic is based on the residuals of least-squares regression of the dependent variable on a constant and a linear time-trend, when there is no seasonality. When there is seasonality, then the test statistic is based on a least-squares regression on a constant and seasonal dummies (or other more complicated ways to model seasonality). Does your software know what kind of regression to estimate in order to calculate the KPSS statistic?

About the stationarity of a sine wave


Drupal best way to render content type data and meta-data

Question: I am new to Drupal and struggling on the best approach to choose, I have several questions which are all related to my approach.
Let say I have a content type "Rooms" and would like to create 2 pages: 1 for listing the rooms and one per room (let's call that one Room A), plus I would like to add some additionnal data for the page listing rooms. Of course I need menu item when being on page "Rooms" but still need the item to be active when on page Room A.
Finally, the page Rooms not only list the room's content type but also display some static blocks which both has and has no relationship to the Room content type.Eg: an image's banner with a small description.
After doing some research, I have found several approach to do this:

Have a taxonomy "Rooms" with no terms and in which I classify all my rooms and add additional field for data specific such as my banner picture. I then create a basic page which I theme to call my blocks and taxonomies. The menu active trail issue is realized by taxonomy-menu trail.

Pro: it works. Cons: the logic bothers me, the purpose of taxonomy is more like a tagging system rather. Therefore I have to tag my content's instance each per each

I create a new content type "Banner" in which I add new fields, an image, a description... Using Node Hierarchy menu, I create a parent relationship for a basic page to a room content type, on that basic page i display all my block...

So, OK the content type is not a page it's an abstract of fields, but what if I want to display in the most efficient way data that are on higher level of abstraction of the content type and that are specific to that content type ?
What's your opinion ?
Answer: If I have understood well, here is what I would do:

Create a content type "Room", with specific fields and configuration (I guess you already did that).
Create several nodes of type "Room", one by actual room.
Create a View (using Views module) to display a list of all my nodes of type "Room" (I can tell you more about that if you need it) and where you can access the rooms page automatically. Of course, you can create a menu item in the same time. Very easy.
Create a custom static block with the banner, text, or whatever you want to be displayed on your View page.
Configure the block to be displayed only on your View page (path/to/your/view).

This is how I would have do that if I had to. I don't know if there is a better way but it seems quite logic and simple to me.
I hope it was the answer you wanted!
EDIT: I just remember the active menu item thing. I did that once in a project, it is a bit tricky but I can explain to you my method.
Comment: Hi, I have multiples pages which observe the same layout with one main jumbotron specific to the page. In my Room example, a banner, description of the page, display of a "from price", in another page "Activities" I'll have another jumbotron specific to the content type it hosts, an image, a description etc.. Therefore I don't feel like creating one static block for each page while it will be using the exact same layout, but creating another content type for giving an abstraction layer to a content type does not sound like a natural approach. I'm also using views but thanks for the advice ! :)
Comment: I think you have no choice to create 1 block per content-type you have. Assign these blocks to a region (custom or not). Test in module or template the path of your page and display a specific block depending on the path. Or I'm misunderstanding
Comment: Hi, following your comments I've thought about a new question (http://drupal.stackexchange.com/questions/123330/views-block-how-to-display-a-block-based-on-the-current-page), a bit a mix of what you said and what I desire, OK for creating a block per page but what if that block is a content type ? Then it becomes easier and better for user xp to create an instance of a block and display that instance based on some filter on the defined pages


WMI Rights required to read root\MicrosoftIISv2 in IIS7 with IIS6 compatibility mode

Question: I need to manage my IIS7 (Windows Server 2008) remotely with a WMI IIS6 API. So I added the IIS6 WMI Compatibility and IIS6 Metabase Compatibility roles to access the root\MicrosoftIIsv2 namespace.
I have a domain account which is not administrator on the remote machine ; with this right, everything is ok.
I configured these rights for my domain account to access the root\MicrosoftIIsv2 WMI  namespace remotely ; note that these rights work perfectly on a IIS6 and Windows Server 2003 :
DCOM :

Account in Distributed COM Users > Remote & local access to DCOM

WMI :

Root\CIMV2 (I need access here too) > Execute methods, Enable Account, Remote Enable
Root\Default (I need access here too) > Execute methods, Enable Account, Remote Enable
Root\MicrosoftIISv2 > Execute methods, Enable Account, Provider Write, Remote Enable

IIS Metabase (Metabase Explorer) :

LM > Full Control (W3SVC inherits these permissions)

I tried to give some access on C:\Windows\System32\inetsrv too ; don't know if needed.
My issue is :
I can't list the IIS WebSites (\root\MicrosoftIISv2:IIsWebServerSetting.Name="W3SVC/*"). I don't get an 'access denied' but nothing is returned.

My API and powershell tests can connect and execute queries in the root\MicrosoftIISv2 namespace
I can read the IIsComputer class

ex: Get-WmiObject IIsComputer -namespace "ROOT\MicrosoftIISv2" -authentication PacketPrivacy | SELECT *

I can't read the IIsWebServerSetting, IIsWebServer ... to list the WebSites : the query returns an empty collection

ex: Get-WmiObject IIsWebServerSetting -namespace "ROOT\MicrosoftIISv2" -authentication PacketPrivacy | SELECT ServerComment

All queries work perfectly if the account is administrator as already said
I am using PacketPrivacy authentication

FI: I got a Warning Event 5605 with the Administrator right or not, that does not seem to have an impact :

The root\MicrosoftIISv2 namespace is marked with the
  RequiresEncryption flag. Access to this namespace might be denied if
  the script or application does not have the appropriate authentication
  level. Change the authentication level to Pkt_Privacy and run the
  script or application again

Ok, I have some more informations, when I use IIS 6 Metabase Explorer with my administrator account I can see the rights are correctly inherited for my non-administrator account.
But when I try to connect using my non-administrator account, I can list the LM node, but get an "access denied, failed to get a key's data" when I try to browse the child nodes.
I'll check further.

I tried to Trace the WMI Activity, and everything seems OK ; this tends to confirm that the problem lies in IIS Rights.
Comment: I am confused..."My API and powershell tests can connect and execute queries", including listing sites?
Comment: Yes, the queries works (no error) but the one listing the sites returns nothing.
Comment: You state that you're using PacketPrivacy authentication, but the PowerShell query to list the websites that you've given as an example doesn't include the `-authentication PacketPrivacy` switch. Is that just a typo?
Comment: Yep, I'll correct this : I tried with `-authentication 6` and same result.
Comment: I'm getting a 'Class not registered' error - was thinking this is related but am confusing myself.
Comment: Nope it is not related, I think it is rather a code running on a machine where the WMI provider is missing : IIS not present or IIS 6 compatibility mode missing.
Answer: Resolved.
The WMI and IIS Metabase rights have to be set as you would do on an IIS 6. So they were correct for me.
The specifity is on the IIS Metabase. First of all, in IIS 7 the W3SVC rights are completely inherited from the root while you have to set the W3SVC/AppPools rights on IIS 6 if you want to handle the application pools.
Since there's a 'compatiblity', the main difference resides in IIS 7 metabase file system. On IIS 6, the read rights on the inetsrv folder (which is the default for Users) and the Metabase ACLs are sufficient.
On IIS 7, the rights have to be set on the IIS Metabase AND the IIS 7 configuration folder : %SYSTEMROOT%/system32/inetsrv/config (and .config files then). By default, only Administrators (thats why it is perfectly working with the Administrator right) and some other reserved groups can access this folder.
Another point, if you need to execute methods like a Stop on an application pool, this feature require the Write rights on the configuration folder.


Simplify this summation

Question: I have $\frac{(m-1)!}{(m+n)!} \sum_{i=0}^{m-1} \frac{(m+n-i-1)!}{(m-1-i)!}$. And i'm fairly certain that this equals 1/(n+1) but i'm not sure how I would simplify the big summation term to show that.
Answer: It helps to write your sum as $\frac{(m-1)!n!}{(m+n)!}\sum_{j=0}^{m-1}\binom{n+j}{j}$, where we take $j=m-1-i$. With the famous result$$\sum_{j=0}^{m-1}\binom{n+j}{j}=\binom{m+n}{m-1},$$we get the desired$$\frac{(m-1)!n!(m+n)!}{(m+n)!(m-1)!(n+1)!}=\frac{n!}{(n+1)!}=\frac{1}{n+1}.$$

Simplify this summation


(Discord.py) How can I get the entire embed content?

Question: I wanna get all the embed content(including the image link), I tried this:
print(msg.embeds)

And that's returning:
[<discord.embeds.Embed object at 0x000002E48768CD30>]
[<discord.embeds.Embed object at 0x000002E48768CAF0>]
[<discord.embeds.Embed object at 0x000002E487F04040>]
[<discord.embeds.Embed object at 0x000002E48768CA60>]
[<discord.embeds.Embed object at 0x000002E48768C9D0>]
[<discord.embeds.Embed object at 0x000002E487F043A0>]

I cant find anything about that on the documentation, only about sending embeds.
Answer: You're just getting embeds. According to API References, you can't get the whole embed content with one function like message.content. You have to get it part by part like Embed.title, Embed.description and Embed.fields.

Embed.fields Returns a list of EmbedProxy denoting the field contents.
See add_field() for possible values you can access.
If the attribute has no value then Empty is returned.

So that means, you can get embed title, description, and fields' name and value. Here's a simple example for this:
embed = discord.Embed(title='Example', description='Embed')
embed.add_field(name='field 1 name', value='field 1 value')
embed.add_field(name='field 2 name', value='field 2 value')

embed.title # returns 'Example'
embed.description # returns 'Embed'
embed.fields # returns a list of fields
embed.fields[0].name # returns 'field 1 name'
embed.fields[0].value # returns 'field 1 value'
embed.fields[1].name # returns 'field 2 name'
embed.fields[1].value # returns 'field 2 value'

Comment: Thanks. That should work, I'll also read the pages that you sent.


java.io.FileNotFoundException (Too many open files)

Question: I use the following code to write some data to files:
BufferedWriter writer = null;
try {
    writer = new BufferedWriter(new FileWriter(file));
    writer.write(...);
    writer.flush();
}
finally {
    if (writer != null)
        writer.close();
}

After invoking the method multiple times I got a FileNotFoundException because too many files are open.
Obviously java does not close the file handles when I close the writer stream. Closing the FileWriter separately does not help.
Is there sth. I can do to force java to close the files?
Comment: Can you post your stacktrace? Are you using this perhaps in a multi threaded environment?
Comment: Try adding `try .. catch around `writer.close()` too, to catch any problems there.
Answer: Your code looks fine. It could be another part of your application which is leaking file handles.
You can monitor file handles using lsof on Linux or pfiles on Solaris. On Windows, you can use ProcessExplorer.
Comment: You're right. The problem does not occur, if I run just the code I posted. Though it threw the exception because there were just no more files left to open. Seems I have to find the leak somewhere else.
Answer: No, Java does close the file handles when you close the writer. Its actually built using Decorator pattern. Hence, it must be something else. Show the stack trace.
Comment: The stack trace points only to the code, I posted. But you're right the problems is somewhere else.
Answer: See this thread about writing to files, good tips there.. pay attention to the finally block in Anons reply.
Answer: BufferedWriter closes the underlying stream. Probably, this a multithreading issue. You can keep an instance of FileOutputStream and close it. Something like:

java.io.FileOutputStream out = new java.io.FileOutputStream(file);
try {
  // make buffered writer, etc.
} finally {
  out.close();
}


Global Memory Load/Store Efficiency and Global Memory Coalescence

Question: I have the following simple code:
#include<stdio.h>

#define BLOCKSIZE_X 32
#define BLOCKSIZE_Y 1

int iDivUp(int a, int b) { return ((a % b) != 0) ? (a / b + 1) : (a / b); }

#define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); }
inline void gpuAssert(cudaError_t code, char *file, int line, bool abort=true)
{
    if (code != cudaSuccess)
    {
        fprintf(stderr,"GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line);
        if (abort) exit(code);
    }
}

__global__ void kernel0(float *d_a, float *d_b, const unsigned int M, const unsigned int N)
{
    const int tidx = threadIdx.x + blockIdx.x * blockDim.x;
    const int tidy = threadIdx.y + blockIdx.y * blockDim.y;

    if ((tidx < M)&&(tidy < N)) {

        d_b[tidy * M + tidx] = d_a[tidy * M + tidx];

    }

}

void main()
{
    const unsigned int M = 32;
    const unsigned int N = 1;

    float *d_a; cudaMalloc((void**)&d_a, M*N*sizeof(float));
    float *d_b; cudaMalloc((void**)&d_b, M*N*sizeof(float));

    dim3 dimGrid(iDivUp(M, BLOCKSIZE_X), iDivUp(N, BLOCKSIZE_Y));
    dim3 dimBlock(BLOCKSIZE_X, BLOCKSIZE_Y);

    kernel0<<<dimGrid, dimBlock>>>(d_a, d_b, M, N);
    gpuErrchk(cudaPeekAtLastError());
    gpuErrchk(cudaDeviceSynchronize());

    cudaDeviceReset();

}

which executes the assignment between two arrays of 32 floats. I'm trying to understand the relation between global memory coalesced accesses and global memory load/store efficiency as well as other metrics/events.
The Visual Profiler shows the following metrics:
Global Memory Load Efficiency = 50%
Global Memory Store Efficiency = 100%

The value of the Global Memory Load Efficiency surprises me. I would have expected 100% efficiency in both the cases since I believe I'm performing a perfectly coalesced memory access. So my question is:
Why do I have a 50% Global Memory Load Efficiency when I'm performing a coalesced memory access and instead I have a 100% Global Memory Store Efficiency?
I have investigated also other metrics/events, which may be useful to be reported:
gld_inst_32bit = 32 (Number of 32-bit global memory load transactions)
gst_inst_32bit = 32 (Number of 32-bit global memory store transactions)

Indeed I'm requesting to load/write 32 floats.
uncached global load transaction = 0 (Number of uncached global load transactions)
l1 global load miss = 2 (Number of global load misses in L1 cache)

The above two events seem to be contradictory, according to my (probably erroneous) understanding. In the case of a l1 cache miss, I would have expected the first event to be different from 0.
gld_request = 1 (Number of executed global load instructions per warp in a SM)
gst_request = 1 (Number of executed global store instructions per warp in a SM)

which seem to be consistent with the fact that I'm performing a perfectly coalesced memory access.
The disassembled code is the following:
/*0000*/         MOV R1, c[0x1][0x100];                          /* 0x2800440400005de4 */
/*0008*/         S2R R3, SR_CTAID.Y;                             /* 0x2c0000009800dc04 */
/*0010*/         S2R R4, SR_TID.Y;                               /* 0x2c00000088011c04 */
/*0018*/         IMAD R4, R3, c[0x0][0xc], R4;                   /* 0x2008400030311ca3 */
/*0020*/         S2R R0, SR_CTAID.X;                             /* 0x2c00000094001c04 */
/*0028*/         ISETP.LT.U32.AND P0, PT, R4, c[0x0][0x2c], PT;  /* 0x188e4000b041dc03 */
/*0030*/         S2R R2, SR_TID.X;                               /* 0x2c00000084009c04 */
/*0038*/         IMAD R0, R0, c[0x0][0x8], R2;                   /* 0x2004400020001ca3 */
/*0040*/         ISETP.LT.U32.AND P0, PT, R0, c[0x0][0x28], P0;  /* 0x18804000a001dc03 */
/*0048*/    @!P0 BRA.U 0x78;                                     /* 0x40000000a000a1e7 */
/*0050*/     @P0 IMAD R2, R4, c[0x0][0x28], R0;                  /* 0x20004000a04080a3 */
/*0058*/     @P0 ISCADD R0, R2, c[0x0][0x20], 0x2;               /* 0x4000400080200043 */
/*0060*/     @P0 ISCADD R2, R2, c[0x0][0x24], 0x2;               /* 0x4000400090208043 */
/*0068*/     @P0 LD R0, [R0];                                    /* 0x8000000000000085 */
/*0070*/     @P0 ST [R2], R0;                                    /* 0x9000000000200085 */
/*0078*/         EXIT;                                           /* 0x8000000000001de7 */

EDIT
My configuration: CUDA 6.5, GeForce GT540M, Windows 7.
If I increase M from 32 to 64 to launch two blocks and make the two available Streaming Multiprocessors of my card busy, then the Global Memory Load Efficiency turns to 100% and these are the new metrics/events:
gld_inst_32bit = 64
gst_inst_32bit = 64

uncached global load transaction = 0
l1 global load miss = 2

gld_request = 2
gst_request = 2

The increases of gld_inst_32bit, gst_inst_32bit, gld_request and gst_request are expected and consistent since now I'm loading7storing 64 floats and 2 global memory load/store coalesced requests. But I do not still understand how uncached global load transaction and l1 global load miss can keep the same, while the global memory load throughput changes to provide 100% efficiency.
EDIT
Results on a Kepler K20c for M=32:
Global Memory Load Efficiency = 100%
Global Memory Store Efficiency = 100%
gld_inst_32bit = 64
gst_inst_32bit = 64
gld_request = 1
gst_request = 1
uncached global load transaction = 1
l1 global load miss = 0
l1 global load hit = 0

Now the Visual Profiler reports an uncached global load transaction but no l1 global load miss.
EDIT
I have investigated a little bit more into this issue, increasing the value of M and keeping the BLOCKSIZE_X fixed.
When the number of blocks is odd, namely the load on the two Streaming Multiprocessors of my GT540M card is unbalanced, then the Global Memory Load Efficiency is less than 100%, otherwise it is 100% in the even case. The Global Memory Load Efficiency slowly tends to 100% as long as the number of blocks is increased in the odd case.
If I disable the L1 cache by compiling with -Xptxas -dlcm=cg, as suggested by @Jez, then the Global Memory Load Efficiency is always equal to 100%, as it is the Global Memory Store Efficiency. I know that global memory stores do not use L1 cache, but only L2.
Some pictures showing, for different values of M, the behavior of the Global Memory Load Efficiency
M=32

M=64

M=96

M=128

M=160

M=192

Note that M is an integer multiple of 32 to enable loading of an entire cache line by a single warp.
By disabling the L1, I have:
M=32

M=64

M=96

EDIT - RESULTS FOR A TESLA C2050
M = 32    33.3%
M = 64    28.6%
M = 96    42.9%
M = 128   57.1%
M = 160   71.4%
M = 192   85.7%
M = 224  100%
M = 256  114%
M = 288   90%

Again, if I disable the L1 cache, I have 100% Global Memory Load Efficiency in all the cases.
Comment: I don't see anything unusual in this question except the case where you have one warp (M=32) and are getting 50% load efficiency.  I haven't been able to reproduce that, and it goes away (for you) as soon as you go to more than one warp.  It's an oddity, but not something I can personally get too worked up about.  It may be a bug in the profiler, or an actual non-obvious functional anomaly in this pathological case (e.g. 2 loads, one of which isn't used).  I can't explain it or reproduce it.
Comment: Regarding `uncached global load transaction` vs `l1 global load miss`: there are two types of global load transactions. Cached and uncached. A cached transaction is cached in L1, uncached is not. On Fermi the default is to cache in L1, and hence you have no uncached global load transactions. If you were to compile with the argument `-Xptxas -dlcm=cg` you would generate loads which were not cached in L1 and the `uncached global load transaction` counter would increment. Note: this is just L1, not L2.
Comment: You have an L1 cache miss because the data your kernel is requesting (`d_a`) is not initially in the L1 cache of the SM in the Fermi case.  That is a "miss".  In the Kepler case, the [L1 cache is disabled for global loads](http://docs.nvidia.com/cuda/kepler-tuning-guide/index.html#l1-cache), so all loads are "uncached" and there will be no L1 misses as there is no L1 in play.
Comment: What compute capability and CUDA version are you using?
Comment: @Jez Thanks. I have added the details of my configuration and the results for a new test case.
Comment: @Jez But if, as we agree, I have no uncached global load transactions, why do I have a `l1` cache miss?
Comment: I think the key is that "uncached global load transactions" is counting the number of load transactions that use the uncached instruction. It is **not** the number of load instructions that didn't hit in the cache, it's the number that didn't even look.
Comment: @RobertCrovella I have investigated a little bit more into this issue, increasing the value of `M` and keeping the `BLOCKSIZE_X` fixed. Unfortunately, this issue does not go away. When the number of blocks is odd, namely the load on the two Streaming Multiprocessors of my GT540M card is unbalanced, then the Global Memory Load Efficiency is less than `100%`, otherwise it is `100%` in the even (balanced) case. The Global Memory Load Efficiency slowly tends to `100%` as long as the number of blocks is increased in the odd case (see my edited question).
Comment: @RobertCrovella If I disable the L1 cache by compiling with `-Xptxas -dlcm=cg`, as suggested by @Jez, then the Global Memory Load Efficiency is always equal to `100%`, as it is the Global Memory Store Efficiency. I know that global memory stores do not use L1 cache, but only L2, as the global memory loads for Kepler are, as you have pointed it out to me. The key to understand this seems to be `L1/L2` caching?
Comment: @RobertCrovella I have done a very fast test on a `Tesla C2050` card and I received a Global Memory Load Efficiency of `33.3%` for `M=32`. But I have no access to that machine right now and I have to confirm this result.
Comment: @RobertCrovella I have updated the post with the results on a Tesla C2050.
Answer: ACCURACY OF COUNTERS
The NVIDIA profilers can collect both raw counters and metrics. Many of the metrics require the kernel to be executed many times. Ideally, the profiler would be able to collect all raw counters for a metric in a single pass but this is simply not possible given the limitations of the performance monitor systems.
On Fermi architecture the HWPM system used to collect L1 statistics for Global Memory Load Efficiency and Global Memory Store Efficiency can only observe 1 L1 unit per GPC. For GF100 (C2050) this equates to 25% observation.
The profiler will not be able to provide accurate results if the workload does not fully fill the machine and the work per unit is the same per pass.
On Kepler architecture the HWPM system can collect L1 statistics from every L1 but still has some limitations for L2 which can lead to small discrepancies.
On Maxwell architecture the memory system is significantly different as global, local, and surface requests now all go through the unified L1/TEX cache.
CACHED VS. UNCACHED
In the Fermi architecture all global load/stores are through the L1 cache. Uncached global loads/stores are still through L1, use an LSU transaction, and require a tag lookup to invalidate the cache line. Atomics are the only form of global access through L1 that do not invalidate the L1 cache.
The Kepler architecture has a few small changes. By default most chips do not cache global memory accesses so all global loads are uncached. On GK110 and GK208 chips it is possible to use the new LDG instruction to load global data through the TEX cache.
Cached and uncached global load transactions from the SM to L1 are 128 bytes.
Cached global load transactions from L1 to L2 are done as 4 32B requests.
Uncached global load transactions from L1 to L2 are done as the minimal number of 32B requests.


How to add class for all parents of one siblings element with jQuery

Question: I have this markup:

Now I need to give a class for each parent, depending on the button clicked.
So i do this:
var main_ctnr = $('.main_cntnr'),
    main_prnt = main_ctnr.find('li.parent');

$('span.button').on('click', function(){
   main_prnt.prevAll().addClass('some_class);
}

And solve the need to have:
after click on first button

after click on second button

and third

It must act only within the first parent, so that the earlier part of the main parent did not receive the class already. No this situation may be, after click this_button:

This is harsh so from the mountains - Much thx for help.
Comment: In the `click` handler of the buttons, just use `$(this).parents(".parent").addClass("some_class");`
Comment: but after this i will have class for all of li parents, i need to add it only for main parent element
Comment: Dude, do you mean to say that you want to apply class only for the first parent, on click of any button, If 'yes', then this should be your solution
$('span.button').on('click', function(){
    $('li.parent:first').addClass('some_class');
});
Comment: @SAM: Your selector is agnostic of scope. that will match the first `.parent` on the page, regardless of which `.button` was clicked.
Comment: not for first, for all
Answer: You want .parent() (direct parent) or .parents() (traverse up through all parents) not .prevAll. .next* and .prev* are for siblings.
From there you can adjust your selector to filter/narrow your search, or change how many parents you want to traverse, e.g. $(this).parents('.parent') matches all parent nodes with the class parent applied.
To visualize it, if you had:
$('span').click(function(){
  $(this)./*one of the below methods*/;
});

See how each method would react if called off of $(this):
                            .parent() .parents() .parents('foo') .parents('bar')

                                  x

                    x          x

    x         x          x               x
      target

An x means it would be returned in the result.


kafka producer blocking on callback

Question: I'm testing the async send() in my kafka producer.
The cluster I want to connect to is offline.
My assumption would be that I send 10000 individual requests (lenght of listToSend) quickly.
Next the timeout (60s) would kick in and after 60 seconds I would see the callbacks hit me with logger.error(s"failed to send record ${x._2}", e)
However it seems to take forever for the method to finish.
That's why I added in the logger.debug("test: am I sending data") line.
It prints, then nothing happens for 60 seconds. I see the failed callback for the 1st record. And only then will it move on.
Is this normal behavior or am I missing something fundamental?
listToSend.foreach { x =>
        logger.debug("test: am I sending data")
        // note: I added this 'val future =' in an attempt to fix this, to no avail
        val future = producer.send(new ProducerRecord[String, String](topic, x._2), new Callback {
          override def onCompletion(metadata: RecordMetadata, e: Exception) {

            if (e != null) {
              //todo: handle failed sends, timeouts, ...
              logger.error(s"failed to send record ${x._2}", e)
            }
            else { //nice to have: implement logic here, or call another method to process metadata
              logger.debug("~Callback success~")
            }
          }
        }
        )
      }

note: I do not want to block this code, I want to keep it async. However it seems to be blocking on the send() regardless.
Comment: You need to get the Future
Comment: isn't that blocking? I added "val future = " in an attempt to fix this, it wasn't originally there
Comment: `producer.send` returns a `Future[RecordMetadata]` (or something like that). You can call `val meta = future.get()` to actually do the block, as well as `producer.close`
Comment: But I don't want to block, that's the thing. It's blocking now, but I just want to "get rid" of my records fast and let the logic handle any kind of failures/downtime/...
Comment: Then you need to set acks to zero in the producer config and not use a Callback or assign the future
Comment: the whole reason I put that in, is to have visibility of what's going wrong. Otherwise, if I don't put that callback in, we could be running a job for days without even knowing we might have not set the brokers correctly. So this is by design? As I understand it, I only have 1 thread for each broker and that's blocked by the callback, even-though I thought I was doing "fire and forget"
Comment: If you want to "forget", you don't need a Callback to verify results, right? You can use multiple threads, which can communicate with multiple brokers. You're not sending a message key, so it'll be null and round robin over all partitions of a topic (ie multiple brokers). And if you get exceptions, those are logged internally by log4j, not completely necessary within your code
Comment: Let me rephrase that: In my "producer send call loop" I don't want to care yet, I just want my 10K records handled so I can go and fetch some more.
However in the callback part, I want to catch exceptions, log them or maybe in future handle them (i.e. send an email to me to tell me that 200 records have not been received due to timeouts/record size limits/...) I know that just an empty "send()" is fire & forget. But I want to know and maybe act upton misshaps that might occur.
Answer: The parallelism I never figured out completely.
However it seems like my topic name (I had named it '[projectname here]_connection') was the issue.
Even though I didn't know of any reserved keywords in topic names, this behavior popped up.
Some further experimenting also brought up that a topic name with a trailing space can also cause this behavior. The producer will try to send it to this topic, but the Kafka cluster doesn't seem to know how to deal with it, causing these timeouts.
So for all of you who come across this issue, check/change your topic name before proceeding your troubleshooting.

kafka producer blocking on callback


Do we hit all 6 strings for upstrokes?

Question: I saw a video in youtube where they told us to play only the bottom 3 strings while upstroking and all 6 strings while downstroking. The reason given was that the upstrokes will sound slightly higher pitched compared to all the downstrokes and that difference makes it sound good. (Of course which strings we actually play depends from chord to chord, but in general this is the recommendation that was given).
Since I am new to playing guitar I don't know whether this is the correct way to play or not. Is this a recommended way to play the upstrokes?
Answer: The short answer: It depends on how you want to sound, what you are playing, and the tones you are looking for.
The long answer: Upstrokes hitting a varying number of strings is really a matter of creative preference. If the sound fits the song, then play it. Think of it like this: when you play a 'power' barre chord you only play the root, fifth, and the octave. You get that specific trio every time--which is pretty versatile across any backing melodies you want to compose. When you start adding more strings to the barre, you get more tonal options and voicings. When you play an upstroke you could potentially think of it the same way. You may only want three strings of a particular chord, or four, or even more to add color to what you are playing. It's by no means restricted to a steadfast rule.
I'll shut up and let someone more knowledgeable in theory take over and give you a better explanation, but that's more or less how a self-taught guy (me) thinks about it.
Answer: For about anything with guitar, there are no "right answers". There are just actions and results. If it doesn't get you the right result, then try another action.
Gillian Welch and David Rawlings play so that she's strumming and mostly hitting the low and high strings, much like you talk, while he plays the melody and harmony lines on the D and G strings in the middle, and this is how they keep out of each other's way.
So, I say it's as good as any and better than most.
Answer: There are many different styles of strumming.   The standard country/bluegrass "boom-chicka-boom"  (bass note, downstroke, upstroke, bass note....) tends to only hit the upper strings on the upstroke.
Folkie-style up-and-down stroke without hitting any single strings tend to involve more strings...
Answer: The key is that unless you are trying to sound exactly like someone else or in a style, you play however you want and whatever sounds good.
For me, it totally depends on a number of factors. In a full band, I will typically play the D, G and B strings, because we have a female singer a lead who plays higher on the neck and a bass so I need to keep the middle tones full as well. If I'm trying to add strength to the melody, I will play what ever string has the root in it.
Try playing around with the same chord and seeing how even just a simple chord has a different feel when playing different parts in different patterns. The number of ways that you can strum is way larger than the number of chords you can play.
Have fun!

Do we hit all 6 strings for upstrokes?


SOS! How do I deploy multiple Laravel apps on a windows IIS server in a LAN

Question: I am setting up an IIS server in readiness to host multiple PHP web apps. These will be used within our local network so no need internet access. I have read a lot of stuff on how to go about it but am getting lost even more. someone please help.
Comment: This look pretty straigt forward https://devopspoints.com/microsoft-iis-10-0-hosting-multiple-websites.html
Comment: Yes, it's good documentation, I also checked, you can follow this.  if any confusion in above documentation, you can also check this one - https://serverfault.com/questions/536866/how-to-host-pages-on-iis-for-a-domain-on-linux
Answer: You can refer to this document for detailed steps about deploy php application on IIS.
Here are some main important points:

Install IIS in control pannel(windows) or server manager(windows server).
Configure php. Youcan download it from php official website or Web PI(more recommand). The version over php8 may not work on IIS.
Make the physical path of site points to root folder of application. It will auto generate web.config. Set the permission of root folder to avoid 500 error.
If you have multiples version of php, you can isntall php manager to configure them.


Find $\frac{dF(x)}{dx}$ Where $F(x)=\int_{2^x}^{3+x^3}\cos t^2\;dt$

Question: Find $\frac{dF(x)}{dx}$ Where$$F(x)=\int_{2^x}^{3+x^3}\cos t^2\;dt$$
I'm not entirely sure about how to do this question having only done basic integrals with $R$ values for $a,b$.
Any help will be appreciated!
Comment: $$F(x) = \int_{2^x}^{3+x^3}C^2\;dt =\int_{0}^{3+x^3}C^2\;dt + \int_{2^x}^{0}C^2 \;dt$$

$$\dfrac{dF(x)}{dx} = \dfrac{d}{d(3+x^3)}\left(\int_{0}^{3+x^3}C^2\;dt \right)\dfrac{d(3+x^3)}{dx} + \dfrac{d}{d(2^x)}\left(\int_{2^x}^{0}C^2 \;dt\right) \dfrac{d( 2^x)}{dx}$$

Can you solve this ?
Comment: Do you know [Leibniz integral rule](https://en.wikipedia.org/wiki/Leibniz_integral_rule)?
Comment: @A---B Would I just sub in $3+x^3$ into $C^2$, and then find the derivative of $3+x^3$ and do the same to the other side?
Comment: @MANMAID I don't quite remember it. This is for a higher year calculus course and we got some practice problems to refresh our memory and I have forgotten all about it. Time to watch some videos and read up that wiki I guess haha
Comment: @HelloMellow "read up that wiki I guess"-- you must... this is straight forward if you know that.
Answer: Use the fundamental theorem of calculus.
Let $f(t) = \cos t^2$
Notice if
$\int \cos t^2 dt = g(x)$ then
$\int_{2^x}^{3+x^3} \cos t^2 dt = g(3+x^3) - g(2^x)$
Then your derivative is
$(3+x^3)'f(3 + x^3) - (2^x)'f(2^x)$
Using the chain rule.
Comment: Very nice answer.
Answer: Use $\frac{d}{dx}(\int_{f(x)}^{g(x)}h(t)dt)=h(g(x))g'(x)-h(f(x))f'(x)$


How many iptables block rules is too many

Question: We have a server with a Quad-Core AMD Opteron Processor 2378. It acts as our firewall for several servers. I've been asked to block all IPs from China.
In a separate network, we have some small VPS machines (256MB and 512MB). I've been asked to block china on those VPS's as well.
I've looked online and found lists which requires 4500 block rules. My question is will putting in all 4500 rules be a problem? I know iptables can handle far more rules than that, what I am concerned about is since these are blocks that I don't want to have access to any port, I need to put these rules before any allow. This means all legitimate traffic needs to be compared to all those rules before getting through. Will the traffic be noticeably slower after implementing this? Will those small VPS's be able to handle processing that many rules for every new packet (I'll put an established allow before the blocks)?
My question is not How many rules can iptables support?, its about the effect that these rules will have on load and speed.
Thanks.
Comment: It completely depends on how your rules sets are structured.  If you use chains and ipsets in appropriate places then you can have a large rule set, but a particular packet will not have to be evaluated against every rule.
Comment: Why not just give it a try and find out? It's simple enough to revert...
Comment: That's the plan. But I thought I would ask first since I won't truly know the effects without leaving it on due unpredictable traffic spikes. And I am just concerned that when those spikes start, it will bring the site down to a crawl.
Comment: https://developers.redhat.com/blog/2017/04/11/benchmarking-nftables/
Answer: It will support that many rules, but you really wouldn't want to traverse a chain of 4500 rules.
As @Zoredache pointed out you could also binary split the chains. If you did it perfectly you could drop the number of chain traversals to 13.
The simplest way to do this is with ipsets.
I am using EL6 which provides support for this. Obviously I dont know all the chinese netblocks so I'm just filling this with garbage..
ipset create china hash:net
ipset add china 22.214.171.124/24
ipset add china 18.104.22.168/16
ipset add china 18.104.22.168/8
ipset add china 126.96.36.199/24

Then add a rule to IPtables to match on that set and drop traffic..
iptables -I INPUT -m set --match-set china src -j DROP

This is much more efficient and faster than standard rule chains.
Comment: You need to sort each network block by its binary IP, at the middle split. Then in the left half, go to the middle, split, the right half, go to the middle, split and keep halving and splitting new halves until you have nothing left to split. It is a bit infeasible in all honesty without automating it.
Comment: Thanks. I forgot all about ipsets. This will solve the problem for the dedicated server, however the VPS's are OpenVZ which do not support ipsets. Can you provide more info about the binary splitting of the chains? I haven't heard of that.
Comment: Can you not just setup the same rules to work in the FORWARD chain of the server the OpenVZ works on instead?
Comment: I don't have access to the host server, only the guest os.
Comment: https://developers.redhat.com/blog/2017/04/11/benchmarking-nftables/
Comment: Worked perfectly with debian stretch (from archive.debian.org) in 2023.


Is the "sum of all natural numbers" unique?

Question: A while ago, there was a great hype about the "identity"
$$\sum_{n=1}^{\infty} n = -\frac{1}{12}.$$
Apart from some series manipulations where the validity seems to be at least questionable, the derivation of this always goes through the zeta function:
Where the series converges, the zeta function is defined by
$$\zeta(s) = \sum_{n=1}^{\infty}\frac{1}{n^s}$$
and outside that range by analytic continuation. And it turns out that inserting $s=-1$ formally results in
$$\zeta(-1) = -\frac{1}{12} = \sum_{n=1}^\infty n$$
However looking at the series in isolation, there is no indication that the zeta function should be chosen.
An obvious way to get an analytic function that at one point gives the sum of all natural numbers is
$$f(x) = \sum_{n=1}^{\infty} nx^n$$
at $x=1$, however (not surprisingly) that function diverges at $1$.
Therefore my question:

Is it possible to get another finite value for the series by analytic continuation of another series?

Concretely, do there exist continuous functions $f_1, f_2, f_3, \ldots$ such that

On some non-empty open subset $S$ of $\mathbb C$, $f(x)=\sum_{n=1}^\infty f_n(x)$ converges to an analytic function.
At some point $x_0$, $f_n(x_0) = n$ for all positive integers $n$.
The analytic continuation of $f$ is well defined and finite at $x_0$.
$f(x_0) \ne -1/12$

What if we demand the functions $f_n$ to be analytic rather than just continuous?
Comment: I agree with Masacroso. $\sum_{n=1}^{\infty} n = \infty\neq -\frac{1}{12}.$ Don't write such a formula.
Comment: I did put the word "identity" in quotes. If it were not allowed to ever write down a wrong equation, mathematics would become a few orders of magnitude harder.
Comment: is not "questionable" , the identity is just false. A possibility to write correctly the idea behind this "identity" is writing $\sum_{n=0}^{\mathfrak R}n=-\frac1{12}$ where the $\mathfrak R$ means that we used the Ramanujan summation method to give a value to the divergent series
Comment: Note that [you can](https://en.wikipedia.org/wiki/Weierstrass_factorization_theorem) write many entire functions $g$ that vanish at $n=1,2,3,...$. Then you can replace $f_n$ with $f_n+\frac{1}{2^n}g$ to get $f+g$ as the sum. Note however, that the question that you asked in the title has another angle besides the one asked at the end. One can ask whether other summation methods give a different answer. Which [properties](https://en.wikipedia.org/wiki/Divergent_series#Properties_of_summation_methods) can be kept, etc.
Comment: The definition that allows to write $\sum_{n=1}^{\infty}n=\infty$ is as arbitrary as the one for $\sum_{n=1}^{\infty}n=-\frac{1}{12}$, so no need to feel bad about writing it, only careful what one deduces from it.
Comment: My question does not spread fake news. Your argument is as meaningful as complaining about someone who writes "Some people claim that the Earth is flat" because some people might incorrectly take that as statement that the Earth is flat.
Comment: To the close voters: In which way is this question off-topic?
Comment: @Carmeister: How exactly is that a duplicate of my question?
Comment: @conditionalMethod Most people tend to be "not careful" with fake news, because they don't know enough to see this. This was for a long time top number one post. It came every week again and again. And always hoping it would be true. Despite some [efforts](https://math.stackexchange.com/questions/39802/why-does-123-cdots-frac112), it didn't stop.
Comment: Possible duplicate of [Why does $1+2+3+\cdots = -\frac{1}{12}$?](https://math.stackexchange.com/questions/39802/why-does-123-cdots-frac112)
Comment: See also that very nice answer of Lubos Motl  https://math.stackexchange.com/a/39811 and the subsequent comments.  I've found this searching for "abstract duplicates" on the meta-site and then the subsection. (That relevant list should possibly some time been curated and actualized...)
Comment: @conditionalMethod: Unless I'm missing something, your comment answers my question. If you make it an actual answer, I'll accept it.
Comment: [I have suggested on meta that this question be reopened](https://math.meta.stackexchange.com/a/30880/25554).
Comment: @MJD: Thank you.
Answer:
What if we demand the functions $f_n$ to be analytic rather than just continuous?

No problem. Define
$$f_n(s) = \frac{n}{(n - (-1)^n)^s},$$
where $k^s$ is as usual defined using the real value of $\log k$ (works since $n - (-1)^n > 0$). Then $f_n(0) = n$ for all $n$, and by a standard argument the series converges absolutely and locally uniformly for $\operatorname{Re} s > 2$. We compute
\begin{align}
\sum_{n = 1}^{\infty} f_n(s)
&= \sum_{n = 1}^{\infty} \frac{n}{(n - (-1)^n)^s} \\
&= \sum_{n = 1}^{\infty} \Bigl(\frac{1}{(n - (-1)^n)^{s-1}} + \frac{(-1)^n}{(n - (-1)^n)^s}\Bigr) \\
&= \sum_{n = 1}^{\infty} \frac{1}{(n - (-1)^n)^{s-1}} + \sum_{n = 1}^{\infty} \frac{(-1)^n}{(n - (-1)^n)^s} \\
&= \biggl(\frac{1}{2^{s-1}} + \frac{1}{1^{s-1}} + \frac{1}{4^{s-1}} + \frac{1}{3^{s-1}} + \ldots\biggr)  \\
&\qquad + \biggl(-\frac{1}{2^s} + \frac{1}{1^s} - \frac{1}{4^s} + \frac{1}{3^s} - \frac{1}{6^s} + \frac{1}{5^s} - \ldots\biggr) \\
&= \sum_{m = 1}^{\infty} \frac{1}{m^{s-1}} + \sum_{m = 1}^{\infty} \frac{(-1)^{m-1}}{m^s} \\
&= \zeta(s-1) + \eta(s)
\end{align}
for $\operatorname{Re} s > 2$. This has an analytic continuation to $\mathbb{C}\setminus \{2\}$, and the value at $0$ is
$$\zeta(-1) + \eta(0) = -\frac{1}{12} + \frac{1}{2} = \frac{5}{12}.$$
One can by similar means obtain different values.
Such summation methods are however very ad-hoc, as far as I know every "reasonable" summation method assigns either $+\infty$ (the natural value) or $-\frac{1}{12}$ to the divergent series. I admit that I don't know a good definition of "reasonable" for summation methods (except maybe "extends 'limit of partial sums', is linear and stable", but that definition excludes several widely used summation methods).
Comment: @Gerben No. If it is absolutely convergent it can be reordered whether one is interested in the absolute value or not. And we are interested in the function the series defines where it is convergent to see whether that sum function has an (unambiguous) analytic continuation to $0$. Since the series converges absolutely where it converges, reordering is no problem at all.
Comment: How do you get from the sum over $n$ to the sum over $m$?
Comment: Reordering and renaming. I could have also kept the name $n$ of course. The sequence $n - (-1)^n$ goes $2,1,4,3,6,5,\ldots$, so I just swap adjacent terms to get it in the usual order.
Comment: I see. It would probably make sense to put that information into the post. Nice example!
Comment: @Gerben Where the series converges at all, it converges absolutely, hence it can be reordered in any way we please without changing the sum. The reordering just serves to identify the sum function more easily.
Comment: @Gerben But the term is $\frac{(-1)^n}{(n - (-1)^n)^s}$, that yields $\frac{(-1)^{m-1}}{m^s}$.
Comment: You might be right. I don't know enough, nevermind.
Comment: @Gerben Not at all. The idea of analytic continuation has nothing to do with summing series in the first place, it's about extending analytic functions to a larger domain than they were originally defined on. Using analytic continuation as a summation method for divergent series is an application. One that has issues, because by judicious choice of the function you continue, you can assign different values to the same divergent series. That is the point of the answer (and the question).
Answer: Here is a copy of an older question which is more general than yours, but I think, your specific question is included by this:
The initial question MSE

Are there any cases when Abel, Cesaro, Borel, Ramanujan, Zeta regularizations are applicable for regularization of a divergent series or integral but give different results?

Here I cite my own comments (and the interactions of the asker), which may answer your question as far as possible

If there were such a case it should be mentioned in wikipedia or mathworld or any serious online/paper encyclopedia ... So I'm sure, there is no such case (except, if you like, that for some regularization the "value" is infinity and for some other is a finite value (multivaluedness in the sense, that only one possible finite value occurs and else only infinities)

@Gottfried Helms I need a reference for paper that these approaches are equal.

Maybe -but not too modern- Konrad Knopp, "On infinite series" (or so) - it is online in german language, but I think I've come across the english translation as well. Chapter XIII is about divergent series. The other classic is surely G.H. Hardy's monography. But besides of discussion of the Tauberian theorems and perhaps general statements about the equivalence of methods I don't think, they've made the explicite statement in that form you wish here - I surely would remember this! (Note that very similar questions appeared here and in math-overflow from time to time, I think to remember one user who collected material with that focus for writing his batchelor-exposé.)
Konrad Knopp, unendliche Reihen, chap XIII, pg 480: "(2) permanence-principle: a new regularization-method should first be compatible with convergent series: for convergent series it should give the same value. (2b) Usefulness: But to be useful at all, we expect that it can regularize at least one series which was not convergent itself" (3) When there are different regularization-methods which are capable to assign a finite value to a given series, then all that regularization-methods shall give the same value to that series. " So (3) is -so to say- an axiom which defines, which methods are acceptable in number-theory. Maybe this passage helps for your text (It is not translated here, I just paraphrased. If it is helpful for you you might find it in the english book likely available in google.books - I'm not so good in english to give you a reliable translation by myself)

One should possibly also mention the Springer-online-encyclopedia, which has a lot of entries for divergent summation, and no such ambiguity (two different finite values given by two different regularizations) is mentioned.

@Gottfried Helms does he list the methods that give the same value?

At least Cesaro, Hölder, Abel, Euler, Riesz,Borel,Le Roy in the book. Don't know at the moment whether he touches Zeta-regularization. Ramanujan is, as far as I remember, in a follow-up article. But I think I've the german chapter locally as pdf-file. I'll see and report
  S. Chapman & G.H.Hardy (1911) is referred to an article (in "quarterly Journal, Vol 42, pg. 181" on the systematizing of the various regularization-methods. Perhaps there is an explicite statement like you need it.
Knopp's most contribution is first part of previous century. He did not, for instance know of methods like Aitken-process etc and I do not know whether this compatibility axiom extends to those modern, non-linear, summation procedures as well. Anyway, the reference-list of Knopp's chap XIII should be understandable for you and gives a rich list of further-readings (of course of his contemporaries only...).

another commenter

It depends how you define Abel, Cesaro, Borel, Ramanujan, Zeta regularizations and how many of them do you assume well-defined for your series. So make your question precise. The first thing to know is that if an=O(nc)
  then ?Abel summationan=A well-defined implies F(s)=?ann-s extends analytically to R(s)>0 and lims?0+F(s)=A. math.stackexchange.com/questions/3328567/… @GottfriedHelms

I don't know whether the following would help you as well:

I've once considered a type of home-brewn matrix-summation-method using the matrix of Eulerian numbers. In the second part of my explorations I look at the cases, where my method cannot assign a finite value, but at most infinity and somehow a "finite residue" (or so).
Anyway, instead of getting the Euler-constant $\gamma_0$ for a regularization of the harmonic series as suggested by the Ramanujan-summation-method (or by computation for the second coefficient of the Laurent-series for $\zeta(1+x)$) the value $\log(2)$ pops up - and for the regularization of your series the "residual" value $2/27$ pops up - but I'm not qualified to put this in a reliable and correct context yet.  If you like to read then look at my homepage par. 3.3 and 3.4 Perhaps this gives a suggestion and hopefully you can help me to find the correct context.... . *(Surely I'll have to rewrite this, to clear up many messy statements and/or formulations - for instance instead of talking of zeta-series I should talk of polylog-series given my specific framework of matrix-summation - , but perhaps there is still something readable and/or worth for you.)*
Answer: Analytic continuation is a very fragile method of summation that often produces inconsistent results depending on what function we choose to continue.
But for this series all the mutually compatible summation methods give the same result.
Moreover, the number $-\frac1{12}$ is just the finite part of the full number. Using approach described here one can obtain the full form of the sum in terms of divergent sums/integrals:
$$\sum_{k=0}^\infty k = \frac{\tau^2}2-\frac1{24}$$
where $\tau=\int_0^\infty dx=\pi\delta(0)$.
Here you can see the full values of the sums of other divergent series (you would need a MathML-capable browser, such as Firefox, not Chrome or Edge): https://exnumbers.miraheze.org/wiki/Main_Page
UPDATE NOTE The approach mentioned in this article introduces umbral-type multiplication of divergent integrals and series. There are other possible definitions, that maybe simplier in certain respects.
Comment: What does "mutually compatible" mean in this context? And what about Daniel Fischer's example? It looks very convincing to me, but it seems to contradict what you wrote.
Comment: Link at the end of the answer is broken.
Comment: @hardmath oh, sorry. I will fix.
Comment: @celtschk As I said, analytic continuation can bring you just any possible result.
Comment: @user76284 thanks, fixed.
Comment: @hardmath hmm looks like i changed the first link rather the second one, will fix at the evening
Answer: The claim $\sum_{n=1}^{\infty} n = - \frac{1}{12}$ depends directly on the Riemann $\zeta$-function. In fact for any constant $c$ one can find a series $\sum a_n(s)$ of functions such that

on some subset of the complex plane the series converges and defines a function $f$ that is holomorphic on that subset
this function $f$ can be extended meromorphically to the entire complex plane
$a_n(-1)=n$
the meromorphic continuation of $f$ evaluated at $-1$ is exactly $c$.

If you use $a_n(s)=\frac{1}{n^{s}}$ you get the Riemann $\zeta$-function but that doesn't make $\sum_{n=1}^{\infty} n = - \frac{1}{12}$ any more correct than assigning any other value to this divergent sum.
Comment: It would have been nice if you had given any evidence for your claim. Like a reference, a plausibility argumentation, or a proof sketch.
Comment: @celtschk This is essentially what Daniel Fischer's answer does. But I just upvoted his answer, no reason to spell out the details a second time.

Is the “sum of all natural numbers” unique?