How to create a view filter which display nodes if "field1" - "field2" < $amount

Question: I have a content type with 2 fields: field1 and field2
I would like to create a view filter which display node based on a calculation on those two fields.
The filter should display only nodes if field1 - field2 is lower then a given amount.
Here is my try: At the end of the code, I don't know how to create the query
 class Myfilter extends FilterPluginBase implements ContainerFactoryPluginInterface {

  protected ViewsHandlerManager $joinHandler;

  private int $amount;

  public function __construct(array $configuration, $plugin_id, $plugin_definition, RouteMatchInterface $route_match, ViewsHandlerManager $join_handler) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->joinHandler = $join_handler;
    $this->amount = 0;
    if (($node = $route_match->getParameter('node')) && ($node->bundle()=='my_bundle')) {
      $this->amount = $node->get('field_inv_amount')->value;
    }

  }

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration, $plugin_id, $plugin_definition,
      $container->get('current_route_match'),
      $container->get('plugin.manager.views.join')
    );
  }

  public function query() {
    //parent::query();

    $fields = [
      'field1',
      'field2',
    ];
    foreach ($fields as $field) {
      $table_field_name = 'node__' . $field;
      $configuration = [
        'table' => $table_field_name,
        'field' => 'nid',
        'left_table' => 'node_field_data',
        'left_field' => 'nid',
        'operator' => '=',
      ];
      $join = $this->joinHandler->createInstance('standard', $configuration);
      $this->query->addRelationship($table_field_name, $join, 'node_field_data');
    }
    // I am stuck here... field1-field2 should be < $this->amount
    $this->query->addWhere( ???? );
  }

}

Any hint will be appreciated
Comment: As an alternative, you might consider leveraging https://www.drupal.org/project/computed_field, and filter on the computed field.
Comment: @beltouche thank you. I can also populate a normal field during node_presave, but as I have many cases like this one, I would prefer to understand how to create those kind of query. (I regular sql, it is easy, so I assume it can be done with the $query object)
Answer: You have a few errors:
The 'field' => 'nid', should be 'field' => 'entity_id',
 The $join =  line needs to use Drupal\views\Views::pluginManager('join')

You can using addWhereExpression, working example:
  public function query() {

    $fields = [
      'field_num1',
      'field_num2',
    ];

    foreach ($fields as $field) {
      $table_field_name = 'node__' . $field;
      $configuration = [
        'table' => $table_field_name,
        'field' => 'entity_id',
        'left_table' => 'node_field_data',
        'left_field' => 'nid',
        'operator' => '=',
      ];
      $join = $this->joinHandler->createInstance('standard', $configuration);
      $this->query->addRelationship($table_field_name, $join, 'node_field_data');
    }

    // Substracts and filters to less than amount.
    $this->query->addWhereExpression('AND', 'node__field_num1.field_num1_value - node__field_num2.field_num2_value <' . $this->amount);

  }

Comment: Many thanks!, it works like a charm! A small note: `$this->joinHandler` doesn't need to be replaced by `Drupal\views\Views::pluginManager('join')` because I used DI : `$container->get('plugin.manager.views.join')` is doing the same job.
Comment: Oh yes [Dependency Injection](https://www.drupal.org/docs/drupal-apis/services-and-dependency-injection/services-and-dependency-injection-in-drupal-8#s-injecting-dependencies-into-controllers-forms-and-blocks), somehow I overlooked that.


AtTask API Add Hours

Question: Is it possible to add Hours to a task via the API?
I was looking through the API documentation and even tried a couple tests agains the API itself. I keep getting back:
<code>{
    "data": {
        "ID": null,
        "objCode": "HOUR"
    }
}
</code>
Not a terribly helpful response.
We are currently using the API to integrate with our Git servers and we would also like to be able to include hours in our commit messages so that we can keep track of our hours without breaking our development flow. We are not so concerned about hours for specific users as much as we are about getting total development time that goes into a task.
Answer: Yes you can add hours through the AtTask API. It would look something like this using a URI.
<code>/attask/api/v4.0/hour?sessionID=****&projectID=4f9afa8d0005ff481ff120f4328b312e&hours=5
</code>
It appears you might be trying to create an hour without any "hours" defined. In AtTask when you enter an hour of 0 (or null / undefined) it will not insert an hour but rather remove any other hours attached to the same object.
Example:
You enter 5 hours for Project A
You then go back and edit the 5 to be 0 hours for Project A
While both of those are initiated as an Add or Edit operation it will remove the hour entries for Project A.
I hope this helps.
Comment: Is that a GET request? When I try what you described

`/attask/api/v4.0/hour?sessionID=*****&projectID=*****&hours=4`

I get

`{"error": {"class": "java.lang.UnsupportedOperationException", "message": "you must specify an action"}}`

With a 405 METHOD NOT ALLOWED status code.  I also tried the same thing as a PUT and POST request and both returned 411 LENGTH REQUIRED.
Comment: The example above was ran within a browser. If you are doing something similar you add method=post to the url and I believe that will fix your problem.
Answer: Here is what worked for me using C#
<code>[HttpGet]
public void AddHoursToProject()
{
    try
    {
        var postData = new Dictionary<string, string>();
        postData.Add("taskID", TestTask);
        postData.Add("hours", "6");

        var httpResponse = Post_HttpResponseMessage_FormUrlEncodedContent("v6.0/HOUR", postData);
    }
    catch (Exception ex)
    {

    }

private HttpResponseMessage Post_HttpResponseMessage_FormUrlEncodedContent(string taskToPerform, IEnumerable<KeyValuePair<string, string>> postData)
{
    HttpResponseMessage responseMessage;

    using (var apiManagementSystem = new HttpClient())
    {
        apiManagementSystem.BaseAddress = new Uri("https://xxx.preview.workfront.com/attask/api/");
        apiManagementSystem.DefaultRequestHeaders.Clear();

        var jsonMediaType = new MediaTypeWithQualityHeaderValue("application/json");
        apiManagementSystem.DefaultRequestHeaders.Accept.Add(jsonMediaType);
        apiManagementSystem.DefaultRequestHeaders.Add("SessionID", "xxxxxx");

        HttpContent httpContent = new FormUrlEncodedContent(postData);

        responseMessage = apiManagementSystem.PostAsync(taskToPerform, httpContent).Result;
    }
    return responseMessage;
}
</code>
Comment: This will add hours for the user that the session ID belongs to.  In order to add hours on the behalf of somebody else you will need an API key and the owner id of who the hours belong to (at least that is how I did it).
Here is the C# code.

                postData.Add("ownerID", OwnerID);
                postData.Add("apiKey", ApiKey);

AtTask API Add Hours


How to check Bootstrap 4's custom checkbox state?

Question: In their documentation here : http://getbootstrap.com/docs/4.0/components/forms/#checkboxes-and-radios-1
It's never mentioned how to properly use the custom checkboxes, using the inspector it doesn't seem like any class is added, and the value is always "on".
It's also not mentioned how do I change their state via html or javascript.
JsFiddle : https://jsfiddle.net/2n40w13k/1/
Js :
$('.custom-control-input').on('change', evt => {
    console.log(evt.target.value);
})

Comment: $(evt.target).prop('checked') ?
Comment: https://jsfiddle.net/2n40w13k/8/
Comment: "on" is the default value for checkboxes. you have to add a value to `` if you want to change this. this is vanilla oldschool HTML.
Comment: @ZimSystem You pointed him back to the link in his first paragraph...
Comment: I just thought it was confusing the phrase "We use the sibling selector to properly style our custom form indicator"
Comment: Functionally it's the same as any checkbox.. it's just styled differently using CSS pseudo selectors.
Comment: @Mojimi The reason that phrase is confusing is because the custom checkbox is NOT using the HTML input element at all. That element is *hidden* via css. So, what you are seeing only looks like a checkbox but it's not the actual HTML input for the checkbox.
Answer: Try this in your event handler:
$(evt.target).is(':checked')

Answer: That is done by using the :checked, :active and :focus pseudo-classes.
So, when you click a custom checkbox (or radio button), the :checked pseudo-class is applied to it. When you click it again, that pseudo-class is removed. And that's what you target with css to change appearance.
The same is true for JavaScript/jQuery. You'd need to add/remove the corresponding pseudo-class (:checked) via JavaScript/jQuery if you wanted to control it that way.
The last snippet of my answer here:
https://stackoverflow.com/a/48401949/8270343
explains it in further detail.
Comment: I don't understand how to apply your answer to javascript/jquery
Comment: You'd need to add the corresponding pseudo-class via JavaScript/jQuery if you wanted to control it that way.
Comment: just in case, angular 2+ example: https://stackoverflow.com/questions/40214655/angular-2-checkbox-two-way-data-binding


Computing cohomology over projective curve in $\mathbf{P}^3$

Question: Let be $k$ an algebraically closed field and Let be $X\subseteq \mathbf{P}^3:=\mathbf{P}_k^3$ a smooth, irreducible curve that is not contained in any hyperplane. Let's call $d=\deg(X)$.
A well known theorem of Gruson, Lazarsfeld and Peskine states that such a curve is $d-(3-1)+1=d-1$-regular, that is
$$H^p(\mathbf{P}^3,\mathscr{I}_X(d-1-p))=0$$
for all $p>0$. Now, some simple computations on this definition show us that this reduces to the following conditions:
$$H^1(\mathbf{P}^3,\mathscr{I}_X(d-2))=0,\,\,\,H^1(\mathbf{P}^3,\mathscr{O}_X(d-3))=0$$
Now the actual question. I would like to show that the theorem holds without using it, but I'm a bit struck. I need in particular the cases of a complete intersection curve and a rational curve of degree $3$.
For example, if you write $X=F_1\cap F_2$ as complete intersection of hypersurfaces $F_1,F_2$ of degree $d_1,d_2$ respectively, then the Koszul complex (aka Hilbert-Burch complex) resolves the ideal of $X$:
$$0\to \mathscr O_{\mathbf{P}^3}(-d_1-d_2)\to \mathscr O_{\mathbf{R}^3}(-d_1)\oplus \mathscr O_{\mathbf{R}^3}(-d_1)\to \mathscr{I}_X\to 0$$
Switching to cohomology sequence, this should imply $H^1(\mathbf{P}^3,\mathscr{I}_X(s))=0$ for all $s$; I'm not so sure this is completely correct.
As for the other condition, we may compute the canonical bundle $$\omega_X=\omega_{\mathbb{P}^3}(+d_1+d_2)=\omega_{\mathbb{P}^3}(d_1+d_2-4)$$ so when $s\geq d_1+d_2-3$ we have $H^1(\mathscr{O}_X(s))=0$ for sure. Then the inequality $d=d_1d_2\geq d_1+d_2-1$ shows the second condition.
Can somebody help me understand better these computations? How should I proceed to yeld a similar result in the case of a rational curve of degree $3$?
Answer: Your computation in the complete intersection case are correct, I just want to point out that you can work just with the Koszul complex, using the first definition of regularity.
When $X$ is the rational normal curve of degree $3$ we can proceed like this: we can look at $X$ as the embedding of $\mathbb{P}^1$ induced by the complete linear system $\left|\mathcal{O}_{\mathbb{P}^1}(3)\right|$, and then we have the identifications $H^i(\mathbb{P}^3,\mathcal{O}_{X}(d)) = H^i(\mathbb{P}^1,\mathcal{O}_{\mathbb{P}^1}(3d))$. In particular $$H^1(\mathbb{P}^3,\mathcal{O}_X(d-3)) = H^1(\mathbb{P}^3,\mathcal{O}_X) = H^1(\mathbb{P}^1,\mathcal{O}_{\mathbb{P}^1})=0$$.
For the other condition, consider the exact sequence of sheaves
$$ 0 \to \mathscr{I}_X(1) \to \mathcal{O}_{\mathbb{P}^3}(1) \to \mathcal{O}_X(1) \to 0 $$
taking cohomology we get the exact sequence
$$ H^0(\mathbb{P}^3,\mathcal{O}_{\mathbb{P}^3}(1)) \to H^0(\mathbb{P}^1,\mathcal{O}_{\mathbb{P}^1}(3)) \to H^1(\mathscr{I}_X(1)) \to 0 $$
however, the map $H^0(\mathbb{P}^3,\mathcal{O}_{\mathbb{P}^3}(1)) \to H^0(\mathbb{P}^1,\mathcal{O}_{\mathbb{P}^1}(3))$ is an isomorphism, since $X$ is the embedding of $\mathbb{P}^1$ by the complete linear system $\left| \mathcal{O}_{\mathbb{P}^1}(3) \right|$, so that $H^1(\mathscr{I}_X(1))=0$
Comment: Thank you, that's a very complete answer. I'm aware of the fact that the only Koszul complex give the answer I need without using the canonical bundle, I just wanted to see if I missed something. Among the other things, how do you get that $H^1(\mathscr{O}_X(d-3))=H^1(\mathscr{O}_X)$?
Comment: You're welcome! In the rational curve case, you have $d=3$ so that $\mathcal{O}_X(d-3)=\mathcal{O}_X$.
Comment: My my, what a silly question I made! Thank you again!


Jekyll URLs add leading slash when pushed to Github Pages

Question: I have successfully hosted on Github Pages. Today I was trying to run the site through browser-sync so I could view my changes faster, and noticed that my urls were different when served locally than on the actual website. Here's what the local url looks like:

Which when clicked on brings me to the page
http://localhost:3000/blog/blog/oven-baked-fajitas/

This same link, once it has been pushed to the Github repo and processed by them, turns into

Which works correctly.
I link to individual posts in my archive like this:

And my _config.yml is as follows:
name: Adam Hammes
description: Adam Hammes' Website
author: Adam Hammes
url: http://hammes.io
permalink: blog/:title/
excerpt_separator:
exclude: ["README.md", "gulpfile.js", "package.json", "node_modules"]

What I have tried:

I added baseurl: "" to my _config.yml; no effect.
I added baseurl: "/"; no effect.
I added baseurl: "/", and changed the link format to {{ site.baseurl }}{{ post.url}}; this fixed the links locally, but resulted in 2 leading slashes live thus breaking the links.
Answer: I was using an old version of Ruby. By updating to Ruby 2 and then running gem install Jekyll I was able to get consistent behavior.


Need someone to check my induction proof for errors

Question: I was told to solve the following recurrence relation/equation
$$T(n) = T(9n/10) + n$$
and after doing the algebra, I got the following solution
$$T(n) = 10[n - 1] $$
note: we are assuming that T(1) = $0$
(if you want to check the work i did to get the above, just check my previous post in my account)
Anyway, here is my induction proof...
BASE : $T(1) = 10[1 - 1]= 0 $
Hypothesis: Assume $T(k) = 10[k - 1]$
Induction steps: prove $T(10k/9) = 10[10k/9 - 1]$
1) $T(10k/9) = T(9n/10) + n$
I used the original recurrence equation and plugged in $10k/9$
2) $T(10k/9) = T(k) + 10k/9$
Now we plug in the hypothesis into our new equation
3) $T(10k/9) = 10[k−1] + 10k/9$
now we simplify..
4) $T(10k/9) = 10k− 10 + 10k/9$
5) $T(10k/9) = 100k/9 − 10 $
6) $T(10k/9) = 10[10k/9 - 1]$
Did I make any errors in my proof?
Any help will be appreciated
Comment: Why can you assume $n$ must be of the form $10k/9$? You write it must be of the form $n = a^k$ but not $10k/9$...
Comment: Uh... no.  You don't want to prove T(10k/9)=10[10k/9-1].  You want to prove T(k+1) = T(k). And pluggin 10k/9 into the original gives T(10k/9) = T(90k/90) + 10k/9.  Not T(9n/10) +n$.  I can't follow your reasoning at all.
Comment: $n = a^k$ was used in the process of getting the solution $T(n) = 10[n - 1] $ This rule only applies in getting the solution, but it is not supposed to be used in the induction process. I shouldn't have included that rule in this post.
Comment: For any constant $k$ the sequence given by $T(n)=10n+k$ satisfies that $T(n)=n+T\left(\frac{9}{10}n\right)$
Answer: Let $\quad T(x)=x+T(\alpha x)\quad$ with $\vert\alpha\vert<1$. Then
, using induction on $n$ you can show that:
$$T(x)=x+\alpha x+\cdots+\alpha^{n}x+T\left(\alpha^{n+1}x\right), \ \forall\,n\geq 1$$
$$T(x)=x(1+\alpha+\cdots+\alpha^{n})+T(\alpha^{n+1}x)
=x\frac{\ \ 1-\alpha^{n+1}}{1-\alpha}+T\left(\alpha^{n+1}x\right)$$
Suppose that $T$ is a continous function. Then taking the limit as $n$ tends to $\infty$, you get: (because $\vert\alpha\vert<1$)
$$T(x)=\frac{1}{1-\alpha}x+T(0).$$

The conclusion here is that the only continuous functions that satisfaies $T(x)=x+T(\alpha x)$ are of the form:
  $$T(x)=\frac{1}{1-\alpha}x+T(0)$$
  Here $T(0)$ is any constant you want.
In particular, if you take $\alpha=\frac{9}{10}$ and $T(0):=-10$. You get $$T(x)=10(x-1).$$

Observe that the assumption $T(1)=0$ is equivalent to $T(0)=-10$.


How to hide my website port number on website url

Question: My website has implemented by using JAVA. So we have taken VPS and installed Tomcat then deployed My website is appearing like this
whenever I click www.mysite.com in url ... it is appearing as below.
http://mysite.com:8080/foldername/
But I would like to see my website as www.mysite.com
Can any one suggest me what to do .. should I do any changes in htaccess file ?
Answer: You should change the port number to 80 in tomcat config. Port 80 is the only port which browsers hide because it's the default port.
Navigate to [your-tomcat-root]/conf/server.xml and then change
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>

to
<Connector connectionTimeout="20000" port="80" protocol="HTTP/1.1" redirectPort="8443"/>


Why do I get more tired when I play on stage?

Question: When I practice guitar on my own at home or with my band, I can play for ~1.5 to 2 hours without getting really tired. When I am on a stage and we play a gig, I get really tired on the first half hour.
I can continue to go on, but I'm really tired. Especially my fingers and left hand(fretting hand). Why does this happen?
Answer: This may be wrong in your case, but given the evidence in the question, it's likely to be stress and adrenalin.
When you practice in a relaxed environment, you play in a relaxed style. You don't tense your muscles. You don't fret any harder than necessary.
With performance nerves, and the buzz of being on stage, you tense your arm, you fret more stridently, and that is more tiring.
I don't know whether you're an experienced stage performer - but if you're new to it, you'll find that after a few performances, stage nervousness becomes less of an issue.
As soon as you find your head is clear enough on stage, make sure you're mindful of a relaxed technique. Make sure that if you tense your muscles more than in practice, you notice it and put a stop to it.
Also ensure that your practice and performance postures are the same. Don't practice sitting down if you'll be performing standing up, for example.
Comment: Excellent answer, kudos to you +1, I might add: prepare your body before going on stage with stretching, deep breaths, a good walk, anything that will get your body to relax.
Comment: In addition to everything you said, I'd also mention hydration before and during the gig. It makes difference.
Answer: And/or .. Dehydration ! This may not be the answer as it depends on your body, but something to pay attention to. ..
Do you sweat when performing, but not so much when practicing ? When you sweat you lose water (of course) and salt.
Half an hour is probably pretty quick for this to happen, but effects of dehydration and lack of salt are general feeling of fatigue, cramping/tiredness in muscles and sometimes you just think more slowly - kind of mental fatigue which can affect inventiveness and dexterity. I speak through experience !
So make sure you have enough salt (but don't overdo it!), and have a bottle/large glass of water avaiable. Sometimes after a couple of gulps, I can feel a difference immediately.
As regards to how much salt is "enough" : depends on your bod really. Try a packet of salted potato crisps or peanuts or something before you start.
Answer: Before reading slim's comprehensive  answer, I'd have said the same. Last point, extended - when you play seated, which is like most folks do, your arm angles (fret and pluck) are PROBABLY quite different from those when you're standing. If you wear your guitar low, as seems to be the current fashion, your fretting arm in particular, will be lower to reach the guitar neck than when seated. This then changes the wrist angle and fingers have to work harder. Harder work = tired quicker. Practise in the same way as you'd perform - or wear your guitar higher so the angle doesn't change sitting/standing. Or perform sitting down !
Comment: "seems to be the current fashion" -- The Beatles were "guitars high" and The Clash were "guitars low", but I can't immediately date the start of the current fashion between that ;-) Keith Richards' guitar position seems to have varied, maybe a series of pictures of him each year of the 1970s would pin it down!


Tabs are above my sherlock action bar

Question: I use ActionBarSherlock. Everything would be OK if my action bar were above the tabs.
<code>public class MyList extends SherlockListActivity implements ActionBar.TabListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.countries_list);

        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_TITLE);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        // Inflating tabs and views

    }

    // onTab methods
}
</code>
Answer: This is a bug in the framework that was only fixed in Android 4.2. ActionBarSherlock displays the same behavior as Android 4.0 for consistency. Even if it was fixed in ABS you'd still see this broken behavior on 4.0 and 4.1 in your apps.
Comment: I was misteken when writing my previous comments. I've compiled Android action bar and got the tabs above the action bar once.

Tabs are above my sherlock action bar


How Does Failover Clustering Work in Windows 2008 R2?

Question: I am trying to learn how the failover clustering features works with Windows 2008 R2 as I am going to be using as part of SQL Server 2012 always on.
I have been able to find information on how to set it up, and what it does. However, I am having trouble finding a nice technical document on how it actually works in detail (For example with keepalived there are docs that explain how often are heartbeat packets sent, what they look like etc).
I know this is a pretty broad question, but I would like to have a good understanding of mechanisms of this feature.
Comment: I have a rule about Microsoft services... Don't ask why things are the way they are or how they work... because you'll just go crazy trying to find the answer... I think maybe that applies here...
Comment: Magic! And unicorns, of course...
Answer: Being that it's a proprietary product I don't think you're going to binary-level analysis of the protocol or even flow diagrams, but I think you can glean some helpful information from:

The Design and Architecture of the Microsoft Cluster Service - This paper, co-authored by one of my CompSci heroes Jim Gray (RIP, Jim), published in the 1998 IEEE Proceedings of FTCS, describes the basic design of the Microsoft Cluster Server product as it was in Windows NT 4.0, which the later products all evolved from. There's even a flow diagram here, though it's probably wildly out of date with respect to the current generations of the product.
Network failure detection and recovery in a two-node Windows Server 2000 cluster - This article, while dated, does describe the low level details of the state machine used to determine network availability of nodes in a cluster.
[MS-CMRP]: Failover Cluster: Management API (ClusAPI) Protocol Specification - This document makes statements about how the product works internally thought its purpose is not specifically documenting the intra-cluster communication protocols and flows.
This functionality has gotten more configurable in later versions of the product. Searching for the name of the command-line management tool, cluster.exe, and the word "heartbeat" targeted against Microsoft's site seems to give a lot of potentially good results (one of the first hits I found has a paragraph containing the phrase "...here each node has an interface on each cluster network, there are N * (N - 1) unicast heartbeats sent per network every 1.2 seconds...", which sounds just like the kind of things you're looking for-- albeit describing Windows Server 2003.)

And, of course, if you want to see more of the low levels yourself set it up and throw a sniffer at it.


Convert Inline background image URLs to data-background

Question: Im trying to change inline background style images to data-background
This is an example output that im expecting to have

Converted to

but instead of falling into parent div, sometimes data-background falls into divs that are one or two levels above the parent div
Example

All the above div ids are made for just an example
The following is the PHP Code which im trying my best if there any alternative please suggest me Thanks
   function add_background_placeholders( $content ) {
    // Don't lazyload for feeds, previews, mobile
    if( is_feed() || is_preview() )
        return $content;
    // Don't lazy-load if the content has already been run through previously
    if ( false !== strpos( $content, 'data-background' ) )
        return $content;
    preg_match_all('~\bstyle=(\'|")(.*?)background(-image)?\s*:(.*?)\(\s*(\'|")?(?<image>.*?)\3?\s*\);?~i',$content,$matches);

    if( empty( $matches ) ) return $content;

    foreach( $matches[0] as $match ){
         preg_match('~\bbackground(-image)?\s*:(.*?)\(\s*(\'|")?(?<image>.*?)\3?\s*\);?~i',$match,$bg);
         $bg_less_match = str_replace( $bg[0], '', $match );
         $data_match = 'data-background="'.$bg['image'].'" '.$bg_less_match;
         $content = str_replace( array($match.';', $match), array( $data_match, $data_match), $content);
    }

  return $content;
}

Answer: use a dom php library, get the node, then get the background attribute. use regular expression to process the css to extract the url. then set the data-background attribute, then export the entire dom document out.
eg.http://php.net/manual/en/book.dom.php
theres a few dom php libraries out there


Como ordenar um combo select pelo texto das options?

Question: Desejo ordenar um combo select do HTML em ordem alfabética e gostaria de ajuda na lógica para conseguir montar uma função que faça isso independente do numero de elementos.
Answer: function NASort(a, b) {
    if (a.innerHTML == 'NA') {
        return 1;
    }
    else if (b.innerHTML == 'NA') {
        return -1;
    }
    return (a.innerHTML > b.innerHTML) ? 1 : -1;
};

$('select option').sort(NASort).appendTo('select');

<select>
    <option value="1">Car</option>
    <option value="2">Bus</option>
    <option value="3">NA</option>
    <option value="4">Bike</option>
    <option value="5">Tractor</option>
    <option value="6">NA</option>
    <option value="7">A</option>
</select>

JSFiddle
Fonte
Answer: Pode usar o Array.prototype.sort():

function ordenar() {
    var itensOrdenados = $('#itens option').sort(function (a, b) {
        return a.text < b.text ? -1 : 1;
    });

    $('#itens').html(itensOrdenados);
}

<select id="itens">
    <option value="2">Maçã</option>
    <option value="1">Banana</option>
    <option value="3">Laranja</option>
    <option value="8">Uva</option>
    <option value="5">Amora</option>
    <option value="15">Melão</option>
</select>
<button onclick="ordenar()">Ordenar</button>
Comment: Olá, obrigado pela resposta, apesar do tópico ser antigo, me ajudou muito! Só uma coisa: nesse exemplo, o valor que aparece pro usuário após a ordenação, é o último da lista ("Uva", no caso). Como fazer pra o valor a aparecer após a ordenação ser o primeiro ("Amora", no caso)?
Comment: Basta inverter o valor de retorno da função `sort` : `return a.text < b.text ? 1 : -1;`.


Renaming a webform handler - old class stuck in DB despite clearing cache

Question: I'm creating a custom webform handler plugin based on the advice here, adding the class, in the correct directory, to an existing module.
I got the class name / some of the docblock info wrong initially - and need to change it.  Having run drush cr, the listing on  /admin/structure/webform/config/handlers seems to be stuck on the old entry.
I get "Cannot declare class ... because the name is already in use" errors when trying to add the handler to the form, for a class name that I'm no longer using, and which, having cleared the cache, definitely isn't in  cache_discovery.webform_handler_plugins in the DB.
I've also swapped browsers.
What am I missing?
Comment: Have you tried restarting PHP or the server? This happens to me in local dev sometimes and rebooting the VM seems to work.
Comment: @Kevin ah thanks - restarting the docker container (devwithlando/php:7.1-fpm) worked.
Answer: Sometimes, especially with a local dev environment, after you have tried every other route the only other avenue is to restart the PHP service and/or reboot the server/VM. This should clear system caches and often times will resolve this issue.


How to solve "Mismatched entity and/or field definitions", specifically, "The URL alias field needs to be installed"?

Question: After migrating from 7.89 to 9.3.12 this warning appears:
ENTITY/FIELD DEFINITIONS Mismatched entity and/or field definitions
The following changes were detected in the entity type and field definitions.
File
The URL alias field needs to be installed.
How do I solve this?
Comment: Note: Also asked at https://www.drupal.org/project/drupal/issues/3279976, which I closed because this is actually a better place for support.
Comment: Please post complete steps to reproduce this situation.
Comment: go into new site and the error above is listed in Configuration.....the links to audio files which worked fine in 7.89 are not populated in 9.3.12....you can usually click on the link and it plays the audio file.....
Comment: That is not steps to reproduce.
Comment: It came up after the upgrade....no way to reproduce it short of doing another upgrade....
Answer: This issue can only happen if you have two modules installed at the same time. Pathauto and File Entity. It is rare that you need File Entity in Drupal 9 because we have now Media entities. You are probably still using it because you've used it in Drupal 7. But it is very rare that you need the field "URL alias" in the File entity. See https://www.drupal.org/project/file_entity/issues/2655844#comment-14212446
So try out this patch to remove this field:
https://www.drupal.org/project/file_entity/issues/2655844#comment-14213753


vbCrLf in Multiline TextBox shows up only when .Trim() is called

Question: I have an ASP TextBox with TextMode set to MultiLine. I'm having problems with preserving the vbCrLf characters when a user tries to put line breaks into the text. When a button on the page is pressed, I'm taking the text from the control, trimming it using String.Trim, and assigning that value to a String property on an object (which, in turn assigns it to a private internal String variable on the object). The object then takes the value from the private internal variable and throws it into the database using a stored procedure call (the SP parameter it is put into is an nvarchar(4000)).
ASPX Page:
<asp:UpdatePanel ID="UpdatePanel2" runat="server" RenderMode="Inline" UpdateMode="Conditional"
                ChildrenAsTriggers="true">
  <ContentTemplate>

    <asp:TextBox TextMode="MultiLine" runat="server" ID="txtComments" Width="100%" Height="60px" CssClass="TDTextArea" Style="border: 0px;" MaxLength="2000" />

  </ContentTemplate>
</asp:UpdatePanel>

code behind:
ProjectRequest.StatusComments = txtComments.Text.Trim

object property:
Protected mStatusComments As String = String.Empty
Property StatusComments() As String
  Get
    Return mStatusComments.Trim
  End Get
  Set(ByVal Value As String)
    mStatusComments = Value
  End Set
End Property

stored proc call:
  Common.RunSP(mDBConnStr, "ProjectStatusUpdate", _
    Common.MP("@UID", SqlDbType.NVarChar, 40, mUID), _
    Common.MP("@ProjID", SqlDbType.VarChar, 40, mID), _
    Common.MP("@StatusID", SqlDbType.Int, 8, mStatusID), _
    Common.MP("@Comments", SqlDbType.NVarChar, 4000, mStatusComments), _
    Common.MP("@PCTComp", SqlDbType.Int, 4, 0), _
    Common.MP("@Type", Common.TDSqlDbType.TinyInt, 1, EntryType))

Here's the strangest part. When I debug the code, if I type
"test
test"
(without the quotes) into the comments text box, then click the save button and use the immediate window to view the variable values as I step through, here is what I get:
?txtComments.Text
"test test"
?txtComments.Text.Trim
"test
test"
?txtComments.Text(4)
"
"c
?txtComments.Text.Trim()(4)
"
"c

Anyone have a clue as to what's going on here?
Comment: are you having a problem or just wondering what's going on?
Comment: I checked it but i got "test test" in both cases
Answer: There are two problems at bay here. First, the immediate window in VB is converting the non-printable character to a space so you cannot see it. In C#, it will show the character using its replacement escape code (e.g. \n or \r\n), but VB does not. Second, VB sees the break as a line-feed only (vbLf) not a carriage-return+line-feed (vbCrLf). Thus, if you do the following in break mode in the immediate window you will see what I mean (assuming you type test, hit Enter, test in the comments box):
?txtComments.Text.Substring(4,1) = vbLf
True

Answer: May be, you should use Environment.NewLine constant to get replaced with the vbCrLf


How can I set a message if db_delete deleted one or more rows

Question: In drupal 6 my code worked like this:
if (db_query("DELETE FROM {,ymodule_fields} WHERE conid = %d", $conid)) {
  drupal_set_message(t("Deleted fields."));
}

Now I'm supposed to use db_delete.
Will this code work?  I know db_delete returns a DeleteQuery object so I'm assuming it's going to evaluate to true every time.  I can't test my module yet because I'm doing a lot of work updating the code that creates cck fields to use core fields.  Is DeleteQuery a PDO that has the rowCount method?
if (db_delete('mymodule_fields')
  ->condition('conid', $conid)
  ->execute()) {
  drupal_set_message(t("Deleted Fields."));
}

Answer: Sure, db_delete() returns an object so you can continue working with the object, but the last method called (the method whose return value your conditional is really checking) in your statement is Query::execute, which returns boolean TRUE or FALSE indicating whether the query worked. So, ultimately the whole statement:
db_delete('drealty_fields')
  ->condition('conid', $conid)
  ->execute();

Should return TRUE or FALSE since you're ultimately executing the Query::execute method. The workflow is just that you call db_delete(), which returns an object, Query::condition, returns an object, then Query::execute returns boolean, but your conditional is just getting and checking the return value of the last method called - execute - rather than the return value of db_delete(). Essentially, the db_delete() return value was already operated on by continuing with a condition, and the condition's return value is inconsequential because it was operated on by execute, thus the execute's return value is the only one really getting sent back to the if statement. Make sense?
So, in essence each of these examples should give the same results:
$query = db_delete('drealty_fields');
$query->condition('conid', $conid);
$success = $query->execute();
if ($success) {
  // Do something.
}

$query = db_delete('drealty_fields');
$query->condition('conid', $conid);
if ($query->execute()) {
  // Do something.
}

if (db_delete('drealty_field's)->condition('conid', $conid)->execute()) {
  // Do something.
}


WPF strategies to avoid graphics card sensitivities?

Question: This is essentially a re-state of a question I asked yesterday because the one answer I got didn't appear to understand my question so I must have been unclear.  My bad.
Because WPF relies on DirectX it's very sensitive to internals of cards and drivers. I have a case where some simple WPF programs render incorrectly on one modern, brand-new PC with a major brand high-performance graphics card and current drivers.   The problems go away if I disable the graphics card (so it uses the integrated grahics).   So I know it's the card or drivers.   These programs render fine on several other older PC's I've tried them on.
As WPF programmers are there deployment strategies or programming strategies we can use to minimize the risks and exposures to stuff like this?  If we can't count on WPF rendering properly on major brands of PC's and graphics cards what can we do?    How common are issues like this with WPF?
Original post:  WPF graphics card problem
Answer: If you are having hardware-dependent rendering issues, you can work around it by forcing software rendering. (In my experience, this has almost never been necessary; in most cases of video glitches, ensuring that customers have the latest drivers has solved the problem. As a WPF developer, I don't worry about this problem.)
If you're using WPF 4, use RenderOptions.ProcessRenderMode to force software rendering for the current process.
In WPF 3.5, your only option is to disable hardware rendering for all WPF applications on by editing the registry. Create/open the HKEY_CURRENT_USER\SOFTWARE\Microsoft\Avalon.Graphics key and create a DWORD value DisableHWAcceleration with the value 0x1.
For more details, see Software Rendering Usage in WPF.
Comment: Thank you - this is exactly the sort of information I'm looking for!  .... with regard to ensuring customers have current drivers, are most WPF apps written for target users where the developer has any input into that, e.g., in-house corporate user-bases?   I write scheduling sw for musicians - ordinary users with random ordinary PC's.   Is WPF a bad choice for that?
Comment: @Peter: The WPF application I primarily work on (Logos Bible Software) is mainly deployed to pastors and other "ordinary" users. They tend to run older systems that have integrated graphics or low-end DX10 cards (i.e., not gamer rigs). In our experience, the benefits of WPF (graphically rich, easy to develop & style UI, data binding, animations, etc.) far outweigh the cost of tech support occasionally needing to walk a non-tech-savvy user through a driver upgrade.
Comment: @Peter: WPF does have more compatibility issues (e.g., http://code.logos.com/blog/2009/11/how_to_crash_every_wpf_application.html) -- you will almost certainly have more users who just can't get your software to work at all by using WPF (over WinForms), but I think you'll make the majority of your users happier by being able to deliver a better UI with WPF.


Using different rate than the default 1/second in iptables

Question: This code does its job perfectly in limiting syn connections but in line 4 instead of 1/s i need it to be 1/5 seconds, it's an assignment i'm working on that needs to protect against syn-flood attacks
iptables -N syn_flood
iptables -A INPUT -p tcp --syn -j syn_flood
iptables -A syn_flood -m limit --limit 1/s --limit-burst 3 -j RETURN
iptables -A syn_flood -j DROP

Comment: 1 connection for 5s => 12 connections for 1 minute : --limit 12/min
Answer: If you honestly believe that 1 syn per second is "too-much"... you've got some serious server issues.  That being said, The minimum limit for limit is 1 second.  Without rewriting that module, you're not going to be able to do less than 1 packet per sec.
Honestly, If you're trying to get 1 packet per 1/5 second... why not simply specify 5/s?  (5 packets per second)  that is pretty much the same thing.
If you're simply trying to limit connections per-host, try using connlimit instead of limit... or perhaps hitcount to limit per-ip connections.
Comment: honestly it's an assignment i'm working on and this is the requirement that's why it's 1/5 seconds. could you help me out with the code to use hitcount or connlimit?
Comment: As this is a very complicated topic, and require a lot of discussion, this isn't really the place to do that.  Also, I am not a fan of doing other people's homework.


onBeginContact not dispatched

Question: I have refactored my code in order to use states and classes. The code is cleaner but the callback associated to the onBeginContact is not called anymore. Without classes, it was working as expected.
In Boot.js:
this.game.physics.startSystem(Phaser.Physics.P2JS);

In Game.js:
this.ship = this.game.add.sprite(200, 200, 'ship');
this.ship.animations.add('propulse', [1, 2, 3]);
this.game.physics.p2.enable(this.ship, false);
this.ship.body.addPolygon({}, 30, 35  ,  0, 35  ,  14, 5);
this.ship.body.onBeginContact.add(this.hitWall, this);

hitWall is not called. I have tried using a simple function but same issue. If you need more information, please ask.
Answer: The line:
this.game.physics.startSystem(Phaser.Physics.P2JS);

Should be in Game.js too.
Comment: More specifically, the physics system is destroyed whenever game state changes. That is why the physics system needs to be restarted and configured accordingly.

onBeginContact not dispatched


How do I get Microsoft.OData.Client to Associate tables on update?

Question: I have tested this request (to Microsoft Dynamics 365 CRM) in postman and it works correctly:
POST request to https://example.com/api/data/v9.2/foo_module?$select=foo_moduleid

Headers include:
Prefer:return=representation

Body
{
    email@example.com : "/accounts(b770a30d-55d9-e211-89ad-005056ae0100)",
    "foo_name": "Module Name"
}

I have no idea how to get the Microsoft.OData.Client to generate this request.
Updating the record would look like the following, and this does work as I can use the primary key
var moduleQuery = from x in context.foo_modules
                    where x.foo_moduleid == record.CrmId
                    select x;

module = new DataServiceCollection<Foo_module>(moduleQuery).Single();
module.Foo_name = $"Example Online Module (from c# at {DateTime.Now})";

var response = context.SaveChanges(SaveChangesOptions.PostOnlySetProperties);

Summary
How do I get the email@example.com : "/accounts(b770a30d-55d9-e211-89ad-005056ae0100)" property in the body when using Microsoft.OData.Client?
Comment: A query to the database must match the database language.  The resutls of the database query need to be put into you class Foo_module so your controller will work with the database.  So the server code queries the database and creates a Foo_module that is send in a Post.  Then client will get the response in proper format.
Comment: I am writing the client only, the server is Micosoft Dynamics 365, I'll add that tag
Answer: The solution was to query the associated record (account) and assign it to the appropriate property.
Here's the code:
var context = _dynamicsContextFactory.CreateContext();

var accountQuery = context.Accounts.Where(x =>
                    x.Primarycontactid.Lastname == lastname
                    && x.Accountnumber == number
                );
var account = new DataServiceCollection<Account>(accountQuery).Single();
var collection = new DataServiceCollection<Foo_module>(context);
var module = new Foo_module();
module.Foo_AccountId = account; // <--- this is the important line
collection.Add(module);
module.Foo_name = $"Example Online Module (from c# at {DateTime.Now})";
var response = context.SaveChanges(SaveChangesOptions.PostOnlySetProperties);


Interconnect a Kubernetes cluster with a Docker network

Question: I am trying to enable communication between Kubernetes (K8s) pods and a Docker container but I cannot find how to do so on Windows. Help would be greatly appreciated.
Scenario description:
The n K8s pods are composed of one (and only) container: a Go microservice accessed by Postman at this time, itself supposed to access a database.
To enable a load-balanced access to the pods as one, a Kubernetes service is put on top, using a NodePort. So far everything is working.
But the K8s-Pod/Go-microservice <> Docker-container/db part do not see each other. The Go microservice obviously says the "db" cannot be resolved. The container db is itself in a user-defined docker network (called "mynw"); its type is a bridge.
Would anyone know how to acheive this in the simplest way? (I mean without third-party/tierce things, heavy proxy configuration, etc.)
Thanks!
Answer: You can create a headless service in k8s, with an endpoint pointing to your database container. Then you have to direct your Go service to use that headless service as the db connection.
Comment: Your suggestion was the clue to the success. Many thanks!
Comment: To share with others a more detailed explanation on how to do it:
1. Deploy your K8s microservice
2. Expose it with a K8s Service
3. Build a Service said Headless because it does not refer to any pods ; it has the particularity to be `spec.type: ClusterIP` and to have `spec.clusterIP: None` so no IP address out of the box ; mind the ports
4. Build an Endpoint with ip address and port of the docker container.

To get this IP, do a `docker container inspect` on your database container.
And voilà!
Answer: On top of headless services mentioned by bserdar, you can also use services of type externalName if your database has a proper DNS name.
Comment: It has not but thanks for the suggestion. I'll have a look for my personal knowledge! Thanks.


My core Comment module is gone

Question: Recently I lost comments and everything related. In the module list I see "Comment (missing)". All I did before:

CK editor update
Installed the Better Formats module.

Manual updating the core from 7.27 to 7.28 didn't help. All comment module files are in the folder they suppose to be (modules/comment/). But Drupal doesn't see the module.
Any help would be appreciated.
Comment: 1) Roll back the last backup you did prior to the changes you mention.  2) Disable Better Formats.
Comment: Thnks for the responds. Unfrtntly I can not roll back... I can but it's the lastest thing I want to do because of my own stupidness (I didn't make any backup just before those changes. the closest backup is almost 1 working day). my fault I know.
Comment: Better Formats is already even uninstalled. No changes.
Answer: If the comment module files are there in /modules/comment but not displayed in Admin > Modules it suggests the folder isn't readable by the webserver user.
Check the permissions are correct on the /modules/comment folder to allow read access.
For example:
# Run from Drupal root
# Comment module folder ensure readable
chmod 755 modules/comment
# Recursive chmod on files to ensure readable
find modules/comment -type f -exec chmod 644 {} \;

Comment: @marcvangend yes, but the problem with `chmod -R 755` is it will change all _file_ permissions to 755 also. Normally 644 is more appropriate for files, with folders at 755. The `find` command with `-type f` will match files only `-type d` will match directories only.
Comment: You can also do a recursive chmod using the -R option. My personal favorite is `chmod -Rvc 755 some/directory`. It will do a chmod on the directory and everything below it and will tell you which files were changed.
Comment: @DavidThomas, Just checked: modules/comment has 755 rights :-(
Comment: @Andrey check permissions on files inside that folder also.
Comment: @DavidThomas I did. The are 644
Comment: Ok, must be something else going on there specific to your site configuration.
Answer: If you're unable to rollback your site to the state it was just prior to the last install/update, and its not a permissions problem, my suggestion is to migrate the content into a fresh install.
First check that the comments are not missing from the database: Use phpMyAdmin or another database examination tool to check the table comment still exists and has usable content). I'll be very surprised if it is gone if you have not actively un-installed the comment module.
Provided comments still are present, do the following:

Disable any module you don't need.  Disabling a module will not make you lose any data.
Uninstall any module that you don't absolutely need.  Un-installing  will often cause data loss, so carefully review your options here.
After  doing the above, make a full backup of your site using the Backup and Migrate module.
Do a fresh install of the latest version Drupal core on a staging server.
Roll back the backup created in step 3 above into the fresh install on the staging server (do not touch your production server at this point).
Check that the core Comment module is present, enabled, and that comments appear as they're supposed to.
Carefully re-enable all the other modules on you want to use, one by one. Make sure you do this on the staging server.  After each install and configuration, check carefully that all is still fine.  Hopefully, this should not cause any breakage, and it should give you a healthy site at the end of the task.  If one install breaks something, you at least knows the cause, and can redo the procedure from step 4, skipping the install that causes the problem.
After you've restored your site to full health on a staging server, take a full backup of that, and then repeat the successful procedure on the production server.

Hope this helps.
Comment: Thx. Sure that's the way I was thinking about. Hope to find an easier way before perform that one.  Anyway comments are still in the db, and I definitely did not un-install Comment module by my own. Maybe there is any  way to manually re-install that module?
Answer: Solved.
The problem was in the traces of my old experiments: there was a folder sites/all/modules/my_comments with almost empty comment.module file inside. I have no idea why didn't that thing come up earlier (I was playing with 'module customization' a while ago and cache has been cleared many times) but now my comments are back.
Thanks everybody who where trying to help. And my apologies for my English.

My core Comment module is gone


Is this correct

Question: Over the post few weeks there have been several "Is this correct?" questions.
It seems like this is a weird fit for SE, but on the general meta (based on Stackoverflow context) they seem to encourage such questions. So even though such questions will tipically not get an affirmative answer ("Yes." is only 4 characters) such questions are on-topic.
(I think there is also some reluctance to close due to the OP having demonstrated effort.)
Is what I wrote above correct?
Answer: Yes.
To cover the required answer-length threshold, confirmation is a useful tool in the educational process. The issue is "does it add valuable content to the site?"
If the answer is "No", providing guidance towards the "Yes" conforms with the purpose of the site, and also, stays there for future wanderers.
If the answer is "Yes", an extra burden is placed on those who answer to make the thread valuable -for example by indicating any redundant steps the OP took, or suggest an alternative way, or show how it is a special case of some more general methodology.
Comment: I was trying to decide what kind of answer to write, but let me instead say that I think Alecos' answer captures my sentiment pretty well.

Is this correct


With a small sample from a normal distribution, do you simulate using a t distribution?

Question: I want to simulate temperature data for some "what-if" calculations.  The problem is, I only have a time series of 10 actual temperature data values.  I want to use temperature as an input to the simulation, so I need a way to generate a large number of temperature values that are consistent with the original 10 values.   It's probably ok to assume that they came from a normal distribution, but I don't know the mean or the variance.
I have no way to prove it, but I doubt the 10 values do a good job of representing the full temperature range.   If I use the sample function for the simulation, as shown below, I only get the original values back.   That just doesn't look right.   If I use the rnorm function, I know that I don't know the variance, so I don't think that is right either.    So, I'm left with the rt function (t-distribution).
Below is a mock up of the problem.
ori <- rnorm(n=10, mean=65, sd=5) #original 10 data points

num.sam <- sample(x=ori, size=100, replace = TRUE) #simulation using sample
num.tdis <- mean(ori) + (rt(n=100, df=10) * sd(ori)) #simulation using a t distribution

hist(ori, breaks=40:90)
hist(num.sam, breaks=40:90)
hist(num.tdis, breaks=40:90)

My questions are,

When I only have data (mean and variance unknown), and it is reasonable to assume that the data came from a normal distribution, is it ok to generate data for a simulation using a t-distribution?
For this type of situation, the only time I would use rnorm for the simulation is if I knew the variance (not a variance estimated from the data), right?
If a t-distribution simulation is ok for these conditions, are there any conditions where it is better to just sample the data (for example 100 original data points, 200, etc)?

Edit:

Since I used the original data to estimate the mean and variance, should the degrees of freedom in the third line of the code (for rt(...)) be reduced from 10 to 9?   Or 8?
Comment: What's the purpose of the simulation?
Comment: I'll use the simulated temperature as an input to feed other calculations, so I can estimate a spread for the final forecast.  I have a related issue about a moving temperature mean and possibly a moving variance, that I'll ask as another question, but this is a simplified version of the main issue.
Comment: I still don't understand what you want to do, but maybe you could use simulations to compare what happens if you simulate using a t distribution compared with using a normal distribution.
Comment: I'm simply trying to generate a large number of temperature values that are consistent with the original 10 value sample. The reason that I assembled the above mock-up code was to compare the generated `rt()` values (not shown, but I also looked at `rnorm()` values) with the `ori` values. In the above mock-up, I actually know the mean and variance of `ori`. The problem was/is, nothing stood out as the "right" way to simulate the data. That's why I'm asking if someone can explain what is the "right" way and why. I may be wrong in assuming this is a common question.
Answer: You could generate a vector of means from a normal distribution (or t if you prefer) representing your uncertainty in the mean, then generate a vector of variances from a $\chi^2$ distribution representing your uncertainty in the variance, then generate the actual observations from a normal with your vector of means and the vector of variances as the parameters.  This will take into account the extra levels of uncertainty that you mention.
If you have some feel for where you think the mean and/or variance should be (but don't know exactly) then you may want to try a Bayesian approach where you can use that prior information.
Comment: I tried your method, but the spread was bigger than my method above, and I wasn't real sure that I did it right.  I generated random sigmas using the following code `sigma <- sqrt((datpoi - 1) * (sd(ori)^2)/rchisq(n=newdatpoi, df=datpoi-1))` where `datpoi` is the number of original data points (in my example, datpoi=10).  And, `newdatpoi` is the number of random values wanted (in my example, newdatpoi=100). Those `sigmas` and some random means (centered around `mean(ori)` ) were fed into `rnorm()` to generate the new data points.  As far as the Bayes approach goes, that's out of my league.
Answer: Using your assumptions that the points came from a normal distribution with unknown mean and variance, The T distribution is the correct distribution to sample from no matter how many data points you have because it is the posterior predictive distribution of your model.  You might want to check your formula though as it looks a bit simpler than what I've seen before.
To answer your questions, (1) yes, (2) yes, and (3) no.
Comment: I tested/re-tested/tested-again the formula (line 3, where `rt()` is used) and I'm not sure what the problem is.  Can you be more specific?   Are you talking about a different line in the code?   I've been digging around on the net, and apparently simulating with a t-distribution is not as common as I originally expected.
Comment: [See here for example](http://www.cs.ubc.ca/~murphyk/Teaching/CS340-Fall07/reading/NG.pdf) and note the posterior predictive distribution.  You are not "simulating", but rather precisely following your Gaussian modelling assumption.  There's a nice derivation [here](http://www.cs.ubc.ca/~murphyk/Papers/bayesGauss.pdf).
Answer: I would elaborate Neil G and Greg Snow's answers as follows :

run a noninformative Bayesian inference for your original $10$ data values
use the posterior predictive distribution to generate new data

The posterior predictive distribution derived from a noninformative prior exactly aims to provide your desire: a distribution that generates data "consistent with the original data", taking into account the uncertainty about the model parameters.
Now, what is the posterior predictive distribution derived from the noninformative prior ? That depends on the choice of the noninformative prior, but there is a good "default" noninformative prior for the normal sample model. You can also "cheat" a little and use the "Bayesian-frequentist" predictive distribution (also called sometimes "the frequentist predictive distribution"). The principle of the frequentist predictive distribution is the following one. The classical $100(1-\alpha)\%$-prediction interval for a new observation is $\bar{y} \pm \mathrm{t}^*_{n-1}(\alpha/2) \hat\sigma\sqrt{1+\frac{1}{n}}$. Then the Bayesian-frequentist predictive distribution is taken to be the distribution of $\bar{y} + T  \hat\sigma\sqrt{1+\frac{1}{n}}$ where $\bar{y}$ and $\hat\sigma$ are considered as fixed and $T$ has the Student $\mathrm{t}_{n-1}$ distribution. Thus, the $100(1-\alpha)\%$-quantile of the frequentist predictive distribution equals the usual $100(1-\alpha)\%$-upper prediction bound.
I do not exactly remember the Bayesian predictive distribution derived from the default noninformative prior but it is very close to the frequentist predictive distribution (there are some slight differences such as $\mathrm{t}^*_{n-\frac{1}{2}}$ instead of $\mathrm{t}^*_{n-1}$). I will update my answer when I will find the formulas.
Here I asked a question related to the performance of these predictive distributions.
I claimed that the frequentist predictive distribution is derived from "little cheating" because it does not really has a theoretical fundation. But I'm sure it is possible to show the performance of the use of this distribution in a frequentist sense.


A discrete time random walk in $\mathbb{R}^n$.

Question: Consider a random walk where at $t=0$ you start at the origin of $\mathbb{R}^n$, and at each time $t\in \mathbb{N}$ you randomly move to a point that's within a ball of radius $1$ from your current location (each point being chosen uniformly at random).
There's a lot of questions one could ask about this, but my main question is: at time $t=2$, what is the probability that you're once again within distance $1$ from the origin?
Comment: I have done this simulation : the result is close to 0.777.
Comment: Yes, I attempted at once large values $n = 10^6$, several times, displying a good stability of the result. This as been made easy by using a first simplification of the problem. I write it below as an answer, because I think this is an advance into solving the problem but still far from solving it.
Comment: There has been changes in my answer. Have a look.
Comment: I managed to reduce the problem to evaluating a certain integral (which I've edited into my original post).  A simulation is a good idea, I might try and code that up either tonight or tomorrow.
Comment: Thanks for doing that!  For reference, did you choose a specific $n$ or did you try it for several and that's what it seemed to converge to as $n$ grew larger?
Comment: @Shashi That's it.
Answer: We can assume WLOG, due to the circular symmetry of the issue, that if $O$ is the center of the disk, the first line segment  $OM_1$, is along the real positive $x$ axis with length $OM_1=R_1$.
Let us call $M_2$ the second point, $R_2$ the distance $M_1M_2$. Let $\theta$ be the polar angle of $M_1M_2$ with respect to the $x$ axis, i.e. such that $\vec{M_1M_2}=\binom{R_2 \cos(\theta)}{R_2 \sin(\theta)}$ .
Cosine law applied to triangle $OM_1M_2$ gives:
$$\text{squared distance} \ (OM_2)^2=R_1^2+R_2^2+2 R_1R_2 \cos(\theta)$$
(with a plus sign in front of the last term because we have to consider angle $\pi-\theta$.)
The issue is now to compute the probability of event :
$$\tag{1}R_1^2+R_2^2+2 R_1R_2 \cos(\theta) < 1.$$
with random variables $R_1, R_2$ uniform on [0,1] and $\theta$ uniform on $[0,2 \pi]$ (in fact $[0,\pi]$ would be enough).
I thought at first that an equivalent problem is as follows : find the pdf $f$ of the random variable "distance of two random points in the unit disk". Then the result is  $\int_0^1 f(\rho)d\rho$ with
$$\tag{2}f(\rho)=\tfrac{4}{\pi}\rho\left(cos^{-1}(\tfrac{\rho}{2})-\tfrac{\rho}{2}\sqrt{1-(\tfrac{\rho}{2})^2}\right) \ \ \ $$
(see Appendix 2 for explanations).
But this is not the case : (2) corresponds to the case of a uniform distribution on the disk, i.e., with a pdf having a top hat shape.
But here, the pdf is :
$$\tag{3}\varphi(r)=\tfrac{1}{2 \pi}\tfrac{1}{r}$$
which has the shape of a kind of  chinese hat shape with an infinite spike at its center (see Appendix 1 for explanations)
The vector sum $\vec{OM_1}+\vec{M_1M_2}$ gives a convolution $f$ of two "chinese hat" distributions. This convolution also has, in a natural manner,  a rotational symmetry, meaning that it can be expressed under the following form:
$$f(r,\theta)=K\psi(r)$$ for a certain normalizing constant $K$, independently of $\theta.$
It remains to find $f$ as the convolution of $\varphi(r)$ with itself.
The last step will be the computation of:
$$\tag{3}\int_{r=0}^1 \int_{\theta=0}^{2 \pi}f(r)\color{red}{r} dr d\theta$$ where $\color{red}{r}$ is the classical jacobian for polar coordinates.
Remark 1 : I have done an extensive simulation using (1). It gives a probability close to $0.777$.
Remark 2 : there is a connection with Radon Transform ; let us recall that this transform amounts to a convolution $f \to f*1/r$ with kernel $1/r$. Thus what we are looking for is the kernel equivalent to applying twice the Radon transform.
Appendix 1: proof of formula (3).
Recall that we deal with points $P$ that are distributed in the unit disk with a uniform distribution for their distance to origin $R=OP$ and a uniform distribution for their polar angle.
Consider the elementary annulus defined by $r_0<r<r_0+dr$ ; its area is $\pi(r_0+dr)^2-\pi(r_0)^2=2 \pi r_0$ (term $dr^2$ has been dropped); the probability that a point is in this annulus is the volume $2 \pi r_0 \varphi(r_0)$ of the corresponding  elementary cylinder under the surface defined by the density. But this quantity must be a constant $K$ independent of position $r_0$. As a consequence $\varphi(r_0)=\tfrac{K}{r_0}$. The fact that $K=\tfrac{1}{2 \pi}$ is due to the normalizing condition $\int_{\theta=0}^{2 \pi} \int_{r=0}^{r=1} \varphi(r)rdrd\theta = 1$.
Appendix 2: References for formula (2) (let us recall that we don't use it here): through the following link (https://math.stackexchange.com/q/934688), I had the indication of a very interesting book by A.M. Mathai "An introduction to geometrical probability" (formula (2.3.63) p.205) ; this book is downloadable (see the last comment). In a non-expected way, (2) is the same as formula that is used in confocal laser technology (see (ftp://ftp.wiley.com/sci_tech_med/electro-optical/problems.pdf)).


Sending permutations

Question: This seems simple but has stumped me for around half an hour...
The paragraph reads: "Let $x_1,x_2,x_3$ be three variables.
We let the permutations in $S_3$ move around like $1$, $2$, $3$". So for instance, the permutation $(132)$ sends
$$
\begin{align*}
x_1 &\to x_3, \\
x_2 &\to x_1, \\
x_3 &\to x_2.\\
\end{align*}
$$
I do not understand what this notation does to explain the permutation $(132)$ because surely $x_1 \to x_1$.
Sorry if this is stupid but I really cannot see it!
Comment: What do you mean with $x1$, $x2$ and $x3$? Do you just mean $1$, $2$ and $3$?
Comment: To clarify, there was a previous sentence saying, let x1,x2,x3 be three variables.
Comment: Ok. Maybe you should add this in the question, it will make it easier to read your question.
Answer: I think you are misreading the notation $(1 3 2)$.  As Ernie060's answer states, this represents the cyclic permutation $\begin{pmatrix}1&2&3\\3&1&2\end{pmatrix}$ where $1\mapsto 3$, $2\mapsto1$, and  $3\mapsto2$.  But based on the last part of your question, it seems like you are reading $(1 3 2)$ as the bottom row of the permutation $\begin{pmatrix}1&2&3\\1&3&2\end{pmatrix}$ where $1\mapsto 1$, $2\mapsto 3$ and $3\mapsto 2$.  This is simply not what the author of the book means.
This is a very common and useful way to represent permutations, arguably more common than the functional notation.  It would be reasonable to assume this as the default meaning if it isn't otherwise specified (but it probably was specified).
Comment: +1 Because you found the possible confusion of the OP.
Answer: The symbol $(132)$ stands for the cyclic permutation that permutates the elements $x_1$, $x_2$, $x_3$ as follows:  $x_1\mapsto x_3$, $x_3\mapsto x_2$ and $x_2 \mapsto x_1$.
Another example in $S_3$: the symbol $(13)$ stands for the permutation that interchanges $x_1$ and $x_3$, but keeps the element $x_2$ fixed.
On this wikipedia page on cyclic permutations there are some other helpful examples.
Comment: So are the conditions in my question just the opposite way around then or?
Comment: I do not understand what you mean by "conditions"? There are no assumptions or whatsoever in your question.

Sending permutations


Javascript if condition with return

Question: Folks, I am modifying a current function slightly to make use of two
variables. I have shown the past and present versions in the code snippet.
Basically what I want is if either one of the  two if conditions namely First Condition and Second Condition are
are true, do not execute the remaining logic of the function. If both are false, continue with the remaining code of the function.
 I think I am making a
silly mistake somewhere and if the first condition is true, execution is stopping right there.
(I Know that is because of the return statement at the end.)
How do I make sure the second if condition as well even if first one was true and returned a return
function myAlgorithm(code1, code2) {

   if(eval(code1)) {

      if(First condition) {
         alert("You cant continue");

         return;
      }
    }

    if(eval(code2)) {
       if(Second condition){
         alert("You cant continue");
       return;
      }

    }

    //If both of the above if conditions say "You cant continue", then only
    //disrupt the function execution, other wise continue with the left
    //logic

    //Rest of the function logic goes here

}

Ealier this code used to be:
function myAlgorithm() {

   if((First Condition) && (Second Condition)){
    alert("You cant continue");

    return;
   }

  //Rest of the function logic goes here
}

Comment: Do you want to eval both `code1` and `code2`, no matter which conditions are true? And did you notice that the `return` in the second `if` is placed *after* the closing brace?
Comment: Have you tried by doing return True; or return 1; in place of those empty return;
Comment: @SLaks, because code1 and code2 are strings.
Comment: @Yogu, Fixed the return. Thanks for pointing out.
Comment: @Mangobug, I didnt try. Should I return 1 from both and later on check for 1?
Answer: Use a variable and increment it once the condition is met. Then check to see if the variable was incremented.
function myAlgorithm(code1, code2) {
    var count = 0;
    if (eval(code1)) {

        if (First condition) {
            alert("You cant continue");

            count++;
        }
    }

    if (eval(code2)) {
        if (Second condition) {
            alert("You cant continue");
            count++;
        }
    }
    if (count == 2) {
        return "both conditions met";
    }

    //If both of the above if conditions say "You cant continue", then only
    //disrupt the function execution, other wise continue with the left
    //logic
    //Rest of the function logic goes here
}

Comment: Thanks Truth.. Let me try this real quick.
Answer: Could use flag variables to keep track of your conditions and then check both of them like before
function myAlgorithm(code1, code2) {
 var flag1;
 var flag2
if(eval(code1)) {
  flag1 = First condition
}

if(eval(code2)) {
  flag2 = second condition
}

if(flag1 && flag2){
  return;
}
//If both of the above if conditions say "You cant continue", then only
//disrupt the function execution, other wise continue with the left
//logic

//Rest of the function logic goes here

}

Comment: Thanks Decad.. I'll try this one as well.
Comment: oops someone downgraded your solution... Folks can someone explain why?

Javascript if condition with return


Programa que receba uma série de notas precisa desconsiderar uma entrada inválida

Question:
Faça um programa que receba uma série de notas de alunos e depois as imprima. Entretanto, o programa não pode aceitar notas maiores que 100 ou menores que 0. Se o usuário digitar alguma nota errada, deve conseguir digitar novamente.

O código até o momento está assim:
public class notaMenorCem
{
  public static void main (String[]args)
  {
    int notaAluno [] = new int[5];
    for (int i=0; i<notaAluno.length; i++)
    {
      notaAluno[i] = Entrada.leiaInt ("Digite a nota: ");
      {
        if(notaAluno[i] <0 || notaAluno[i] >100)
        {
          System.out.println("Nota inválida, digite novamente:");
        }
      }
    }
    for (int i=0; i<notaAluno.length; i++)
    {
      System.out.println("Nota do aluno " +i+ ":"+notaAluno[i]);
    }
  }
}

O usuário recebe o aviso por inserir uma nota maior que 100 porém ela fica registrado igual, o que está faltando?
Answer: Faltou não fazer a atribuição se a validação falhar, por isso coloquei um continue. E faltou voltar o contador para trás se o item não for inserido, para manter o sincronismo.
Faltou validar quando um valor digitado não é um número, se fizer esse teste a aplicação quebrará, mas não vou corrigir isso.
Faltou outras coisas menos relevantes.
import java.util.Scanner;

public class Main {
    public static void main (String[] args) {
        Scanner sc = new Scanner(System.in);
        int notaAluno [] = new int[5];
        for (int i = 0; i < notaAluno.length; i++) {
            var nota = sc.nextInt();;
            if (nota < 0 || nota > 100) {
                System.out.println("Nota inválida, digite novamente:");
                i--;
                continue;
            }
            notaAluno[i] = nota;
        }
        for (int i = 0; i < notaAluno.length; i++) System.out.println("Nota do aluno " + i + ":" + notaAluno[i]);
    }
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.


How to get char** using C#?

Question: I need to pass an argument to an unsafe DllImported function in the form of:
[DllImport("third_party.dll")]
private static extern unsafe int start(int argc, char** argv);

I'm assuming it's an array of strings.  However when I try to do the following, I get 'Cannot convert from string[] to char**' error.  How do I go about getting this to work?  Thanks.
string[] argv = new string[] { };
start(0, argv);

EDIT 1:
The question was marked as duplicate, but looking at the possible duplicate question, I still do not see how to get this to work.
EDIT 2: To further clafiry the question and required parameters.  It looks like your standard argc/argv parameters (parameter count, and then parameter values).  The same way you would start a c program: int main(int argc, char** argv);  For this particular problem, I don't want to pass any arguments at all (so count is 0).
EDIT 3:
I got more information from the 3rd party library vendor. Here it is:

the first parameter is the count of arguments
the second parameter is an array of null terminated strings
the strings are ANSI encoded

EDIT 4: Final edit with a working solution (at least in my case).  I would make this the answer, but can't because this question is marked as a duplicate.  Here's a link to a question that helped me the most.  In the end the dll function expected an array of pointers to buffers with ANSI strings.  So my final approach (based off the linked question), was as follows.  Create an array in memory to hold the pointers, then allocate each string elsewhere in memory, and write pointers to those strings inside the first pointer array.  This code works in production:
[DllImport("third_party.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern int start(Int32 args, IntPtr argv);

public bool start(params string[] arguments)
{
    int result;

    if (arguments == null || arguments.Length == 0)
    {
        result = dll_system_startup(0, IntPtr.Zero);
    }
    else
    {
        List<IntPtr> allocatedMemory = new List<IntPtr>();

        int sizeOfIntPtr = Marshal.SizeOf(typeof(IntPtr));
        IntPtr pointersToArguments = Marshal.AllocHGlobal(sizeOfIntPtr * arguments.Length);

        for (int i = 0; i < arguments.Length; ++i)
        {
            IntPtr pointerToArgument = Marshal.StringToHGlobalAnsi(arguments[i]);
            allocatedMemory.Add(pointerToArgument);
            Marshal.WriteIntPtr(pointersToArguments, i * sizeOfIntPtr, pointerToArgument);
        }

        result = start(arguments.Length, pointersToArguments);

        Marshal.FreeHGlobal(pointersToArguments);

        foreach (IntPtr pointer in allocatedMemory)
        {
            Marshal.FreeHGlobal(pointer);
        }
    }

    return result == 0;
}

Comment: Agreed - question is actually concise.  I've not done this so I cannot answer :)
Comment: Note that if it's `char` in C it won't be `char` in C#; C `char` is 1 byte but C# `char` is 2 bytes
Comment: using ref to a char * might do it.
Comment: How about this link: http://stackoverflow.com/questions/11572631/marshal-a-double-char-pointer-return-value
Comment: You still have not defined the interface. Usually argv is of length argc + 1 with a final entry that is NULL. Is that the case here? You've asked the question poorly and have received a lot of poor advice.
Comment: `char*` I know how to do, but `char**`...? Argh.
Comment: I think you need to use StringBuilder[] instead of string[]
Comment: Possibly, but there still is the signature issue - char ** is not a StringBuilder.
Comment: @LukStorms I'm not in control of the function.  It's a 3rd party dll.
Comment: What about using `&args` in an `unsafe` context (where `args` is a `string`)?
Comment: @MichaelDorgan The answer to that question has a seemingly useful link (Marshaling char**) http://www.mono-project.com/docs/advanced/pinvoke/ and that's probably where I'll start looking if an easier solution doesn't present itself.
Comment: The downvotes are perfectly valid. Asking how to call an unmanaged function without specification of that unmanaged function is pointless. The type is `char**`. Fine. But what are the semantics?
Comment: I feel this is missing information; how many strings are you expecting to be added to the array? Are they null terminated or fixed length strings?
Comment: @DavidHeffernan I updated the question with relevant information.
Comment: @MeirionHughes Question updated.
Comment: No you did not. We still have no idea what the unmanaged interface is. Anyway, you've accepted an answer, and the question is closed. I'm amazed at the interest in this question. I'm not sure why there is so much activity, but unfortunately you have received a huge amount of poor advice. There should be no answers because your question is not well specified. Until you can specify the interface which you are trying to meet, it is pointless for anyone to write code. That you are doing all this trial and error is just a huge waste of time.
Comment: @DavidHeffernan There's so much activity because main(int argc, char** argv) is a fairly common entry to native c dll's, and there isn't a single stackoverflow question that answers how to marshal data across it. Certainly not the alleged duplicate questions (one talks about char*, the other about const char**).
Comment: @DavidHeffernan All I'm getting from the vendor, is that they expect the first argument to be name of the executable, no mention of the final NULL argument.  I'll check again to be sure.  In any case, I finally got it working (see my final edit).  The function was expecting an array of pointers to string buffers, and not concatenated string buffers as I was told initially.  Once I made that change, the application started working as expected.  Your point about NULL argument is a good one, as it may just work by accident now, if the memory beyond my pointers just happens to be zeroed.
Comment: Just verified, they use argc to exit the parsing loop.
Answer: I think you might need to use Marshal.
var a = (char*)Marshal.StringToCoTaskMemAuto("myString");
char** = &a;

This is just a guess because I don't have a library that takes char** so I haven't been able to try it.
Comment: It compiled, without me having to change the DllImport signature, but I still end up with PInvokeStackImbalance exception.  The call does seem to work partially though, because I see 3rd party dll logging to output window.  I need to verify something else is not causing it, before I accept your answer.  +1 for now.
Comment: @Eternal21 Given the PInvokeStackImbalance error, I'm going to guess you were right on it being "an array of strings," though it'd be really helpful to see more details on the third-party library.  Steve is on the right path that you should use Marshal in order to convert strings to unsafe pointers, but I'm thinking you'll need to figure out what those strings are supposed to be, and then build your array from your strings.
Answer: The equivalent of C's char** is a fully-pinned byte[][] in C# (and by fully-pinned I mean the outer array AND all inner arrays). If you want to pass C# strings you'll have to convert them to byte arrays, for instance with Encoding.ASCII.GetBytes.
Comment: I've decided to manually 'Marshal' the data as a single byte[] buffer.  Ive edited my question with the new code I came up with.  It looks like it should work, but the library doesn't like it, I end up with Access Violation from it.  Not sure if it's because I used IntPtr instead of byte**.
Comment: Your dllimport signature is probably wrong. It's unlikely the function expects a C# `char**`, which would be like a `wchar_t**` in C. It should probably be simply `string[]` instead and let P/Invoke deal with the marshalling, as in the linked duplicate questions.
Comment: The function doesn't expect a C# char**, which is why I used a byte like you suggested.
Comment: But then the C# DllImport signature is wrong because it uses the C# `char`.
Comment: All fixed now in my final edit.  Your byte comment was helpful.
Answer: Can you change the DllImport declaration parameter type to StringBuilder[]? Then you can call the function like:
StringBuilder[] args = new StringBuilder[] { };
start(args);

Comment: After everything I read, shockingly this might actually work.

How to get char** using C#?


Accounting for discrete or binary parameters in Bayesian information criterion

Question: BIC penalizes based on the number of parameters. What if some of the parameters are some sort of binary indicator variables? Do these count as full parameters? But I can combine $m$ binary parameters into one discrete variable that takes values in $\{0,1,...,2^m-1\}$. Are these to be counted as $m$ parameters or one parameter?
Answer: It is partly because of this imprecision in the "number of parameters" in BIC that DIC (the deviance information criterion) introduced an effective number of parameters as
$$
p_D(x) = \mathbb{E}[D(\theta)|x] - D(\mathbb{E}[\theta|x])
$$
where
$$
D(\theta)=-2\log f(x|\theta)
$$
and
$$
\text{DIC}(x) = p_D(x) + \mathbb{E}[D(\theta)|x]
$$
Note that $p_D(x)$ is then data-dependent. (As discussed there, DIC also has problems of its own!)
Comment: Yes, BIC is an approximation of the marginal likelihood.  However, it is only an approximation that converges to the "truth" when the sample size grows to infinity. It is therefore not directly Bayesian (does not use the prior, for one thing!) and completely unrelated to MCMC (where the approximation is of a Monte Carlo type: if I increase the number of simulations, the approximation improves). DIC is deemed to be more Bayesian by many (incl. B. Carlin and D. Spiegelhatler)
Comment: So I am slightly confused. I thought BIC was an approximation of $E[log P(y|Model)] = \log(\int P(y|\theta)P_{model}(\theta)d\theta)$, which can be calculated from the MCMC simulations. Why then would we calculate DIC?
Comment: I guess my question was, is the DIC an approximation of the marginal model likelihood too? I guess I should read about it myself, but since we were discussing it, I thought explaining this would make the answer more complete. Thanks!


Simplifying $\sum\limits_{k=0}^{\infty}\frac 1{2^{k+1}}\sum\limits_{n=0}^{\infty}\binom kn\frac 1{2(n+1)(3n+1)}$

Question:
Question: Is there a way to simplify $$\sum\limits_{k=0}^{\infty}\dfrac 1{2^{k+1}}\sum\limits_{n=0}^{\infty}\binom kn\dfrac 1{2(n+1)(3n+1)}\tag{1}$$
  Into a single summation symbol? $\sum\limits_{k=0}^{\infty}\text{something}$

I inputed it into WolframAlpha and got a really complicated expression$$\sum\limits_{k=0}^{\infty}\dfrac {1-2^{k+1}+3\left(_2F_1\left[\begin{array}{c c}\frac 13,-k\\\frac 43\end{array};-1\right]\right)+3k\left(_2F_1\left[\begin{array}{c c}\frac 13,-k\\\frac 43\end{array};-1\right]\right)}{2^{k+3}(k+1)}$$
Which isn't what I really wanted because the inner sum is significantly more complex than before. Is there a way?
I'm still relatively new to this. If you have a hint, it would mean a lot if you commented it!
Comment: I edited your post to eliminate the display styled math expression in the title.  Please refer to [this answer about titles](http://meta.math.stackexchange.com/q/16946/290189) on meta math.SE for further explanation.
Answer: Without recognizing a binomial transform, you may notice that
$$\begin{eqnarray*}\sum_{n=0}^{k}\binom{k}{n}\frac{1}{2(n+1)(3n+1)} &=& \frac{3}{4}\int_{0}^{1}\sum_{n=0}^{k}\binom{k}{n}\left(x^{3n}-x^{3n+2}\right)\,dx\\&=&\frac{3}{4}\int_{0}^{1}(1-x^2)(1+x^3)^k\,dx\end{eqnarray*}$$
hence:
$$\sum_{k\geq 0}\frac{1}{2^{k+1}}\sum_{n=0}^{k}\binom{k}{n}\frac{1}{2(n+1)(3n+1)}=\frac{3}{4}\int_{0}^{1}\frac{1-x^2}{1-x^3}\,dx $$
and the last integral can be computed through partial fraction decomposition.
Comment: (+1) I was going to mention this, but it appears you finished before I did.
Comment: are you sure about the $\frac{1}{6}$ ? $\frac{1}{3n+1}  - \frac{1}{3n+3} = \frac{2}{3(n+1)(3n+1)}$ I think it should be $\frac{3}{4}$
Comment: @Anonymous: you are right, now fixing.
Answer: Notice that
$$\binom kn=0\forall n>k$$
Thus, it simplifies down to
$$\sum_{k=0}^\infty\frac1{2^{k+1}}\sum_{n=0}^k\binom kn\frac1{2(n+1)(3n+1)}$$
And by an inverse Euler sum, this reduces down to
$$\sum_{n=0}^\infty\frac1{2(n+1)(3n+1)}=\frac1{12}(\pi\sqrt3+9\ln(3))$$
Comment: Okay, I blame myself for this, but I *started* with $$\sum\limits_{n=0}^{\infty}\dfrac 1{2(n+1)(3n+1)}$$Performed an Euler Sum and got $(1)$. Is there a way to simplify $(1)$ into a different summation? I'm just wondering if there is a faster convergence for $$\pi=4\sqrt{3}\sum\limits_{n=0}^{\infty}\dfrac 1{2(n+1)(3n+1)}$$
Comment: Lmao, thought you did.  To be honest, you could just apply another Euler sum to get back to the original, but beyond that I don't know.


Predict time series data from another

Question: Here is my problem:
I have two times series which are highly correlated. One of my time series have one more data point. I would like to predict the other time series missing data.
For example (in R):
a = c(126,140,178,223,208,266)
b = c(155,154,220,277,256,334,330)

length(a) < length(b)

cor(a,b[1:6])

names(a) = seq(2000,2005,1)
names(b) = seq(2000,2006,1)

1. My very basic solution is just copy the change of b when I predict a, like this:
ch = (b[7] / b[6]) - 1
a[7] = a[6] + (a[6]*ch)

2. A little bit more complicated version but still basic is this (to predict a from b):
a = c(126,140,178,223,208,266)
b = c(155,154,220,277,256,334,330)

2.1. Give a same "scale" of it (same as plotting a and b to a 1 graph at the same time):
pred = c(NA)

for (i in 1:length(b))
{
pred[i] = ( b[i] / max(b) ) * max(a)
}

2.2 make a custom CI:

mistake = c(NA)

for (i in 1:(length(pred)-1))
{
mistake[i] = (pred[i] / a[i]) -1
}

sd_mis = sd(mistake)

CI_l = c(NA)
CI_U = c(NA)

for (i in 1:length(pred))
{
CI_l[i] = pred[i] - (pred[i] * sd_mis)
CI_U[i] = pred[i] + (pred[i] * sd_mis)
}

pred = round(pred,0)
CI_l = round(CI_l,0)
CI_U = round(CI_U,0)

2.2 plotting:
plot(pred, type='o', col = "green", xaxt='n', ylim = c(0,max(c(a,pred,CI_l,CI_U))))
lines(a, type='o', col = "black")
lines(CI_l, type='o', col = "red")
lines(CI_U, type='o', col = "red")
axis(side=1, at=seq(1,length(pred),1), labels = seq(2000,2006,1))

3. linear regression
Linear regression would be a decent solution, but I afraid to use because of a small n.
fm <- lm(a ~ b[-7])
predict(fm, list(b = 330))

4. Vector autoregression
I've also tried vector autoregression, but this process needs a same variable length, and also gives me a meaningless result (also because of a small n, I guess)
m = matrix(NA,length(a),2)
m[,1] = a
m[,2] = b[-7]

library(vars)

summary(VAR(m))

My questions are:

Is there a more sophisticated way to get the forecasts?*
Is my second model mathematically correct?*
Comment: Your real data has 6 observations too?
Comment: Yes! This is one of the problem.
Answer: Plotting your data shows that a and b appear to be strongly linearly correlated:
> dataset <- data.frame(b=b[1:6],a)
> plot(dataset,type="n")
> with(dataset,text(b,a,rownames(dataset)))

However, with no more than six historical observations, anything fancy like VAR or others will likely overfit. In addition, VAR forecasting really only makes sense if you need to forecast all components - but here, you already know the 2006 b component, you don't need to forecast it.
The simplest thing would be to simply regress a on b:
> model <- lm(a~b,dataset)
> model

Coefficients:
(Intercept)            b
    17.7859       0.7409

Here is the prediction:
> predict(model,newdata=data.frame(b=b[7]))

    2006
262.2801

You write that you are afraid of using it because of small n - but there really is nothing simpler than this, and with the relationship as obvious as it is here, this is what you should be doing.

EDIT: You could also fit an AR model to your a, but this will of course only pick up the inherent signal in a (auto.arima(a) yielded an ARIMA(0,1,0) model with drift), not the relationship with b, so it's not using information you have, which is wasteful.
Or you could do a really fancy ARIMAX model for a using b as an eXternal variable:
> library(forecast)
> ar.model <- auto.arima(a,xreg=b[1:6])
> ar.model
Series: a
ARIMA(0,0,0) with zero mean

Coefficients:
      b[1:6]
      0.8118
s.e.  0.0110

sigma^2 estimated as 42.47:  log likelihood=-19.76
AIC=43.52   AICc=47.52   BIC=43.1
> forecast(ar.model,xreg=b[7])
  Point Forecast    Lo 80    Hi 80    Lo 95  Hi 95
7       267.9071 259.5552 276.2589 255.1341 280.68

The result is pretty close to the one from the simple regression.
Anyway, I really wouldn't be using ARIMA(X) with only six observations. Just go with a simple regression.
Comment: Thanks for Your reply! And what about autoregression? I learned that linear regression is not suitable for prediction.
Comment: Why would linear regression not be suitable for prediction? I edited my answer to also include ARIMAX, which I really don't think is justified if you have only six observations.

Predict time series data from another


Android with sourceCompatibility = JavaVersion.VERSION_11 gives error error: "package android.app does not exist"

Question: When using the JDK 11 target, then I get this error:

error: package android.app does not exist

I saw a solution to upgrade to the 'Canary' AS version. I prefer to use the beta or stable Android Studio version. I have updated it regularly. Not planning a major change for just an upgrade.
So, this works well: even with an Android Studio "Project settings" and "JDK" with "JDK 11".
When the build.gradle has these compile options, everything works fine.
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

This gives the mentioned errors:
compileOptions {
    sourceCompatibility = JavaVersion.VERSION_11
    targetCompatibility = JavaVersion.VERSION_11
}

My build.grade project file is:
buildscript {
    repositories {
        mavenCentral()
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:4.2.1'
        classpath 'org.ajoberstar:grgit:3.3'
    }
}

allprojects {
    repositories {
        maven { url "https://jitpack.io" }
        google()
    }
}

Parts of my build.grade module file is:
apply plugin: 'com.android.application'
repositories {
    mavenCentral()
    maven { url "https://jitpack.io" }
    google()
}

How can I build normally using the (Oracle) JDK 11 compiler?
Answer: Just receive the Android Studio / Gradle 7 upgrade.
Everything is working right now!

Use this as your compiler options:

compileOptions {
    sourceCompatibility JavaVersion.VERSION_11
    targetCompatibility JavaVersion.VERSION_11
}

In the settings you see that the JDK 11 is already chosen. If not chosen automatically, you will be allowed to chose that JDK 11 version.
Comment: Any idea what the underlying problem was?


AttributeError: 'list' object has no attribute 'apend'

Question: Por que ocorre este errp?

"AttributeError: 'list' object has no attribute 'apend'" with this code?

class Stack :
  def __init__(self) :
    self.items = []

  def push(self, item) :
    self.items.apend(item)

  def pop(self) :
    return self.items.pop()

  def isEmpty(self) :
    return (self.items == [])

  s = Stack()
  s.push(54)
  print s.pop()

Comment: Qual linguagem esta utilizando? é muito provável que seja  self.items.append(item) em vez de  self.items.apend(item)
Answer: Foi apenas um erro de digitação. Vc esqueceu um 'p' em "append"
Troque

self.items.apend(item)

por

self.items.append(item)

Além disso, vc precisa recuar esse bloco para o escopo correto.
    s = Stack()
    s.push(54)
    print s.pop()

O código final ficaria assim
class Stack :
  def __init__(self) :
    self.items = []

  def push(self, item) :
    self.items.append(item)

  def pop(self) :
    return self.items.pop()

  def isEmpty(self) :
    return (self.items == [])

s = Stack()
s.push(54)
print(s.pop())

Veja funcionando online aqui
Comment: Caramba, obrigada, estava errado no site onde estou aprendendo...
Comment: Se o seu problema foi resolvido, considere [aceitar](https://pt.stackoverflow.com/help/someone-answers) a resposta clicando no 'v' verde ao lado esquerdo da pergunta.
Bons estudos.


Views pagers for anonymous users

Question: I've been trying to figure out why the pager element for views won't show up for anon users in Drupal 7. The following are the things I've tried to get them to show, cache clear, mess with the access param in the actual view, create a function that calls
<code>drupal_static_reset('user_access');
drupal_static_reset('user_role_permissions');
</code>
Has anyone been able to solve this? I've searched Google for over an hour for a fix/explanation.
Comment: Those `drupal_static_reset()` calls just force Drupal to re-read the database tables, or invoke the hooks implemented by modules, to restore static values. They don't stop Drupal from applying permissions.
Answer: If after running the permission checks drupal doesn't find enough items to fill your view it will not show the pager (for any user role). You should check why there aren't enough items for the view.
Did you check for the number of items on a page (in the view). Is the pager set to be on (in the view). There are chances that you forgot to check some of these settings. It happens.
Comment: It turns out its a bug with D7 views alpha, so I upgraded to beta3, and lost all of my views. Now have to rebuild them in the new, terrible UI

Views pagers for anonymous users


Cannot find module 'reflect-metadata'

Question: Quando vou instalar o angular 2 usando:
ng new angular-teste

Recebo o erro:

Cannot find module 'reflect-metadata'

O que pode ser?
Answer: NPM deve ser atualizado para v3. Versões anteriores causarão este erro.
Para atualizar sua versão:
npm install npm -g

Referência.

Cannot find module 'reflect-metadata'


Quanto mais queries no MySQL maior o consumo?

Question: Estou desenvolvendo um site e meu código está usando muitas queries/consultas no MySQL de uma vez só, estou tentando diminuir essas queries para o menor número já que acho que quanto mais consultas mais recursos serão consumidos, estou certo?
Exemplo 1:
<code>$busca = $conexao->query("SELECT nome FROM graficos");
$busca2 = $conexao->query("SELECT nascimento FROM graficos");
</code>
Exemplo 2:
<code>$pegadeumavez = $conexao->query("SELECT nome, nascimento FROM graficos");
</code>
O Exemplo 1 teria o mesmo consumo de Exemplo 2? Digo qualquer tipo de consumo como memória RAM, CPU, bytes, processamento, etc
Answer: boa noite
a ideia ai é bem simples...quanto mais condesada for a sua consulta (ou seja, quanto mais dados você conseguir pegar de uma única vez) melhor, o maior gargalo que as aplicações tem hoje é o chamado Server Round Trip, ou seja a quantidade idas ao servidor para pegar dados , quanto menos vezes melhor. claro que cabe ao bom senso também não fazer uma mega consutla que retorna um zilhão de linhas, se possível quebre em pequenas cargas. Mas respondo, sim quanto mais dados em uma úncia consulta melhro para a perfomance da sua aplicação.


How to find index of javascript array of object if value is given?

Question: Here is my array of objects:
$scope.choices =  [
  {
     id: 0,
     product: [{id:'0'}]
  },
  {
    id: 10,
    product: [{id:'5'}]
  }
];

How to find index number for id value "10"?
Answer: Let following is the object you want to search in an array
var searchObject={
    id: 0,
    product: [{id:'0'}]
};

Now using following
$scope.choices.indexOf(searchObject);

Hope this helps :)
Comment: [How do I format my code blocks?](https://meta.stackoverflow.com/questions/251361/how-do-i-format-my-code-blocks)
Answer: you can use this:
var reqIndex;
$scope.choices.forEach(function(choice, index) {
    if (choice.id === 10) {
        reqIndex= index;
        return
    }
})

Answer: try this
$scope.choices.findIndex(function(x) {
   return x.id==10;
});

Answer: if you like to use pure javascript andno problem to use the you can use following
function findWithAttr(array, attr, value) {
    for(var i = 0; i < array.length; i += 1) {
        if(array[i][attr] === value) {
            return i;
        }
    }
    return -1;
}

findWithAttr(choices, 'id', 10);

Alternatively for angular you can use the following function
  $scope.findIndex=function(){

            angular.forEach( $scope.choices,function(object,index){
                     console.log(object);
                    if(object.id==10){
                        console.log('index'+index);
                    }

                })

        };

Answer: You could use Object.keys() to retrieve all the keys of you're object then iterate on them to find if there is one that has the corresponding value.