How to alter a custom form

Question: I am using Drupal 7 to create an registration form, there are: username, email dan password fields, but I want to make an username checking while user leave username field (ajax).
I found an module as Username Check
This module is great and working in "myweb/user/register" form, but I need to move this function to my custom form in username field too
The code:
function username_check_menu() {
  $items = array();

  $items['username_check/isunique'] = array(
    'type' => MENU_CALLBACK,
    'page callback' => 'username_check_callback',
    'access arguments' => array('access content'),
    'file' => 'username_check.unique.inc',
  );

  $items['admin/config/system/username_check'] = array(
    'title' => 'Username check',
    'type' => MENU_NORMAL_ITEM,
    'page callback' => 'drupal_get_form',
    'page arguments' => array('username_check_settings'),
    'access arguments' => array('administer site configuration'),
    'file' => 'username_check.admin.inc',
  );

  return $items;
}

function username_check_form_user_register_form_alter(&$form) {

  $mode     = variable_get('username_check_mode', 'auto');

  if($mode != 'off')
  {
    _username_check_load_resources($mode);
    $form['account']['name']['#field_suffix'] = ' ';
    $form['account']['name']['#suffix'] = '

';
  }

}

/**
 * Load username_check resources.
 */
function _username_check_load_resources($mode) {
  $module_path = drupal_get_path('module', 'username_check');
  drupal_add_css($module_path . '/username_check.css');
  drupal_add_js($module_path . '/username_check.js');

  drupal_add_js(array(
    'usernameCheck' => array(
      'ajaxUrl' => url('username_check/isunique', array('absolute' => TRUE)),
      'delay'   => variable_get('username_check_delay', 1),
    ),
  ), 'setting');
}

and my form as userregis_form
How to apply this to my custom form?
Answer: you need to add a validation to your form via
    $form['#validate'][] = 'yourFunction';

  function yourFunction($form, &$form_state) {
        //to show the form values
        dpm($form_state);
        //do validation
  }

Comment: im successfull to load the css file, but the ajax file not working. @user3278675 can you specify ur mean as #validate form?
Comment: im not talking about the module.

Im talking about making your own validation for the username.

Is there any configuration needed for it to work or did you just enabled it and it work on other form?

How to alter a custom form


Can we add the destination query parameter to a link from yml configuration?

Question: When creating a link from yaml
ie: mymodule.links.action.yml
my_module.my_entity.add:
  route_name: node.add
  title: 'Add My Entity'
  route_parameters:
        node_type: 'my_entity'
  appears_on:
    - my_module.my_entity.admin_content

Is there a way that this links would be generated with the ?destination=path/to/redirect ?
Comment: You can try creating a custom route for that link. And add the destination in the route definition.
Comment: @eyal Can you be more specific about `adding the destination in the route definition`? Should the custom route be done by code using route callback ? Thanks
Comment: Try and create a mymodule.routing.yml file. In that for you can define new routes and provide parameters for them. I'm not sure if it is possible to add a destination parameter but it is worth the try.
Answer: Yes, you can add the destination query directly in the yml file.
@see : \Drupal\Core\Menu\LocalActionDefault::getOptions
ie: mymodule.links.action.yml
my_module.my_entity.add:
  route_name: node.add
  title: 'Add My Entity'
  route_parameters:
        node_type: 'my_entity'
  options:
    query:
      destination: '/path/to/redirect'
  appears_on:
    - my_module.my_entity.admin_content

Answer: The query string is not part of the route. The controller fetches the query parameters from the webserver request and does the processing, in this case returns a redirect:
$request = \Drupal::request();
$destination = $request->query->get('destination');
return new RedirectResponse($destination);

When generating an url for the example mentioned in the question, the node_type is a parameter that goes into the route as configured in the routing yml file and the destination is a query parameter that is appended to the url and is not part of the route:
$url = \Drupal\Core\Url::fromRoute(
    'node.add',
     array('node_type' => $type->id()),
     array(
       'query' => array('destination' => $destination),
       'absolute' => TRUE,
     )
);

On both sides the routing system ignores whatever you put in the query of the url, you have to handle this in the code yourself.


Evaluating productivity metrics in an A/B test system

Question: I'm beginning work on an A/B testing system for UX changes to a tool my team builds. Our users are doing simple, repeatable tasks assigned by another team's system. My team handles the UI/UX part.
Users typically have a steady stream of work assigned to them, and they can see their current task, and complete it. Tasks typically take under a minute. Each task has an expected time to complete it and the users are rated based on their overall "actual / expected" for a day's work.
My question is this: Given that a random subset of users are consistently seeing a slightly different treatment (the deterministic 'random' selection is a solve problem), and I can get a steady stream of [User, expected time, actual time, treatment] for each complete task, how can I evaluate the overall productivity changes for users in a statistically valid way?
To give some insight into why this is tricky, here are some things we've been worried about:

Let's say users under Treatment A are 10% more efficient. As a result, they will produce more data points. With the wrong analysis, more data points might skew the results, and we want exact figures, with high confidence. We want to know how much the change helps the average user.
The data is very noisy, but seems to average out over an hour/day/shift for each user. One task may take a fraction of the expected time, or a magnitude more than expected. This is in part because our ability to estimate completion time is in need of improvement (but on average, it's pretty accurate). We worry that our high variability in estimated completion time will increase our uncertainty in results analysis.

Thanks very much.
Answer: Seems like you will be inadvertently measuring the randomness (variation in accuracy) of your "expected time" estimation system.  If your work load can stomach it, an ideal solution would be to assign the same actual work task to pairs of agents, one agent using treatment-A, the other using treatment-B.    This removes the "expected time" aspect of the system entirely; allowing direct comparison between the two treatment systems.  ALSO, it provides an opportunity to compare the results (not just the time-taken to complete the task).  Do the results obtained by the two agents match?  If not, then there is some sort of error rate difference that can be investigated too.  (One "treatment" may make it faster, but what if it also increases error rate?)


Rails 4 not rendering code

Question: I am trying to render a partial on a page in rails. For some reason the code is not being rendered into html. I have tried taking it out of the partial and just placing it in the profile page but still nothing. I am getting no errors and have restarted the server but still nothing. This is in development mode. Also all code except the message code works fine. Any help would be appreciated. Here is the code.
profile.html.erb
<% unless @pictures.nil? %>

      <% @pictures.each do |picture| %>
        <%= image_tag(picture.image.url(:thumbnail)) %>
      <% end %>
      <%= image_tag("left.png") %>
      <%= image_tag("right.jpeg") %>

<% end %>

<% render 'message' %>

_message.html.erb
<% form_for @message, :url => messages_create_path do |f| %>
  <% f.hidden_field :from, value: current_user.id %>
  <% f.hidden_field :to, value: @user.id %>
  <% f.text_area :message %>

  <% f.submit "Send Message" %>
<% end %>

Answer: To make your form_for code block to render you need to use <%= tag as follows:
<%= form_for @message, :url => messages_create_path do |f| %>
  <% f.hidden_field :from, value: current_user.id %>
  <% f.hidden_field :to, value: @user.id %>
  <% f.text_area :message %>

  <% f.submit "Send Message" %>
<% end %>

Comment: Thanks for the extra set of eyes
Answer: To elaborate on vinodadhikary's answer, ERB has output tags and evaluation tags. To evaluate something you would use <% expression %>, and to output you would use <%= output.me %>. The earlier is usually used for flow control in templates, and outputs nothing. The output happens within after a decision is made. The latter is used to output stuff.
Comment: Thanks for the extra set of eyes
Comment: Yes I did know all about this. Just a dumb mistake and question that I am going to delete.
Comment: You're welcome. This stuff still happens to me today!

Rails 4 not rendering code


C# RestSharp RestClient Confusion

Question: I'm setting up an API call that I know works with the given credentials. I'm new to C# and .NET in general and I've been told to use RestSharp for API calls. What gets passed as an argument to RestClient? I've tried my local server but not sure that's it.
Here is the controller code:
    const string endpoint = "https://api.test.hotelbeds.com/hotel-api/1.0/status";

    string signature;

    using (var sha = SHA256.Create())
    {
        long ts = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds / 1000;
        Console.WriteLine("Timestamp: " + ts);
        var computedHash = sha.ComputeHash(Encoding.UTF8.GetBytes(apiKey + sharedSecret + ts));
        signature = BitConverter.ToString(computedHash).Replace("-", "");
    }

    var client = new RestClient("?");
    var request = new RestRequest(endpoint, Method.GET);

    request.AddHeader("X-Signature", signature);
    request.AddHeader("Api-Key", apiKey);

    var  response = client.Execute(request);
    Debug.WriteLine("this is the response" + response);

    return View();
}

Answer: The endpoint should be passed into the constructor of RestClient. The URL segments should be passed into the RestRequst.
From the example on http://restsharp.org/
var client = new RestClient("http://example.com");
// client.Authenticator = new HttpBasicAuthenticator(username, password);

var request = new RestRequest("resource/{id}", Method.POST);
request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
request.AddUrlSegment("id", "123"); // replaces matching token in request.Resource

So in your example, you should declare endpoint as:
https://api.test.hotelbeds.com/

and pass hotel-api/1.0/status into the RestRequest constructor.
Comment: Ok, i saw that example, don't know why I over complicated it. Thanks.

C# RestSharp RestClient Confusion


Letting anonymous user to see fields?

Question: I just created a content type with a field:images.
Then I added some content and I create a View to show these content. Then the view shows the images (from the images field)
Everything works fine but when I logout the anonymous user can not see the images.
As you can see in this picture I have "checked" Access content for anonymous user. But it doesn't work...
.
What I need to do to make the images visible for anonymous users is to have 'checked' View field_images. You can see the picture.

my question: do I need to checked on every field I create to make them visible to anonymous users? Is there any way to set that any new create field should be visible to anonymous users.
Thanks
Answer: If there is no field permission module installed, all fields are always visible. So if you don't want to restrict any fields, then disable the content permissions module.
Once such a module is installed, it works as implemented by that module. And there is no way for such a module to guess the permissions you want (should it be visible to auth users only, or anon users too.. maybe only a specific role?), so it can only chose the safe way and does not grant anything automatically.
That is consistent with all other permissions, when you install a new module.
Comment: Thanks berdir. I had Content Access module enabled, as you said I disabled but now the images are not visible, maybe I need to delete and re-create the nodes again to rewrite their permissions? I tried flushing all caches but nope...
Comment: solved! when creating new content all fields are visible.
Comment: Strange, I don't know why this would happen.

Letting anonymous user to see fields?


Find maximum of $f(0)$

Question: Let $f$ be a continuously differentiable function on $(-1,4)$, $f(3)=5$ and $f'(x)\geq-1$ for all $x$. Find maximum of $f(0)$.
I have plotted the graph of $f$ and found the maximum is $8$. But I didn't find the solution exactly.
Answer: $f(0) = f(3) - \displaystyle \int_0^3 f'(x)\,dx$.
$f(3)-f(0) = \displaystyle \int_0^3 f'(x) \,dx$
$f(3)-f(0) \geq -3$
$5 - f(0) \geq -3$.
$8 \geq f(0)$.
Answer: Since $f$ is continuously differentiable the followng quantiy is well defined :
$$\int_0^3f'(x)dx$$
Firstly knowing that $f(3)=5$ we get :
$$\int_0^3f'(x)dx=f(3)-f(0)=5-f(0)$$
And since $f'(x)\geq-1$ :
$$\int_0^3f'(x)dx\geq-3$$
Finally :
$$5-f(0)\geq-3 \iff f(0)\leq8$$
Answer: By MVT
$$f (0)=f (3)-3f'(c)=5-3f'(c) $$
with $c\in (0,3) $.
but $f'(c)\geq -1$ thus
$$f (0)\leq 5+3$$

Find maximum of $f(0)$


How can I prove $\sqrt{(111...)+(55...)^2}=5...6$

Question: The formula in my question can be illustrated as follow:

$$\sqrt{11+5^2}=6$$
  $$\sqrt{111+55^2}=56$$ $$\sqrt{1111+555^2}=556$$ $$\sqrt{11111+5555^2}=5556$$ and so on

How can I prove the general formula

$$\sqrt{\underbrace{11\ldots 1}_{n+1\text{ times}} + (\underbrace{55\ldots 5}_{n\text{ times}})^{2}} = (\underbrace{55\ldots 5}_{n-1\text{ times}}6)^{2}$$
Answer: These equalities are just instances of
$$\sqrt{(2n+1)+n^2}=n+1.$$
Comment: And from here you can do a proof but induction
Comment: @UsernameUnknown: Induction?! How about just squaring both sides instead?
Comment: @TonyK Username Unknown is right. You need induction to prove any statement true for all natural numbers. Just that it being trivial doesn't mean it does not use induction.
Comment: Well you want to show this is true for any n
Comment: @UsernameUnknown: What, that $(n+1)^2 = n^2+2n+1$? Srsly?
Comment: You see proof by induction is what is need if you were to go with this approach
Comment: @Adhvaitha: So how would you prove $(x+1)^2=x^2+2x+1$ for all $x \in \mathbb R$?
Comment: @UsernameUnknown TonyK is right, this is a remarkable identity. Induction is overkill.
Comment: @TonyK Strictly speaking the identity $(x+1)^2 = x^2+2x+1$ must be first proved for $\mathbb{N}$, then for $\mathbb{Z}$, then for $\mathbb{Q}$ and finally use completeness to obtain it for all $\mathbb{R}$.
Comment: @TonyK How do you prove commutativity, distributivity, and associativity of the arithmetic operators over $\mathbb{R}$?
Comment: @Adhvaitha: No, simple algebra is enough, using the commutativity, distributivity, and associativity of the arithmetic operators. If you claim that these properties must themselves be proved by induction, then I expect your inductive proof of $(n+1)^2=n^2+2n+1$ to contain such proofs! (But that would be silly,right?) (Sorry -- edited and cross-posted.)
Comment: @TonyK Commutativity, distributivity, and associativity of the arithmetic operators over $\mathbb{R}$ needs to proved. How do you prove them? You prove them for $\mathbb{N}$, then for $\mathbb{Z}$, then for $\mathbb{Q}$ and finally for $\mathbb{R}$. This is probably a bit too pedantic, but is the right way to go.
Comment: @Adhvaitha: If you sit down and write out an everyday inductive proof that $(n+1)^2=n^2+2n+1$, you will find yourself using such properties without proof. So why can't I use these properties in a purely algebraic proof?
Comment: @TonyK You can use them. All I am saying is that behind each of these there is induction.
Comment: @Adhvaitha: Well,if that's really all you're saying, I guess we agree...
Answer: Hint: rewrite your statements as:
$$6^{2}-5^{2} = 11$$
$$56^{2}-55^{2}=111$$
$$\cdots$$
And prove it using difference of squares (factor the expression).
Comment: Square both sides and subtract? If the downvoter can't see that, I guess we're just going to have some downvotes.
Comment: If the downvoter would kindly comment, I would be happy to improve my answer.
Comment: Maybe a missing explanation of the relation relation between the LHS and RHS ? (I am not the downvoter)
Answer: We have
\begin{align}
\underbrace{\dfrac{10^{n+1}-1}9}_{1111\ldots11} + \underbrace{\left(5\cdot \dfrac{10^n-1}9\right)^2}_{555\ldots55^2} & = \dfrac{9\cdot 10^{n+1} - 9 + 5^2 \cdot 10^{2n} - 5^2\cdot 2 \cdot 10^n + 5^2}{9^2}\\
& = \dfrac{5^2 \cdot 10^{2n} + 4 \cdot 10^{n+1} + 16}{9^2}\\
& = \underbrace{\left(5 \cdot \dfrac{10^n-1}9 + 1\right)^2}_{555\ldots56^2}
\end{align}
Comment: Correct but the "hard" way.
Comment: @YvesDaoust "hard" is a relative term and highly person dependent.


Definition of a slope of a straight line

Question: I am learning about the straight line and its slope was defined as "rise over run".
Why not "run over rise"? Was "rise over run" chosen arbitrarily or it was derived based on some physical relationship?
Thanks in advance
Answer: With the conventional definition, "large slope" corresponds to a very steep uphill incline, and "zero slope" corresponds to a horizontal line.  Both of those line up naturally with how we talk about a physical incline.
Answer: It depends on what you mean by "rise" and "run". If you take "run" to mean "horizontal distance", then it's arbitrary, because (this part of) mathematics at this level doesn't care about the difference between horizontal and vertical.
If by "run" you mean "independent variable" (say $x$) and by "rise" mean "dependent variable" ($y$, $f(x)$, and such), then there is a reason to choose this definition of slope over another:

With this definition, the slope of $f$ where $f(x) = 0$ is $0$, which is a real number.
With the "run over rise" definition, the slope of $f$ is undefined, or at least not a real number if you choose to use infinities.

Since we like to avoid dealing with $\infty$, which has fewer useful properties than regular real numbers, the usual definition is more useful.
(Also, in "run over rise" there is no function which has a slope of $0$. So the usual definition has fewer oddities all around.)
Answer: Slope is a word that is used to describe many things, but I think one thing is most pertinent here..."effort" as it relates to moving up an incline. It's intuitive. That's probably why they chose "rise over run". Of course, they could have chosen "drop over run", but that just doesn't work as well.
Answer: We need to go back to the linear function $y=mx+b$, $m$ is the slope and the y-intercept is $(0,b)$. What does that all mean? Well, let's replace $x$ by $x+1$ and plug that in the equation: $y=m(x+1)+b=mx+b+m.$ (Watch that order: I wrote $b+m$ instead of $m+b$) With respect to the given function, if you go one unit to the right from $(0,b)$, you will now have to go $m$units up to get back on the line. (Draw it out on a paper!)
So here we have established the most important property of the slope: It is the vertical displacement needed to get back on the line, if you move one unit away horizontally from a point on the line. The imaginary triangle, which you often see on laminated cheat sheets for Algebra 1 is depicted with unit $1$ on the horizontal side, $m$ on the vertical side and the line passing though the hypothenuse. Now how does that relate to $\frac{y2-y1}{x2-x1}?$ This is essentially "scaling down" a right triangle between two given points in the xy plane to the triangle that has sides $1$ and $m$, think of similar right triangles. This is where the "rise over run" comes from. Not a definition, but a well crafted consequence of what the slope truly means.
Answer: There are are just two choices: rise over run or run over rise. Choosing is a matter of convention and then one sticks to convention.
Anyway let me attempt to give some reasoning:
Imagine a civil engineer's problem to construct a road bridge to cross a railway line. She/he takes into consideration the height of trains and arrives at some number like  9 metres above the ground level would be the appropriate
maximum height for the bridge.
Having arrived at that number how much height to clear the engineer has to decide what run is needed to reach that height that will be comfortable to drivers while climbing.  Approximating the slope as rational number  $m/n$ would mean $m$ metres of rise needs $n$ metres of run. So the bridge
will start $n$ metres from the first point where height $m$ is required.
Answer: Rise is the difference in y and run is the difference in x. If you are given 2 point point1= $(x_1,y_1)$ and point2= $(x_2,y_2)$ the difference can be written as $(x_1-x_2\,,\,y_1-y_2)$ if the two points are on the same line than this difference contains the ratio of rise to run for the line. (run,rise) and the slope of the line can therefor be written as $y_1-y_2 \over x_1-x_2$ or as it is often said $rise \over run$.
Because we do math on a chalk board where we typically have x on the horizontal and y on the vertical doing slope this way is sensible as it makes the slope of a horizontal line 0 and a vertical line $\infty$, which is intuitive.


Find all possible values of c

Question: A triple of integers $(a,b,c)$ satisfies $a+bc=2017$ and $ b+ca=8$. Find all possible values of $c$

I have applied subtraction and addition to these 2 equations which resulted $2c= \frac {2025}{a+b} - \frac{2009}{a-b} $. Since  $a+b$ has 15 distinct values and $a-b$ has 6 distinct values , if I do the combination, the value of $2c$ will be 80 values which is so much to write. So, is there any method?
Comment: what about $bc+c^2a=8c\implies a-c^2a=2017-8c\implies a=\frac{2017-8c}{1-c^2}$?
Comment: And only satisfied when c=0 ?
Answer: Add the 2 equations to get $(a+b)(c+1)=2025$, from which you can then get the factors and hence the possible values for $c+1$.
Similarly, subtract the 2 equation and you'll get $(c-1)(b-a)=2009$, and do the same here to get another set of possible values of $c-1$. Here, the values of $c$ we get are $-2008,-286,-48,-40,-6,0,2,8,42,50,288,2010$.
Now any value of $c$ that is admissible, must satisfy both the above equations.Thus,of these values of $c$ we just found, only $c=-6,0,2,8$ satisfy the first equation. Hence these are the only values of $c$ satisfying both the equation.
Comment: But $c=0$ could be the answer too
Comment: Yeb , and it has 15 answers. When I do the subtraction , it shows other 6 answers . So , is that it?
Comment: @NovemberftBlue yeah, that's all you have to do. Since they asked only for possible values of $c$ this problem becomes much easier. You need to look at subtraction too and take the intersection of values
Comment: @NovemberftBlue I completed the solution, and explained it a bit more
Comment: I got it , thank you:D
Comment: @NovemberftBlue ah yes, it's because i missed the case $c-1=-1$ (I forgot all the negative factor cases too, i'll edit it soon)
Comment: Thank you:) ! And don't forget the answer c=0 and " only 4 values of c "
Comment: @NovemberftBlue  yeah I fixed it. Though there were silly errors in my answer, I hope you understood the intuition behind the method?
Comment: Yeah I do , because I had followed your method before ,I thought it was too much , so I tried to find other ways. But anyway , Thank you. I appreciate it .

Find all possible values of c


grails-2.3.7 plugins/repository not found

Question: Suddenly my Grails application having error by causing of some plugins are not found. I think the repository has been removed or move somewhere.
Code on my BuildConfig.groovy:
log "warn"
checksums true
legacyResolve false
.....
compile ":db-reverse-engineer:0.5"
compile ":cache:1.0.1"
compile ":jaxrs:0.10"
compile ":jasper:1.8.0"
.....

Having Error on my Grails Apps from today:
 Error |
Resolve error obtaining dependencies: Failed to resolve dependencies (Set log level to 'warn' in BuildConfig.groovy for more information):

- org.grails.plugins:db-reverse-engineer:0.5
- org.grails.plugins:jaxrs:0.10
- org.grails.plugins:jasper:1.8.0

org.codehaus.groovy.grails.resolve.ResolveException: Failed to resolve dependencies (Set log level to 'warn' in BuildConfig.groovy for more information):

- org.grails.plugins:db-reverse-engineer:0.5
- org.grails.plugins:jaxrs:0.10
- org.grails.plugins:jasper:1.8.0

Note: grails repository has been removed from maven http://maven.restlet.org/org/
Can anyone suggest me to resolve those errors? Thanks in advance!!
Answer: There is a temporary problem with the central repository in some versions of Grails. You can work around this in one of two ways:
1) Use Aether as your dependency resolver, in BuildConfig (recommended):
grails.project.dependency.resolver = "maven"

2) If you must use Ivy (not recommended) then add the following repo to your repositories in BuildConfig:
mavenRepo "http://repo.grails.org/grails/plugins/"

Comment: I faced the issue with grails 2.3.7 as of today. Solution 1) worked for me.(did not try 2 yet though as 1 worked).
Comment: This URL worked better for me on Grails 2.1.1:  mavenRepo "http://repo.grails.org/grails/repo/"


How do I allow regular non-admin users to view other users' emails?

Question: Email is now an included field in core, but the stock email for users seems to be set to private; only users with administrator privileges or the user themselves can see.
I'd like to allow other users to see this basic field, without having to create yet another email field where someone has to copy the information over from the other other simply for the ability for it to be visible.
This should be a fairly easy/common practice, but I can't find anything yet.
How do I allow regular non-admin users to view other users' emails?
Comment: I do not want to make users' email fields available to the general public. But, in my 12 years of working with several federal departments, a host of NGOs, and numerous school systems - I can assure you it is very common practice to make your colleagues' general contact information, including their primary email, available to other authenticated users.

If your case is that the standard method for providing this email is as a separate entity than the user's registered account email, I can accept that - though it seems a bit unnecessarily redundant for a closed system.
Comment: In 15 years of developing for the web, I've literally never once been on a website where people's email addresses are made public. I wouldn't consider this to be common practice at all, might be why you're struggling to find an existing solution. Altering the access of that element in whatever context(s) you need is probably quite straight forward with code, but where should users be "seeing" this information? On the profile page with other fields for example?
Comment: The fact the email is not visible to other users is simply to avoid spamming. Also, it is a bad idea to show the email used to create an account. I agree with @Clive tha showing the email address is not such a common practice.
Answer: One route you can take is to allow users the View user information permission and display this information on the user profile page.
To do so, override user.html.twig in your theme (copy it from core/modules/user/templates/user.html.twig to your theme's template directory) then inject the email into the template via hook_preprocess_user() in your mytheme.theme file:
/**
 * Implements hook_preprocess_user()
 */
function mytheme_preprocess_user(&$variables) {
  $variables['mail'] = $variables['user']->getEmail();
}

In this example, you'll be able to user {{ mail }} to insert the email variable into your user profile template.
Comment: The equivalent workaround for views would be something like [hook_preprocess_views_view_field](https://api.drupal.org/api/drupal/core!modules!views!views.theme.inc/function/template_preprocess_views_view_field/8.2.x) to inject the user email into your views field.
Comment: $variables['user']->getEmail(); this returns only currently logined users email.
Comment: Thanks, that works great! Is there a way to enable the email field to show using views, though? The user directory is the primary way users look up contact information.
Answer: I had a similar use case. Here's another solution:
I added a new email field to users' profiles, and in a custom module (I did this is Drupal v8.1), use hook_user_presaveSee Drupal Api:
function MYMODULE_user_presave(User $user){
    $user->set('field_profile_email', $user->getEmail());
}
Then you can use this new field in Views, for example, in a department contact list, as was mentioned in a comment to the question. You could use Field Permissions to further enhance this as well.
This does have the downside of creating a second field, but the function avoids having to manually copy it, and it's now available anywhere.
Comment: this will copy the email once it's saved or updated but will not copy it if it already exists in the email field, right ?
Comment: Correct. This wouldn't affect any users already in the database. To do that, you'd need resave them.
Answer: There is a D8 Vore feature request to add a permission to see other users' mail address: Add new permission to view user email field [#2799049] \| Drupal.org


How to know if the p value will increase or decrease

Question: you conduct a hypothesis test. After 100 sample observations you observe values for sample mean and sample standard deviation that do not lead to the rejection of null hypothesis since p value is 0.12. After observing 200 sample observations you still observe the same sample mean and standard deviation. What will happen to the p value?
a. increase
b. decrease
c. stay the same
d. may increase or decrease
I got this question in an interview and I am so confused. Can someone please help me answer this. I think the answer should be d, but I am unsure.
Comment: The intuition here is that having a larger sample size should make you more confident that your sample mean reflects reality, which would correspond to a smaller p-value.
Answer: I believe that more precision could be added to exactly solve the problem and know what test are we talking about. But because you are talking about 1 sample mean and 1 standard deviation, I will assume a classic Z-test Statistics.
You are trying to see if the average of your sample $\bar{x}$ is significantly different from $\mu$. The "precision of your average" is given by the standard deviation expressed as: $\sigma/\sqrt{n}$. All of this can be found here https://en.wikipedia.org/wiki/Z-test
One can see that the more sample you add, the more your estimated variance will shrink. This in turns means a higher value for Z and thus a lower p-value, according to the following formula:
$$Z = \frac{(\bar{x}-\mu)}{(\sigma/\sqrt{n})}$$
A more intuitive way of seeing it, is that the more you draw sample, the more confident you are about the average because the smaller is standard deviation around that average. Now there will be a point, where that average is "precise enough" to be significantly different than any number $\mu$ that you were trying to compare it to.
In the case you were given, the p-value would then decrease.
[edit] Thanks for the precision from Sal Mangiafico : in the case where $\bar{x} =\mu$ then the p-value will remain unchanged and equal to 1
Comment: I do think this is the point of the question.  One outside case is that if the sample mean is exactly equal to mu (for both samples described), then the p-value would be exactly 1 for both samples.
Comment: +1 answer. Essentially, as n increases the difference $\bar x - \mu_0$ increases and the variance decreases, making $Z$ larger (if $\mu_0 \ne \mu$). However, the part with the average being significantly different than any $\mu_0$ only holds if $\mu_0$ is different than the true value $\mu$ (i.e.  $H0: \mu \ne \mu_0$).
Answer: I thought I would add some code so OP can easily see this effect in action.  This answer supports that by @Romain, except I used a one-sample t-test instead of a one-sample Z-test.  That won't make much of a difference.
A is a sample of 100 observations with a mean of approximately 10 and a standard deviation of approximately 3. (These could be changed in the rnorm function.)
B will be a similar sample of 200 observations.  A and B have exactly the same mean.  Their sample standard deviation will be just slightly different, because of the way sample standard deviation is calculated.
This code can be run in R or at rdrr.io/snippets. The code is a little complex, but the output is easy to read.  You can run it many times to see the behavior of the p-value starting with different samples.
Funny = function(){
  A   = rnorm(100, 10, 3)
  lA  = length(A)
  mA  = mean(A)
  sdA = sd(A)
  pA  = t.test(A, mu=10)$p.value

  B   = c(A,A)
  lB  = length(B)
  mB  = mean(B)
  sdB = sd(B)
  pB  = t.test(B, mu=10)$p.value

  Out = data.frame(Statistic=rep("A", 8), Value = rep(0.00, 8))
  Out$Statistic = c("n for A", "Mean of A",
                    "Standard deviation of A", "t-test p-value for A",
                    "n for B", "Mean of B",
                    "Standard deviation of B", "t-test p-value for B")
  Out$Value = c(signif(lA,3), signif(mA,3), signif(sdA,3), signif(pA,3),
                signif(lB,3), signif(mB,3), signif(sdB,3), signif(pB,3))

  return(Out)
}

Funny()

   ### Example output
   ###
   ###                 Statistic  Value
   ### 1                 n for A 100.000
   ### 2               Mean of A 10.200
   ### 3 Standard deviation of A  3.140
   ### 4    t-test p-value for A  0.518
   ### 5                 n for B 200.000
   ### 6               Mean of B 10.200
   ### 7 Standard deviation of B  3.140
   ### 8    t-test p-value for B  0.358


How to redirect traffic on vpc instance

Question: I'm working with Amazon web services and I have a VPC with two instances one of the instances is running my app and the other one has a VPN connection to a payments system. The VPN tunnel is working and I can ping the payments system, I can also ping one instance from the other.
I would like to make REST requests from the instance where my app is running, but I have to do it through the tunnel. So what I would need is a way to redirect all the traffic that goes into the instance with the VPN to the payments system, or at least that is my idea, I don't know if there is a better way.
I'm new to AWS so I don't know if there is a native way, or if I would have to build a server to redirect all the traffic(would like to avoid this).
Answer: The normal way would be to set up a site-to-site VPN to the remote network.  You would set up an instance running a site-to-site VPN like one of these:
https://aws.amazon.com/marketplace/search/results/ref=brs_navgno_search_box?page=1&searchTerms=vpn
I think the Sophos is great and it supports a bunch of VPN protocols.
If your instance connected to the remote network is only able to be a VPN client, you can set up port forwarding.  You would forward all connections of a port range incoming to the VPN connected instance to your remote server.  If your instance is only a VPN client and not a router, you can't directly route traffic from another instance.  The connections must masquerade as coming from the VPN client machine.
Comment: Thanks, I think I already have the site-to-site connection, I used OpenSwan, as described here, http://aws.amazon.com/articles/8800869755706543, I think the port forwarding option is what I need, would you be so kind to give me an example of how to do that. I don't think my instance is just a VPN client since it is a full ubuntu instance.
Thanks!!
Comment: If you have the site-to-site connection already what you need to do is configure your route table to route to the remote subnet.  Configure the route table for the subnet the app instance is located in so that

Destination: remote network subnet
Target: interface of OpenSwan instance
Comment: Finally the table routing worked, as explained, another option that I read in case someone else has the problem is using nginx and leaving the instance as a proxy. Thanks  for the help!

How to redirect traffic on vpc instance


Handling gaps in statistics

Question: For a web application we are building I am supposed to overhaul our statistic collection service.
Basically we are collecting simple statistics such as positive comments, negative comments, views, likes, etc.
We are not using any analytics API and we are supposed to store metrics in a relational database.
What we came up with is the following database design:
statistics: from:DateTime, to:DateTime, ref_id, metric_id, value
metrics: id, name

The Data is collected by a job that runs every few minutes and collects data from various sources. For every metric a seperate record is created. When the metrics value does not change instead of creating a new record the to column for the metric_id will be extended to the current DateTime.
So far so good. In a perfect world that idea should work good enough but unfortunately that probably won't be the case. There are basically three sources of failure:

The job does not run for some reason
A bug in the application causes metric/stat records to not be created
3rd party APIs which collect data may fail

In this case gaps will occur that aren't supposed to be there. My question is:
Are there any best practices to "patch" those gaps? My thoughts on that:

Silently extend the to Timestamp of the record before the gap occured to the start time of the latest "after-the-gap" record
Interpolate statistics linaeally: Subtract the metrics of the record after the gap and the record before the gap and distribute the results across the timespan of the gap

I don't like both ideas. Silently extending seems to be just a dirty cover-up for failure but at least end users won't be affected. The second options looks a bit better but results will still be inaccurate because statistics are most often not a linear matter.
I would appreciate any thoughts or ideas on that matter.
Comment: You might get some ideas from financial applications. Missing data for certain time-periods is a very common scenario when showing graphs and calculating statistics for financial metrics. (Some days are bank holidays in certain markets or there is no trading in a stock etc)
Answer: Provided that the probability of an observation being missing does not depend on the value of the observation (technically, data are "Missing at Random"), the method of multiple imputation is a reasonable approach.
Instead of doing a simple single linear interpolation, several sets of "complete" data are generated stochastically, in principle using information from all of the associated data. Analyses are then run separately on each of the imputed data sets, and combined appropriately. This way you don't throw out data and you can estimate the error introduced by the imputation process.
There is a multiple-imputation tag on this site that you can follow, and a useful website with further information. Tools (like mice) are available in packages written for R.

Handling gaps in statistics


Salesorderdetail detail not bring amount from product, CRM 2015

Question: I have created a plugin in which I am creating Sales Order and then creating salesorderdetail (sales order products) dynamically. Everything is working fine, products are shown correctly in the sub grid on order form but there is no price on the products at all.
I am using the following code to create sales order product.  When I create a quote then quote the product using same code (changing entity and references to quote) then later converting that quote to an order everything is fine.  However when I create an order and order product directly it is not working.
Please suggest a solution.
<code>var orderProduct = new Entity
{
    LogicalName = "salesorderdetail"
};

orderProduct.Attributes.Add("salesorderid", new EntityReference("salesorder", OrderId));
orderProduct.Attributes.Add("productid", new EntityReference(product.LogicalName, product.Id));
orderProduct.Attributes.Add("quantity", Convert.ToDecimal(1));
orderProduct.Attributes.Add("uomid", new EntityReference("uom", uom.Id));

_service.Create(orderProduct);
</code>
Comment: Could you please expound upon, " not working". Error etc ...
Comment: There is no error at all. Order Products are being created fine in the CRM and i can see those product on the Order form in sub grid, but total amount on the order is 0.
Answer: I found the solution to this.
When creating Order Products (salesorderdetail) using Plugin or webserivce and prices on the products should be coming from CRM automatically then
ispriceoverridden and isproductoverriden should be set to false explicitly in the code.
Working for me now :)


Como Listar Usuários com Asp.Net MVC 5

Question: Estou utilizando Visual Studio 2013, estou criando um novo projeto Asp.NET Web Application usando MVC e autenticação por "Conta de Usuário Individual".
Gostaria de saber como listar todos os usuários registrados.
Models:
IdentityModel
using Microsoft.AspNet.Identity.EntityFramework;

namespace WebApplication9.Models
{
    // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
    public class ApplicationUser : IdentityUser
    {
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection")
        {
        }
    }
}

AccountViewModels
using System.ComponentModel.DataAnnotations;

namespace WebApplication9.Models
{
    public class ExternalLoginConfirmationViewModel
    {
        [Required]
        [Display(Name = "User name")]
        public string UserName { get; set; }
    }

    public class ManageUserViewModel
    {
        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Current password")]
        public string OldPassword { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "New password")]
        public string NewPassword { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm new password")]
        [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
    }

    public class LoginViewModel
    {
        [Required]
        [Display(Name = "User name")]
        public string UserName { get; set; }

        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [Display(Name = "Remember me?")]
        public bool RememberMe { get; set; }
    }

    public class RegisterViewModel
    {
        [Required]
        [Display(Name = "User name")]
        public string UserName { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
    }
}

Comment: Você consegue exibir uma lista qualquer com EntityFramework?
Comment: Sim, eu consigo.
Answer: Se o contexto está mapeado corretamente, o seguinte Controller pode resolver:
public class UsuariosController : Controller
{
    public UserManager<ApplicationUser> UserManager { get; private set; }
    public RoleManager<IdentityRole> RoleManager { get; private set; }
    public MyDbContext context { get; private set; }

    public UsuariosController()
    {
        context = new MyDbContext();
        UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
        RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
    }

    public UsuariosController(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
    {
        UserManager = userManager;
        RoleManager = roleManager;
    }

    //
    // GET: /Users/
    public async Task<ActionResult> Index()
    {
        return View(await UserManager.Users.ToListAsync());
    }
}

O contexto deve ter a seguinte configuração:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<IdentityUser>()
        .ToTable("Users");
    modelBuilder.Entity<ApplicationUser>()
        .ToTable("Users");
}

Verifique se sua solução já utiliza estes pacotes (packages.config). Se sim, experimente fechar a solution e abrir novamente.
  <package id="Microsoft.AspNet.Identity.Core" version="2.0.0-alpha1" targetFramework="net45" />
  <package id="Microsoft.AspNet.Identity.EntityFramework" version="2.0.0-alpha1" targetFramework="net45" />
  <package id="Microsoft.AspNet.Identity.Owin" version="2.0.0-alpha1" targetFramework="net45" />
  <package id="Microsoft.AspNet.Mvc" version="5.0.0" targetFramework="net45" />
  <package id="Microsoft.AspNet.Razor" version="3.0.0" targetFramework="net45" />
  <package id="Microsoft.AspNet.Web.Optimization" version="1.1.0" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebPages" version="3.0.0" targetFramework="net45" />
  <package id="Microsoft.Owin" version="2.0.2" targetFramework="net45" />
  <package id="Microsoft.Owin.Host.SystemWeb" version="2.0.2" targetFramework="net45" />
  <package id="Microsoft.Owin.Security" version="2.0.2" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.Cookies" version="2.0.2" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.Facebook" version="2.0.2" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.Google" version="2.0.2" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.MicrosoftAccount" version="2.0.2" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.OAuth" version="2.0.2" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.Twitter" version="2.0.2" targetFramework="net45" />
  <package id="Microsoft.Web.Infrastructure" version="188.8.131.52" targetFramework="net45" />
  <package id="Owin" version="1.0" targetFramework="net45" />

Exemplo completo:

https://github.com/rustd/AspnetIdentitySample
Comment: Seu `ApplicationUser` deriva `IdentityUser`? Pode postar o código dos seus `Models` na pergunta?
Comment: Problema resolvido!!!

Obrigado Cigano!
Comment: Cigano, olha o erro retornado:
'Microsoft.AspNet.Identity.UserManager' does not contain a definition for 'Users' and no extension method 'Users' accepting a first argument of type.
Comment: A única alteração que fiz foi no contexto, o meu é ApplicationDBContext.
Comment: A ApplicationUser deriva de IdentityUser. Coloquei o código lá.
Comment: Atualizei a resposta. Pode ser que falte alguma configuração no seu contexto.
Comment: O erro continua:
'...UserManager' does not contain a definition for 'Users' and no extension method 'Users' accepting a first argument of type 'Microsoft.AspNet.Identity.UserManager' could be found (are you missing a using directive or an assembly reference?) C:\Users\Renatto.Machado.DesRenatto\documents\visual studio 2013\Projects\WebApplication9\WebApplication9\Controllers\UsuariosController.cs 36 43 WebApplication9
Comment: Deve ter algo errado na configuração do seu projeto. Aqui repliquei o exemplo e funcionou. Fiz mais uma edição.
Comment: Cigano, o que fiz foi o seguinte: New Project > ASP.NET Web Application > Escolhi o Template MVC > Alterei a Autenticação para Individual User Account > Botão OK.

Por isso acho que não é algo errado com a configuração do projeto.
Comment: Alguma sugestão Cigano?
Comment: Fiz o mesmo e aqui tudo funcionou após a atualização de pacotes. Experimente apertar F12 em `UserManager` para verificar se a referência está correta.
Comment: Fiz o que falou, fui levado para Assembly Microsoft.AspNet.Identity.Core.dll, v22.214.171.124, onde é definido a classe UserManager.
Comment: E não tem uma property chamada `Users` dentro desse `UserManager`?
Comment: Na verdade não. Só tem isso:

`public class UserManager : UserManager where TUser : class, Microsoft.AspNet.Identity.IUser
    {
        public UserManager(IUserStore store);
    }`
Comment: O pacote está desatualizado. Experimente atualizar.
Comment: Cigano, eu entrei no menu Tools > Extensions and Update > Update. Todos os pacotes estão atualizados.

Como faço a atualização que você disse, neste caso?
Comment: `View > Other Windows > Package Manager Console`. Digite o comando `Update-Package Microsoft.AspNet.Identity.Core`.

Como Listar Usuários com Asp.Net MVC 5


Tensor product of (general?) groups

Question: I am starting to learn about tensor products of abelian groups.
Why is the tensor product defined for abelian groups? In which part of the construction the commutativity of the groups is needed?
Comment: I was wrong. The tensor product of general groups really satisfies the universal property, due to the link in the answer of @3 1 3. Which was interesting for me.
Comment: There is no (important) tensor product for groups. But tensor products of  modules over commutative rings exists and are important. An Abelian group is a $\mathbb Z$-module.
Comment: check this http://groupprops.subwiki.org/wiki/Tensor_product_of_groups
Comment: @janmarqz Why not post that as an answer?
Comment: If I want the tensor product on two groups $G$ and $H$, couldn't I generate the free group by the elements of $G \times H$ and then quotient by the corresponding relations? When does this construction fail?
Comment: @MattSamuel: I am new on the subject, i am thinking
Comment: @zxv: but what do you mean with a tensor product between two groups? The universal property does not exist for this, I think.
Comment: @Lehs: you should check the link I gave
Comment: @janmarqz, yes I have seen it. I might be wrong, but I think it's a "kind of" type of tensor product, rather than an object with a universal property.
Answer: @Laters: Just to add to the answer of laters, the following should explain the idea of the nonabelian tensor product. More details are in the Brown-Loday paper linked in that answer.
Let $M,N$ be normal subgroups of the group $P$. Consider the commutator map
$$c=[\, ,\, ]: M \times N \to P, (m.n) \mapsto mnm^{-1}n^{-1}.  $$
Then $c$ is not bimultiplicative but it is a biderivation in the sense that there are formulae for $[mm',n], [m,nn'] $,  which I leave you to work out, and which involve the conjugation $^n m= nmn^{-1}$. So we form the universal construction for biderivations, i.e.  a biderivation $\kappa: M \times N \to M \otimes N$ which is universal for biderivations; it is constructed from the free group on $M \times N$, by factoring out the biderivation rules. One has to do some fiddling to prove some key properties; the main one is  to use the biderivation rules to interpret $mm' \otimes nn'$ in two ways, ending up with the nice formula
$$[m,m'] \otimes [n,n']= [m \otimes n,m' \otimes n'].   $$
Since $\kappa$ is a morphism it has a kernel.  The main result of the BL paper implies that this kernel is isomorphic to $\pi_3(X)$ where $X$ is given by the pushout of spaces
$$\begin{matrix}K(P,1) & \to & K(P/N,1) \\
\downarrow && \downarrow \\
K(P/M,1) & \to & X \end {matrix} $$
while $\pi_2(X)  \cong (M \cap N)/ [M.N]$. A useful special case is when $M=N=P$, when $X\simeq SK(P,1) $.
January 10: To answer the original question, if you seek for a universal object $M \otimes' N$  for bimultiplicative maps, then fiddling with expressing $mm' \otimes nn'$ in two ways leads one to the conclusion that $M \otimes
' N$ is abelian, and is the usual tensor product of the abelianisations of $M,N$. This argument can be found in some classics on group theory.
Comment: A reference for the last paragraph? A rapid look in google book gives *Non-Abelian Homological Algebra and Its Applications*, Hvedri Inassaridze, chapter VI, but that part is not available for free and this seems a quite advanced book.
Answer: There is a version of the tensor product for nonabelian groups, but this notion is much more specialized. See http://www-irma.u-strasbg.fr/~loday/PAPERS/87BrownLoday%28vanKampen%29.pdf, section 2. In the construction at some point you do a mod out, which you cannot do in general if you do take the free group instead of the free abelian group. (You see a free group on some set is nonabelian unless the set has cardinality $>1$, so you need to have a normal subgroup to form the mod out, and the standard way to get over this issue is to take the normal closure. This is implicit in the paper, where they use a presentation.)
see also http://pages.bangor.ac.uk/~mas010/nonabtens.html
Comment: If it is natural, what's the problem then? If I quotient the free group by the normal subgroup generated by those relations, don't I get what I want?
Comment: Could you be more specific about which mod out wouldn't work?
Comment: @zxv: in the tensor product for abelian groups you consider $F(A\times B)/N$ where $F(A\times B)$ is the free abelian group on $A\times B$ and $N$ the subgroup generated by the defining relations. For the nonabelian tensor product you must take $N$ to be the normal subgroup generated by the relations (a presentation). But this is a natural thing to do
Comment: @zxv: sorry, I didn't see your response. No there is not a problem, it is very natural generalization, you certainly get what you want. I just pointed out what one has to change.
Answer: The tensor product in defined for $R$-modules, with $R$ unit ring, and the abelian groups are $\Bbb{Z}$-modules.

Tensor product of (general?) groups


Reversing each word in file and printing it out

Question: I have a file that looks like it:

"Gettyburg Address
Abraham Lincoln
Fourscore and seven years ago our fathers brought forth on this
continent a new nation, conceived in liberty, and dedicated to the
proposition that all men are created equal. "

What I am trying to do is to print the file in the same format how it is but with reversed words. Could someone help me with that?
here is my method:
public static void convertWord() throws Exception {
    String name;
    int sum = 0;

    Scanner sc2 = new Scanner(new File("text.txt"));
    while (sc2.hasNextLine()) {
        name = sc2.nextLine();
        for (int i = name.length() - 1; i >= 0; i--) {
            char c = name.charAt(i);
            System.out.print(c);

        }

This is the output:
run:
sserddA grubytteGnlocniL maharbA siht no htrof thguorb srehtaf ruo oga sraey neves dna erocsruoF eht ot detacided dna ,ytrebil ni deviecnoc ,noitan wen a tnenitnoc  .lauqe detaerc era nem lla taht noitisoporpBUILD SUCCESSFUL (total time: 0 seconds)
Everything is in one line.
Thank you in advance for your help :)
Answer: You can reverse using StringBuilder::reverse
public static void convertWord() throws Exception {
    String name;
    Scanner sc2 = new Scanner(new File("text.txt"));
    StringBuilder builder = new StringBuilder();
    while (sc2.hasNextLine()) {
        name = sc2.nextLine();
        builder.append(name);
    }
    String reverse = builder.reverse().toString();
    System.out.println(reverse);
    sc2.close();
}

Answer: I guess the problem is more elaborate than just handling the newlines correctly.
The way I understand it is that only the words themselves need to be reversed, not the order of the words.
Example: "Foo bar" should become "ooF rab", and not "rab ooF".
And then there may be commas, periods, question marks and other stuff that does not belong to a "word", which should also stay in place. Actually this is the far more tricky part of the problem than the word reversing itself.
My first shot would be something like this, although I have not tested it, so don't blame me for minor issues. You get the idea:
String[] words = wholeContentsOfFile.split("[\n\t .,!?]"); // whatever delimiters you may like
Map<String, String> map = new HashMap<>();
for (String w : words) {
    if (!"".equals(w)) {
        map.put(w, new StringBuilder(w).reverse().toString());
    }
}

String result = s;
for (Map.Entry<String, String> e : map.entrySet()) {
    result = result.replaceAll("\\b" + e.getKey() + "\\b", e.getValue());
}

System.out.println(s);


ABRSM: Piano performance diploma

Question: The information on the ABRSM website isn't entirely clear to me.
Is there a diploma for piano performance only?
Thanks!
Answer: I assume you mean a diploma with no viva voce, sight-reading, or written requirements.
The ARSM is the only such diploma offered by the ABRSM. It is a fairly new entry-level diploma.

ABRSM: Piano performance diploma


Showing Mahonian triangle numbers related to inversion probability

Question: From this OEIS page about Triangle of Mahonian numbers:
http://oeis.org/search?q=+A008302&language=english&go=Search
I know 2 things:

That the  $T(n,k)$ can be generated by the coefficients in expansion of $$\prod_{i=0..n-1} (1 + x + ... + x^i)$$, where $k$ ranges from $0$ to A000217(n-1).
$T(n,k) :=$ number of permutations of $\{1,\ldots,n\}$ with $k$ inversions.

But can you please connect these two distinct ideas, i.e. why would the coefficients of this product of polynomials give the number of inversions of a set of consecutive integers? How are these two things related?
Answer: When you multiply $$\prod _{i=0}^{n-1} \sum _{j=0}^i x^j=1(1+x)\cdots (1+x+\cdots +x^{n-1}),$$ what you get as coefficient of $x^k$ is $|\{(a_1,\cdots , a_n):a_i<i \wedge \sum a_i = k\}|$ because of Cauchy product(i.e., $$(\sum _{i=0}^n a_i x^i)(\sum _{i=0}^m a_i x^i)=\sum _{ i = 0}^{n+m}(\sum _{\substack{r+s=i\\ r\leq n\\ s\leq m}}a_rb_s)x^i$$)
Now take a permutation $\pi\in S_n$ with $k$ inversions and denote $A_i = |\{j:j<i \wedge \pi _i < \pi _j\}|,$ so $\sum A_i = k,$ because you are doing a partition of the inversion pairs and $A_i<i$ because $0\leq j<i.$

Hope it helps.
Answer: To give a more intuitive and less strict approach:
Claim: There is a bijection with permutations of length $n$ and $n$-tuples $(c[1], c[2], \dots, c[n])$, with $0 \le c[i] \le n - i$ for each $i$.
For each permutation $(p[1], p[2], \dots, p[n])$, let's assign
$(c[1], c[2], \dots, c[n])$, where $c[i] = \#\{j > i: p[i] > p[j]\}$. In other words, $c[i]$ counts number of inversions with $i$ being the first member of the pair. Note the property of this tuple: $c[i] \le n - i$ (as there are only $n-i$ other members to it's right). Let's call tuples that satisfy $0 \le c[i] \le n - i$ valid.
Crucial idea is that we can uniquely go in a reverse direction too: for a given valid n-tuple, there's a unique permutation that corresponds to it (easy to prove by construction recursively).
This means there's a bijection, and the number we're looking for is same as the number of valid tuples. Now let's use generating functions to count this: for each $i$, define $G[i](x) = \sum _ {j = 0}^{n - i} x^j$. Multiplying all $G[i]$'s with each other and finding coefficient of $x^k$ gives the desired quantity. (Note that after multiplying all $G[i]$ and rearranging terms, we get the same product as mentioned in the question above).


Using scrapy to get content length of a lists of links

Question: As the title indicates, I am interested to know if scrapy can be used to process a list of url's ( url's are stored in a mysql database ).
The only thing i need for each URL is the content-length of the data returned.
Anybody worked on similar projects ?
Thanks
Answer: In a callback yield a Request with method='head'. In the next callback extract header HTTP_CONTENT_LENGTH from the response object.


select datas between ranges

Question: Into an Oracle DB i have two tables, TABLE A and TABLE B,
TABLE B have a range of dates and i have to find if a YEAR in table A is before the start date, after the finish date or if is not in the range
TABLE A
+-----+-----+
|NAME |YEAR |
+-----+------
|R1   |2016 |
|R1   |2015 |
|R1   |2014 |
|R1   |2013 |
|R2   |2016 |
|R2   |2015 |
|R2   |2014 |
|R2   |2013 |
+-----+-----+

TABLE B
+----+---------+----------+
|NAME|YEARSTART|YEARFINISH|
+----+---------+----------+
|R1  |2015     |2016      |
|R1  |2013     |2013      |
|R2  |2016     |2016      |
|R2  |2013     |2014      |
+----+---------+----------+

RESULT
+----+----+
|NAME|YEAR|
+----+----+
|R1  |2014|
|R2  |2015|
+----+----+

i found when a record is before the lower start date and after the higthest finish date
but how to find if a year is not in a range?
in my example i got R1 2014 and R2 2015 which are not in the range, how to identify them?
Answer: Use a left join:
SELECT *
FROM TableA a
LEFT JOIN TableB b ON a.NAME = b.NAME
                  AND a.YEAR >= b.YEARSTART
                  AND a.YEAR <= b.YEARFINISH
WHERE b.NAME IS NULL

Answer: You can use NOT EXISTS to return a row from table A if same name doesn't exist in table b with overlapping years:
select ta.name, ta.year
from tablea ta
where not exists (select 1 from tableb tb
                  where ta.name = tb.name
                    and ta.year between tb.yearstart and tb.yearend)

select datas between ranges


Solução para  com muitas opções

Question: Qual a melhor solução para fazer o <select> deixar tal resultado selecionado em um <select> com muitas opções ?
Eu uso IF nesssa situação com poucas opções, mas fica inviavel para um  muito grande...
segue código de exemplo:
<select class="alterarperfilNomeInput2" name="sexo">
<?php
if ($row[sexo] == "Masculino")
{
echo "<option value=\"Masculino\" selected>Masculino</option>
<option value=\"Feminino\">Feminino</option>";
}
else
{
echo "<option value=\"Masculino\">Masculino</option>
<option value=\"Feminino\" selected>Feminino</option>";
}
?>
</select>

segue tambem código do select que preciso deixar uma opção selecionada apenas de acordo com o BD...
<select name="dia" class="alterarperfilNomeInput2A">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
</select>

Answer: Nessas situações você pode utilizar o operador ternário ?:, diretamente no echo, assim:
<select class="alterarperfilNomeInput2" name="sexo">
<option value="Masculino"<?php echo ($row[sexo] == "Masculino" ? ' selected':'') ?>>Masculino</option>
<option value="Feminino"<?php echo ($row[sexo] == "Feminino" ? ' selected':'') ?>>Feminino</option>
</select>

Para o dia use um for, assim:
<select name="dia" class="alterarperfilNomeInput2A">
<?php
for($i = 1;$i<=31;$i++) {
    echo '<option value="'.$i.'"'.($row[dia] == $i ? ' selected':'').'>'.$i.'</option>'."\n";
}
?>
</select>

Answer: Podes sempre fazer uma chamada ajax e obter o valor que tens guardado na base de dados (consegues fazer isso?). A partir daí, basta colocares uma função no document ready da página:
$( document ).ready(function() {
    var opcao = "5"; //exemplo de um valor do dia
    $('[name=dia]').val(opcao);
});

Link: jsfiddle
Com este exemplo vai funcionar para qualquer tipo de select que possas ter. Caso apareça um que não seja com os dias do mês (o value é um inteiro) e seja com marcas de automóvel ou assim (o value é string) terás problemas...
Answer: Com esta função fica com a liberdade de utilizar numeros ou letras e também pode colocar o valor diferente do texto nas suas opções para select.
$dias = range(1,31);//array 1 a 31
$cont = 5;
select($dias,$cont);

$gender = array("masculino"=>"homem", "feminino"=>"mulher");
$gcont = "masculino";
select($gender,$gcont);

function select(array $options, $controler){
    $select_options = NULL;
    foreach ($options as $key=>$value) {
        $selec = ($key == $controler) ? "selected='selected'" : "";
        $select_options .= "<option value='$key' $selec>$value</option>";
    }
    return $select_options;
}

Solução para  com muitas opções


Binding in Phonegap

Question: I'm building an app using Phonegap and I am running into a strange issue where the binding to click events is not working, does anyone know why?
document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
    navigator.geolocation.getCurrentPosition(onSuccess, onError);

    $('._jsClick').on('click', function() {
        alert('Hi!')
    });

And here is the HTML
<button class="_jsClick">Click Here!</button>

Comment: Are you using jQuery Mobile to build your mobile app?
Comment: @MattStarkey have you tried the answer?
Answer: First you should change click function to:
$('._jsClick').on('click', function(event) {
        alert('Hi!')
    });

Also you should:
$('div:jqmData(role="page")').on('pagebeforeshow', function(){
    $('._jsClick').on('click', function() {
        alert('Hi!')
    });
});

$('div:jqmData(role="page")').live('pagebeforeshow', function(){
        $('._jsClick').on('click', function() {
            alert('Hi!')
        });
    });

Not document.ready
Check this link out: how can I make jquery mobile "pagebeforeshow" event fire every time, not just on refresh. The code above will be called when $.mobile.changePage is called.
This should look like this:
document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
    navigator.geolocation.getCurrentPosition(onSuccess, onError);
    $('div:jqmData(role="page")').die('pagebeforeshow');
    $('div:jqmData(role="page")').live('pagebeforeshow', function(){
       $('._jsClick').off('click');
       $('._jsClick').on('click', function() {
        alert('Hi!')
       });
     });
    }

Comment: also don't forget to unbind using 'off' on 'pagehide' or to block bound elements from being re-bound when a user visits a page was not removed from the DOM
Comment: Your pagebeforeshow binding is inncorect. It should be $(document).on('pagebeforeshow', '#index', function(){
Comment: If you have multiple pages, you should only use that for that page.
Comment: Check this link out: http://stackoverflow.com/questions/7549571/how-can-i-make-jquery-mobile-pagebeforeshow-event-fire-every-time-not-just-on
Comment: Again, take a look what have you written.
Comment: So I need to have all my binding etc for each different page within a different    $(document).on('pagebeforeshow', '#index', function(){ each time?

Binding in Phonegap


Error NoReverseMatch

Question: Olá, estou com o seguinte erro em uma aplicação em Django.

NoReverseMatch at /row/details/2 Reverse for 'get-weatherdata' with
  keyword arguments '{'rowId': 1, 'sensorId': 1}' not found. 1
  pattern(s) tried: ['api/weatherData/$'] Request Method:   GET Request
  URL:  http://localhost:8000/row/details/2 Django Version: 2.2.5
  Exception Type:   NoReverseMatch Exception Value:  Reverse for
  'get-weatherdata' with keyword arguments '{'rowId': 1, 'sensorId': 1}'
  not found. 1 pattern(s) tried: ['api/weatherData/$']

Estou precisando passar como parâmetro para a api/weatherdata dois identificadores. Não sei se estou fazendo corretamente, mas segue os demais códigos
views.py
def get_weatherData(request, rowId, sensorId):
    weatherData = WeatherData.objects.filter(row_id=rowId, sensor_id=sensorId)

urls.py
url(r'^api/weatherData/$', get_weatherData, name='get-weatherdata'),

index.html

Answer: Você está enviando parâmetros no template e também os recebendo na view mas não existe uma rota em urls que satisfaça esta condição, assim, acrescente os parâmetros nela.
    url(
        r'^api/weatherData/([0-9]+)/([0-9]+)/$',
        get_weatherData,
        name='get-weatherdata'
    ),

Na versão 2.x do Django foi introduzida a path() que é bem mais clara para definir a sintaxe das URL que as regex da url().

Error NoReverseMatch


Calculating the convolution of $\sin(t)/t$

Question: So how would I go about calculating the convolution of:
$$1* \sin(t)/t$$
This will be a simple looking integral, however $\sin$ or $\cos$ are not defined for infinity and negative infinity.
Comment: See [Sine Integral](http://mathworld.wolfram.com/SineIntegral.html).
Answer: As stated, the convolution is simply the integral of the function, or
$$\int_{-\infty}^{\infty} dt \frac{\sin{t}}{t} = \pi$$
Comment: I'm still not quite sure how you get pi from that
Comment: This is a well-known integral and can be computed in several ways, e.g., Parseval-Plancherel, Cauchy's theorem, ...


Performance of DateTime comparison in LINQ

Question: For example, I have some data source (probably, database) from where I need to extract all records for the last month. I'm using LINQ. There are two possible ways how to achieve this:
First:
var res = from rec in _records
          where rec.RequestDateTime.Date.Year == date.Year &&
                rec.RequestDateTime.Date.Month == date.Month
          select rec;

Second (using direct Date comparison):
var year = date.Year;
var month = date.Month;

var monthStart = new DateTime(year, month, 1);
var monthEnd = new DateTime(year, month, DateTime.DaysInMonth(year, month));

var res = from rec in _records
          where rec.RequestDateTime.Date >= monthStart &&
                rec.RequestDateTime.Date <= monthEnd
          select rec;

I heard that the second code works faster for the most LINQ providers, but can't find any proofs or explanations (or disproofs). So, what way actually better to use for better performance and why?
Comment: What did your profiling tell you?
Comment: @Rune FS, sadly profiling doesn't explain why...
Comment: correct it only answers the first part of your question.
Answer: I'd go further - IMO it will work faster for almost all providers (not least, LINQ-to-Objects). When talking about indexed data - database indexes are usually sorted, so taking a selection based on a range is really really quick and easy. There is no interpretation required by >= and <=, and it can jump directly to the required range very quickly. However, if you are comparing the year and month, it has two choices:

calculate the year / month (based on the numeric value underpinning a date) and compare for equality - and note it may or may not be able to use the index, needing instead a full scan
do some very clever thinking to determine that it is a range (making query parse more complex)

For the simplest case (LINQ-to-Objects) the same holds true; >= etc is trivial - it is a numeric compare. Testing month/year requires computing the month / year. That data is not stored explicitly as integers and is not directly on hand. Yes it isn't overly expensive to calculate, but when considering date en-masse, it isn't free either.


Why does adding a suitable multiple of $9$ always lead to the reverse of the number?

Question: For example:

$12$ reversed is $21$ and $12$ + $9$ = $21$.
$17$ with the two values swapped is $71$, and $17$ + $9$ + $9$ + $9$ + $9$ + $9$ + $9$ = $71$.
Take the number $123$ and add $9$ a total of $22$ times you get $321$, which is the reverse.

It seems to work for every number. Why is this the case? Is it just a addition thing?
Comment: Because $10a+b-(a+10b)$ is a multiple of $9$ (Exercise:  generalize to more than $2$ digits).
Comment: Next exercise: generalize to other bases (try base 8)
Comment: Next exercise "this works for every number" - provide proof of this statement
Comment: @AshwinIyengar - Shades of Tom Lehrer's [*New Math*](https://www.youtube.com/watch?v=UIKGV2cTgqA). :-)
Comment: It is not just reversal: you can put the digits in any order. So while $321=123+22\times 9$, you also have
$312=123+21\times 9$,
$231=123+12\times 9$,
$213=123+10\times 9$,
$132=123+1\times 9$.
Comment: I was just going to say, "Because adding 9 is 1 less than adding 10..."
Comment: It's not literally true, of course. No matter how often you **add** 9 to 321, you'll never get 123. And even changing it to "why does adding _or subtracting_ ..." doesn't cover the case where the number is a palindrome (its own reverse). In short, `x = palindrome(x)+ c * 9` but c ∈ ℤ, not ℕ
Comment: Why does adding a 1 or a multiple of 1 always lead to the reverse of the number? 17 + 1 + 1 + 1 + 1 + .... + 1 + 1 = 71
Comment: It's also not true that adding 9 or a multiple of 9 always leads to the reverse of the original number; rather, reversing the digits of a number always leads to adding or subtracting a multiple of 9. (In the case of a palindrome, the multiple of 9 is 0.) The direction of implications is important.
Comment: Another trivial and non useful thing with plenty of upvotes.
Answer: Any number is congruent modulo $9$ to the sum of its digits:
$$a_na_{n-1}\ldots a_1a_0\equiv a_n+a_{n-1}+\ldots +a_1+a_0\pmod 9$$
If you reverse the digits, the sum is unchanged. Therefore $$a_0a_1\ldots a_{n-1}a_n\equiv a_na_{n-1}\ldots a_1a_0\pmod 9$$
which is equivalent to your statement.

Note a stronger statement implied by the same reasoning:
By adding or subtracting a suitable amount of $9$'s, you can reach any permutation of the digits.
Answer: This isn't a formal proof or anything, but it's the way that makes the most sense to me. Adding 9 to something is the same as adding 10 then subtracting 1, which means that you're bumping one place up and the other down. Therefore, the sum of the digits in a number doesn't change when you add or subtract 9 to it, and by repeatedly adding (or subtracting) 9 to a number you can cycle through all the different numbers whose digit sum equals your original number. As the reverse of a number still has the same digit sum as your original number, you can get to it through adding or subtracting 9's. Hope this makes sense!
Comment: This works well except when the number is a multiple of 10. Then the sum of the digits changes. However, in terms of simplicity, this is a good way to understand the process and can lead to an intuitive conclusion.
Comment: This seems nice as an intuitive starting point, but as a mathematical argument it has some problems. When I bump up the tens place and bump down the ones place, *usually* nothing special happens and it's clear the digit sum stays the same... but *sometimes* this causes a carry into or out of the tens place, and then the argument that the digit sum stays the same is harder (because it isn't, in fact, true!). And even if you did have a process that kept the digit sum the same, that doesn't mean you can cycle through all the numbers with the same digit sum just by iterating it.
Comment: @CJ Dennis You are right, but then if we take the digit sum again, all the way down to a single digit number, that number shouldn't change. So 10 becomes 1, and 19 becomes 10, which becomes 1 as well.
Answer: Well, take a number  $N=a_na_{n-1}a_{n-2}.....a_2a1$.
This is $N=\sum_{k=0}^n a_i*10^n$.  Reverse the digits  and you get $M = \sum_{k=0}^n a_i 10^{n-i}$.
Subtract them and you get:
$N-M = \sum_{k=0}^n a_i*(10^i - 10^{n-i})$.
Now I claim that for any $j,k$ that $10^j - 10^k$ is a multiple of $9$.  If $k< j$ then $10^j - 10^k = 10^k(10^{j-1} - 1) = 10^k*9999....9$.  That's clearly a multiple of $9$.  (Actually, if this were a formal proof we'd have to prove that... sigh... but we won't).
So $N - M$ is ... a multiple of $9$.
So.... if you add $9$ enough times, you'll eventually get from $N$ to $M$.
=====
It's actually kind of interesting.
Take $8364$ and $4638$ then $8364 - 4638= 8*1000 + 3*100 + 6*10 + 4 - 6*100 - 4*1000 - 3*100- 6*10 -4 = 8*(1000-1) + 3*(100 - 10) - 6*(100-10) - 4*(1000 -1)$.
Kind of an interesting symmetry, isn't it?  (I had never noticed it before.)
Have you ever seen this trick:
Take a three digit number:  $abc$,  reverse it  $cba$, subtract them $abc- cba = def$.  Reverse it $fed$ and add them.  $def + fed = 1089$.  Always.
Comment: I think you want to use `\cdot` ($\cdot$) or `\times` ($\times$) instead of `*` for multiplication.
Comment: Your closing "trick" fails if a = c, since the three digit number is then a palindrome that is necessarily equal to its reverse causing the difference to be zero.
Comment: The indices are a bit off in the beginning (eg $N=\sum_{k=0}^n a_i*10^n$ should be $N=\sum_{k=0}^n a_k*10^k$)
Comment: I don't reckon fleablood is going to change the $\ast$ `\ast` habit... but what's really unreadable are those inline chain equations.
Answer: Good observation!  To flesh out the proof a little bit, let's write out your number in base $b$, from right to left (like when you add, subtract or multiply).  Call the smallest digit $a_0$, the next-smallest $a_1$ and so on, and since they're digits, $0 \leq a_i < b$.  Then any number has the form $a_0 b^0 + a_1 b^1 + a_2 b^2 + ...$ For example, the number 117 in base 10 is $7 \cdot 10^0 + 1 \cdot 10^1 + 1 \cdot 10^2 + 0 \cdot 10^3$, and we can write out as many more zero digits as we want.
Now let's pick a $c$ so $b \equiv 1 \;(\operatorname{mod} c)$. (When $b = 10$, one value of $c$ that works is $9$.  What's the other?) Apply that equivalence to the general form we just found for any number in terms of its digits:
$$a_0 b^0 + a_1 b^1 + a_2 b^2 + ... \equiv a_0 1^0 + a_1 1^1 + a_2 1^2 + ... \equiv a_0 + a_1 + a_2 + ... \;(\operatorname{mod} c)$$
A special case of this is, that when $b = 10$ and $c = 9$, you can rearrange the digits any way you want and they will still have the same sum, which means the same remainder divided by 9, so the difference between them will be a multiple of 9.
This theorem has a number of mildly-practical applications. One is the method of "casting out nines," which people have used to check their arithmetic for centuries.  A corollary of that is that any number will be congruent, modulo 9, to the sum of its digits. So let's say we want to check the answer $123 + 456 = 589$. $123 \equiv 1 + 2 + 3 \equiv 6 \;(\operatorname{mod} 9)$ and $456 \equiv 4 + 5 + 6 \equiv 9 + 6 \equiv 6 \;(\operatorname{mod} 9)$. So, we know $123 + 456 \equiv 6 + 6 \equiv 3 \;(\operatorname{mod} 9)$.  But, $589 \equiv 5 + 8 + 9 \equiv 4 \;(\operatorname{mod} 9)$, and therefore, our answer was wrong.  In fact, our intuition tells us that the sum of our digits was off by one, so probably one of our digits was also off by one. There are similar tricks we can use with the numbers 6, 7, and 11 in our heads. (Hint: what happens when $b \equiv -1 \;(\operatorname{mod} c)$ or $b \equiv b^2 \;(\operatorname{mod} c)$?)
Cheap microchips have made that particular trick less useful, and I don't think it's even taught any more.  But it's also created real-world applications for the technique in computer science.  For example, we might want to interpret an object as some arbitrary sequence of 32-bit unsigned words, representing the digits of a number in base $2^{32}$, then take mod 65,537 in order to calculate a hash value for it.  Or we might do bignum arithmetic, or find a remainder on a CPU with no mod instruction.
Answer: It's a simple consequence of 9 being 1 less than 10, the base of our system of numeration.
Consider $10^n$ for $n \in \mathbb Z^+$. The reversal of $10^n$ is 1, and $10^n - 1$ is all 9s.
Next consider the table of multiplication for 9: $1 \times 9 = 9$, $2 \times 9 = 18$, $3 \times 9 = 27$, etc. Notice how the one's place decreases by 1 each time, until getting to $10 \times 9 = 90$ and $11 \times 9 = 99$, and so the cycle repeats again.
This is not a proof either, but I hope it helps you see this more clearly.
Comment: This is what I was going to say.    Each consecutive +9 is the same as saying +10 - 1.
Answer:
Lemma: $\overline{ab}-\overline{ba}\equiv 0 \pmod 9$.
  Proof: $(10a+b)-(10b+a)=9(a-b)\equiv 0 \pmod 9$.

Based on the Lemma, $\overline{abc}-\overline{cba}\equiv 0\pmod 9$, because:
$$\overline{abc}-\overline{acb}\equiv \overline{acb}-\overline{cab}\equiv \overline{cab}-\overline{cba}\equiv 0 \pmod 9 \iff \\
(\overline{abc}-\overline{acb})+(\overline{acb}-\overline{cab})+(\overline{cab}-\overline{cba})\equiv 0 \pmod 9 \iff \\
\overline{abc}-\overline{cba}\equiv 0\pmod 9.$$
Note: It is $T(2)=3:\overline{abc}\Rightarrow \color{red}{\overline{acb}\Rightarrow \overline{cab}\Rightarrow \overline{cba}}$.
In general, $\overline{a_1a_2...a_n}-\overline{a_na_{n-1}...a_1}\equiv 0 \pmod 9$ and:
$$\overline{a_1a_2...a_n}\overbrace{\Rightarrow}^{T(n-1)} \overline{a_na_{n-1}...a_1}.$$


I have a Problem with function OnClick Fragment _kotlin in Android studio

Question: Hello everybody,I Add OnClick in XML_Fragment
in code_fragment , function Don't work
but in layout,function is work , ,How do you do for work with code fragment?,Thank you
Answer: You don't need to add onClick property for each element in your layout.
You can directly make the fragment extends the OnClickListener interface.

extend your fragment with OnClickListener
then implement onClickListener methods
in the onClick method, do the stuff you want (nembrememore)


Questions about Python time_to_sleep?

Question: When writing the code, the following code will be activated on time, saying it is stopped until the hour.
However, to operate the code on time, it takes more than 59 minutes to run the code must run the code.
Is there a way to make it work at 12pm by adjusting the minutes and hours instead of seconds in that code?

enter code here`current_time = time.time()
time_to_sleep = (60 - (current_time % 60))
time.sleep(time_to_sleep)

Answer: Instead of sleep, you can pause until a defined time:
import pause
from datetime import datetime

pause.until(datetime(2022, 10, 25, 12))

Answer: or you can do it like this:
import datetime
import time

while datetime.datetime(2022,10,25,10,28,0) > datetime.datetime.now():
   time.sleep(30)
    pass
print("it's time to act")

but @Tanner version seems to be more preferable
Comment: To be fair, I like yours too :)
Comment: this is a tight loop. it will burn CPU cycles needlessly, checking the condition a million times a second. put some small sleep in the loop, say a second or so.
Comment: @Christoph you're right
Comment: time. sleep(30)
does it mean that when 2022.10.25.10.28.00 is reached, it will be executed after 30 seconds? That is, is the execution statement executed at 2022.10.25.10.28.30?
Comment: You'd better use the second version with `pause.until`, this one is just worse analog. Yes, you're right, this code checks time every 30 second (check pause can be set to any needed time), in some condition it really can wait another 30 second after pointed date.

Questions about Python time_to_sleep?


What letters are used for guitar chords in Ukraine?

Question: There are Ukrainian refugees in my town and I may have the opportunity to give some guitar or ukulele lessons. Language is going to be a bit of a problem but I expect music to transcend that.
If I draw out the chords what lettering should I use for naming them? European A, B, C, ..., G or do they use their own alphabet?
Comment: That's awesome! If you're teaching complete beginners, of course, you can teach any system from scratch. I have no idea, but my guess is that most users of the Cyrillic alphabet also learn about the Latin alphabet and are more familiar with it than I am with theirs, but if not, teaching the letters along with the chords could also be a very useful lesson!
Comment: Absolutely a laudable idea! However, since there's a fair possibility those potential guitarists will be in your country for a good while, and have far more access to the more standard nomenclature, thus see it and use it more often, they'd benefit more from you using the standard A B C. Just a thought.
Answer: It is really only in European countries where Germanic languages (German, Dutch, English, ...) are spoken, that the A-G or A-H letter system is common. Other countries, including Russia and I assume also Ukraine, use fixed-do solmization in formal music education.
I see a lot of sources online where Russian or Ukrainian is mixed with Latin-script note names, so it's possible that Ukrainians will recognize "do, re mi, ...". Sources that use Cyrillic script have these names, which seem to be phonetic versions of French solmization:

do      до
re      ре
mi      ми
fa      фа
sol     соль
la      ля
si      си

flat    бемоль     (bémol)
sharp   диез       (dièse)

minor   минор
major   мажор

So a key or chord would be named e.g. "фа-диез минор" (see Wikipedia). I don't know whether there is a standard way of simplifying or abbreviating these.
Younger people may of course have watched English or German-language music lessons on YouTube, or looked for sheet music or tabs online, and may be familiar with "Em" and "F#" and "Bsus4".
Comment: @Transistor - you'd probably sing 'Doe, oh dear!'  But, fixed do is always C in fixed do language. In one band, I'm asked to play 'si bemol' (Bb) to get the horns in tune.
Comment: Your assumption about Ukraine using solmization is correct, according to Wikipedia at least:  "In ... Ukrainian, ... the note names are do–re–mi–fa–sol–la–si rather than C–D–E–F–G–A–B. "

https://en.wikipedia.org/wiki/Musical_note
Comment: I always regarded do-re-me as being relative to the tonic or root note of the key being used. In English we wouldn't say "in the key of *la*". Do they, in fact, do that in Ukraine? How would you sing "Doe, a dear" (Sound of Music) in the key of D?


O que há de errado neste código em delphi?

Question: No onCreate do mainform, tenho o seguinte código:
procedure TForm1.FormCreate(Sender: TObject);
begin
 QuickRep1.Prepare;
 QuickRep1.Printer.Load('arquivo.qrp');
 QuickRep1.ExportToFilter(TQRAsciiExportFilter.Create('teste.txt'));
 QuickRep1.Free;
end;

Ele deve abrir um arquivo QRP e salvar como TXT. Ele até cria o teste.txt, mas o arquivo está em branco, com 0kb. Onde estou errando?
Comment: Para ter certeza eu precisaria baixar o componente, mas tenho uma duvida. O arquivo 'arquivo.qrp' está junto com o executável da aplicação ? Tenta especificar o caminho dele. Ex: 'c:/arquivo.qrp'.
Comment: Sim, está junto. Quando eu dou um QuickRep1.Printer.Preview; o arquivo é exibido, sinal de que ele está sendo carregado corretamente
Comment: Pode me dizer qual a versão do QuickReport está utilizando ?
Comment: é a versão 5.02
Comment: Não consegui montar o código como o seu exemplo. Na parte do `QuickRep1.Printer.Load('arquivo.qrp');` tiver que trocar por `QuickRep1.QRPrinter.Load('arquivo.qrp');` Alem disso, consegue disponibilizar um arquivo de extenção .qrp para testes ?
Answer: Tente da seguinte forma:
Crie 2 novas variáveis (na uses interface declare: QRPrntr):
  vFilterLibrary : TQRExportFilterLibraryEntry;
  vExportFilter  : TQRExportFilter;

Depois do Prepare:
  vFilterLibrary := QRExportFilterLibrary.GetFilterByExtension('txt');
  vExportFilter  := vFilterLibrary.ExportFilterClass.Create(vNomeAnexo);
  QuickRep1.ExportToFilter(vExportFilter);

O que estamos fazendo é localizar o Filter pela extensão, depois pedimos para ele criar o arquivo (forma correta).
Nota: Para este procedimento funcionar, o formulário report que será exportado deve possuir um Filter que exporte com a extensão txt!
Comment: Compilou, mas na execução deu o seguinte erro: `raised exception class EAccessViolation with message 'Access violation at address 0050CBD8 in Module 'Project1.exe'. 'Read of address 000000004'`. Na seguinte linha:  `vExportFilter  := vFilterLibrary.ExportFilterClass.Create('teste.txt');`
Comment: Uma violação nesta linha só pode ocorrer se não existir no formulário um filter para a extensão mencionada!
Comment: Eu testei aqui, coloquei todos os filters do qreport no form, tentei com outro formato, mas ainda dá violação :(


SUMIFS function returning different value than filtering and using SUBTOTAL

Question: say I have an Excel table with columns as below.
A    B     C

Date|Name|Amount

I want to return the sum of amounts between dates x and y with names {"a","b"}.
I wrote a SUMIFS function
=SUMIFS(C:C,B:B,{"a","b"},A:A,">="&DATE(2018,1,1),A:A,"<"&DATE(2018,4,1))

Say that function returns 1,500,000
Now if I decide to filter for names "a" and "b", then I filter for the dates I want and use a subtotal function:
=SUBTOTAL(109,C:C)

it will return a number such as 2,000,000 greater than my SUMIFS function.
Is my mistake in the way im filtering or the SUMIFS function?
Answer:
=SUMIFS(C:C,B:B,{"a","b"},A:A,">="&DATE(2018,1,1),A:A,"<"&DATE(2018,4,1))

Is only summing where they are equal to a To get it to iterate we need to wrap it in SUM or SUMPRODUCT:
=SUMPRODUCT(SUMIFS(C:C,B:B,{"a","b"},A:A,">="&DATE(2018,1,1),A:A,"<"&DATE(2018,4,1)))

That is the reason for the difference.


Is it worse to go with Samsung 960 EVO instead of Pro version in terms of price to perforamce measure?

Question: We are about to deploy shared storage researching for ultra-fast storage to implement Microsoft SQL Server Failover Cluster (FCI). So far the project goes, we would to start with 500K IOPS and have ability of grows up to 2M IOPS in a year or so, due to the SQL server growing expectations.
For the purpose of the project, we are going to deploy 4-node cluster of Microsoft Storage Spaces Direct (S2D). Microsoft recommends going with NVMe or NVMe + SSD to obtain maximum performance. Therefore, after some research, Samsung SSDs are good to go with. The setup we consider is following: Samsung 960 EVO NVMe + Samsung 960 PRO SSD.
https://www.starwindsoftware.com/blog/benchmarking-samsung-nvme-ssd-960-evo-m-2
http://www.storagereview.com/samsung_960_pro_m2_nvme_ssd_review
Would S2D deliver 500k-2M IOPS to SQL FCI if the setup of S2D is Samsung 960 EVO NVMe + Samsung 960 Pro?
Comment: neither for business
Comment: Relevant: [What is the current state (2016) of SSDs in RAID?](https://serverfault.com/q/776564/58408) and [Are SSD drives as reliable as mechanical drives (2013)?](https://serverfault.com/q/507521/58408)
Comment: Jesus - don't use consumer kit for shared-anything, "Hi I'm going to build something that's a single-point-of-failure for my business using the cheapest components! durrr!"
Answer: When you are measuring price for performance, it really depends on the performance that you need to have in an application and if you need to for writes, or reads.
IF those are your only options, I would take the one with price for performance after a benchmark of what your application requires.
However if your building this for a business, I would encourage you to use something that would sustain high rates of either read or write, depending on your application.
http://www.samsung.com/us/business/computing/solid-state-drives


Migrating DNS from Windows Server 2003 to Windows Server 2012 R2

Question: Current environment: Two Windows Server 2003 servers, not joined to our domain (These are here to handle our outside DNS requests).
Plan: Stand up Windows Server 2012 R2 server, do not join to our domain. Give IP and install DNS role on server.  Mark server as slave to our master DNS server which is Windows Server 2003.  Once replication is complete, mark 2012 R2 DNS server as master.  Build secondary DNS server on 2012 R2 platform, join as slave to 2012 R2 master.  Then decommission 2003 DNS servers.
My question is, are there any "gotchas" or issue with this plan?  Will there be compatibility issues between the 2003 server and the 2012 R2 server?  Is our plan viable?  I have been searching around and have not found anything about doing this either from Microsoft or from one of their partners.
Answer: I've replicated this way before.  It's just a zone transfer, really.
I had to do it as part of a migration to new 2008 DC's in preparation for raising the functional level and replacing old hardware.  The issue I had with 2003 was ad-integrated DNS not playing nicely.  May have simply been because this domain had been an upgrade from NT 4.0 -> win2k -> win2k3 and then to win2k8.  Only 2k12 member servers... that being said:
https://support.microsoft.com/en-us/kb/323383
https://technet.microsoft.com/en-us/library/cc739904(v=ws.10).aspx
Biggest issue that I had was with internal servers having DHCP addresses but manually configured DNS servers ( I know this makes no sense ).  My advice would be to keep the old servers live and change your outside NS records to point to new servers before decommissioning the old ones ( external DNS should still accept SOA for secondaries ).  That will keep you alive during DNS zone propagation on the outside.  It will also let you roll back with less pain.
Comment: https://technet.microsoft.com/en-us/library/cc771150.aspx Sorry, too new to be allowed to post more than two links!
Answer: Edit:
Please note the below only transfers A records and no other so you would still need to manually input remaining.
I've never done the above, but another alternative would be to:

export your A records and zones from 2003. Save it - c:\dnsrecords.txt
re-importing into Server 2012.
Replicate other 2003 settings on 2012 that covers external lookups.
Assign one PC with the new DNS servers and monitor the effects.

Exporting the DNS entries can be done on 2003 server. You should have a text file similar to the below.
User-PC Host (A)    10.24.2.48
Fileserver  Host (A)    10.25.2.49

Get the file into XLS and turn Host & (A) into columns so you are only left with.
User-PC   10.24.2.48
Fileserver  10.25.2.49

You can then use for &  dnscmd to import the entries into your server 2012. Below is the dnscmd syntax and below that an example, which will run the command multiple times using the .txt you created as the input. It will replace %i with the hostname  and %j with the IP address.
dnscmd ServerName /RecordAdd DNSZoneName HostName RecordType IPAddress

DNScmd syntax:
for /f "tokens=1-2" %i in (c:dnsrecords.txt) do dnscmd Server2012 /RecordAdd test.local %i A %j

Answer: we have upgraded our DNS server as Slave in 2003 Domain server environment. I know you mentioned about not being in domain environment but I don't think that would be an issue as long as you have access/admin rights to Master DNS server. Once the new 2012 server is configured with DNS role, you will get an option at one stage to replicate from Master DNS server. As stuart mentioned, it would be mainly zone transfer and should not cause any issues having both running at the same time but you ideally want to demote/stop using 2003 server.
Answer: @Ankh2054 - Great answer!  Make certain that you clarify that you're only transferring A records with your script. ( my apologies for not commenting directly, I can't comment on posts yet )
While in windows in an inside environment using AD you usually have the SRV records created by AD, MX records are commonplace.  NS records are pretty big as well, even internally with NS IP's provided by DHCP.  Don't forget reverse zones for convenience ( PTR records ) and some mail servers will complain if there is not an external PTR for sanity checks.
Original Poster didn't specify whether or not they were using SPF,Google Apps, or some other Federated services which often require adding TXT records with a fingerprint, verification key, or something similar.  External CNAME records are common and a great way to provide the ability to manually fail over to backup servers and to segregate services from the IP they're running on.
Still, your script is a very elegant solution.  I've used something close ( but not as clean ) to bulk add missing PTR records.


Can't save my Preferences after app killed

Question: Hi I'm trying to implement a settings page on my Android App.
I defined a xml Preference file, where I implemented CheckBoxPreference and EditTextPreference.
All the settings work perfectly while running the app, but when I kill it I lose all the settings.
Preference.xml file:

<PreferenceCategory android:title="Connection">

    <CheckBoxPreference
        android:title="Auto Log-In"
        android:summary="Auto connect "
        android:key="autoLogIn"
        android:enabled="true"
        android:selectable="true"/>

    <EditTextPreference
        android:name="Server"
        android:summary="Change the default server"
        android:defaultValue="www.google.com"
        android:title="Change server to:"
        android:key="www.google.com" />

</PreferenceCategory>

Preferences.class
public class Preferences extends PreferenceActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);\
    }
}

How do I make the app save the settings?
UPDATE:
I did some test, and on the Virtual device and on my old HTC Legend with android 2.1 the settings work fine! But they don't work on the Samsung Galaxy S with android 2.2! Does this make sense to anybody?
Answer: I solved the problem with a soft reset* of my Samsung Galaxy S... can't belive I waisted an all day on a correct code.
Hope this will save some time to others.
Marco
*Soft reset: Settings -> Privacy -> Factory data Reset.
Answer: There shouldn't be any reason for the prefs not to be saved.
The prefs are saved immediately when you perform a change (e.g. checking the checkbox).
Are you sure you didn't simply confuse the key with the value? Your server key is android:key="www.google.com" Maybe that's why you think it is not saved?
Answer: I think you need to set android:persistent="true" for the preferences you want to store in SharedPreferences. As given here.