refresh uitableview on button click

Question: I have 2 views in my app
1st view: tableview and button(update)
2nd view: detail view
I want to refresh table in 1st view when I am pressing update button.
Answer: If I understand you correctly you want to reload the data if you come back from the DetailView?
then put it in viewWillAppear: or viewDidAppear:
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [tableView reloadData];
}

then connect your button in interfacebuilder or with
[yourButton addTarget:self action:@selector(reloadTableView:) forControlEvents:UIControlEventTouchUpInside];

to this method
- (IBAction)reloadTableView:(id)sender {
    [tableView reloadData];
}

Comment: no...i want refresh table when i am pressing UPDATE button in same view......i alredy tried your solution but this is not what i am looking for...do you know what should i have to do to refresh table on button click..thank you
Comment: @Pooja maybe you should try to improve your question. for me it's not completly clear what you want.
Comment: and where should i write this   [yourButton addTarget:self action:@selector(reloadTableView:) forControlEvents:UIControlEventTouchUpInside];
Comment: @fluchtpunkt: please check it once again.
Comment: you put it where you create your button. If you create the button in interface builder you have to connect your button in interface builder with reloadTableView:. Therefor you have to put the definition of reloadTableView: in your header. And you should definitely search for a tutorial about the basics of iphone app design.
Comment: ok, here i figure out, i was not updating array values..and now its work fine [tableview reloadData];

refresh uitableview on button click


Question based on profit and loss(doubt)

Question:
A person sold an electronic watch at Rs. 96 in such a way that his percentage profit is same as the cost price of the watch. If he sells it at twice the percentage profit of its previous percentage profit then what will be the new selling price

What I did:-
Given:- S.P.=96
CP=profit=x
SP-CP=Profit
96-x=x
96=2x
x=48
SP-CP=48
CP=48
$48/48*100=100%$
I don't understand what to do next
Answer: Let $x$ be the cost/price of watch. The profit percentage is then $x\%$. The selling price can be defined as $$\frac{x(100+x)}{100}$$
We have a selling price of Rs.$96$. Therefore
$$\frac{x(100+x)}{100} \Rightarrow x = 60$$
In other words, the cost price is Rs.$60$ and the profit percentage is $60\%$. if he sells twice the percentage profit, i.e. $120\%$ the new selling price is then
$$\frac{60(120+100)}{100} = 132$$


How to optimize this recursion function?

Question: This is really similar to Fibonacci Sequence problem. I understand the DP optimization with Fibonacci function using the for loop, but I'm having hard time to connect to this problem.
The recursion function I want to optimize is:
def cal(n):
if n <= 0:
return 1
else:
return cal(n-25)+cal(n-26)
Comment: `from itertools import lru_cache` then add `@lru_cache` decorator before your function. all done ✅
Comment: Can you please write the code out?
Comment: line 1) `from itertools...` line 2) `@lru_cache`, line 3) `def cal(n): ...`, line 4) `print(cal(some_number))`
Comment: @underflow - can you show us a few expected outputs?
Answer: Something like this may help:
(It's inspired by previous post)

from functools import cache

@cache
def cal(n):
    if n <= 0:
        return 1
    else:
        return cal(n-25) + cal(n-26)

print(cal(100))

Answer: The idea of a "for loop optimization" is that we calculate cal(0), cal(1), cal(2), ... consecutively. And when we want cal(n), we already have cal(n-25) and cal(n-26) stored in an array.
So, the following solution has linear complexity for non-negative n:
def cal(n):
    mem = [1]  # cal(0) is 1
    for i in range(1, n + 1):
        num = 1 if i - 25 < 0 else mem[i - 25]
        num += 1 if i - 26 < 0 else mem[i - 26]
        mem.append (num)
    return mem[-1]

One can further optimize to make all the values cal(1), cal(2), ..., cal(n) globally available after calculating the last of them.
Comment: Try it with cal(100)  or cal(10) both got this - ```IndexError: list index out of range```?
Comment: It's well explained and working perfectly.


Render custom field from user registration form

Question: I'm trying to render a custom field that shows up on the user registration form on a separate new form that creates users of a particular role with specific permissions.
I have everything working except being able to render this custom field.
When I view the field under the user registration form settings page, it says it's an entity reference field. When it renders it has 4 check boxes.
I've figured out how to kint out the fields that are on the user registration form from my new form, but I can't figure out how to render the specific one that I need.
$entityTypeManager = \Drupal::service('entity_field.manager');
$fields = $entityTypeManager->getFieldDefinitions('user', 'user');

foreach ($fields as $field_name) {
  kint($field_name);
}

That gives me a listing of all of the fields in the user registration.
I feel like I'm missing something very obvious.
Comment: Normally you would create a custom form mode and configure the field widgets you need. I think you are asking the question because you built the form from scratch. This is easy for simple field types, but a lot of work for complex ones.
Comment: Yeah it's a from scratch build within a module. This has to be rolled out and turned on in production, which we have minimal control over because of a federal client. I'm finding very little on creating custom registration forms and reusing fields from user forms.
Answer: A form mode is configuration which you can roll out via CMI (drush cex/cim) or install with the module by including the YAML files in the modules config folder.
Implementing a new register form mode is not very intuitive. The basics:

Create the form mode:
/admin/structure/display-modes/form

Enable and configure it like in this questions for the pre-installed Register form mode:
How to hide custom fields on the registration form?

To place the new form mode on a page you need either a contrib module
https://www.drupal.org/project/form_mode_manager
or custom code:
How do I load a form with a specific form display (form mode)?
or a custom route:
mymodule.routing.yml
mymodule.register2:
  path: '/admin/people/ch-create'
  defaults:
    _entity_form: 'user.register2'
    _title: 'Create new account'
  requirements:
    _permission: 'register certain users'

register2 needs to be registered as form handler in the entity type:
mymodule.module
function mymodule_entity_type_build(array &$entity_types) {
  $entity_types['user']->setFormClass('register2', 'Drupal\user\RegisterForm');
}

Comment: Ok so if I understand you correctly, the user registration form has a form mode that is not accessible without jumping through some hoops (ie using this contrib module). Is that correct? I'd much rather code this instead of leaning on a contrib module, but let me look into this a little bit first. Contrib modules have to be approved and signed off on (just the natural of some fed clients).
Comment: The pre-installed *Register* form mode is the only form mode which works out of the box without additional code. For a custom form mode, like *Register 2*, you need **either** a contrib module **or** custom code.
Comment: So I'm still circling around this. I'm not really trying to create a new form mode. I'm fine with using the out of the box register form mode. I'm just trying to get an entity reference field that was added on to the user registration form into a second user registration form that creates a user with a unique role. I can access all kinds of information about the field via kint, but I can't get it to render from the buildForm function. Everything else renders fine. I guess I don't understand how a form mode is needed here if I can access the field data.
Comment: FYI....the contrib module has some errors and isn't working in Drupal 9 right now it looks like.
Comment: These two solutions are only examples to make clear what needs to be done, there are a wide range of other solutions for step 3 like building a custom form route. If you are stuck at this point ask a question with details where you want to place the second form on your site.
Comment: Oh I see. Actually....I did leave that detail out. This is an admin form. In other words, not accessible by anonymous users. The use case is that they want to let someone add users of a certain role, but don't want to give them access to the full registration form. I've that form completely built and works except I need one field from the main registration form that is an entity reference field. The path to the form is /admin/people/ch-create and everything is generated by the module I wrote. I'm just stuck at getting this one field. I haven't found much on programmatically reusing fields.
Comment: OK, then create an entity form route for the path. See the edited answer.
Comment: Thanks for your patience with me. I didn't really achieve what I wanted to. I was never able to figure out how to load one single field from the main registration form into a new registration form on the admin side. Again there is very little documentation about programmatically reusing fields. But this did help me to completely recreate the main registration form and I just altered it to my needs and assigned roles to it upon completion. Thank you for your help!


Proof of distributivity in bicartesian closed categories using Yoneda embedding

Question: I want to prove that in a cartesian closed category with finite coproducts, the following distributivity law always holds:
$$ X \times (Y + Z) \cong (X \times Y) + (X \times Z) $$
In Bicartesian closed category is distributive, the OP specifically asks for proofs avoiding the Yoneda embedding.
I'm interested to know wheter the following proof using the contravariant Yoneda embedding $y$ defined by $X \mapsto \hom(X, -)$ is correct (specifically the last step):
By the properties of exponentials and the fact that $\hom$ preserves colimits in the first variable, we have:
$$y(X \times (Y + Z)) = \hom(X \times (Y + Z), -) \cong \hom(Y + Z, -^X) \cong \hom(Y, -^X) + \hom(Z, -^X) \cong \hom(X \times Y, -) + \hom(X \times Z, -) = y(X \times Y) + y(X \times Z) $$
Now, using the fact that any fully faitfhul functor reflects colimits, we conclude that $X \times (Y + Z) \cong (X \times Y) + (X \times Z)$.
I'm not so confident about this last assertion. The chain of equations above shows that $y(X \times (Y + Z))$ is isomorphic (but not equal) to the colimit of the coproduct diagram for $y(X \times Y)$ and $y(X \times Z)$. Is this (together with the fact that $y$ reflects colimits) enough to assert the conclusion, or am I missing some important details, e.g. the naturality of the above isomorphisms?
Comment: https://math.stackexchange.com/q/4833692
Answer: You are close to a correct proof. The corrected version is the following.
$$y(X \times (Y + Z)) = \hom(X \times (Y + Z), -) \cong \hom(Y + Z, -^X) \cong \hom(Y, -^X) \times \hom(Z, -^X) \cong \hom(X \times Y, -) \times \hom(X \times Z, -) \cong \hom((X \times Y) + (X \times Z), -) = y((X \times Y) + (X \times Z))$$
In particular, the universal property of a coproduct involves a product of hom-sets, not a coproduct. Finally, one applies full faithfulness of the Yoneda embedding to directly obtain an isomorphism between $X \times (Y + Z)$ and $(X \times Y) + (X \times Z)$.


Update url-aliase for nodes of a specific content type

Question: I'm using drupal 7 in combination with path auto. I imported nodes of a specific content type using the feed importer, but the url alias is not set correctly.
My problem is, that i can not use the bulk update for content paths, because there is other content, that was migrated manually and that uses non generic url-aliases.
Is there a way to trigger the bulk alias update for a specific content type?
Answer:
To update URL for Existing Contents You could go to admin/content
In Update Options, You can choose Update URL alias after filtering a specific content type
Comment: Just for everyone else' knowledge, I think the "Update Options" drop down menu shown in the screenshot above, is provided by Views Bulk Operations module (VBO): https://www.drupal.org/node/1326928 (it wasn't mentioned entirely in the question or answer).
Comment: This action is in Drupal 8/9 (in the **Action** dropdown) at admin/content.  It is provided by Pathauto.
Comment: In D8+ this won't update existing aliases. SQL posted below if it helps anyone.
Answer: In the settings you can chose what updating needs to do if there already is an alias. Under 'Update action' select 'Do nothing. Leave the old alias intact'. Then do a bulck update.
Comment: Thanks for your answer. But that will not work for me because the nodes already have an existing alias, but it was not set correctly (the pattern was not used).
Comment: After searching the web for solutions i think, that VBO is the best way to do this
Answer: If you're comfortable using SQL, you can do the bulk operation against the database without involving Drupal.
I'd recommend testing the query against a slave, staging or non-production instance of the database to verify the results first, just to be safe:
SELECT alias FROM node
JOIN url_alias
ON CONCAT('node/', node.nid) = url_alias.source
WHERE node.type= 'machine_name';

After you've carefully reviewed the query to verify the results, perform the actual delete:
DELETE url_alias FROM node
JOIN url_alias
ON CONCAT('node/', node.nid) = url_alias.source
WHERE node.type = 'machine_name';

If you don't have access to MySQL database or Drush, you can perform the operation by using a custom Views Bulk Operation or by using Drush:
$ drush sql-query "DELETE url_alias FROM node [...]"
Answer: If anyone is looking for Drupal 8 version of this SQL it's a bit messy. We had a content type called web_site which had /content/.... as the URL alias. We needed this to be /website/.... The machine name of the content type in question is 'web_site'. See query below:-
update path_alias pa
set alias = concat('/website/',substring_index(substring_index(pa.alias,'/',-1),'/',1))
where pa.path like '/node/%'
and substring_index(substring_index(pa.path,'/',-1),'/',1)
in (select nid from node where type = 'web_site');

NOte: checking the existing path contains /node/% ensures we don't update aliases for users, files, etc...


Proving that an $A$-module map between $S^{-1}A$-modules is in fact an $S^{-1}A$-module map using just universal property

Question: Let $A$ be a commutative ring and $S$ a multiplicatively closed system. I am trying to see that if $\alpha \colon N_1 \rightarrow N_2$ is an $A$-linear map of $A$-modules which are in fact $S^{-1}A$-modules, then $\alpha$ is in fact $S^{-1}A$-linear. I want to do this just using the universal property of the localisation. Is this possible?
My attempt is as follows: $\alpha$ being $A$-linear just means that we have a commuting diagram

Now by the universal property, $A \rightarrow S^{-1}A$ is initial among ring maps $A \rightarrow B$ sending $S$ to invertibles. Now since $N_1$, $N_2$ are even $S^{-1}A$ modules,  $A \rightarrow \mathrm{End}(N_1)$ and $A \rightarrow \mathrm{End}(N_2)$ are two maps sending $S$ to invertibles. Hence, we have a larger diagram which I want to show is commutative:

The problem is, how can I conclude from this that
$$
  S^{-1}A
  \rightarrow \mathrm{End}(N_1)
  \rightarrow \mathrm{Hom}(N_1, N_2)
  =           S^{-1}A
  \rightarrow \mathrm{End}(N_2)
  \rightarrow \mathrm{Hom}(N_1, N_2) \,.
$$
One would be tempted to use the uniqueness of the map from $S^{-1}A$ to any ring $B$ where $A \rightarrow B$ sends $S$ to invertibles. The problem is that $\mathrm{Hom}(N_1, N_2)$ is not a ring!
Even so, I haven't used uniqueness yet, but I don't see how.
Comment: You should consider the localization on modules, not on rings.
Comment: See https://math.stackexchange.com/q/2798579/348926
Comment: Not quite. Rather, the localization $M\mapsto S^{-1}M$ is left adjoint to the restriction of scalars, say $F$, along $A\to S^{-1}A$. You ask that $F$ is fully faithful and this is equivalent to showing that the counit of the adjunction $S^{-1}F(M) \to M$ is an isomorphism of $S^{-1}A$-modules. And this can be checked using the universal property.
Comment: I don't think this has to be true.
Comment: If $A$ is commutative, it is definitely true @Randall. See that
$$b\alpha(\frac{a}{b}n) = \alpha(b\frac{a}{b}n) = \alpha(an)=a\alpha(n) = b\frac{a}{b}\alpha(n)$$
for $a\in A$, $b\in S$, and $n\in N_1$. Then, if $b$ is not a zero-divisor, the zero rule gives the desired result. If $b$ is a zero-divisor, $S$ contains $0$, and so everything is trivial.
I don't know how to formulate this in terms of universal properties though.
Comment: Oh yes, I meant that $A$ is commutative to start with, sorry. I can see it's trivial using the explicit construction of the localization, but yes, I'm wondering if there's a way to prove it using the universal property.
Comment: Note that an analogous statement holds for any epimorohism of rings $R \to T$
Comment: @Claudius Do you mean I should show that $A \rightarrow S^{-1}A$ is both the localization of $A$ as a ring and as an $A$-module, and then use the universal property of $S^{-1}A$ as the localization of the $A$-module $A$ to deduce what I want, taking into account the fact that $Hom(N_1, N_2)$ is an $A$-module?
Answer: Let us abbreviate $\mathrm{Hom}_ℤ$ and $\mathrm{End}_ℤ$ as $\mathrm{Hom}$ and $\mathrm{End}$ respectively.
Framework
Let us first consider two abelian groups $M$ and $N$.
The abelian group $\mathrm{Hom}(M, N)$ becomes a left $\mathrm{End}(N)$-module via postcomposition and a right $\mathrm{End}(M)$-module via precomposition.
For a given element $f$ of $\mathrm{Hom}(M, N)$ we can consider the set
$$
  E_f
  :=
  \{
    (h, k) ∈ \mathrm{End}(M) × \mathrm{End}(N)
    \mid
    h f = f k
  \} \,.
$$
This set is a subring of $\mathrm{End}(M) × \mathrm{End}(N)$.
It is also closed under invertibility, in the following sense:
whenever $(h, g)$ is an element of $E_f$ that is invertible in $\mathrm{End}(M) × \mathrm{End}(N)$, its inverse $(h, k)^{-1} = (h^{-1}, k^{-1})$ is again contained in $E_f$.
Observation
The ring $E_f$ helps us understand module structures on $M$ and $N$ for which $f$ is a homomorphism.
Let $B$ be a ring.
A $B$-module structure on $M$ is the same a homomorphism of rings from $B$ to $\mathrm{End}(M)$.
Simultaneous $B$-module structures on $M$ and $N$ are therefore the same as a pair $(φ_1, φ_2)$ of homomorphisms of rings $φ_1 \colon B \to \mathrm{End}(M)$ and $φ_2 \colon B \to \mathrm{End}(N)$.
Such a pair of homomorphisms is the same as a single homomorphism $φ \colon B \to \mathrm{End}(M) × \mathrm{End}(N)$ (whose components are given by $φ_1$ and $φ_2$).
The map $f$ is a homomorphism of $B$-modules if and only if the image of $φ$ is contained in the subring $E_f$ of $\mathrm{End}(M) × \mathrm{End}(N)$.
In other words, if and only if there exists a homomorphism of rings $φ' \colon B \to E_f$ such that $φ = j ∘ φ'$, where $j$ is the inclusion map from $E_f$ to $\mathrm{End}(M) × \mathrm{End}(N)$.
The problem at hand

Let us now consider the original problem:
$M$ and $N$ are not just abelian groups, but $S^{-1} A$-modules.
These simultaneous $S^{-1} A$-module structures correspond to a homomorphism of rings $φ \colon S^{-1} A \to \mathrm{End}(M) × \mathrm{End}(N)$.
We can regard $M$ and $N$ as $A$-modules by restriction, and these simultaneous $A$-module structures correspond to a homomorphism of rings $ψ \colon A \to \mathrm{End} × \mathrm{End}(N)$.
The homomorphism $ψ$ is just the restriction of $φ$ to $A$.
More precisely, $ψ = φ ∘ i$ where $i$ is the canonical homomorphism from $A$ to $S^{-1} A$.
Suppose that $f$ is not only additive, but also $A$-linear.
This means that the image of $ψ$ is contained in $E_f$.
In other words, there exists a homomorphism of rings $ψ'$ from $A$ to $E_f$ with $φ' = j ∘ ψ'$.
For every element $s$ of $S$ the element $ψ'(s)$ of $E_f$ is invertible in $\mathrm{End}(M) × \mathrm{End}(N)$, because $s / 1$ is invertible in $S^{-1} A$ and $ψ'(s) = ψ(s) = φ(s / 1)$.
We have seen that $E_f$ is closed under invertibility, so it follows that $ψ'(s)$ is already invertible in $E_f$.
It now follows from the universal property of the localization $S^{-1} A$ that there exists a unique homomorphism of rings $φ'$ from $S^{-1} A$ to $E_f$ with $φ' ∘ i = ψ'$.
We have $j ∘ φ' ∘ i = j ∘ ψ' = ψ = φ ∘ i$ and therefore $j ∘ φ' = φ$.
In other word, $φ'$ is the restriction of $φ$ to a homomorphism of rings from $S^{-1} A$ to $E_f$.
The existence of this restriction tells us that $f$ is $S^{-1} A$-linear.
Comment: This is a fantastic answer! The trick of factoring through $E_f$ is very ingenious.


How to implement OpenDNS style proxying of web traffic

Question: I have a requirement that I believe may be impossible and wanted to confirm this with experts in this community.
A client wants us to configure a DNS server to point all non-whitelisted domains to an IP address of a server on the internet. This server should forward / redirect all non-http traffic to an IP address associated with the real DNS record as accurately as possible. However, for all port 80 traffic, it should intercept the traffic and forward to a web proxy. This could in theory be possible if we had a large block of public IP addresses that could intelligently route based on the sender's IP to the proper destination, but the engineering effort required there to keep the DNS request and subsequent requests to that same domain in sync would be immense. Not to mention we would be limited from a concurrency perspective.This is probably similar to how OpenDNS does their DNS+Proxying, but they only seem to do it for google.com. This needs to work for an arbitrary set of domains (potentially all of them).
Is the above approach feasible? If not, are there other ways this problem can be approached short of requiring specialized gateway hardware?
Ideally the system will minimize bandwidth usage & latency for non-http traffic without requiring anything besides DNS or firewall configuration. I realize we can forward all http traffic at the firewall level, but the client wants to avoid http requests to CDNs or media heavy sites as well as minimize deployment effort across disparate network configurations.
Comment: This is more of a question for Server Fault.
Answer: OpenDNS works by blacklisting instead of whitelisting
When a host is blacklisted, openDNS will resolve the name into their IP address, which in turn prevent the client from accessing the real IP.
In your case, looks like you need transparent proxy where you can route all HTTP traffic to your proxy server:
See :

http://www.howtoforge.com/dansguardian-content-filtering-with-transparent-proxy-on-ubuntu-9.10-karmic
Comment: OpenDNS do provide white-listing as a paid for service.
Answer: This might not be exactly what you are looking for but take a look at my article "How To Setup A Transparent Content Filtering Proxy" in which I utilize OpenDNS's blacklisting capabilities.
Answer: You can do it using two pieces:

DNS resolver configured with *. pointing to IP A.B.C.D (wildcard)
NGINX reverse proxy listening on A.B.C.D that proxy request to the domain present in the Host header.


Calculate the difference in total days between two dates

Question: i would like to subtract two dates, and have it show me the number of days between the two dates ($current_hour give me a actual hour):
<code>$a = date('Y-M-d' , 1705809951);
$b = date('Y-M-d', $current_hour);

$start_date = $a;
$end_date = $b;

$interval = date_diff(date_create($start_date), date_create($end_date));
echo "$interval->y years, $interval->m months, $interval->d days";
</code>
With this i get it to show me the years, months, and days, but how can I get it to calculate the total number of days?
Or...
$current_hour = 22-jan-2024
How can i transform it to an integer? That is, as $a that $a = 1705809951 and is equivalent to decem-2021
Comment: Why is your question about getting the difference if what you really want to know is how to parse a date?
Comment: Now you say `January 23, 2024`. You've mentioned 3 different date formats in this question. What is your actual date format? There's no built-in method that will parse all these different date styles.
Comment: The difference between March 1 and April 1 is 31 days. The difference between April 1 and May 1 is 30 days. But in both cases it's 1 month.
Comment: Use `$interval->days`
Comment: Didn't I mention that in your [earlier question](https://stackoverflow.com/questions/77853657/understanding-date-diff-in-leap-years)?
Comment: @Barmar Thnx for ur answer again! ^^I want the total days that the subtraction equals. Setting interval->days shows me the difference between the days of the subtraction
Comment: I don't understand the distinction you're making. Can you update the question and show your desired result?
Comment: @Barmar Okay, I'm going to put it another way. I have $current_time. $current_time is a string. (output example -> 1970-Jan-01)
How can I transform that date to unix? Like the variable $a (1705809951). I'm sorry I have to ask this in parts, but I don't know how to express what I want well in English :(
Comment: Use https://www.php.net/manual/en/datetime.createfromformat.php
Comment: @Barmar Because I realize that I put it wrong. How could I convert a date to UNIX? EX: January 23, 2024, 01:18:49 am to UNIX -> (I don't know the equivalence, but it would be in this format (1705809951))
Comment: Are your dates `DD-MMM-YYYY` or `YYYY-MMM-DD`? You have the first in the question, but the second in a comment.
Comment: @Barmar, Thnx u!! I had bad format... With $interval->days It shows me the actual days that have passed, it doesn't matter if the months have 30, 31, or 500 days, correct?
Comment: And the difference in days between Feb 1 and Mar 1 depends on whether it's a leap year, but it's still 1 month.
Answer: Maybe what the funcion you seek is "strtotime()"
The link for the doc is this one: https://www.php.net/manual/en/function.strtotime.php
This code may be of use to you:
<code>echo strtotime('1970-10-01');
</code>
Best regards to u.
Comment: As mentioned in a comment, their date format is `1970-Oct-01`. `strtotime()` doesn't understand this format.
Comment: Hence the documentation link is there so that a solution or equation may be thought.
Comment: adequation not equation, I misspelled


Derivative of Mean Squared Error

Question: I'm studying with a book and I'm at the Linear Regression part. The author is showing that we have to calculate the derivative of each part of the equation that leads to the loss.
But he's using the MSE to calculate the loss and so, I tried to calculate the derivative of MSE:
the derivative of $ (y-p)^2 $ with respect to y (the target) is equal to $2(y-p)$ but  in the book it is written $-1*(2(y-p))$ which is simplified as $-2(y-p)$. Why do I have different values ? Where is this $-1$ coming from?
Comment: Is the author taking the derivative with respect to $p$?
Answer: We are to take derivative with respect to $p$ (and not $y$). We note that MSE is a composition of 2 differentiable functions: $f(g(p))$ where $f(z)$ is $z^2$ and $z$ is $g(p)$ and $y-p$. Therefore, we will resort to the chain rule, by first taking the derivative of $f(z)$ and multiplying it by the derivative of $g(p)$. Namely,
$f'(z)$ is $2(z)$ and $g'(p)$ is $−1$.
We plug and chug and the derivative results in:  $2(y-p)\times-1 =>−2(y−p) => 2p - y$
Comment: Could you pls explain the last step $−2(y−p) => 2p - y$

Derivative of Mean Squared Error


creating interaction term for dummy variables and categorical variables

Question: I want to create interaction term by using dummy variables and categorical variables.
For example, if I want to create interaction term by gender(0=male, 1=female) and
education level(0=less than elementary, 1= middle and high school, 2= college or more)
Is it right to multiply these two terms?
0(male) x 0 (less  than elementary) = 0
0(male) x 1 (middle and high) = 0
0(male) x 2 (college or more) = 0
Above examples get same variable ' 0'.
Can you give me a right way to create interaction term?
Comment: the point about categorical variables is that they are not numbers, so they do not multiply! you form the cartesian product of the categorical variables so six possible combinations (male,less than elementary ,...etc) -> six dummy variables... [in fact you would typically use 5 - since one combination is represented as 5 0s]
Answer: The multiplication scheme only works if you want to treat the education variable as a continuous or ordinal variable that is linearly related to your dependent variable after controlling for sex. In most of the cases (from my experience), this linear assumption seldom holds as there are just too many heterogeneity within some of the educational categories.
If you treat education as a categorical variable, the computation of interaction terms is a bit tricky. Generally, if you have two categorical variables: $x_1$ with $j$ levels and $x_2$ with $k$ levels, to completely model their interactions you'll need $(j-1)\times (k-1)$ dummies. Here are the possible schemes:

Variable $female$ has two levels and variable $education$ has three, so to model the interaction you'll need $(2-1)\times(3-1) = 2$ more dummies on top of the dummies used for main effects.
For instance, if people in college is your reference group, to model the main effect, you'd need $female, D_{Elementary}, D_{Middle}$. To further model the interaction, you'll then need add the products $female\times D_{Elementary}$ and $female\times D_{Middle}$, which is Scheme 1 in the table.
Alternately, if you use other levels in your education variable as reference group, you can change your scheme accordingly. But overall, you should have 5 binary independent variables. These five dummies and the intercept together will allow you to estimate all the 6 means (2 sexes by 3 education levels = 6 possible combinations).

In real setting, we rarely do that by hands. Most software packages allow us to assign the type of variables so that the regression analysis will handle the variable appropriately.
In SAS, look into class statement in proc glm; in SPSS, check the factor and covariate panel in glm module; in R, use factor() or as.factor() functions to change the variable's nature; in Stata, look into adding prefix i. before your independent variable.
Answer: The misunderstanding here is in how categorical variables are presented/coded for usage in analysis. You have two categorical variables (gender with 2 levels and education with 3 levels), and you need to dummy-code them in order to use them - note the distinction between the type of variable (categorical) and how you encode them (dummy).
In this case, you end up with a representation that looks something like
            isF
male        0
female      1

            isH isC
elementary  0   0
high        1   0
college     0   1

And when you interact the variables together, you get sensible differentiation.
                    isF isH isC
male, elementary    0   0   0
male, high          0   1   0
male, college       0   0   1
female, elementary  1   0   0
female, high        1   1   0
female, college     1   0   1

And probably nearly all statistical packages takes care of this in the background, and also note that there are other ways of encoding categorical variables as well.
Comment: @Aksakal That is true, but it is difficult to represent ordinal predictors (whereas ordinal outcomes are much more broadly covered). And outside the scope of the question.
Comment: Gender is a categorical variable, at least in the Western world. Education is usually ordinal, in that Higher>Elementary. When you encode Education with dummies you lose the ordinal relationship.
Answer: What you have described is an ordinal, not really a categorical. In case of education it is probably not a good idea to multiply the ordinal variable. If you are using stat software, it can be told how to treat the variable. This way you don't manually multiply variables to create the interaction term, but let the stat software do it in a consistent way.


viewWillAppear vs Viewdidload ios

Question: When code with iOS navigation application, I have facing with trouble this:
where can I put the method "initdata" for UITableView? in viewWillAppear or viewDidLoad?
please help me out.
Comment: It depends on what you mean by init data.
Answer: You can put initData as per your requirement of the app,
if your table needs to load data every time with new Data then it should be under
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //initData
}

Otherwise, if the table needs to be reload by a single Data which doesn't vary or there is not any editing operation performed on Data , you should use
- (void)viewDidLoad {
    [super viewDidLoad];
   //initData
}

Comment: if I put the code in both place. It will runs that code 2 times when I push this tableView into a UInavigationcontroller
Comment: You should place it under "viewwillAppear" only, as your Array depending on change value of child View.It will work.
Comment: Never init data in viewWillAppear. Depending on the way you load view controller into the screen (into other VC or throughout segues) it may not be invoked at all.
Comment: This actually made the difference between the two very clear - viewDidLoad is used specifically for static data/instantiation, whereas viewWillAppear is for dynamic data that could always be changing.
Answer: It is better to call that in initWithNibName:bundle: or initWithCoder: method and release the loaded data in -(void)dealloc.
Also, you can have that in viewDidLoad and release the loaded data in viewDidUnload. But it is better to avoid calling that from viewWillAppear:
Edit:
I hope that array is depending on the selection in the parent view. In that case, write a setter method, which sets the condition and init the data before pushing the view controller.
DetailViewController *detailViewController = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
// Pass the selected object to the new view controller and depend on that, load the data.
[detailViewController initData:(id)[_list objectAtIndex:indexPath.row]];
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];

Comment: in my case, I have a  NSArray need prepare for uitableview. and value of this array depending on change value of child View.

viewWillAppear vs Viewdidload ios


Applying the chain rule on vectors and matrices

Question: I need to find $\frac{dy}{dx}$ for the following
y = $||A^Tx - b||_2^2$ where $A \in R^{3x3}, b \in R^{3x1}, x \in R^{3x1}, y \in R,$ and $||.||_2$  is the euclidean norm so for example $||z||_2^2 = z^Tz$ for $z \in R^{3x1}$. I'm familiar with the chain rule but I've never really used it in this way. Also, I'm not sure what $R^{3x3}$ represents and how I can use it with the chain rule.
Answer: Define the vector
$$z=A^Tx-b$$
Write the function in terms of this new vector. Then find its differential and gradient.
$$\eqalign{
 y &= z^Tz \cr
dy &= 2z^Tdz = 2z^T(A^Tdx) = (2Az)^Tdx \cr
\frac{\partial y}{\partial x} &= 2Az = 2A(A^Tx-b) \cr\cr
}$$
The symbol ${\mathbb R}^{m\times n}$ denotes a matrix of real numbers with $m$ rows and $n$ columns.


Logical error in display/math not displaying initial result

Question: I have a population estimator program for school, the results do not display the first set of results. Here is the code.
private void Button1_Click(object sender, EventArgs e)
{
    double startingPop;
    double increasePer;
    double numDays;

    const int INTERVAL = 1;

    if (double.TryParse(textBox1.Text, out startingPop))
    {
        if (double.TryParse(textBox2.Text, out increasePer))
        {
            if (double.TryParse(textBox3.Text, out numDays))
            {
                for (int i = 1; i <= numDays; i += INTERVAL)
                {
                    startingPop = (startingPop * (increasePer / 100) + startingPop);
                    Results.Items.Add("After " + i + " days, the amount of organisms is " + startingPop);
                }
            }
        }
    }
}

private void Button2_Click(object sender, EventArgs e)
{
    this.Close();
}

private void Button3_Click(object sender, EventArgs e)
{
    textBox1.Text = "";
    textBox2.Text = "";
    textBox3.Text = "";
    Results.Items.Clear();
}

I want it to show day 1 2 organisms, instead it shows the first calculation with the increase percentage i.e (day 1 2.6). I know this is probably super obvious so I apologize. Thanks for your insight.
Comment: What are the values of the textboxes?
Comment: Looks like all you need to do is to just swap the two lines inside the `for` loop. That being said, are you sure that this is a logical error? In other words, are you sure that _"**After** 1 day"_, the population should _still_ be the same as the starting population?
Comment: No, I need it to show the starting pop on day 1, then show the pop for the days after after the increase is applied. The startingPop variable is also the estimated population.

It should show like this
Day 1 2 organisms
Day 2 2.6 organisms
day 3 3.38 ect, it shows up as Day 1 2.6 currently.
Answer: If I understand your problem correctly, your code should look something like this:
private void button1_Click(object sender, EventArgs e)
{
    double startingPop;
    double increasePer;
    double numDays;

    const int INTERVAL = 1;

    if (double.TryParse(textBox1.Text, out startingPop) &&
        double.TryParse(textBox2.Text, out increasePer) &&
        double.TryParse(textBox3.Text, out numDays))
    {
        Results.Items.Add("On the first day, the amount of organisms is " + startingPop);

        for (int i = 1; i <= numDays; i += INTERVAL)
        {
            startingPop = (startingPop * (increasePer / 100) + startingPop);
            Results.Items.Add("After " + i + " day(s), the amount of organisms is " + startingPop);
        }
    }
}

The changes I made to the code:

Combine the three if statements into one using the && operator.
Print the population value before increasing it so that the next displayed value (which reads "after 1 day") will be the next incremented value.
To make your result items grammatically correct, you may the second line inside the loop with something like:
string s = (i > 1 ? "s" : string.Empty);
Results.Items.Add($"After {i} day{s}, the amount of organisms is {startingPop}.");

Now, assuming the values in textBox1, textBox2, textBox3 are 2, 30, and 5, the displayed result would be something like this:


limits $\lim_{x \to 0} \frac{e-(1+x)^{1/x}}{x},\lim_{n \to \infty} \frac{n}{\log n} (n^{1/n}-1).$

Question: Find the following limits
$$\lim_{x \to 0} \frac{e-(1+x)^{1/x}}{x},$$
$$\lim_{n \to \infty} \frac{n}{\log n} (n^{1/n}-1).$$
Comment: Welcome to MSE! Three posts in a minute? Can you please show your work and thoughts? Also, it helps readability to format using MathJax (see FAQ). regards
Comment: hint for #1: do you know a series expansion for $(1+x)^{1/x}$? what about for $\frac1x\log(1+x)$?
Comment: I've edited your post, but I'm not completely sure that I've done the second one correctly (it's a bit ambiguous in your post where does $(n^{1/n}-1)$ go). Please, see if it needs correcting.
Answer: By Taylor series we have
$$\frac{e-(1+x)^{1/x}}{x}=\frac{e-\exp\left(\frac{1}{x}\log(1+x)\right)}{x}\\
=e\frac{1-\exp(-\frac{x}{2}+O(x))}{x}=\frac{e}{2}+O(x)$$
and
$$n^{1/n}=\exp(\frac{\log(n)}{n})=1+\frac{\log(n)}{n}+o\left(\frac{\log(n)}{n}\right)$$
so
$$\frac{n}{\log n} \left(n^{1/n}-1\right)=1+o(1)$$


What function should I use to loop through Node List in JavaScript?

Question: const navLinks = document.querySelectorAll(".nav-link");
  navLinks.forEach((link) => {
    link.addEventListener("click", (e) => {
      console.log(e.target.classList);
      return e.target.classList.toggle("active");
    });
  });

When I log out the classlist I get a list of all elements with the navLink class, not the clicked one. I have a feeling it's the for each function I am using. How do I get the correct classist as in for the clicked link? , right now when I log out I get classes in all the navlink elements
Comment: Your code should work fine. In what way is it not?
Comment: `e.target.classList` will be all the classes in the `.nav-link` that was clicked
Comment: It's intended that the `classList` contains all of the classes on the DOM element. See [the documentation of `Element.classList`](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList).
Comment: No, `console.log(e.target.classList);` logs the classlist of the clicked element ... If you want something different: What exactly do you want to be logged?
Comment: What you are mean with: "How to get correct classList" It is not quite clear what you are trying to achieve. Can you please explain your question a bit more?
Comment: @Nick i also thought it would but it doesnt
Comment: Well, please edit your question to make an example that demonstrates the problem you are seeing
Answer:
Use stopPropagation to prevent further propagation of events

classList is ArrayLike object, not actually an array. But it can be converted to Array.

const navLinks = document.querySelectorAll(".nav-link");
navLinks.forEach((link) => {
  link.addEventListener("click", (e) => {
    e.stopPropagation(); // prevents further propagation of the current event in the capturing and bubbling phases
    console.log('Array: ', Array.from(e.target.classList));
    console.log('ArrayLike: ', e.target.classList);
    return e.target.classList.toggle("active");
  });
});
.nav-link {
 width: 150px;
 height: 50px;
 border: 1px solid gray;
}

Comment: Maybe because it doesn't have anything to do with the question, and it is not even clear *what* the question is ...
Comment: `When I console.log out the classlist I get a list of all elements with the navLink class not the clicked one` what's unclear here? @derpirscher
Comment: @MedetTleukabiluly That's not true. If you do `console.log(e.target.classList)` it logs the `classList` object of the clicked element and certainly not all elements which have a `nav-link` class ... Which can be seen in your own code. Or does it print `nav-link 4-item` anywhere if you click on the first item?
Comment: you're correct, and that's what OP is asking. so added stopPropagation and an example of ArrayLike, which OP might confuse with `...all elements with the navLink`
Comment: Well if that's the case, that the real point of your answer is the `stopPropagation` you should have mentioned that a bit more prominent in your answer. Currently the main aspect of your answer seems to be the distinction between `Array` and `ArrayLike` A *good*  answer also explains why it is the answer to the question.
Comment: Agree, should have mentioned explicitly
Comment: I don't think `e.stopPropagation()` is required here at all. I ran the snippet without it and it did not make the slightest difference. I rather believe that OP was confused by the output they received from `console.log(e.target.classList)` and therefore @MedetTleukabiluly's answer _has_ a point.


OOP PHP with FB Graph API

Question: I am creating a Student object using OOP in PHP via the Facebook Graph API. My problem is that not all users share the same amount of data on FB so if a particular user doesn't list certain variables instantiated in the object, I get undefined variable messages. What is the best way to prepare for this, i.e. create an object whether or not the user has shared all of the data in the object or not? Code below:
<?php
require_once('class.Student.php');

$name = $user_profile['name'];
$hometown = $user_profile['hometown']['name'];
$location = $user_profile['location']['name'];
$birthday = $user_profile['birthday'];
$highschool = $user_profile['education'][0]['school']['name'];
$hsgrad = $user_profile['education'][0]['year']['name'];
$collegeid = $user_profile['education'][1]['school']['id'];
$college = $user_profile['education'][1]['school']['name'];
$majorid = $user_profile['education'][1]['concentration'][0]['id'];
$major = $user_profile['education'][1]['concentration'][0]['name'];
$grad = $user_profile['education'][1]['year']['name'];
$company = $user_profile['work'][0]['employer']['name'];
$jobtitle = $user_profile['work'][0]['position']['name'];
$startdate = $user_profile['work'][0]['start_date'];
$interest = $interests['data'][0]['name'];
$interestid = $interests['data'][0]['id'];

$objStudent = new Student($name,$hometown,$location,$birthday,$highschool,$hsgrad,$collegeid,$college,$majorid,$major,$grad,$company,$jobtitle,$startdate,$interest,$interestid);

?>

And the class itself:
<?php

class Student {

public $name;
public $hometown;
public $location;
public $birthday;
public $highschool;
public $hsgrad;
public $collegeid;
public $college;
public $majorid;
public $major;
public $grad;
public $company;
public $jobtitle;
public $startdate;
public $interest;
public $interestid;

    public function __construct($name,$hometown,$location,$birthday,$highschool,$hsgrad,$collegeid,$college,$majorid,$major,$grad,$company,$jobtitle,$startdate,$interest,$interestid) {
        $this->name = $name;
        $this->hometown = $hometown;
        $this->location = $location;
        $this->birthday = $birthday;
        $this->highschool = $highschool;
        $this->hsgrad = $hsgrad;
        $this->collegeid = $collegeid;
        $this->college = $college;
        $this->majorid = $majorid;
        $this->major = $major;
        $this->grad = $grad;
        $this->company = $company;
        $this->jobtitle = $jobtitle;
        $this->startdate = $startdate;
        $this->interest = $interest;
        $this->interestid = $interestid;
    }

I understand how to handle this in the functions of the class, using a simple isset such as:
  function goalRecommender () {

        if (isset($this->interest)) {
            if ($this->interest =='Computer Science') {
            echo "
Based on your interest in Computer Science, we recommend working in the software industry. Furthermore, your interest in user interface design would be thoroughly put to use at Facebook, one of the fastest growing technology companies in the world. If you would like to pursue another goal,
            search our database to the right or click one of the 'popular goal' links.
";
            }
            elseif ($this->interests =='Finance') {
                echo "
You're interested in Finance
";
            }
            elseif ($this->interests =='Film') {
                echo "
You're interested in Film
";
        }
            elseif ($this->interests =='Marketing') {
                echo "
You're interested in Marketing
";
            } else {
                echo "
Choose a goal.
";
            }
        }   else  {
                echo "
What are you interested in?
                <select>
                <option>Finance</option>
                <option>Marketing</option>
                <option>Film</option>
                <option>Software</option>
                </select>
";
        }
    }

But I'm just learning OOP in PHP and am unsure how to do it when instantiating an object. Any guidance would be sincerely appreciated.
Answer: There's a lot for your class:

Have your Student constructor take an array. This will reduce the pain of variable adjustments, especially if you end up extending Student.Clarification: rather than passing in the name, college, hometown, birthday, etc, you pass in an array that has all that same information.
$name = $user_profile['name'];
$hometown = $user_profile['hometown']['name'];

//becomes

$user['name'] = $user_profile['name'];
$user['hometown'] = $user_profile['hometown']['name'];

It's faster.  The cost of any parameter isn't much, but when you have tons like this it can at least make a mark.
It's easier to call. You no longer have to remember the order of variables.  "Is it name, hometown, location, birthday? Or name, birthday, location, hometown?"  You have tons of variables, there's no way to easily remember that.
It's easier to change.  Adding a variable?  No problem, add it to the array and check for it inside the function.  Removing a variable? That's hard to do, but not if it's in an array.
public function __construct(
    $name,
    $hometown,
    $location,
    $birthday,
    $highschool,
    $hsgrad,
    $collegeid,
    $college,
    $majorid,
    $major,
    $grad,
    $company,
    $jobtitle,
    $startdate,
    $interest,
    $interestid) {

//becomes
public function __construct(array $info) {

Your variables should be protected or private, not public. This is pretty much industry standard.

You'll want to provide getter and setter methods because the variables are inaccessible.  Many IDE's can do this for you.

As for your error messages:

You need to check to make sure the variable exists before you actually access it.  Use the isset() function for this:
$hometown = isset($user_profile['hometown']['name']) ? $user_profile['hometown']['name'] : null;

Comment: Thank you for the insight. I've implemented 2/3 of your suggestions. The first one: "Have your constructor take an array" I'm a bit unclear on. I think you're referring to the Graph when you mention variable adjustments. Like, if a user only has college listed, there will be a [0] for college but if they list hs and college, college is the [1] outset. If so, how do I have the constructor take an array to solve this, I'm not sure I understand exactly what you mean.
Comment: @MattMcClintock I updated the question to hopefully make it more clear.
Comment: When you wrote construct (array $info) did you mean construct (array $user)?
Comment: @MattMcClintock It doesn't really matter what you name the array.  But that's the idea, yes.
Comment: So what goes after the constructor? public function __construct(array $user) { ??????? }

OOP PHP with FB Graph API


Interpreting interactions in a regression model

Question: A simple question I hope.
I have an experimental design where I measure some response (let's say blood pressure) from two groups: a control group and an affected group, where both are given three treatments: t1, t2, t3. The data are not paired in any sense.
Here is an example data:
set.seed(1)
df <- data.frame(response = c(rnorm(5,10,1),rnorm(5,10,1),rnorm(5,10,1),
                         rnorm(5,7,1),rnorm(5,5,1),rnorm(5,10,1)),
                 group = as.factor(c(rep("control",15),rep("affected",15))),
                 treatment = as.factor(rep(c(rep("t1",5),rep("t2",5),rep("t3",5)),2)))

What I am interested in is quantifying the effect that each treatment has on the affected group relative to the control group. How would I model this, say using an linear model (for example lm in R)?
Am I wrong thinking that:
lm(response ~ 0 + treatment * group, data = df)

which is equivalent to:
lm(response ~ 0 + treatment + group + treatment:group, data = df)

is not what I need? I think that in this model the treatment:group interaction terms are relative to the mean over all baseline group and baseline treatment measurements.
I therefore thought that this model:
lm(response ~ 0 + treatment:group, data = df)

is what I need but it's quantifying each combination of treatment and group interaction terms: treatmentt1:groupcontrol treatmentt1:groupaffected treatmentt2:groupcontrol treatmentt2:groupaffected treatmentt3:groupcontrol treatmentt3:groupaffected
So perhaps this model:
lm(response ~ 0 + treatment + treatment:group, data = df)

is the correct one?
Although in addition to quantifying each combination of treatment and groupaffected interaction term it's also quantifying the effect of each treatment. I'm not sure what is the baseline each of the treatment and groupaffected interaction terms are compared to in this model.
Help would be appreciated.
Also, let's say I ran a fourth treatment which is actually the combination of two treatments, say t1+t3, where I don't know what the expectation of their combined effect is: additive/subtractive or synergistic. Is there any way this can be combined?
Answer: You should not exclude the intercept. Instead, you should make sure that the control is the reference group for treatment contrasts:
df$group <- relevel(df$group, "control")

Then you should of course plot your data:
library(ggplot2)
ggplot(df, aes(x = treatment, y = response, color = group)) +
  geom_boxplot()

It looks like the control group doesn't differ between treatments and the affected group seems to exhibit lower values for treatments t1 and t2, but not t3.
I would now fit the following model:
fit <- lm(response ~ group * treatment, data = df)
summary(fit)
#Call:
#lm(formula = response ~ group * treatment, data = df)
#
#Residuals:
#    Min      1Q  Median      3Q     Max
#-2.2528 -0.4973  0.1965  0.5250  1.4737
#
#Coefficients:
#                           Estimate Std. Error t value Pr(>|t|)
#(Intercept)               10.129270   0.438666  23.091  < 2e-16 ***
#groupaffected             -2.669703   0.620367  -4.303 0.000244 ***
#treatmentt2                0.005866   0.620367   0.009 0.992534
#treatmentt3               -0.091147   0.620367  -0.147 0.884419
#groupaffected:treatmentt2 -2.384202   0.877331  -2.718 0.012013 *
#groupaffected:treatmentt3  2.283003   0.877331   2.602 0.015626 *
#---
#Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#
#Residual standard error: 0.9809 on 24 degrees of freedom
#Multiple R-squared:  0.8226,   Adjusted R-squared:  0.7857
#F-statistic: 22.26 on 5 and 24 DF,  p-value: 2.691e-08

Here, the intercept represents the mean of the control group at t1. We see that the control groups at t2 and t3 don't differ significantly from this mean (as the treatment coefficients tell us). We also see that we have a significant difference between the groups at t1 and an even larger difference at t2, but approximately no difference (-2.67 + 2.28) at t3. You could test the significance of the latter using a post-hoc test, but it is probably sufficient to look at the least squares means:
library(lsmeans)
lsmeans(fit, c("group", "treatment"))
#group    treatment    lsmean        SE df lower.CL  upper.CL
#control  t1        10.129270 0.4386656 24 9.223909 11.034631
#affected t1         7.459567 0.4386656 24 6.554206  8.364928
#control  t2        10.135136 0.4386656 24 9.229774 11.040497
#affected t2         5.081231 0.4386656 24 4.175869  5.986592
#control  t3        10.038123 0.4386656 24 9.132762 10.943484
#affected t3         9.651423 0.4386656 24 8.746062 10.556784
#
#Confidence level used: 0.95

As you see, the confidence intervals of the groups at t3 overlap strongly.
Obviously, you need to employ the usual diagnostics to check for variance heterogeneity, influential points etc.
Comment: If don't exclude the intercept in lm(response ~ 0 + treatment + treatment:group, data = df), meaning: lm(response ~ treatment + treatment:group, data = df) I get all 3 interaction terms: treatmentt1:groupaffected, treatmentt2:groupaffected, and treatmentt3:groupaffected quantifying the effect of each treatment on the affected group relative to the control group. That seems to me more intuitive than the summary of: lm(response ~ group * treatment, data = df)


Logarithmic Integral II

Question: While reviewing an old calculus book the following integral was assigned:
\begin{align}
\int_{0}^{1} \left( x^{a-1} - x^{n-a-1} \right) \, \frac{\ln^{2}x \, dx}{1-x^{n}} = \frac{2 \, \pi^{3} \, \cos\left(\frac{a \pi}{n}\right)}{n^{3} \, \sin^{3}\left(\frac{a \pi}{n}\right)}
\end{align}
for $a \neq n$. The proposed questions here are:

What are some methods to prove the given integral?
What are the changes if the power of the logarithm is lowered to one or raised to 3?

The old calculus book is: Ralph A Roberts, "A treatise on the integral calculus; part 1", 1887. The propoblem presented here is found on page 354 as example 36. The book can be found in the Google Books collection.
Comment: Have you tried a transformation of variables to put it in the form $\int_0^\infty \frac{x^{\mu=1}}{1+x}\ln^2x\,dx =  \frac{\pi^3(1+\cos^2(\mu x)}{\sin^3 (\mu x}$ which is in part 315 of vloume I of Erdelyi's Tables of Integral Transforms?
Comment: What is this so brilliant book?
Comment: Wow, this is tough.  What was the book?
Comment: @MichaelGaluza A note has been added about the book
Comment: @MarkFischler A note has been added about the book
Answer: That is not terribly difficult. One just has to prove that:
$$\int_{0}^{1}\frac{x^{a}-x^{n+a}}{1-x^n}\cdot\frac{dx}{x}=\frac{1}{a},\qquad \int_{0}^{1}\frac{x^{a}-x^{n-a}}{1-x^n}\cdot\frac{dx}{x} = \frac{\pi}{n}\,\cot\left(\frac{\pi a}{n}\right)\tag{1}$$
that follows, for instance, from the reflection formula for the digamma function or from the residue theorem, then differentiate the above line with respect to $a$ the right number of times. Another chance is given by exploiting:
$$ \int_{0}^{1}x^{\alpha-1} \log(x)^k\,dx = \frac{(-1)^k k!}{\alpha^{k+1}}\tag{2}$$
together with:
$$ \psi'(z)=\sum_{n\geq 0}\frac{1}{(z+n)^2},\quad \sum_{n\geq 0}\frac{1}{(n+z)^k} = \frac{(-1)^k}{k!}\, \psi^{(k-1)}(z)\tag{3}$$
from which:
$$\int_{0}^{1}\frac{x^{a/n}}{1-x}\cdot\frac{\log(x)^k}{x}\,dx = (-1)^k k!\sum_{m\geq 0}\frac{1}{\left(m+\frac{a}{n}\right)^{k+1}}=\psi^{(k)}\left(\frac{a}{n}\right).\tag{4}$$
Comment: Isn't the first integral trivial?
Comment: @RonGordon, it's for completeness
Answer: Bit long for a comment, but thought I might add my (incomplete) bit... I will finish it off / delete it when I have a bit more time.
Using the change of variable $x=e^y$ gives
$$I=-\int_0^\infty z^2\text{csch}\left(\frac{nz}{2}\right)\sinh\left(az-\frac{nz}{2}\right)dz=-\int_0^\infty z^2\frac{\sinh\left(az-\frac{nz}{2}\right)}{\sinh\left(\frac{nz}{2}\right)}dz.$$
Since the integrand is an even function we have
$$I=-\frac{1}{2}\int_{-\infty}^\infty z^2\frac{\sinh\left(az-\frac{nz}{2}\right)}{\sinh\left(\frac{nz}{2}\right)}dz..$$
For $n>a$ I think the semi-circular integral for $z=Re^{i\theta}$ where $0\leq\theta<\pi$ tends to zero as $R\to\infty$, in which case we may sum the residues in the complex plane above the real axis. Not sure if this converges yet but will take a look soon unless someone else does !
Answer: This one is trivial. All you have to do is notice that $x^a-x^b=(1-x^b)-(1-x^a)$, and then recognize the expression in question as a linear combination of second-order derivatives of generalized harmonic numbers. Since the latter are umbilically connected to digamma functions, use the reflection formula to arrive at the desired result.

Logarithmic Integral II


Visual Studio 2010 project settings for pre-baked MS code

Question: I'm not a much of a programmer, but I'm trying to follow this 4 part guide to store Windows logs in SQL:
http://msdn.microsoft.com/en-us/library/bb552512(v=vs.90).aspx
In the first part, they discuss using an "Application Settings File".
http://msdn.microsoft.com/en-us/library/bb552510(v=vs.90).aspx
Is that like an app.config? I tried using the provided XML as an app.config and even generated the .xsd schema. When I do that I receive:
"The name 'Settings' does not exist in the current context"
MS is providing all the code, so I must be throwing it together wrong. If someone could let me know what template to use in Visual Studio, I think I could take it from there.
Answer: Right-click a project in your solution and select Properties. Then select the Settings tab. It will probably look like this:

Click the link to create a settings file, which will have its values stored for you in app.config - you can use the Visual Studio editor to make settings changes.
Comment: Thank You! That MS doc doesn't make much sense for the uninitiated.


Lightgallery not working when adding h1 tag?

Question: I am using Lightgallery and everything works, except when I echo an
 tag inside a foreach loop. When I remove it, the gallery works fine.
The only issue when I add the
 tag is that the images are not being loaded. I just see the preloader loading forever. What could be causing this?
My code:

    <?
    $dir = $_SERVER['DOCUMENT_ROOT'].'/images/PROJECTEN/';
    $folders = array_diff(scandir($dir), array('index.html', '.', '..'));

    function scan_dir($dir) {
        $ignored = array('.', '..', '.svn', '.htaccess','index.html');

        $files = array();
        foreach (scandir($dir) as $file) {
            if (in_array($file, $ignored)) continue;
            $files[$file] = filemtime($dir . '/' . $file);
        }

        arsort($files);
        $files = array_keys($files);

        return ($files) ? $files : false;
    }

    foreach($folders as $gallerypart){
        $nounderscore = str_replace('_', ' ', $gallerypart);
        $gallery .= '
'.$nounderscore.'
';
        foreach(scan_dir($_SERVER['DOCUMENT_ROOT'].'/images/PROJECTEN/'.$gallerypart.'/') as $entry) {

            $gallery .= '

                ';
        }

    }
    echo $gallery;
    ?>

This is the part that breaks it:
$gallery .= '
'.$nounderscore.'
';

Answer: I fixed it by instead of using the standard markup, I used a selector.
Like this:

And then inside the loop I added the following code:
$gallery .= '

';


Jboss Múltiplos context-root apontando mesmo war

Question: boa noite.
É possível eu configurar no Jboss vários context-root apontando para o mesmo war? Caso não seja possível no jboss, existe alguma forma de eu fazer isso?
Obrigado
Comment: Da uma olhadinha nesta resposta:
http://stackoverflow.com/questions/30875657/multiple-context-root-for-single-war-deployment-jboss-eap-6-1
Comment: Muito bom, mas não consegui configurar para Jboss 6, só no 7. Obrigado1
Answer: Acho que é possível sim, acabei achando esse comando caso vc use o jboss 7+
Pin your application via jboss-web.xml to context-root path1 and add rewrite rule to standalone.xml as shown:
<code><virtual-server name="default-host" enable-welcome-root="false">
     <alias name="localhost"/>
     <rewrite name="rule-1"  pattern="^/path1(.*)$" substitution="/path2/$1" flags="NC"/>
 </virtual-server>
</code>
Comment: Fiz uma POC com Jboss 7 e funcionou do jeito que eu quero, mas preciso para o Jboss 6 e tá difícil de achar.
Answer: Senhores, no final consegui resolver seguindo a documentação abaixo:
http://jbossweb.jboss.org/modules/rewrite.html
Meu rewrite.properties ficou assim:
RewriteRule ^/path1(.*)$  /path2$1 [NC]


Views: Highlight today's post based on previously referenced node

Question: I have a weekly recipe list view, I manually create the list at the first day of the week.
for instance I assign Node 1 for Reference field labeled with Monday, Node 2 for Tuesday and so on using reference field in my Weekly content-type.
Next I made a page views of Weekly nodes and show the last node which contains that 7 referenced nodes previously mentioned.
What I want to do is to somehow determine today's date and change display mode of today's node along with Views Sort, like that if today is Sunday, the node referenced in Sunday field becomes highlighted and shows on top of the list.
Is there anyway to manage this using views, display suite or any other way?
Answer: From what I understand your page view only displays a single (the last one) weekly node that in turn displays the fields with references. If this assumption is correct, what you can do (and what I would do in this case) is to create a node--weekly.tpl.php file in your theme folder based on node.tpl.php. Here you will be able to get the current day of the week in PHP. Based on that, use render() to display the reference fields in the order you wish, while adding the required html and css classes to make the current day highlighted.
More information about theming individual content types can be found here: https://www.drupal.org/node/17565
I don't know what's your experience with theming, but if you need help with the actual template, let me know.
[later edit]
You can of course use a separate display suite template if you don't wish to override the general template of the weekly node. It's the same principle, but instead of having a node--weekly.tpl.php, you will have something like this: https://www.drupal.org/node/1098068 I think that the custom display suite layout involves a bit more work, but I may be wrong. Depending on your particular use case and how do you plan to display the "weekly" nodes across your website (e.g. if you will always have the same template or use multiple ways of displaying it), then you can choose one approach over the other. Both of them can help you accomplish what you need.


R - equivalent of pip freeze (how to install all R dependencies from a file listing packages names and versions)

Question: I'm on a new project where there is R code with tons and tons of dependencies, and a specific version of R (3.1.1). When they originally wrote the code they used R's install.package('the-package') to download the most recent version, however now many of the dependencies have new versions which make them incompatible with the R version used (the newest versions of certain packages for instance dplyr, rcpp would require an R upgrade which is not a possibility)
From this experience R seems like it has the worst package manager - I'm coming from NPM where you specify each package and the specific version of the package needed. It is a huge pain (Going on 5+ hours) to resolve these dependencies manually, because apparently the default behavior is to always download the bleeding edge of any package. I have been relatively successful thus far, clicking the 'old sources' link on the CRAN page for the package, downloading the tars and then installing from their.. But this seems like a lot of unnecessary pain. I've had a team member follow this guide to get a list of all the dependencies and versions I need (This at least gives me the possibility to install all the packages up front, and then proceed with trial and error, rather than resolving 50+ dependencies individually each time the build fails in my new environment).. but there is no "R, process my dependencies file" command.

Javascript - you use NPM to install from package.json.
Python - you can do pip freeze and pip install pip_freeze.txt, the same concept
R - as far as I can tell, no easy way to download exactly what you need if you have specific needs like I do

This is a shell script which is easily modified to download a specific version of a package
#!/bin/bash
# CRAN doesn't have a version of this installable in our old R.
wget -P /tmp https://cran.r-project.org/src/contrib/Archive/Rcpp/Rcpp_0.12.5.tar.gz || { echo 'wget failed'; exit 1; }
Rscript -e "install.packages('/tmp/Rcpp_0.12.5.tar.gz', repos = NULL, type='source')" 2>&1 | tee -a rPkgInstall.log
 if egrep "non-zero exit status|Error in install.packages|^package .* is not available" rPkgInstall.log; then
    echo 'FAILED';
    exit 1;
fi

How can I make this an easier process for the next person who joins the team? Documentation can go a long way, but what I'm looking for is a functional package manager in R... Or a convention that allows me to do the same as NPM install (from a package.json) in R
Comment: go check out the checkpoint package. It will allow you to time-travel back to a specific day starting in late 2014 and get all packes in their then current versions on CRAN.
Answer: The packrat package should work for your use case.  If you're using RStudio I suggest using the Packrat tool they've built into the UI, but you can also use it apart from RStudio.  From the Packrat walkthrough:
## Install the package from CRAN
install.packages("packrat")

## Initialize packrat
packrat::init("~/path/to/your/project")

## Later on, install some package
## It will be installed in ~/path/to/your/project/packrat/lib
install.packages("reshape2")

## Take a snapshot of installed packages
packrat::snapshot()

I'm probably only half-way describing the manual process.  I've only ever used the automatic mode in RStudio.  I installed it after starting a project, and it looked through my code, managed to pull all the necessary packages (not sure about versions, since I'm always at the bleeding edge), saved the source files, and installed them in my project directory.  Then I was able to move the packrat directory to another machine and have it install all the packages.
Answer: There is a python package for the same: https://github.com/chinmayshah99/r_freeze.
Usage:
pip install r_freeze

For printing the name of packages:
r_freeze .

For creating a requirments file:
r_freeze -o req.txt .

For creating a requirments as R script:
r_freeze -o req.R .

For overwriting a requirments file:
r_freeze -o req.R --overwrite .

PS. I wrote this package due to my frustration that there doesn't exist such service for R when I myself had to generate these requirements from a huge project.
Answer: As suggested in this page, you can use a library snapshot of a given date (for example Microsoft stores them since 2014), that is, pass, e.g. repos='https://cran.microsoft.com/snapshot/2016-08-06/' to install.packages or devtools::install.
Answer: I guess this should solve your problem
pkgLoad <- function( packages = "favourites" ) {

  if( length( packages ) == 1L && packages == "favourites" ) {
    packages <- c( "data.table", "chron", "plyr", "dplyr", "shiny",
                   "shinyjs", "parallel", "devtools", "doMC", "utils",
                   "stats", "microbenchmark", "ggplot2", "readxl",
                   "feather", "googlesheets", "readr", "DT", "knitr",
                   "rmarkdown", "Rcpp"
    )
  }

  packagecheck <- match( packages, utils::installed.packages()[,1] )

  packagestoinstall <- packages[ is.na( packagecheck ) ]

  if( length( packagestoinstall ) > 0L ) {
    utils::install.packages( packagestoinstall,
                             repos = "http://cran.csiro.au"
    )
  } else {
    print( "All requested packages already installed" )
  }

  for( package in packages ) {
    suppressPackageStartupMessages(
      library( package, character.only = TRUE, quietly = TRUE )
    )
  }

}

## call the function
pkgLoad()


Calculate the segment EC in the rectangle ABCD

Question: In a rectangle $ABCD$, a point $E$ is marked inside it and a rectangle $DELK$ is constructed congruent to the previous one, $m(\angle CED)=m(\angle ECD),\ BE=CK,\ EL=4+2\sqrt3$ and $m(\angle ELC)=\dfrac{53^\circ }{2}$. Calculate $EC$. (Answer:$ EC = 4$)
Would anyone have a solution using geometry? I made the drawing and I find a solution by use of trigonometry

$EC =ED = DC$ ???? How to demonstrate?
$\therefore \angle DEC = 60^\circ \implies \angle LEC = 30^\circ $
$\dfrac{EC}{\sin(26.5^\circ)} = \dfrac{EL}{\sin(180^\circ - (26.5^\circ + 30^\circ))} \Longrightarrow$
$EC = \displaystyle\frac{\sin(26.5^\circ)(4+2\sqrt{3})}{\sin(123.5^\circ)} \approx{4}$
Comment: I am getting confused by your terminology. By $m<CED$ do you mean $m(\angle CED)$, denoting the measure of angle $CED$? This can be typeset as ```m (\angle CED)```
Comment: yes,,,,,,,.................................
Comment: Just an idea, not sure if it works, reflect ABCD about CD, then the new rectangle when rotated about D gives EDKL
Comment: @petaarantes It seems that you have an unfortunate drawing, as a result it misled you. Neither $C$ nor $E$ are centers of rectangles.
Comment: @kabenyuk  The drawing is to scale (geogebra). Based on the data, it cannot be said that they are centers, which is proven by geogebra
Comment: Then why do you have $EC=ED=DC$?
Comment: Actually, $EC=ED=DC$ can be proven @kabenyuk. I am posting an answer now
Comment: @kabenyuk The fact that they are equal does not mean that $E$ and $C$ are centers... The question is how to demonstrate that they are equal to arrive at the solution... I just replicated a solution and confirmed it using geogebra
Answer: Here is a slick proof of $EC=ED=DC$: (other than that, I don't see any way to avoid trig, because we have a not-so-easy angle measure)
Reflect the rectangle $ABCD$ about $CD$ to get rectangle $A'B'CD$. Let the corresponding reflection of $E$ about $CD$ be $E'$.
Now, rotate the new rectangle $A'B'CD$ about $D$ with an angle of $\alpha$ such that $C$ lands on $E$ (this is possible since we are given $DC = DE$ - in terms of angles). Then $A'$ lands on $K$ and $B'$ lands on $L$. Note that $\angle EDC = \alpha$.

Since $E'$ is the reflection of $E$ about $CD$, the angles they both make at $D$ w.r.t to $CD$ must be equal, i.e, $\angle CDE' = \angle EDC = \alpha$.
This shows that our rotation guarantees that $E'$ lands on $C$.
Next, $BE = CK$ is given, and $CK = E'A'$ by our rotation, so that $BE = E'A' = EA$. This means the perpendicular bisector of $AB$ (which is also perpendicular bisector of $CD$) passes through $E$, so that $CE = DE$ as desired.

Now we can use the sine rule like you did to get:
$$EC = \frac{\sin(26.5^\circ)(4+2\sqrt3)}{\sin(123.5^\circ)}\approx \boxed{4}$$Although we can use the well-known $\sin(53^\circ) = 4/5$ to approximate this, I am sure this is very messy without a calculator.

Edit: Actually, we can do the calculation without a calculator:
First, note that $\sin(30^\circ+\theta)/\sin(\theta) = \cot(\theta)/2+\sqrt3/2$. Then $\sin(123.5^\circ)/\sin(26.5^\circ) = \sin(30^\circ+26.5^\circ)/\sin(26.5^\circ) = \cot(26.5^\circ)/2+\sqrt3/2$.
We can find $\cot(26.5^\circ)$ using
$$3/4 \approx \cot(26.5^\circ \cdot 2) = \frac{\cot^2(26.5^\circ)-1}{2\cot(26.5^\circ)} = \frac{m^2-1}{2m}$$which, upon solving gives $m \approx 2$ or $-0.5$. The negative value is discarded, hence $\sin(123.5^\circ)/\sin(26.5^\circ) \approx 1+\sqrt3/2 = \frac{2+\sqrt3}{2}$.
Finally, $$EC = \frac{\sin(26.5^\circ)(4+2\sqrt3)}{\sin(123.5^\circ)}\approx (4+2\sqrt3)\cdot \frac{2}{2+\sqrt3} = \boxed{4}$$
Comment: Thanks for help
Answer:
Hint: For geometric solution consider this construction:
(1):$D_1C_1=tan 60^o=\sqrt 3$
(2): $B_1G=E_1B_1=D_1C_1$
(3):$C$ is reflect of $B_1$ about $G$, so $B_1C=2\sqrt 3\Rightarrow BC=4+2\sqrt 3$
(4):Triangle DEC is isosceles so CD and CE are symmetric about perpendicular bisector CE . $LC=BE$ , this means CM is also a perpendicular bisector o BL and ALCE is an isosceles trapezoid and $ CE||BL$ and $BE_1CE$ is a rhombus.
(5): Points $E$, $B_1$ and $E_1$ are on a circle with radius $4$, hence $CE=BE=4$
As you see the construction shows $\angle ELC=21.09$, you can follow this instruction and make the accurate construction.Also $AB=5.56$.
Answer: Here is an exact (as possible) picture in geogebra:

To see that $\Delta CDE$ is equilateral use a reflection denoted by a prime w.r.t. the angle bisector in $D$ of this triangle. Then $ABCD$ is reflected in
$KLED$ because it is enough to check that $C,E$ and $A,K$ reflect in each other. From $BE=CK$ we obtain $AE=A'E'=KC=CK=BE$, so $E$ is on the perpendicular bisector of the segment $AB$, thus also of $CD$, giving $EC=ED$.
By reflection, $C$ is on the perpendicular bisector of the segment $DE$, so $CE=CD$, making together $\Delta CDE$ equilateral.
This clears the question concerning this triangle and the angles in $C,D,E$.

It turns out that the exact value of $CE$ is not $4$, but some number "close to four", the value (shown with $15$ decimal digits precision) is the label of $CE$. We can get as many decimals as we want in this century, here are some first few of them:
<code>sage: F.<u> = CyclotomicField(720)

sage: j = u^90     # this is sqrt(-1)
sage: s = (u^53 - u^-53)/2/j    # this is sin(53°/2)
sage: t = (u^247 - u^-247)/2/j    # this is sin(247°/2)
sage: (s/t * (4 + 2*sqrt(3))).n(300).real()
</code>
And we obtain:
$$   3.99391107195919450602102403886251977140233475054345819553790569969721788705367742719545068\dots
$$
with first geogebra decimals confirmed.

To have still some "geometric confirmation" that we land "near four", let us make the same construction "using the four", but letting that $\frac 12{53^\circ}$ angle open. And here is the picture, we are grouping a square and an equilateral triangle both with side four together:

and it turns out that
$$
\arctan\frac 24 =\arctan\frac12\approx 26.565051177077989351572193720453294671204214299645\dots^\circ
$$
is almost $\frac 1253^\circ$. (The points $C,D,E$ from the last picture are approximations of the "real ones".)
Comment: Thanks for help


ebay-sdk-php notification handling

Question: I'm using the https://github.com/davidtsadler/ebay-sdk-php, the unofficial PHP SDK for eBay.
I've been going around in circles with notifications, particularly 'FixedPriceTransaction' notifications. I've managed to subscribe to the notifications and send a request to ensure that the subscription has been correctly created.
Unfortunately I can't work out which method to use when the notification is sent by eBay to handle it.
Answer: Full disclosure: I'm the developer of the eBay SDK
eBay's notification service is not something that is officially supported by the SDK as it's an area of the API that I'm not to familiar with, but I will try and answer your question as best as I can.
As I understand it there are two parts to the eBay's Platform Notifications.

You inform eBay which user notifications you are interested in.
eBay's Platform Notifications then asynchronously pushes the notifications to your delivery location (which will typically be a URL under a domain that you control.)

The first part should be possible with the SDK as it just involves sending a request to the SetNotificationPreferences operation. It sounds like that you have already worked out how to do this part but I've included the example below just on the off chance that it helps. I haven't tried the code below but it should give you some idea of what to do.
use \DTS\eBaySDK\Trading\Services;
use \DTS\eBaySDK\Trading\Types;

/**
 * Fill out $request according to your project needs.
 */
$request = new Types\SetNotificationPreferencesRequest();
$request->UserDeliveryPreferenceArray = new Types\NotificationEnableArrayType();
$notification = new Types\NotificationEnableType();
$notification->EventEnable = 'Enable';
$notification->EventType = 'FixedPriceTransaction';
$request->UserDeliveryPreferenceArray->NotificationEnable[] = $notification;

/**
 * Handle response according to your project needs.
 */
$response = $service->SetNotificationPreferences($request);
if ($response->Ack !== 'Failure') {

}

The second part may be possible with the SDK but this is one area that I don't have any experience with. As I understand it, eBay will send a POST HTTP request to a URL that you control. It is your responsibility to process the data that is included in the request and to respond with a standard HTTP status 200 OK. I assume that the POST data includes a SOAP body that can be accessed by the PHP script as a string. Inside the SOAP body should be the XML of the notification. As long as you have some way to obtain the actual XML string that eBay sends, you can use the XmlParser class. This class is what the SDK uses to convert the XML response from the API back into a PHP object. This means that you can also do the same.
<?php
require __DIR__.'/vendor/autoload.php';

use DTS\eBaySDK\Parser;

/**
 * This string is not a complete example of what eBay could send.
 * A full example can be found at http://developer.ebay.com/Devzone/guides/ebayfeatures/Notifications/Notif-EndOfAuction.html#Example
 * It assumes that eBay sends a POST request to your sever and
 * that you can obtain the data as a string, E.g via $_POST[] or some other way.
 */
$soap = <<<EOF_S
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <soapenv:Header>
    <ebl:RequesterCredentials soapenv:mustUnderstand="0" xmlns:ns="urn:ebay:apis:eBLBaseComponents" xmlns:ebl="urn:ebay:apis:eBLBaseComponents">
      <ebl:NotificationSignature xmlns:ebl="urn:ebay:apis:eBLBaseComponents">1w5Fdyr9V9ofTq67etR0lA==</ebl:NotificationSignature>
    </ebl:RequesterCredentials>
  </soapenv:Header>
    <soapenv:Body>
        <GetItemTransactionsResponse xmlns="urn:ebay:apis:eBLBaseComponents">
            <Item>
                <ItemID>123456789</ItemID>
            </Item>
    </GetItemTransactionsResponse>
    </soapenv:Body>
</soapenv:Envelope>
EOF_S;

/**
 * Very simple method of extracting the XML from the string.
 */
$matches = array();
preg_match('#<soapenv:Body>(.*?)</soapenv:Body>#s', $soap, $matches);

$xml = $matches[1];

/**
 * The parser requires the full namespace and classname of the object that will be built from the XML.
 */
$parser = new Parser\XmlParser('DTS\eBaySDK\Trading\Types\GetItemTransactionsResponseType');
/**
 * Pass the XML and the parser will return a PHP object.
 */
$response = $parser->parse($xml);
/**
 * Use the object.
 */
echo $response->Item->ItemID;

Comment: Excellent! I have something similar already for the first part, but the second part is unbelievably useful. Much appreciated!
Comment: thanks. can you let me know if there is a way to know if ebay sent notification to url. i'm adding log message but not getting called. email devliery url works
Comment: I was about to submit and issue on github, but this totally answered my question!
Comment: Hello @coder771 you have this notification handler available? i'm stuck in this from 2 days, thanks in advance
Comment: Hello @nikksan by any change, do you have this notification handler available? i'm stuck in this from 2 days, thanks in advance
Comment: Not really, I couldnt make the notification service work, as far as I remember, I ended up setting up a cronjob to run once a few couple hours which only checked the quantities of the products.

ebay-sdk-php notification handling


how to define an extensible C++ enum system

Question: I have encounter a problem in my project on enums.
In EventDef.h,
enum EventDef {
    EVT1 = 0,
    EVT2,
    EVT3,
    EVT_NUM,
}

In this way, I can extend the EventDef system in another header UIEventDef.h by
#include "EventDef.h"
enum UIEventDef {
    UIEVT1 = EVT_NUM,
    UIEVT2,
    UIEVT3,
}

But, there is a limitation that i can not do this in NetEvent.h the same way.
#include "EventDef.h"
enum NetEventDef {
    NETEVT1 = EVT_NUM,
    NETEVT2,   //wrong: this will have the same value as UIEVT2
    NETEVT3,
}

Is there a better compile time solution in C++ such as templates that can help ?
Comment: What exactly is the problem of having the same value? The types differ(UIEventDef vs. NetEventDef) anyway, so you should probably not be comparing them.
Comment: btw, I have used the __COUNTER__ macro, but sadly it dont work :(
Comment: to zxcdw. I have a switch-case event handler, so i need they have different values. yes, i can give them categories, but i just want a better and flexible solution
Comment: @rechardchen: What is it that you want to achieve? The purpose of enums is providing *different* types so that even if the same values that will not matter. You are basically trying to achieve the opposite: a single range that has different values in different headers... You should state the problem that you want to *solve* rather than asking how to deal with your *broken* design.
Comment: @rechardchen: Providing categories is a *better more flexible solution* than a single enum in all respects.
Comment: @DavidRodríguez-dribeas: i think the purpose of enum is not only providing type-checking. The problem is to define different id for different events, but the system need to be flexible( in different headers ).whether to use enum is not the issue
Answer: The idea of extensible enums is not inherently "bad design". In other languages there is a history of them, even if c++ does not support them directly. There are different kinds of extensibility.
Things that extensible enums would be useful for

error codes
message types
device identification (OIDs are a hierarchical enum like system)

Examples of enum extensibility

Objective Modula Two has enums that are extensible with a class like inheritance.
The Extensible Enum Pattern in Java, which can be implemented in c++.
Java enums are extensible in that extra data and methods can be a part of an enum.
In c++, the typeid operator is essentially a compiler generated enum with attached values.

The kind of extensibility you showed in your sample code does not have an elegant implementation in unaided c++. In fact, as you pointed out, it easily leads to problems.
Think about how you are wanting to use an extensible enum.  Perhaps a set/map of immutable singleton objects will meet your needs.
Another way to have extensible enums in c++ is to use a code generator.  Every compilation unit that wants to add to an extensible enum, records the ids in its own, separate, .enum file.  At build time, before compilation, a script (ie perl, bash, ...) looks for all .enum files, reads them, assigns numeric values to each id, and writes out a header file, which is included like any other.
Answer: Why do you want your event enums to be declared like that? What do you gain by having them 'linked' if you will, they way you describe?
I would make them completely independent enums. Secondly, I recommend you not use the old style enums anymore. c++11 is here and available in gcc. You should use enum classes:
enum class EventDef  : unsigned { Evt1 = 0, Evt2, Evt3, ... LastEvt }
enum class NetEvtDef : unsigned { NetEvt1 = 0, NetEvt2, NetEvt3, ... NetLastEvt }

If you are switching you can do this:
void doSwitch(EventDef evt_def)
{
  switch(evt_def)
  {
    case EventDef::Evt1
    {
     // Do something;
     break;
    }
    default:
    // Do something;
  };
}

void doSwitch(NetEvtDef net_def)
{
  switch(net_def)
  {
    case NetEvtDef::NetEvt1
    {
     // Do something;
     break;
    }
    default:
    // Do something;
  };
}

By creating an overloaded function for doSwitch you segregate all your enum types. Having them in separate categories is a benefit not a problem. It provides you the flexibility to deal with each event enum type differently.
Chaining them together as you describe needlessly complicates the problem.
I hope that helps.
Comment: good, thank you to let me know the new c++11 style enum. :) Does it work in VS2008 and xcode4.x? I think what i want to archive is something like categories in objective-C ..
Comment: There are situations when you need extensible enum classes. And overloading switching function seems like a crutch to me.
Answer: I find the following a useful compromise between complexity, features, and type safety. It uses global variables of a custom class that has a default constructor to make initialisation easy. The example below is an extendable set of error codes. You might want to enclose within a name space also (but I typically don't bother).
//
//  ErrorCodes.h
//  ExtendableEnum
//
//  Created by Howard Lovatt on 10/01/2014.
//

#ifndef ErrorCodes_h
#define ErrorCodes_h

#include <string>

class ErrorCodes {
public:
    static int nextValue_;
    explicit ErrorCodes(std::string const name) : value_{nextValue_++}, name_{name} {}
    ErrorCodes() : ErrorCodes(std::to_string(nextValue_)) {}
    int value() const { return value_; }
    std::string name() const { return name_; }
private:
    int const value_;
    std::string const name_;
    ErrorCodes(const ErrorCodes &);
    void operator=(const ErrorCodes &);
};

int ErrorCodes::nextValue_ = 0; // Weird syntax, does not declare a variable but rather initialises an existing one!
ErrorCodes first;
ErrorCodes second;
// ...

#endif

//
//  ExtraErrorCodes.h
//  ExtendableEnum
//
//  Created by Howard Lovatt on 10/01/2014.
//

#ifndef ExtraErrorCodes_h
#define ExtraErrorCodes_h

#include "ErrorCodes.h"

ErrorCodes extra{"Extra"};

#endif

//
//  ExtraExtraExtraCodes.h
//  ExtendableEnum
//
//  Created by Howard Lovatt on 10/01/2014.
//

#ifndef ExtendableEnum_ExtraExtraCodes_h
#define ExtendableEnum_ExtraExtraCodes_h

#include "ErrorCodes.h"

ErrorCodes extraExtra{"ExtraExtra"};

#endif

//
//  main.cpp
//  ExtendableEnum
//
//  Created by Howard Lovatt on 10/01/2014.
//

#include <iostream>
#include "ErrorCodes.h"
#include "ExtraErrorCodes.h"
#include "ExtraExtraErrorCodes.h"

// Need even more error codes
ErrorCodes const localExtra;

int main(int const notUsed, const char *const notUsed2[]) {
    std::cout << first.name() << " = " << first.value() << std::endl;
    std::cout << second.name() << " = " << second.value() << std::endl;
    std::cout << extra.name() << " = " << extra.value() << std::endl;
    std::cout << extraExtra.name() << " = " << extraExtra.value() << std::endl;
    std::cout << localExtra.name() << " = " << localExtra.value() << std::endl;
    return 0;
}

The output is:
0 = 0
1 = 1
Extra = 2
ExtraExtra = 3
4 = 4

If you have multiple compilation units then you need to use a variation on the singleton pattern:
class ECs {
public:
    static ErrorCode & first() {
        static ErrorCode instance;
        return instance;
    }
    static ErrorCode & second() {
        static ErrorCode instance;
        return instance;
    }
private:
    ECs(ECs const&);
    void operator=(ECs const&);
};

Comment: Added that if you have multiple compilation units then, as always you have to use static access methods to overcome initialisation order and multiple definitions.
Answer: We can construct an extensible "enum" in C++ as follows:
struct Last {};

struct D
{
    using Next = Last;
    static const char* name = "D";
};

struct C
{
    using Next = D;
    static const char* name = "C";
};

struct B
{
    using Next = C;
    static const char* name = "B";
};

using First = B;

We can iterate thru the above using these constructs:
void Process(const B&)
{
    // do something specific for B
    cout << "Call me Ishmael" << endl;
}

template <class T>
void Process(const T&)
{
    // do something generic
    cout << "Call me " << T::name << endl;
}

template <class T>
struct IterateThru
{
   static void iterate()
   {
       Process(T());
       IterateThru<T::Next>::iterate();
   }
};

template <>
struct IterateThru<Last>
{
    static void iterate()
   {
       // end iteration
   }
};

To iterate through the "enumeration":
IterateThru<First>::iterate();

To extend the "enumeration":
struct A
{
    using Next = B;
    static const char* name = "A";
}:

using First = A:

Answer: I have written a blog post on how to do this, except with enum classes: C++ Extending Enums
What you end up with is something like this, where the FirstEnum, LastEnum values are used to guard against enum overlaps (doesn't fully prevent intentional abuses though):
enum class EventDef {
    EVT1 = 0,
    EVT2,
    EVT3,
    FirstEnum = EVT1,
    LastEnum = EVT3
};

enum class UIEventDef {
    UIEVT1 = EventDef::LastEnum + 1,
    UIEVT2,
    UIEVT3,
    FirstEnum = UIEVT1,
    LastEnum = UIEVT3
};

template <>
struct EnumExtension<EventDef> { using ExtensionType = UIEventDef; };


Compile C - Windows

Question: I am wanting a simple way to compile Windows Console Applications in C. I am doing cross-platform development for university, and copying things into Microsoft VS to compile for Windows, and then using cygwin for *nix compilation is just too tedious.
If anyone has a simpler solution, maybe a way to compile with a makefile in cmd (if so please provide resources for simple windows make files) then that would be awesome. Thanks in advance.
Comment: cygwin doesn't do unix compilation (at least, none of the compilers that come packaged with it, although it is possible to build a cross compiler).  It does Windows compilation from unix source code.  If you have code that compiles with gcc, and you have cygwin gcc on your Windows box and gcc on your Unix box, then you don't need Visual Studio at all.
Comment: I see! So I would just need to make a "windows makefile" for it to compile the source code using the _WIN32 definition? (as my source code files are broken up with `#ifdef _WIN32 ... #else ... #endif`)
Comment: When compiling with Cygwin gcc, the `_WIN32` macro will be true, the compiler automatically predefines it.  So if you have for example (on multiple lines of course) `#if _WIN32 #include  #else #include  #endif` then your cygwin build will take the Win32 path and your Unix build will take the else.  And you can use the same Makefile and GNU make on both, if you install the appropriate packages in cygwin and your Unix or Linux package manager.
Answer: Check out mingw-64 to write portable C code for Windows and Unix.
https://en.wikipedia.org/wiki/MinGW
The read up on cross compiling with cmake
https://gitlab.kitware.com/cmake/community/wikis/doc/cmake/CrossCompiling

Compile C - Windows