Expose HTML fragments as REST API vs Web Components?

Question: I have a use case where the common sections of the website, "article detail" or "header" needs to be reused across other streams & the teams of my organization as well as some external agencies as well.
We can expose the Content in the form of JSON using REST endpoints but the problem here is that each team will then need to design the UI & we may lose the consistency & more chances of error.
To address this I can think of 2 solutions:
1) Self-Rendered Web Components
2) Extract the HTML fragment & expose the same as REST API
I am more inclined towards the 2nd approach as we already have the working HTML & as I am using CMS, each section of the web is already identified as a component & we have a dedicated template associated with it.
I will need to make this fragment more independent & self-rendered by removing the common dependencies available at the page level.
This way I can expose these sections via Rest endpoints which will return pure HTML output instead of JSON.
I would like to understand to know your opinion & if you see any issues.
Thanks
Comment:   1   2
Comment: Thanks but why do you think I shouldn't go with just Case 2. Are there any drawbacks or any specific benefits going with webcomponents?
Comment: WebComponents encapsulate logic and complexity, makes re-use easier. see https://iconmeister.github.io as example how a WebComponent (aka Custom Element) makes working with SVG easier. Your Solution #2 requires your developers to work with JS code, and they can make all sorts of usage mistakes. So your option isn't 1 **OR** 2. The best is a mix of both (because you already have 2)
Comment: Basically you will wrap a Custom Element (Custom HTML tag) around your API: ````
Answer: It's common on MVC framework like .Net Core or Laravel to return a View from a component with all the HTML output, instead of a simple JSON.
So for sure you can do, also from Ajax call


What are the implicit assumptions that justify the usage of the "relative error"?

Question: In applied statistics, for example, analyzing data from a science experiment, we sometimes use "absolute error" while at the most of time, we calculate the "relative error". Generally, under what circumstances should we use the "relative error" instead of "the absolute error"?
If we use relative error, are we basically implicitly assuming that the variance of the sample distribution is positively correlated with the value of the mean? Is there a fundamental axiom in mathematics or statistics called "scale independence"?
It is similar to the financial math literature, the variance of the random variable $X_t$ is usually correlated with the exact value of $X_{t−1}$. If $X_{t−1}$ is greater, the variance of $X_t$ is greater. This often leads to something like a Lognormal distribution.
Answer: I think you are getting a bit ahead of yourself.  Both absolute error and relative error are measures of error that are useful for different purposes.  There are no assumptions required to use either of these measures$^\dagger$, so long as they are correctly interpreted.  Of course, the statistical properties of these measures will depend on the underlying distribution of the values being predicted and the predictions being made, so if you want to assert a particular distributional property of one of these measures, you may need to make some assumptions.  So, if you are asking what assumptions are needed, then naturally you first need to ask, for what?  What statistical property are you seeking?
If you have a prediction $\hat{x}_t$ of an unknown value $x_t$ then the absolute error $\varepsilon_t = |\hat{x}_t - x_t|$ gives a measure of the amount by which you are wrong in your prediction.  Often it is the case that this is not particularly useful on its own, since this amount might be large or small in comparison to the size of the thing you are predicting.  For this reason, analysts often prefer to measure their error using the relative error $\eta_t = |\hat{x}_t - x_t| / |x_t|$.
If you are seeking a particular statistical property for one of these measures, then please specify the property you would like it to have, and then we can help to suggest sufficient conditions that would yield the required property.

$^\dagger$ Strictly speaking, you need to have $x_t \neq 0$ to calculate the relative error, so this could possibly be taken as a required assumption.  Alternatively you could merely adopt the convention that $\eta_t = \infty$ when $x_t = 0$.

What are the implicit assumptions that justify the usage of the “relative error”?


Identifying Feature Importance in Text

Question: I am trying to perform feature interpretability on a text corpus but I am becoming quite confused as to how I identify the importance of particular features (words). I have done substantial research to try and figure this out and have provided an implementation below but for some reason it is not coming out the way I would expect. I'd appreciate direction as to whether I have the wrong theory or if I have a bug in my code.
Theory: From what I understand obtaining feature interpretability is easiest when using a linear model. To that end I have trained an SVM with a linear kernel, and a one vs. rest approach for multiclass learning. According to this post I should be able to obtain the individual feature significance from the coef_ variable of the trained SVM. When parsing my text through either a TF-IDF or Count Vectorizer and I receive the same output (so I am mostly certain this is not related to the issue).
My text corpus is simple, and involves several of the same lines with changes only to a single word. The same is true of the evaluation corpus. As such a classification can only be made using the words: 'cat', 'dog', and 'rat'.
Code:
<code>from sklearn.feature_extraction.text import CountVectorizer
from sklearn import svm, metrics

import numpy as np

# Setup training/eval data

Xtrain = [
    "I am a cat",
    "What do i cat",
    "a cat is where its at",
    "how about that cat",
    "the cat there sat",

    "I am a dog",
    "What do i dog",
    "a dog is where its at",
    "how about that dog",
    "the dog there sat",

    "I am a rat",
    "What do i rat",
    "a rat is where its at",
    "how about that rat",
    "the rat there sat",]

Ytrain = [0,0,0,0,0, 1,1,1,1,1, 2,2,2,2,2]

Xeval = [
    "it was a cat",
    "it was a dog",
    "it was a rat",

    "I watched cat where it sat",
    "I watched dog where it sat",
    "I watched rat where it sat",]

Yeval = [0,1,2,0,1,2]

# define model

vect = CountVectorizer()
clf = svm.SVC(max_iter=100, tol=1e-4, probability=True,
kernel='linear', decision_function_shape='ovr' )

Xtrain_vect = vect.fit_transform(Xtrain)
clf.fit(Xtrain_vect, Ytrain)

# fit model
pred = clf.predict(vect.transform(Xeval))
print(metrics.accuracy_score(pred, Yeval))   # Achieves 100% accuracy

#--------------------------
# understanding features
#--------------------------
fn = np.array(vect.get_feature_names())
print(fn)   # prints vocabulary

coef = clf.coef_.toarray()
print(coef.shape) # (3, 16)

# for each of the available classes I try to output the
# most significant features to that model, because I use
# a one vs. rest approach I anticipate that I should see
# 'cat', 'dog', and 'rat' as the most significant word
# in each of the three models.

for label in range(coef.shape[0]):

    print('')
    print("Label: ", label)

    cf = coef[label].reshape(-1)

    # sort features in descending order
    order = cf.argsort()
    cf = cf[order][::-1]
    fn = fn[order][::-1]

    # print feature importance
    for f, c in zip(fn, cf):
        print(f, c)
</code>
Result: Because I am using a one vs. rest approach to my SVM I anticipate that 'cat', 'dog', and 'rat' should be the most important features in the prediction. This is especially true considering that model is 100% accurate on the evaluation dataset. However when I run the code I am seeing the following output:
<code>('Label: ', 0)

(u'cat', 1.0)
(u'where', 0.0)
(u'what', 0.0)
    #condensed for space
(u'am', 0.0)
(u'about', 0.0)
(u'dog', -1.0)

('Label: ', 1)

(u'there', 1.0)
(u'dog', 0.0)
(u'about', 0.0)
     #condensed for space
(u'where', 0.0)
(u'cat', 0.0)
(u'is', -1.0)

('Label: ', 2)
(u'do', 1.0)
(u'is', 0.0)
(u'cat', 0.0)
     #condensed for space
(u'dog', 0.0)
(u'there', 0.0)
(u'sat', -1.0)
</code>
As can be observed, the first class correctly identifies 'cat' as being very important but only considers 'dog' to be uninformative. For the other two labels I am receiving words I would consider uninformative as the most important and least important words.
What am I doing wrong? Thank you in advance.
UPDATE: So I have discovered this is in part due to a bug, namely that I was not deep-copying the Feature name list and was manipulating it each time I modified the 'order' for each new label. This explains why the first label made some sense. When I correct this bug I am getting the following output:
<code>('Label: ', 0)

(u'cat', 1.0)
(u'where', 0.0)
...
(u'about', 0.0)
(u'dog', -1.0)

('Label: ', 1)

(u'cat', 1.0)
(u'where', 0.0)
...
(u'about', 0.0)
(u'rat', -1.0)

('Label: ', 2)

(u'dog', 1.0)
(u'where', 0.0)
...
(u'about', 0.0)
(u'rat', -1.0)
</code>
Answer: I resolved this problem some time ago and thought I would present the answer for those who are looking.
In short, the Sklearn SVM does not perform in a typical one-vs-rest implementation. Instead it uses a wrapper to develop a decision function that combines the decision functions of several one-vs-other classifiers to perform its classification. This approach has changed between implementations and I encourage you to refer to your installation of Sklearn to find out how yours is being performed.

Identifying Feature Importance in Text


how can I check if a Gyroscope is present on device?

Question: Just wondering can I check if the device (iPhone, iPad, iPod i.e. iOS devices) has a Gyroscope ?
Answer: - (BOOL) isGyroscopeAvailable
{
#ifdef __IPHONE_4_0
    CMMotionManager *motionManager = [[CMMotionManager alloc] init];
    BOOL gyroAvailable = motionManager.gyroAvailable;
    [motionManager release];
    return gyroAvailable;
#else
    return NO;
#endif

}

See also my this blog entry to know you can check for different capabilities in iOS devices
http://www.makebetterthings.com/blogs/iphone/check-ios-device-capabilities/
Comment: I believe __IPHONE_4_0 is just a defined constant.  It seems the proper way to do this would be using `__IPHONE_OS_VERSION_MIN_REQUIRED >= 40000` (according to this StackOverflow question: http://stackoverflow.com/questions/3955331/if-iphone-4-0-on-ipad)
Comment: @jonsibley CMMotionManager is only available on iPhone os 4 ..if we try to use it on earlier os it will not compile
Comment: What advantage does using #ifdef have here?
Answer: CoreMotion's motion manager class has a property built in for checking hardware availability. Saurabh's method would require you to update your app every time a new device with a gyroscope is released (iPad 2, etc). Here's sample code using the Apple documented property for checking for gyroscope availability:
CMMotionManager *motionManager = [[[CMMotionManager alloc] init] autorelease];

if (motionManager.gyroAvailable)
{
    motionManager.deviceMotionUpdateInterval = 1.0/60.0;
    [motionManager startDeviceMotionUpdates];
}

See the documentation for more info.
Answer: I believe the answers from @Saurabh and @Andrew Theis are only partially correct.
This is a more complete solution:
- (BOOL) isGyroscopeAvailable
{
// If the iOS Deployment Target is greater than 4.0, then you
// can access the gyroAvailable property of CMMotionManager
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_4_0
    CMMotionManager *motionManager = [[CMMotionManager alloc] init];
    BOOL gyroAvailable = motionManager.gyroAvailable;
    [motionManager release];
    return gyroAvailable;
// Otherwise, if you are supporting iOS versions < 4.0, you must check the
// the device's iOS version number before accessing gyroAvailable
#else
    // Gyro wasn't available on any devices with iOS < 4.0
    if ( SYSTEM_VERSION_LESS_THAN(@"4.0") )
        return NO;
    else
    {
        CMMotionManager *motionManager = [[CMMotionManager alloc] init];
        BOOL gyroAvailable = motionManager.gyroAvailable;
        [motionManager release];
        return gyroAvailable;
    }
#endif
}

Where the SYSTEM_VERSION_LESS_THAN() is defined in this StackOverflow answer.
Comment: I am completely confused by looking at all these answers on this page. @jonsibley Is it true that the method "gyroAvailable" is only available in IOS4+?


mail_form gem rspec "undefined method `email' for"

Question: how can I write a test mail_form gem?
Вut the test gives an error.
How to associate a OrderForm and MailForm?
I have :
model:
class OrderForm < MailForm::Base
  attributes :name
  attributes :email
  attributes :phone_number
  attributes :order_name
  attributes :address
  attributes :file_1, attachment: true
  def mail_attachments
    [:file_1]
  end

controller, where:
class OrdersController < ApplicationController

  def create
    @order_form = OrderForm.new(params[:order_form])
    @order_form.deliver
    redirect_to root_path, notice: 'Заявка отправлена'
  end
end

end view(form of sending a letter):
orders/new.html.haml_spec.rb
   =form_for @order_form, url: orders_path, method: :post do |f|
         =f.text_field :name, placeholder: 'ФИО', class: 'gui-input'
         =f.text_field :email, placeholder: 'Email', class: 'gui-input'
         =f.text_field :phone_number, placeholder: 'Номер телефона',

end I write test:
require 'rails_helper'
RSpec.describe "orders/new", type: :view do
    it do
        assign(:order, build(:order))
        render
      expect(rendered).to have_field :name
    end
end

Comment: and, a have message error:
orders/new
     Failure/Error: =form_for @order_form, url: orders_path, method: :post do |f|

     ActionView::Template::Error:
       First argument in form cannot contain nil or be empty
Answer: check the output of rake routes, url orders/new will execute the orders#new action and render the view orders/new.html.erb
GET /orders/new orders#new  return an HTML form for creating a new order

new.html.erb will use the variables from your orders#new action. You are missing those variables
class OrdersController < ApplicationController

  def new
    @order_form = OrderForm.new
  end

  def create
    @order_form = OrderForm.new(params[:order_form])
    @order_form.deliver
    redirect_to root_path, notice: 'Заявка отправлена'
  end
end

Comment: I have url orders/new, and orders#new action, and other actions (send_message, show etc).rendered the views - ok.
I have the problem with rspec test:
I have message error:
orders/new
     Failure/Error: =f.text_field :email, placeholder: 'Email', class: 'gui-input'

     ActionView::Template::Error:
       undefined method `email' for #
Comment: @AleksZadkov `OrderForm` has the `email` attribute. You don't have the email attribute for `Order`. All your architecture is wrong.. You don't create an orderform object. read the guides http://guides.rubyonrails.org/form_helpers.html and try to understand the concept of http://guides.rubyonrails.org/active_record_basics.html


Bash script code explanation

Question: I am looking into the fast.ai course (deep learning for coders). One of their bash scripts to setup an instance in AWS, has this line of code that I am failing to understand (albeit knowing what it does):

I am quite certain, that this calls another bash script in the same directory. But there are six things I would like to understand/clarify:

Q1
Why is there a . before $(dirname "$0")

Q2
What is the difference between "$0" and $0, are you forcing the output in the fist case to be converted into a string?

Q3
I checked what dirname "$0" does by echoing it into my command line. It looks like it gives the name of the shell? So in my case (using Cygwin and executing: echo "$0"), it prints "-bash" to the console.

Q4
What does dirname do?

Q5
What is the value of $(dirname "$0")?

Q6
Will the variables: $region,$ami and $instanceType be transferred into setup_instance.sh, and why?
Comment: 1: `type .` and `help .` 4: `type dirname` and `man dirname`
Comment: [BashGuide/Sourcing](http://mywiki.wooledge.org/BashGuide/Sourcing), [Quotes](http://mywiki.wooledge.org/Quotes), [BashFAQ/028](http://mywiki.wooledge.org/BashFAQ/028), [`dirname` manual](https://www.gnu.org/software/coreutils/manual/html_node/dirname-invocation.html#dirname-invocation) are a few good reads.
Answer:
. is the original name for the source command. It executes a shell script in the current process.
Quoting a variable expands it as a single word and prevents wildcard expansion of the result. Most of the time you should quote variables when you're using them, unless you specifically need word splitting and globbing.
Inside a shell script, $0 contains the pathname of the script. In an interactive shell it contains the pathname of the shell.
It outputs the directory portion of a pathname. dirname foo/bar/baz prints foo/bar.
Combine the answers to #3 and #4 -- it's the directory portion of the script's pathname. So this looks for the setup_instance.sh script in the same directory as this script.
Yes, they will, because . executes the commands in setup_instance.sh in the same shell process where these were assigned.
Comment: add 6. and because it is executed in the same shell, variables set within that script are still valid after the script has finished. Which would not be the case if called without the dot, thus called in a subshell.

Bash script code explanation


Prove columns of a Matrix span $\mathbb{Q}^3$

Question:
Problem: Consider matrix $B =  \left(\begin{smallmatrix}  1 & 1 & 1 & 1 \\  1 & 2 & -1 & 3 \\  1 & 0 & 3 & -2 \\
\end{smallmatrix}\right) $. Show that the columns of this matrix span
  $\mathbb{Q}^3$ given that $B \in M_{34}(\mathbb{Q})$.

Attempt: When you do a RREF, you end up with $\left(\begin{smallmatrix}
1 & 0 & 3 & 0 \\
0 & 1 & -2 & 0 \\
0 & 0 & 0 & 1 \\
\end{smallmatrix}\right)$. Clearly there are 3 Pivots. Will this be sufficient to say that matrix span $\mathbb{Q}^3$? Do I need anything extra? This question is from the chapter of Linear transformations and I am wondering if I have to use any linear transformation property here.
Comment: This is sufficient. Since the first, second and fourth columns of $B$ are linearly independent, they form a basis for $\Bbb Q^3$, so any set of vectors containing these three columns spans $\Bbb Q^3$.
Answer: As long as your row reduction is correct, when you look at  the first, second and fourth columns of your row reduced matrix, these correspond to the three standard basis vectors of $\mathbb Q^3$, since they have a $1$ in precisely one position and zero in all the other positions. Hence, you are correct in saying that the columns of this matrix span $\mathbb Q^3$.
In fact, a slightly stronger statement is true : note that only  the first,second and fourth columns were used to deduce that the column span is $\mathbb Q^3$. Therefore, if you omit the third column of $B$ (that is, create a new matrix which is now $3 \times 3$ with the third column removed), it's columns would still have spanned $\mathbb Q^3$. This would not be true if you would have omitted the fourth column, though.


Python3 check if string is a specific type of list expression(without eval)

Question: A string, for example, string = "[["3", "4"], ["2", "5"]]".
Now I need to check if it is a list expression, with all elements being lists(e.g. ["3","4"]) that contains two string in it.
Is there any simple ways to check that? (I'd prefer not using eval() for safety reason)
Comment: Well, this answer is from here :[How to convert string representation of list to a list?](https://stackoverflow.com/questions/1894269/how-to-convert-string-representation-of-list-to-a-list).You could get more details about that.
Comment: `isinstance(json.loads(string), list)`.Or `ast.literal_eval`
Comment: @jizhihaoSAMA Great! That answers my question. May you make a answer so I can accept it?
Comment: this is very clever solution, but be aware that your string might not always be json-like
Comment: @Tomerikoo Yes, for the `ast.literal_eval()` part; And no, for checking each element is a list with 2 string elements in it- but I think it's pretty easy after I know  how to safely convert the string to list.
Comment: Well, use `len` and something like `all(isinstance(s, str) for s in sublist)`... Anyway your question is too broad. If you are able to convert to a list, ask a specific question about how to check if it has two lists of two strings
Comment: @Tomerikoo I will use `all` and list conprehension for that undoubtedly.
Answer: You can use ast.literal_eval() to  make it a list.
Docs for ast.literal_eval():

Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.

Code for ast.literal_eval():
import ast

l = ast.literal_eval('[["3", "4"], ["2", "5"]]')

Or you could also use json.loads() (usually used for loading JSON):
Docs for json.loads():

Deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object using this conversion table.

Code for json.loads():
import json

l = json.loads('[["3", "4"], ["2", "5"]]')

To check if each element is a list you can use:
def checkEachElementIsList(l):
    for elem in l:
        if type(elem) != list:
            return False
    return True

Or you could use:
def checkEachElementIsList(l):
    return all(type(elem) is list for elem in l)

Comment: Well you basically implemented the [`all`](https://docs.python.org/3/library/functions.html#all) function. Your `checkEachElementIsList` function is equivalent to `all(type(elem) is list for elem in l)`
Comment: `all` doesn't as well... It's called [short-circuiting](https://stackoverflow.com/questions/2580136/does-python-support-short-circuiting)
Comment: Check the docs... The implementation is exactly the same as your function
Comment: by the way, that `break` in the function is uneccessary since `return` already stops the function directly.
Comment: @Tomerikoo Yes but `checkEachElementIsList(l)` is sometimes slightly faster than `all(type(elem) is list for elem in l)` since it might not need to go through all them elements in the list
Comment: `all` is the same.
Comment: @jizhihaoSAMA But it will need to go through all the element in the list
Comment: @Acc-lab Now removed `break`
Comment: @Tomerikoo Fixed that as well now
Answer:
Now I need to check if it is a list expression, with all elements being lists(e.g. ["3","4"]) that contains two string in it.

import ast

string = "[['3', '4'], ['2', '5']]"

data = ast.literal_eval(string)
if isinstance(data, list):
    print('we have a list')
    for entry in data:
        if isinstance(entry,list):
            print('we have inner list')
            if len(entry) == 2:
                print('Inner list contains 2 items')

Comment: Thanks for that, but you forgot to check if the `entry`'s elements are strings.
Comment: I can do that part


Inserir PDO MySQL

Question: Bom, estou precisando fazer um inserção e utilizo PHP OO, porém, como devo fazer isto? Segundo o meu código está cadastrando, porém não está funcionando perfeito.
Estou fazendo algo de errado ?
Não da nenhuma mensagem de erro, somente fala que está cadastrado com sucesso!
        try {
                   $sql = $conn->prepare("INSERT INTO tbl_PESSOAS (
                                       COD_IDENT_IGREJ,
                                       TXT_NOMEX_PESSO,
                                       TXT_FONEX_PESSO,
                                       DAT_NASCI_PESSO,
                                       FLG_SEXOX_PESSO,
                                       FLG_IDENT_PESSO,
                                       TXT_EMAIL_PESSO,
                                       TXT_SENHAX_USUAR,
                                       TXT_ENDER_CEPXX,
                                       TXT_ENDER_BAIRR,
                                       TXT_ENDER_LOGRA,
                                       TXT_ENDER_NUMER,
                                       TXT_ENDER_COMPL,
                                       COD_IDULT_ATUAL,
                                       DAT_ULTIM_ATUAL)
                               VALUES (:COD_IDENT_IGREJ,
                                       :TXT_NOMEX_PESSO,
                                       :TXT_FONEX_PESSO,
                                       :DAT_NASCI_PESSO,
                                       :FLG_SEXOX_PESSO,
                                       :FLG_IDENT_PESSO,
                                       :TXT_EMAIL_PESSO,
                                       :TXT_SENHAX_USUAR,
                                       :TXT_ENDER_CEPXX,
                                       :TXT_ENDER_BAIRR,
                                       :TXT_ENDER_LOGRA,
                                       :TXT_ENDER_NUMER,
                                       :TXT_ENDER_COMPL,
                                       :COD_IDULT_ATUAL,
                                       :DAT_ULTIM_ATUAL)");

        $collection = array(
            'COD_IDENT_IGREJ' => $codIgreJ,
            'TXT_NOMEX_PESSO' => $lbl_NOME,
            'TXT_FONEX_PESSO' => $lbl_TELEFONE,
            'DAT_NASCI_PESSO' => $dte_ANIVERSARIO,
            'FLG_SEXOX_PESSO' => $lbl_SEXO,
            'FLG_IDENT_PESSO' => $lbl_FLAG_IDENT,
            'TXT_EMAIL_PESSO' => $lbl_EMAIL,
            'TXT_SENHAX_USUAR' => $lbl_SENHA,
            'TXT_ENDER_CEPXX' => $lbl_CEP,
            'TXT_ENDER_BAIRR' => $lbl_BAIRRO,
            'TXT_ENDER_LOGRA' => $lbl_RUA,
            'TXT_ENDER_NUMER' => $lbl_NUMERO,
            'TXT_ENDER_COMPL' => $lbl_COMPLEMENTO,
            'COD_IDULT_ATUAL' => $lbl_COD_ID,
            'DAT_ULTIM_ATUAL' => $lbl_NOW
        );

        $sql->execute($collection);
        /* $UltAiAdd = $conn->lastInsertId();

          $sql2 = $conn->prepare("INSERT INTO tbl_PESSOA_CELULA VALUES ( COD_IDENT_PESSO =  :COD_IDENT_PESSO, COD_IDENT_CELUL = :COD_IDENT_CELUL, FLG_IDENT_PESSO = :FLG_IDENT_PESSO, "
          . "COD_IDULT_ATUAL = :COD_IDULT_ATUAL, DAT_ULTIM_ATUAL = :DAT_ULTIM_ATUAL)");
          $sql2->bindParam(":COD_IDENT_PESSO", $UltAiAdd);
          $sql2->bindParam(":COD_IDENT_CELUL", $codCel);
          $lbl_FLAG_PE = 'M';
          $sql2->bindParam(":FLG_IDENT_PESSO", $lbl_FLAG_PE);
          $sql2->bindParam(":COD_IDULT_ATUAL", $lbl_COD_ID);
          $sql2->bindParam(":DAT_ULTIM_ATUAL", $lbl_NOW);

          $sql->execute(); */
    } catch (Exception $exc) {
        error_log($exc->getMessage());
        echo "058"; //Erro no cadastro.
    }
    echo "057"; //Cadastrado com sucesso!

Comment: O que não está funcionando perfeito, pode nos mostrar?
Comment: Simplesmente não da nada. Não acusa erro, porem quando vou a tabela de dados ela não esta cadastrada.
Comment: em vez de usar bindParam, experimente passar tudo como array direto no execute: `$collection[] = ['COD_IDENT_PESSO", $UltAiAdd]; $sql->execute($collection);`
Comment: É que o bom bindParam vc tem que tratar o tipo do dado.
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/27345/discussion-between-renan-rodrigues-and-ivan-ferrer).
Comment: vc precisa fazer o PDO imprir o erro ... `$sql->execute() ? print 'sucesso' : print_r($sql->errorInfo());` faça o mesmo para `$sql2`
Comment: Da uma olhada la
Comment: Não entendo de php, mas eu faria o inser assim:`"INSERT INTO tbl_NomedaTabela (campo1, campo2 VALUES (:valor1, :valor2)"`
Comment: faltou parentesse no `$sql->errorInfo()` ... eu esqueci de colocar.
Comment: @rray não está funcionando o comando.
Comment: Preciso que o erro apareça no console, como ficaria ?
Comment: Como tem dois inserts uma possibilidade do é de integridade referencial, o valor inserido(id) na segunda tabela não existe pq o primeiro insert falhou seja por uma restrição ou qualquer outro motivo.
Comment: Se esta chamando o esse insert via ajax, vc precisa pegar o retorno do ajax e dar um `console.log()` no seu javascript.
Comment: o `$sql->errorInfo()` retornou alguma mensagem?
Comment: Não teve nenhum log, continuou da mesma maneira.
Comment: Esse erro diz que existem mais colunas que valores no insert, deve ter algum placeholder que errado.
Answer: O problema é que você estava misturando a estrutura de UPDATE com a de inserção da query:
Para insert use:
INSERT INTO TABELA (campo1, campo2) VALUES (:campo1, :campo2)

Para update use:
UPDATE TABELA SET campo1=?, campo2=? WHERE campo_where:campo_where

    $stmt = $conn->prepare("INSERT INTO tbl_PESSOAS (
                                           COD_IDENT_IGREJ,
                                           TXT_NOMEX_PESSO,
                                           TXT_FONEX_PESSO,
                                           DAT_NASCI_PESSO,
                                           FLG_SEXOX_PESSO,
                                           FLG_IDENT_PESSO,
                                           TXT_EMAIL_PESSO,
                                           TXT_SENHAX_USUAR,
                                           TXT_ENDER_CEPXX,
                                           TXT_ENDER_BAIRR,
                                           TXT_ENDER_LOGRA,
                                           TXT_ENDER_NUMER,
                                           TXT_ENDER_COMPL,
                                           COD_IDULT_ATUAL,
                                           DAT_ULTIM_ATUAL)
                                   VALUES (:COD_IDENT_IGREJ,
                                           :TXT_NOMEX_PESSO,
                                           :TXT_FONEX_PESSO,
                                           :DAT_NASCI_PESSO,
                                           :FLG_SEXOX_PESSO,
                                           :FLG_IDENT_PESSO,
                                           :TXT_EMAIL_PESSO,
                                           :TXT_SENHAX_USUAR,
                                           :TXT_ENDER_CEPXX,
                                           :TXT_ENDER_BAIRR,
                                           :TXT_ENDER_LOGRA,
                                           :TXT_ENDER_NUMER,
                                           :TXT_ENDER_COMPL,
                                           :COD_IDULT_ATUAL,
                                           :DAT_ULTIM_ATUAL)");

$collection = array(
  ':COD_IDENT_IGREJ' => $codIgreJ,
  ':TXT_NOMEX_PESSO' => $lbl_NOME,
  ':TXT_FONEX_PESSO' => $lbl_TELEFONE,
  ':DAT_NASCI_PESSO' => $dte_ANIVERSARIO,
  ':FLG_SEXOX_PESSO' => $lbl_SEXO,
  ':FLG_IDENT_PESSO' => $lbl_FLAG_IDENT,
  ':TXT_EMAIL_PESSO' => $lbl_EMAIL,
  ':TXT_SENHAX_USUAR'=> $lbl_SENHA,
  ':TXT_ENDER_CEPXX' => $lbl_CEP,
  ':TXT_ENDER_BAIRR' => $lbl_BAIRRO,
  ':TXT_ENDER_LOGRA' => $lbl_RUA,
  ':TXT_ENDER_NUMER' => $lbl_NUMERO,
  ':TXT_ENDER_COMPL' => $lbl_COMPLEMENTO,
  ':COD_IDULT_ATUAL' => $lbl_COD_ID,
  ':DAT_ULTIM_ATUAL' => $lbl_NOW
);
$conn->execute($stmt, $collection);
$UltAiAdd = $conn->lastInsertId();

Comment: Acho que a forma de declarar o array abreviado foi no [5.4](http://php.net/manual/en/pdo.errorinfo.php)
Comment: Tentarei daqui a pouco, eu posto o resultado, obrigado por enquanto.
Comment: [Mon Aug 24 10:55:39 2015] [error] [client 192.168.1.105] PHP Parse error:  syntax error, unexpected '[' in /opt/lampp/htdocs/renan/pdo_acao.php on line 47, referer: http://127.0.0.1:58889/http-services/emulator-webserver/ripple/userapp/x/C/Users/hotsystems/AppData/Local/XDK/xdk-scratchdir/b9796bb6-a6c6-4479-94a3-7154a6043f83/platforms/android/assets/www/index.html
Comment: Deu este erro...
Comment: Atualizei a pergunta, de uma olhada la.
Comment: @RenanRodrigues, desculpe, havia um erro, veja se funciona agora. O values estava duplicado de forma errada.
Comment: [Mon Aug 24 11:37:52 2015] [error] [client 192.168.1.105] PHP Parse error:  syntax error, unexpected '[' in /opt/lampp/htdocs/renan/pdo_acao.php on line 47, referer: http://127.0.0.1:58889/http-services/emulator-webserver/ripple/userapp/x/C/Users/hotsystems/AppData/Local/XDK/xdk-scratchdir/b9796bb6-a6c6-4479-94a3-7154a6043f83/platforms/android/assets/www/index.html
Comment: Mude para o `array()` tradicional. e tente novamente.
Comment: Estava faltando alguns campos, conforme @rray apontou.
Comment: Teste e veja se parou de dar erro.
Comment: Pronto, porem agora voltou o problema de não cadastrar.
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/27353/discussion-between-ivan-ferrer-and-renan-rodrigues).
Answer:
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in

Significa que no insert existem mais colunas especificadas do que valores, no caso você tem um bind que não está mapeado para um coluna que é :TXT_FONEX_PESSO
Comment: Mas o erro não é este pois eu consertei e conitnua
Comment: Continua a mesma mensgam de erro? @RenanRodrigues
Comment: sim. o erro do log é o memso
Comment: Atualizei novamente e o erro continua o que poderia ser ? Será que há alguma forma mais fácil para mim desenvolver este insert ? O interessante é que o select funcionou perfeitamente.
Comment: Tem um bind que está `XT_SENHAX_USUAR`, parece que faltou um `T` antes. @RenanRodrigues

Inserir PDO MySQL


SSL Enabled site refusing connections

Question: I am attempting to encrypt my site using SSL. I created a self-signed certificate (in the interim) and am attempting to integrate it into my nginx server.
I placed the certificate into the main nginx.conf file, as I have multiple domains (dev and beta).
# SSL
ssl_certificate     /srv/ssl/nginx.pem;
ssl_certificate_key /srv/ssl/nginx.key;
ssl_session_cache   shared:SSL:10m;
ssl_session_timeout 10m;

In the server block, I have the following:
+server {
+   listen 80;
+   server_name dev.DOMAIN.com;
+
+   location / {
+       rewrite ^ https://$server_name$request_uri permanent;
+   }
+}

server {
+   listen 443 ssl;
    server_name dev.DOMAIN.com;

    access_log /var/www/dev/logs/access.log;
    error_log /var/www/dev/logs/error.log;
    root /var/www/dev/public_html;
+   keepalive_timeout   70;

    location / {
        index  index.html index.htm index.php;
    }

    // [.. A couple other rewrite statements here ..]
}

I made the same changes to the server block for my beta build, but while it works in the dev build, I am receiving Connection Refused errors on the beta build.
I've verified that both dev and beta files are identical (except for the subdomain).
The code on both builds is identical as well. Neither the error log nor the access log show any entries.
I honestly have no idea where to go next...!
Comment: `julian@julian-work:~$ telnet 22.214.171.124 443 \ Trying 22.214.171.124... \ Connected to 184.108.40.206.`
Comment: Can you define what "refusing connections" means?  Is the port closed?  Is the SSL connection returning an error?
Comment: Hi @AndrewM., when I try to access the site, Firefox says that a connection cannot be established. When I try to `wget` the site, the message "Connection Refused" is returned. I believe it is an nginx erorr?
Comment: I can't imagine the port would be closed, as both `dev` and `beta` are hosted on the same machine. SSL on the dev build works, while the beta doesn't.
Comment: Working down the OSI stack, is the port open and accessible?  Try telnetting to 443 and see if you're able to establish a connection (note that windows telnet doesn't necessarily open a connection even though it may look open on the console).
Comment: Can you verify that "dev.DOMAIN.com" and "beta.DOMAIN.com" are indeed the same machine, and that there's nothing forgotten in your /etc/hosts? "Connection refused", when coming from wget, normally means that the port is closed.
Comment: I'm with @AntonisChristofides on this one; connection refused is an issue with connecting, not with SSL.  Make sure you're accessing the machine you think you are, and also try accessing it from another machine (i.e., not localhost).
Comment: Thanks for the comments - I'm almost positive (although by this point, perhaps I've gone bug-eyed) that the two are on one machine, since I set up this machine myself. Perhaps I miswrote an IP address, but I'm sure I double checked that as well. They are both on `184.108.40.206`
Comment: I restored the old `server` blocks for beta, and discovered upon `wget` that it resolved to its CloudFlare DNS IP. *headdesk*. This must be why. My dev builds bypass the CloudFlare network completely.
Answer: Note: The answer pertains specifically to my issue. If you are experiencing a similar problem, please read the comments for the original question, as they are probably more relevant
As it turned out, CloudFlare interferes with SSL websites unless they are specifically configured to be as such. For my case, the dev subdomain was set to bypass the CloudFlare network completely, while beta was "accelerated", which caused the IP to shift to CloudFlare's IP.
Cloudflare does offer SSL support for the free accounts if you create a subdomain named "ssl". Further support requires the pro version (~$20/mo).

SSL Enabled site refusing connections


error: The following untracked working tree files would be overwritten by merge: main/projects/banking_web/WebContent/WEB-INF/security/RIBprivate.key

Question: while trying to git pull , facing the issue. I followed some git commands,
git clean -f -d
git reset --hard
git fetch --all
But still encountered the same issue.
expectations is to pull the latest code in my local.
Answer:
Solution:
Go to the specified path till security, Delete the RIBprivate.key
file . do a mvn clean install, it will resolve the issue.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Best strings for heavy metal (I love distortion)?

Question: I just bought a Fender Squier. I went to buy some strings and there were so many choices. My friend has just got some Ernie Ball heavy bottom skinny top, and he says they're supposed to be close the the best. My neighbor says to get some Ernie Ball cobalt slinky, and he says they are really good and will work best with the magnets in my pickups and will have no hum. I don't have much hum right now anyways though.
My goal: Get some strings that will get me the best distortion sound. I am a beginner, So i'd like help finding the best for tone, but also maybe a suggestion that is still really good for tone but a little easier on my fingers, please give me both suggestions.
My guitar as it is sounds great with distortion, I'm just looking to optimize it, get the best growly distortion out of it. It needs new strings anyway.
Comment: The benefit of the skinny top heavy bottom string sets is that they will give you a "chunky" bass, which is typically desired for heavy metal, but not be too cumbersome when trying to solo on the high strings, due to the easier action of light gauge strings. Heavy strings have a stronger bass response, lighter strings are easier to play on. It's a tradeoff.
Comment: If you are looking for a particular sound and have an example (a guitarist you like) then see what they do. I stumbled onto 14-65 sized strings this way and I love 'em. I play mostly death metal and the change to thicker strings was tricky to get used to but I find I get a more solid sound. I also found that if you play on different string sizes you add a lot of nuances to your playing style (your understanding of the keyboard will grow faster). BUT IN THE END, to worry about this when learning is probably not nearly as important as learning to properly mute or EQ yourself.
Comment: Neil - this question may be popular, but it is not a good question. There is no definitive answer - some folks say thicker strings, some say thinner, I say it doesn't matter but go with what you like. The OP is also asking for brand recommendations - which is a no-no, in fact I'll edit that bit out.
Comment: Ernie ball beefy slinkys are great, optimal for detuning strings, i play anywhere from drop D to Drop A and these strings are great
Comment: cmon guys give the man some upvotes for a popular question.
Answer: There is a lot of snake oil involved when it comes to guitar strings. I would say there are no special string technology that make a remarkable difference in sound, no matter what the manufacturers are claiming.
I would recommend to first figure out what gauge you like, using a well known brand like D'Addario or Ernie Ball. Use their "normal" sets (nickel wound), you probably don't want e.g. flatwounds. They will sound good enough. Experiment with different gauges. Then when you found a gauge you like you can try the "magic" variants...
Another note is: what pickup type is your guitar equipped with? Fender usually have single coils, in that case you might not get the distorted sounds you are looking for.
String technology comes late in the chain of importance for the sound. Pickup type and amplifier are orders of magnitude more important. Decreasing the gain goes a long way in many cases.
Comment: Geeky - the strings are almost irrelevant, and as a beginner entirely irrelevant to you. Some metal players use thick strings, some use thin strings. Meaningful is correct here - and you started with the rudeness. Try being polite and listening to people who are trying to help you.
Comment: So basically, it would be a waste of my money for me (as a beginner) to be buying the more expensive strings? I get good distortion with my amp/pedal, I had my neighbor play it with his guitar before I got the squire. I had a cheap harmony that went out of tune super fast and sounded like crap, and I got the squire today.
Comment: I would say so.
Comment: Well, I'd have to say you don't know what you're talking about then.
Comment: @GeekyDewd: Is the issue that you are not getting the sounds out of your amp with your guitar that rad neighbor dude with the cobalt strings got? If you're not satisfied with the sound you got now, different strings than vanilla Ernie Balls/D'Addarios will not make a huge difference. But good luck in the string jungle...
Comment: I didn't come off rude first, I simply told him that there are different types of strings and there is no way they are all the same, or there wouldn't be so many choices.
Comment: @GeekyDewd: When I said their "normal" sets, I was referring to the ones you get in a music store when just asking for a set of electric guitar strings. Those are nickel wound for both Ernie Ball (Slinky series) and D'Addario (EXL series). That was unclear in my answer. I do know what I'm talking about, I've been playing guitar a great deal longer than you have lived, and I have tried a lot of the fancy new strings and formulas, and came to the conclusion that there's not much to it. Relax and focus on playing instead of equipment at this stage.
Comment: So medium (regular gauge) nickel strings, is what you're suggesting?
Comment: @GeekyDewd: Yes. 10-46 is probably a good starting point, then go up or down depending on how they feel.
Answer: I have played .012+ on my electric. My #1 guitar now has .008s. I'm happy with this, but that's me.
My suggestion to all new guitarists is medium. On acoustic, that's about .012s and on electric, .010. (Guitar strings are usually judged by the gauge of the lightest string.)
There are people who rep for heavier gauge strings, saying they sound better and stay in tune better. That's fine, but the higher tension can tend to hurt your fingers, especially if you haven't worked out how hard to fret the notes.
There are people who rep for lighter gauge strings, saying they bend easier and don't hurt your fingertips. That's fine, but the lower tension can tend to cause you to bend when you don't intend to, making you sound out of tune, especially if you haven't worked out how hard to fret the notes.
You might end up loving bridge cables. You might like angel-hair strings. I don't know what you'll grow to love, but I say buy mediums until you can explain why you want to go higher or lower.
I'd also suggest that, as a beginner guitarist, you likely have no idea what "tone" means in terms of guitar strings. It's such a heavily-overloaded term that I don't think any two guitarists use it to mean the same thing. Could be bass/treble, brightness, sustain, signal or something else. Use mediums from a reputable brand, and stay with that type of string (not necessarily that set, they do wear out) until you can explain what you're looking for and not hearing.
Your strings have nothing to do with hum. Your pickups, your guitar's shielding, the quality of your cables, pedals and amp all have something to do with hum.
Ernie Ball Slinkys are perfectly good. There are brands some like better, and that's fine, but many of the best guitarists out there play Slinkys, and even if they're getting them free, if they didn't sound good, those guitarists would go to other brands. If you find your body chemistry makes your strings go dull quickly, try coated strings. There's only one string maker whose products I would suggest you avoid, and to be honest, they were violin strings, which are played differently than guitar strings.
To repeat and summarize: stick with .010s from a reputable brand until you know why you want to change.
Comment: I very much like your answer, and will likely pick yous. But I hope to get a more specific answer (if possible) by being more clear. Firstly, I understand that the majority of tone depends on the guitar and amp (and any pedals in between). But I am also trying to get an optimal heavy distortion sound. Here is what I want (again I understand this guy has extremely high end pickups, etc) http://youtu.be/kwxbihuTZPY?t=28s The distortion starts at 1:00 But I like the high notes (with his flanger or whatever it is). It is very clear he has expensive gear, and is using effects.
Comment: MORE: I get good distortion, but the strings are old and need to be replaced anyways. I really like the chugging (palm muting) in that song.
Comment: Heavier strings can be tuned down a step without getting too floppy.  Sometimes the lower pitch helps that "heavy" distortion sound.
Comment: @markrages I recently found strings specifically for tuning low. I like to play mostly in drop-b but also drop-a and they're really great for not having that bending-all-over-the-place sloppiness you get when you take your light gauge strings down to drop-a. The only strings like this I've found have all been heavy gauge.
Comment: Jasper what strings are those?
Comment: Some have heavy low strings and light high strings, so that you can drop the low strings. They have different names, but if the low string on a medium set is .042,  you could buy a .046 or .048 single string to swap out the low string so it isn't too floppy.
Answer: From an engineering point of view, if you are going for heavy distortion, I'd lean towards a lighter gauge.  They will have less disharmonicity (overtones that are somewhat off-pitch) and since distortion adds a number of frequency differences to the results, disharmonicity in combination with distortion washes out the pitches.
It's not plausible that an electric guitar is equipped with nylon strings.
As a beginner, you should make it a habit to practice without distortion most of the time.  Distortion masks a lot of mistakes and uncleanliness, but that does not mean that the audience, not distracted by having to play themselves, will not notice.
Of course you need to recheck your results with distortion as well, particularly when improvising: since distortion adds a lot of non-fundamental harmonics, one usually needs to work with significantly simpler chords and harmonies in order not to end up with total mud.
Personally I think that the guitar builders are making a mistake by not offering ganged pickups and pedals (just think of the equipment they could sell!): if you'd pick up every string separately and route it through a separate distortion channel (possibly with a separate control for determining some amount of bleedover between channels), then you could use distortion on more complex chords/harmonies, basically similar to what you get if you play "distorted guitar" samples through a keyboard rather than putting a single distortion pedal on "undistorted guitar" keyboard play.
Comment: You can get guitars with every string on a separate channel, but you pay through the nose for it, which is why it doesn't happen more :-)
Comment: Sure, but it's pointless if you don't get matching pedals that do the _same_ operation on six channels in parallel.  If I have six separate volumes and distortion depths to handle, this is useless, particularly so in a live setting.  I think the manufacturers are selling the separate channels mainly for the idea of doing _different_ things with the separate channels.  But the real benefit with distortion would be doing the _same_ thing to the separate channels _without_ getting "intermodulation" distortion drowning out everything else.
Comment: If you were going to do it, you would buy either six pedals or run a rack module application to do this. It is  straightforward, but as I mentioned, it is expensive.
Comment: Good point with not always playing with distortion turned on. Took me a few years to realize how crappy I was playing... Whenever I have trouble with a riff I turn off the distortion, slow down, and see how well I can actually play the riff.
Comment: Good thinking about the inharmonicity part – but actually the argument doesn't quite work out, because thinner bass strings would need to be driven to higher amplitudes where the oscillation becomes nonlinear, giving you effectively _more_ inharmonicity (and even the fundamental doesn't stay consistent). With fat strings you can keep the amplitude low and still have plenty of output, also you can (palm mute etc.) better concentrate the energy into a few lower harmonics, where inharmonicity doesn't come very much into effect yet. Most harmonics you hear in the end are from distortion itself.
Answer: As Meaningful says, there is no "best"

Some have longer resistance to rusting
Some are tougher and less likely to snap (but may be more likely to wear your frets down)
Some hold their tone longer

Just get a common name set of strings and use them. If you want heavy distortion sounds, you should focus on the distortion pedal you want. Along with a good pre-amp, you can get a really heavy sound.
I have been gigging for 26 years or thereabouts and basically use Ernie Balls, D'Addarios and Elixirs. I have tried various others (most notably some fluorescent orange strings - but they were terrible) and none offer anything noticeably different. I do use a fair amount of technology around the distortion and amplification of my sound though (links in my profile if you want to hear)
Comment: Nobody is going to suggest something that is better for metal, rather than clean... I mean come on!!! I think my question was pretty clear!
Answer: If your strings are indeed nylon, you'll get very little sound through the amp., let alone distortion. There is no noticeable hum with single coil pups on Fender/Squier Strats. To get the sort of sound you are after,this probably isn't the guitar you need.One with humbuckers will give a fatter sound. Yes, use a distortion pedal, but the sound will be better with , say, a Les Paul type guitar.
The strings will make only a little difference to your sound, it's far more important to find strings that suit you - and your guitar.Some like really heavy and some hate them. Me included ! If you're riffing a lot, heavy bottoms may help a little, but come to soloing, and you may well need lighter gauge , especially on the top 3 or 4.
If you're trying to play full chords with lots of distortion, you will realise that actually it sounds not that good. Overdrive accentuates the harmonics of each string played, and on full chords, they clash with each other to make an awful sound.
Get used to the guitar, try different gauge strings for a month at a time, and when you find some you like, then start to look at the sound with a more experienced eye.By then, you may be considering that the present guitar isn't what you needed anyway. Buy a different one, and start all over again. When you have a good valve amp that can be overdriven, or even a half decent tranny amp, you'll get good sounds without using the pedal, although using it as well will give you lots of differing distortion.
Answer: To actually answer your question, which is "Best strings for heavy metal (I love distortion)?", most metal bands use higher gauge strings across all the brands, i.e. .10 gauge and above, its not so much about the brand.
Hybrid gauges are also popular. This is where the "lower strings" (tone wise, E, A, D), are thicker than they would usually be for a matching set.
See how Alexi uses a set with .10 on the high e, but .56 on the low e compared to Synyster Gates:
http://www.uberproaudio.com/who-plays-what/210-children-of-bodom-alexi-laihos-guitar-gear-rig-and-equipment
- Alexi now has his own Signature DR electric strings with his picture on the box, 10-56 gauge.
http://www.uberproaudio.com/who-plays-what/188-avenged-sevenfold-synyster-gates-guitar-gear-rig-and-equipment
- Ernie Ball strings, gauged .010-.052. ('skinny top, heavy bottom' strings)
Alexi is using a hybrid gauge, meant to give more weight to the heavy riffing on the E,A,D strings.
Answer: Just go with a standard set. You will not be able to hear the difference with too much distortion I believe. Just pick a standard set of .009 to .042 since that is easy to handle... It's all about personal preferences. Don't pick strings because they should sound better. Pick them because you personally think they sound better and most importantly, they feel right! The feeling is the number 1 concern in my humble opinion. If you can't bend a .010 string, but you want fat sound and therefore you pick a standard .011 set, that's completely wrong...
Answer: I will say that i know zero about strings, but I do know about density vs. mass, and i am 100% sure the trick is behind the difference between those two. something tells me more density is going to be chunkier while less density will be brighter.
Comment: Kevin, unlike an online discussion forum, here we require posts to be an answer to the question. Please read [answer] for some guidance.
Comment: Since you "know zero about strings", you may not realize that there are different alloys used in acoustic strings that affect acoustic tone, and that there are different alloys used in electric strings that affect both acoustic tone and electric tone; or that wound strings may be wound on either round or hexagonal cores; or that strings may be roundwound, flatwound, or groundwound. All of these things affect tone, some quite significantly, and apart from string gauges.


Testing difference in (dependent) slopes from a multiple regression?

Question: Is there a formal test or an equation for comparing slopes from a multiple regression? That is, the estimates are not independent.
For example,
$$Y = β_0 + β_1X_1 + β_2X_2 + ε$$
Is there a formal test or equation for testing $β_1 - β_2$?
Comment: Do you mean $\beta_1 - \beta_2$?
Comment: yes, I meant B1 - B2
Comment: @NickMichalak I think you mis-edited it
Answer: This linear model can be redefined to be
$$
Y = \beta_0 + (\beta_1 - \beta_2) \frac{X_1 - X_2}{2} + (\beta_1 + \beta_2) \frac{X_1 + X_2}{2} + \epsilon
$$
So, replacing your data $X_1$ and $X_2$ with $(X_1-X_2)/2$ and $(X_1+X_2)/2$, your linear model will be directly sensitive to $\beta_1-\beta_2$ and their sum $\beta_1 + \beta_2$.
One caution -- the result result will be highly dependent on the scales of $X_1$ and $X_2$.
For example, if $X_1$ is generally a thousand times greater than $X_2$, $\beta_1$ could be a thousand times smaller than $\beta_2$.
You'll likely want to "normalize" the two datas somehow to make sure that $\beta_1-\beta_2$ is meaningful -- making sure that $X_1$ and $X_2$ have the same units, if they are dimensionful, or rescaling them to have unit variance.
Comment: Thank you @jwimberley! I have one more question then: If I ran this regression you defined above, would I be looking at the significance test for β1−β2?
Comment: The parameter corresponding to $(X_1-X_2)/2$ would be $\beta_1-\beta_2$, so its significance would the the two-sided significance test for the difference, yes.
Comment: Clever, I hadn't thought of this before, and I'm actually putting this into practice right now (+1)


jax-ws redirect http / https

Question: I am having problem with jax-ws making it work if the server return 301 on http to https. I got an exception, and after debugging it with charles it seems that the redirect doesn't work. I also noticed that there is some trick for http to https[*], but i am not sure if it still apply to java8
That's the pseudo-code that i would like to use with a dirty fix that i found online
<code>    TestImplService service = new TestImplService();
    Test test = service.getTestImplPort();
    Map<String, Object> tmp = ((BindingProvider) test).getRequestContext();

    /*dirty fix*/
    tmp.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, tmp.get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY).toString().replace("http:", "https:")
    );

    test.dosomething();
</code>
Replacing http with https work, but i am not 100% sure that's the correct way.
Let's suppose that the server decide to stop to support https, disable the 301 for http, then my fix won't work anymore.
Can i force the follow redirect in another way?
[*] https://docs.oracle.com/javase/6/docs/technotes/guides/deployment/deployment-guide/upgrade-guide/article-17.html
Comment: Ideally enforcing `http` to `https` should be done on `web-server` like `apache` or `nginx` etc, not in application layer. would like to understand, why you are doing like that, any particular reason?
Comment: unfortunately i have to call a remote service where i have no control of. i already asked to change the http->https but obviusly thy are deaf from this ear... if you know what i mean...
Comment: Instead of `apache`, you could use `nginx`, I think it has body rules support.
Comment: i am the consumer of the webservice, not the producer.
Answer: BindingProvider class BindingProvider.ENDPOINT_ADDRESS_PROPERTY property is usable for change endpoint URL; Sometimes HTTPS connection ended with network switches/routers. Therefor application server cannot realize the path of https.
<code>service = new ....(url, SERVICE_NAME);
port = service.get...BasicHttpEndpoint();
BindingProvider provider = ((BindingProvider) port);
Map<String, Object> map = provider.getRequestContext();
String current = map.get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY).toString();
map.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, current.replace("http:", "https:"));
</code>

jax-ws redirect http / https


boost::asio async_read guarantee all bytes are read

Question: I have a server that receives a compressed string (compressed with zlib) from a client, and I was using async_receive from the boost::asio library to receive this string, it turns out however that there is no guarantee that all bytes will be received, so I now have to change it to async_read.  The problem I face is that the size of the bytes received is variable, so I am not sure how to use async_read without knowing the number of bytes to be received.  With the async_receive I just have a boost::array<char, 1024>, however this is a buffer that is not necessarily filled completely.
I wondered if anyone can suggest a solution where I can use async_read even though I do not know the number of bytes to be received in advance?
void tcp_connection::start(boost::shared_ptr<ResolverQueueHandler> queue_handler)
{
    if (!_queue_handler.get())
        _queue_handler = queue_handler;

    std::fill(buff.begin(), buff.end(), 0);

    //socket_.async_receive(boost::asio::buffer(buff), boost::bind(&tcp_connection::handle_read, shared_from_this(), boost::asio::placeholders::error));
    boost::asio::async_read(socket_, boost::asio::buffer(buff), boost::bind(&tcp_connection::handle_read, shared_from_this(), boost::asio::placeholders::error));
}

buff is a boost::array<char, 1024>
Answer: How were you expecting to do this using any other method?
There are a few general methods to sending data of variable sizes in an async manor:

By message - meaning that you have a header that defines the length of the expected message followed by a body which contains data of the specified length.
By stream - meaning that you have some marker (and this is very broad) method of knowing when you've gotten a complete packet.
By connection - each complete packet of data is sent in a single connection which is closed once the data is complete.

So can your data be parsed, or a length sent etc...
Answer: Use async_read_until and create your own match condition, or change your protocol to send a header including the number of bytes to expect in the compressed string.
Answer: A single IP packet is limited to an MTU size of ~1500 bytes, and yet still you can download gigabyte-large files from your favourite website, and watch megabyte-sized videos on YouTube.
You need to send a header indicating the actual size of the raw data, and then receive the data by pieces on smaller chunks until you finish receiving all the bytes.
For example, when you download a large file over HTTP, there is a field on the header indicating the size of the file: Content-Length:.
Comment: @b.g. read the code and question again: it has nothing to do with TCP parsing. The user needs to know if the data from recv() is all what the sender sent.
Comment: @b.g. Your comment is not true, just go and read the accepted answer and you'll see that item 1 is a general case for Content-Length.


Match Dates and Count in Entity Framework

Question: I have two tables:
create table dbo.Dates (
  Id int not null
    constraint Dates_Id_PK primary key clustered (Id),
  [DateValue] date not null
}

create table dbo.Posts (
  Id int identity not null
    constraint Posts_Id_PK primary key clustered (Id),
  Created datetime not null,
  Title nvarchar (200) not null
)

For these tables I have Date and Post entities.
How can I get a table that has the column DateValue from Dates and the number of Posts with that date.
I need to match the datetime Created value to the date DateValue.
Thank you,
Miguel
Answer: I assume your Posts have dates with times, so you'll have to truncate them to the date part (as in the Date property of a DateTime):
from d in context.Dates
select new {
             Date = d.DateValue,
             NrOfPosts = (from p in context.Posts
                 where EntityFunctions.TruncateTime(t.Created) == d.DateValue
                 select p).Count()
           }

Answer: you can use anonymous types. try the following snippet.
DateTime dateToMatch = GetDateToMatch();

using(YourEntities context = new YourEntities())
{
    var result = context.Dates.Where(d => d.DateValue == dateToMatch)
                              .Select(d => new { Date = d.DateValue, PostCount = d.Posts.Count() });
}

Comment: Maybe I explained myself wrong. I am looking for have a new tables with all Dates.DateValue and Posts.Cound ... Not a specific one.


How to filter entries from a list based on a criteria and get the index in Python?

Question: I have a list say list=[1,4,6,3,2,1,8] and I want to filter this list based on the condition that entry>3 and return the corresponding index.
So the output should be : [1,2,6] which corresponds to the values 4,6 and 8.
how to do this efficiently in Python?
Answer: You can use a list comprehension with enumerate.
l = [1,4,6,3,2,1,8] # you should not overwrite the list builtin
res = [i for i, x in enumerate(l) if x > 3]

Comment: [Try it online!](https://tio.run/##K6gsycjPM/7/P0fBViHaUMdEx0zHWMdIx1DHIparKLUYJJqpkJZfpJCpo1ChkJmnkJpXmptalFiSqpGjqZCZBhS0UzCO5Sooyswr0QDq0Pz/HwA)


Non-linear constrained problem transformation to equivalent un-constrained problem

Question: I have the following non-linear optimization problem:
min $f(x, y, z) = x + y + z$
s.t.
$x^2 + y = 3$
$x + 3y + 2z = 7$
Is there a way to transform this problem to an equivalent minimisation problem without any constraints?
I have a hunch that it has something to do with Lagrange multipliers but I really can't figure out how to start this one.
Thanks,
Louis
Answer: Guide:
We have $y=3-x^2$, that is whenever we see $y$, we can replace it by $3-x^2$.
Also, we can express $z$ as a function of $x$ and $y$.
Hence yes, we just have to perform a substitution to replace everything in terms of $x$.
The unconstrained problem is a quadratic minimization problem.


After querying DB I can't print data as well as text anymore to browser

Question: I'm in a web scripting class, and honestly and unfortunately, it has come second to my networking and design and analysis classes. Because of this I find I encounter problems that may be mundane but can't find the solution to it easily.
I am writing a CGI form that is supposed to work with a MySQL DB. I can insert and delete into the DB just fine. My problem comes when querying the DB.
My code compiles fine and I don't get errors when trying to "display" the info in the DB through the browser but the data and text doesn't in fact display. The code in question is here:
<code>print br, 'test';

my $dbh = DBI->connect("DBI:mysql:austinc4", "*******", "*******", {RaiseError => 1} );
my $usersstatement = "select * from users";
my $projstatment = "select * from projects";

# Get the handle
my $userinfo = $dbh->query($usersstatement);
my $projinfo = $dbh->query($projstatement);

# Fetch rows
while (@userrow = $userinfo->fetchrow()) {
    print $userrow[0], br;
}

print 'end';
</code>
This code is in an if statement that is surrounded by the print header, start_html, form, /form, end_html. I was just trying to debug and find out what was happening and printed the statements test and end. It prints out test but doesn't print out end. It also doesn't print out the data in my DB, which happens to come before I print out end.
What I believe I am doing is:

Connecting to my DB
Forming a string the contains the command/request to the DB
Getting a handle for my query I perform on the DB
Fetching a row from my handle
Printing the first field in the row I fetched from my table

But I don't see why my data wouldn't print out as well as the end text. I looked in DB and it does in fact contain data in the DB and the table that I am trying to get data from.
This one has got me stumped, so I appreciate any help. Thanks again. =)
Solution:
I was using a that wasn't supported by the modules I was including. This leads me to another question. How can I detect errors like this? My program does in fact compile correctly and the webpage doesn't "break". Aside from me double checking that all the methods I do use are valid, do I just see something like text not being displayed and assume that an error like this occurred?
Comment: Is `fetchrow` a valid method? Some `DBD::xxx` implementations only support more qualified methods like `fetchrow_array` and `fetchrow_hashref`.
Comment: For that matter what does the `query` method come from? I don't see it in the `DBI` spec.
Comment: use $dbh->do() for inserts and updates, and use fetchrow_array and fetchrow_hashref for selects or use the prepare(), execute() and looped fetch.   For more, go reread perldoc DBI
Comment: Um. I am using DBD::mysql and DBI. I ought to double check the methods in those. That is something I overlooked and didn't consider. Will let you know if this was the problem.
Answer: Upon reading the comments, the reason your program is broken is because query() does not execute an SQL query.  Therefore you are probably calling an undefined subroutine unless this is a wrapper you have defined elsewhere.
Here is my original posting of helpful hints, which still apply:

I hope you have use CGI, use DBI, etc... and use CGI::Carp and use strict;
Look in /var/log/apache2/access.log or error.log for the bugs
Realize that the first thing a CGI script prints MUST be a valid header or the web server and browser become unhappy and often nothing else displays.
Because of #3 print the header first BEFORE you do anything, especially before you connect to the database where the script may die or print something else because otherwise the errors or other messages will be emitted before the header.
If you still don't see an error go back to #2.
CGIs that use CGI.pm can be run from a command line in a terminal session without going through the webserver.  This is also a good way to debug.


Snipping HTML with DOMDocument outputs invalid characters

Question: I'm using the DOMDocument class in PHP to snip out a few lines of text. The text here is a large block of HTML which was entered by a WYSIWYG editor.
The code I'm using to do is like this:
$body_string .= '
';

$domd = new DOMDocument();
$domd->encoding = 'utf-8';
libxml_use_internal_errors(true);
$domd->loadHTML(utf8_decode($post['content']));
libxml_use_internal_errors(false);

$domx = new DOMXPath($domd);
$items = $domx->query("//p[position() = 1] | //div[position() = 1]");

$body_string .= substr($items->item(0)->textContent, 0, 230);
$body_string .= '

But, when the string has special characters like the ellipsis or the curly quotes, they get turned into a question mark.
So a text like this:

We know, TED talks can sometimes feel a little… overblown. While there
  are loads of great talks; some of them go nowhere and don't seem to
  add much to your life at all. To make things worse… there are a lot of
  TED talks and it's hard to tell

turns into this:

We know, TED talks can sometimes feel a little? overblown. While there
  are loads of great talks; some of them go nowhere and don?t seem to
  add much to your life at all. To make things worse? there are a lot of
  TED talks and it?s hard to tell

This happens only if I use the DOMDocument class. Without it the characters don't get converted to the question marks.
How can I fix this? The HTML document already has a <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> in the
Comment: can you provide an example of this string that can replicate this problem of yours?
Comment: @Ghost I'm not sure what you mean... See the text above?
Comment: im trying to replicate this on my env, what i mean is  the contents of `$post['content']`. but anyways, only the thing that i can do here is to guess.
Comment: @Ghost See the quoted text. That is in the `$post['content']`
Answer: Can't seem to reproduce that one, instead try this workaround:
$body_string .= '
';

$domd = new DOMDocument('1.0', 'utf-8');
libxml_use_internal_errors(true);
$domd->loadHTML(mb_convert_encoding($post['content'], 'HTML-ENTITIES', 'UTF-8'));
libxml_clear_errors();

$domx = new DOMXPath($domd);
$items = $domx->query("//p[position() = 1] | //div[position() = 1]");

$body_string .= substr($items->item(0)->textContent, 0, 230);
$body_string .= '

Sample Output
Closest thing reproducible.
Comment: @maxxon15 yes basically the conversion is before feeding it into `->loadHTML`
Comment: Can you maybe explain what was I doing wrong? I still don't understand what I was doing wrong... :)
Comment: @maxxon15 what it basically did is first, since `->loadHTML()` defaults to `ISO-8859-1` it messes up those entities. so before loading them, the workaround is to convert them to html entities instead.
Comment: @maxxon15 there is a very eloquent answer here on SO regarding that part. i think its hakre's answer but i can't find the post. sorry if i cannot explain well as english isn't really my first language
Comment: Oh I see. So, merely setting the `$domd->encoding = 'utf-8';` won't work. I have to explicitly convert the html with the `mb_convert_encoding` function after that. Right?
Answer: Setting DOMDocument::encoding is only useful for changing the encoding when printing out the DOMDocument as a string, so won't have any effect here.
Similarly, setting 'utf-8' in the DOMDocument constructor has no effect, as it is only used when creating a new document from scratch, not when parsing an existing document.
The HTML parser needs to know what the encoding of the posted content is, like this:
$domd = new DOMDocument();
libxml_use_internal_errors(true);
$domd->loadHTML('<meta charset="utf-8">' . $post['content']);
libxml_use_internal_errors(false);


Quadratic terms in linear regression

Question: I've been making regression models for quite a while now, I am comfortable with the idea that $$y = \beta_0 +\beta_1x^2 \text{ is linear and } y =\beta_0 +\beta_1^2x \text{ is not}$$
but I've never really understood why that is. In my mind, we're assuming $\beta_1$ is a fixed number, so why can't we just say $\beta_{new} = \beta_1^2$ and go from there. Additionally, when would it come up that I have a quadratic regression coefficient? Overall, I'm really curious about why this matters at all.
Comment: In your example, it seems $\beta_{new}$ is being forced to be non-negative, so a regression method which could produce negative estimates might not work.
Answer: In general, linearity of some function is defined (see Wikipedia) by the function satisfying 2 conditions:

Additivity: $f(a+b)=f(a)+f(b)$
Homogeneity of degree 1: $f(ac) = cf(a) \quad \forall c$.

When speaking about linear regression model, the linearity is meant as a linearity in parameters ($\beta$).
So it can be seen that the function $\beta_0 + \beta_1 x^2$ satisfies the definition of linearity with respect to the parameter $\beta_1$, while the equation $\beta_0 + \beta_1^{2} x$ does not. In both cases, we don't care about the linearity with respect to $x$ or $x^2$, as these are simple some constants to us.
Answer: $\beta_1$ isn't fixed until we estimate it. Once we estimate it, we could, of course, square it, but then it would not work in the equation.
I can't think, off the top of my head, why you would want this (and some quick Googling was not effective), but it is sometimes the case that you want the parameter as an exponent  $y = \beta_0 + x_1^{\beta_1}$, I've see that. Here is an example from Penn State class Stat 462.
Wikipedia gives an example where $f(x, \beta) = \frac{\beta_1x}{\beta_2} + x$ that is apparently used in enzyme kinetics (I don't even know what "enzyme kinetics" is).
Comment: Your candidness is appreciated.
Answer: linear neural networks are an example where you generate polynomials in the coefficients.https://arxiv.org/abs/1312.6120.  In that paper they explain that though representationally equivalent to a linear regression, the optimisation is non convex and shows some of the same difficulties in optimisation (ie finding a solution) as nonlinear neural networks
Note linear neural networks are proposed in the paper as a way of studying the optimisation behaviour of (nonlinear) neural networks; they have the same representation power as linear regression.
So to answer your question, you cannot find the solution using standard least squares linear algebra when your coefficients are polynomials.
Note that if your coefficient is $\beta_1^2$ then it is forced to be positive, so in your example a solution may not even exist.

Quadratic terms in linear regression


(C++) IF Statements seem to simply be not working

Question: This code will only ever output the else statement, and I cannot figure out why. Of course I have tried entering 0, and it still returns using the else statement. The int seninel is defined because I was trying to use if (num = SENTINEL) to force it to execute, but it did not work.
#include <iostream>
using namespace std;

int main()
{
    int num;
    const int SENTINEL = 0;
    cout << "Enter a number";
    cin >> num;

    if (num = 0)
    {
        cout << "It equals 0";
        system("Pause");
        return 0;
    }
    else
    {
        cout << "it does not equal 0";
        system("pause");
        return 0;
    }

}

This is my first time using overflow and I am new to coding. Please forgive me if this post is not great. Ill reply to any questions promptly. Thank you for any potential help
Comment: Heed thy warnings ;-)
Comment: I don't have any error messages. The code compiles just fine. The only output I can ever get is the else statement though.
Comment: `if (num = 0)` is something like `if (isCrazyHumanKillingRobots = true)`. Use `==` (check for equality), not `=` (assignment).
Comment: https://www.tutorialspoint.com/cplusplus/cpp_operators.htm *`=` Simple assignment operator, Assigns values from right side operands to left side operand.*
Comment: So: `==` != `=`
Comment: Oh my lord haha, that worked. Thank you so much. I figured I had a simple issue here, and that was it. You're a life saver.
Comment: My problem has been solved! Thanks for the help. Once I'm better at C++ Ill be sure to repay the favor to other coders on stackOverflow.
Comment: As a technical issue, you should increase the warning level of your compiler (e.g. say  `-Wall` with gcc or `/W4` with Visual Studio) so that you see warnings like this one. You should then *understand* each and every warning (which is often not trivial, e.g. with numerical conversions) and *only then*  eliminate each and every warning.
Answer: if (num = 0)

This assigns the value 0 to the variable called num. The resulting expression evaluates to 0 which, obviously, is always false.
You obviously meant to write
if (num == 0)

instead.
Comment: That was exactly the issue. Thank you for your response and help. I have been working with if statements for a minute in class, but this is the first time I have ever had to check for equality. Thank you for helping me learn a new basic skill


Stirling's Formula for Quotient of Gamma Functions

Question: I am reading a paper in which the authors arrive at the quotient of Gamma functions $\frac{\Gamma(s+k-1)}{\Gamma(k-1)}$ where we are thinking of $s$ as the variable and $k$ is just some other parameter. They then say

By Stirling's formula, for any vertical strip $0<a\leq \Re(s)\leq b$, we have that
$$\frac{\Gamma(s+k-1)}{\Gamma(k-1)}=(k-1)^s\left(1+O_{a,b}((\vert s\vert+1)^2k^{-1})\right)$$

Now I am curious as to derive this from Stirling's formula (since using Stirling's formula is something I have always struggled with).
Since we are in a vertical strip, the version of Stirling's formula that I plan to use is
$$
\Gamma(s)=\sqrt{2\pi}s^{s-\frac{1}{2}}e^{-s}\left(1+O\left(\frac{1}{\vert s\vert}\right)\right)
$$
If I use this for our quotient, we have
$$
\frac{\Gamma(s+k-1)}{\Gamma(k-1)}=\frac{\sqrt{2\pi}(s+k-1)^{s+k-\frac{3}{2}}e^{-s-k+1}\left(1+O\left(\frac{1}{\vert s+k-1\vert}\right)\right)}{\sqrt{2\pi}(k-1)^{k-\frac{3}{2}}e^{1-k}\left(1+O\left(\frac{1}{\vert k-1\vert}\right)\right)}=\frac{(s+k-1)^{s+k-\frac{3}{2}}e^{-s}\left(1+O\left(\frac{1}{\vert s+k-1\vert}\right)\right)}{(k-1)^{k-\frac{3}{2}}\left(1+O\left(\frac{1}{\vert k-1\vert}\right)\right)}
$$
I don't know how to conclude from here. It seems as though heuristically since we are in a vertical strip we will have that the real part of $s$ is bounded so if I just say for simplicity that $s=0$, then I see how the $(k-1)^s$ term comes out, but all the other parts with the big $O$ still confuse me. I don't know if there is an easy way to get this or if I'm doing something wrong. Any help would be greatly appreciated.
Comment: Considering the case $k\gg1$ and $k\gg s$
$$\frac{\sqrt{2\pi}(s+k-1)^{s+k-\frac{3}{2}}e^{-s-k+1}}{\sqrt{2\pi}(k-1)^{k-\frac{3}{2}}e^{1-k}}=\sqrt{1+\dfrac s{k-1}}e^{-s}\frac{(k-1)^{s+k-1}\big(1+\frac s{k-1}\big)^{s+k-1}}{(k-1)^{k-1}}$$
$$=\sqrt{1+\dfrac s{k-1}}e^{-s}e^{(s+k-1)\ln(1+\frac s{k-1})}(k-1)^s=\sqrt{1+\dfrac s{k-1}}e^{-s}e^{(s+k-1)(\frac s{k-1}-\frac{s^2}{2(k-1)^2}+...)}(k-1)^s$$
$$=(k-1)^2\sqrt{1+\dfrac s{k-1}}e^{-s}e^se^{\frac {s^2}{2(k-1)}+O\big(\frac1{(k-1)^2}\big)}=(k-1)^s\left(1+O\Big(\frac1{k-1}\Big)\right)$$
Answer: I think that it is easier to start with logarithms
$$A=\log \left(\frac{\Gamma (k+s-1)}{\Gamma (k-1)}\right)$$ Assuming that $k$ is large and larger than $s$, using twice Stirling approximation
$$\log (\Gamma (x))=x (\log (x)-1)+\log \left(\sqrt{\frac{2\pi}{x}}\right)+\frac{1}{12
   x}-\frac{1}{360 x^3}+O\left(\frac{1}{x^5}\right)$$
and continuing with Taylor series gives (with $\color{red}{p=k-1}$)
$$A=s \log (p)+\frac{(s-1) s}{2 p}-\frac{(s-1) s (2 s-1)}{12
   p^2}+\frac{(s-1)^2 s^2}{12 p^3}+O\left(\frac{1}{p^4}\right)$$ Exponentiating and continuing with Taylor
$$e^A=(k-1)^s \left(1+\frac{(s-1) s}{2 (k-1)}+\frac{(s-2) (s-1) s (3 s-1)}{24(k-1)^2}+O\left(\frac{1}{k^3}\right) \right)$$
Comment: I understand using the twice Stirling approximation, but I am confused when you "continue with Taylor series" to get your formula for $A$, since when trying to work it out on my own, I just wrote $A=\log(\Gamma(s+p))-\log(\Gamma(p))$, and used the twice Stirling, but I didn't get that it simplified as nicely as you have, if you don't mind adding a bit to help explain it more. After that, I see how exponentiating gives me what I want, but now I'm just a little hung up over that one equality for $A$.


Form API multiple select drop downs in a paragraph

Question: I am trying to recreate the following paragraph in a custom Drupal form.

How do you create multiple selects in a single paragraph?
Comment: What about wrapping them in a field prefix/suffix div... could that maybe help?
Comment: @longboardnode: That's an excellent suggestion and I will investigate it BUT some of the sentences can and do have more than one dropdown list item
Answer: You can try a combination of wrapping the whole form in a div, so:
form['#prefix]='
';
  $form['markup1'] = array(
    '#type' => 'markup',
    '#markup' => 'Hello this is a pulldown '
  );
  $form['pulldown1'] = array(
    '#type' => 'select',
    '#required' => TRUE,
    '#options' => array('option1', 'option2', 'option3'),
  );
  $form['markup2'] = array(
    '#type' => 'markup',
    '#markup' => ' and this is another pulldown '
  );
  $form['pulldown2'] = array(
    '#type' => 'select',
    '#required' => TRUE,
    '#options' => array('option4', 'option5', 'option6')
  );
form['#suffix]='
';

then use theme_form_element to remove the field wrapper divs that Drupal injects automatically around each field, see this post. Once these individual divs around each pulldown are removed then the pulldowns will render inline with the markup.


Is it possible for a right triangle (drawn on some specific topology) to have all sides with equal lenth?

Question: Consider a triangle ABC drawn on some surface (for example, a soccer ball or top hat). Is it possible for lengths AB, BC, and CA to be equal while the angle between two of the lines is 90 degrees?
I am not very skilled with geometry, but I want to learn more! Here is my best attempt so far:
I assume that:

There is a right angle between lines AB and CA:    $\vec{AB} \cdot \vec{CA} = 0$

The triangle takes us on a closed path:             $\vec{AB} + \vec{BC} + \vec{CA} = 0$

The sides are of equal length:                     $|\vec{AB}| + |\vec{BC}| + |\vec{CA}| = 0$

I think the next step is to assume some geometry. I think I can map the surface height from the Cartesian coordinates as $s(\vec{x})$ (since $s$ would just be the height of the surface it is just a scalar. I envision $\vec{x}$ as having two dimensions). Since the lines are drawn on the surface, they should also be functions of $\vec{x}$. It seems like I should then rewrite the dot products somehow.
This is where I'm stuck. I'm not sure if it is even fair to define dot products of vectors on a surface. If I walk in a straight line on the surface, I can trace my path to form one line of the triangle. It seems like an OK assumption that those "straight line paths" can be parameterized using some small number of inputs, which is what $AB$ would represent.
I've looked through the first fundamental theorem of differential geometry  but I'm not sure if that is relevant to my problem. It seems like it contains important information for my problem, but I have not been able to exploit it.
What would be my next step in solving this problem? Is it possible to construct a geometry that allows for a right angled triangle with three sides possible?
Comment: It is possible in a spherical geometry.  Consider the earth.  If we look at the lines created by the prime meridian, the 90 degree meridian, and the equator, we will create a triangle with 3 90 degree angles, and all sides equal.
Comment: Topology is probably not the word you want, because topology has no notion of "length." A better word is "geometry."
Comment: @ThomasAndrews Thanks! I edited the question to avoid using the word topology.
Comment: @DougM Thanks! Could you point me towards a proof please? I'd like to derive this myself if possible :)
Answer: On a sphere $S^2$ you can draw a triangle with all angles $\pi/2$ (the sides are parts of the equator and of two orthogonal meridians).
Comment: Thanks! Is it possible to derive a more general class of surfaces that have this property?
Comment: Examples: surfaces of positive curvature.
Answer: Sure it is, as is clear in this figure:


A question combining Farey sequences and Lattice points

Question: I am trying exercises of Tom M Apostol Modular functions and Dirichlet series in Number Theory (Ch-5)
Adding image of exercise ->
Assuming a/b and c/d to be consecutive, I proved (b, d) belongs to $  T_{n}'$ .
But on the opposite if b, d belongs to $T_{n}'$ , then by Bezout Lemma there exists x, y
belonging to integers st xb+dy=1 , one of them must be -ve as b, d are both +ve but how to be sure that y must be -ve and x,- y both belongs to [1, n] .

Can someone please tell how to prove the opposite part.
Comment: There's an algorithm for constructing the fraction just after $a/b$ in the Farey sequence $F_n$; do you know it?
Comment: @Greg Martin No, it is not given in apostol s book.
Answer: This problem can be solved by reminding some properties of Farey sequences. To prove that $a/b$ and $c/d$ are consecutive fractions in a Farey sequence if and  only if $b,d \in T'_n$, we have to prove that:

$b$ and $d$ are coprime;
$ b+d \geq n+1$ (the other conditions $1\leq b\leq n$,  $1\leq d\leq n$, and $b+d \leq 2n$ trivially result from the definition of the sequence);
for any $n$,  the sequence $F_n$ contains all pairs of coprime $b,d$ satisfying $1\leq b \leq n$,  $1\leq d \leq n$, and $b+d\geq n+1$.

Let us begin with the first statement. A relevant property of Farey sequences is that, given two consecutive terms $a/b$ and $c/d$, then
$$bc-ad=1$$
Now let us set $b=b' k$ and $d=d' k$, where $k\geq 1$ is the GCD between $b$ and $d$.  Making the substitutions, we get $k(b'c-ad')=1$. Since $k$ and $(b'c-ad')$ are both integers, the only possibility to have a product equal to $1$ is given by $k=1$ and  $b'c-ad'=$ $bc-ad=1$. This implies  that $b$ and $d$ are coprime.

Now let us consider the second statement. Another property of Farey sequences is that between the fractions $a/b$ and $c/d$ always lies the fraction $(a+c)/(b+d) $ formed by summing their numerators and their denominators (this central fraction is usually called the "mediant"). So, if we consider two fractions $a/b$ and $c/d$,  they can be consecutive in a sequence $F_n$ only if $b+d\geq n+1$. In fact, if $b+d\leq n$, then their mediant $(a+c)/(b+d)$ has a denominator $\leq n$ and is necessarily present between them within the sequence.

Lastly, let us assess the third statement. We can note that every sequence $F_n$ includes all fractions included in $F_{n-1}$, plus a group of new fractions of the form $i/n$, where $i$ is any integer ranging from $1$ to $n$ and coprime with $n$. So, for any $F_n$, these new fractions  have all denominator $n$.
Let us take a fraction of $F_n$ with denominator $b$, such that $b$ is coprime with $n$. If $c$ is chosen among the integers ranging from $1$ to $n$, the terms $bc \pmod n$ represent a complete residue system modulo $n$. So there exists some $c$ such that $bc=1 \pmod n=an+1$. Note that $c$ is coprime with $n$, as well as $a$ is coprime with $b$ (otherwise we would have $bc-an\neq 1$).
Now let us consider the fractions $c/n$ and $a/b$, which are both in their lowest terms and that are necessarily present in $F_n$. The difference between $c/n$ and $a/b$ is $(bc-an)/(bn)$$=1/(bn)$. It can be shown that, within the sequence $F_n$, the fraction $c/n$ has to be placed immediately after $a/b$. To prove this, firstly note that, at the right of $a/b$, a fraction with a denominator $k<n$ cannot be present: in fact, if this was the case, the difference between this fraction and $a/b$ would be  $\geq 1/(bk)$, which is larger than $1/(bn)$.  So, after $a/b$, there is a fraction with denominator $n$. On the other hand,  for given $a,b,n$, the only numerator that satisfies $bc-an=1$ is $c$. Thus, within $F_n$, the fraction $c/n$ must follow $a/b$.
In this way we have shown that, in a sequence $F_n$, for any value $b$ coprime with $n$, there exists a fraction $a/b$ that is followed by a fraction $c/n$. In other words, for any $b$ ranging from $1$ to $n$ and coprime with $n$, a new fraction with denominator $n$ occurs so that a pair of successive denominators $b,n$ is in $F_n$. The same demonstration can also be repeated to show that $F_n$   contains not only such pairs $(b,n)$, but also their symmetric pairs $(n,b)$ (this can also be shown more rapidly by reminding that the series of the denominator in a Farey sequence is symmetric with respect to the central fraction $1/2$).
Based on these considerations, as we pass from $F_1$ to $F_2$,  $F_3$, and so on,  all possible pairs of coprime $b,d$ with $1 \leq b\leq n$ and $1 \leq d\leq n$   progressively appear as denominators of successive fractions. Interestingly,  the new fractions with denominator $n$ that occur in any $F_n$, when inserted within the sequence between two fractions that are consecutive in $F_{n-1}$,  do not eliminate pairs of coprime integers present in $T'_{n}$. In fact, all these new fractions in $F_n$ appear between fractions whose denominators have sum equal to $n$: then, none of these "lost" pairs can be present in $T'_n$, whose lattice points by definition include only pairs with sum $\geq n+1$ and $\leq 2n$. Indeed, the loss of these pairs also allows to satisfy the condition that $b+d\geq n+1$, and leads to a one-to-one correspondence between the pairs of successive denominators in $F_n$ and the lattice points of $T'_n$.
For example, for $n=2$,  the only possible pairs of integers $b,d$ included in $T'_2$ (i.e., coprime,  included in the range between $1$ and $2$ and such that their sum is $\geq 2+1=3$) are $(1,2)$ and its symmetric $(2,1)$. Accordingly, they both appears as pairs of  consecutive denominators  in
$$F_2\left(\frac{0}{1},\frac{1}{2}, \frac{1}{1}\right) $$
For $n=3$,  the possible pairs of integers $b,d$ in $T'_3$  (as above, coprime,  included in the range between $1$ and $3$ and such that their sum is $\geq 3+1=4$) include the new pairs $(1,3)$, $(2,3)$ and their symmetric  $(3,1)$ and $(3,2)$.  Accordingly, they all appear as new pairs of  consecutive denominators  in
$$F_3\left(\frac{0}{1}, \frac{1}{3},\frac{1}{2},\frac{2}{3}, \frac{1}{1}\right)$$
Note that $(1,2)$ and $(2,1)$ are no longer included in $T_3$ because $2+1$ does not satisfy the criterion $\geq 4$. As expected, they do not appear in $F_3$ because they have been "lost" after the insertion of the new fractions $1/3$ and $2/3$.
For $n=4$,  the possible pairs of integers $b,d$ in $T'_4$ include the new pairs $(1,4)$, $(3,4)$ and their symmetric pairs $(4,1)$ and $(4,3)$. In addition, $T'_4$ also includes $(2,3)$  and $(3,2)$ that were already present in $T'_3$. Accordingly, all these appear as pairs of  consecutive denominators  in
$$F_4\left(\frac{0}{1},  \frac{1}{4}, \frac{1}{3},\frac{1}{2},    \frac{2}{3},
 \frac{3}{4}, \frac{1}{1}\right)$$
Note that $(1,3)$ and $(3,1)$ are no longer included in $T_3$ because $3+1$ does not satisfy the criterion $\geq 5$. As expected, they do not appear in $F_4$ because they have been lost after the insertion of the new fractions $1/4$ and $3/4$.
In conclusion, in any sequence $F_n$, all possible pairs $b,n$ included in $T'_n$ appear as pairs of successive denominators.
The third statement is then proved, and the whole proof is completed.
Comment: how did you used the equation ac-bd=1 in paragraph 2 ? We have to prove a/b, c/d to be consecutive assuming b and d belonging to $T'_n $ .
Comment: in your statement( In 2 nd last para) :To complete the proof, it is now sufficient to exclude that the new fractions with denominator n that occur in Fn, when inserted within the sequence between two fractions that are consecutive in Fn−1, do not eliminate pairs of coprime integers present in T′n. Can you please  tell how this condition is sufficient to prove what is asked?
Comment: I added several parts to my answer to better explain these issues. I hope it can be clearer now.


lower bound and upper bound of expression ($1-\frac{1}{n})^{\log n}$

Question: Let's say that $f(n)=\bigl(\frac{n-1}{n}\bigr)^{\log n}$ ( I know bounds of  $\bigl(\frac{n-1}{n}\bigr)^{n}$ ).
Is there any way I can get good upper bound of $f(n)$ when n is positive?
Thanks in advance
Comment: bounds for what sort of $n$?
Comment: when n is positive
Comment: Huh?  For example, which $\log(1/2)$-power of $-1$? (when $n=\frac12>0$)
Answer: Recall that
$$
\left( 1 - \frac{1}{n} \right)^n \leq \frac{1}{e} \leq \left( 1 - \frac{1}{n} \right)^{n-1}.
$$
Then
$$
\log f(n) = \log n \cdot \log \left( 1 - \frac{1}{n} \right) \leq -\frac{\log n}{n}
$$
and
$$
\log f(n) = \log n \cdot \log \left( 1 - \frac{1}{n} \right) \geq -\frac{\log n}{n-1},
$$
hence
$$
\left( \frac{1}{n} \right)^{\frac{1}{n-1}} \leq f(n) \leq \left( \frac{1}{n} \right)^{\frac{1}{n}}.
$$
Answer: For  $n>1$, $\;0<1-\dfrac1n<1\;$ and $\; \log n>0$, so
$$\Bigl(1-\frac1n\Bigr)^{\log n}<\Bigl(1-\frac1n\Bigr)^0=1.$$
Furthermore, the limit of $f(n)$ isqual to $1$:
$$f(n)=\mathrm e^{\log n\,\log\bigl(1-\tfrac1n\bigr)}=\mathrm e^{\log n\bigl(-\tfrac1n+o\bigl(\tfrac1n\bigr)\bigr)}=\mathrm e^{-\tfrac{\log n}n+o\bigl(\tfrac{\log n}n\bigr)}\to\mathrm e^0.$$


Salvar dados em varias tabelas

Question: Estou fazendo um sistema de cadastro e gostaria de uma ajuda de voces para poder salvar os dados em varias tabelas.
Meu cadastro e composto pelos seguintes campos.
Nome do Paciente
Nome do Doutor
Tipo de Serviço
Data de Entrada
Estagio

Agora assim esta minha tabela do banco de dados:
id_paciente
 nome_do_paciente
 nome_do_doutor
Esses dados serão salvos na tabela paciente e preciso do id desse registro para dar sequência.
id_servico
 tipo_servico
 data_servico
 id_paciente
Esses dados serão salvos na tabela serviço e preciso também do id desse registro.
id_estagio
 id_servico
 data_estagio
 tipo_estagio
Esses dados serão salvos na tabela estagio e preciso também do id desse registro.
Abre_Conexao();
if (@mysql_query(INSERT INTO cad_paciente VALUES (NULL, $nome_paciente, $nome_doutor))) {

    if(mysql_affected_rows() == 1){
        echo "Registro efetuado com sucesso
";
    }

}

Já vi fucionando dessa maneira abaixo mais quero acrescentar a esse padrão acima pois meu codigo esta todo nele
$query1 = "INSERT INTO paciente VALUES ('NULL, $nome_paciente, $nome_doutor')";
mysql_query( $query1 );

$id_paciente = mysql_insert_id();

$query2 = "INSERT INTO servico VALUES ('NULL, tipo_servico, data_servico,{$id_paciente})";
mysql_query( $query2 );

$id_servico = mysql_insert_id();

$query3 = "INSERT INTO estagio VALUES ('NULL, {$id_servico}, data_estagio, tipo_estagio')";
mysql_query( $query3 );

Comment: E o php entra onde nessa história?
Comment: Editei a pergunta informando melhor o que estou precisando
Answer: Acho que o PHP tem uma função nativa (mysql_insert_id) para retornar o ID gerado.
Tenta dar uma olhada nessa documentação:
http://php.net/manual/pt_BR/function.mysql-insert-id.php
ex.
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');

if (!$link) {

die('Could not connect: ' . mysql_error());

}

mysql_select_db('mydb');

mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>

Answer: faça assim:
if (mysql_query("INSERT INTO cad_paciente VALUES (NULL, "$nome_paciente", "$nome_doutor"))) {

    if(mysql_affected_rows() == 1){
        echo "Registro efetuado com sucesso
";
    }

}

entretanto, depois que estudar um pouco mais de PHP e de MySQL e estiver com tudo funcionando, procure outro método de inserir os dados ou pelo menos validar os dados antes de fazer coisas como essa, pois esse método permite um tipo de ataque chamado SQL Injection.
Comment: @CristianoCardosoSilva olha... o melhor é elaborar isso em outra pergunta. Pq assim no comentário ficou muito confuso. Nas resposta eu mostrei como inserir dados em uma tabela. Agora, a lógica a seguir fica por sua conta.
Comment: Nelson eu quero e dar continuidade salvando os registros para que eu faça apenas uma tela de cadastro e nao varias telas cada uma para cada tabela, quero fazer apenas uma tela e nela inserir todos os dados e ao enviar para fazer o insert ele ja distribuir os dados automaticamente
Comment: $query1 = "INSERT INTO test (value) VALUES ('test')";
mysql_query( $query1 );

$id = mysql_insert_id();

$query2 = "INSERT INTO test_2 (test_id, value) VALUES ({$id}, 'test')";
mysql_query( $query2 );
Comment: Tipo esse que postei no comentario
Comment: Tem com verificar a pergunta novamente
Comment: e qual o problema ? use o     if(mysql_affected_rows() para cada query
Comment: Não dei conta de montar, ele salva apenas o primeiro
Comment: retire as aspas simples e tente novamente

Salvar dados em varias tabelas