Convert node URL to absolute

Question: We are using Drupal Core v8.6.2 and we have a url variable in our node--page.html.twig template. While using ksm() and {{ kint() }} we are finding that if we use hook_preproces_node($variables) that the url is inserted into the $variables array. Unfortunately this url is relative, but we need an absolute URL in our twig template.
How can we convert this url variable from our node--page.html.twig template to be absolute?
node--page.html.twig
I have reduced the comments section to only include comments that were relevant to the question.
{#
/**
 * @file
 * Theme override to display a node.
 *
 * Available variables:
 * - node: The node entity with limited access to object properties and methods.
 * - label: The title of the node.
 * - content: All node items. Use {{ content }} to print them all,
 * - url: Direct URL of the current node.
 * - attributes: HTML attributes for the containing element.
 * @see template_preprocess_node()
 *
 */
#}

 {# url is the variable we want to be absolute #}

 {{ label }}

  {{ content.body }}

Comment: How are you creating this variable?
Comment: @Kevin I added more lines from the comment's section of the twig template in the question. It is a copy of the `node.html.twig` from the [classy node.html.twig](https://api.drupal.org/api/drupal/core%21themes%21classy%21templates%21content%21node.html.twig/8.6.x) template. So nothing I generated myself.
Answer: You can use hook_preprocess_node to passe base_url to your twig like the following:
function mymodule_preprocess_node(&$variables) {
  global $base_url;
  $variables['base_url'] = $base_url;
}

in node--page.html.twig you will get the absolute url by:
{{ base_url ~ url }}

Convert node URL to absolute


Map Multiple Controls to one Method

Question: I know in the .Net framework you can map any controls events to a singular method, as if you wanted to map a column of buttons in a GridView to one method, you could.
In VBA i have since forgotten this information.  Could someone help me out in how i can map a Forms' Control(s) to one method in the Forms Code-Behind?
Current OnClick Events, to be consolidated
<code>Private Sub btnSubmit_Click()
    CloseForm Me
End Sub

Private Sub btnCancel_Click()
    CloseForm Me
End Sub
</code>
There are at least two of these methods per form.  On some there are 3 or 4 for various Events but they all have the same body, one line pointing to a global method.
Answer: It depends on what you want to do. You can set up the form so that it receives the click events  and check the screen.active control or you can set the event line on the property sheet for each control to a function. Frequently, people who are not familiar with the ease of MS Access go a long way around, which is why it is useful to say what you wish to do, there is often an easier way and often a way that does not involve code at all.
On the click line of the property sheet for the control:
<code>=Menu_Or_Exit([Name],"cmdClose")
</code>
of course you could pass Me as form, but I have found [Name] to be very useful in a number of ways.
An excerpt from the function:
<code>        Case "cmdClose"
            DoCmd.Close acForm, FormName
            CheckMainMenu
</code>
You can keep a menu form, a menu subform, or just copy the button from form to form.
Comment: I have around 10-15 forms....and, at least, two buttons on each form do the same thing `CloseForm Me` and i figured it would be easier if i had a Module Global method that i could map the Buttons.OnClick event to.  Ill Revise my Q Post to show you the destination Method for these controls Click Event
Comment: so understand the parts `Menu_Or_Exit` is the method name, `[Name]` is a directive synonymouse with `Form.Name`, and of course `"cmdClose"` would be the control name.  So in theory i could lop off `"cmdClose"` parameter and just pass the method the `[Name]` parameter and be done with it?
Comment: Yes, you could. The above was a menu function with other possible buttons and actions, for example, cmdHide. There was no need to tell the user I was hiding, not closing the form :)
Comment: Was noticing that the method, after being placed in a Module was not showing up in the Expression Builder.  Is there a readon why a `Public Sub` in a Module would not show up in Expression Builder?  Or does it only look for Parametered Methods?
Comment: Function, not sub. You can only refer to functions in this way.
Comment: ok that would be the reason it wasnt showing up.....just a Null return Function but still has to be declared as a Funtion?
Comment: I am afraid so. I think it relates back to macros.
Comment: Last question in regards to mapping.  Can the Function/Macro be Public on the Form itself or must it always be a Module-Level method?

Map Multiple Controls to one Method


About 1st-order formulas encoding the runtime configurations of some Turing Machine

Question: I was reading the Trakhtenbrot's theorem in https://en.m.wikipedia.org/wiki/Trakhtenbrot%27s_theorem, and there is something I cannot understand.
I have read that, for any Turing Machine M, it is possible to build a logic formula $\phi_M$ s.t. $\phi_M$ is finitely satisfiable if and only if M halts.
The idea, as far as I have understood, is to obtain $\phi_M$ by:
(1) considering some predicates that enables to represent the configuration of $M$ at different execution times. For instance, using some predicates $T_0(s, t)$ and $T_1(s, t)$ to represent that at time $t$ the value contained in the position s of the machine tape is 0 or 1, respectively.
(2) impose the necessary logic conditions to ensure that these different configurations follows the Turing Machine program.
My doubt is the following:
If M does not hold, it seems to me that, then, every model of $\phi_M$ would satisfy that "every configuration is followed by another one", which, I think, could be encoded in logics by something like this:
$\psi_M = \forall_{s, t}( (T_0(s, t) \lor T_1(s, t)) \rightarrow (T_0(s, t+1) \lor T_1(s, t+1))$).
Thus, I am reaching to the (wrong) point where we can check if a Turing machine M does not halt by checking if some first-order formula $\phi_M \rightarrow \psi_M$ is a theorem. However, this is impossible, since by running M in parallel to some algorithm to check if $\phi_M \rightarrow \psi_M$ is a theorem, we would decide if M halts. Could you help me to identify where is the mistake, please?
Answer: If we had an infinite model which claims that some machine "halts" in an infinite number of steps, this model will have an infinite number of steps followed by a single "final" step, so that it isn't true that every step is followed by another one, even though the model is infinite.
More generally, the problem is that you are trying to find a way of expressing "the model is infinite" in a first-order way, and then letting that formula be $\psi_M$. But if you could express "the model is infinite" then, by taking negations, you could express "the model is finite". That is impossible in this case, by compactness. Because Turing machines can take an arbitrarily long time to halt, the models can be of arbitrarily large finite size.  By compactness, if a formula has models of arbitrarily large finite size, it also has infinite models. So there is no way to capture "the model is finite" in this case, than thus no way to capture "the model is infinite".


copy a site to another installation

Question: Read this documentation https://drupaltraining.stanford.edu/node/111
But I was under the impression the sql database file has to be edited before you can do this?
"Before importing SQL file to new database, find and replace old URL and site name with new one." but I cannot find url or site name in sql file.
Comment: In any case, a question is only good as the answer and there is nothing wrong with filtering info from various sources.
Comment: @CharlieBunt A question on any SE site needs to stand on its own - that is to say, the bulk of your question cannot reside in an external resource. If that resource goes down, the question is useless. Remember, this is a Q+A site, not a support forum, so any question needs to be useful for future visitors, it's not just to get you an answer to an immediate problem you're facing. In future I'd recommend summarising the relevant parts of any external document into your question, and providing a proper, full description of the problem you're having. Otherwise downvotes will naturally abound :)
Comment: Have since successfully copied databases by just renaming them in drupal with no problem.
Answer: If you want to replace the old URL then you may do that before taking a dump of existing database:

Search the OLD_URL_VALUE in the database from the phpmyadmin. (It may be possible that you will get no value in result, that would be the case when you have no hard coded value of your Old domain)

Build the query to replace the OLD URL something like:
// Example: Replacing OLD_URL_VALUE (from the "body" column of the "node_revisions" table):
update node_revisions
set body = REPLACE(body, 'OLD_URL_VALUE', 'NEW_URL_VALUE')
WHERE body LIKE '%OLD_URL_VALUE';

Alternatively you may try the Backup and migrate module: Back up and restore your Drupal MySQL database and files or migrate a site between environments.
Also you can dump some or all of your database tables to a file download or save to a file on the server or offsite, and to restore from an uploaded or previously saved database dump. You can choose which tables and what data to backup and cache data is excluded by default.
Comment: @GisleHannemyr For the drupal6 I have faced this issue, specially with the files of tinymce module (containing the files path along with the domain)
Comment: Well, I don't use phpadmin just linux command line but I did open the sql file in an editor and nowhere could I see a URL so I'm just going to ignore it.
Comment: @GisleHannemyr I have migrated lots of Drupal 6 sites, and have routinely run into absolute URLs.  The Insert module + TinyMCE is normally the culprit.

copy a site to another installation


What is the best line algorithm to use in drawing application?

Question: What would be considered the best algorithm for line drawing in a program like photoshop or gimp?
I've been playing around with bresenham's line algorithm and I find that the lines don't render very well because it does not pick up on the natural flow (curves) of the pen.
i.e:

What is the best way to draw smooth lines from user input with no post editing? Can some form of bezier curve be used?
Is there a standard accepted algorithm for this kind of thing or just a general idea of how it should be done?
Answer: There are different kinds of splines which can be used for this, where Bézier curves are the the best-known. Basically, two kinds of splines are distinguished, namely interpolating splies (which go through the control points) and approximating splines (which are not required to go through the control points, but try to minimize a suitable difference to the line segments). For evaluation of Bézier curves, an algorithm by De Casteljau for evaluation of the Bernstein polynomials can be used, although other schemes will perhaps work as well.


multiple div boxes with images with one class. Only fade one image at a time?

Question: I have a problem with my javascript.
I am trying to create a javascript that fades away a white/black png file when you hover over the div.
But the problem is that I have several divs and images, and one class.
How can I get this to work?
Put it all in a JSFiddle:
http://jsfiddle.net/auURQ/61/
All help is very appreciated :-)

$(document).ready(function () {
$(".overlay").show();
$('.eTop').hover(

function () {
    $('.overlay').fadeOut('slow');
},

function () {
    $('.overlay').fadeIn('slow');
});

});
Comment: I dont exactly understand the problem. Both of your eTop divs are overlapping in the fiddle so whenever you hover over either of them, the image fades in. That's not what you want?
Comment: Overlapping???

I want only one to fade at a time when you hover.
Comment: Do you mean that you only want the fading to happen to the `.eTop` that you are hovering over?
Comment: Yea, I want the fade to happen when you hover the `.eTop`  div.
But only one box at a time.
Answer: If I get it right, you want the animation to appear only to image that is currently hovered. For this you need to add following code:
$(document).ready(function () {
$(".overlay").show();
$('.eTop').hover(

function () {
    $(this).children('.overlay').fadeOut('slow'); // selects element with class     .overlay that is direct child of div that is currently hovered
},

function () {
    $(this).children('.overlay').fadeIn('slow');
});
});

Here is updated jsfiddle - http://jsfiddle.net/auURQ/71/
Answer: Use $(this) first to spot the specific div.eTop and then find the contained image.
$(document).ready(function () {
    $(".overlay").show();
    $('.eTop').hover(

    function () {
        $(this).find('.overlay').fadeOut('slow');
    },

    function () {
       $(this).find('.overlay').fadeIn('slow');
    });
});


Where can I find Image(RGB) data to implement K means agorithm?

Question: I am a newbie to Data science.I have learned about clustering algorithms(especially K-means algorithm)and I would like to implement this algorithm(using Euclidian distance metric) to segment image on basis of RGB values of the image so that I could find clusters of most similar colours in an image .but I didn't have any relevant dataset with me if anyone has or know where can I find the dataset ? please provide me any direct link .?
Answer: It seems that you are referring to quantizing the colors in an image using K-Means for vector quantization. So you would, for example, pick an image and then say that you want to reduce the number of colors to five in this image. You are asking for data, which in this case couldn't be simpler: It can be literally any image.
As an example, here is how you would do it in Mathematica:
Pick the famous Mandrill image (although, again, the image doesn't have to be famous!):
mandrill = ExampleData[{"TestImage", "Mandrill"}]

Find the RGB vectors and run K-Means on them:
data = ImageData[mandrill];
clusters = FindClusters[Flatten[data, 1], 5, Method -> "KMeans"];

Replace the RGB vectors with the centroid in each cluster and create the new image:
rules = Dispatch@Flatten[MapThread[
     Function[{cluster, mean}, # -> mean & /@ cluster],
     {clusters, Mean /@ clusters}
     ], 1];

Image[data /. rules]

This new image uses only five different colors because we asked for five clusters when running K-means.
The key operation here for you is
data = ImageData[mandrill]

which takes an image and returns a grid of RGB vectors corresponding to the colors of the pixels in the image. You need to find a function like that in your programming language of choice, and then you can use whatever image you like.
Comment: but I would like to know one more thing here .can I draw an elbow curve for this data so that I can choose the optimal number of clusters for this data instead of  predefining the number of clusters to be 5
Comment: @læran91 Hopefully this will be answered in response to your [other](https://stats.stackexchange.com/questions/316628/how-to-get-pixel-matrixrgb-values-for-the-elbow-plot) question.
Comment: hmm.yeah.but Thank you @C.E for you help :)


Error getting the output of child process in node

Question: I have a c program (I didn't code it) that prints some data in the terminal. I launch the program as a child process in node with the spawn function.
const child_process = spawn('./myProgram', ['--arg']);

After that, I code the event to get the printed data:
child_process.stdout.on('data', function(data) {
        console.log(data);
});

When I run the program I can't see the output data from my c program in my nodejs terminal. If I initialize the child process with stdio as inherit it works.
const child_process = spawn('./myProgram', ['--arg'], {stdio :'inherit'});

The key point here is that I need to process that data in my nodejs app. I suppose the way the c file prints the data is not the standard one, so my nodjs program does not get it.
Comment: Shouldn't that be `child_process.stdout.on(...)`?
Comment: Yes, you are right. I missed out typing the question.
Comment: Does this work with other programs? A simple test is like `spawn('ls')`.
Comment: Another thing to check is that you're not getting any errors, or that it's not outputting to `stderr` instead.
Comment: It works. The problem is with that c program. I have also created my own c program to test it and works.
Comment: Remember there's both STDOUT and STDERR, there's *two* output streams. Check both. They will look the same in a terminal, but `program > /dev/null` will suppress just STDOUT.
Comment: @tadman You are right. It was outputting to the 'stderr'. Thanks for your help!
Answer: The file was outputting to stderr instead to stdout. It was fixed by adding the event to stderr:
child_process.stderr.on('data', function(data) {
        console.log(data);
});

@tadman got the answere.


Aligning divs side by side - angular

Question: I have been trying to align my responses or data side by side in my panel but that would work out for me. What could i be doing wrong. I know this is very basic but i am a beginner. i want the the div in light blue to align just as the creamish div.  please help

    //light blue

  {{client.line_text}}
   {{client.from}} | {{client.created_at}}

//creamish

    {{client.line_text}}
   {{client.from}} | {{client.created_at}}

Answer: since you´re using pull-right I am assuming youre using you are using bootstrap,
you problem is the pull-right class makes it float to the right so it starts stacking sideways
I would suggest to use the grid system of bootstrap to make 2 columns and stack the divs there a.e.
like this:

      Text Here

      Text Here

      Text Here

      Text Here

https://jsfiddle.net/xb9Ljxrv/
so you seperate the both parts in two even columns and fill them instead of floating to the right
which gives you a output like this

Aligning divs side by side - angular


How to check if my other apps are installed on iOS 10?

Question: Until iOS 9, we were able to use canOpenURL method to check if there are apps who can handle specific URL schemes, thus it was widely used to check if a specific app was installed by user.
Now, since iOS 9, we have to declare upfront the URL Schemes that can be checked by the app. This is cool in general, but it means that for every release of a new app, we would have to update previous apps to be able to check if the new one is installed or not.
Is there any sane way to do it now?
I guess most of the ads and cross promotion services out there relies on this and had to adapt somehow, anyone knows how?
Thanks
Krystian
Comment: @Krystian, you say _"I download a list of apps from server and check which ones are installed. Now that won't be possible."_, but you don't see the same case from a most important perspective: the __end-user's privacy__. Apple explicitly tries to prevent developers to violate the end-user's privacy uncontrollably so if the developers intend to collect marketing information about the device, Apple wants to keep that under control as much as possible; that is what you are facing to here.
Comment: @Krystian, c'mon. Q: why would an app like to check the other installed app dynamically on certain devices in background? A: _marketing purpose_ and who knows what else you would collect in your app about the end-user and building a huge database using or selling to third parties. the control is if your app suspiciously monitors that in that background, and that is clearly not related to your app's original purpose (e.g. harmless dating-app where users share more private information about themselft via), Apple will be able to disable your app remotely immedetaly undoubtably. you are funny. :)
Comment: @Krystian, you can update your app as many times you'd like to, extending the `info.plist` file and going through the review procedure each occasion; nobody prevents you to do so, but the developers (especially app-developer companies) won't be able to embed such hidden features into their client's applications anymore to take advantages of someone else's applications for their own benefits. that is very simple to understand, you don't need to victimise yourself, you may not do any harm and you also have a legal way to work around this issue – under a strict control by Apple.
Comment: @Krystian, let's go back in time: at first e.g. the UDID was available for anyone to indetifiy the user (=device), but app devs started using it for tracking the device only and purchasing-selling behaviours of people; then Apple stopped granting access to UDID. another example the `SKProduct` could have been generated programmatically by devs and they tricked the end-user by showing a lower _tier_ for the purchase than the actual payment was; Apple started giving access `SKProduct` only via StoreKit; and the list goes on, but it may show the violations in past and how Apple corrected it.
Comment: @Krystian, and the current situation is pretty much the same category; even if _you_ are using it responsibly, it does not mean everyone does, and Apple just changes the rules to protect their consumers' privacy. you (or I) may have different views about _privacy_ than Apple does but they don't care about devs at all, everything which they do or will do is for their consumers' best interests only. it can be a long conversation, but I don't want to _off_ this thread, I only hope I could show the point and the basic pricipal behind it.
Comment: One of the way is that use the website URL to open that App for example http://map.apple.com will open Apple Maps. This creates a dependency on the other app developers.
Comment: @New16 but it's my own check. I need to know if my other apps are installed or not and I would like to control this without republishing my app. I download a list of apps from server and check which ones are installed. Now that won't be possible.
Comment: I don't think so there is any other way. The next would be to use MDM concepts, which is not a feasible solution at all.
Comment: How would you imagine a MDM would work in regards of ios privacy policies? There's no way to match a single user/device only by starting an app.
Comment: @holex nope.. I think your and Apple's views are very limited. End user's privacy is not violated in any way in my case. The whole thing is intended to improve their experience with the apps. Apple does not want to keep that under control, they have disabled the ability and that's it. There's no control here. They are only forcing me to update apps I would not need to update. The only reason of the update is to add a single entry to the Info.plist file. Where's privacy control here?
Comment: @holex no you are funny. There's nothing blocking me from doing that, I just have to update the app to include more and more schemes. Just because dynamite can be used to make harm, it's not the only way it can be used. Seriously, open your eyes.
Comment: @holex i understand that. I fail to understand though, about what developer control are you talking about? Preventing other devs from taking advantage of one's app. What's that suppose to mean? Is there a list one can sign up to,which says 'don't use my scheme'?
Answer: Ok, so to recap.
Currently, the only way to handle my scenario, is to assign a specific scheme per app in an orderly fashion, for example:
my.domain.app01
my.domain.app02
...

If you have apps already released, just update them to add a new, additional scheme.
Now in Info.plist file, you will have to add all of your existing and future schemes to LSApplicationQueriesSchemes list in Info.plist.
The idea is: even though you have 10 apps released, you add entries for let's say 40. This way, you will not have to update your app to add schemes for future apps, they will already be there and you will be able to detect them.
This of course covers my scenario, where I want to be able to detect my own apps and make use of them.
Remember, that your app can handle more than one scheme, so you can assign the internal scheme + use something better named to allow external access to your app.


On whether reducts and axioms commute.

Question: Consider theories $T$ and $T'$, where $T$ is a subset of $T'$, in the same language $L$. Also, let $L'$ be a subset of the language $L$. We can either take the reduct of $T$ or the reduct of $T'$ with $L'$. Would it be the case that the reduct of $T$ is a subset of the reduct of $T'$?
Comment: Well, with the current Covid-19 crisis they are working from home. So no commuting.
Answer: If $T$ is a theory, the reduct of $T$ to the language $L'$ is $T\cap \mathrm{Sent}(L')$, where $\mathrm{Sent}(L')$ is the set of $L'$-sentences.
If $T\subseteq T'$, then $(T\cap \mathrm{Sent}(L'))\subseteq (T'\cap \mathrm{Sent}(L'))$.
(This is just elementary set theory: If $X\subseteq Y$, then for all $Z$, $(X\cap Z)\subseteq (Y\cap Z)$.)
Answer: Yes, since the reducts of $T$ and $T'$ are still the same sets, with some of the logical structure removed. Any embedding $\pi: T \to T'$ will still be an embedding between the reducts.
Misread the question. @AlexKruckman's answer is correct.
Comment: $T$ and $T'$ are theories, not models. What is an embedding $T\to T'$?
Comment: Also, I'm not sure what you mean by "the same sets, with some of the logical structure removed". I think you interpreted $T$ and $T'$ to be models...
Comment: @AlexKruckman you're dead right.

On whether reducts and axioms commute.


Global existence ODE

Question: I have a question regarding the exercise below. Sorry if I am not writing it in LaTex but it would be a mess to rewrite all this. I do not understand why, at point b) the author writes: We surely have global existence for all initial $k_0 ∈ [0,k_2]$ while this is not guaranteed for $k_0 > k_2$. Why is this true?
Comment: I removed the stochastic calculus tag because it has no relevance here. Do you know conditions under which you have global existence? Do you know any examples where global existence fails? Can you see why they resemble the case $k_0 > \bar{k}_2$?
Comment: Global existence means that a particilar solution holds for any $t \in T$. Perhaps here he is referring to the fact that we have global existence at least at right for every $ t \in T$ because any solution converges to $k_2,k_1,k_0$ in finite or infinite time. Could you help me, please?
Answer: In order not to have global existence, the solution $k(t)$ would have to blow up in finite time. But if the solution starts in the interval $[0,k_2]$, it can't get out of that interval (since it can't cross the equilibrium solutions), so that can't happen.
On the other hand, if you start to the right of $k_2$ it may perhaps happen that $k(t) \nearrow +\infty$ as $k \nearrow T$, for some finite time $T$.

Global existence ODE


How to remove every nth byte from a byte array?

Question: Say I have a byte array like
<code> byte[] bytes = {69, 121, 101, 45, 62, 118, 101, 114, 195, 61, 101, 98};
</code>
How can I remove every nth byte from this byte array? If n = 3 then result should be every multiple of 3 ( starting from index 0 => 3, 6 ,9 12 and so on). So 45, 101, 61.. nth.
Do I need to use System.arraycopy with a new holder array?
Comment: `195` can't be added to `byte` array, max value for byte is `127`.
Comment: To answer to "Do I need to use System.arraycopy with a new holder array?": No.  You specifically need **not to use** `System.arraycopy`.  `System.arraycopy` is for copying a  _block_ of elements; you need to copy individual elements one at a time.
Comment: You can't remove anything from a byte array. You can only replace the value stored at a given index by another value. If you want to create a new array, with all the original values except some, then do just that. If you know about loops, division and the modulo operator, this should be easy enough. Try something.
Comment: Please show us some effort and btw. this isn't even a valid byte array.
Comment: I have downvoted this question because it appears to be a zero-effort requirements dump.  If you can [edit] your question to show us a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) of your attempt, or to clarify *precisely* where you are having difficulty, this downvote may be retracted.
Answer: First, YOU must try to put some effort in coding and show us the result of your trying so we can help you...
That code will give you a new array without the nth elements:
<code>    byte[] bytes = { 69, 121, 101, 45, 62, 118, 101, 114, 127, 61, 101, 98 };
    int n = 3;
    List<Byte> byteList = new ArrayList<Byte>();

    for (int i = 0, j = n; i < bytes.length; i++) {
        if (i == j) {
            j += n;
            continue;
        }
        byteList.add(bytes[i]);
    }

    // if you want to return the code to a byte[]
    byte[] newByte = new byte[byteList.size()];
    for (int i = 0; i < byteList.size(); i++) {
        System.out.println( byteList.get(i));
        newByte[i] = byteList.get(i);
    }

   // Or you can use toArray method
   // Byte[] newByteArray = byteList.toArray(new Byte[byteList.size()]);
</code>
Sample output:
<code>69
121
101
62
118
114
127
101
98
</code>
Comment: I guess this is not what OP wanted. He would like to remove every nth byte from a byte array. not to acquire data every nth byte from a byte array instead.


How to evaluate $\frac{1}{\sinh^4(x\pm i\epsilon)}$?

Question: I should evaluate the following expression for $\epsilon\rightarrow 0^+$:
$$\frac{1}{\sinh^4(x\pm i\epsilon)}$$
I know that $\frac{1}{x\pm i\epsilon}=P\frac{1}{x}\mp\delta(x)$, so I tried to obtain something similiar. I started by exploiting the identity $\sinh(a+b)=\sinh(a)\cosh(b)+\cosh(a)\sinh(b)$ and then I expanded in Taylor series around $\epsilon=0$, keeping (after evaluating the power) only the first two terms. In this way I get, after a "rationalitazion":
$$\frac{1}{4\cosh(x)\sinh^3(x)}\frac{\frac{1}{4}\tanh(x)\mp i\epsilon}{\frac{1}{16}\tanh^2(x)+\epsilon^2}$$
After this point, however, I do not know how to continue. Honestly I am not even sure that neglecting the $O(\epsilon^2)$-terms is correct, since $\sinh(x)$ could be equal to zero.
Comment: Isn't it $\frac{1}{\sinh^4(x)}$?
Comment: @Gary do you mean the final result? There should be also a derivate of a Dirac's delta
Comment: Are you missing an integral in your question?
Comment: Nope. Unless you don't want to evaluate it by evaluating its action on another, generic, function, like $\int\frac{1}{\mathrm{sinh}^4(x\pm i\epsilon)}f(x)$ @Gary
Comment: For $\operatorname {csch}^4(x + i \epsilon) - (x + i \epsilon)^{-4} + (2/3) (x + i \epsilon)^{-2}$, the distributional limit and the pointwise limit are the same, so the structure of the result is a regular distribution plus $(x + i0)^{-n}$ terms. If we want to use $x^{-n}$ instead of $(x + i0)^{-n}$, with $x^{-n}$ defined as $(-1)^{n - 1}/(n - 1)!$ times the distributional derivative of order $n - 1$ of $\mathcal P(1/x)$, we have
$$(x + i0)^{-n} =
x^{-n} - \pi i \frac {(-1)^{n - 1}} {(n - 1)!} \delta^{(n - 1)}(x).$$
Comment: @Maxim Thank you very much
Answer: If you start with
$$\sinh (x+i \epsilon )=\sinh (x)+i \epsilon  \cosh (x)-\frac{1}{2} \epsilon ^2 \sinh
   (x)-\frac{1}{6} i \epsilon ^3 \cosh (x)+O\left(\epsilon ^4\right)$$ Using multiple angle formulae
$$\sinh^4 (x+i \epsilon )=\sinh ^4(x)+4 i \epsilon  \sinh ^3(x) \cosh (x)+\epsilon ^2 (\cosh (2
   x)-\cosh (4 x))+\frac{2}{3} i \epsilon ^3 (\sinh (2 x)-2 \sinh (4
   x))+O\left(\epsilon ^4\right)$$ Now long division
$$\frac 1 {\sinh^4 (x+i \epsilon)}=\text{csch}^4(x)-4 i \epsilon  \coth (x) \text{csch}^4(x)-2 \epsilon ^2
   \left((2 \cosh (2 x)+3) \text{csch}^6(x)\right)+\frac{4}{3} i \epsilon
   ^3 (13 \cosh (x)+2 \cosh (3 x)) \text{csch}^7(x)+O\left(\epsilon
   ^4\right)$$  that is to say
$$\text{csch}^4(x)\Big[1-4 i \epsilon  \coth (x)-2 \epsilon ^2 \left((2 \cosh (2 x)+3)
   \text{csch}^2(x)\right)+O\left(\epsilon ^3\right) \Big]$$
If you try for $x=1$ and  $\epsilon=0.01$ the above truncated series gives $(0.523466\, -0.0275352 i)$ while the exact value is $(0.523467\, -0.0275178 i)$.
Edit
If you consider the  series expansion of $\text{csch}^4(x+\delta )$ around $\delta=0$ you could transform it into the simplest Padé approximant and obtain
$$\text{csch}^4(x+\delta )=\text{csch}^4(x)\,\,\frac {\sinh (2 x)-\delta  \,(2 \cosh (2 x)+1) }{\sinh (2 x)+\delta\,  (2 \cosh (2 x)+3) }$$ Just make $\delta=\pm i\epsilon$ got get the result.
For the worked example, this gives $(0.523467\, -0.027512 i)$


How to insert Mysql with limit and Continue using foreach PHP?

Question: I have 100k data. My server is only able to insert 20k data. How do you insert data with a limit then insert again until 100k data is inserted
code :
 $url_setting = LIBRARY_PATH.'data/uploads/document/dataSettin.json';
 $jsondata_setting = file_get_contents($url_setting);
 $data_setting = json_decode($jsondata_setting, true);

foreach ($data_setting as $key=>$row)
{
$insert_sql = array(
   'PROMO_CODE' => $row['PROMO_CODE'],
   'PROMO_NAME' => $row['PROMO_NAME'],
   'DISCOUNT_TYPE' => $row['DISCOUNT_TYPE'],
   'PROMO_PRIORITY'=> $row['PROMO_PRIORITY'],
   'PROCESS_TYPE'  => $row['PROCESS_TYPE'],
   'PROMO_STATUS'  => $row['PROMO_STATUS'],
   'CREATED'       => $row['CREATED'],
   'CREATEDBY'     => $row['CREATEDBY'],
   'UPDATED'       => $row['UPDATED'],
   'UPDATEDBY'     => $row['UPDATEDBY'],
                  );
  $db->insert('M_PROMO_SETTING', $insert_sql);
}

I've tried inserting 20k data, success. But more than 20k data an error occurs
Comment: If I were you, I will generate a CSV with PHP, and let MySQL to import the CSV file via `LOAD DATA INFILE 'path/to/data.csv' INTO TABLE ...` command.
Comment: MySQL doesn't have such a small limit on the amount of data you can insert. Databases can store many gigabytes of data. What error are you getting when you try to store more than 20k?
Comment: You can only hit such kind of limits if you pack several rows into a single `INSERT` statement, and you don't seem to be doing that. My guess is that you're loading and decoding your entire data set into RAM and PHP runs out of memory, and perhaps you haven't configured PHP to [report errors](https://phpdelusions.net/articles/error_reporting) so blaming MySQL is a guess.
Answer: We can insert bulk data into a database using for-loop pagination logic. We need to find the total number of pages using the total records and the total number of records we want to insert in one request.
You can refer below function

function processInsertData()
{
    $totalRecords = 100000;
    $pageLimit = 100;
    $totalPages = math.ceil($totalRecords/$pageLimit);
    $currentPageNumber = 1;

    for(let i=$currentPageNumber; i <=$totalPages; i++ ){
      // get data using current page number and record $pageLimit
      //if you are fetching from CSV then read from total records fetched from CSV
      //if you are using another table and use page page and page limit in sql LIMIT case

      // For example we are reading data from csv
      echo "Current page".$currentPageNumber." Out of ".$totalPages;
      $fetchedRecords = [];
      if(count($fetchedRecords)>0){
        $insertResponse = insertData($fetchedRecords);
        if($insertResponse){
          // increment page size by 1
          $currentPageNumber++;
        }
      }
      else {
        echo "All data inserted successfully";
      }
    }
}


Secured communication between two web servers (Amazon EC2 with Django and Google App Engine)

Question: I have a website which uses Amazon EC2 with Django and Google App Engine for its powerful Image API and image serving infrastructure. When a user uploads an image the browser makes an AJAX request to my EC2 server for the Blobstore upload url. I'm fetching this through my Django server so I can check whether the user is authenticated or not and then the server needs to get the url from the App Engine server. After the upload is complete and processed in App Engine I need to send the upload info back to the django server so I can build the required model instances. How can I accomplish this? I was thinking to use urllib but how can I secure this to make sure the urls will only get accessed by my servers only and not by a web user? Maybe some sort of secret key?
Answer: apart from the Https call ( which you should be making to transfer info to django ), you can go with AES encryption ( use Pycrypto/ any other lib). It takes a secret key to encrypt your message.
Answer: For server to server communication, traditional security advice would recommend some sort of IP range restriction at the web server level for the URLs in addition to whatever default security is in place. However, since you are making the call from a cloud provider to another cloud provider, your ability to permanently control the IP address of either the client and the server may diminished.
That said, I would recommend using a standard username/password authentication mechanism and HTTPS for transport security. A basic auth username/password would be my recommendation(https:\\username:firstname.lastname@example.com\). In addition, I would make sure to enforce a lockout based on a certain number of failed attempts in a specific time window. This would discourage attempts to brute force the password.
Depending on what web framework you are using on the App Engine, there is probably already support for some or all of what I just mentioned. If you update this question with more specifics on your architecture or open a new question with more information, we could give you a more accurate recommendation.
Answer: SDC provides a secure tunnel from AppEngine to a private network elsewhere -- which could be your EC2 instance, if you run it there.


Problema com inserção de dados em tabela via laravel

Question: Estou com um projeto em laravel ao mesmo tempo que aprendo a usar a framework, preciso inserir um determinado valor em um campo de uma tabela, para isso existe uma condição que coloquei no controller:
public function setExpert()
{
    if($concessionaria->user_id = 0)
    {
        $concessionaria->expert = 0;
        $concessionaria->save();
    }
    else
    {
        $concessionaria->expert = 1;
        $concessionaria->save();
    }

A ideia é criar um botão em que um especialista possa deixar de ser especialista em uma concessionaria, para isso criei uma condição que se já exista um especialista em uma determinada concessionária o valor de um campo booleano seja setado como 0(não_tem_especialista, isso quando ele apertar esse botão) automaticamente, e se não exista será setado como 1(ao apertar o botão), não sei se ficou claro, se for necessário eu explico denovo.
Essa é a model com os dados que preciso:
class ConcessionariaDelete extends Model
{
public $table = "concessionaria";

public $fillable = [
    'user_id',
    'expert',
    'nome',
    'expert_da_concessionaria',
    'slug',
    'tipo',
    'area',
    'cep',
    'endereco',
    'view_count',
    'status',
    'created_at',
    'updated_at'
];

Esses são os campos que precisam ser alterados
O que eu fiz criar foi uma model para gerenciar a tabela do banco de dados, e um controller ligado a model com as condições para setar se é ou não especialista, o meu problema esta sendo para executar a função, eu preciso só recarregar a pagina? é necessário colocar ela em alguma pagina para ser executada? Eu não entendi corretamente como faço para as condições do meu controller fazerem alterações no meu banco de dados.
Comment: Posso te ajudar, mas antes preciso entender um pouco melhor a estrutura do seu projeto. Cada concessionária terá apenas um especialista? Quais são as ações que esse especialista fará dentro do seu projeto?
Comment: A ideia é que cada concessionaria tenha 3 especialistas, ele se torna especialista a partir de pontos que ele faz no decorrer da carreira, mas ainda não fiz um botão para deixar de ser especialista, pretendo usar a função setExpert() em um botão feito em javascript via ajax, o problema é que não estou conseguindo atribuir essa função ao botão, e mesmo que consiga não sei se vai funcionar, acredito que apenas de eu recarregar o meu banco de dados já deveria aparecer as mudanças que condicionei em setExpert().
Comment: Tem que ver os demais campos não são obrigatórios se for é preciso passar no cadastro caso seja um update está errado
Answer: o Eloquent não deve estar identificando a chave primária da tabela.
class ConcessionariaDelete extends Model
{
 ...
 protected $primaryKey = "sua chave primária"
 ...

Comment: Não é preciso especificar se o nome for ID o laravel interpreta já o ID como primaryKey
Answer: Caso seja um update segue um exemplo:
public function setExpert($id)
{
   $concessionaria =  Model::find($id);
   if($concessionaria->expert === 0){
        $concessionaria->expert = 0;
   }else{
     $concessionaria->expert = 1;
   }

   $concessionaria->save();

}


How long does a player stay in the ICC rankings for once no longer appearing for the national side?

Question: Batsmen and bowlers have an individual rating between 0-1000 based on performances, and naturally their ratings drop for each game missed.
Is their a specific time period after which their rating disappears completely?
I remember Brett Schultz being on the old PWC rankings for at least two years after his last appearance for South Africa, and Kevin Pietersen is England's third highest batsman 18 months after playing his last test.
Answer: The ICC Rankings FAQ notes that

Players have to have appeared in a match within the qualifying period to appear in the lists (normally 12-15 months for Tests [...])

As such, Pietersen would not "normally" count as qualified for the rankings. I don't know if this is because he's being treated as a special case due to his... unique relationship with the England cricket team, or just because it hasn't been removed yet and that will happen sometime this summer.


Is this rhythm called a salsa or samba or something else?

Question: Is there a name for this little beat?
<code>         main: .--.|--.-|--.-|-.--
accompaniment: .-.-|.-.-|.-.-|.-.-
</code>
(a dot is a hit and a dash is a rest)
Sorry for the makeshift notation and lack of terms, I'm not doing a great job at conveying this question... I hope my message gets through...
Answer: What you wrote down is the clave of a ryhthm called Bossa Nova, although you usually write it as two bar pattern. It's a Brasilian rhyhthm pretty close to samba, mostly slower.
Comment: Bah, ignore my previous comments, I see that Wikipedia has the beat there in a little image.  +1!
Comment: Perfect, that's exactly what I was looking for but couldn't remember.
Answer: do you mean a son clave ? usally it is  something  with  3 against 2 or  2-against 3
http://en.wikipedia.org/wiki/File:Son_and_rumba_clave.png
or
X . . X . . X . . . X . X . . .
Answer: This is a very typical bossa nova 'clave'.
XooX ooXo ooXo oXoo
It comes up in samba sometimes too, depending on the batucada—some schools play this rhythm in accents in their caixas.


Connected planar simple Graph: number of edges a function of the number of vertices

Question: Suppose that a connected planar simple graph with $e$ edges and $v$ vertices contains no simple circuit with length greater than or equal to $4.\;$ Show that $$\frac 53 v -\frac{10}{3} \geq e$$
or, equivalently, $$5(v-2) \geq 3e$$
Comment: I believe I've seen this before, just can't remember the proof off the top of my head, but $$5 \cdot v - 10 \geq 3 \cdot e$$ definitely looks familiar O_o...
Answer: As Joseph suggests, one of two formulas you'll want to use for this problem is Euler's formula, which you may know as
$$r = e - v + 2 \quad\text{(or}\quad v + r - e = 2)\qquad\qquad\quad (1)$$
where $r$ is the number of regions in a planar representation of $G$ (e: number of edges, v: number of vertices).  (Note, for polyhedra which are clearly not planar, this translates into $r = F$, where $F$ is the number of faces of a polyhedron.)
Now, a connected planar simple graph drawn in the plane divides the plane into regions, say $r$ of them. The degree of each region, including the unbound region, must be at least five (assuming graph $G$ is a connected planar graph with no simple circuit with length $\leq 4$).
For the second formula you'll need: remember that the sum of the degrees of the regions is exactly twice the number of edges in the graph, because each edge occurs on the boundary of a region exactly twice, either in two different regions, or twice in the same region.  Because each region $r$ has degree greater than or equal to five, $$2e = \sum_{\text{all regions}\;R} \mathrm{deg}(R) \geq 5r\qquad\qquad\qquad\qquad (2)$$
which gives us $r \leq \large\frac 25 e$.
Now, using this result from (2), and substituting for r in Euler's formula, (1), we obtain $$e - v + 2 \leq \frac 25 e,$$
$$\frac 35 e \leq v - 2,$$
and hence, we have, as desired: $$e \leq \frac 53 v - \frac {10}{3} \quad\iff \quad \frac 53 v - \frac{10}{3} \geq e \quad \iff \quad 5(v-2) \geq 3e$$
Answer: Try using Euler's "polyhedral formula" - If G is a connected plane graph then V + F - E = 2.


Solve by means of regular perturbation to obtain an approximate solution up to and including $\mathcal{O}(\epsilon^2)$

Question:
I have to solve the following ODEs:

$y''+ y = e^{\epsilon \cos x}$, $y(0,\epsilon)=y(1,\epsilon)=0$;
$y''+ y = \epsilon y^2$, $y(0,\epsilon)=1$, $y'(0,\epsilon)=0$.

I am having trouble with these two questions.
For the first one, I got:
\begin{align}
y''_0 + y_0 &=1,& y_0(0)&=y_0(1)=0\\
y''_1 + y_1 &= \cos x,& y_1(0)&=y_1(1)=0
\end{align}
Not sure where the $\cos x$ is from.
For the second question, unsure how $y_0(x)=\cos x$
and $y_1(x)=1/2-1/3(\cos x)-1/6(\cos 2x)$
Comment: Welcome to MSE. Please read this text about [how to ask a good question](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question).
Answer:
) You can write the right side as series expansion in $ϵ$, that is, insert the series for the exponential function
$$
e^{ϵ\cos x}=1+ϵ\cos x+\frac{ϵ^2}2\cos^2 x+\frac{ϵ^3}6\cos^2 x+...
$$
) The initial equation is the harmonic oscillator
$$
y_0''+y_0=0,~~y_0(0)=1,~~y_0'(0)=0
$$
which has $y_0(x)=\cos(x)$ as solution. The next equation of the terms of first order in $ϵ$ is
$$
y_1''+y_1=y_0^2,~~y_1(0)=1,~~y_1'(0)=0
$$
and $\cos^2x$ is as is well-known equal to $\frac12(1+\cos(2x))$. Apply the method of undetermined coefficients to find the corresponding particular solution.
Comment: solving y''+y=0 gives me: c1cos(x)+c2sin(x)

and solving for the particular integral: substituting acos(x)+bsin(x) back into the ODE:

y= acos(x)+bsin(x)
y'=-asin(x)+bcos(x)
y''=-acos(x)-bsin(x)
plugging this into the ODE would just cancel and leave 0=cos(x)

So, how does the solution give y=1/2sin(x)
Comment: Now apply variation of constants or undetermined coefficients to find a particular solution for the right side $1$.


Finding the minimum number of transaction

Question: The problem,

There are $1024$ people. Each person is having $1024$ similar fruits. No
  two persons are having same kind of fruits. Find the minimum number of
  transactions required so that each-person is having $1024$ different
  kinds offruits. Note that a single transaction is defined as exchange
  of any number of fruits between any two persons.

The suggested solution is as follows:

If $2$ people having $2$ fruits each then only one transaction will be
   required. If $4$ people having $4$ fruits each then $2 \times 2$
   transactions are required. $8$ people having $8$ fruits each then $3
 \times 4$ transactions will be required.Like this for $1024$ we would
  need a minimum of $10 \times 2^9 = 5120$

But I am not sure that I can fully construe this.Lets denote the fruits by alphabets,For two people initially we have
aa  bb

Hence,only one exchange of 'a' with 'b',will make it
ab  ab

But when when we have four people then,
aaaa bbbb cccc dddd

I tried but I could not make this to
abcd abcd abcd abcd

in only $4$ steps,could anybody show me how to do this in $4$ steps?
Answer: aaaa bbbb cccc dddd ==> 1st and 2nd person exchanging two fruits
aabb aabb cccc dddd ==> 3rd and 4th person exchanging two fruits
aabb aabb ccdd ccdd ==> Person 1 gives an a and a b to person 3, and vice versa
abcd aabb abcd ccdd ==> Similar for 2 and 4
abcd abcd abcd abcd.
Answer: In the first round do the transactions:

aaaa + bbbb $\to$ aabb + aabb (trading aa for bb)
cccc + dddd $\to$ ccdd + ccdd (trading cc for dd)

After this in the second round two pairs of people can do the transaction

aabb + ccdd $\to$ abcd +abcd (trading ab for cd)

Four transactions total. Apply a bit of recursive thinking.


Use of unresolved identifier NSSecondCalendarUnit in Swift

Question: I try to fetch hours minutes from current date:
var date:NSDate = NSDate()
        var calendar:NSCalendar = NSCalendar.currentCalendar()
        var components:NSDateComponents = calendar.components(unitFlags: NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit, fromDate: date)
        var hour = components.hour
        var minute = components.minute
        var seconds = components.second

However it doesn't recognize Calendar Units:
NSHourCalendarUnit, NSMinuteCalendarUnit andNSSecondCalendarUnit

I get error:
use of unresolved identifier NSSecondCalendarUnit ...

Do I miss something?
Answer: Use NSCalendarUnit constants instead
var date:NSDate = NSDate()
        var calendar:NSCalendar = NSCalendar.currentCalendar()
        var components:NSDateComponents = calendar.components(
            NSCalendarUnit.CalendarUnitHour | NSCalendarUnit.CalendarUnitMinute | NSCalendarUnit.CalendarUnitSecond, fromDate: date)
        var hour = components.hour
        var minute = components.minute
        var seconds = components.second

Reference:
From NSCalendar class
func components(unitFlags: NSCalendarUnit, fromDate date: NSDate!) -> NSDateComponents!
                             ^^^^^^^

Comment: With Swift 2.0 you have to use the following syntax for line #3 above:
var components:NSDateComponents = calendar.components([.Hour, .Minute, .Second], fromDate: date)


Elementary embedding between infinite atomic Boolean algebras

Question: Let $S$ be an infinite set of atoms and let $At(S)$ be the infinite atomic Boolean algebra generated by $S$.
Now suppose we expand $S$ to $S'$ by adding some other atoms, and let $At(S')$ be the infinite atomic Boolean algebra generated by $S'$.
Let $\mathscr{L}$ be the language of Boolean algebra and $T$ be the theory of infinite atomic Boolean algebra in $\mathscr{L}$. $At(S)$ and $At(S')$, as models of $\mathscr{L}$, are both models of $T$ (and hence they are elementarily equivalent). Now my question is: is $At(S)$ an elementary submodel of $At(S')$, in the sense that for any $\phi(x_1, ..., x_n)$ of $\mathscr{L}$, and $a_1, ..., a_n \in At(S)$,
$$At(S) \models \phi(x_1, ..., x_n)[a_1, ..., a_n] \, \, \text{iff}\, \, At(S') \models \phi(x_1, ..., x_n)[a_1, ..., a_n]$$
I can see that $At(S) $ is definitely a submodel of $At(S')$, but I struggle about the quantified forlumas.
Answer: (Below, given a set $X$ let $\mathsf{At}(X)$ be the atomic Boolean algebra generated by $X$.)
Yes, as long as $S$ is infinite we have $\mathsf{At}(S)\preccurlyeq\mathsf{At}(S')$ whenever $S\subseteq S'$. The easiest way to see this in my opinion is via the following two facts:

Fact $1$ (Tarski-Vaught): To show $\mathcal{X}\preccurlyeq\mathcal{Y}$ it's enough to show that whenever $\overline{a}\in\mathcal{X}$ and $\varphi$ is a formula such that $\mathcal{Y}\models\exists\overline{x}\varphi(\overline{x},\overline{a})$, there is some $\overline{b}\in\mathcal{X}$ such that $\mathcal{Y}\models\varphi(\overline{b},\overline{a})$.

Fact $2$: Suppose $A,B,C,D$ are sets with $A\subseteq B\cap C$, $\vert B\vert=\vert C\vert$, $B,C\subseteq D$, and $\vert D\setminus B\vert=\vert D\setminus C\vert$. Then there is an automorphism $\alpha$ of $\mathsf{At}(D)$ which is the identity on $\mathsf{At}(A)$ and restricts to an isomorphism $\mathsf{At}(B)\cong\mathsf{At}(C)$.

The proof of Fact $1$ can be found on the wiki page linked above, and I'm going to leave the proof of fact $2$ as an exercise since it's a bit tedious. The point is that as long as $S$ is infinite we can combine these to show $\mathsf{At}(S)\preccurlyeq\mathsf{At}(S')$ as follows:
Fix a finite tuple of elements $\overline{a}\in \mathsf{At}(S)$ and a formula $\varphi(\overline{x},\overline{y})$ such that $\mathsf{At}(S')\models\exists\overline{x}\varphi(\overline{x},\overline{a})$. We want to find some $\overline{c}\in\mathsf{At}(S)$ such that $\mathsf{At}(S')\models\varphi(\overline{c},\overline{a})$ (if we can do this we'll be done by Fact $1$ above). Let $\overline{b}\in\mathsf{At}(S')$ be such that $\mathsf{At}(S')\models\varphi(\overline{b},\overline{a})$; since $S$ is infinite and $\overline{a}$ is finite we can apply Fact $2$ to get an automorphism of $\mathsf{At}(S')$ which fixes $\overline{a}$ and sends $\overline{b}$ to some $\overline{c}\in\mathsf{At}(S)$. Since automorphisms preserve first-order truth, we're done.

EDIT: actually, the third fact comes up in the above and is probably worth mentioning explicitly:

Fact $3$: The "$\mathsf{At}(\cdot)$-construction" is locally finite, in the sense that for all $X$ we have $$\mathsf{At}(X)=\bigcup_{F\subseteq X\mbox{ finite }}\mathsf{At}(F),$$ and so in particular for every finite tuple $\overline{a}\in\mathsf{At}(S)$ there is some finite $F\subseteq S$ with $\overline{a}\in\mathsf{At}(F)$ (since the finite union of finite sets is finite).

This gets to the precise definition of $\mathsf{At}(\cdot)$. The key is that elements of $\mathsf{At}(X)$ are recursively built up via taking finite joins and meets (and complements); if we take arbitrary joins and meets we wind up building the complete atomic Boolean algebra generated by $X$, $\mathsf{At_{comp}}(X)$, which is a different object. Now as it happens we still have $\mathsf{At_{comp}}(S)\preccurlyeq\mathsf{At_{comp}}(S')$ when $S\subseteq S'$ and $S$ is infinite, since in fact $\mathsf{At}(X)\preccurlyeq\mathsf{At_{comp}}(X)$ holds for all $X$, but this takes a different argument than the above (which crucially uses local finiteness).
In fact, at this point it's probably worth being explicit. There are a few different concrete constructions which can be used here; I think the following are the simplest:

$\mathsf{At_{comp}}(X)$ is the powerset Boolean algebra on $X$; elements of $\mathsf{At_{comp}}(X)$ are subsets of $X$, and the join/meet/complement operations are just union/intersection/complement.

$\mathsf{At}(X)$ is the subalgebra of $\mathsf{At_{comp}}(X)$ consisting of all sets which are either finite or cofinite. For each $a\in\mathsf{At}(X)$ we can pick out a finite piece of $X$ as being "important" for $a$, namely $a$ itself if $a$ is finite and $X\setminus a$ if $a$ is infinite.
Comment: Thanks so much! I have two remaining questions: (1) For the proof to work I think we need $a_1, ..., a_n \in At(S)$ instead of just $a_1, ..., a_n \in S$, and there is no guarantee that $a_1, ..., a_n$ are all generated by a finite subset of $S$. (2) Similarly, in order to apply Fact 2, I think we need that $b_1, ..., b_n$ are generated by a subset of $S'$ that is at most as big as $S$. But how can we make sure this?
Comment: @SeverineClimacus "For the proof to work I think we need $a_1,...,a_n\in \mathsf{At}(S)$" Quite right, that was a silly typo - fixed! "there is no guarantee that $a_1,...,a_n$ are all generated by a finite subset of $S$" Actually **there is**! Can you show that, for every $X$, we have $$\mathsf{At}(X)=\bigcup_{F\subseteq X\mbox{ finite}}\mathsf{At}(F)$$ (and so every finite *tuple* of elements is generated by some finite set of atoms since a finite union of finite sets is finite)?
Comment: @SeverineClimacus I've updated my answer to include this third fact.
Comment: I see. Thanks! Actually I'm also really curious about why $At_{comp}(S)$ is also a elementary submodel of $At_{comp}(S)$. Do you mind to elaborate on that? That is actually the question I had in mind when I asked the question. I've updated my question to include this. Thanks so much!
Comment: @SeverineClimacus I think you should ask the updated version of the question as a separate question, since it's a significant change to the original question and the original question was not trivial.
Comment: I will do that! Thanks! @NoahSchweber
Comment: The new question: https://math.stackexchange.com/questions/4261798/elementary-embedding-between-infinite-complete-atomic-boolean-algebras


Correlation $=\pm 1$ iff $Y = a +bX$ for constants a and b.

Question: I need a bit of help proving the following:
$$Cor(X,Y) = \pm 1 \Leftrightarrow  Y = a +BX$$ with probability 1, for some constants a and b. Here $Cor(X,Y)$ is the Correlation of $X$ and $Y$.
I can manage to prove one way, that is if $Y = a +bX$, then $Cor(X,Y) = \pm1$, however I'm having trouble proving the opposite way. Any help is appreciated.
Comment: Can you tell us about $X$ and $Y$? More precisely, are you hoping for a proof where $X$ and $Y$ are random variables on an arbitrary probability space? Or are they random variables on some nice finite probability space like "the set of possibilities when I flip three coins"?
Comment: @JohnHughes Why do you ask? Unless specified otherwise, one is "hoping for a proof where X and Y are random variables on an arbitrary probability space"...
Comment: Hint: Assume without loss of generality that $E(X)=E(Y)=0$ and that the correlation is $+1$, then this corresponds to the equality case in Cauchy-Schwarz inequality. Thus...
Comment: @Did: you might well be right. But given the nature of the question, it's possible that OP is just starting probability theory, and has not even heard of a probability space (think "is taking a first discrete-math course" rather than "already knows a good deal of measure theory"). In that case, mentioning Cauchy-Schwartz may not be helpful (indeed, OP may not know C-S). I was trying to gauge the OP's level of sophistication so that I could give an answer appropriate to that level. But please, go ahead and take over: you'll have an easier time providing an answer than I will.
Comment: @JohnHughes Re-reading your comment, what is mysterious to me in your queries is that I know no proof of the desired property for "random variables on (every) nice finite probability space" that does not work for "random variables on (every) probability space" as well. Anyway, as you say, it might be better to wait for the OP's input now...
Comment: Well...one proof will only involve finite sums. Of course, it's readily generalizable ... but the generalization is informative only if you know what all the terms mean, while the finite-sum version should be comprehensible to anyone who knows enough algebra. (It's possible, albeit unlikely, that OP doesn't even know any calculus or linear algebra.)
Comment: @JohnHughes  I am just told that X and Y are random variables.I am familiar with Cauchy-Schwartz, but really I'm just looking for any sort of proof right now and then I can judge whether the methods used are beyond the scope of the class.
Comment: ?? If you know Cauchy-Schwarz (with no "t") then apply my comment and basta. Did you?
Answer: Following @Did's hint:
Step 1:
Let $X' = X - E(X), Y' = Y - E[Y]$ (I suppose I'm assuming here that they actually have expected values...). Then
$$
Cor(X', Y') = Cor(X, Y)
$$
If we can show that $Y' = c X'$, then we have
$$
Y = E[Y] - cE[X] + cX
$$
so letting
$$
a = E[Y] - c E[X] \\
b = c
$$
we then have $Y = a + bX$ as needed. In short: we need only consider the case where $X$ and $Y$ have mean zero.
Step 2:
Let's examine the case where the correlation is $+1$. (The $-1$ case is very similar, and I leave it to you).
By definition of the correlation, we have
$$
\frac{E(X'Y')}{\sigma_X' \sigma_Y'} = 1
$$
so that
$$
E(X'Y') = \sqrt{E(X'^2) E(Y'^2)}
$$
Now noting that $\langle <X', Y'> \rangle = E(X'Y')$ is an inner product on the space of mean-zero random variables, the Cauchy-Schwarz-Bunyakovsky inequality tells us that in general,
$$
E(X'Y') \le \sqrt{E(X'^2) E(Y'^2)}
$$
with equality only in the case where $Y'$ is a multiple $cX'$ of $X'$.
I'm being a little sloppy here: what's really required is that $Y'$ and $X'$ are linearly dependent, but since $X'$ is nonzero, that's the same as $Y'$ being a multiple of $X'$. I'm being sloppy in another way: if you change the value of $X'$ or $Y'$ on a set of probability zero, then equality still holds. So what I can really conclude is that
$$
P(Y' - cX' \ne 0) = 0.
$$
But that's exactly what we needed to prove that
$$
Pr (Y = a + bX) = 1.
$$
(I'm pretty sure that the sloppiness here will offend some folks, but it gets across the main ideas, I believe; in the case where the domain of the random variables $X$ and $Y$ is finite, and where there are no massless atoms, what I've said is correct.)
Comment: Fixed, thanks. With a small addition. :)
Answer: WLOG, assume $\mathbb{E}X=\mathbb{E}Y=0,\mathbb{E}X^2=\mathbb{E}Y^2=1,\text{Corr}[X,Y]=1$.

Then $\text{Cov}[X,Y]=\mathbb{E}XY=1$.
Now note $\mathbb{E}(X-Y)^2=\mathbb{E}X^2-2\mathbb{E}XY+\mathbb{E}Y^2=1-2+1=0$.
As $(X-Y)^2\ge0$, we can infer that $(X-Y)^2\equiv0$ a.s., i.e. $Y=X$.

So, in generality, $\text{Corr}[X,Y]=1$ implies that the rescaled  versions of $X,Y$ are equal, i.e. $Y=a+bX$ for some $b>0$.
For $\text{Corr}[X,Y]=-1$, one follows the same line of reasoning with $(X+Y)^2$ in place of $(X-Y)^2$.


How do I create an Excel file?

Question: I'm developing a module. I need to give to the users the option to download the coupons in XLS (Excel) format.
How I can do this?
Comment: It depends on a lot of things NOT mentioned in this question.  Coupons for what?  Commerce?  Ubercart?  General Coupons?  Are you just looking to run a DB query and then export the results to an XLS sheet?  As it stands it's impossible to answer this question, I'd suggest editing it with more information.
Answer: I'm assuming you are using some content type for the content needed on your module.  If so, then you can use Views with a module like Views Data Export.
Comment: I would HATE to have to have Views as a dependency of my module unless it was a Views plugin of some sort.
Answer: As an alternative to the Views Data Export module (suggested in another answer here), you could also use the Forena module to create an appropriate report, and then save (export) the report data (= query results) in the desired format, of which XLS is one of the supported options (apart from CSV, HTML, DOC, PDF, etc). For an online example of this, refer to the Customized Simple Table of States, and its related annotations to explain the example.
For somebody who rather wants/needs a JSON or XML format, refer to my answer to "How to add a link to the CSV download to my module page, for a report created with Forena?".
To integrate Forena in a custom module, use any of the hooks available to do so, as documented in Forena's Developers Guide.

How do I create an Excel file?


Working with Visual Studio 2005 projects in Visual Studio 2008

Question: I've received a new computer from my employer. This time I don't want to maintain several versions of Visual Studio (although I know they work great side-by-side). Can I work with an ongoing VS2005 project in VS2008? By 'working' I mean the ability to open, modify, and save back to the original format.
Any ideas?
Answer: You can't do this without editing the .csproj files. You'll need to change the "ToolsVersion" attribute in the project header.
Comment: Maybe there's some kind of an add-on to export to a previous version?
Comment: Not that I've ever heard of. Why do you need both versions? VS2008 can target .NET 2.0.
Comment: Because I cannot convince my foreign colleagues to switch to VS2008. Stupid, I know
Comment: @Kerido: maybe they'll switch to 2008 in a month when 2010 comes out. They'd do better to take the chance to try VS2010 for free, right now.
Answer: You can maintain to csproj files, when opening in VS2008 it will convert it. Make sure you have a backup.
Comment: This is not an option, because whenever I modify the converted VS2008 version, the two project files are no more in sync.
Comment: Then @John Saunders is your only option.


$\sup x_n⩾x⟺∀ϵ>0 ∃n x_n⩾x−ϵ$

Question: Is the following correct? $\sup x_n⩾x⟺∀_{ϵ>0} ∃_n x_n⩾x−ϵ$
I would say so. My doubt is from the RHS to LHS. Even with the equality, since we can get an $x_n$ as close as we want from $x$, the supremum must be at least as high as $x$, right?
Any help would be appreciated
Comment: Suppose $\sup x_n<x$. See what you can get.
Comment: @Jack, I would get that from a certain epsilon and smaller, every $x_n$ would be below x-$\epsilon$ . So, I would have proved.
Comment: Yes, the epsilon chosen in my answer, for instance.
Answer: If $\sup_{n}x_{n} < x$, then $x_{n} < x$ for all $n$ by definition; so
$$
x_{n} < x - \frac{(x-\sup_{n}x_{n})}{2}
$$
for all $n$ (seeing this inequality geometrically could be easier for some);
then the "if" part follows.
Answer: try to proof from RHS to LHS by contradiction: Assume $sup(x_n) <x$. That means  $ \forall n \in \mathbb{N}: x_n < x$ or $x-x_n > \delta$ for some $\delta \in \mathbb{R}$. This is already a contradiction the the RHS.
Answer: Yes, try using contrapositive: if the supremum was less than $x$, there would be $\epsilon$ such that $x-\epsilon$ was greater than all $x_n$.

$\sup x_n⩾x⟺∀ϵ>0 ∃n x_n⩾x−ϵ$


under what circumstances $\sup_{x \in \mathbb{R}} \{ f(x) + g(x) \} = \sup_{x \in \mathbb{R}} \{f(x) \} + \sup_{x \in \mathbb{R}} \{g(x)\}$?

Question: Let $f$ and $g$ be real-valued functions on $\mathbb{R}$.
As we know that the elementary property of supremum of functions is
$$\sup_{x \in \mathbb{R}} \{ f(x) + g(x) \} \leq \sup_{x \in \mathbb{R}} \{f(x) \} + \sup_{x \in \mathbb{R}} \{g(x)\}. $$
I'm curious about under what circumstances the equality will hold? I thought constant functions $f,g$ could make it to be equal. What else?
Any suggestions would be greatly appreciated.
Comment: Since $f$ and $g$ are not necessarily continuous, I guess there won't be a necessary condition for the equality.
Comment: If the maxima of $f,g$ are at the same point, it holds.
Comment: @ThePortakal What if $f$ and $g$ are both continuous, then how to make the equality hold? Thanks
Answer: It is equivalent to:
for each $n\in \mathbb Z ^+$:  $f^{-1}(\sup(f)-\frac{1}{n},\sup f]\cap g^{-1}(\sup(g)-\frac{1}{n},\sup g ]\neq \varnothing$
Comment: What happens if $f=1$ and $\sup g = + \infty.$

Equality holds but not your condition $g^-1 (+\infty , +\infty ]  = \emptyset$
Comment: I was assuming finite supremum
Answer: One can be $f,g$  be monotone functions of same type.
and It doesn't have to be strictly monotone!  This even covers all constant functions
Another one can be  only $f$  be a constant function , No condition on $g$
Comment: Definitely, I  don't claim  necessary and sufficient @coffeemath
Comment: There are other cases making equality.
Comment: @coffeemath Could you give us some examples making equality? thanks
Comment: @Paradiesvogel  Another type example, given $f \ge 0,$ is to use $g=kf$ for some $k>0.$
Comment: @Redshoes Would you mind to explain what does "$f, g$ be monotone functions of same type"? did you mean that $f$ and $g$ are either both monotone increasing or both monotone decreasing? Many thanks again :-)


The sum of $\frac{999}{1999} + \frac{999}{1999} \frac{998}{1998} + ...+ \frac{999}{1999} \frac{998}{1998}...\frac{1}{1001}$?

Question: Ive tried to represent $\frac{999}{1999}$ as $1 - \frac{1000}{1999}$ and so on, but it didnt lead me anywhere. I also tried to represent it as $\frac{999!}{1999!} \cdot \frac{1998!}{998!} + \frac{999!}{1999!} \cdot \frac{1997!}{997!} + \dots + \frac{999!}{1999!} \cdot \frac{1002!}{2!} + \frac{999!}{1999!} \cdot \frac{1001!}{1!} + \frac{999!}{1999!} \cdot \frac{1000!}{0!}$. Basically, it means that all that's left to do is calculate what $ \frac{1998!}{998!}+\frac{1997!}{997!} + \dots + \frac{1000!}{1!}$ is, but i am stuck and don't have any idea how to do that. Is there any other way to do it faster?
Answer: It becomes easier if the terms are added from right to left.
The sum of the last two terms is
$$
\frac{999}{1999} \frac{998}{1998} \cdots \frac{3}{1003}\frac{2}{1002}\left(1 + \frac{1}{1001}\right) = \frac{999}{1999} \frac{998}{1998} \cdots \frac{3}{1003} \cdot \frac{2}{1001} \, .
$$
The sum of the last three terms is therefore
$$
\frac{999}{1999} \frac{998}{1998} \cdots \frac{4}{1004}\frac{3}{1003}\left( 1 + \frac{2}{1001}\right) =
\frac{999}{1999} \frac{998}{1998} \cdots \frac{4}{1004} \cdot \frac{3}{1001} \, .
$$
Continuing in this way one finally gets for the complete sum
$$
\frac{999}{1999} \left( 1 + \frac{998}{1001}\right) = \frac{999}{1001} \, .
$$

Another option is to write the sum as
$$
 \sum_{k=1}^{999} \frac{999! (1999-k)!}{(999-k)! 1999!}
= \frac{1}{\binom{1999}{1000}} \sum_{k=1}^{999} \binom{1999-k}{1000} = \frac{\binom{1999}{1001}}{\binom{1999}{1000}}
= \frac{999}{1001} \, ,
$$
using the the hockey-stick identity.
Answer: $$\frac{999}{1999}+\frac{(999)(998)}{(1999)(1998)}+....\frac{999!}{(1999)(1998)...(1001)}$$
$$\sum_{k=0}^{998}\frac{\frac{999!}{k!}}{\frac{1999!}{(1000+k)!}}$$
$$\frac{(999!)}{(1001)(1002)...(1999)}\sum_{k=0}^{998}\frac{(1000+k)!}{(k!)(1000!)}$$
Note that,
$$\binom{x}{y}=\frac{x!}{(y!)(x-y)!}$$
$$\frac{999!}{(1001)(1002)...(1999)}\sum_{k=0}^{998}\binom{1000+k}{1000}$$
By using Christmas stick identity (Also known as hockey stick identity) we get it's equal to,
$$\frac{(999!)(1999!)}{(1001)(1002)...(1999)(1001!)(998!)}$$
Which after simplification leads to
$$\frac{999}{1001}$$


Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/logging/lo g4j/LogManager

Question: Estou tentando iniciar um arquivo jar e assim que executo, recebo esse erro! Vocês podem me ajudar?

C:\Unky\Web\BloodStrikeServer-master>mvn clean package -Dmaven.test.skip=true
'mvn' não é reconhecido como um comando interno
ou externo, um programa operável ou um arquivo em lotes.

C:\Unky\Web\BloodStrikeServer-master>java -jar target/lobbyplayer-0.0.1-SNAPSHOT
-fat.jar
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/logging/lo
g4j/LogManager
        at com.bloodstrike.lobbyserver.Main.<clinit>(Main.java:17)
Caused by: java.lang.ClassNotFoundException: org.apache.logging.log4j.LogManager

        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 1 more

C:\Unky\Web\BloodStrikeServer-master>pause Pressione qualquer tecla para continuar. . .

Arquivo main:
package com.bloodstrike.lobbyserver;

import java.io.FileOutputStream;

import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;

import com.bloodstrike.lobbyserver.manager.NetworkManager;

import io.vertx.core.Vertx;
import io.vertx.core.net.NetClient;
import io.vertx.core.net.NetServer;
import io.vertx.core.net.NetSocket;

public class Main {
    private static final Logger logger = LoggerFactory.getLogger(Main.class);

    public static void main(String[] args) throws Throwable {
        logger.info("===============================================================================");
        logger.info("BloodStrike Lobby Server");
        logger.info("Créditos: ExtremsX");
        logger.info("Versão: 0.1 Beta");
        logger.info("===============================================================================");

        logger.info("Carregando Configurações");
        Config.loadConfig();

        logger.info("Iniciando NetworkManager");
        NetworkManager.getInstance();

            Vertx.vertx().setTimer(1000, id -> {
                    try {
                        startClientDebug();
                        logger.info("Iniciando DUMPER");
                    } catch (Exception e) {
                        logger.error("Falha ao iniciar o DUMPER");
                    }
            });

        logger.info("Iniciando NetworkServer");
        NetworkServer.getInstance();
    }

    private static void startClientDebug() throws Exception {
        Logger log = LoggerFactory.getLogger(Main.class);
        int port = Integer.parseInt("4000");
        String host = "0.0.0.0";
        FileOutputStream fos = new FileOutputStream("./network.dump");

        NetServer server = Vertx.vertx().createNetServer();
        server.connectHandler(handler -> {
            NetClient client = Vertx.vertx().createNetClient();
            log.error("Nova conexão recebida de " + handler.remoteAddress());

            client.connect(port, host, res -> {
                if (!res.succeeded()) {
                    log.error("Erro ao se conectar ao servidor", res.cause());
                    try { fos.close(); } catch (Exception e) { }
                    return;
                }
                log.error("Erro ao se conectar ao servidor", res.cause());

                NetSocket socket = res.result();
                // Do cliente para o servidor
                handler.handler(buffer -> {
                    try {
                        fos.write("\n\nClient -> Servidor\n".getBytes());
                        fos.write(buffer.getBytes());
                    } catch (Exception e) { }
                    socket.write(buffer);
                });

                // Do servidor para o cliente
                socket.handler(buffer -> {
                    try {
                        fos.write("\n\nServidor -> Client\n".getBytes());
                        fos.write(buffer.getBytes());
                    } catch (Exception e) { }
                    handler.write(buffer);
                });
            });
        });
        server.listen(3999, res -> {
            if (!res.succeeded())
                return;
            log.info("Servidor DUMPER iniciado na porta 3999");
        });
    }
}

Comment: Se no seu arquivo `main`, você colocar um `//` antes de qualquer chamada, uso ou importação do `Logger`, ele funciona?
Comment: Já tentou trocar as chamadas ao log4j por `System.out.println`?
Answer:

C:\Unky\Web\BloodStrikeServer-master>mvn clean package -Dmaven.test.skip=true
'mvn' não é reconhecido como um comando interno
ou externo, um programa operável ou um arquivo em lotes.

O maven não está devidamente instalado. Basta insalar o maven e certificar-se que a pasta bin dele está na variável %PATH%.
Quanto a esse comando:
java -jar target/lobbyplayer-0.0.1-SNAPSHOT-fat.jar

Faltou colocar o log4j no classpath. Deveria ser assim:
java -cp log4j.jar -jar target/lobbyplayer-0.0.1-SNAPSHOT-fat.jar

Talvez você precise também colocar vários outros JARs, seria assim:
java -cp pasta1/jar1.jar;pasta2/jar2.jar -jar target/lobbyplayer-0.0.1-SNAPSHOT-fat.jar

Utilize ; para separar o nome de um JAR do outro no classpath. Você pode acabar precisando de um monte de JARs.
Comment: Já fiz isso e continua a mesma coisa
Comment: já nem sei mais oq fazer, tentei tantas coisas e nunca deu certo, ficava sempre no mesmo erro, só agora fui apelar para a ajuda de alguem
Comment: @JúlioSousa O JAR do log4j está em qual pasta?
Comment: java -cp classpaths/log4j-api-2.6.2.jar;classpaths/log4j-core-2.6.2.jar -jar target/lobbyplayer-0.0.1-

SNAPSHOT-fat.jar pause depois de alterar, criei a pasta e pus os jars]
Comment: E esses dois JARs estão na pasta `C:\Unky\Web\BloodStrikeServer-master\classpaths`, né? É `classpaths` no plural mesmo?
Comment: Antes de mais nada, alem de usar os necessarios para o app, necessita de uma outra api do log4j?
Comment: Se fosse esse o problema, ele provavelmente daria um erro diferente.
Comment: Sim. pus no plural propositalmente, mas eu pus a pasta no plural e as cp tambem
Comment: Bem, então não sei o que é. Deve ser alguma coisa boba, mas não sei.
Comment: Já tentei de tudo, trocar de log4j para slf4j, já tentei mudar algo na manifest.mf, mas sempre fica no mesmo erro. Não consigo entender o por que disso :P


Filter products by custom product attribute et post meta data in a WP_Query

Question: I have already filtered by category, but don't know how to filter products by custom attributes or meta values
code:
$key="naam"; //custom attribute name
$value="test";// custom value
$query_custom = array('key' => $key, 'value' => $value);
$meta_query[] = $query_custom ;

$args=array('meta_query'=>$meta_query, 'product_cat' => 'activiteiten','posts_per_page' => 10,'post_type' => 'product');

$loop = new WP_Query( $args );

`
Comment: You can find a working solution for this issue here: https://stackoverflow.com/questions/74200775/how-can-i-filter-woocommerce-shop-products-product-loop-by-their-custom-produc
Answer: Here is a working example of a query involving:

product category filtering
post meta value filtering (meta query)
product attribute value filtering (tax query)

The code:
$products = new WP_Query( array(
    'posts_per_page' => 10,
    'post_type'   => 'product',
    'post_status' => 'publish',

    // 1. Product category filter
    'product_cat' => 'clothing',

    // 2. The Post meta query part (filtering by post meta value)
    'meta_query' => array( array(
         'key'     => '_price',
         'value'   => 5,
         'type'    => 'numeric',
         'compare' => '>',
    ), ),

    // 3. The taxonomy meta query part (filtering by term values)
    'tax_query' => array( array(
        'taxonomy' => 'pa_color', // Product attribute taxonomy: always start with 'pa_'
        'field'    => 'slug', // Can be 'term_id', 'slug' or 'name'
        'terms'    => array('blue'),
    ), ),
) );

// Testing output
if( $products->have_posts() ) :
echo '
'
while ( $products->have_posts() ) : $products->the_post();
echo '
' . get_the_title() . '
';
endwhile;
wp_reset_postdata();
echo '
'
endif;

Tested and working:
Official reference documentation for Wordpress WP_Query:

WP_Query and Custom fields parameters
WP_Query and Taxonomy parameters
Answer: You can achieve using following code.
            $args = array(
              'meta_query'=> array(
                array(
                  'key' => 'vote', // here use your field name
                  'compare' => '=', // comparison sign
                  'value' => 5, // value using that you can search

                )
              ),
              'product_cat' => 'activiteiten',
              'posts_per_page' => 10,
              'post_type' => 'product'
            ) );

            query_posts( $args ); // get all the posts data using above filter.

query_posts is used to find out the posts with list of arguments meta_query is used in your case to find the matched custom field data.
Comment: Code only answers arent encouraged as they dont provide much information for future readers please provide some explanation to what you have written


Como manipular strings com ".find"

Question: Eu posso usar o ".find" para fazer o programa buscar alguma palavra dentro de um texto digitado e dizer se existe ou não existe?(true or false) e em que linha do texto está localizado,se não, qual comando uso para fazer isso?
O que já tenho até agora:
a = str(input())
#output: Criando um exemplo.
print(a.find('exemplo'))

Comment: Para podermos te ajudar, [forneça um código Mínimo, Completo e Verificável](https://pt.stackoverflow.com/help/mcve).
Answer: O método find deve ser utilizado apenas se te interessar a posição da ocorrência na string, isto é, saber em que parte da string foi encontrado o valor desejado. Se a intenção é apenas verificar se for encontrado, o ideal é utilizar o operador in:
texto = input()
if "exemplo" in texto:
    print("Encontrou")

Veja funcionando no Ideone | Repl.it
Lembrando que no Python 3, o retorno da função input já é uma string, então não há necessidade de convertê-la novamente.
Se realmente for interessante saber em qual posição ocorreu o valor desejado, é possível fazer algo como:
texto = input()
index = texto.find("exemplo")
if index >= 0:
    print("Encontrou na posição %d" % index)

Veja funcionando no Ideone | Repl.it
Comment: @LucasSouza sim. Se esse texto está em uma variável, o mais simples seria efetuar um `split` nas quebras de linha, `\n`, percorrê-las e verificar linha a linha se possui o conteúdo desejado.
Comment: Existe alguma forma de sinalizar em que linha a palavra está, no caso de textos grandes?

Como manipular strings com ".find"


Why does Relay need a mutation id to reconcile GraphQL mutations?

Question: I've tried to figure out why, but always end up concluding that the "tracking" could be easily done within the closure of the request that was sent. I'm clearly missing something here.
Why does Relay need a mutation ID to track the request/response?
Comment: Have you seen https://facebook.github.io/relay/graphql/mutations.htm? It's not an answer to your question but the best resource I could find :)
Comment: @marktani, I have. Thanks for the link though. :)
Answer:
"tracking" could be easily done within the closure of the request that was sent

You're thinking in terms of implementation. Relay is a JavaScript framework that implements the Relay specification. Under the specification, it is not a good idea to rely on something (closure) that a language may or may not support. Therefore, Relay Input Object Mutations Specification specifies clientMutationId to track the mutation.
Comment: I see. I've read the spec before but hadn't thought of that. Would you mind giving an example of a language where something like JS closures won't be available to track mutations?
Comment: My C++ knowledge is rusty. AFAIK, C++ before C++11 standard does not have built-in closure support.


Emmeans produce negative values for prob 95%CI for multinomial regression

Question: I'm fitting a multinomial logistic regression and I'm getting two issues:
  library(emmeans)
  library(nnet)
  library(multcomp)
  DF = data.frame(IND = c(rep("A",5),rep("B",11),rep("C",4),
            rep("A",3),rep("B",5),rep("C",2)),
            G = c(rep("G1",20),rep("G2",10)))
  table(DF)
  MULTI = multinom(IND ~ G, data = DF);summary(MULTI)
  EMMEANS = emmeans(MULTI,~G*IND, mode = "prob");EMMEANS
  PAIR = pairs(EMMEANS, type = "response", adjust="tukey");PAIR
  CLD = cld(EMMEANS, alpha=0.05, Letters=letters,adjust="tukey");CLD

1 - Why are emmeans and cld reporting negative values for lower.CL, even if I used mode = "prob"? Can I convert them to zero?
2 - Why pairs does not return odds.ratio, even if I used ratio = T? If I use exp(estimate) do I get odds.ratio?
Thank you all in advance!
Comment: This happens because when there isn't much data, and some of the estimated probabilities are small. It's possible ifor the SEs to be big enough to mske the CI endpoints go negative. CLD is just a data frame so you can nanipulate the negative limits to be changed to 0. Or get more data?
Comment: Dear Prof. Lenth, thank you so much for your reply. Unfortunately, I cannot get more data, so I'll have to convert the negative values to zero. Best regards.
Answer: It is not unusual at all to get negative confidence limits with small datasets. They are due to using naive normal-theory intervals: $\hat p \pm z_{\alpha/2}SE(\hat p)$. When $\hat p$ is small and the sample size is small, the $\pm$ part can easily exceed $\hat p$, leading to a negative bound.
There is kind of a workaround for this. The "prob" mode involves considerable post-processing, so by the time we get to the estimates themselves, it is way too late. However, the transform argument is passed to the reference grid right after it is constructed, along with auxiliary arguments such as N.sim. So we can get the software to simulate values from the sampling distribution on the linear-predictor scale; then those simulations are used henceforth as if they were samples from a posterior distribution. This does a much better job of keeping us in bounds:
> (emm2 = emmeans(MULTI,~G*IND, mode = "prob",
                  transform = "pass", N.sim = 1000))

Generating a posterior sample of size 1000
 G  IND  prob lower.HPD upper.HPD
 G1 A   0.251    0.0724     0.455
 G2 A   0.303    0.0298     0.578
 G1 B   0.549    0.3216     0.763
 G2 B   0.487    0.1979     0.812
 G1 C   0.203    0.0181     0.378
 G2 C   0.197   -0.0156     0.465

Point estimate displayed: median
HPD interval probability: 0.95

> pairs(emm2)
 contrast    estimate lower.HPD upper.HPD
 G1 A - G2 A -0.05611  -0.36235    0.2973
 G1 A - G1 B -0.29662  -0.66566    0.0561
 G1 A - G2 B -0.24502  -0.60983    0.1033
 G1 A - G1 C  0.04915  -0.23211    0.3643
 G1 A - G2 C  0.04872  -0.25559    0.3496
 G2 A - G1 B -0.24292  -0.59601    0.1025
 G2 A - G2 B -0.18666  -0.69630    0.3710
 G2 A - G1 C  0.10710  -0.19314    0.4655
 G2 A - G2 C  0.10372  -0.32463    0.4908
 G1 B - G2 B  0.06313  -0.32163    0.4363
 G1 B - G1 C  0.35135   0.00661    0.7039
 G1 B - G2 C  0.35400   0.03511    0.6642
 G2 B - G1 C  0.29695  -0.03502    0.6413
 G2 B - G2 C  0.29292  -0.21142    0.7314
 G1 C - G2 C  0.00192  -0.28734    0.2834

Point estimate displayed: median
HPD interval probability: 0.95

Note that this produces a Bayesian-like summary based on highest posterior density regions. It didn't keep all the limits from going negative, but they are a lot better behaved. (You can do summary(emm2, point.est = mean) if you would rather see means instead of medians; it will not change the intervals.)
You can't use cld() on these results, but that's a method I recommend against anyway.
Postscript
I was surprised to see any negative values at all, so I traced this and found out that the simulations not done early as I had thought, but are done on the final results on the "prob" scale. They still behave a lot better, probably because the covariances among the estimated $\hat p$ values are taken into account. I will investigate why it didn't work at the linear-predictor level as I had described.
Postscript 2
Adding transform = "response", N.sim = ... does already work
correctly for ordinal models, just not for multinom because it turns out
this doesn't use regrid() until later. I souped-up
the multinom support so this does also work for multinom
(the transform option is not necessary.)
> emmeans(MULTI,~G*IND, mode = "prob", N.sim = 1000)
Simulating a sample of size 1000
 G  IND  prob lower.HPD upper.HPD
 G1 A   0.247    0.0888     0.437
 G2 A   0.296    0.0845     0.572
 G1 B   0.535    0.3251     0.742
 G2 B   0.477    0.2196     0.779
 G1 C   0.197    0.0684     0.415
 G2 C   0.183    0.0227     0.456

Point estimate displayed: median
HPD interval probability: 0.95

You need to install this from GitHub or wait until this is updated on CRAN (probably version 1.5.1)
Comment: Dear Professor Lenth, thank you so very much for your very detailed explanation. I would like to ask just one more question. You said that we can't use the `cld` function. Is this impossibility of use due to a numerical incompatibility between the two functions (i.e. the calculations are wrong), or due to a philosophical incompatibility (i.e. the results lead to a wrong interpretation)? Does function `pairs` suffers from this same issue?
Comment: pairs() works because it obtains the pairwise differences of the simulations. But cld() is strictly a frequentist method. It requires P values which we don't have. As I said, I don't recommend cld anyway because it highlights NON-findings rather than findings. Two means not being significantly different is a non-finding because we didn't prove they are the same, we only failed to prove them different. So when we group things according to what we aren't able to show, that's confusing if not downright misleading.
Comment: Now I totally understand, prof. Lenth. Thank you very much again!


In spring manage threads created by one controller's different instances

Question: I have written a controller to deal with video upload. The hard part for me is to convert the video type to both mp4 and webm. I chose to new a thread in my controller and the thread will new a process which is a video convert software called "ffmpeg".
The problem is that this thread will occupy too much resources(at least 25% CPU usage). So I guess I have to make these threads created by different controller instances execute in a shared queue. It is terrible to have these threads in concurrent execution.
It seems that the taskExecutor in Spring can only manage threads created by one controller instance. And is there any way to manage threads among threads created by one controller class but different instances? It seems like a public or shared thread pool..
Comment: What about ExecutorService from which you make fixed threadpool of 2 threads and add the two conversions to the pool?
Answer: I don't know exactly how your project is set up, but that's what I meant if it makes sense.
<code>@Controller
@RequestMapping(value = "/convert")
public class UploadController {
    ExecutorService threadPool = Executors.newFixedThreadPool(2);

    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView processVideoConvert() throws InterruptedException {

    final ModelAndView modelAndView = new ModelAndView("convert");

    threadPool.submit(new Runnable() {
        @Override
        public void run() {
          //first conversion
        }
    });

    threadPool.submit(new Runnable() {
        @Override
        public void run() {
         //second conversion
        }
    });

    threadPool.shutdown();
    //threadPool.awaitTermination(500L, TimeUnit.MILLISECONDS);
    return modelAndView;
    }
}
</code>
Comment: It really saves me! Thanks a lot ! And by the way, is there any problem if I comment the statement "threadPool.shutdown();" ?
Comment: Otherwise if the num of threads is over 2, it will always throw Reject Exception even when the tasks in the pool are completed.
Comment: Hmm I am not exactly sure, I believe you actually must have shutdown together with awaitTermination, so after shutdown the await makes sure all the tasks are done. So you would have to uncomment the termination, but remove the timeout unless you have some specific time how long you want to wait before the tasks are terminated.
Comment: Actually the requirement is that the video upload controller can handle the request anytime. So I think the number of tasks is supposed to be infinite ^_^ Then can I just do not shundown this shared threadpool?
Comment: Fixed thread pool only accepts 2 tasks at any time. Shutdown is called to say that do the pool is not accepting any new tasks. I think it is a good practice to call shutdown and then awaitTermination, just set the timeout to max. This ensures you that all the threads have finished. `awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);`