How to adjust prices depending on quantity and attributes using Drupal Commerce?

Question: I am using Drupal Commerce, and have a question about some of the available price/quantity modules. As an example, if people want to buy 1-5 pictures, the price is $49/each, if 6-10, than it is going to be $39 per each.
I found Commerce Price Table (1st) and Commerce Pricelist (2nd) modules for that. Looks like 2nd is more functional, but it is very "new" ... Not sure which one I should go for.
Or should I consider some other module(s) that are also popular for that? Or can I do it right from Drupal Commerce?
What I am actually looking for: a way which can adjust the price depending on quantity and attributes.
Answer: Module comparison
I'm not familiar with any other such pricing related modules. It seems to me that you will have to decide between these options:

A stable module (aka the price "table" module).
A module that's on the horizon (aka the price "list" module).

Whenever I have to decide between multiple modules, I often use the (23) criteria that I ever documented in "maintenance scorecards" (within the Community documentation). Those scorecards are actually "applied" to charting modules, but the same criteria can be used, I think, to mostly any type of module comparisons.
I'd be happy to provide some more details (via a next iteration of my answer), but if I was to decide I would definitely go for the stable, commonly used price "table" module. The major "red flag" (= no go) for the newer "list" module is criterium nr 26 (downloads vs reported installs ratio). Correct me if I'm wrong, but only like 10 % of downloads seem to have resulted in sites that continue using it.
Rules is your friend
I would definitely also consider the Rules module, using some custom Rules, something like so:

Events = Calculate Sell Price of Product.
Actions = calculate the price, and set the price to the calculated value.

Not sure (yet) if you'd need some extra 'Conditions' added to this.
Refer to Drupal commerce and rules: changing the product price dynamically for an example of dynamically changing product prices.
Create your own custom Rule
If for some reason you can't get it to work with the Rules module, then I'd consider writing my own custom Rule(s), similar to what is described in Drupal custom Rules how to write your own events conditions, actions and custom object.
The main steps that are detailed in this tutorial are further described below (with the code included below quoted from that link).
Part 1: Defining the Event, Condition and Action
Define the Rules Event
/**
* Implementation of hook_rules_event_info().
* @ingroup rules
*/
function your_module_rules_event_info() {
  return array(
    'your_module_package_bought' => array(
      'label' => t('A package was bought'),
      'module' => 'your_module',
      'arguments' => array(
        'acting_user' => array('type' => 'user', 'label' => t('The user who bought the package.')),
        'package' => array('type' => 'package', 'label' => t('The purchased package.')),
      ),
    ),
  );
}

Define the Rules Condition
/**
 * implementation of hook_rules_condition_info()
 */
function your_module_rules_condition_info() {
  return array(
    'your_module_condition_package_type' => array(
      'label' => t('Type of the package'),
      'arguments' => array(
        'package_id' => array('type' => 'value', 'label' => t('The type of the purchased package.')),
        'package_type' => array('type' => 'string', 'label' => t('The type of the purchased package is')),
      ),
      'module' => 'your_module',
    ),
  );
}

Define the Rules Action
/**
 * Implementation of hook_rules_action_info().
 */
function packages_rules_action_info() {
  return array(
    'your_module_action_change_order_status' => array(
      'label' => t('Change the order status'),
      'arguments' => array(
        'order' => array('type' => 'value', 'label' => t('The order object.')),
      ),
      'module' => 'your_module',
    ),
  );
}

Part 2: Coding the custom Event, Condition and Action
Event:
Somewhere in your custom module, you need to include logic to trigger the event, with something similar to this example (note the your_module_package_bought in it):
  //here the code for buying a package will be located
  //when that code returns that a package was bought trigger the rule
  $order = order_load($oid);//$oid will be the id of the order made
  $package = package_load($pid);//pid will be the id of the bought package
  global $user;
  rules_invoke_event('your_module_package_bought', $user, $package, $order);

Condition:
To evaluate the Rules condition (to check if it is TRUE or FALSE), the function your_module_condition_package_type is executed using the arguments provided. Here is an example of how such function could look like:
function your_module_condition_package_type($pid, $type) {
  $package = package_load($pid);
  return ($package->type == $type) ? true : false;
}

Action:
Somewhere in your custom module, you need to include logic to perform the actual action, in this example it should be done within the function named your_module_action_change_order_status.
Comment: Tried these two modules. 2nd is a little unstable. 1st works fine, BUT. If I need different prices for attributes, than I also have to fill price/ quantity for this attributes as well. Looks like that is a lot of work. In my case it is not too my, but I think there is rational way. I thought it works like: calculate total price for product depend on quantity and THAN add attribute price and multiple on this amount of items. I think I have to try Rules now...
Comment: I can imagine that it might be a lot of work if you have many attributes. But I believe it is "a" way to gt it to work. Otherwise you have to consider some type of custom module with some custom Rule (which may be "a lot of work" too, first to write such module, later on to maintain it. Because keep in mind that those prices may need to be changed some day also ... (that's why I'd hesitate to write a custom module for it).
Comment: quick question. Are you a programmer? What if we would ask you to write a module like that, how much can it cost?
Comment: i sent you message on drupal.org, but not sure if you did it right :) can you please email me? email@example.com


Using st_write in a for loop to export multiple shape files

Question: I am trying to create multiple shapefiles (and dataframes) based on unique field values within FIREYEAR. I have been able to produce individual dataframes based on each year with the corrrect number of observations in each one. When using st_write to create shapefiles though they come out incorrectly. My code creates individual shapefiles with the correct name but each shapefile contains all values from every year. In this case each exported shapefile should have 2 observations but comes out with 4. 2 from 1985 and 2 from 1986. How can I implement st_write in my for loop to correctly export multiple shape files? Thanks.
Sample data
df1 <- data.frame(FIRENAME = c("Gold", "Tree", "Tank", "Green_1"),
                  UNIQFIREID = c("1985-AZASF-000285", "1985-AZASF-000286", "1985-AZASF-000287", "1985-AZASF-000288"),
                  FIREYEAR = c("1985", "1985", "1986", "1986"),
                  TOTALACRES = c(60, 70, 80, 90))

# I left out the geometry which was sfc_MULTIPOLYGONs and didn't seem to make a difference for the example.

For loop and st_write code
for(i in unique(df1$FIREYEAR)) {
  list_data <- split(df1, df1$FIREYEAR)
  names(list_data) <- paste0("df_", names(list_data))
  list2env(list_data, .GlobalEnv)
  st_write(df1, dsn = "F:/School/NAU/Forestry/Masters/MSF_Project_2-7-2020/Michaels_Analysis/Fire_History/R", paste0(i), driver = "ESRI Shapefile", append = TRUE)
}

Answer: The problem with this code:
for(i in unique(df1$FIREYEAR)) {
  list_data <- split(df1, df1$FIREYEAR)
  names(list_data) <- paste0("df_", names(list_data))
  list2env(list_data, .GlobalEnv)
  st_write(df1, dsn = "F:/School/NAU/Forestry/Masters/MSF_Project_2-7-2020/Michaels_Analysis/Fire_History/R", paste0(i), driver = "ESRI Shapefile", append = TRUE)
}

is that no matter what you are doing inside this loop, the line:
st_write(df1, dsn = "....

is only going to write df1 again and again.
Either loop over the unique values and subset the dataframe, writing only the subset, something like this (untested because currently doing an upgrade... but I think it works):
## loop over all unique fire years:
for(year in unique(df1$FIREYEAR)) {
## subset only that year's data.
  df.year = df1[df1$FIREYEAR==year,]
## construct a file name like df_1986.shp and save this data:
  file.name = paste0("df_",year,".shp")
  st_write(df.year, file.name)
}

or use split and loop over the elements of the list that is returned.
You don't need extraneous packages to do simple things like this.
Answer: Instead of using a for() loop, you may want to use the iwalk() function in the purrr package. The code below will let you know how to use it to save your files:
library(sf)
library(purrr)

df1 <- data.frame(FIRENAME = c("Gold", "Tree", "Tank", "Green_1"),
                  UNIQFIREID = c("1985-AZASF-000285", "1985-AZASF-000286", "1985-AZASF-000287", "1985-AZASF-000288"),
                  FIREYEAR = c("1985", "1985", "1986", "1986"),
                  TOTALACRES = c(60, 70, 80, 90))

list_data <- split(df1, df1$FIREYEAR)
names(list_data) <- paste0("df_", names(list_data))

iwalk(list_data, function(dat, name){
  st_write(obj = dat, dsn = paste0("path/to/file/", name, ".shp"))
})


What is $\sqrt{\sin^2(-60^o)}$ equal to?

Question: I begin with the assumptions that:

$\sin(-60^o)= -\frac{\sqrt {3}}{2}$
$\sin^2(-60^o)=(\sin(-60^o))^2$
$(\sin(-60^o))^2= \sin(-60^o)*sin(-60^o) =-\frac{\sqrt {3}}{2}*(-\frac{\sqrt {3}}{2})=\frac {3}{4} $
$\sqrt[a]{x^a}=x$

So in my mind,
I. $\sqrt{\sin^2(-60^o)}=\sqrt{\sin(−60^o)∗\sin(−60^o)}=\sqrt{-\frac{\sqrt {3}}{2}∗(-\frac{\sqrt {3}}{2})}=\sqrt{\frac {3}{4}}=\frac{\sqrt{3}}{2}$
which is is what I would normally assume. But what happens in the case where I use 4. $\sqrt[a]{x^a}=x$?
Now when I try to find $\sqrt{\sin^2(-60^o)}$ , I get:
II. $\sqrt{\sin^2(-60^o)}=\sin(-60^o)=-\frac{\sqrt {3}}{2}$
But I also know, that $\sqrt{x}$ is defined only for $x\ge0$, so is II. even possible, or does $\sqrt{\sin^2(-60^o)}$ have an imaginary part, or am I making a mistake somewhere?
Comment: $\sqrt{x^2}$ is equal to $|x|$, not $x$ (also, you should really use radians when expressing angles...)
Comment: It's fine to use degrees for angles, but then you need to use the degree symbol. Otherwise you are in radians. Compare:
$$\sin60 = -0.3048106211\ldots$$
$$\sin60^\circ = \frac{\sqrt3}2$$
Comment: $$\sqrt {X^2}=|X |$$ the left side is positive.
Comment: If $a$ is even, then $\sqrt[a]{x^a} = |x|$
Answer: $$\sqrt{\sin^2(-60^{\circ})}=\sqrt{\frac{3}{4}}=\frac{\sqrt3}{2}.$$
Another way:
$$\sqrt{\sin^2(-60^{\circ})}=|\sin(-60^{\circ})|=\left|-\frac{\sqrt3}{2}\right|=\frac{\sqrt3}{2}.$$
Answer: Inside -out:
$-60$ is "fourth quandrant" so $\sin -60 < 0$ and $\cos -60 > 0$.
$\sin -60 = - \sin 60 = -\frac {\sqrt 3}2$
$\sin^2 -60 = (\frac{\sqrt 3}2)^2 = \frac 34$
$\sqrt{\sin^2 -60} = \sqrt {\frac 34} = \frac {\sqrt 3}2$.
Outside in:
$\sqrt{x^2} = |x|$
so $\sqrt{\sin^2 (-60)} = |\sin (-60)|>0$ so equivalent to the angle that gives a positive value.  As $\sin(x) = -\sin(-x) = \sin(\pi - x) = -\sin(\pi + x)$ etc. so the positive value is $\sin 60 = \frac {\sqrt 3} 2$.
Without handwaving and keeping the internal monolog internal (where is belongs):
I)  $\sqrt {\sin^2 (-60)} = \sqrt {(-\frac {\sqrt{3}}2)^2} = \sqrt{(\frac {\sqrt{3}}2)^2} = \frac {\sqrt 3}2$
II) $\sqrt{\sin^2(-60)} = |\sin(-60)| = |-\frac {\sqrt 3}2| = \frac {\sqrt 3}2$.
.... Basically, keep the basic understanding of signs basic:  Squaring something has a positive result; what's under a radical sign must be positive; the square root is always the non-negative square root; $\sin (-x) = - \sin (x)$ etc.  Keeping those in mind and know that $\sin {60} = \frac {\sqrt 3}2$, then..... you just do it.
=====
In other words:

I begin with the assumptions that:
4) $\sqrt[a]{x^a} = a$.

That is a wrong assumption.
If $a=2n; n\in \mathbb N$ is even then $\sqrt[a]{x^a} = |x|$.
If $a=2n-1; n \in \mathbb N$ is odd then $\sqrt[a]{x^a} = x$.
If $a \not \in \mathbb N$ then we have to define $\sqrt[a]{x^a}$ in terms of logarithms and that requires $x > 0$ and we will get $\sqrt[a]{x^a} = x$ provided $a \ne 0$>
Comment: Thank you for the thorough explanation!


Ruby app onetimesecret failing to start from systemd unit

Question: I'm trying to install ruby app onetimesecret on CentOS 7.4.1708 (Core)
by this manual: https://github.com/onetimesecret/onetimesecret.
Ruby is installed with rvm.
Everything is fine while running this command from shell:
/usr/local/rvm/rubies/ruby-2.3.8/bin/bundle exec thin -e dev -R config.ru -p 7143 -P /var/run/onetime/onetime.pid -l /var/log/onetime/onetime.log -d start

Server starts and works.
But it does not work with systemd unit.
[Unit]
Description=Onetime secret backend service
After=network.target
After=nginx.service

[Service]
Type=forking
RemainAfterExit=no
WorkingDirectory=/home/ots/onetimesecret
ExecStart=/usr/local/rvm/rubies/ruby-2.3.8/bin/bundle exec thin -e dev -R config.ru -p 7143 -P /var/run/onetime/onetime.pid -l /var/log/onetime/onetime.log -d start
TimeoutStopSec=10
PIDFile=/var/run/onetime/onetime.pid
Restart=on-failure
User=root
Group=root

[Install]
WantedBy=multi-user.target

Systemctl status onetime.service:
● onetime.service - Onetime secret backend service
   Loaded: loaded (/etc/systemd/system/onetime.service; enabled; vendor preset: disabled)
   Active: failed (Result: start-limit) since Sun 2019-09-15 13:30:37 +04; 1s ago
  Process: 4296 ExecStart=/usr/local/rvm/rubies/ruby-2.3.8/bin/bundle exec thin -e dev -R config.ru -p 7143 -P /var/run/onetime/onetime.pid -l /var/log/onetime/onetime.log -d start (code=exited, status=1/FAILURE)
 Main PID: 2306 (code=exited, status=1/FAILURE)

Sep 15 13:30:36 vm-web-01 systemd[1]: onetime.service: control process exited, code=exited status=1
Sep 15 13:30:36 vm-web-01 systemd[1]: Failed to start Onetime secret backend service.
Sep 15 13:30:36 vm-web-01 systemd[1]: Unit onetime.service entered failed state.
Sep 15 13:30:36 vm-web-01 systemd[1]: onetime.service failed.
Sep 15 13:30:37 vm-web-01 systemd[1]: onetime.service holdoff time over, scheduling restart.
Sep 15 13:30:37 vm-web-01 systemd[1]: start request repeated too quickly for onetime.service
Sep 15 13:30:37 vm-web-01 systemd[1]: Failed to start Onetime secret backend service.
Sep 15 13:30:37 vm-web-01 systemd[1]: Unit onetime.service entered failed state.
Sep 15 13:30:37 vm-web-01 systemd[1]: onetime.service failed.

journalctl -xe:
Sep 15 13:30:36 vm-web-01 bundle[4296]: /usr/local/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require': cannot load such file -- bundler [LoadError]
Sep 15 13:30:36 vm-web-01 bundle[4296]: from /usr/local/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
Sep 15 13:30:36 vm-web-01 bundle[4296]: from /usr/local/rvm/rubies/ruby-2.3.8/bin/bundle:10:in `'
Sep 15 13:30:36 vm-web-01 bundle[4296]: from /usr/local/bin/ruby_executable_hooks:24:in `eval'
Sep 15 13:30:36 vm-web-01 bundle[4296]: from /usr/local/bin/ruby_executable_hooks:24:in `'
Sep 15 13:30:36 vm-web-01 systemd[1]: onetime.service: control process exited, code=exited status=1
Sep 15 13:30:36 vm-web-01 systemd[1]: Failed to start Onetime secret backend service.

Answer: You should call thin directly using the wrapper that RVM has provided for you. Without this, the system may end up running the wrong ruby, which indeed appears to be what happened.
For example:
ExecStart=/usr/bin/bash /usr/local/rvm/wrappers/%i/thin start <your options>

Answer: I've googled right answer: https://mikewilliamson.wordpress.com/2015/08/26/running-a-rails-app-with-systemd-and-liking-it/
So, I have to add "/usr/bin/bash -lc" to command in ExecStart. It will be:
ExecStart = /usr/bin/bash -lc '/usr/local/rvm/rubies/ruby-2.3.8/bin/bundle exec thin -e dev -R config.ru -p 7143 -P /var/run/onetime/onetime.pid -l /var/log/onetime/onetime.log -d start'

Comment: That should also work, though it's very strange that he used `-l`. This should not be necessary and might open up a security problem in some contexts.


keras preprocessing logic

Question: Background:
In a vision application on a GCP, we are using TF serving. The application using TF Serving is written in Go. This application converts the image to Tensor and sends it to the TF serving using gRPC.
Problem:
The preprocessing logic in Golang does not work as well as it does in Python, using Keras image library (the accuracy of inference suffers). A part of the reason could be that Python libraries were used during training.
We tried,
Tensorflow serving provides a way to introduce a pre-processor that can run on the serving container. It seems to have limited functionality (can't package Keras library with the model). We tried the following two options
What works is Keras Preprocessing (Python), on the client side as follows.
img = tf.keras.preprocessing.image.load_img(file_name, target_size=(HEIGHT, WIDTH))
img_array = tf.keras.preprocessing.image.img_to_array(img)

… grpc call to TensorflowServing...
Our goal is to use "serving_input_receiver_fn" and preprocess image in the TFServing space as described in this blog post: https://medium.com/devseed/technical-walkthrough-packaging-ml-models-for-inference-with-tf-serving-2a50f73ce6f8
But the following code which is executed as "serving_input_receiver_fn" does not yield the correct inferences.
image = tf.image.decode_image(image_str_tensor, channels=CHANNELS                                       dtype=tf.uint8)
image = tf.reshape(image, [HEIGHT, WIDTH, CHANNELS])

Our goal is to run the following Keras code (in a similar way) inside ""serving_input_receiver_fn" (assuming that we can load the image from "grpc" stream).
img = tf.keras.preprocessing.image.load_img(file_name, target_size=(HEIGHT, WIDTH))
img_array = tf.keras.preprocessing.image.img_to_array(img)

Is it possible? This is a massive deployment (70 GPUs & 2300 CPUs) therefore every bit of the performance counts. In our case, the image preprocessing on TF-Serving machine is the most optimal.
Comment: This questions lacks details : what keras preprocessing functions were you using, and how did you try to reproduce them in Go ? Moreover, keras is open source : you can fetch the function code you where using and reimplement them in native TensorFlow to use with the TF Serving preprocessor.
Answer: I don't actually have an answer but maybe can point you to some resources to help. I think firstly, keras.preprocessing is supposed to be quite slow, check out https://www.tensorflow.org/tutorials/load_data/images and it recommends building pre-processing pipeline as a tf.data.Dataset pipeline

The above keras.preprocessing method is convienient, but has two
  downsides:
It's slow. See the performance section below. It lacks fine-grained
  control. It is not well integrated with the rest of TensorFlow. To
  load the files as a tf.data.Dataset

Why not include the pre-processing layer as part of the model graph itself so that it will run WITHIN tensorflow serving?

keras preprocessing logic


How to stop autosuggest in node author field and write our own?

Question: Is there anyway to stopping auto suggest in author field of node content and write our own author names instead of users??
Answer: You could write a small module that implements hook_form_alter in which you remove the autocomplete functionality for this field.  This should convert it to a textfield.  However, this will certainly break if an author name that is not also the username of a user is inserted, since this field is used to populate $node->uid, which must have a valid username.
A more viable solution would be to create a vocabulary of your author names, and a taxonomy term field on your content type (pointing at that vocabulary).  And then display this field as you desire.


Prove $\int_0^{\infty}\frac{\ln (x)}{(x^2+1)(x^3+1)}\ dx=-\frac{37}{432}\pi^2$ with real method

Question: I came across the following integral:
$$\large{\int_0^\infty \frac{\ln (x)}{(x^2+1)(x^3+1)}\ dx=-\frac{37}{432}\pi^2}$$
I know it could be solved with resuide method, and I want to know if there are some real methods can sove it?
Meanwhile,I remember a similar integral:
$$\large{\int_0^\infty \frac{1}{(x^2+1)(x^a+1)}\ dx=\frac{\pi}{4}}$$
And I want to know the following one:
$${\color{red}{\large{\int_0^\infty \frac{\ln x}{(x^2+1)(x^a+1)}\ dx = \huge{?}}}}$$
Using the Mathematica I got the follow result.

Could you suggest some ideas how to prove this?  Any hints will be appreciated.
Answer: A real-analytic technique may be to exploit
$$ I = \int_0^1 \frac{1-x^3}{(1+x^2)(1+x^3)}\log(x)\,dx $$
then expand $f(x)=\frac{1-x^3}{(1+x^2)(1+x^3)}$ as a Taylor series around $x=0$,
$$ f(x) = \sum_{n\geq 0}\left(1-x^2-2 x^3+x^4+2 x^5+x^6-2 x^7-x^8 + x^{10} \right) x^{12n} $$
and exploit
$$ \int_0^1 x^k\log(x)\,dx = -\frac{1}{(k+1)^2} $$
to convert $I$ into a combination of Dirichlet $L$-functions $L(s,\chi)$ where $s=2$ and $\chi$ is a Dirichlet character $\!\!\pmod{12}$, or a combination of trigamma functions evaluated at multiples of $\frac{1}{12}$: the reflection formula for $\psi'$ is helpful, since it gives
$$ \sum_{n\geq 0}\left(\frac{1}{(12n+1)^2}+\frac{1}{(12n+11)^2}\right) = \frac{2+\sqrt{3}}{36}\,\pi^2,$$
$$ \sum_{n\geq 0}\left(\frac{1}{(12n+3)^2}+\frac{1}{(12n+9)^2}\right)=\frac{1}{72}\,\pi^2,$$
$$ \sum_{n\geq 0}\left(\frac{1}{(12n+4)^2}+\frac{1}{(12n+8)^2}\right)=\frac{1}{108}\,\pi^2,$$
$$ \sum_{n\geq 0}\left(\frac{1}{(12n+5)^2}+\frac{1}{(12n+7)^2}\right)=\frac{2-\sqrt{3}}{36}\,\pi^2,$$
$$ \sum_{n\geq 0}\frac{1}{(12n+6)^2}=\frac{1}{288}\pi^2.$$
To deduce $I=\color{red}{-\frac{37}{432}\pi^2}$ is now just a matter of simple algebra.
Comment: nice one but still cumbersome (as my method!). i wonder if something more elegant exists (+1)
Comment: Wow, Thank you Jack D'Aurizio for your detailed answer. An excellent answer.
Answer: Preliminary Result:
$\displaystyle \frac{2}{(x^2+1)(x^3+1)} \equiv \frac{x+1}{x^2+1}-\frac{x^2+x-1}{x^3+1}$
Proof: Obvious.
Consider the parametrised integral:
$\displaystyle f(\alpha) = \int \frac{x^\alpha \, \text{d}x}{(x^2+1)(x^3+1)} = \frac{1}{2} \int \frac{x^{\alpha+1}+x^\alpha}{x^2+1}-\frac{x^{\alpha+2}+x^{\alpha+1}-x^\alpha}{x^3+1} \, \text{d}x$
For the first part, substitute $t = x^2$, and $t = x^3$ for the second part
$\displaystyle f(\alpha) = \frac{1}{4} \int_0^\infty \frac{t^{\frac{\alpha}{2}}+t^\frac{\alpha-1}{2}}{1+t} \text{d}t +\frac{1}{6}\int_0^\infty \frac{t^{\frac{\alpha}{3}}+t^{\frac{\alpha-1}{3}}-t^{\frac{\alpha-2}{3}}}{1+t} \text{d}t$
Use the Integral Representations of the Beta Function to obtain:
$\displaystyle f(\alpha) = \frac{\text{B}(1+\frac{\alpha}{2},-\frac{\alpha}{2})+\text{B}(\frac{1+\alpha}{2},\frac{1-\alpha}{2})}{4} - \
\frac{\text{B}(1+\frac{\alpha}{3},-\frac{\alpha}{3})+\text{B}(\frac{2+\alpha}{3},\frac{1-\alpha}{3})-\text{B}(\frac{1+\alpha}{3},\frac{2-\alpha}{3})}{6}$
$\displaystyle \frac{f(\alpha)}{\pi} = \frac{\csc{\left(\pi+\frac{\pi \alpha}{2} \right)}+\csc{\left(\frac{\pi}{2}+\frac{\pi \alpha}{2}\right)}}{4}-\frac{\csc{\left( \pi + \frac{\pi \alpha}{3} \right)}+\csc{\left(\frac{2\pi}{3} +\frac{\pi \alpha}{3}\right)}-\csc{\left( \frac{\pi}{3} + \frac{\pi \alpha}{3}\right)}}{6}$
$\displaystyle \frac{12f(\alpha)}{\pi} = 3\sec{\frac{\pi \alpha}{2}} -3\csc{\frac{\pi \alpha}{2}}+2\csc{\frac{\pi \alpha}{3}}+2\csc{\left( \frac{2\pi}{3}+\frac{\pi \alpha}{3}\right)}-2\csc{\left(\frac{\pi}{3}+\frac{\pi \alpha}{3}\right)}$
Differentiate both sides with respect to $\alpha$ and evaluate at $0$ to obtain the integral you want.
Comment: A very clear and straightforward solution.
Comment: @Jack Lam  Thank you Jack Lam for your excellent answer, I like your answer very much!
Comment: Nice answer (+1). i wanted to do the same but was too lazy to write a second answer
Answer: Let's define the branch of $\log$ to lie on the posive real axis. We consider the complex valued function
$$
f(z)=\frac{\log(z)^2}{(z^2+1)(z^3+1)}
$$
we integrate this function around a keyhole contour in the complex plane with slit at the positive real axis. The contributions from the big circle will vanish out because $f(|z|)\sim \log(|z|)/|z|^5$ as $|z|\rightarrow \infty$ so we are left with
$$
\oint f(z)=\int_0^{\infty}\frac{\log(x)^2}{(x^2+1)(x^3+1)}-\int_0^{\infty}\frac{(\log(x)+2 i \pi)^2}{(x^2+1)(x^3+1)}=2\pi i\sum_i\text{Res}(f(z),z=z_i)
$$
where are the roots of the denominator of $f(z)$: $z_0=-1,z_{2/3}=\pm i,z_{4,5}=e^{\pm i2 \pi/3}$. We can rewrite this as
$$
\int_0^{\infty}\frac{\log(x)}{(x^2+1)(x^3+1)}=\sum_i\text{Res}(f(z),z=z_i)-2\pi i\int_0^{\infty}\frac{1}{(x^2+1)(x^3+1)}
$$
The remaining integral can be evaluated either by cumbersome partial fraction decomposition or by considering
$$
g(z)=\frac{\log(z)}{(z^2+1)(z^3+1)}
$$
integrated around the same contour then above.
I leave the details to you but from now on (also the calculation of residues if one keep in mind $\log(i)=\frac{i\pi}{2},\log(i)=\frac{3i\pi}{2}$ for this choice of branchcut) so i leave the details to you...
As an alternative the remaining integral might be ignored because it will yield a purely imaginary contribution and we can write (the lhs is purely real)
$$
\int_0^{\infty}\frac{\log(x)}{(x^2+1)(x^3+1)}=\Re\left[\sum_i\text{Res}(f(z),z=z_i)\right]
$$

This method will work for
$$
\int_0^{\infty}\frac{\log(z)^2}{(z^2+1)(z^n+1)}dz
$$
as long $n$ is a natural number
Comment: @Jack D'Aurizio this question is tagged as "residue calculus " soi have no remorse :D. Thx anyway!
Comment: (+1) It is a perfectly sound method, but not a real method :D
Comment: @tired A very nice answer. For the integral of $\ln x$,the residue method always to be effective. And I'm sorry for tagging as "residue calculus".
Comment: @Downvoter...have you cared to read the comments under my answer?
Comment: @ tired Ok,I will do it now.
Comment: +1 as it's tagged as residue so it's a good answer
Answer: Here is a variant of @tired's solution. In this solution, you are only required to know:

How to expand a rational function into partial fraction decomposition,
How to compute complex logarithm, and
The following claim:

Claim. For any $z \in \Bbb{C}\setminus(-\infty, 0]$ we have
  $$ I(z) := \int_{0}^{\infty} \left( \frac{\log x}{x+z} - \frac{\log x}{x+1} \right) \, dx = -\frac{1}{2}\log^2 z \tag{1}$$
  where $\log$ is the principal value of the complex logarithm.

Computation. Before proving the claim, let us see how $\text{(1)}$ allows us to compute the integral in question. Using the partial fraction decomposition, we get
\begin{align*}
\frac{1}{(1+x^2)(1+x^3)}
&= \frac{1-i}{4} \cdot\frac{1}{x-i} + \frac{1+i}{4}\cdot\frac{1}{x+i} \\
&\qquad \qquad + \frac{1}{6}\cdot \frac{1}{x+1} - \frac{1}{3}\cdot \frac{1}{x - e^{\pi i/3}} - \frac{1}{3}\cdot \frac{1}{x - e^{-\pi i/3}}.
\end{align*}
(Obviously this is a disguise of @tired's complex-analytic solution, since this decomposition often comes from residue computation. On the other hand, residue is no longer a necessity and thus one can work purely with algebra.)
Also notice that the sum of 'coefficients' are zero: $ \frac{1-i}{4} + \frac{1+i}{4} + \frac{1}{6} - \frac{1}{3} - \frac{1}{3} = 0$. Therefore it follows from the claim that
\begin{align*}
\int_{0}^{\infty} \frac{\log x}{(1+x^2)(1+x^3)} \, dx
&= \frac{1-i}{4} I(-i) + \frac{1+i}{4}I(i)\\
&\qquad \qquad + \frac{1}{6}I(1) - \frac{1}{3}I(-e^{\pi i/3}) - \frac{1}{3}I(-e^{-\pi i/3}) \\
&= -\frac{1}{2} \bigg[ \frac{1-i}{4} \left( -\frac{i\pi}{2} \right)^2 + \frac{1+i}{4}I\left( \frac{i\pi}{2} \right)^2 \\
&\qquad \qquad + 0 - \frac{1}{3}\left( -\frac{2i\pi}{3} \right)^2 - \frac{1}{3}\left( \frac{2i\pi}{3} \right)^2 \bigg] \\
&= -\frac{37}{432}\pi^2.
\end{align*}

Proof of Claim. Now it remains to compute the integral $\text{(1)}$ This is easily done by differentiating $I(z)$:
$$ I'(z) = - \int_{0}^{\infty} \frac{\log x}{(x+z)^2} \, dx. $$
In order to compute this integral, we first replace the lower limit by $\epsilon > 0$ to obtain
$$ - \int_{\epsilon}^{\infty} \frac{\log x}{(x+z)^2} \, dx = \frac{\epsilon \log \epsilon}{z(z+\epsilon)} - \frac{1}{z}\log (z+\epsilon). $$
Taking limit as $\epsilon \to 0^+$, we get
$$ I'(z) = -\frac{1}{z}\log z, \qquad I(1) = 0. $$
This is enough to prove the claim. ////
Comment: Thank you very much for your excellent answer.


$a,b,n \in \mathbb Z$. Find the smallest value of $n$ such that $b\mod n = a$

Question: Let $a,b,n \in \mathbb Z$. Find the smallest value of $n$ such that $b\mod n = a$ where $a,b$ are known values and $b > a$.
What's the most efficient way to solve such a problem? The naive approach would be choose values of $n$ and increment up until the smallest $n$ is found.
Comment: Does it allow negative $n$?
Comment: @mvw all positive numbers
Comment: How would it work for $a=4, b=6$?
Comment: @Arthur That case doesn't work I suppose.
Comment: How is your $\bmod$ defined?
Comment: @mvw $\frac{b}{n}$ gives remainder $a$
Answer: "$b\ mod\ n\ =a$" means $\ b\equiv a\mod n\ $ , so we have $\ n|b-a\ $, thus the smallest positive value of $\ n\ $ is just the smallest prime factor of $\ b-a\ $, if we assume $n>1$. If $\ b-a=1\ $, the only solution is $n=1$, if we allow it.
In the case $n$ must be greater than $a$ :
If there is a divisor of $\ b-a\ $ which is greater than $a$, then the smallest of the divisors greater than $a$ is the optimal solution, but in this case, we do not always have a solution at all. For example $b=19$ , $a=16$.
Comment: Thanks for your answer, Peter. As an example, let $b=277,a=5$. Then $b-a=272$ with smallest prime factor of 2, but 2 doesn't satisfy the equation. $8$ is the smallest value of $n$ in this case. Am I misunderstanding your answer?
Comment: @WHY I edited the answer


printing alphabets using star pattern side by side in C

Question: I am trying to print the initials of My First Name "S S" using * pattern in C. However the patterns are printed one after the other. Is there any way to print the alphabets using * pattern one at the side of the other with a little space in between. I do not want to allot a very big box for both the alphabets. I want to code for individual alphabets and put them side by side with some space in between. My Code and out our is given below:
int k,l,i,j;
for(k=1;k<=7;k++){
    for(l=1;l<=4;l++){
        if(k==1 && l<=4){
            printf("*");
        }
        else if(k>=2 && k<=3 && l==1){
            printf("*");
        }
        else if(k==4 && l<=4){
            printf("*");
        }
        else if(k>=5 && k<=6 && l==4){
            printf("*");
        }
        else if(k==7 && l<=4){
            printf("*");
        }
        else{
            printf(" ");
        }
    }
    printf("\n");
}
for(i=1;i<=7;i++){
    for(j=1;j<=4;j++){
        if(i==1 && j<=4){
            printf("*");
        }
        else if(i>=2 && i<=3 && j==1){
            printf("*");
        }
        else if(i==4 && j<=4){
            printf("*");
        }
        else if(i>=5 && i<=6 && j==4){
            printf("*");
        }
        else if(i==7 && j<=4){
            printf("*");
        }
        else{
            printf(" ");
        }
    }
    printf("\n");
}
return 0;
}

Output:
****
*
*
****
   *
   *
****
****
*
*
****
   *
   *
****

However, I want my expected output to be:
****      ****
*         *
*         *
****      ****
   *         *
   *         *
****      ****

Comment: Will you accept any answer that has reasonably simple code and prints the expected output?
Comment: Please don't use screenshots when code-formatted text would do.  abelenky already edited your quesiton to be readable and then you messed it up.  I think you should revert to revision 2.
Comment: With just very basic coding I want to code for individual alphabets in * patter and put them side by side with white space in between I don't want to allot a very big box instead small codes for each alphabets and printing them side by side. Thank You!
Comment: sorry I am new to this site, while manually pasted the output the site was showing some dots instead of the actual pattern I thought it would create some confusion so I edited the same
Comment: You can select your star patterns and click the "Code Sample" button to format them properly.  This adds 4 spaces at the beginning of each line so that it will be formatted as code.  Even though it's not technically code, this will make the output be legible.  Use the preview to make sure your question looks good before posting.
Comment: Don't add images when text can be used instead.
Comment: I guess now the output is perfectly understandable.Kindly help me how can I code for Individual alphabets with * pattern and put them side by side with white space without occupying and allowing a very big box and having code for each alphabet.
Comment: If you want to write your name say with `NxN` matrix of stars, then prepare a matrix for each letter. Then write them to show up side by side.
Answer: The most important thing when approaching problems like this is to decompose your code in smaller pieces, using functions and/or typedefs or structs to organize things.  In your case, you can easily separate the "knowledge" of how to print stars and spaces for your letters from the main code (which knows which letters to print in which order) using functions.  Refactoring you code that way, we get:
void S(int k, int l) {
   if(k==1 && l<=4){
        printf("*");
    }
    else if(k>=2 && k<=3 && l==1){
        printf("*");
    }
    else if(k==4 && l<=4){
        printf("*");
    }
    else if(k>=5 && k<=6 && l==4){
        printf("*");
    }
    else if(k==7 && l<=4){
        printf("*");
    }
    else{
        printf(" ");
    }
}

int main() {
    int k,l,i,j;
    for(k=1;k<=7;k++){
        for(l=1;l<=4;l++){
            S(k, l);
        }
        printf("\n");
    }
    for(i=1;i<=7;i++){
        for(j=1;j<=4;j++){
            S(i, j);
        }
        printf("\n");
    }
    return 0;
}

Now you can easily rewrite main to print the letters side by side
int main() {
    int k,l,i,j;
    for(k=1;k<=7;k++){
        for(l=1;l<=4;l++){
            S(k, l);
        }
        printf(" ");
        for(j=1;j<=4;j++){
            S(k, j);
        }
        printf("\n");
    }
    return 0;
}

You could also extend this by writing different letters in different patterns (though having a function for each letter is somewhat verbose -- better would be to store the pixels for all letters in a data structure and print it that way)
Comment: Thank You Very Much! However am a beginner in C so I know up to loops and condition statements so I still don't properly get it, so I wanted the same output with just basic coding but anyways Thank You very Much!
Comment: IMO you should probably learn about functions before you learn about loops and conditionals, as they are more fundamental.
Answer: Use pattern matrix for every character you want to print. It'll make printing easier. You run through each letter of the string to print for every row in the pattern.
#include <stdio.h>
#include <string.h>

#define ROWMAX 7
#define COLMAX 5
#define CSPACE 1
#define PATTERN '#'

char cCube [26][ROWMAX][COLMAX] = {
    {   {0, 1, 1, 1, 1}, // letter S
        {1, 1, 0, 0, 1},
        {1, 1, 0, 0, 0},
        {0, 1, 1, 1, 0},
        {0, 0, 0, 1, 1},
        {1, 0, 0, 1, 1},
        {1, 1, 1, 1, 0}
    },
    {   {0, 1, 1, 1, 0}, // letter O
        {1, 1, 0, 1, 1},
        {1, 0, 0, 0, 1},
        {1, 0, 0, 0, 1},
        {1, 0, 0, 0, 1},
        {1, 1, 0, 1, 1},
        {0, 1, 1, 1, 0}
    },
    {   {1, 1, 1, 1, 0}, // letter D
        {1, 0, 0, 1, 1},
        {1, 0, 0, 0, 1},
        {1, 0, 0, 0, 1},
        {1, 0, 0, 0, 1},
        {1, 0, 0, 1, 1},
        {1, 1, 1, 1, 0}
    }, //so on for alphabets you want to use
};

int chIndex [256] = {0};

void print_pat_msg (const char* msg) {
    int mlen = strlen (msg);
    for (int ri = 0; ri < ROWMAX; ++ri) {
        for (int mi = 0; mi < mlen; ++mi) {
            int chi = chIndex[ (unsigned char) msg[mi]];
            for (int ci = 0; ci < COLMAX; ++ci)
                (cCube[chi][ri][ci]) ? putchar (PATTERN) : putchar (' ');
            for (int spi = 0; spi++ < CSPACE;) putchar (' ');
        }
        putchar ('\n');
    }
    printf ("\n");
}

int main () {
    // if patterns are indexed alphabetically below initialisation can be omitted
    chIndex[ (unsigned char) 'S'] = 0;
    chIndex[ (unsigned char) 'O'] = 1;
    chIndex[ (unsigned char) 'D'] = 2;

    char message [] = "ODDS";
    print_pat_msg (message);
    return 0;
}

This way you can design/customise the pattern for each letter with ease at one place. Code & pattern can be reused for other messages & names.
Printing here works somewhat like a dot-matrix printer, striping across putting out pattern-line of each letter in the string one at a time.
You can also replace 0/1 flags with pretty much any character to draw ASCII images. You just have to adjust the pattern array, which is easy to follow & change at will.
Come to think of it, this is how fonts work at pixel level, patterns.
Comment: Some elaboration on why the OP would want to use patterns set up this way would improve this answer.
Comment: Perhaps something about how having it stored in lines means you can print lines of multiple letters "in parallel."
Answer: My quickie solution:
#include <stdio.h>

static const unsigned char S[] = {0xF0, 0x80, 0x80, 0xF0, 0x10, 0x10, 0xF0};

int main(void) {

    for(int i=0; i<sizeof(S); ++i)
    {
        for(int b=7;b; --b)
        {
            printf("%c", "* "[!(S[i] & (1<<b))]);
        }
        for(int b=7;b; --b)
        {
            printf("%c", "* "[!(S[i] & (1<<b))]);
        }
        printf("\n");
    }
    return 0;
}

Output:
Success #stdin #stdout 0s 5548KB
****   ****
*      *
*      *
****   ****
   *      *
   *      *
****   ****

Comment: Thanks a Lot! However am a beginner so I know up to loops and condition statement so I couldn't get it clearly anyways thank you very much
Comment: Some explanation would greatly improve this answer.


Why is Erik Satie's Saraband 1 in A flat major?

Question: Why is Erik Satie's Saraband 1 in A flat major?
There are so many F, C, and G flat accidentals through out the score it seem like it could have been notated in G sharp minor (enharmonic of A flat minor) with the tonic G sharp minor altered to be major at the beginning and end.
I get that altering the tonic chord would sort of contradict the key signature, but wouldn't the majority of the score then be much easier to read?
Maybe this is a sick joke from Satie, but his other scores don't seem to play musical enharomnic spelling jokes. His sense of humor came out in other ways.
https://imslp.org/wiki/3_Sarabandes_(Satie%2C_Erik)
Comment: Is there a source that clarifies A-flat *major*? IMSLP surprisingly has F minor listed (!).
Comment: Oh, I see that at IMSLP now. But, I'm saying A flat *major* because of 4 flats signature and the start/end chords are A flat major seven chords.
Comment: Wikipedia agrees with me ;-) https://en.wikipedia.org/wiki/Sarabandes#Music
Answer: Because it is "a sick joke" about enharmonic spelling.  For a more flagrant example, see Satie's Vexations.
Comment: Yes.  The Peters edition of the W.T.C. even inflicts this on the C# pieces, renotating them in D flat at the back of the volume.
Comment: If that is indeed the case, and if I made my own arrangement in `G#` minor, do you think it would be easier to read? I really would like to play this, but want something readable! Satie, why are you so cruel?!? :-)


Is this version of null hypothesis definition wrong?

Question: Would it wrong to say that the definition of null hypothesis is as follows:
Null hypothesis is a statistical hypothesis that usually asserts that nothing special is happening with respect characteristic of the population.
Someone mentioned that this definition will not hold in some cases. Is it true that the above mentioned definition is incorrect is some cases? If so, can you mention a case where it would fail.
Comment: This is all very ambiguous, can you give concrete examples/references/quotes?
Comment: Being pedantic about the English, if the definition says that something "usually" holds, then it is completely acceptable that there are some exceptions. It's usually true that a high school basketball player won't play professional basketball. Alas, there are players in the NBA.
Comment: "Nothing special is happening" might be useful for suggesting the intended meaning, but it certainly is no definition.  When you think about it, it's hard to find anything objective in it whatsoever.  Indeed, what does it even mean?  In a statistical test or popularion, to what does "happening" refer and how do you characterize or quantify "special" (which sounds completely subjective and arbitrary)?
Answer: Definitions are not just characterised or judged by their correctness/accuracy. They need to be as precise as possible to be maximally useful. The problem with your definition is that it is vague in multiple respects, and arguably self-contradictory. 'usually asserts' and 'nothing special' are ambiguous and imprecise. Even worse, usually implies exceptions, which essentially undermines the whole definition - are there null hypotheses that this does not apply to? What characterises/defines those? And 'happening' is both ambiguous and irrelevant to many possible applications of the term.
It can be helpful for our own understanding to come up with loose explanations of terms in simple language that we can grapple with. But this is a step towards deeper understanding, and  we should not mistake it for a rigorous definition.
As a mild caveat to what I wrote above, many fields do use definitions (or 'working definitions') that do have exceptions. Biology famously still doesn't have an unambiguous and universally applicable definition of what a 'species' is. But that's in large part because a 'species' is a construct that maps only loosely onto reality. It is an attempt to put hard boundaries on reality when reality itself is more porous (as the phenomenon of fertile hybrids of different species shows). This looseness is much less justifiable when dealing with mathematical (and most statistical) constructs. Where greater precision is possible, we should aim for it.


Why doesn't text.replace("old", "new") change the text variable?

Question: I am just learning python and wanted to create a little program which changes words in a string.
But for some reason it doesn't work how i intended.
here is the code i try to run.
<code>#setting text as variable
text= "hi my name is john"

#replacing the names
text.replace ("john", "peter")

#printing the new string
print (text)
</code>
for my understanding of the function replace () shouldn't it replace john with peter?
or what is my mistake?
thanks in advance
Comment: `replace` doesn't change the object you pass into it but returns a new string with the replaced substring
Comment: the original string is not modified, use `text=text.replace("john", "peter")`
Answer: the replace function returns a new string object and is not assigned to the text variable. use:
<code>#setting text as variable
text= "hi my name is john"

#replacing the names
text = text.replace ("john", "peter")

#printing the new string
print (text)
</code>
Comment: In [How to Answer](https://stackoverflow.com/help/how-to-answer), see the section *Answer Well-Asked Questions*, and therein the bullet point regarding questions that "have been asked and answered many times before".
Answer: String is immutable,so you must create new string variable
<code>text_2=text.replace("john","peter")
Print(text_2)

</code>


Rolling four dice and the difference between predictions

Question: Four standard dice are rolled.
What are the chances of:
1.) Rolling three sixes and one five?
2.) Two sixes and two fives?
3.) Exactly one six?
4.) Four different numbers?
Here is my thought process for them, please help me develop an intuition for these sort of questions and/or correct me:
1.) Is it safe to assume that on the first dice I roll and get a five. The probability of that is $\frac{1}{6}$, and then the probability of rolling three sixes is $\frac{1}{6^3} $, with the final probability being $\frac{1}{6^4}$.
2.) Again... I'm not sure I'm doing this correctly. Wouldn't it be the same as 1?
3.)Exactly one six would be $\frac{1}{6}*\frac{5^3}{6^3}$
4.) Four different numbers would be $\frac{6}{6}*\frac{5}{6}*\frac{4}{6}*\frac{3}{6}$
Comment: https://en.wikipedia.org/wiki/Combination (you got the last one right)
Answer: There are $6^4=1296$ different outcomes.

Rolling $3$ sixes and $1$ five

There are $\frac{(3+1)!}{3!\cdot1!}=4$ ways to do it, hence the probability is $\frac{4}{1296}$

Rolling $2$ sixes and $2$ fives

There are $\frac{(2+2)!}{2!\cdot2!}=6$ ways to do it, hence the probability is $\frac{6}{1296}$

Rolling exactly $1$ six

There are $\binom41\cdot(6-1)^{4-1}=500$ ways to do it, hence the probability is $\frac{500}{1296}$

Rolling $4$ different numbers

There are $\binom64\cdot4!=360$ ways to do it, hence the probability is $\frac{360}{1296}$
Comment: @RonaldB  **Second one** $\frac{(2+2)!}{2!~2!}$ counts the ways select dice to show the two sixes and two fives. It is $\binom{4}{2}$. **Third one:** There are $\binom 4 1$ dice that could show the six, and $(6-1)^{4-1}$ ways the other dice could show not-six.  **Fourth one:** There are $\binom{6}{4}$ ways to have four distinct numbers to show, and there are $4!$ ways these could be shown on the dice.
Comment: Thank you for the response! Any chance you could explane the second and third one?
Answer:
1.) Is it safe to assume that on the first dice I roll and get a five. The probability of that is $\frac{1}{6}$, and then the probability of rolling three sixes is $\frac{1}{6^3} $, with the final probability being $\frac{1}{6^4}$.

Sure, but don't ignore the other ways to roll 1 five and 3 sixes. The five could be rolled on the first, second, third, or fourth die, and the sixes on the remaining three.
$$\frac 4{6^4}$$

2.) Again... I'm not sure I'm doing this correctly. Wouldn't it be the same as 1?

Yes, but this time you have to count ways that two dice can show the fives.   There are $^4\mathrm C_2$ ways that could happen.
$$\frac {6}{6^4}$$

3.)Exactly one six would be $\frac{1}{6}*\frac{5^3}{6^3}$

Again, that is for the six in a particular die.   To account for the fact that it could be any of the four, multiply.
$$\frac{4\cdot 5^3}{6^4}$$

4.) Four different numbers would be $\frac{6}{6}*\frac{5}{6}*\frac{4}{6}*\frac{3}{6}$

Indeed.  $\frac{^6\mathrm P_4} {6^4}$


Kiselev's geometry Problem 67: In an isosceles triangle, two medians/bisectors/altitudes are congruent

Question: Problem 67 from Kiselev's Geometry,

Prove that in an isosceles triangle, two medians are congruent, two angle bisectors are congruent, two altitudes are congruent.

Here is the content page in the book. The problem belongs to Chapter 1.5.
The theorems covered in chapter 1.5 are,

(i) In an isosceles triangle, the bisector of the angle at the vertex is at the same time the median and the altitude.
(ii) In an isosceles triangle, the angles at the base are congruent.
(iii) In an isosceles triangle, the bisector of the angle at the vertex is an axis of symmetry of the triangle.

I have understood the proof for these theorems and I have tried to use these theorems and others mentioned in previous chapters to prove the theorem in problem 67, but I can't prove it.
Please help. Also, please avoid using theorems that are covered in the later part of the book.   :)
Comment: Are you talking about angle bisectors ??
Comment: Have you tried similarity ??
Comment: Okay, I have done it with the help of similarity on triangles.
Comment: In each case, you need to prove triangles congruent, then use the fact that corresponding parts of congruent triangles are congruent to draw the desired conclusion.
Comment: The congruency tests are what I had in mind.  I am not familiar with the book, so I do not know what results you are allowed to use.
Comment: I don't think mere definitions can provide such results. Does that book have any solution ??
Comment: @N.F.Taussig I have uploaded the content page of the book. The problem is from chapter 1.5
Answer: First thing to do is make a picture.

We need to prove each of these separately.
In all three cases, though the proof will be based on the idea that $\triangle APB \cong \triangle AQC$
We can prove one by SAS
One by ASA
While we cannot generally prove congruence by AAS, we can when they are right triangles.
Comment: Seems like we have to use the idea of congruent triangles. It's a little weird to me because the author presented the chapter on congruence triangles after this set of problems. =/
Comment: I have managed to prove that line segments $AP$ and $BQ$ are congruent. But it was first assumed that the three sides of the triangle are congruent. I cannot have this assumption to prove the theorem for triangles that have exactly two congruent sides.
Comment: @yh05 is that better.
Comment: You could make an argument based on the axis of symmetry.  But I think that is higher level thinking than the congruent triangle arguments.
Answer: This problem comes before the theorems on triangle congruence are introduced. An earlier commenter says, "you could make an argument based on the axis of symmetry", and in fact this is exactly what Kiselev intends: half the chapter is devoted to proving various properties of isosceles triangles, and the other half is devoted to explaining the concept of 'axial symmetry' and showing that (in Kiselev's words):

in an isosceles triangle, the bisector of the angle at the vertex is
an axis of symmetry of the triangle.

Following this, Kiselev remarks:

Two symmetric figures can be superimposed by rotating one of them in
space about the axis of symmetry until the rotated figure falls into
the original plane again.

Remembering that congruence is defined in terms of superposition, it is easy to understand the proofs Kiselev was trying to lead his reader towards:  By rotating an isosceles triangle around its axis of symmetry, we carry one median onto another (because the sides are congruent), one angle bisector onto another (because the base angles are congruent), and one altitude onto another (because the perpendicular drawn from a point to a line is unique (§24)).


How to inject Class as bean?

Question: I have the following class UserAuthorityRepository as repository:
@Repository
public class UserAuthorityRepository extends BaseRepository<UserAuthority, Long> implements IUserAuthorityRepository {

public UserAuthorityRepository(Class<UserAuthority> domainClass, EntityManager em) {
  super(domainClass, em);
}

}

And in UserAuthorityService I have:
@Service
public class UserAuthorityService extends BaseService<UserAuthority, Long> implements IUserAuthorityService {

private static final Logger LOGGER = LoggerFactory.getLogger(UserAuthorityService.class);

@Autowired
private IUserAuthorityRepository userAuthorityRepo;

public UserAuthorityService() {
  super();
  LOGGER.info("UserAuthorityService Has Been Created");
}

@Bean
@Override
public Class<UserAuthority> getDomain() {
  return UserAuthority.class;
}

@Override
public IBaseRepository<UserAuthority, Long> getRepository() {
  return userAuthorityRepo;
}

}

But my application gets exception at startup as follow:
***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in com.bia2hd.dao.impl.UserAuthorityRepository required a bean of type 'java.lang.Class' that could not be found.

Action:

Consider defining a bean of type 'java.lang.Class' in your configuration.

Comment: Possible duplicate of [How to set Class value to spring bean property?](http://stackoverflow.com/questions/5834311/how-to-set-class-value-to-spring-bean-property)
Comment: @JoeC Thanks, But I have no xml configuration, it's all annotations.
Comment: So potentially silly question here... but why do you need to inject a `Class` in this context?  The only legal value for your constructor argument is `UserAuthority.class`, so why not set that explicitly in your superconstructor call instead of depending on it getting injected (and then only the `EntityManager` needs to be injected)?
Comment: Despite of what you think about whole silly question here, the problem is more complicated. there is dozen of repositories whit such situation.
Comment: Please see my other post
Answer: I just solved it(not very pleasing, but working).
@Configuration
public class Beans {

   @Autowired
   private ApplicationContext applicationContext;

   @PostConstruct
   public void createClassBeans() throws ClassNotFoundException {

      ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);

      scanner.addIncludeFilter(new AnnotationTypeFilter(Entity.class));

      ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext) applicationContext)
            .getBeanFactory();

      for (BeanDefinition bd : scanner.findCandidateComponents("my.package")) {
         Class<?> bean = Class.forName(bd.getBeanClassName());
         beanFactory.registerSingleton(bean.getName(), bean);
      }

   }

}

And
@Repository
public class UserRepository extends BaseRepository<User, Long> implements IUserRepository {

   UserRepository(@Qualifier("my.package.User") Class<User> domainClass, EntityManager em) {
      super(domainClass, em);
   }

}

Answer: Have you tried using @Configuration?
@Configuration
public class InjectConfiguration {

    @Bean("providerEmployeeContext")
    @RequestScope
    public IEmployeeContext<Employee> providerEmployeeConfiguration() {

        return new EmployeeContext<>(sessionFactory(), Employee.class);
    }

}

How to inject Class as bean?


Pygame functions having two brackets

Question: Why does pygame.dispay.set_mode(()) and other similar functions has two braces instead of one and why it isnt working if i just put only one brace?
Comment: This function takes a tuple as an argument and the second pair of parens enclose the tuple values. If you remove parens then it's two separate values when a method is expecting only one tuple object.
Comment: You should give details for "Isn't working".
Answer:
This function takes a tuple as an argument and the second pair of parens enclose the tuple values. – pavel

So when you add two brackets, you are passing a tuple
Answer: The display mode gets a tuple with two items to describe the resolution for the render-screen. And a tuple will be defined by
pygame.dispay.set_mode(size=(640, 280))

When using the default you just use the empty tuple definition
pygame.dispay.set_mode(size=(0, 0))

I have found this here PyGame Documentation

Pygame functions having two brackets


What is the proper way to back up ISC DHCPd lease files?

Question: According to this answer, DHCPd lease files are cleared every hour. The goal is to back up the leases file continuously, so there is never a lease lost. This is made difficult since it is unclear whether the hour timer is based on system time (eg the file is rewritten at 1am, 2am, 3am etc) or process time (service_start + 1h, service_start + 2h, etc). Say the leases file is cleared at exactly 3am, and a lease is granted at 2:58:55; the service that backs up the lease file would need to run, quickly, before the file is cleaned.
The DHCPd process makes its own backup of the file to /var/lib/dhcpd/dhcpd.leases~. The best bet then seems to be to make a script that backs up this file to another location every hour. But if the DHCPd process is restarted and the timer is relative to the process, it would be possible for the hour mark on the backup tasks to align, which might end in one process reading while the other writes, and that could mangle the file (depending on how it's done). So the backup task would need some knowledge of when DHCPd starts. This is getting complicated.
What is the 'correct' way to back up the DHCPd leases file, so no leases are lost?
Comment: Just my thought from reading this: Event-based (eg inotify) triggered on the new `dhcpd.leases~` being closed?
Answer: From DHCP sources:

      if (snprintf (backfname, sizeof backfname, "%s~", path_dhcpd_db)            >= sizeof backfname)

[...]

      if (unlink (backfname) < 0 && errno != ENOENT) {

[...]

      if (link(path_dhcpd_db, backfname) < 0) {

The previous backup file is deleted, then the current lease file is hardlinked as backup with a trailing ~.
On Linux, with the inotify(7) event facility, a hardlink is seen as a creation event.
I would suggest to use inotifywait (from inotify-tools package) to signal when such event happened. One should expect the apparition of /var/lib/dhcpd/dhcpd.leases~ which is then directly ready for backup (it's a hardlink to the original). As the file will be a different file (different inode) each time, it's the directory that should be watched for proper detection, and for example the --include option can be used to simplify shell processing (no processing, even the read line is discarded in a dummy variable):
inotifywait -m -e create --include dhcpd.leases~ /var/lib/dhcpd | while read dummy; do
    do_backup /var/lib/dhcpd/dhcpd.leases~
done

If the command is not recent enough, it might not understand --include in such case, the test has to be done in the event loop:
inotifywait -m -e create /var/lib/dhcpd | while read -r dir event filename; do
    if [ "$filename" = dhcpd.leases~ ]; then
        do_backup /var/lib/dhcpd/dhcpd.leases~
    fi
done

Alternatively, the incron package (available at least on CentOS 8 Stream), could be used with an entry similar to:
/var/lib/dhcpd IN_CREATE,recursive=false if_correct_file_do_backup $#

with if_correct_file_do_backup being for example a shell checking this was the intended filename:
#!/bin/sh

if [ "$1" = dhcpd.leases~ ]; then
    do_backup /var/lib/dhcpd/dhcpd.leases~
fi


Connection refused on remote (sles) server port, even though inside that server port shows as open

Question: When trying to connect to port 7077 to a spark cluster via pyspark in Python, I get Connection refused Error.
Running nmap server_ip from my local machine (Ubuntu 20.04) shows 4 open ports (80, 8080, 22, 9000)
Running nc -zv server_ip 7077 gives the output:
nc: connect to server_ip port 7077 (tcp) failed: Connection refused

Then I ssh to the sles server (have to be connected to a VPN) and run the following command:
ss -tulw. The command gives this output for port 7077:
Netid  State      Recv-Q Send-Q Local Address:Port                 Peer Address:Port
tcp    LISTEN     0      128     *:7077                            *:*

If I understand it correctly, this means the port 7077 is open for any address.
Why am I then getting a Connection refused Error?
There is no firewall for the port 7077 in the VPN Connection.
Edit:
Output from iptables -L:
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:7077
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:7077

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination
DOCKER-USER  all  --  anywhere             anywhere
DOCKER-INGRESS  all  --  anywhere             anywhere
DOCKER-ISOLATION-STAGE-1  all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere             ctstate RELATED,ESTABLISHED
DOCKER     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere             ctstate RELATED,ESTABLISHED
DOCKER     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere
DROP       all  --  anywhere             anywhere

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Chain DOCKER (2 references)
target     prot opt source               destination
ACCEPT     tcp  --  anywhere             another_ip           tcp dpt:9870
ACCEPT     tcp  --  anywhere             another_ip           tcp dpt:cslistener
ACCEPT     tcp  --  anywhere             another_ip           tcp dpt:7077

Chain DOCKER-INGRESS (1 references)
target     prot opt source               destination
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:http-alt
ACCEPT     tcp  --  anywhere             anywhere             state RELATED,ESTABLISHED tcp spt:http-alt
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:http
ACCEPT     tcp  --  anywhere             anywhere             state RELATED,ESTABLISHED tcp spt:http
RETURN     all  --  anywhere             anywhere

Chain DOCKER-ISOLATION-STAGE-1 (1 references)
target     prot opt source               destination
DOCKER-ISOLATION-STAGE-2  all  --  anywhere             anywhere
DOCKER-ISOLATION-STAGE-2  all  --  anywhere             anywhere
RETURN     all  --  anywhere             anywhere

Chain DOCKER-ISOLATION-STAGE-2 (2 references)
target     prot opt source               destination
DROP       all  --  anywhere             anywhere
DROP       all  --  anywhere             anywhere
RETURN     all  --  anywhere             anywhere

Chain DOCKER-USER (1 references)
target     prot opt source               destination
RETURN     all  --  anywhere             anywhere

Comment: Ok, the input rules were not needed (default policy is to ACCEPT), but it looks like you are running docker on that machine and that's heavily messing with your routing; however this should not be a problem if your are trying to connect to the server itself...
Comment: What is the server's IP?
Comment: @Massimo are you asking what's the `server_ip`? I don't understand why that matters
Comment: Because you have an iptables rule forwarding TCP port 7077 to IP address 172.18.0.4, and I'd like to understand what that is and if it can conflict with the same port listening on the server itself.
Comment: Your networking seem to be a lot more complex than expected, due to Docker being involved.
Comment: @Massimo ah, the server ip is different from that one. The spark master I am trying to connect is located in the `server_ip` itself. However, there are different spark workers in different servers. The `server_ip` only has one worker.
Comment: Is it possible that your server (whatever you have listening on TCP port 7077) is actively refusing connections from your machine? You said you get a "connection refused" error, while a firewall or routing issue would most likely result in a timeout due to the connection not being answered at all.
Comment: @Massimo but the server listening on TCP port 7077 is the one I output the `iptables -L` of, so `server_ip`. According to that information, it is listening to that port. Or am I confusing your question?
Comment: I *think* this is not a firewall issue (although your networking is more complex than it seems); but a server, even if it's listening on all addresses and can actually receive a connection, can still choose to refuse it. When a firewall drops a connection, it usually times out (no answer). When the server chooses to explicitly *refuse* the connection, this results in a TCP RST and thus in a "connection refused" error. This looks like the second case.
Comment: @Massimo I understand. If the server is _excplicitly refusing_ a connection, is there a way I can verify, or debug this?
Comment: The server should generate logs. And it should have config settings where it's defined which connections it should accept or reject. I'm not familiar with this software, but you should be able to look at its docs.
Comment: @Massimo, I'll try that, thank you!
Answer: Looks like the local firewall in the target machine is not allowing incoming connections on TCP port 7077.
This should solve the issue:
iptables -A INPUT -p tcp --dport 7077 -j ACCEPT

Depending on existing rules, you might need to use -I instead of -A:
iptables -I INPUT -p tcp --dport 7077 -j ACCEPT

Comment: when I run `firewall-cmd --list-ports` I get the message `FirewallD is not running`. Woudln't this mean that there's no firewall?
Comment: I added the rule, but the error is still the same
Comment: FirewallD is a firewall management service, not the actual firewall. Please add the output of `iptables -L` to your question.
Comment: Also, please check that on both the source and the destination machine; it's also possible that *your* machine doesn't allow outbound connections on TCP port 7077.
Comment: I checked for my machine and outbound connections like so: `time nmap -p 7077 portquiz.net`. `State` shows as `open`.


Simplify the Boolean expression $X Y Z+X Y' Z'+X' Y' Z+X' Y Z'$?

Question: $$X Y Z+X Y' Z'+X' Y' Z+X' Y Z'$$
I know it simplify to (X XOR Y XOR Z),BUT I want to simplified using only AND, OR, and NOT Gates?
Please help I spent three hours but I don't get the same truth table.
Comment: If you want a sum of products, then $X Y Z+X Y' Z'+X' Y' Z+X' Y Z'$ is as simplified as you can get it.
Comment: Thank you I though am going crazy.
Answer: I suppose the prime means negation and then $X'=1+X$ etc.
$XYZ+XY'Z'+X'Y'Z+X'YZ'=$
$XYZ+X(1+Y)(1+Z)+(1+X)(1+Y)Z+(1+X)Y(1+Z)=$
$XYZ+X(1+Y+Z+YZ)+(1+X+Y+XY)Z+(Y+XY)(1+Z)=$
$XYZ+X+XY+XZ+XYZ+Z+XZ+YZ+XYZ+Y+YZ+XY+XYZ=$
$X+Y+Z$
Since $X+Y=(X\vee Y)\wedge \neg(X\wedge Y)$ just use AND, OR and NOT to construct $X+Y+Z$, that is $X$ XOR ($Y$ XOR $Z$)
Comment: what style, sir
Answer: Let T : C3 → C3 be the linear operator defined by T(z1, z2, z3) = (z1 + iz2, iz2 - z3, z1 + z3).
(1.1) Find a formula for T ∗(z1, z2, z3) expressed as a single vector in terms of z1, z2, z3.
(1.2) Find a basis for N (T) .
(1.3) Find a basis for R (T ∗) .
(1.4) Show that R (T ∗)⊥ = N (T) .


Qual é o código http adequado para responder o conteúdo de uma imagem?

Question: Bem, a pergunta é bem direta.
Estou querendo usar o PHP para responder o conteúdo de uma imagem. Porém, gostaria de saber se o tipo de status http causará algum impacto quanto ao cliente (como por exemplo, cache de imagens no browser).
No caso, estou utilizando o Laravel 3
$cachedImage = 'storage/images/cached.jpg';

$code = ... // Qual deles usar?

return Response::make(File::get($cachedImage), $code, ['content-type' => 'image/jpeg']);

Eu deveria utilizar o código 200 ou 304 ? Percebi que no Google Chrome, é retornando 304 para imagens!
Comment: o normal é o código 200 a não ser que vc queira enviar um status específico. Se quer usar uma imagem para representar uma página não encontrada, pode usar 404, por exemplo.
Comment: Mas, no caso, preciso de um status que represente uma imagem existente , porém a mesma deve ser retornada pelo PHP.
Comment: ué.. então é 200 rsrss
Answer: Para isso existem as RFC, são documentos técnicos desenvolvidos e mantidos pelo IETF (Internet Enginnering Task Force), instituição que especifica os padrões que serão implementados e utilizados em toda a internet.
De acordo com o RFC 2616, seção 10:

10.3.5 304 Not Modified
If the client has performed a conditional GET request and access is allowed, but the document has not been modified, the server SHOULD respond with this status code. The 304 response MUST NOT contain a message-body, and thus is always terminated by the first empty line after the header fields.
The response MUST include the following header fields:

Date, unless its omission is required by section 14.18.1
  If a clockless origin server obeys these rules, and proxies and clients add their own Date to any response received without one (as already specified by [RFC 2068], section 14.19), caches will operate correctly.
ETag and/or Content-Location, if the header would have been sent
      in a 200 response to the same request
Expires, Cache-Control, and/or Vary, if the field-value might
      differ from that sent in any previous response for the same
      variant

If the conditional GET used a strong cache validator (see section 13.3.3), the response SHOULD NOT include other entity-headers. Otherwise (i.e., the conditional GET used a weak validator), the response MUST NOT include other entity-headers; this prevents inconsistencies between cached entity-bodies and updated headers.
If a 304 response indicates an entity not currently cached, then the cache MUST disregard the response and repeat the request without the conditional.
If a cache uses a received 304 response to update a cache entry, the cache MUST update the entry to reflect any new field values given in the response.

Resumindo
Para sua resposta, você pode usar sim o 304 já que a requisição do usuário não vai modificar nada no servidor e você está apenas retornando a imagem.

Fontes:

http://canaltech.com.br/o-que-e/internet/O-que-e-um-RFC/#ixzz3eeKVTf3m
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
Answer: Na realidade, para imagem, nunca vi utilizarem nenhum! O código neste caso é implicitamente 200, portanto, seria redundante inserir 200.
O mais importante é o header que você já está inserindo.
Comment: HTTP response sem código? F12 -> Network...
Comment: Como está utilizando Laravel: **SIM**, sem explicitar response já retorna 200 como padrão.


How to prove a relation between the evolution operators in the Schrödinger and interaction pictures of quantum mechanics?

Question: Consider a Hamiltonian $H$ of two components, a time-independent $H_0$ and a time-dependent $V(t)$,
$$H(t)=H_0+V(t)\,.$$
In the Schrödinger picture of quantum mechanics, the state $\left|\psi(t)\right\rangle_{\mathrm{S}}$ evolves according to:
$$\mathrm{i}\hbar\frac{\partial}{\partial t}\left|\psi(t)\right\rangle_{\mathrm{S}}=H(t)\left|\psi(t)\right\rangle_{\mathrm{S}}\,.$$
This equation admits a formal solution given by,
$$\left|\psi(t)\right\rangle_{\mathrm{S}}=U(t,t_0)\left|\psi(t_0)\right\rangle_{\mathrm{S}}\,.$$
$U(t,t_0)$ is the evolution operator corresponding to $H(t)$, defined by
$$U(t,t_0)=\mathcal{T}\exp\left(-\frac{\mathrm{i}}{\hbar}\int\limits_{t_0}^{t}\mathrm{d}t'H(t')\right)\,,$$
where $\mathcal{T}$ is the time-ordering operator.
One define the states and operators in the interaction picture as
$$\left|\psi(t)\right\rangle_{\mathrm{I}}=\exp\left(\frac{\mathrm{i}}{\hbar}H_{0}t\right)\left|\psi(t)\right\rangle_{\mathrm{S}}\,,$$
$$A_{\mathrm{I}}(t)=\exp\left(\frac{\mathrm{i}}{\hbar}H_{0}t\right)A_{\mathrm{S}}(t)\exp\left(-\frac{\mathrm{i}}{\hbar}H_{0}t\right)\,.$$
$A_{\mathrm{S}}(t)$ is the operator in the Schrödinger picture, such as $V(t)$, which in general could depend on time.
One could prove that
$$\mathrm{i}\hbar\frac{\partial}{\partial t}\left|\psi(t)\right\rangle_{\mathrm{I}}=V_{\mathrm{I}}(t)\left|\psi(t)\right\rangle_{\mathrm{I}}\,.$$
This resolves into
$$\left|\psi(t)\right\rangle_{\mathrm{I}}=U'(t,t_0)\left|\psi(t_0)\right\rangle_{\mathrm{I}}\,,$$
where
$$U'(t,t_0)=\mathcal{T}\exp\left(-\frac{\mathrm{i}}{\hbar}\int\limits_{t_0}^{t}\mathrm{d}t'V_{\mathrm{I}}(t')\right)\,.$$
I know that $U$ and $U'$ are related to each other by
$$U'(t,t_0)=\exp\left(\frac{\mathrm{i}}{\hbar}H_{0}t\right)U(t,t_0)\exp\left(-\frac{\mathrm{i}}{\hbar}H_{0}t_0\right)\,.$$
This can be proved by a differentiation procedure (and essentially this is how the interaction picture is derived from the Schrödinger one). But how can one prove this based on the expansion in Neumann's series of the evolution operators only?
Answer: It is not correct that $$U'(t,t_0)=\exp\left(\frac{\mathrm{i}}{\hbar}H_{0}t\right)U(t,t_0)\exp\left(-\frac{\mathrm{i}}{\hbar}H_{0}t_0\right)\,.$$ You can simply see this when setting $V\equiv 0$. We then have that
$$ U(t,t_0) = \exp\left[-i (t-t_0) H_0\right]$$
while $$U'(t,t_0)= 1 \neq\exp\left(\frac{\mathrm{i}}{\hbar}H_{0}t\right)U(t,t_0)\exp\left(-\frac{\mathrm{i}}{\hbar}H_{0}t_0\right)\,.$$
Comment: Respectfully disagree (I wanted to say Holy Cow!). In the case you considered, couldn't you just split $U(t,t_0)$ into $\exp(-\frac{\mathrm{i}}{\hbar}H_0t)\times\exp(\frac{\mathrm{i}}{\hbar}H_0t_0)$. $H_0$ commutes with itself!


Standard form of trig equations

Question: The standard form for any trig equation is y=Asin(B(x-D))+C (I'm just using sine in the equation). For the "D" which is the horizontal translation, if D is added does the graph move left or right, likewise when it is subtracted?
Comment: When $D>0$ the graph is moved D units to the right; if $D<0$ the graph is moved $|D|$ units to the left.
Answer: define $f:f(t)=A\sin(Bt)+C$ also define $g:g(t)=f(t-D)$
clearly $g(t)$ has the same value as $f$ evaluated $D$ units to the left of $t$ (i.e. $t-D$), hence $f(t-D)$ has the same value as $g$ evaluated $D$ units to the right of $t-D$ (i.e. $(t-D)+D=t$). Now suppose that $x=t-D$, then $f(x)$ has the same value as $g$ evaluated $D$ units to the right of x. Thus, the graph moves to the right for $D>0$.
Another approach is
$$y = A\sin(B(x-D))+C$$
$$y-C = A\sin(B(x-D))$$
$$\frac{y-C}{A} = \sin(B(x-D))$$
$$\sin^{-1}\bigg(\frac{y-C}{A}\bigg) = B(x-D)$$
$$\frac{1}{B}\sin^{-1}\bigg(\frac{y-C}{A}\bigg) = x-D$$
$$\frac{1}{B}\sin^{-1}\bigg(\frac{y-C}{A}\bigg)+D = x$$
You can easily see what will happen if you start "tweaking" the $D$ parameter. Increasing $D$ will tend to increase $x$ (which is what "moving to the right" means).

Standard form of trig equations


HTML form JSON array output is not formated as expected

Question: I have been making a project about cinema tickets booking, and each ticket has a certain type. I was previously making it with PHP, and I was generating a form to choose the ticket type for each seat with a select input like this one:
<select name="seats[D3]">

I could then loop over the "seats" array in PHP, and for example seats["C3"] was containing the value "Student", and it was working fine.
But now that I try using JavaScript for my server side  instead of PHP, the obtained POST request body is not a dictionnary linking a seat number to its type anymore. Instead I get something like this:
{"seats[E1]":"Adult","seats[D2]":"StudentSenior"}

You can clearly see that I do not have a dictionnary structure, the bracket notation has no effect and I just have independent variables, while I would like to get something like this:
{"seats":["E1":"Adult", "D2":"StudentSenior"]}

I know I could just read every entry and check if it starts with "seats[" and then get the value after it, but I just find it strange that PHP can use this form request to build an array and javascript cannot...
Thank you for your help!
Comment: Whatever server side technology, browser will submit same value as per the input type. So just inspect the html code generated for select box when it was PHP based and when its javascript based. Look like the drop down is not getting generated correctly.
Answer: You should set your body-parser urlencoded helper to extended mode...
var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true })) //  note "true"

This sets body-parser to use the qs library which is capable of parsing bracketed strings into objects.


The expansion of $(a+b+c+d)^{20}$

Question: Let us consider the expansion of $$(a+b+c+d)^{20}.$$
Find:

The coefficients of $a^{11}b^6c^2d$ and $a^{11}b^9$,
The total number of terms of this expansion,
The sum of all the coefficients.

Thank you for your help.
Comment: For the sum of the coefficients put $a=b=c=d=1$.
Comment: To see what's going on, look at a simpler problem, like the binomial expansion of $(a+b)^5$. Write that one down explicitly, $\binom{5}{0}a^5+\binom{5}{1}a^4b+\binom{5}{2}a^3b^2+\cdots +\binom{5}{5}b^5$, and you will see that when you put $a=b=1$ you will get the sum of the binomial coefficients.
Comment: This is the number of solutions of $a+b+c+d=20$ in non-negative integers. Look at the Wikipedia article on Stars and Bars (combinatorics). You will find that the number of solutions is $\binom{20+4-1}{20}$ or equivalently $\binom{23}{3}$.
Comment: See https://www.artofproblemsolving.com/wiki/index.php?title=Multinomial_Theorem
Comment: @AndréNicolas Why does it work like this?
Comment: @AndréNicolas Now I see perfectly. I've already found the answer to my first question, these can be calculated quite easily. But how about the number of terms in the expansion?
Answer: The first are just the multinomial coefficients $\binom{20}{11,6,2,1} = \frac{20!}{11! 6! 2! 1!}$ and $\binom{20}{11,9,0,0} = \frac{20!}{11!9!0!0!}$.
There is one term for every tuple $(a,b,c,d)$ with $a+b+c+d = 20$. where $a,b,c,d \ge 0$, all integers. This equals (e.g. see this wiki article) $\binom{23}{3}$.
To get the sum of all, just consider the multinomial theorem. Consider $(x_1 + x_2 + x_3 + x_4)^{20}$, which has all the same coefficients. To get the sum of them, fill in $x_1 = x_2 = x_3 = x_4 = 1$ to make all products of $x_i$ equal to 1, so we get $4^{20}$ as the answer.
Answer: Observe that each term in the expansion of $$(a+b+c+d)^{20}=(a+b+c+d)(a+b+c+d) \cdots (a+b+c+d)$$ is obtained by taking one of the four terms $a,b, c$ or $d$ from each of the $20$ factors.  Hence, the coefficient of $a^{11}b^6 c^2 d$ is the number of ways to choose $11$ of the $20$ factors for $a$ (which is ${20 \choose 11}$), times the number of ways to choose $6$ of the remaining $9$ factors for $b$ (which can be done in ${9 \choose 6}$ ways),  times the number of ways to choose factors for $c$ (which can be done in ${3 \choose 2}$ ways), times the number of ways to choose the factors for $d$ (which can be done in ${1 \choose 1}$ ways).  Hence, the coefficient in question is the product ${20 \choose 11}{9 \choose 6}{3 \choose 2}{1 \choose 1}$, which is equal to the multinomial coefficient $\frac{20!}{11! 6! 2! 1!}$.  The coefficient of $a^{11} b^9$ can be obtained similarly.
To obtain the total number of terms in this expansion, observe that one term is of the form $\alpha a^7 b^7 c^6$ for some constant $\alpha$, and another is of the form $\beta a^6 b^6 c^6 d^2$.  The former term corresponds to the partition $(7,7,6,0)$ of $20$ into $4$ parts, and the latter term corresponds to the partition $(6,6,6,2)$ into 4 parts.  The number of ways to divide $20$ into $4$ parts is ${20+4-1 \choose 3}={23 \choose 3}$. To see why, place $20$ beads in a straight horizontal line, and you want to add three vertical lines (separator bars) to obtain the partition of $20$ into $4$ parts.  The number of permutations of $20$ identical beads and $3$ identical bars is $\frac{23!}{3! 20!}$.
The sum of all coefficients in an expansion $\alpha a^7 b^7 c^6+ \beta a^6 b^6 c^6 d^2 \cdots$ is the sum $\alpha + \beta + \cdots$.  Observe that the latter is obtained from the former by substituting $1$ for $a,b,c$ and $d$.  Hence, we can substitute $1$ for $a,b,c$ and $d$ in the left hand side, ie in $(a+b+c+d)^{20}$, and we get $4^{20}$.

The expansion of $(a+b+c+d)^{20}$


What am I doing wrong in this trigonometry/rate simulation problem?

Question: I'm refreshing on some trig and cannot figure out how to solve this non-realistic word problem simulating a person walking in a circle.
A person is located at the point (8,0) at time, t = 0, and walks at the rate of  8 yards/min in a counterclockwise direction along the circle centered at the origin of radius 8.

What are the coordinates (x,y) which give the location of the person after 29 minutes?
After how many minutes will the person return to their starting location (8,0)?

I know that I'm supposed to be using the unit circle, but can't seem to come up with an answer. Here's what I've done:
i.) The circumference of the circle is 16Pi?
ii.) The distance traveled in 29 min is 232 yards?
iii.) Hypotenuse is 232?
I know that I somehow have to make a triangle and use trig functions to answer the 2 questions but I don't understand what the side lengths would be. Starting out, I think the adjacent side is 8 yards? And I believe x = r*cos(z) and y = r*sin(z)?
I just need some help getting started. Anything will be greatly appreciated. Thanks!
Comment: The hypotenuse is $8$. Calculate the number of revolutions travelled. It is $\frac{232}{16\pi}\approx 4.6155$. That's $4$ complete revolutions plus about $221.5776$ degrees. Call this angle $\theta$. Your coordinates will be $x=r\cos\theta$, $y=r\sin\theta$, where $r=8$. Do check my arithmetic! Depending on your course, you may want to work in radiams rather than degrees.
Comment: That ratio is the number of **revolutions**. I removed the leading $4$, but you actually don't need to. Then multiply by $360$ to get the angle in degrees. Or multiply by $2\pi$ to get the angle in radians. That's actually nicer in this problem, since the $\pi$ cancel, and we get $\frac{232}{8}=29$. No accident of course. I used degrees because I guessed you were working in degrees.
Comment: @AndréNicolas so theta would = 232/16pi? Or would it be 221.5776 degrees (converted to radians)?
Comment: @AndréNicolas Perfect, thanks! The last thing I can't figure out is how long it will take before the person gets back to (8,0)
Comment: You mean how long after the $29$ minutes? Let's find the time for $5$ revolutions, and take away $29$. Five rev. is $80\pi$, at speed $8$ takes $10\pi$. Subtract the $29$ already travelled.
Comment: Wait what? Like total.So 80pi - 29?
Comment: It is $10\pi -29$. I should have written a full answer, it would have been clearer to you than comments.
Answer: We can work in degrees or in radians. The advantage of degrees is that our intuition is better developed. We will set up the computations in both.
The circumference of the circle is $16\pi$. If we have travelled for $29$ minutes at $8$ yards per minute, we have travelled a distance $(29)(8)$.
Divide by $16\pi$. That gives us the number of revolutions. So we have travelled through $\frac{(29)(8)}{16\pi}$ revolutions. Thus we have travelled through an angle of
$$\frac{(29)(8)}{16\pi}\cdot 360$$
degrees.
In radians, the angle we have travelled through looks much simpler. There are $2\pi$ radians per revolution, so we have travelled through
$$\frac{(29)(8)}{16\pi}(2\pi)=29$$
radians. The reason the answer is so simple is that at $8$ yards per minute, which matches the radius, we are rotating at $1$ radian per minute.
Whatever measure we use, if $\theta$ is the angle we have travelled through, our location $(x,y)$ is given by
$$x=8\cos\theta,\qquad y=8\sin\theta.$$
Now we can compute. Put the calculator in radian mode, and find $8\cos(29)$ and $8\sin(29)$.
The question about return to the starting point is a little ambiguous. The amount of time for a complete revolution is the circumference divided by the speed, so this is $\frac{16\pi}{8}$ minutes.
But if we have been travelling for $29$ minutes, then we have gone through $\frac{(29)(8)}{16\pi}$ revolutions, somewhat more than $4.6$. To get to the start point, we need to complete the fifth revolution.
Doing $5$ complete revolutions take time $\frac{(5)(16\pi)}{8}=10\pi$ minutes. So if we have already travelled for $29$ minutes, the additional time we need to return to $(8,0)$ is $10\pi-29$ minutes.


How to know if a specific role can access a page?

Question: I have Drupal set up and some module enabled.
Specifically I have the translation_overview module installed.
Now I want to give a specific role access to those pages so they can see what needs to be translated.
So I gave them access to 'View translation overview assignments' but when I ask a person with this role if she can see it, she tells me she cannot.
I am an administrator, so I can obviously see everything in there.
But how can I see what other roles see?
Comment: do you solve your problem?
Answer: You can make use of Masquerade module to switch users who belongs to different roles. This will help you see what other role users see.
Answer: In general I think people test permissions by going to the permissions page and tweaking it until it works. That's an OK process, but can have unintended consequences (you may grant more or less than you wanted).
So, first, I suggest setting up test users that you can use to log in to your site with various different combinations of permissions. That's an effective way to test out your changes.
Second, set up a test site for this kind of experiment. Doing that kind of change on a test site will help you be more confident when you tell a user that you've fixed their permissions.
Often the README.txt or project page or documentation (if it exists) will tell you what permissions to use.
My final suggestion is that the one way to be really confident that a user can access a page is to look at the code. The hook_menu of translation_overview.module and the hook_permission together shows that users with "View translation overview assigments" should be able to see the path at admin/content/translation-overview-assignments. However, there is also a permission for 'manage ' . check_plain($lang_code) . ' translation overview priorities' which is relevant. Note that there is a typo in the permission where it is missing the letter "n" in assinments.
It's possible that there is a bug in the module's permissions enforcement. The module's bug queue has a few issues that could be related.
Also, it's possible that the menu is broken and the person can access the page, but the link isn't presented. I would try visiting the page directly rather than using a link to see if access is the problem or navigation.
Answer: Unfortunately, permissions are a complex topic and contrib documentation (where it exists) will rarely be able to fully address all situations.
When documentation doesn't provide the info you need you have 2 options:

Play around with it.  Create a test account with the same role(s) as
the user you're trying to solve the problem for and play with
granting various permissions.  Unfortunately it's not always obvious
what permissions are going to have which effects as there are some
permissions (like "administer content") that have far-reaching
consequences.
Look at the code.  For page-based permissions you can typically look at the implementation of hook_menu and look at two array elements in particular: access callback and access arguments.  Looking at translation_overview_menu I see several callbacks defined: To access admin/content/translation-overview-manage you can look at the access callback function and see that your user needs the manage x translation overview priorities permission, where x is any language on your site.  For all of the other pages provided by the module you will notice that no access callback is defined, so they inherit the user_access value for this from their parents.  So the string set in access arguments is passed directly to the user_access() function meaning that your user needs the translation overview assigments permission to see any of those pages.

If you want to learn more about how access callbacks or arguments work, read the hook_menu documentation.
This is not specific to translation_overview as it seems like a pretty simple module, but for future reference it's also worth noting that not all permissions are enforced in the menu system.  Sometimes (often) code that is rendering the page itself will make calls to user_access() or node_access() or any of the other access-related functions to determine if the user has access to something and will change what's shown on the page as a result of those calls.  In that case, if you don't feel too comfortable with code, you will almost certainly be reduced to using the "play around with it" method to determine the impact of various permissions.
Comment: Many have dreams about "how great it would be if all contributed modules would come with complete, clear and up-to-date documentation about install, admin and usage of any module" ... Only a few wake up and start contributing such documentation ... which is a perfect way to really learn how a module works. My recommendation: start digging in the issue queue of any module, and review at least any support / documentation issue. Then summarize everything you learned ... and contribute that back to the module ...
Comment: @Pierre.Vriens Oh, I agree.  My "ideally" wasn't a value judgement on anyone.  None of my modules are really documented at all :).  I'm just saying that *ideally*...in a perfect world...it would be the case that this was in the docs.
Comment: No problem, don't worry. Maybe you should rephrase your first phrase to something like "these are the facts: ...". That way you avoid provoking thoughts like in my comment. Just FYI: I've spend a lot of time in producing "community docu" about some of the modules I (co-)maintain (like chart, charts, and forena). True, it's "only" docu, but I think it helped quite a bit in reducing the amount of support requests (more important: "I" learned a lot from it about these modules I got involved in).
Comment: Fair enough, I've reworded it to make it not appear critical of module maintainers.
Answer: Please create a test user with the permissions.Login with the test user account and check above case so that you get to know what other users can see.
Comment: I didn't want to use this method, because I have a lot of roles. I did think about it though.
Answer: Go to admin/people/permissions and set the permissions Translate content , Administer content translations and  View translation overview assigments  and you must enable too this permissions for the content type:
My content type: Create new content
My content type: Edit any content


Release app crashes, debugging on device works fine - android

Question: I see lots of people here with this problem for the iPhone, but this is a Nexus 7 device.  App crashes with the release build, yet when I debug directly on the device, the crash doesn't happen.  I can tell it's the latest, newest version of the software.
Anyone else run into this?
Release version and debug version are even running off the same database.
Here is the code that's crashing (null pointer exception - line indicated):
<code>        mTabHost = (TabHost)findViewById(R.id.tabHost);
    mTabHost.setup();
    mTabHost.setOnTabChangedListener(this);

    String className = this.getLocalClassName();

    if (surveyID < 68) {
        String sql = "Select * FROM L_Options WHERE Type = 'TabSetup' AND Setting = '" + optIncludeSurvey + "' "
                   + "AND Value = " + surveyID;
        Cursor c = DataBaseConnector.query(sql);
        if (c != null) {
            if (c.moveToFirst()) {
                surveyID = c.getInt(c.getColumnIndex("FK_RecID"));
            }
        }
    }

    String sql = "SELECT TS.TextID, TS.TabClass, TS.TabHeaderID, TS.Comments,O.Value "//
            + "FROM L_TabSetup AS TS LEFT JOIN L_Options O ON "//
            + "O.FK_RecID = TS.TabSurveyID AND O.Type = 'TabSetup' AND O.Setting = '" + optIncludeSurvey + "' "//
            + "WHERE TS.ScreenClass = '" + className + "' "//
            + "AND TS.Active = 1 "//
            + "AND O.Active = 1 "//
            + "AND TS.TabSurveyID = " + surveyID + " ";

    if (GlobalVars.subjectLeftToRight == 1) {
        sql += "ORDER BY TS.DisplayOrder ASC";
    } else {
        sql += "ORDER BY TS.DisplayOrder DESC";
    }

    Cursor c = DataBaseConnector.query(sql);

    if (c != null) {
        if (c.moveToFirst()) {
            TabInfo tabInfo = null;

            do {
                String comment = c.getString(c.getColumnIndex("Comments"));
                int includeSurveyID = c.getInt(c.getColumnIndex("Value"));
                Class<?> tabClass = getClass(c.getString(c.getColumnIndex("TabClass")));
                int tabHeaderID = c.getInt(c.getColumnIndex("TabHeaderID"));
                //put in included SurveyID
                if (args != null) {
                    if (args.getInt(optIncludeSurvey, -1) == -1) {
                        args.putInt(optIncludeSurvey, includeSurveyID);
                    }
                }
                else {
                    args = new Bundle();
                    args.putInt(optIncludeSurvey, includeSurveyID);
                }

                String[] texts = Lookups.getText(c.getInt(c.getColumnIndex("TextID")));

                //crash line
                ////////////////////////////////////////////////////////
                tabInfo = new TabInfo(tabClass, args, texts, c.getInt(c.getColumnIndex("TextID")), tabHeaderID, comment, surveyID);
                //end crash line
                //////////////////////////////////////////////////////////

                addTab(this, tabInfo);
                this.mapTabInfo.put(tabInfo.texts[0], tabInfo);

            } while (c.moveToNext());
        }
        c.close();
        c = null;
    }
</code>
Please be kind about the coding practices - this is legacy code.
EDITED: Logcat file
<code>08-15 10:07:09.818: E/AndroidRuntime(1221): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.assistek.ediary/com.assistek.ediary.SubjectMenuEvent}: java.lang.NullPointerException
08-15 10:07:09.818: E/AndroidRuntime(1221):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
08-15 10:07:09.818: E/AndroidRuntime(1221):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
08-15 10:07:09.818: E/AndroidRuntime(1221):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-15 10:07:09.818: E/AndroidRuntime(1221):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
08-15 10:07:09.818: E/AndroidRuntime(1221):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-15 10:07:09.818: E/AndroidRuntime(1221):     at android.os.Looper.loop(Looper.java:137)
08-15 10:07:09.818: E/AndroidRuntime(1221):     at android.app.ActivityThread.main(ActivityThread.java:5039)
08-15 10:07:09.818: E/AndroidRuntime(1221):     at java.lang.reflect.Method.invokeNative(Native Method)
08-15 10:07:09.818: E/AndroidRuntime(1221):     at java.lang.reflect.Method.invoke(Method.java:511)
 08-15 10:07:09.818: E/AndroidRuntime(1221):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
 08-15 10:07:09.818: E/AndroidRuntime(1221):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
 08-15 10:07:09.818: E/AndroidRuntime(1221):    at dalvik.system.NativeStart.main(Native Method)
08-15 10:07:09.818: E/AndroidRuntime(1221): Caused by: java.lang.NullPointerException
08-15 10:07:09.818: E/AndroidRuntime(1221):     at com.assistek.ediary.SubjectMenuEvent.setupTabHost(SubjectMenuEvent.java:255)
08-15 10:07:09.818: E/AndroidRuntime(1221):     at com.assistek.ediary.SubjectMenuEvent.onCreate(SubjectMenuEvent.java:96)
08-15 10:07:09.818: E/AndroidRuntime(1221):     at android.app.Activity.performCreate(Activity.java:5104)
08-15 10:07:09.818: E/AndroidRuntime(1221):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
08-15 10:07:09.818: E/AndroidRuntime(1221):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
08-15 10:07:09.818: E/AndroidRuntime(1221):     ... 11 more
</code>
Related question:
Reinstalling app does not bring over all the changes of released app android
Comment: Any idea what line could be failing? Might be worth having loads of if statements (for testing on a device) and if one of them is null to display an error explaining which of the variables is null. Also using a try catch here and there might be useful too... The potential reason the debug works is because code runs much slower, which gives time for a variable not to be null (if initiated on a thread or similar)
Comment: I put the line that was failing in the code.  I was able to see what was going on in Logcat.  I will do a try catch block to test this out.  Thanks for taking a look.
Comment: Not running this in a thread (I know bad design).
Comment: Can you provide the full logcat crash?
Comment: As above your logcat will be useful here. Threads are not always a good thing for simple apps anyway so don't worry about it :)
Answer: It looks like the application was not be updated with the most current release (the old apk from previous downloads was not being deleted).  So this is a non-issue.  I did learn a lot, though.
Comment: Please elaborate more. Deleted from where? Sync what?


Autoamte SPSS from Access with VBA?

Question: I have an Access database (2010) which needs to automatically send data to SPSS, have statistical functions run on it there, and then export said information back into Access. I need to know wheter it is possible to do these workflow steps all from Access using VBA.
I have found some instructional material on the IBM Website which indicates that you can hook up an Access Database to SPSS using ODBC drivers. I have also found information on automating SPSS using their scripting language.
Saddly I have not found any information on the web of anyone having used VBA to automate SPSS. What I would like to know is: a) can it be done? and b) would I need to learn the SPSS scripting language to do it?
Answer: SPSS Statistics has a full set of automation methods available similar to VBA in Office.  Look at the help for Basic scripting in Statistics or reference the SPSS automation libraries from Access.  These methods are not limited to use from Basic, but if you are starting with Access VBA, that would be a reasonable way to do this.

Autoamte SPSS from Access with VBA?