How to do something like : If not %var1%==%var2% goto fail (Batch)

Question: I'm working on a password protected notepad style thing
UPDATED CODE:
:login
cls
Echo Welcome %Name%
Echo Please enter your password
set/p %passin%=
if "%passin%" neq "%pass%" goto :menu
echo Correct password.
pause
goto :menu

:loginfail
echo incorrect password, you have (%loginfails%) attempts remaining
[INSERT SCRIPT FOR CHANGING THAT NUMBER AND SOME METHOD OF SECURITY WHEN IT HITS ZERO HERE]
pause
cls
goto :login

However, after the set/p it automatically closes, even if I put in the right password which I setup a loading script earlier in the file.
Any assistance would be appreciated :)
EDIT : its no longer closing out after entering password, but no matter what it thinks the password is correct. how could i fix this (when i have echo on, it says if "" == "" goto :menu
(
EDIT2 : i used neq as a commentor says, opposite results, still doesnt work
Comment: I congratulate you in providing a minimal example; however in doing so, and based on your incorrect use of `Set /P` and `If`, there may be several other issues with your code. _Your use of `If` should be utilising doublequotes, `If Not "%passin%"=="%pass%" ...`_.
Comment: now its not caring what the password is, its just progressing on with the script
Comment: Aside from other comments, your logic fails, change to `if "%passin%" neq "%pass%" goto :loginfail`
Comment: i changed it to neq, the new code seems to think every password is wrong
Comment: If that's your new code, what happened to the advice @Mofi provided in their 2nd comment? _Because, as I implied previously, unless the value of %passin% is passin, that's your issue_.
Comment: @Mofi I looked at linked answers and i couldnt work out quite what was being said : and i tried neq because of a comment above.
Answer: The error you are getting (closure, unexpected terminate of batch file) is because you have written:
set /p %passin%=

which is completely wrong. You had to enter ONLY the variable name (without percent signs (%...%)).
Have a corrected version of the script you provided us:
@echo off

set "pass=PASS_YOU_WANT"
set "loginfails=NUMBER_YOU_WANT"
set "name=NAME_YOU_WANT"

:login
cls
Echo Welcome %Name%
set /p "passin=Please enter your password: "
if /i NOT "%passin%"=="%pass%" ( goto loginfail ) else ( echo Correct password. )
pause
goto menu

:loginfail
set /a "loginfails-=1" >nul
echo incorrect password, you have (%loginfails%) attempts remaining
rem [INSERT SCRIPT FOR CHANGING THAT NUMBER AND SOME METHOD OF SECURITY WHEN IT HITS ZERO HERE]
pause
cls
goto login

where if /I means enable case-sensitivity.
Hope this helps!


anonymous delegate with return value

Question: [Actually, I am not sure the problem is relate to anonymous and delgate or not.]
In my application, I use the asynchronous for create new item. In AddNew method, it will call create a new item from the repo class then add it to list item. The create method has parameter but it has a return value.
The problem is I really don't know how to call a create method with the anonymous.
The code as following.
    protected void AddNew()
    {
        _repo.Create(() => AddToListItem(x)) // I want the value (x) that return from repository.Create to use with AddToListItem(x)
    }

    public P Create(Action completed = null)
    {
        var p = new P();
        Insert(p);
        return p;
    }

    public void Insert(P p, Action completed = null)
    {
        _service.Insert(p,
            () =>
            {
                if (onCompleted != null)
                {
                    onCompleted();
                }
            }
            );
    }

Comment: The above code is not asynchronous. Furthermore, it's not clear, what you are trying to do at all. Please elaborate more.
Answer: Instead of parameterless Action use generic Action<T>:

Encapsulates a method that has a single parameter and does not return a value.

Your code should looks like that:
public P Create(Action
 completed = null)
{
    var p = new P();
    Insert(p, completed);
    return p;
}

public void Insert(P p, Action
 completed = null)
{
    _service.Insert(p,
        () =>
        {
            if (completed != null)
            {
                completed(p);
            }
        }
        );
}

You have to also change your lambda expression to match Action
:
protected void AddNew()
{
    _repo.Create((x) => AddToListItem(x))
}

Comment: Then in the last method you can even get rid of the lambda since the parameter list is just passed on unchanged to one method, so you can say `_repo.Create(AddToListItem);` if you like.
Comment: @JeppeStigNielsen Yes, you're right! I always forget about that, because personally find that way less readable then `x => Method(x)`.
Comment: Why less reliable? It even removes one additinal method call: the generated method for your lambda.
Comment: @riezebosch You've misread my comment. I think it's less **read**able, not less reliable.

anonymous delegate with return value


The requested theme does not exist

Question: Help, I'm lost :(
My site was hacked and I was investigating the issue (see the code below)
<code>RewriteEngine On
RewriteRule ^[a-zA-Z0-9_-]+/([0-9]{1,7})([a-zA-Z0-9]{4})[a-zA-Z0-9_-]+/$ index.php?smsite=$2&smid=$1 [L]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</code>
I removed the second line and the site had stopped working
I returned back the same file, and now it doesn't work at all
And I get the following message:
The requested theme does not exist
The site is hosted with AWS
The theme is located in not were you were expecting it to be
instead of root domain/wp-content/themes
you can find it at root domain/themename/etc.
Besides changing and taking back the file, I haven't change anything
Please advice
Answer: try this:
<code># BEGIN WordPress

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

# END WordPress
</code>

The requested theme does not exist


Browser localStorage refreshing at every page

Question: I have coded a pop-up div which I want to display once per visit to the website per user, for which I was able to piece together as follows, but unfortunately it seems to pop-up at every single page I visit on the website:
//COOKIE POLICY POP-UP
$(document).ready(function () {

if (localStorage.getItem('pops') != 'visible') {
    setTimeout(function () {
        $('#cookie_popup').css('bottom', '0');
    }, 1000);

    $('#cookie_popup a.button').click(function () {
        $('#cookie_popup').css('bottom', '-100px');
    });

    localStorage.setItem('pops', 'visible');
}

});

window.onbeforeunload = function () {
    localStorage.removeItem('pops');
};

Edit: As pointed on the comments below, the last section window.onbeforeunload needed to be removed for it to keep the cache for the whole session.
Comment: `window.onbeforeunload = function () { localStorage.removeItem('pops');};` is removing the flag so that every time you come to the page, the flag isn't there and the popup is shown. Remove that part and make sure you manually clear `localStorage` yourself before you test.
Comment: Thank you @ScottMarcus you are right. I tried without and it worked.
If you'd like to write your comment as an answer I'll be able to upvote it.
Thank you so much for taking the time to help me, really appreciated!
Comment: about the comment above: that is the expected behavior, closing the browser doesn't clean the localStorage, just the sessionStorage, to clean the localstorage, you must clear the browser cache and etc...
Comment: That is true, I have tested it again according to the first comment and it worked.
Thank you for your comment @CalvinNunes
Answer:  window.onbeforeunload = function () { localStorage.removeItem('pops');};

is removing the flag so that every time you come to the page, the flag isn't there and the popup is shown. Remove that part and make sure you manually clear localStorage yourself before each of your tests.
Comment: Thanks again for your help @ScottMarcus


AJAX form - replacing #default_value not working

Question: I have an AJAX form. I want to update the text of a textfield when a button is triggered. But this does not work. My form is below:
<?php
function my_form($form, &$form_state) {
  $form['ask_first_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Ask me my first name'),
    '#default_value' => 'I LOVE chickens',
    '#prefix' => '
',
    '#suffix' => '
',
  );
  $form['update'] = array(
    '#type' => 'button',
    '#value' => t('Update'),
    '#ajax' => array(
      'callback' => 'ajax_example_autotextfields_callback',
      'wrapper' => 'textfields',
      'effect' => 'fade',
    ),
  );

  // shouldn't this update the default value when the button is pressed??
  if (isset($form_state['values'])) {
    $form['ask_first_name']['#default_value'] = 'I HATE chickens';
  }

  return $form;
}
?>

When I press the 'update' button I'm expecting the field text to change, but it doesn't. If I use #value instead of #default_value it works, but I know I shouldn't use that because I still want the user to be able to change it again.
<?php
// using #value works - but should I use that?
$form['ask_first_name']['#value'] = 'I HATE chickens';
?>

What is the recommended Drupal way to change the field value after AJAX is triggered?
NOTE: This answer solved the problem in my case, but as mentioned in the comments there is not access to the values in $form_state['values'] after submit. However, I'm storing the data in $form_state['storage'] so I can still access the data, though I'll probably implement ctools object cache in the end.
Answer: This is taken from the description of #default_value in the form api documentation:

The value of the form element that will be displayed or selected
initially if the form has not been submitted yet

Because your form has been submitted, it wont be using #default_value. Just use #value, the user will still be able to change it.
2021 edit.....
As people have pointed out, the above is wrong as although it will allow you to set the value, it wont allow the user to submit an altered value.
Now using Drupal 9, in a form alter, I needed to set some default field values when an ajax button (which I inserted) was clicked.
I needed to set default values on the node "body" field and "field_url" link field.
I removed the user input for these fields before setting a default value.
$userInput = $form_state->getUserInput();
unset($userInput['body']);
unset($userInput['field_url']);
$form_state->setUserInput($userInput);

$form['body']['widget'][0]['#default_value'] = 'my default value set after ajax callback';
$form['field_url']['widget'][0]['uri']['#default_value'] = 'my default value';

To be honest, I am not 100% sure it is the correct way, but it does work.
Comment: User-entered value will not be includes in $form_state['values'] if #value is set.
Comment: @Ayesh K. If it works with #value and it's okay to do so, I'll do that. I can always get the value from $form_state['input']?
Comment: I've got this working, but the thing stopping me giving it a correct answer is that the data does not appear in $form_state['values'] or $form_state['input'] after submit, as Ayesh said. I've worked around this by storing the data in $form_state['storage']. If I don't find a better answer I'll mark this as the accepted answer.
Comment: Ayesh K may be correct, I haven't tried it. @ Web Assistant, try it an tell us if it works.
Comment: 8 years later I start reading this answer only to realize it's by me... lol. The answer is wrong BTW, Doing it like this ignored further user input.
Comment: Updated the answer with what is working for me in D9
Answer: I made it the quick and dirty way. In my ajax callback, I set the
$form['inputfield']['#value'] = $form['inputfield']['#default_value'];

The I changed the value in the input field manually to test if the value can be changed by user and is then submitted.
After checking the $form_state['values']['inputfield'] I realized, that the value was correctly submitted, although the field got a '#value' attribute in the ajax callback.
But I think you have to be careful: Only set the '#value' attribute in the ajax callback, not in the form declaration!
Hope that helps, although a little bit late.
Comment: The extra important part of this is:  "you have to be careful: Only set the '#value' attribute in the ajax callback, not in the form declaration!"
Answer: As 2pha pointed out #default_value cannot be changed once the form has been submitted.
However the array in $form_state['input'] can be manipulated at any time.
To update the example you gave:
if (isset($form_state['values'])) {
  $form_state['input']['ask_first_name'] = 'I HATE chickens';
}

When the actual html for your form is built the value we set in $form_state['input'] will be used as the default value.
Comment: This seems like the best solution to me
Answer: 2pha's answer did not work for me - if I set values with um, value, ie $form['myfield']['#value'] then sure the value changed - but it then ignored further user input!
So this is how I achieved setting values dynamically in my form builder function during ajax call backs and still let the user amend the values (within the if at end).
Note in my case, I'm updating 3 fields whenever the user changes a couple of other fields.
 $form['ld']['letterdrop_allocations'] += array(
     '#type' => 'textfield',
     '#title' => t('Letterdrop allocations for %contact in drop %letterdrop',
       $tokens),
     '#description' => 'blah.'
     );

 $form['ld']['letterdrop_notes'] = array(
     '#type' => 'textfield',
     '#title' => 'Notes',
     '#description' => t('notes for all allocations %contact in drop %letterdrop',
       $tokens));

 $form['ld']['letterdrop_kitstate'] = array(
     '#type' => 'select',
     '#title' => 'Kit state',
     '#options' => AgcLetterDrop::kitstates(),
     '#description' => 'some words for here');

 if ($letterdrop_allocations_changed) { // overwrite field values
   unset($form_state['input']['letterdrop_allocations']);
   unset($form_state['input']['letterdrop_notes']);
   unset($form_state['input']['letterdrop_kitstate']);

   $form['ld']['letterdrop_notes']['#default_value'] =
     $ldallocations['notes'];
   $form['ld']['letterdrop_allocations']['#default_value'] =
     $ldallocations['lda_id'];
   $form['ld']['letterdrop_kitstate']['#default_value'] =
     $ldallocations['kit_state'];

 }

hope that helps - i've lost about ten hours on this!
Comment: This will work - the values will change, however it would be simpler to just update `$form_state['input']` directly instead of unsetting it and then setting the `#default_value`
Answer: I believe the proper way to change the user input or a submitted form value is by calling form_set_value.
This comment explains how to use this.
// form_set_value requires that #parents be set on the field
$form['field_your_field']['#parents'] = array('field_your_field');
// set the value by calling form_set_value($element, $value, $form_state)
form_set_value($form['field_your_field'], array('und' => array(0 => array('value' => 'WORKS'))), $form_state);

$form_state is passed by reference so the actual user input is changed and this will be reflected when the form is rebuilt and passed back by ajax callback. Therefore I think it's best to call this function during a form_validate function.


Thousand separator NAN and Infinity JavaScript/ jQuery error

Question: I am trying to implement a thousand separator while typing in MVC 6 razor page, the code below seems to work but it shows NAN if the number is deleted completely and also shows INFINITY if a large set of numbers are also entered into the textbox, lastly, it only separates the thousand part, it doesn't add the dot and the hundredth part to it, e.g: 10000 = 10, 000, but I want it to be like this: 10000 = 10, 000.00. I appreciate any assistance.

Comment: Have you considered using [Intl.NumberFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) instead of reinventing it?
Comment: I don't want to display, I want to thousand separator to happen while typing the digits in a textbox
Comment: You're only triggering on `keyup` but what if somebody copy/pastes into that field using only the mouse?
Comment: I am a backend developer, I don't know much about JavaScript and jQuery
Comment: Not sure what you mean by "I don't want to display". NumberFormat does precisely what you're trying to do.
Comment: Can you throw more light on how this could be implemented on HTML textbox to show the digits grouping while the user is typing in figures on the textbox?
Answer: What you're trying is to make a masked input for a number. I would NOT recommend to do it yourself, there're already well-established libraries for that.
I recommend inputmask:
https://robinherbots.github.io/Inputmask/#/demo


Manipulating Theme Suggestion Priorities

Question: I'm adding in some theme suggestions using mytheme_theme_suggestions_alter(), when certain criteria is met. My issue is, for some reason these additional theme suggestions are appearing at the top of the theme suggestions list whilst debugging.
Basically my theme suggestion is ignored, as Drupal believes my additional theme suggestions aren't a priority over the default ones.

I've tried some 'dirty' solutions, such as trying to clear or reverse the $suggestions[] array without any luck.
My guess is that the hook I'm using is actually running too early, however I'm unable to find a more appropriate one. Something dedicated to hooking into view theme suggestions would be great.
Thanks in advance.
Comment: @Kevin I have encountered the same issue as the question poster - and unfortunately, changing the module weight is still not changing the order of the theme suggestions (I've tried values both higher and lower than the View module, to be sure). Is there anything else that can be tried?
Comment: How does it know to use this template? Does the file name have typo(s)? Can you post that code?
Comment: I don't understand what you're trying to say, sorry. As you can see in the HTML debugging comment above, my theme suggestion is there, however it's choosing to load the default `views-view.html.twig`.
Comment: I see that it's there, what I am saying is does the twig template have a typo preventing it from being picked up?
Comment: Ah, I see. And yep, I have a file named `views-view--venues-grid-rows.html.twig`.
Comment: According to docs, `The call order is as follows: all existing suggestion alter functions are called for module A, then all for module B, etc., followed by all for any base theme(s), and finally for the active theme. The order is determined by system weight, then by extension (module or theme) name.` - so perhaps setting your module weight higher than Views would do the trick, though I am not 100% on that.
Comment: I am stimm having the same issue (core is 8.5.6). Anyone who solved it?
Answer: You shouldn't need to add a theme suggestion if you're trying to override the view template for a given view ID. The confusing thing is the fact that Views' suggestions don't show in the debug code (see: https://www.drupal.org/node/2118743).
If you add a file named views-view--view-machine-name.html.twig (replacing machine-name, of course) in your theme's templates directory and clear caches, it should pick it up. Note: it has to be templates and not in your theme's root or my_templates or anything else. Drupal is picky that way.
You should not need to worry about module/theme weights as all module alter functions run before theme alter functions.
Finally, if you are adding theme suggestions, I would recommend using the more targeted hook_theme_suggestions_HOOK_alter. (For views, the HOOK is views-view so your function would look like:
function mytheme_theme_suggestions_views_view_alter(array &$suggestions, array $variables) {
  $suggestions[] = ...
}

Hope that helps.


How many ways are there to win Settlers of Catan?

Question: The object of the board game "The Settlers of Catan" is to obtain 10 "victory points". There are five ways to obtain victory points:

Settlements, worth 1 victory point. Each player starts the game with 2 settlements and can build up to 3 more, for a total of 5.
Cities, worth 2 victory points. Cities are built on top of settlements, replacing them in doing so. Players can build up to 4 cities.
Victory Point development cards, worth 1 victory point. Players can buy up to 5 such cards from the deck.
The Longest Road card, either held or not held, worth 2 victory points.
The Largest Army card, either held or not held, worth 2 victory points.

I remember that we can decompose this into the number of integer solutions to the equation:
$$
s + 2c + v + 2r + 2a = 10
$$
where
$$
0\leq s \leq 5; 0 \leq c \leq 4; 0 \leq v \leq 5; 0 \leq r \leq 1; 0 \leq a \leq 1
$$
and
$$
s + c \geq 2
$$
to account for the 2 starting settlements that can be upgraded into cities.
Also, it is possible to have 9 victory points and then take Longest Road or Largest Army, bringing your total to 11. I think the number of additional solutions here is
$$
\text{Solutions}(s + 2c + v = 9) + 2\times\text{Solutions}(s + 2c + v = 7)
$$
multiplying by 2 to account for interchangeability of Longest Road and Largest Army, with bounds as above.
However, I don't remember how to find the number of solutions to these equations.

At commenters' request, here are some example solutions:

2 settlements, 2 cities, Longest Road, and Largest Army; $2 + 2(2) + 2 + 2 = 10$
4 settlements, 1 city, 4 Victory Point cards: 4 + 2(1) + 4 = 10
Player has 4 cities and 1 Victory Point card and takes Longest Road, 2(4) + 1 + 2 = 11
Player has 3 settlements, 1 city, 2 Victory Point cards, and Longest Road and takes Largest Army, 3 + 2(1) + 2 + 2 + 2 = 11
Comment: It might help if you gave an example or two of a "path to victory" so that we can see more clearly what it is you are trying to count. In particular, does the *order* in which you acquire victory points matter? (Also, I think the formula you want is $s+2c+v+2r+2a=10$, since the Longest Road and Largest Army cards are, like Cities, worth $2$ points each.)
Comment: Another question: Is it not possible to have $9$ victory points and then build another City, bringing your total to $11$? (You don't mention it as possible.)
Comment: @BarryCipra Added, and the order does not matter. That is not possible. Cities must be built on top of an existing settlement, so they can only increase the Victory Point total by 1 when they are built. Good question, though.
Comment: @BarryCipra Fixed.
Comment: I just noticed one more potential problem: The constraints as given allow for $(s,c,v,r,a)=(2,4,0,0,0)$ as a solution. But is it possible to build $4$ cities yet leave $2$ settlements? Do you want the extra constraint to be $2\le s+c\le5$?
Comment: @BarryCipra Yes, that is possible. You could build 4 settlements, upgrade them all to cities, then build 2 more.
Comment: Oooh I love Catan.  Great question!  BTW I don't recommend adding the following complication, but it is theoretically possible to score $12$ pts under this exact scenario (which I have never seen in the $200+$ games I've played):  You have $9$ points and $<5$ settlements and someone else holds the Longest Road.  You build an extra settlement, breaking up that player's road, resulting in your existing road being longest.  Thus you gained $3$ points with that one build and jumped from $9$ to $12$ instantaneously (atomically).  Like I said, though, lets not add this super-rare case...
Answer: Rewriting slightly, you have
$$s + v + 2(c + r + a) = 10$$ subject to $$0\leq s \leq 5 \\ 0 \leq v \leq 5 \\ 0 \leq c \leq 4 \\ 0 \leq r \leq 1 \\ 0 \leq a \leq 1 \\ s + c \ge 2$$
So clearly $s$ and $v$ must have the same parity. I think the easiest way to count solutions is to case split on $c+r+a$ ignoring the final constraint:
$$\begin{array}{c|c|c}
c+r+a & \textrm{Number of solutions} & s+v & \textrm{Number of solutions} & \textrm{Total}  \\
\hline
0 & 1 & 10 & 1 & 1 \\
\hline
1 & 3 & 8 & 3 & 9 \\
\hline
2 & 4 & 6 & 5 & 20 \\
\hline
3 & 4 & 4 & 5 & 20 \\
\hline
4 & 4 & 2 & 3 & 12 \\
\hline
5 & 3 & 0 & 1 & 3 \\
\hline
& & & \textrm{Grand total} & 65 &
\end{array}$$
and then subtract the cases $s+c < 2$. If $s=c=0$ then the others can only total 9, so there are two cases:

$s=0, c=1$: $s+v \le 5$ and $c+r+a \le 3$ so the only case is $s=0, v=4, c=1, r=1, a=1$;
$s=1, c=0$: $s+v \le 6$ and $c+r+a \le 2$ so the only case is $s=1, v=5, c=0, r=1, a=1$.

Therefore we have 63 solutions.

I disagree with you on the second case. I think that the correct way to state it is
$$s + v + 2(c + r + a) = 11$$ subject to $$0\leq s \leq 5 \\ 0 \leq v \leq 5 \\ 0 \leq c \leq 4 \\ 0 \leq r \leq 1 \\ 0 \leq a \leq 1 \\ r + a \ge 1$$
Then the same case split gives
$$\begin{array}{c|c|c}
c+r+a & \textrm{Number of solutions} & s+v & \textrm{Number of solutions} & \textrm{Total}  \\
\hline
1 & 2 & 9 & 2 & 4 \\
\hline
2 & 3 & 7 & 4 & 12 \\
\hline
3 & 3 & 5 & 6 & 18 \\
\hline
4 & 3 & 3 & 4 & 12 \\
\hline
5 & 3 & 1 & 2 & 6 \\
\hline
& & & \textrm{Grand total} & 52 &
\end{array}$$
Here we only have one overcount case:

If $s=0, c=1$ then we get $s=0, v=5, c=1, r=1, a=1$.
If $s=1, c=0$ then we can't get a total of 11.

So we get 51 solutions, which added to the previous 63 makes 114.
Comment: +1 nice modeling of the $11$ points case via $r+a \ge 1$
Comment: Although [WolframAlpha gives the same answer](https://www.wolframalpha.com/input/?i=a+%2B+2b+%2B+c+%2B+2d+%2B+2e+%3D+10;+0+%3C%3D+a+%3C%3D+5;+0+%3C%3D+b+%3C%3D+4;+0+%3C%3D+c+%3C%3D+5;+0+%3C%3D+d+%3C%3D+1;+0+%3C%3D+e+%3C%3D+1;+a+%2B+b+%3E%3D+2), I'm not sure it's correct. Consider the case $(s, v, c, r, a) = (1, 5, 0, 1, 1)$. It is illegal because $s + c < 2$, but I think it is counted in table 1 row 3 (the row starting with $c + r + a = 2$).
Comment: I overlooked the constraint $s+c\ge 2$. My bad. I'll edit shortly.
Comment: Should the "total" in table 1 row 5 not be 3? I count 3 possible solutions to $c + r + a = 5: (c, r, a) = (3, 1, 1), (4, 1, 0), (4, 0, 1)$.
Comment: @StackExchange, also correct. Not my finest hour. Still, it explains why Wolfram Alpha gave the same answer: my errors cancelled each other out.
Comment: @antkam notes that it is possible to have 9 VPs then build a settlement that breaks someone else's Longest Road and passes Longest Road to you, winning with 12 VPs. We can model this as $s + v + 2c + 2a = 9$, subject to the constraints as in the 10 case except that $s \leq 4$. [WolframAlpha says there are 28 more solutions](https://www.wolframalpha.com/input/?i=a+%2B+2b+%2B+c+%2B+2d+%3D+9%3B+0+%3C%3D+a+%3C%3D+4%3B+0+%3C%3D+b+%3C%3D+4%3B+0+%3C%3D+c+%3C%3D+5%3B+0+%3C%3D+d+%3C%3D+1%3B+a+%2B+b+%3E%3D+2), bringing the final total to 142.


Redirect after form submission

Question: I created a custom form in Drupal 8. I remember we can redirect to custom path  in Drupal 7 with $form_state['redirect'] = 'mycustompath'; in a submission handler.
How can I achieve the same in Drupal 8?
I know I should use submitForm().
public function submitForm (array &$form, FormStateInterface $form_state) {
   // Redirect users.
}

Answer: In your "submitForm" method write below code
 $form_state->setRedirect('machine_name');
 return;

where machine_name is the machine name mentioned in the routing file.
I hope this helps .. :)
Comment: $form_state->setRedirect(''); return;
Comment: it shouldn't be '/start'. It is the alias mentioned in the routing file.
Comment: It should be $form_state->setRedirect('tcdev.content');
Comment: not work. I try my custom route `$form_state->setRedirect('/start');return;` , let's suppose I want to redirect to home page. what is exact snippet?
Comment: `''` worked what you about path alias ? this is my route `tcdev.content:
  path: '/start'
  defaults:
    _controller: 'Drupal\tcdev\Controller\TrainingCenterController::content'
    _title: 'Start Training Center'
  requirements:
    _permission: 'access content'`
Comment: It's not a path alias; it's the route name. Path aliases are a different think, in Drupal.
Comment: For a real path use:

`$url = Url::fromUri('internal:/oag_estimator/form/estimator');`
`$form_state->setRedirectUrl($url);`
Answer: If you want to set at buildform you need to use some routing path like.
use Drupal\Core\Url;

$url = Url::fromRoute('route.path');
$form_state->setRedirectUrl($url);

Comment: Check the API: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21FormState.php/function/FormState%3A%3AsetRedirectUrl/8.3.x.
setRedirect() just converts the route to a URL first then calls setRedirectUrl().
Comment: what is namespace of Url?
`Url' not found`
Comment: should be `use Drupal\Core\Url;` (without the preceding slash)
Comment: `$form_state->setRedirectUrl($url);` can also be used in submitForm().
Answer: Theres a lot of answers in here but none that correctly show how to redirect to a specific path.
Firstly, you want to set the redirect in your submit handler. You can add a new one to the form array in your form_alter;
$form['#submit'][] = 'my_form_submit_handler';

Sometimes you may need to add the handler to the submit button as well;
$form['actions']['submit']['#submit'][]  = 'my_form_submit_handler';

Its important to append the item to the submit array so that you don't remove any handlers that already exist.
Then, in your submit handler;
function my_form_submit_handler(&$form, FormStateInterface $form_state) {
  $form_state->setRedirect(URL::fromUserInput('/whatever/path/you/want'));
}

And thats it. Theres no return as more submit handlers may come after this one.
And dont use any Response returns like RedirectResponse. Their correct usage is in Controllers when returning a response to a request.
Answer:
use Drupal\Core\Url;

// url to redirect
$path = '/my-path';
// query string
$path_param = [
 'abc' => '123',
 'xyz' => '456'
];
// use below if you have to redirect on your known url
$url = Url::fromUserInput($path, ['query' => $path_param]);
$form_state->setRedirectUrl($url);

Answer: This took me a while to figure out, so I thought I'd share.
I wanted to redirect the user to /admin after a custom admin form submission.  I could not find the admin route in Google searches.
I grepped all the routing ymls in core:
find -name \*.routing.yml -exec grep -l "path: '/admin'" {} \;

...and found it in ./modules/system/system.routing.yml
system.admin:
  path: '/admin'
  defaults:
    _controller: '\Drupal\system\Controller\SystemController::systemAdminMenuBlockPage'
    _title: 'Administration'
  requirements:
    _permission: 'access administration pages'

So my form redirect is:
$form_state->setRedirect('system.admin');

Needed a cache clear before it worked.
Answer: use Drupal\Core\Url;
use Drupal\node\Entity\Node;
use Symfony\Component\HttpFoundation\RedirectResponse;

$redirect_to_thankyou = new RedirectResponse(Url::fromUserInput('/thankyou')->toString());
$redirect_to_thankyou->send();

Works in Drupal 9 - 9.0.7, if you just want to direct to a URL on your site (haven't tested it on external URLs), rather than ponce about with routing.
Put it at the end of your submitForm function in your class that extends FormBase.
Comment: RedirectResponse is for Controllers. Forms need redirect set on the form_state.
Answer: If you want to redirect user edit form to the home page or other page follow below code.
First, add-hook - hook_form_alter`
function yourmodulename_form_alter(&$form, FormStateInterface $form_state, $form_id)
{
    if ($form_id === 'your form id') {
    $form['actions']['submit']['#submit'][] = 'modulename_user_edit_form_submit';
  }
}

after adding hook add below function
function modulename_user_edit_form_submit($form,  FormStateInterface &$form_state) {
  global $base_url; //set base path
  $response = new Symfony\Component\HttpFoundation\RedirectResponse($base_url ."/xyz"); //set url
  $response->send();
  return;
}

I hope this help.
Comment: You should have only `$form_state->setRedirect()` in the form submit so that all the other submit handlers can be processed.
Comment: Doesn't this bypass all the submit handlers that should fire after your handler?
Comment: RedirectResponse is not correct for form redirection. It is for Controller responses. As @joekers said, you just need to set the redirect.

Redirect after form submission


Dereferencing a copying the value of a unique_ptr

Question: I have a function that is given a unique_ptr to a string.  I want to copy that value is lambdas and use it to invoke functions that take std::string.  Is what I am doing below the right way to do this:
void someFunc(std::unique_ptr<std::string> id) {
    const std::string idStr = *id;
    stream.subscribe([=](auto arg1) { arg1.invoke(idStr); });
}

What I want to do is just copy the string into a new location.  Don't care about the id unique_ptr at that point.  I found this discussion that says that seems to indicate that I can do the following:
std::string idStr = std::move(id);

However, that does't actually work for me.  It fails with "no viable conversion" error.
Comment: `std::string idStr = std::move(id);` can't work when if is an `std::unqiue_ptr`. I think, you misunderstand the question.
Comment: `std::string idStr = *id;`
Comment: @SergeyA  I know it's not working for me.  However, your comment doesn't make sense to me.  In the linked discussion, it is also a unique_ptr.  In any case, what I am asking here is what I am doing (idStr = *id) is doing what I think it does and is the right way for me to move forward.
Comment: I do not understand what is the question. I have no idea if what you are doing is *right* or *wrong*, since you didn't tell us anything about your use case. What is the `stream`, what is the `subscribe`, what is the `invoke`?
Comment: `void someFunc(std::unique_ptr id)` is a bizarre function signature.  Since the `unique_ptr` is passed by value that means the call site is giving up ownership to it.  If you don't care about it, you aren't using it for anything, then why even take a `unique_ptr`.  You could just have `someFunc` take a string by value and move it into the lambda.
Comment: @Pratik `in the linked discussion, it is also a unique_ptr.` No, `S s;` is not a unique pointer.
Answer:
I have a function that is given a unique_ptr to a string. I want to copy that value
void someFunc(std::unique_ptr<std::string> id) {
    const std::string idStr = *id;

What I want to do is just copy the string into a new location.

That is a correct way to copy the pointed string, yes.

... that I can do the following:
std::string idStr = std::move(id);

That is ill-formed. You cannot do that. The examples in the linked question do not do that.


Best classifier machine-learning model for data with few samples

Question: What machine-learning algorithm do you use if you have an attribute matrix that was rows = samples and cols = attributes and a target vector that matched the attributes to a specific classifier?
Would I want something like a neural network?  Unfortunately, I have many more attributes than samples but only categories to classify (i.e. 0,1, and 2). Considering this, what would be the best algorithm to use for a dataset like the one below? Values will be positive floats.
My data looks something like the DataFrames below.  I'm trying to use the attributes to predict the target. I use Python for everything so I was going to try sklearn or tensorflow.
In the end, I would like to have a model that predict the classifier and ALSO to be able to output the important variables that were useful in the model prediction.
import pandas as pd
DF_attributes = pd.DataFrame([
                               [0.1, 12, 0.3, 0.4, 3.4],
                               [0.3, 15, 0.2, 0.7, 6.9],
                               [0.5, 10, 0.8, 0.4, 5.3],
                               [0.6, 13, 0.5, 0.5, 6.3],
                               [0.4, 11, 0.8, 0.4, 7.3],
                               [0.3, 11, 0.4, 0.5, 6.3]
                              ],index=["s1","s2","s3","s4","s5","s6"],columns=["att_1","att_2","att_3","att_4","att_5"])

SR_target = pd.Series([0,0,1,0,2,1],index=["s1","s2","s3","s4","s5","s6"])
    att_1  att_2  att_3  att_4  att_5
s1    0.1     12    0.3    0.4    3.4
s2    0.3     15    0.2    0.7    6.9
s3    0.5     10    0.8    0.4    5.3
s4    0.6     13    0.5    0.5    6.3
s5    0.4     11    0.8    0.4    7.3
s6    0.3     11    0.4    0.5    6.3
s1    0
s2    0
s3    1
s4    0
s5    2
s6    1
dtype: int64

Answer: I am guessing that your data will be much larger. If you are interested in using Python then for Neural Networks (NN) you can look into the library you mentioned tensorFlow but I also recommend looking into theano and lasange.
There are however many different algorithms that I would suggest for this type of classification based off of personal experience. There is an extension of gradient boosting machines library in both Python and R called xgboost. This particular library is very powerful and is responsible for a lot of winning algorithms on Kaggle.
Finally, I think you will find a fairly good classification in both the RandomForestClassifier and ExtraTressClassifier found in the sklearn.ensemble modules in python. In general, these algorithms perform fairly well and are also robust to things like missing values and outliers.
Note
Just to add a little more to this, another way to create a more powerful classifier would be to run all of the different algorithms mentioned above and take a majority vote of the classification.
Comment: Yes absolutely, one of the great things about these models is the aspect of variable importance. You, can find which variables are important to each model and incorporate the variables that help model your outcome the best!
Comment: My opinion may be a little biased but I would stick with the random forests or the gradient boosting machine. Reason, being is that NNs can be hard to tune. For a really comprehensive approach I recommend looking at this tutorial (also in python) explaining the mechanics of NNs. http://iamtrask.github.io/2015/07/12/basic-python-network/. This has really helped me when it comes to NNs.
Comment: w/ random forests, can you output which attributes were useful in making useful models? When I was doing linear regressions, I would do cross validation and then output the non-zero coefficeints (attributes) to a list that I could look at later.
Comment: Hey thanks the help.  Is there any benefit of using a neural network for something like this or are random forests the best way for this type of data?


What do you have on your PXE server?

Question: Basically, what cool utilities does everyone have loaded up on a PXE server ready to use on any computer you netboot from? I've just set one up at home with the following:

Clonezilla
Memtest86
Ubuntu Desktop and Ubuntu Netbook
remix 9.10
Gparted
Parted Magic

If I were to do this at work (and I plan to at some point) I'd probably add some sort of integrated deployment solution such as Cobbler as well. I'm just curious to see what other people have running.
Answer:
Darik's Boot and Nuke ("DBAN") is a self-contained boot disk that securely wipes the hard disks of most computers. DBAN will automatically and completely delete the contents of any hard disk that it can detect, which makes it an appropriate utility for bulk or emergency data destruction.
Breakin is Advanced Clustering's stress-test and hardware diagnostics tool.
Answer: I've yet to set mine up but the first thing I'll be putting on it is Bart PE, with all the plug-ins I like to have. I can no longer imagine life without it.
Answer: I have a bunch of things, as evident by my iPXE menu (see https://gist.github.com/robinsmidsrod/2234639).
The one I use more often is SystemRescueCD, SpinRite and OpenELEC. I also have DBAN and Breakin, same as knweiss.

What do you have on your PXE server?


Back in black sound

Question: I'm finally learning back in black from tabs after doing it by ear for a long time.
I've come to the iconic lick during the intro and its tab is given by this almost everywhere:

For the life of me I can't figure out how to fit in the second pull off from 3 to 0 on the B string. I've listened to the record version over and over again and I just cannot hear the open B.
Is it just played very quickly or missed out when Angus plays it sometimes?
I know the lick starts an extra 1/16th in than what you might first expect and putting in this extra note seems to throw off my playing.
Does anyone have any tips or sympathise with what I'm saying? Input would be really appreciated!
Comment: Bad tab is not unknown
Comment: Just gave it a listen on Youtube and I can hear it just fine. Perhaps "doing it by ear for a long time" (apparently incorrectly) has conditioned your ear to hear what it's expecting instead of what's actually there.
Comment: The tab seems good to me, but I'm not sure how to answer this question, since we already have the tab and we already have a recording of how it sounds.  Maybe writing the beats on top of the tab would help?  Or a video of someone playing it?
Comment: I can hear it clearly. The more you play and listen critically the more your ear will develop and you'll be surprised at what you start hearing that you didn't hear before.
Comment: I can also hear it. The issue for me is how to do a one-tone bend on the G string from fret 2. That is hard!
Comment: Thank-you all, I'll just listen and practice more. I expect I've almost trained myself not to hear it so that might take some undoing.
Answer: I recognize that this is an unusual answer format for this site, but I think this is the best way I can illustrate the timing here.  It's not the open B that's played quickly but rather the bend that is quick.

Back in black sound


How to find the result of following matrix operation

Question: Given$$A=\begin{pmatrix}
0&1\\
-12&8
\end{pmatrix}$$
To find$$A^5-6A^4-3A^3+17A^2-A+19I_2$$
I cannot come up with a simple algorithm to solve the polynomial, and I did use NumPy to calculate the result, which turned out to be extremely large (like $a_{21}=2081253036$).
This problem appears in a math test so I don't think the result should be that huge. What is the right way to find the correct answer?
Comment: You can use $A^2=8A-12I$.
Comment: Also ```>>> arr=np.array([[0, 1],[-12,8]])
>>> ans=np.linalg.matrix_power(arr,5) - 6*np.linalg.matrix_power(arr, 4)-3*np.linalg.matrix_power(arr, 3)+17*np.linalg.matrix_power(arr,2)-arr+19*np.eye(2)
>>> ans
array([[  7.,  -5.],
       [ 60., -33.]])```, so you must have done something seriously wrong in numpy.
Comment: Is the question simply to find that Sum/Difference?
Comment: @rschwieb Yes, you are right, sorry for the mistake.
Answer: Simply use CAYLEY HAMILTON theorem to get the characteristic equation of $A$ as
$A^2-8A+12I=0$.
Now note that $A^5−6A^4−3A^3+17A^2−A+19I2= (A^2-8A+12I)(A^3+2A^2+A+1) - 5A+7I2$ (due to polynomial division). Since $A^2-8A+12I=0$, we have $A^5−6A^4−3A^3+17A^2−A+19I2= 7I2 - 5A$, which is easy to calculate : )
Comment: This method is cool, thank you a lot.
Comment: @B.W.Zhang you're welcome. Note that sometimes the questions can be a bit tougher like find A^50. In those cases pattern observation and induction work really well (clearly polynomial division becomes infeasible there). Pattern observation means something like A^3= A or on some elements of A (often asked in JEE exam).
Answer: You can find the eigenvalues $\lambda$ of matrix $A$ by solving $\det(A-\lambda I)=0$, where $I$ is the $2\times 2$ identity matrix, which gives $\lambda=2,6$, from where you can find out the eigenvectors $v_1,v_2$, such that $Av_1=2v_1, \ Av_2=6v_2$ by solving two pairs of simultaneous equations.
Then taking $v_1,v_2$ to be the columns of a $2\times 2$ matrix $Q$, you should have $A=Q\Lambda Q^{-1}$, where $\Lambda = diag(2,6)$ is the diagonal matrix with eigenvalues of $A$ on the diagonal.
Finally, this helps because $A=Q\Lambda Q^{-1} \implies A^n = Q\Lambda^n Q^{-1}$.
P.S. Angina's comment emphasises the polynomial (in $\lambda$) you get when you put $\det(A-\lambda I)=0$, the characteristic polynomial of $A$.
Comment: I actually had tried this before posting the question, but it seemed still to take a lot of computation as 6^5 is a large number and $Q^{-1}$ consists of fractions. But thank you all the same for giving this suggestion. :-)
Answer: Diagonalize A, i.e. find the matrix of eigenvectors such that $A=V^{-1}DV$, with D the diagonal matrix of eigenvalues. Note that $A^n=V^{-1}D^nV$. $D^n$ is easy to calculate since it's diagonal. Now, rewrite the equation as
$V^{-1}(D^5-6D^4-3D^3+17D^2-D+19 I)V$
Should be easier


Como usar os comando do Git sem sudo?

Question: Sempre que preciso usar alguns comandos como git pull, git stash, aparece uma mensagem que não foi possível realizar a operação pelo fato da permissão não ser suficiente. Como faço para que não precise usar o sudo?
Comment: O usuário que você está usando não tem permissão para alterar as pastas que esses comandos estão tentando alterar. Em que pasta estão os seus arquivos? Tente colocar em uma pasta do usuário.
Comment: tentou dar o comando "sudo -s" e a senha de admin.. é isso que precisa ?
Answer: Você tem duas opções:
1) Fazer o checkout como outro usuário. ("git checkout ...").
2) Alterar a permissão em todo o projeto para que o usuário que você quer possa utilizar o sistema de arquivos. (chown -R)
Comment: Realmente isso, a segunda opção deu certíssimo!! Estou trabalhando em uma máquina homologada e com o docker, assim o docker setou o meu usuário no container com id de usuário 1000, mas a minha maquina tem um id gerado pela empresa, quando executava os comandos nao tinha permissao mesmo... Obrigado!!

Como usar os comando do Git sem sudo?


Multilingual site title

Question: I've got a problem translation my site title with the Configuration translation module. I set my set title to let's say XXX which is not displayed by the tamplte at all. Instead, it always attaches "| Drupal" string to the end of the node title.
When I click to add translation, translate the string to let's say YYY and save the form, everything appears to be saved correctly, the English version of my site even displays the correct title. However, the form for adding Site information translation still displays an "Add" button as if nothing had been added before and the default version of the site continues to display the "| Drupal" string even though my site name is set to XXX.
Has anybody else experienced the same behaviour?
Answer: Well, I have experienced a similar problem when manipulating with more language versions. In the config database table, I had two rows with the name system.site - one of them had a collection = "language.sk" and the other (full record) had an empty collection and in the data column langcode SK. So, I think the interface was confused, because there were two rows for one language. However, I do not know how the database got into this state.
So I have deleted the row with collection = "language.sk", cleared the cache and now you can change source site name and also create translations - it started to work. Please try this and let me now, if that works.

Multilingual site title


Form Submission Problem

Question: I've a form...
function modulename_myform($form, &$form_state)
{
        $form['my_ta'] = array(
            '#type' => 'textarea',
            '#resizable' => FALSE,
        );
        $form['my_submit'] = array(
            '#type' => 'submit',
            '#input' => TRUE,
            '#value' => 'Submit',
            '#name' => 'sub_1',
            '#button_type' => 'submit',
        );
        return $form;
}

My form couldn't submit any data... So I tried doing two variants...
/* Form Submit */
function modulename_myform_submit($form, &$form_state)
{
    drupal_set_message('Submitted Value @name',array('@name'=>$form_state['values']['my_ta']));
}

Output : Doesn't print anything and says value is null at that location...
/* Form Submit */
function modulename_myform_submit($form, &$form_state)
{
    drupal_set_message(t('Submitting values: @values', array('@values' => var_export($form_state['values']['my_ta'], TRUE))));
}

Output : Prints the Dump with proper values...
Why is that? It should be giving me the text entered in my_ta right? Please help me...
Answer: the first attempt doesn't contain t() function in set message function... hence it's failing...
Answer: The 1st would not work as it is neither default and nor explicitly defined against #submit.
For first to work:
$form['#submit'] = array('modulename_myform_submit')

The 2nd should work.
If still it is not getting submitted then make sure the form is properly rendered and processes by drupal_get_form()
Comment: The submission handler is invoked, as it has the default name a submission handler should have. If that would be the problem, the submission handler would do nothing in both the cases. As the OP reported, in the first case the code is missing the call to `t()`.

Form Submission Problem


How to reference URL relative to current page in a block

Question: I have a custom block where I need to reference a URL relative to the current page (such as node/7/images or node/293/images) that will link to the "Images" view mode I made for the node. I am using a module so that a view mode is accessible via URL (which I have as node/#/images), but I am having trouble getting a working link to /images that would work on any given node.
I have tried to link it to /images and /#/images but have gotten a 404 each time, likely because it is going to example.com/images or example.com/#/images. I have also tried using the Token for current page URL which 404'd as well.
Is there a way, hopefully through the UI, in which I can reference the current node in a way that on any given node the link to the "Images" view mode will link to /node/[current node #]/images?
I have seen ways to implement it using custom modules or code, but I am not very experienced with putting custom code into Drupal and prefer to use the UI is possible.
update
I briefly had a fix, but then I broke it.
I had got it working adding a link that referenced "images/" (without the quotations). While viewing the node, the custom block originally linked to example.com/node/#/images as intended.
However, I then configured the block to be hidden on */images (wasn't necessary to link to the view while viewing it). After I did this, the link broke on the node page, instead now referencing to example.com/node/images, missing the node # in the URL. I have no idea how this got broken as I only worked through the UI
I tried deleting the block then adding it again with no effect
Using "#/images" will direct to /node/123#/images (adding the actual # into the URL) - while this gets the current node id into the URL it doesnt work with the presence of the # symbol
Answer: Adding a relative path (without the starting "/") is WRT the current "directory", so when you're on a node page the "directory" is "node" and the NID is the "page". Your "images" is supposed to be another page within the same "directory". That's the simplified explanations about how relative paths work in general.
To solve your problem the easiest way is probably through a Token. Do you have Token Filter or a similar module installed and configured? If your Text format doesn't evaluate tokens you won't get the correct output.
Try some available tokens in your text and see what they output. Maybe there's a [current:path] or similar token, or [current:nid]. When you find one with the output you like you can contruct the link:
Images
or
Images
If you need more control over the Block Visibility you can try Block Exclude Pages.
Another way to create contextually aware links is through Views (Block display). You would have a Node ID as the contextual filter, and override the Link to content field to add "/images" at the end of it.


Why chrome ignores border radius when a box inner shadow is set?

Question: Take a look at this in both chrome and firefox: http://jsbin.com/imuxe3
As you see, it renders fine in firefox, but chrome literally ignores the -webkit-border-radius CSS rule when adding a -webkit-box-shadow with inset mode.
Can some one explain/get a solution for this?
Thanks
Answer: It seems to be a bug in chrome. However you can use a workaround by defining a simple border: rule.
For more Details see this:
http://code.google.com/p/chromium/issues/detail?id=29427
Comment: I will +1 for the link when it's tomorrow (and I have votes again).
Answer: I wondered about this recently, myself.
Although, looking at my button in Chrome dev now, it's fixed.
So you must simply wait for the fix to the issue mentioned by @mightyuhu to be pushed to the stable version of Chrome.


How to run Django task periodically on Heroku?

Question: I have a Django application deployed on Heroku using 1 web dyno, basically just hosting a website where people can signup, then the app can send emails to those people.
Right now I send all the emails manually; I go in django shell everytime on heroku server, and call function like a.send_customized_email()
I'm wondering how to make a scheduler thing to send emails periodically without me coding in commands in the backend everytime?
I heard about Django celery, but how to integrate it exactly? Should I fire up another dyno? What should be the configuration files?
Thanks in advance.
Answer: In settings.py file you can use
from celery.schedules import crontab

app.conf.beat_schedule = {
    # Executes every Monday morning at 7:30 a.m.
    'add-every-monday-morning': {
        'task': 'a.tasks.send_customized_email()',
        'schedule': crontab(hour=7, minute=30, day_of_week=1),
        'args': (16, 16),
    },
}

and in your tasks.py file you can specify what send_customized_email() is


Including line breaks & bullet points in a Facebook graph post function

Question: I'm trying to allow my users to post a bulleted list from my webapp to their Facebook feed. The list is created in a form (with bullets & line breaks) that can then be edited and submitted.
My code works fine when sending regular text (posting the form contents to FB feed), but it breaks when the message has bullets (●●) and line breaks (
) aren't recognized.
I've tried a bunch of different ways of encoding the message, but none of them work. Here's my FB function:

My questions are how should I encode $share_text, which comes from a POST form, and should I use a different way to write bullets & line breaks so that Facebook understands there are bullets and line breaks?
If I copy bullets and line breaks into a status update they work fine, so I assume this is possible.
EDIT: I've narrowed the problem down to the line breaks. I can post bullets to FB if there are no line breaks in the text. I think the issue is that html encoding of
 includes ;'s.
Thanks
Comment: I just watched the video regarding Section 2.3 - Prefilling Content. My method is completely within the guidelines. Users submit different lines of text to me. They click a button to share this text. I show them a text box that gets filled with the text they already gave me and tell them they can share to Facebook. If they click Share, it posts that exact message to Facebook. I don't append anything to their message and I don't auto-fill anything into their message. I show them the message they chose to share so they can edit it, then I post it if they say OK. It is not a policy violation.
Comment: The message the user them self need to manually type every single character. You are saying that they are adding linebreaks and bullets?
Comment: I add the line breaks and bullets initially, but the user has the ability to edit them before submitting the dialog to share on FB. I obviously want the line breaks and bullets to be processed correctly on the FB share side of things.
Comment: You are not allowed to prefill the message. The user have to type every single character in the message
Comment: I can prefill the message just fine as long as I don't put in bullets or line breaks. If I put bullets/line breaks in, it breaks. https://developers.facebook.com/docs/javascript/quickstart/v2.1#graphapi That link outlines exactly what I did, I just replaced "hello, world" with whatever I want to post.
Comment: You can not prefill the message according to Facebook Platform Policy: https://developers.facebook.com/policy .
Comment: Well it let's me do it by simply following the steps in their tutorial. Either way, that's not the issue. The issue is when special characters are in the message.
Comment: I didn't say it was technically impossible. I said it wasn't allowed. When you apply for the publish_actions permission that you will need they will deny the request because you are not following the policy
Answer: Figured it out. The problem was the line breaks themselves.
My solution was to take a textarea input $input, change all the line breaks to
 via nl2br($input),
replace all the
 to \r\n\r\n via str_replace('
','\r\n\r\n',nl2br($input)) because Facebook recognizes \r\n\r\n as a new line
and then remove all hidden line breaks via preg_replace( "/\r|\n/", "",str_replace('
','\r\n\r\n',nl2br($share)));
Taking the user's form input and running it through that last preg_replace function allows Facebook to read it correctly and post a bulletted list with line breaks!


Migrated Virtual Machine Shows Up in Both Datastores

Question: We're using Vsphere client 4.0.0 Build 208111 with Virtual Center Server same version and same build.
I have one vm with only one disk that is shown on 2 different datastores. If I look through VMs and Templates I see only 1 vm. If I look through Datastores screen, I see it in datastore-002 and datastore-003. If I go to settings of the virtual machine on datastore-002 and check the disk, I see the path as datastore-003.
How can I fix this ?
Comment: Hi

On which datastore is the vmdk (.vmdk and -flat.vmdk)?

did the migration of the virtual machine raise any error or was it successfull?

Did you do a *datastore migration* or did you migrate the vm onto another host?
Answer: Right-click on both of those datastores and verify whether there's a folder in each one called VMNAME.
If there's a folder in only 1, then you probably have an ISO mounted on the VM and it's located on the second datastore.
If there's a folder for the VM in both datastores, check inside and see if both folders have a .vmdk inside. If they both have the disk VMDK file, then you probably got in a situation where a storage vMotion didn't completely finish up and the old files were left hanging around on the old datastore. This happens a fair bit. To fix, right-click the VM and select 'Edit Settings'. Select the hard disk device, and make a note of the datastore it's on. You can then safely delete the VMDK in the other datastore.
It's also possible to have a VM's configuration files on one datastore, and the VMDK hard drive file on another datastore. So if you find a folder for the VM in both locations, see if one of them has the .vmx, and the other one has the .vmdk. You can easily get around this problem by storage vMotioning the VM to an entirely different datastore.
Answer: This can occur if you have, e.g., an ISO image mounted from a particular datastore.
Answer: In fact it can occur if you have an ISO mounted at all. Strangely the ISO doesn't need to be on the same datastore, at least with ESXi-5.5. I suspect there's a lockfile or an in-memory record that doesn't get changed during Storage VMotion.
Answer: In my experience, I saw where a Serial device was installed on a particular LINUX VM.  It was not connected.  Upon further inspection, the original datastore still contained a single file: "serial.log."
I simply highlighted the device, and changed the DS directory where it's "output file" was set for.  I changed it from the old DS to the new DS where I migrated it to.
In this case, it wasn't the common, "mounted ISO", or "snapshot" that was the issue.


Explained variance in dimensionality reduction

Question: I am new to dimensionality reduction and I am trying to learn different techniques about it. I am noticing that, unlike PCA, many other algorithms do not provide the explained variance of each feature (or am I wrong?). That said, how do I choose the size of the reduced feature?
I would appreciate also some reference to read about the state-of-the-art algorithms for nonlinear dimensionality reduction.
Answer: Suppose your input is $X_{m \times d}$, where $m$ is the number of data points and $d$ is the dimension of each point.  The total variance is a property of your input $X$; call it $v(X)$.
Now, suppose the reconstructed input after applying dimensionality reduction is $\tilde{X}$ (of the same dimensions), it has a variance $v(\tilde{X})$.
Then the fraction of variance explained is simply: $v(\tilde{X})/v(X)$.
This doesn't depend on how you implement the dimensionality reduction.  For PCA, the explained variance can be computed directly from the eigenvalues of the covariance matrix.  For other non-linear techniques, you can compute the reconstruction and then compute the explained variance from its intuitive definition.
Comment: When I try it with PCA I get completely different results. In my case I have 14 features and using the eigenvalues I get that the first 5 are sufficient to explain all the variance. Doing what you suggested I get that only the first 2 are needed.
Comment: Could you post your matrix (if it's small), its eigenvalues and the list of explained_variance_ratio output by your PCA algorithm?
Comment: My bad. I forgot that Matlab automatically centers and standardize the input data. Doing as you said returns the same result as using the eigenvalues. Thanks!


How to find a quadrature formula of a specific shape?

Question: What are the steps one needs to follow to find a quadrature formula of a certain shape with maximal degree of precision.
For example: Find a quadrature formula of the following shape

$\int_1^2 (x^4 - 1)f(x)dx = A_1f(x_1) + A_2f(x_2) + A_3f(x_3) + R_3(f)$

Should I start by changing the interval to [-1, 1] and then somehow change the formula to a known orthogonal polynomial, Legendre for example ?
Answer: You need to construct the Gaussian quadrature for a specific weight function, $w(x) = x^4 - 1$ in your case.
Start with constructing polynomials orthogonal with that weight, i.e.
$$
\int_1^2 P_m(x) P_n(x) w(x) = C_n \delta_{nm},\qquad \operatorname{deg} P_n(x) = n.
$$
Since you need a quadrature with three points, the nodes of the quadrature are roots of the $P_3(x)$ polynomial. The easiest way to build the orthogonal set by hand is to apply Gramm-Schmidt process to the $1, x, x^2, x^3$ set.
$P_0(x)$ is constant and could be taken as $1$ without loosing any generality. $P_1(x) = x - \alpha$. Since $P_1(x)$ should be orthogonal to $P_0(x)$ we have
$$
\int_1^2 P_1(x) P_0(x) (x^4-1)dx = \int_1^2 (x-\alpha)(x^4-1) dx = 9 - \frac{26}{5}\alpha = 0,
$$
so $\alpha = \frac{45}{26}$.
Next, $P_2(x) = x^2 - \beta x - \gamma$. Integrating with $P_0(x)$ and $P_1(x)$ we have
$$
\int_1^2 P_2(x) P_0(x) (x^4-1)dx = \frac{332}{21} - 9\beta -\frac{26}{5}\gamma = 0\\
\int_1^2 P_2(x) P_1(x) (x^4-1)dx = \frac{555}{728} - \frac{127\beta}{546} = 0,
$$
so $\beta = \frac{1665}{508}, \gamma = -\frac{56165}{21336}$. (Ewww)
Finally, $P_3(x) = x^3 - \delta x^2 - \epsilon x - \zeta$.
$$
\int_1^2 P_3(x) P_0(x)(x^4-1)dx = -\frac{332 \delta }{21}-9
   \varepsilon -\frac{26 \zeta
   }{5}+\frac{225}{8}\\
\int_1^2 P_3(x) P_1(x)(x^4-1)dx = -\frac{555
   \delta }{728}-\frac{127
   \varepsilon
   }{546}+\frac{17783}{9360}\\
\int_1^2 P_3(x) P_2(x)(x^4-1)dx = \frac{18419}{284480}-\frac{40337
   \delta }{2987040}
$$
And the $P_3(x)$ is $$P_3(x) = x^3 -  \frac{386799}{80674}x^2 +\frac{4566058}{605055}x - \frac{2512489}{645392}$$ with roots
$$
x_1 \approx 1.24311506656362394748261056490...\\
x_2 \approx 1.62867605333517443866228087173...\\
x_3 \approx 1.92280193362526141007198140964...
$$
Now we are able to compute the weights by integrating Lagrange basis polynomials
$$
w_i = \int_1^2 \ell_i(x) (x^4 - 1) dx, \qquad \ell_i = \prod_{j \neq i} \frac{x-x_j}{x_i - x_j}\\
w_1 \approx 0.498562063242571816059749610...\\
w_2 \approx 2.242930705042292632885672141...\\
w_3 \approx 2.458507231715135551054578248...
$$
Checking that it actually works for integrating every polynomial of degree up to five including:
$$
\int_1^2 1 (x^4 - 1)dx = 5.2 = w_1 + w_2 + w_3\\
\int_1^2 x (x^4 - 1)dx = 9 = w_1 x_1 + w_2 x_2 + w_3 x_3\\
\int_1^2 x^2 (x^4 - 1)dx = 15.809523 = w_1 x_1^2 + w_2 x_2^2 + w_3 x_3^2\\
\int_1^2 x^3 (x^4 - 1)dx = 28.125 = w_1 x_1^3 + w_2 x_2^3 + w_3 x_3^3\\
\int_1^2 x^4 (x^4 - 1)dx = 50.577777 = w_1 x_1^4 + w_2 x_2^4 + w_3 x_3^4\\
\int_1^2 x^5 (x^4 - 1)dx = 91.8 = w_1 x_1^5 + w_2 x_2^5 + w_3 x_3^5\\
\int_1^2 x^6 (x^4 - 1)dx = 167.9480519 \neq 167.947233 = w_1 x_1^6 + w_2 x_2^6 + w_3 x_3^6.
$$


How to filter a dataframe based on column values(multiple values through a arraybuffer) in scala

Question: In scala/spark code I have 1 Dataframe which contains some rows:
col1      col2
Abc       someValue1
xyz       someValue2
lmn       someValue3
zmn       someValue4
pqr       someValue5
cda       someValue6

And i have a variable of ArrayBuffer[String] which contains [xyz,pqr,abc];
I want to filter given dataframe based on given values in arraybuffer at col1.
In SQL it would be like:
select * from tableXyz where col1 in("xyz","pqr","abc");

Answer: Assuming you have your dataframe:
val df = sc.parallelize(Seq(("abc","someValue1"),
                            ("xyz","someValue2"),
                            ("lmn","someValue3"),
                            ("zmn","someValue4"),
                            ("pqr","someValue5"),
                            ("cda","someValue6")))
                 .toDF("col1","col2")

+----+----------+
|col1|      col2|
+----+----------+
| abc|someValue1|
| xyz|someValue2|
| lmn|someValue3|
| zmn|someValue4|
| pqr|someValue5|
| cda|someValue6|
+----+----------+

Then you can define an UDF to filter the dataframe based on array's values:
val array = ArrayBuffer[String]("xyz","pqr","abc")

val function: (String => Boolean) = (arg: String) => array.contains(arg)
val udfFiltering = udf(function)

val filtered = df.filter(udfFiltering(col("col1")))
filtered.show()
+----+----------+
|col1|      col2|
+----+----------+
| abc|someValue1|
| xyz|someValue2|
| pqr|someValue5|
+----+----------+

Alternately you can register your dataframe and sql-query it by SQLContext:
var elements = ""
array.foreach { el => elements += "\"" + el + "\"" + "," }
elements = elements.dropRight(1)
val query = "select * from tableXyz where col1 in(" + elements + ")"

df.registerTempTable("tableXyz")
val filtered = sqlContext.sql(query)
filtered.show()
+----+----------+
|col1|      col2|
+----+----------+
| abc|someValue1|
| xyz|someValue2|
| pqr|someValue5|
+----+----------+


ADB not responding. If you'd like to retry, then please manually kill "adb.exe" and click Restart

Question: I am new to android studio, as i run android studio, this error is poped out.can anyone help me out with this error
Answer: try sudo adb devices  - it restart youre adb.
if you have 64 bit Ubuntu more than 13 version, try install lid32ia like this sudo apt-get install lib32z1 lib32z1-dev lib32stdc++6


How much horsepower is needed to have 100Mbit/sec OpenVPN throughput?

Question: My small ALIX machine is not coping with the new demand for OpenVPN throughput I have. So I'm looking to replace it. Problem is, I don't have any experience with hardware sizing for OpenVPN. I'm looking for something that satisfies this profile:

= 100Mbit/sec Througput

Cipher either AES-128-CBC or AES-256-CBC or Blowfish
Small power footprint

I've been looking into pairing a small Atom single-core with a PCI GigE nic, but have my doubts.
What works for you?
What can you recommend?
Any answers like "I get x Mbit/sec with this rig" also very much appreciated to get a feeling for it.
Thanks in advance.
Comment: What OS? If the OS support crypto acceleration boards then this Soekris board will allow an Alix to push most of that connection: http://soekris.com/vpn1401.htm You'd still be limited to the 100Mbit connections (and the nic-chips on the Alix have a hard time saturating the connection).
Comment: That's what I thought *grin* Bought a vpn1411 for my Alix 2D3, put "engine cryptodev" in OpenVPN config and "cipher AES-128-CBC" and ... 10 Mbit/sec. To be honest I think this hardware acceleration sucks on ALIX because of Interrupt latency. Some other folks confirmed that. But maybe we all miss something? EDIT: I'm on OpenBSD 4.6 i386
Comment: @leto - from the FAQ: "If you are not comfortable with the idea of your questions and answers being edited by other trusted users, this may not be the site for you." My edits were for grammar, proper capitalization, and setting the proper form of "horsepower", which is supposed to be one word. As the FAQ said, if you're not comfortable with others editing your questions/answers, then you may want to go elsewhere.
Comment: I didn't see any difference. Sorry for that, I normally also correct errors of people, I promise to be better next time. I'm kind of new here. Will check out the FAQ now.
Comment: No problem, just making sure you were brought up to speed on how things go around here.  Welcome!
Comment: How many concurrent VPN connections?  These primarily road warriors?
Comment: The Setup looks like this: (home network)<--GigE-->(openvpn router)<--100Mbit-->(Internet)<-->(dedicated server). It's to get a static IP at home, so we're talking about one connection, the router acting as a client. Maybe three connections maximum in the forseeable future, but that would be the worst case. The client is on a dynamic IP, so yes, a road warrior.
Comment: @Leto, I've had an Alix2C10 (2D3 w/o some pins) with the LX700, VPN1411, FreeBSD 8.1, IPSec AES 128 CBC did about 40Mbps (lightning got it). A friend has a similar setup and it does 60Mbps. I've heard of problems in the past with software not using the hardware, possibly the case here? Or Maybe the 2D3 has issues I'm not aware of, do you have any links to more info?
Answer: Getting 100 Mbps throughput is easy, getting much more than 300 Mbps throughput is very hard (on Linux). This is due to the 'tun'/'tap' design in the Linux kernel.
Also, the blowfish algorithm is largely clockspeed bound, as I've found out when comparing hardware that ranged from brandnew to 8 yrs old.
AES128 and AES256 might benefit from Intel's AES-NI patch which seems to speed things up even on non-AES-NI capable hardware.
Anything running more than 800 MHz should be fine to get 100 Mbps throughput, with decent GigE cards (intel, broadcom, etc).
Answer: You need at least:

decent GBit NICs. Cheap NICs generate too much interrupts per traffic, which hogs CPU.
when the machine doesn't do anything else, a 800MHz to 1GHz x86 (Atom) should do
look into a VIA CPU. They've integrated crypto, which lends itself very good to machines designated as VPN concentrator.
Comment: Good to hear, they have a very amicable power footprint, AFAIK. What are you using exactly? I've read there are differences concerning Padlock features. What would you opt for?
Comment: The basement junk yard says: Get a D510 Atom dual-core, I have the DDR2 memory, the Intel GbE desktop NIC (PCI) and some USB-Sticks for RAID1. It has interrupt moderation and TCP offload. The VIA mainboards are nice, no question. But after I've been burn't with interrupts and latency with the vpn1411 I guess I would like to try a software only solution. What do you think? Intel Atom + Intel 1000 GT? Greets
Comment: I've been burned by vpn1411 too, the VIA C7/Eden CPUs are different, because the crypto is builtin into the CPU. Works great and, at least with OpenBSD, out-of-the box.
Comment: I've come across the J7F4K1G5S with a VIA C7 CPU (http://www.jetwaycomputer.com/spec/J7F4K1G5S.pdf). Might it possibly push 100Mbit/sec AES-128-CBC? Thanks in advance
Comment: this look almost like too much :-) I don't know, how efficient OpenVPN is, but with a http://www.liantec.com/product/emboard/EMB-5730.htm (C7 500MHz) we did about 50-60 MBit IPSec (AES+SHA) with CPU utilization <15%, so I think you will be fine.


Proving Integral Inequality

Question: I am working on proving the below inequality, but I am stuck.

Let $g$ be a differentiable function such that $g(0)=0$ and $0<g'(x)\leq 1$ for all $x$. For all $x\geq 0$, prove that
$$\int_{0}^{x}(g(t))^{3}dt\leq \left (\int_{0}^{x}g(t)dt  \right )^{2}$$
Answer: Since $0<g'(x)$ for all $x$, we have $g(x)\geq g(0)=0$. Now let $F(x)=\left (\int_{0}^{x}g(t)dt  \right )^{2}-\int_{0}^{x}(g(t))^{3}dt$. Then
$$F'(x)=2g(x)\left (\int_{0}^{x}g(t)dt  \right )-g(x)^3=g(x)G(x),$$
where
$$G(x)=2\int_{0}^{x}g(t)dt-g(x)^2.$$
We claim that $G(x)\geq 0$. Assuming the claim, we have $F'(x)\geq 0$ from the above equality, which implies that $F(x)\geq F(0)=0$, which proves the required statement.
To prove the claim, we have
$$G'(x)=2g(x)-2g(x)g'(x),$$
which is nonnegative since $g'(x)\leq 1$ and $g(x)\geq 0$ for all $x$. Therefore,
$G(x)\geq G(0)=0$ as required.
Comment: @Ashok: This is a nice typical way of proving such functional inequality. As done here, to prove a functional inequality is to first check if the function is monotone and accordingly check if the inequality is satisfied at the desired end points. In essence it is checking whether the inequality is satisfied for the desired extremum of the function. If so, then the inequality is satisfied for the entire function.
Comment: Paul, I completely understand the mathematics here. Can one think of having some geometrical/physical meaning for coming up with such a proof? Or is it just from a trial basis?
Comment: Thank you very much @Sivaram.You are absolutely right.
Answer: It's straightforward: The function $g$ is positive for all $x>0$. Therefore $g'(t)\leq 1$ implies
$$2 g(t)g'(t)\leq 2 g(t)\qquad(t>0)\ ,$$
and integrating this with respect to $t$ from $0$ to $y>0$ we get
$$g^2(y)\leq 2\int_0^y g(t)\ dt\qquad(y>0)\ .$$
Multiplying with $g(y)$ again we have
$$g^3(y)\leq 2 g(y)\ \int_0^y g(t)\ dt ={d\over dy}\left(\Bigl(\int_0^y g(t)\ dt\Bigr)^2\right) \qquad(y>0)\ ,$$
and the statement follows by integrating the last inequality with respect to $y$ from $0$ to $x>0$.

Proving Integral Inequality


setErrorByName not working properly if field is in #details

Question: In a form, some fields are defined in '#details':
$form['person2'] = [
  '#type' => 'details',
  '#title' => t('Person2'),
];
$form['person2']['lastname2'] = [
  '#type' => 'textfield',
  '#title' => $this->t('Last Name'),
  '#size' => 32,
  '#default_value' => $this->store->get('lastname2') ? $this->store->get('lastname2') : '',
];
$form['person2']['firstname2'] = [
  '#type' => 'textfield',
  '#title' => $this->t('First Name'),
  '#size' => 32,
  '#default_value' => $this->store->get('firstname2') ? $this->store->get('firstname2') : '',
];
$form['person2']['email2'] = [
  '#type' => 'email',
  '#title' => $this->t('Email'),
  '#size' => 64,
  '#default_value' => $this->store->get('email2') ? $this->store->get('email2') : '',
  '#weight' => $weight,
];

In validateForm() I have some controls: if one of the fields has a value, the others should have one too.
I use setErrorByName but I can't have the faulty field highlighted in red, though the control fires as expected...
Here is the code:
  if (!$form_state->getValue('firstname2')) {
    $form_state->setErrorByName('lastname2', $this->t('This field is required.'));
  }

Comment: @Leigh Might be wrong, but I think you exclude the leading/trailing bracket for that pattern? e.g. `'person2][firstname'`
Comment: Try something like `$form_state->setErrorByName('[person2][firstname]', $this->t('This field is required.'));` as your field is a child of a container you need to specify the container in the name
Comment: It seems it is more a CSS thing: in the theme used for my site, there are no `.form-item input.error` definition... When I add it, it works.
Answer: Answer provided by Clive in comment is the correct one.
$form_state->setErrorByName('person2][lastname2', $this->t('This field is required.'));

Though if you just want to make the field required it would be better to do:
$form['person2']['lastname2'] = [
  '#type' => 'textfield',
  '#title' => $this->t('Last Name'),
  '#size' => 32,
  '#default_value' => $this->store->get('lastname2') ? $this->store->get('lastname2') : '',
  '#required' => true,
];


multisite not working: one site correctly redirected, the other one throwing 500 error

Question: Using  Ubuntu 16.04.7 LTS and Drupal 7.
Installed Drupal on /var/www/html/drupal
Created folders
/var/www/html/drupal/sites/siteone.org.es
/var/www/html/drupal/sites/sitetwo.com

Added settings.php inside the folders above
Modified /etc/apache2/apache2.conf to include
<VirtualHost *:80>
DocumentRoot /var/www/html/drupal
ServerName sitetwo.com
SeverAlias *.sitetwo.com
</VirtualHost>

<VirtualHost *:80>
DocumentRoot /var/www/html/drupal
ServerName siteone.org.es
SeverAlias *.siteone.org.es
</VirtualHost>

When I go to Firefox and navigate to sitetwo.com it works fine and the Drupal site is loaded without issues. However, when I navigate to siteone.org.es I get a 500 error. These are the details from Firefox:
HTTP/1.1 500 Service unavailable (with message)
Date: Sun, 28 Aug 2022 09:58:46 GMT
Server: Apache/2.4.18 (Ubuntu)
X-Drupal-Cache: MISS
Expires: Sun, 19 Nov 1978 05:00:00 GMT
Cache-Control: no-cache, must-revalidate
X-Content-Type-Options: nosniff
Content-Language: es
X-Frame-Options: SAMEORIGIN
Permissions-Policy: interest-cohort=()
X-Generator: Drupal 7 (http://drupal.org)
Content-Length: 0
Connection: close
Content-Type: text/html; charset=utf-8

any clue what am I missing?
Comment: 500 errors are logged. Examine logs for more information.
Comment: where are they logged? there's nothing about 500 errors on `/var/log/apache2/error.log`
Comment: There is an older article at https://www.drupal.org/node/158043 covering this. System logging levels and locations and PHP error reporting  are particular to how you set up the platform.
Comment: How does your sites.php file look like?
Answer: I figured out what the the issue was by visiting /update.php on the site and reading the detailed error message. Several not installed modules were the main reason, among others.


Affine transformation of the curve for the complex line integral.

Question: I'm studying the efficient ways to calculate for the complex line integral.Though this question  looks like silly, I want to check my thought is right or not.
Let the complex function $f : \mathbb{C}\to \mathbb{C}$
Say the  curve $C_r$ on the complex plane. Define the function $\phi : C_r \to C'_r$ by $z\to w $ (Here the mapping $\phi$ is either rotation, the symmetry or scaling)
From this we get  $w= \phi (z) $  and $dw = \phi'(z) dz $
As the example, I took the $\phi$ that rotation as $\frac\pi 2$ counter-clockwise. (I.e. $\phi : z \to w(=iz)$)
Then Does the $\int_{C_r} f(z) dz = \int_{C_r'} f(\frac{w}{i})\frac{dw}{i}$ hold?
Plus If we generalize this thought, Could we say $\int_{C_r} f(z) dz = \int_{C_r'} f(\phi^{-1}(w)) \frac{dw}{\phi'(z)}$?
If my things incorrect, what is the exact form of that?
Answer: Let $D \subset \Bbb C$ be an open set, and $\gamma: [a, b] \to D$ a (piecewise differentiable) path in $D$. For any continuous function $f: D \to \Bbb C$, the integral over $f$ along $\gamma$ is defined as
$$
 \int_\gamma f(z) \, dz = \int_a^b f(\gamma(t)) \gamma'(t) \, dt \, .
$$
Now let $\phi: D \to D' \subset \Bbb C$ be complex differentiable. Then $\Gamma = \phi \circ \gamma$ is a path in $D'$, and
$$
\int_\Gamma f(z) \, dz = \int_a^b f(\Gamma(t)) \Gamma'(t) \, dt
= \int_a^b f(\phi(\gamma(t)) \phi'(\gamma(t))\gamma'(t) \, dt
= \int_\gamma f(\phi(z))\phi'(z) \, dz\, .
$$
So we have the "substitution rule"
$$
 \boxed{\int_{\Gamma} f(z) \, dz =\int_\gamma f(\phi(z))\phi'(z) \, dz \, .}
$$
Roughly speaking: One can substitute $w = \phi(z)$ in a complex line integral, as long as one takes into a account that the new integral is along a different path.
Note that $\phi$ is not required to be an "affine transformation" here, just complex differentiable.
If $\phi$ happens to be invertible in $D'$ then $\gamma = \phi^{-1} \circ \Gamma$, and therefore
$$
 \int_{\gamma} f(w) \, dw =\int_\Gamma f(\phi^{-1}(w))\frac{1}{\phi'(\phi^{-1}(w))} \, dw \, .
$$
Comment: Awesome proof! I'll try to prove again by the method you've suggested


Log-space probability of a log-space probability not occurring

Question: Normally the probability of some probability $p$ not occurring would be $1-p$. However, I'm working with very small probabilities and therefore must work with $p$ in $\log$ space (Ie. I'm working with values of $\log(p)$ rather than $p$, otherwise I would receive an underflow error).
How do I find the value of log(1-p) without converting p back to base 10? (Ie. without first calculating 10^log(p)).
Answer: If $p$ is very small then $\log (1 - p) \simeq -p$ will also be very small, so you'll get underflow. How are you going to avoid that underflow?
Comment: Ahh... I think you're right, the underflow is unavoidable in this case. Thanks for your response!


How to use RemoveFolderEx to recursively remove folder in LocalAppData on install AND uninstall

Question: Here's what I have (based on what I've gleaned from several other Stack Overflow posts and elsewhere:
<Property Id="CACHEFOLDER">
  <RegistrySearch Key="SOFTWARE\SIL\Transcelerator" Root="HKCU" Type="raw"
    Id="CacheFolderRegSearch" Name="CachePath" />
</Property>

<Directory Id="TARGETDIR" Name="SourceDir

  <?define AppCacheFolder = "SIL\Transcelerator" ?>
  <Component Id="CacheCleanup" Guid="{6A45D61D-EA73-4A8C-8941-B49A881ABB49}">
    <RegistryValue Root="HKCU" Key="Software\SIL\Transcelerator" Name="CachePath"
                   Type="string" Value="[LocalAppData]$(var.AppCacheFolder)"
                   KeyPath="yes" />
    <util:RemoveFolderEx On="both" Property="CACHEFOLDER"/>
  </Component>

</Directory>

<Feature Id="MainApplication" Title="App Name" Level="1" Absent="disallow" Display="expand" AllowAdvertise="no" InstallDefault="local">
  <ComponentRef Id="CacheCleanup" />
</Feature>

Note: Eventually, I'll want to make the MainApplication feature hidden, but for now it's comforting to see it.
Here are what I think are the relevant excerpts from the WIX log file:
AppSearch: Property: CACHEFOLDER, Signature: CacheFolderRegSearch
MSI (c) (38:F0) [18:25:39:116]: PROPERTY CHANGE: Adding CACHEFOLDER property. Its value is 'SIL\Transcelerator'.
Action ended 18:25:39: AppSearch. Return value 1.
...
MSI (c) (38:F0) [18:25:45:594]: Switching to server: PARATEXT7="C:\Program Files (x86)\Paratext 7\" PARATEXT7TEST="C:\Program Files (x86)\ParatextDir7Test\" PARATEXT8="C:\Program Files (x86)\Paratext 8\" PARATEXT8TEST="C:\Program Files (x86)\ParatextDir8Test\" PARATEXT75100ORGREATER="C:\Program Files (x86)\Paratext 7\Paratext.exe" CACHEFOLDER="SIL\Transcelerator" TARGETDIR="C:\" INSTALLDIR7="C:\Program Files (x86)\Paratext 7\plugins\Transcelerator\" INSTALLDIR7TEST="C:\Program Files (x86)\ParatextDir7Test\plugins\Transcelerator\" INSTALLDIR8="C:\Program Files (x86)\Paratext 8\plugins\Transcelerator\" INSTALLDIR8TEST="C:\Program Files (x86)\ParatextDir8Test\plugins\Transcelerator\" PLUGINDIR7="C:\Program Files (x86)\Paratext 7\plugins\" PLUGINDIR7TEST="C:\Program Files (x86)\ParatextDir7Test\plugins\" PLUGINDIR8="C:\Program Files (x86)\Paratext 8\plugins\" PLUGINDIR8TEST="C:\Program Files (x86)\ParatextDir8Test\plugins\" CURRENTDIRECTORY="C:\Projects\Transcelerator" CLIENTUILEVEL="0" CLIENTPROCESSID="17976" SOURCEDIR="C:\Projects\Transcelerator\output\installer\" ACTION="INSTALL" EXE
...
MSI (s) (E4:44) [18:25:46:006]: PROPERTY CHANGE: Adding CACHEFOLDER property. Its value is 'SIL\Transcelerator'.
...
Action 18:25:46: WixRemoveFoldersEx.
Action start 18:25:46: WixRemoveFoldersEx.
MSI (s) (E4:00) [18:25:46:041]: Invoking remote custom action. DLL: C:\Windows\Installer\MSI6019.tmp, Entrypoint: WixRemoveFoldersEx
MSI (s) (E4:78) [18:25:46:042]: Generating random cookie.
MSI (s) (E4:78) [18:25:46:044]: Created Custom Action Server with PID 18712 (0x4918).
MSI (s) (E4:54) [18:25:46:067]: Running as a service.
MSI (s) (E4:54) [18:25:46:069]: Hello, I'm your 32bit Impersonated custom action server.
WixRemoveFoldersEx:  Recursing path: SIL\Transcelerator\ for row: wrfA9D8B049E87ACFF02034C5FFCFB64E42.
WixRemoveFoldersEx:  Search path not found: SIL\Transcelerator*
Action ended 18:25:46: WixRemoveFoldersEx. Return value 1.
...
MSI (s) (E4:44) [18:25:46:267]: Executing op: ComponentRegister(ComponentId={6A45D61D-EA73-4A8C-8941-B49A881ABB49},KeyPath=01:\Software\SIL\Transcelerator\CachePath,State=3,,Disk=1,SharedDllRefCount=0,BinaryType=0)
1: {97A212AC-E01E-486A-A220-AF9BBBC79E87} 2: {6A45D61D-EA73-4A8C-8941-B49A881ABB49} 3: 01:\Software\SIL\Transcelerator\CachePath
...
MSI (s) (E4:44) [18:25:46:597]: Executing op: RegOpenKey(Root=-2147483647,Key=Software\SIL\Transcelerator,,BinaryType=0,,)
MSI (s) (E4:44) [18:25:46:597]: Executing op: RegAddValue(Name=CachePath,Value=SIL\Transcelerator,)
WriteRegistryValues: Key: \Software\SIL\Transcelerator, Name: CachePath, Value: SIL\Transcelerator
...
Property(S): CACHEFOLDER = SIL\Transcelerator
Nothing relevant seems to be getting added to the registry. (At one point, it seems it was adding something withe correct GUID to tell it to do an uninstall action, but now I can't figure out what I changed to make that go away.) And none of files or subfolders in C:\Users\bogle\AppData\Local\SIL\Transcelerator are getting removed either on install or uninstall. I also tried changing from On="both" to On="Uninstall" to see if I could get that to work, but no dice.
Comment: "SIL\Transcelerator" isn't a valid full path? The information on RemoveFolderEx's Property attribute says that it is "The id of a property that resolves to the full path of the source directory. " You want CACHEFOLDER to be "C:\Users\bogle\AppData\Local\SIL\Transcelerator"
Comment: Yes, but I can't figure out how to make that happen.
Comment: According to [this article](https://stackoverflow.com/questions/47195875/wix-remove-localappdata-appdata-local-my-app-folder-on-uninstall) and others, putting [LocalAppData] in the RegistryKey's Value attribute should cause it to prepend the rooted path to the current user's AppData\Local folder, but it's not working for me.
Comment: When I've used RemoveFolderEx I've just read a registry key that had the full path as its value like the article you linked. It looks like the property name should actually be "LocalAppDataFolder" https://msdn.microsoft.com/en-us/library/aa369768(v=vs.85).aspx
Comment: I tried LocalAppDataFolder as well, but it made no difference.
Answer: I ended up using a custom action because it turns out that what I really needed to do was clear the cached files for any/all users, not just the current user. This was especially true because the installer always runs under elevated privileges, so the current user quite typically would not be the one I actually care about. I will point out that the original problem remains unsolved, so if anyone can figure out the problem and post an alternate answer that might help someone else, that could be useful.
Answer: The name of the directory property is LocalAppDataFolder, not LocalAppData. That's not defined so it's an empty string and the path RemoveFolderEx is given isn't valid (hence the Search path not found: SIL\Transcelerator error).


How to count overall post activity(likes, dislikes, comment) from postModel and reference sum of those in userModel using mongodb and mongoose

Question: I use MERN Stack to create social network, I need to implement count for overall user's posts activity(likes, comment, dislikes) and be able to access that sum in Profile, when fetching that through REST API.
The goal is to implement scoring system, where the next calculation will define the score (Likes+comment-dislikes = score).
Code for Post Model:
const Schema = mongoose.Schema;

const PostSchema = new Schema({

    user: { //we want post to be connected to the user
        type: Schema.Types.ObjectId,
        ref: 'users',
    },
    text: {
        type: String,
        required: true
    },
    name: { //name of user to keep posts even if the user delets the account
        type: String
    },
    avatar: {
        type: String
    },
    likes: [{
        user: {
            type: Schema.Types.ObjectId,
            ref: 'users'
        }
    }],
    dislikes: [{
        user: {
            type: Schema.Types.ObjectId,
            ref: 'users'
        }
    }],

    comments: [{
        user: {
            type: Schema.Types.ObjectId,
            ref: 'users'
        },
        text: {
            type: String,
            required: true
        },
        name: { //name of user to keep comments even if the user delets the account
            type: String
        },
        avatar: {
            type: String
        },
        date: {
            type: Date,
            default: Date.now
        }
    }],

    date: {
        type: Date,
        default: Date.now
    }
})

module.exports = Post = mongoose.model('post', PostSchema);

Code for profile
const mongoose = require('mongoose');

const ProfileSchema = new mongoose.Schema({
    user: {
        type: mongoose.Schema.Types.ObjectId, //every profile is associated with user, so connect with user.id
        ref: 'user' //reference to user model
    },
    website: {
        type: String
    },
    location: {
        type: String
    },
    bio: {
        type: String
    },
    activity_count: {
        type: Number,
        ref: 'post'
    },

    social: {
        youtube: {
            type: String
        },
        twitter: {
            type: String
        },
        facebook: {
            type: String
        },
        linkedin: {
            type: String
        },
        instagram: {
            type: String
        }
    },
    date: {
        type: Date,
        default: Date.now
    }
});

module.exports = Profile = mongoose.model('profile', ProfileSchema)

Comment: Please share input and output you want at https://jsoneditoronline.org/
Answer: If this was a sql database it would make sense to implement some queries that calculates each user's score in database side.
But with mongodb you have to take a different approach. In general, doing any sort of calculations in the database side is very inefficient. Mongodb server converts all the relevant the BSON documents into javascript object and then does calculates with javascript which is relatively slow.
Instead of calculating the score for every request, you should store the score and probably also the counts of likes, comment and dislikes in the post document.
Also remember that in MongoDB(NoSQL), denormalizing is not a bad thing.
If you need to do some calculation for every database request, its a sing to store the calculated data in a new field.
For example when someone adds a comment you probably do something like this:
Post.findOneAndUpdate({ _id:postId }, { $push: { comments: newComment })

Now just change this to
Post.findOneAndUpdate({ _id:postId }, { $push: { comments: newComment }, { $inc: { commentCount: 1, score: 1 } } )

When some deletes a post
Post.findOneAndUpdate({ _id:postId }, { $pull: { 'comments.id': commentId }, { $inc: { commentCount: -1, score: -1 } } )

Now all these requests are very fast because these updates are handled in BSON. You can apply this same logic to your profile document.


Using cookies in 2 distincts websites

Question: I have 2 websites and I would like to use the same cookie for both websites. The problem is they are not in the same domain.
How can I do ?
Comment: Forget about asking specific questions about cookies; What functionality are you trying to achieve? There may be a better way to acheive your goal.
Answer: You can set two cookies for both domains,  example PHP code:
<code>setcookie("TestCookie", "value", $path, "domain1.com");
setcookie("TestCookie", "value", $path, "domain2.com");
</code>
Link:
http://php.net/manual/en/function.setcookie.php
Answer: I guess you can't. Cookies are only sent to the domain they belong to. You most create diferent cookies to  both diferent domains.
Answer: You can't do that with cookies.
You have to save the data of your cookies on your server. You can use a database to do this.

Using cookies in 2 distincts websites


Menu issue with switch. When i input my choice, it works for all of mu switches

Question: Its hard to explain, but basically if i press 3 it works for all of my case parts (switches). How do i make Value be new every time. If i for example press 3, then it prints this:
Pasirinkite objekta ir jo metoda
-1 Buyer
-2 Item
-3 Shop
Shop. Pasirinkite metoda
1 Name
2 Email
3 Company Code
4 Address
5 Delivery Price
Comapny code:
Invalis selection
public class Main{
public static void main(String[] args) {
    int Value = 0;

    System.out.println("***************************************Menu***************************************");
    System.out.println("1 - jei norite atspauzdinti programje sukurtu objektu sarasus");
    System.out.println("2 - jei norite sukurti naujus objektus, ju duomenis ivedant is klavieturos");
    System.out.println("3 - jei norite iskviesti objektu metodus");

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    try {
       Value = Integer.parseInt(br.readLine());
    } catch (IOException ioe) {
       ioe.printStackTrace();
    }

    switch (Value) {
    case 1: {
        System.out.println("1 Selected");
        break;
    }
    case 2:
        System.out.println("2 Selected");
        break;

    case 3:
        System.out.println("Pasirinkite objekta ir jo metoda");
        System.out.println("-1 Buyer");
        System.out.println("-2 Item");
        System.out.println("-3 Shop");
        if (Value == 3) {
        switch(Value) {

        case 1:
            System.out.println("Buyer. Pasirinkite metoda");
            System.out.println("1 Email");
            System.out.println("2 Phone Number");
            switch(Value) {
            case 1:
                System.out.println("Email: ");// + getEmail());
                break;
            case 2:
                System.out.println("Phone number: ");// + getPhoneNumber());
                break;
            }

            break;
        case 2:
            System.out.println("Item. Pasirinkite metoda");
            System.out.println("1 Name");
            System.out.println("2 Price");
            System.out.println("3 Warranty");
            System.out.println("4 Extra Warrantys");
            //value4 = input.next();
            switch(Value) {
            case 1:
                System.out.println("Name: ");// + getName());
                break;
            case 2:
                System.out.println("Price: ");// + getPrice());
                break;
            case 3:
                System.out.println("Warranty: ");// + getWarranty());
                break;
            case 4:
                System.out.println("Extra warranty: ");// + getExtraWarranty());
                break;
            }
            break;
        case 3:
            System.out.println("Shop. Pasirinkite metoda");
            System.out.println("1 Name");
            System.out.println("2 Email");
            System.out.println("3 Company Code");
            System.out.println("4 Address");
            System.out.println("5 Delivery Price");
            switch(Value) {
            case 1:
                System.out.println("Name: ");// + getName());
                break;
            case 2:
                System.out.println("Email: ");// + getEmail());
                break;
            case 3:
                System.out.println("Comapny code: ");// + s.getCompanyCode());
                break;
            case 4:
                System.out.println("Address: ");// + getAddress());
                break;
            case 5:
                System.out.println("Delivery price: ");// + getDeliveryPrice());
                break;
            }

        break;
        }
        }
    default: System.out.println("Invalis selection");
    break;

}

}
}
Comment: What do you want to do? Your logic is a bit messy. Look at your switch-in-switch-in-switch: `switch (Value) { ... case 3: ... if (Value == 3) { ... switch  (Value) { ... case 3: ...`, what is the expected result of all this?
Answer: I'm not sure I understood the problem, but I think you want to read a new value between each switch. So you should add lines here to read from the keyboard again
case 3:
    System.out.println("Pasirinkite objekta ir jo metoda");
    System.out.println("-1 Buyer");
    System.out.println("-2 Item");
    System.out.println("-3 Shop");

    try {
        Value = Integer.parseInt(br.readLine());
    } catch (IOException ioe) {
       ioe.printStackTrace();
    }

    if (Value == 3) {
        ....

If I were you, I would rearrange the code to avoid using nested switches and using more methods. It is really hard to read