Why does MXToolBox not return MX records for my domains hosted with Amazon Route 53?

Question: Ok, this should be straight forward and I'm ashamed I haven't been able to figure this one out for myself, but...
I've recently discovered Amazon Route 53 DNS services and I'm now using this for the domains which I manage. In order to sanity check my MX records, I use MXToolBox.com to show the MX records and run a quick SMTP check on each MX server.
Here's an example of one of the domains in Route 53:

However when I try to run the query mx:nylandconstruction.co.uk on MXToolBox.com, I am [what seems to be] redirected to the query results for a:nylandconstruction.co.uk and the MX records are not returned:

So I check from command line:
$ dig nylandconstruction.co.uk MX +short
10 mx01.nylandconstruction.co.uk
15 vps02.aws.joe.nyland.tk.

Which confirms that the MX records are present.
If I query MX servers for gmail.com, MXToolBox.com behaves correctly:

So it appears that it's only my domains that are not returning valid MX records to MXToolBox, at least.
Does anyone have any ideas why? Does the above work correctly for anyone else using Route 53 for their DNS?
Comment: To confirm, the URL I am using to check from MXToolBox.com is: http://mxtoolbox.com/SuperTool.aspx?action=mx%3anylandconstruction.co.uk&run=toolpage#
Answer: Looks like a bug with mxtoolbox. This happens on all .co.uk, .co.nz ... domains. I guess it doesn't like TLDs with two fields. You can check with mx:google.co.uk, mx:thetimes.co.uk, mx:nzherald.co.nz, you always get an A record.
Comment: Great! Why didn't I think of that? :) I've opened up a thread on the MXToolBox.com forums so hopefully they can fix this. http://community.mxtoolbox.com/forums/viewtopic.php?f=8&t=1890316&p=1927652#p1927652
Answer: Did you recently change your records? You may need to wait for the TTL to expire on the previous records. They are reporting correctly for me.
nylandconstruction.co.uk mail is handled by 10 mx01.nylandconstruction.co.uk.
nylandconstruction.co.uk mail is handled by 15 vps02.aws.joe.nyland.tk.

Comment: The domain has been running on Route 52 for approx. 1 week, so MX records have been present on there for some time, hence MXToolBox should return *some* MX records. Furthermore, MXToolBox queries the name servers for the domain directly, so any changes to MX records in Route 53 should show up pretty much straight away from queries performed my MXToolBox.com...
Comment: Also, I'm aware that the `host` command is returning MX records for the domain, as you have pointed out, hence I included the output of dig in my original question. Thanks for confirming this from another location, though.
Comment: This seems to be some bug at mxtoolbox, because it seems to be happening on ALL .co.uk domains. Try for yourself with `mx:google.co.uk`, `mx:thetimes.co.uk` or whatever...
Comment: Same problem with .co.nz domains...


Iterating over container or range - problem with constness

Question: I am trying to write a template function that will sum up all elements of some collection - specified either as a plain stl container, or as a ranges-v3's range. (The actual function, as shown below is a bit more generic) I thought this would work:
template <typename Range, typename Ret, typename Func>
std::pair<Ret, int> sum(const Range& range, Ret zero, Func extract) {
  using It = decltype(range.begin());
  Ret sum = zero;
  int numElements = 0;
  for (It it = range.begin(); it != range.end(); ++it) {
    sum += extract(*it);
    ++numElements;
  }
  return { sum, numElements };
}

This indeed works for STL elements, but not for ranges. This gives me a very long error:
<this file, at line 'using It'> error C2662: 'ranges::v3::basic_iterator<ranges::v3::adaptor_cursor<ranges::v3::basic_iterator<ranges::v3::adaptor_cursor<std::_Tree_const_iterator<std::_Tree_val<std::_Tree_simple_types<_Ty>>>,ranges::v3::iter_transform_view<Rng,ranges::v3::indirected<Fun>>::adaptor<false>>>,ranges::v3::remove_if_view<ranges::v3::transform_view<Rng,Fun>,ranges::v3::logical_negate_<EnemyGroup::stepUpdate::<lambda_c582fb1297dce111c4572cef649d86b9>>>::adaptor>> ranges::v3::view_facade<Derived,ranges::v3::finite>::begin<Derived,false,0x0>(void)': cannot convert 'this' pointer from 'const Range' to 'ranges::v3::view_facade<Derived,ranges::v3::finite> &'
note: Conversion loses qualifiers

originally, I thought it was some deficiency of the vs2015 branch of ranges-v3. Without thinking much, I just hacked a quick walkaround:
template <typename Range, typename Ret, typename Func>
std::pair<Ret, int> sum(const Range& range, Ret zero, Func extract) {
  using It = decltype(const_cast<Range*>(&range)->begin());
  Ret sum = zero;
  int numElements = 0;
  for (It it = const_cast<Range*>(&range)->begin(); it != const_cast<Range*>(&range)->end(); ++it) {
    //sum += extract(std::as_const(*it)); (does not work either, converts to void)
    sum += extract(*it);
    ++numElements;
  }
  return { sum, numElements };
}

but with the newest MSVC version that just came out from preview, the master branch of ranges is now officially supported. Yet, the above error prevails.

Is using range's objects as const& a wrong thing to do? I know these objects are lightweight and are easy to copy around, but using a const reference shouldn't hurt, or? On the other hand, if a concrete STL container is passed, I need it to be passed as const&
If using const& is incorrect, is there some easy way to have a function work with both containers and ranges, without writing anything at the call site (e.g. invoking view::all)

I am using Visual Studio Community 2017, Version 15.9.3. Note, that before 15.9, range-v3 in its master branch was not supported.

Since you are asking how exactly I call it. My actual code is complicated, but I reduced it down to this small example:
#include <set>
#include <range/v3/view/filter.hpp>

template <typename Range, typename Ret, typename Func>
std::pair<Ret, int> sum(const Range& range, Ret zero, Func extract) {
  using It = decltype(range.begin());
  Ret sum = zero;
  int numElements = 0;
  for (It it = range.begin(); it != range.end(); ++it) {
    sum += extract(*it);
    ++numElements;
  }
  return { sum, numElements };
}

int main() {
  std::set<int*> units;
  auto [vsum, num] = sum(
    units | ranges::v3::view::filter([](const int* eu) { return *eu>0; }),
    0,
    [](const int* eu) { return *eu/2; }
  );
}

This gives me the same conversion errors as above.
Comment: Does free function `std::cbegin/ranges::cbegin` work?
Comment: Can you add which ranges-v3 header you include, the range you create and how you call your `sum` function with it? I tried `for (const auto& v : range) { sum += extract(v);` and that worked on my own range lib with a `const` range, but with the iterator, it didn't (can't explain why).
Comment: @TedLyngmo  I provided a complete example
Comment: Does using `cbegin()` instead of `begin()` help?
Comment: Thought that too, but I quickly learnd that `'cbegin': is not a member of 'ranges::v3::remove_if_view.......`
Comment: Nope. `using It = decltype(ranges::v3::cbegin(range));` gives me `'operator __surrogate_func': no matching overloaded function found`, followed by `error C2893: Failed to specialize function template 'unknown-type ranges::v3::_cbegin_::fn::operator ()(const R &&) noexcept() const'`
Comment: Can't tell you why this isn't working but another workaround could be to make the fucntion `template
std::pair sum(Range& range, Ret zero, Func extract) { code here }` and `template
std::pair sum(Range&& range, Ret zero, Func extract) { return sum(range, zerp, extract); }`
Comment: Simplification idea, you can lose the `It` type alias and just do `for ( auto it = ... `   This may magically fix your const problem as well.
Comment: I'd say that the problem is in your functor. Which one are you using? Note that `begin` applied to a `const Range` returns a `const_iterator` and a lambda taking an `auto &` may be problematic. I have just tested `std::cout << sum(view::reverse(view::iota(0u,100u)),0u,[](auto i) { return 2.0*i; }).first;` and in works fine under VS2015
Answer: Not all ranges are const-iterable. That is, there are range types T for which const T is not a range. filter is the classic example: it needs to cache the value of the iterator returned from begin so that future calls are O(1) (See http://eel.is/c++draft/range.filter.view#6). Consequently, begin cannot be a const member function without violating the Standard Library policy that const members are callable from multiple threads without introducing data races.
As a consequence, const Range& isn't idiomatic for accepting general Range arguments as it was for accepting "container that I don't intend to modify." We recommend that functions that take Range arguments accept them by forwarding reference. If you alter your program to:
#include <set>
#include <range/v3/view/filter.hpp>

template <typename Range, typename Ret, typename Func>
std::pair<Ret, int> sum(Range&& range, Ret zero, Func extract) { // Note "Range&&"
  Ret sum = zero;
  int numElements = 0;
  for (auto&& e : range) {
    sum += extract(e);
    ++numElements;
  }
  return { sum, numElements };
}

int main() {
  std::set<int*> units;
  auto [vsum, num] = sum(
    units | ranges::v3::view::filter([](const int* eu) { return *eu>0; }),
    0,
    [](const int* eu) { return *eu/2; }
  );
}

It will compile and run correctly.


About the dimension of the a few vector spaces

Question: The set of all real numbers, $\mathbb{R}$, defined over a field of real numbers, $\mathbb{R}$, forms a vector space. What is the dimension of this vector space? I think that dimension is 1. Because any real number can be written in terms of a real multiple of a single real number (say, $1$).
The set of all complex numbers, $\mathbb{C}$, defined over a field of real numbers, $\mathbb{R}$, forms a vector space. I think, in this case, the dimension is 2. This is because any complex number can be expressed in terms of a real multiple of 1 plus a real multiple of $i$.
The set of all complex numbers, $\mathbb{C}$, defined over a field of real numbers, $\mathbb{C}$, forms a vector space. I think, in this case, the dimension is again 1. Any complex number can be expressed as a complex number multiplying a real number (say, $1$).
How correct is my understanding of dimension in these three cases?
Comment: Yes, you are correct in all three cases.
Answer: The dimension of a vector space $V$ is defined as the number of vectors in a basis for the vector space, and a basis for $V$ is just a linearly independent spanning set for $V$.
When you say at the end of each paragraph something like

Because any real number can be written in terms of a real multiple of a single real number

you're describing a basis for each of the vector spaces.
For your first example (call the vector space $V$), the set $\mathcal B=\{1\}$ is linearly independent since $1t=0,t\in\mathbb R$ only has solution $t=0$. It also spans $\mathbb R$ since, for any $x\in\mathbb R$, there exists $t \in \mathbb R$ such that $x=1t$. Hence, $\mathcal B$ is a basis for $V$ with $\mathcal B$ containing one vector. $V$ has dimension $1$.
Your second example (call the vector space $U$) has dimension $2$ because the associated field of scalars has been restricted to $\mathbb R$. That is, a set such as $\{1\}$, although linearly independent, does not span $U$ because any complex number $z\in \mathbb C$ cannot be written as $1t,t\in \mathbb R$. We must add another element to the set to compensate for this restriction. Let $\mathcal C = \{1, i\}$. Now, we have $z=1s+it$ for $ s,t\in\mathbb R$. This new set $\mathcal C$ is linearly independent and spans $\mathbb C$ so it is a basis for $U$.
The third example is similar to the first.
I hope that by sticking to the definitions, I've answered your question clearly.


Existence of prime ideals in rings without identity

Question: Let $R$ be a commutative ring (not necessarily containing $1$). Say that $R$ is the trivial ring if it has trivial (zero) multiplication. If $R$ is the trivial ring, then $R$ has no prime ideals (as any ideal contains $0$, hence the square of every element). Is the converse true - i.e.,

if $R$ is not the trivial ring, then does $R$ necessarily have a prime ideal?

If $R$ has a unity 1, then $R$ has a maximal ideal, which is necessarily prime. However, if $R$ does not have a 1, then maximal ideals need not exist, and even if they do, they need not be prime (in fact, an ideal $I \subseteq R$ is a nonprime maximal ideal iff $R/I$ is the trivial ring of order $p$, for some prime $p \in \mathbb{Z}$). So at first glance, considering maximal ideals doesn't seem terribly helpful...
Answer: Take $R=2\mathbb Z/8\mathbb Z$. This ring has no prime ideals and the multiplication is clearly not trivial.
Since the OP took another way, I'd like to add a generalization of the example above: take $R=d\mathbb Z/n\mathbb Z$ with $d\mid n$, and $m=n/d$. The prime ideals of $R$ are of the form $pd\mathbb Z/n\mathbb Z$ with $p$ prime, $p\mid m$ and $p\not\mid d$. Now it's easy to give examples of such rings without prime ideals.
Comment: Ah, I saw that $2\mathbb{Z}/4\mathbb{Z}$ didn't work, but I should have tried this. Thank you. This seems to give a general class of examples - I'll post this below.
Answer: Extending YACP's example, we have the following general class of examples:
Let $R$ be a commutative ring with 1, $p$ a prime ideal, $I$ any ideal satisfying $p^2 \not \subset pI$ and $V(I) \cap \operatorname{Spec}(R_p) \subset \{p\}$ (viewing $\operatorname{Spec}(R_p) \subseteq \operatorname{Spec} R$). Then viewing $S := p/pI$ as a
non-unital ring gives an example of a nontrivial ring with no prime ideals (as long as $p$ has no idempotents modulo $pI$).
To see why, note that $p^2 \not \subset pI$ is equivalent to saying that multiplication in $S$ is nontrivial. Now any prime ideal of $S$ must come from a prime ideal of $R$, contained in $p$, and containing $pI$. By the assumption on $V(I)$, the only possible such prime is $p$ itself, which is not a proper ideal in $S$, so $S$ has no primes.
As an example, taking $I = p^n$, for $n \geq 2$ (note: $n = 1$ never works!), will satisfy the conditions above (as long as $p^2 \not \subseteq p^3$, e.g. $p^2 \neq 0$ is finitely generated). This recovers YACP's example with $R = \mathbb{Z}$, $p = 2\mathbb{Z}$, $n = 2$.
Notice that $2\mathbb{Z}/6\mathbb{Z}$ is not an example though: the element $4$ acts as a 1. So the assumption that $p$ has no idempotent mod $pI$ is not an empty statement. It seems to hold when $I = p^n$ and $R$ is Noetherian though, e.g. possibly by considering the order in a local ring (the largest power of the maximal ideal an element lies in) - can anyone provide a proof of this?
Edit: Suppose $R$ had a prime ideal $p$, such that $p/p^n$, $n \geq 3$, has an idempotent $x$. Replacing $R$ by $R_p$, we may assume that $p$ is maximal and $R$ is local. Then $x^2 - x = x(x-1) \in p^n$, but $1-x$ is a unit in $R$ (since $x \in p$), so $x \in p^n$, i.e. $x = 0$ in $p/p^n$. So the example $I = p^n$ does work (without Noetherian hypotheses).


An unexpected chord

Question: The other day, I looked up the chord sequence for a song I like. It turns out it goes like this:
G, F, C, D, Em, Am, D, G
Looking at the rest of the chords in the song, this is clearly and unambiguously in the key of G major. And, really, the chords aren't anything unusual or surprising.
But look again at the chords I listed. What is that F major chord doing there? In the key of G major, that is an illegal chord. So why is it here? More to the point, why doesn't it sound wrong? Until I looked this up, I had no idea anything unusual was going on. I certainly didn't hear the song and think "oh man, that second chord sounds weird!" What arcane musical theory did they use to achieve this?
(Incidentally, the verse is the only place where this F major chord shows up. Every single other chord in the song is in the key of G major and follows the typical sorts of patterns you'd expect for that key.)
Comment: It's probably a "mixolydian moment," but to get the most accurate answer, please specify the song, or ideally add an image of the sheet music. Music theory analysis is based on context; it's like asking "What does the word 'head' mean"; it can be a body part, a leader, a verb meaning to lead, a reference to the top of something like an article, etc.
Comment: @AndyBonner - doing that will bring the question dangerously close to violating the site rules, won't it?
Comment: Illegal chord? Thanks for starting my day with a chuckle. Music would be much less interesting if we weren't allowed to use chords that are non-diatonic. Here's a nice article about that specific chord: https://www.icce.rug.nl/~soundscapes/VOLUME22/Magnificent_flat-seventh.shtml
Answer: There have been so many questions similar to this, I wonder who's spreading the 'theory' that all chords must be diatonic. 'Cos it ain't necessarily so.
Any piece in any key can (and often does) contain any chord just about anywhere.
However - that diatonic theory is probably taught to keep beginners on the straight and narrow. The wider theory says that chords can be used from the parallel key. In other words, your F is found in key G minor, the parallel key of G major. Another theory is that your piece is actually written, not in G major, but G Mixolydian - which also contains that F chord. That may then negate the use of a D chord - but you're happy with that, anyway!
Comment: Beginner theory is often not mentioning things like mixolydian. It mostly focuses on a major and minor scale and how to harmonize them. Blues and country theory might mentioning mixolydianin in the beginning. Pop music or gregorian chant are often not the focus in music theory (although we have music theory for pop and gregorian).  People should study the theory of the music the want to play or sing.
Comment: @Tim first you release us from the restriction of being diatonic.  Then you double back and require us to be diatonic in a closely related key!   Can't you just completely accept non-diatonic notes/chords?
Comment: @Laurence - I can, but can everyone else?
Answer: We can take (at least) two approaches to this.

Who told you that only diatonic chords were 'correct'?  And, come to that, who told you that non-diatonic chords had to be justified by being diatonic in some other, connected, key?  Not so.  'Diatonic' is a framework, not a restriction.  And I'd argue that the concept of 'borrowing' is largely unnecessary.

♭VII is so commonplace in popular music that it can be considered 'honorary diatonic'.   Likewise iv and ♭III.

An unexpected chord


Run a command based program at a custom date-time (Add/modify/delete)

Question: I have a python script which takes few params as argument and I need to run tasks based on this script at a given date and time with other params. I am making an UI to add/modify/delete such tasks with all given params. How do I do it? Is there any tool available? I dont think crontabs are the best solution to this especially due to frequent need of task modification/deletion. The requirement is for linux machine.
One soln could be: Create an API to read all the tasks stored in DB to execute the python script timely and call that API  after every few minutes via crontab.
But I am looking for a better solution. Suggestions are welcome.
Comment: I think, this is gonna be helpful: http://www.baeldung.com/java-timer-and-timertask https://stackoverflow.com/questions/11361332/how-to-call-a-method-on-specific-time-in-java Let me if you know something better.
Comment: I think you can actually use python celery for this.
Comment: It would help if you described your use case better.  Specifically, are you wanting to use a specific technology for your UI, or is that one of the things you want help with?  In a comment you said "I want to trigger them only when date-time is mentioned, not check regularly" I'm not entirely sure what you mean by that.  Say someone uses your UI and enters some params, and a date/time.  Do you want a single event scheduled to happen at the specified time?
Answer: I am assuming that all the arguments (command line) are know beforehand, in which case you have couple of options

Use a python scheduler to programmatically schedule your
tasks without cron. This scheduler script can be run either as daemon or via cron job to run all the time.
Use a python crontab module to modify
    cron jobs from python program itself

If the arguments to scripts are generated dynamically at various time schedule (or user provided), then the only is to use a GUI to get the updated arguments and run python script to modify cron jobs.
Comment: crons or cron based library solutions aren't helping me. I need to run a third party python script with dynamically added/modified/deleted arguments including date-time and image url. I want to trigger them only when date-time is mentioned, not check regularly. Can you give a demo link where some python/java based cron library is able to easily add/modify/delete each task?
Comment: If you want to trigger any script on specific date-time, you still need to check regularly whether the date-time has arrived if you don't rely on framework like cron. With `crontab` you can specifiy the date-time from python script itself. Lots of [crontab](https://www.programcreek.com/python/example/97685/crontab.CronTab) examples here.
Answer: from datetime import datetime
from threading import Timer

x=datetime.today()
y=x.replace(day=x.day+1, hour=1, minute=0, second=0, microsecond=0)
delta_t=y-x

secs=delta_t.seconds+1

def hello_world():
   print "hello world"
   #...

t = Timer(secs, hello_world)
t.start()

This will execute a function in the next day at 1 am.
Answer: You could do it with timer units with systemd. What are the advantages over cron?

Dependencies to other services can be defined, so that either other
services must be executed first so that a service is started at all
(Requires), or a service is not started if it would get into
conflict with another service currently running (Conflicts).
Relative times are possible: You can cause Timer Units to start a
service every ten minutes after it has been executed. This
eliminates overlapping service calls that at some point cause the
CPU to be blocked because the interval in the cron is too low.
Since Timer Units themselves are also services, they can be
elegantly activated or deactivated, while cronjobs can only be
deactivated by commenting them out or deleting them.
Easily understandable indication of times and spaces compared to
Cron.

Here come an example:
File: /etc/systemd/system/testfile.service
[Unit]
Description=Description of your app.

[Service]
User=yourusername
ExecStart=/path/to/yourscript

The Timer Unit specifies that the service unit defined above is to be started 30 minutes after booting and then ten minutes after its last activity.
File: /etc/systemd/system/testfile.timer
[Unit]
Description=Some description of your task.

[Timer]
OnBootSec=30min
OnUnitInactiveSec=10min
Persistent=true
User=testuser
Unit=testfile.service

[Install]
WantedBy=timers.target

Answer: One solution would be to have a daemon running in the background, waking up regularly to execute the due tasks.
It would sleep x minutes, then query the database for all the not-yet-done tasks which todo datetime is smaller than the current datetime. It would execute the tasks, mark the tasks as done, save the result and go back to sleep.
You can also use serverless computation, such as AWS Lambda which can be triggered by scheduled events. It seems to support the crontab notation or similar but you could also add the next event every time you finish one run.
Comment: "You can also use serverless computation, such as AWS Lambda which can be triggered by scheduled events. It seems to support the crontab notation or similar but you could also add the next event every time you finish one run." This seems interesting..any demo I can refer to? other options I am aware of...looking for something which doesn't need to keep running just to check regularly.
Comment: A tutorial is available: https://docs.aws.amazon.com/lambda/latest/dg/with-scheduledevents-example.html
Answer: I found the answer to this myself i.e, Timers Since my experience and usecase was in java, I used it by creating REST API in spring and managing in-memory cache of timers in java layer as a copy of DB. One can use Timers in any language to achieve something similar. Now I can run any console based application and pass all the required arguments inside the respective timer. Similarly I can update or delete any timer by simply calling .cancel() method on that respective timer from the hashmap.
  public static ConcurrentHashMap<String, Timer> PostCache = new ConcurrentHashMap<>();
  public String Schedulepost(Igpost igpost) throws ParseException {
        String res = "";
        TimerTask task = new TimerTask() {
            public void run() {
                System.out.println("Sample Timer basedTask performed on: " + new Date() + "\nThread's name: " + Thread.currentThread().getName());
                System.out.println(igpost.getPostdate()+" "+igpost.getPosttime());
            }
        };
        DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date date = dateFormatter.parse(igpost.getPostdate()+" "+igpost.getPosttime());
        Timer timer = new Timer(igpost.getImageurl());
        CacheHelper.PostCache.put(igpost.getImageurl(),timer);
        timer.schedule(task, date);
        return  res;
    }

Thankyou everybody for suggestions.


prior & posterior probability in Bayesian Decision Theory

Question: Learning Bayesian decision theory (specifically in Machine Learning) recently, couldn't figure out what do the posterior possibility $P(c|x)$ and the prior possibility $P(x|c)$ mean exactly.
Anybody knows what $x$ and $c$ represent exactly in the possibility formula?
(all I know is c stand for class and x stand for samples. But I suppose they have some different meaning in the formula, perhaps represent some events?)
Comment: Possibility and probability are different things, while you seem to be using them as synonyms https://stats.stackexchange.com/q/445832/35989
Comment: @Tim Thanks for editting my question! My comprehension from your reference is that probability is a quantified representation of possibility. Do I get the point?
Answer: $x$ and $c$ in Bayes theorem are random variables. Any random variables. Bayes's theorem is about being able to flip sides of the conditional distribution from $P(x|c)$ to $P(c|x)$ or the other way around. They could be events, e.g. "probability that it rains ($x$) given that it's cloudy ($c$), $P(x|c)$", in naive Bayes algorithm $x$ is a feature of the model and $c$ is the predicted class, in a classical Bayesian model $x$ would be your data and $c$ the parameter of the model.
Comment: @Bog I'm not sure what do you mean.
Comment: The question is  more about machine learning.  And after reading some materials,  I think c stands for given an arbitrary sample (sample here means something like training examples instead of the ''sample'' in statistics) ,  the sample belongs to a class c.  And x means given an arbitrary sample, the sample is identical to x.  What do you think?
Answer: Let us give an example that makes this as simple as possible.
Suppose your samples are all taken from a Bernoulli distribution, i.e. these are ``binary samples'', these are just $1$'s and $0$'s. Let those samples by denoted by: $x_1,x_2,...,x_n$. Here each $x_k$ is equal to either $1$ or $0$. Let $\mathbf{x}$ denote the entire vector of all those samples, so $\mathbf{x} = (x_1,x_2,...,x_n)$.
Now, since these samples are coming from a Bernoulli distribution it means there is an unknown parameter $c$ which represents the ``success rate''. The number/parameter $c$ is unknown, and it is supposed to represent how often the samples display $1$. Therefore, if $c=.9$ then we expect to see a lot of $1$'s in the vector $\mathbf{x}$ and if $c=.1$ then we expect to see mostly zeros instead.
Let us say, for example, that our sample vector $\mathbf{x}$ consists of $70$ observations of "$1$" and $30$ observations of "$0$". It is reasonable to guess that $c = \frac{70}{100} = .7$. However, because of random flucations in the data it could happen that the true value of $c=.65$ and the data was just more lucky and generated a bit more $1$'s.
The "posterior distribution", which you denote as $P(c|\mathbf{x})$ is supposed to quantify your uncertainty about the value of the $c$ parameter. In the example we are using, where $\mathbf{x}$ has 70 successes and 30 failures, it can be shown (perhaps, you can show this yourself!), that the posterior distribution looks like this,

From this picture you can see that the most reasonable choice for $c$ is $0.7$, but it could also be $0.8$ but much less likely, however when we reach $0.9$ it becomes very unreasonable. Instead of saying "more reasonable", or "less reasonable", ect, we make the language precise so there is no confusion about what we mean, and the posterior distribution is what quantities your uncertainty and likelihood of the unknown parameter $c$.
Comment: Assuming you have $c$ and $x$ the correct way round, then $p(c)$ would be the prior density for $c$, and $\mathbb P(\mathbf{x} \mid c)$ would be the Bernoulli or binomial probability for $\mathbf{x}$ given $c$ which is proportional to the likelihood, and combined would give $p(c \mid \mathbf{x}) =\dfrac{\mathbb P(\mathbf{x} \mid c) \,p(c)}{\int_c \mathbb P(\mathbf{x} \mid c) \,p(c)\, dc }$ as the posterior density for $c$ given $\mathbf{x}$
Answer: In a very simplified way:
Posterior probability = $P(\gamma | D)$ = probability that your parameter (or vector of parameters) $\gamma$ is equal to the value you've sampled given your dataset $D$.
Prior = arbitrary guess of the value of $\gamma$ based on an expert knowledge (or ignorance for uninformative prior)
However, a question you don't ask is "what means the likelihood" in the Bayesian formula: basically, it is the opposite of the posterior probability.
Likelihood = $P(D|\gamma)$ = probability that your data is observed for the given values of the parameter(s) $\gamma$


Using R for crunching system data?

Question: I frequently hear good things about the R language for statistical analysis of data, but it looks as though the learning curve is steep.  I'm interested to know if anyone's using R to crunch data about system performance and scalability to give greater insight into behaviour than a basic time series from a monitoring system gives.  What value does R give you as a sysadmin?
Comment: I've done it.. Combination of R and Python for analysing apache log hit rates on a time-series.  Hell of a learning curve, but like matlab, it's worth it.
Answer: We have looked at R as a common analysis and reporting back end for data from multiple performance test tools but unfortunately we have not had the time tom implement R for this task as we have simply been too busy performance testing servers...just not enough downtime.
Here's my take on R at least from a performance testing analytics perspective

We need to correlate data which is inclusive of response time and system monitor data across dozens of hosts involved in the performance test.   Using R gives us the ability to import data from multiple disparate data sources in multiple formats for a consolidated analysis set
For testing we need reproducibility, otherwise what we are engaging in is 'experimenting' and not 'testing.'   R will help us to understand better the quality of our data set based upon the number of samples and also allow us to better understand how statistically close are our tests when we run tests back to back to check for consistency.
The weak link in all of the open source performance test tools is analytics and the ability to correlate an increase in response time event to increases or drops in other system metrics.   R should allow us to provide the same level of analytical capability on open source test tools that we can get today with the best of the commercial tools, and for the commercial tools it should allow us greater insight into the nature of the sample sets where we can calculate the area under the curve for the frequency of the samples and get a delta when compared to the optimal curve (one half of the bell curve with low standard deviation).   This delta we will use to guide our feedback to development on where to spend the time and energy for a fix
All of the tools on the market are poor when comparing to a robust performance requirement which is typically written as an SLA, i.e., a response time of 'x, y% of the time , under a load of Z.'   R will allow us to better report on the requirements/SLA targets, especially where moving SLAs may be present based upon load.
For technical benchmarking R will allow us to better compare the output of current and prior tests against different builds, finding statistically significant deviations in performance from one test to the next to report back to development

On the test server analytics side today we use a combination of monitored metrics collected during our tests, log analysis with Microsoft logparser and a reporting engine based upon LaTeX/PSTRICKS which outputs PDF.   With R we expect to move to a more structured rules based analysis of results which we should be able to automate to a high degree where today we need a lot of manual intervention on the analytical side of the house for eyeballing results and formatting the output.
Answer: R is a programming language like any other, with strengths and weaknesses. The strengths are in the depth of statistical methods implemented - so, for example, if you want to fit your system loads to a generalized autoregressive conditional heteroscedastic (I'm not making that up) time series model you can. There might be an implementation of that in Python or Perl, but I doubt its as widely-used or tested.
For me its weakness is the programming language itself - fairly irregular and quirky in places. Full of traps. If you've never used a programming language before you might take to it, if you're a competent programmer in any current language (Python, Perl, C(++), VB?) you might hate it.
If the statistical techniques and graphics exist in your favourite language of choice then I'd go for that. If you could implement them quite easily in your favourite language of choice I'd think about doing that. If you want cutting-edge stats that don't exist in other programming languages, use R.

Using R for crunching system data?


Gerar elementos HTML via Javascript

Question: Preciso criar um código que após passar alguns parâmetros ele gera-se um gráfico parecido com a imagem abaixo, pensei em criar uma tabela para cada atividade.
Alguém tem alguma dica, ou conhece um artigo que possa me ajudar?
Penso em usar Json para passar os dados (sei trabalhar com Json), meu problema seria criar essa function em Javascript

Essa tabela é definida por dependências, como vemos na imagem a atividade B é dependente da atividade A
Meu Json terá uma estrutura parecida com essa abaixo:

      CodigoProduto
      Quantidade
      PrecoUnitario
      Editar
      Deletar

Answer: Tente isto:

Este código vai no head de sua página, ele pega uma página isolada "cria_tabela.php" e alimenta o item "tabela" no seu código com o resultado desta página, assim você pode continuar a programar PHP com poucas linhas de JavaScript.
Este é o item a ser alimentado:

E na cria_tabela teria suas tabelas criadas em PHP.
Se ainda não conhece, recomendo dar uma pesquisada em bootstrap, para melhor aparência da página.

Gerar elementos HTML via Javascript


How to access attribute of interface

Question: It was my intention to use the HTTP status codes both in the header and the body of the two response structs. Bu that without setting the status code twice as function parameter and again for the struct to avoid redundancy.
The parameter response of JSON() is an interface to allow both structs to be accepted. The compiler throws the following exception:
response.Status undefined (type interface {} has no field or method Status)

because the response field must not have a status attribute. Is there an alternative way to avoid setting the status code twice?
type Response struct {
    Status int         `json:"status"`
    Data   interface{} `json:"data"`
}

type ErrorResponse struct {
    Status int      `json:"status"`
    Errors []string `json:"errors"`
}

func JSON(rw http.ResponseWriter, response interface{}) {
    payload, _ := json.MarshalIndent(response, "", "    ")
    rw.WriteHeader(response.Status)
    ...
}

Answer: The type response in rw.WriteHeader(response.Status) is interface{}. In Go, you need to explicitly assert the type of the underlying struct and then access the field:
func JSON(rw http.ResponseWriter, response interface{}) {
    payload, _ := json.MarshalIndent(response, "", "    ")
    switch r := response.(type) {
    case ErrorResponse:
        rw.WriteHeader(r.Status)
    case Response:
        rw.WriteHeader(r.Status)
    }
    ...
}

A better and the preferred way to do this however is to define a common interface for your responses, that has a method for getting the status of the response:
type Statuser interface {
    Status() int
}

// You need to rename the fields to avoid name collision.
func (r Response) Status() int { return r.ResStatus }
func (r ErrorResponse) Status() int { return r.ResStatus }

func JSON(rw http.ResponseWriter, response Statuser) {
    payload, _ := json.MarshalIndent(response, "", "    ")
    rw.WriteHeader(response.Status())
    ...
}

And it's better to rename Response to DataResponse and ResponseInterface to Response, IMO.
Comment: @user3147268 IMO it's better to use the interface. You can also create a base common structure that implements `Status()` but that's just an overdo. It's always ok to repeat a little in Go.
Comment: Naming is your preference. Go for anything you prefer. As a side note, in Go if an interface wraps a method `M` they call the interface 'M'er. Look at `io.Reader`, `io.Writer`, and `io.ReadWriteCloser` to get an idea.
Comment: Thanks for the solution. Is it now better so set the status code twice as new paramter and inside the structs or to write two new functions and an interface to achieve the same?
Comment: nit: `DataResponse` is probably better than `OKResponse`. Another name for the `Status() int` interface would be `Statuser` or just `Status` (the former doesn't sound right but there is a precedence for such `…er` non-word interfaces).
Comment: Thanks @Dave-C. Changed the answer a bit.
Comment: Then I'll use the interface approach.
Comment: By the way: would be `Responder` acceptable as interface name by following the -er convention?
Answer: Interfaces don't have attributes, so you need to extract the struct from the interface. To do this you use a type assertion
if response, ok := response.(ErrorResponse); ok {
    rw.WriteHeader(response.Status)
    ...

Comment: Why are you only use `response.(ErrorResponse)`?
Comment: @user3147268: I don't understand the question
Comment: Is there any difference of using either `response.(ErrorResponse)` or `response.(Response)`?
Comment: The difference is you get an `ErrorResponse` or you get a `Response`. If you want them to be interchangeable, make an new interface that gets the desired attributes.
Comment: That would be the approach of [Soheil Hassas Yeganeh](https://stackoverflow.com/users/1733239/soheil-hassas-yeganeh)

How to access attribute of interface


Is it true that $\sum_{j=k}^{2k} {2k \choose j}\big(\frac{1}{2}\big)^{2k}-\frac{1}{2}=\frac{1}{2}\Big({2k \choose k}\big(\frac{1}{2}\big)^{2k}\Big)$?

Question: On the first page of Lionel Penrose's 1946 paper "The Elementary Statistics of Majority Voting," Penrose claims that "the amount by which [an individual voter's] chance of winning exceeds one half" (call this quantity $A$) is equal to "half the likelihood of a situation in which an individual vote can be decisive--that is to say, a situation in which the remaining votes are equally divided upon the issue at stake" (call this quantity $B$).
Suppose an individual Bob has a given preference on a vote between two options/candidates. Based on the discussion in the paragraph quoted above, it seems like what Penrose means by quantity $A$ is the difference between $\frac{1}{2}$ and the probability that enough other voters will agree with Bob for his choice to win a majority vote, assuming that the probability any other voter agrees with Bob is $\frac{1}{2}$. Hence, if the number of voters is $2k+1$, it seems that what Penrose means by what we call quantity $A$ is $\sum_{j=k}^{2k} {2k \choose j}\big(\frac{1}{2}\big)^{2k}-\frac{1}{2}$.
Similarly, it seems that what Penrose means by quantity $B$ is one half times the probability that exactly one half of all voters other than Bob will agree with him, assuming each other voter has a $\frac{1}{2}$ chance of agreeing with Bob. So if there are $2k+1$ voters, it seems that what Penrose has in mind for what we call quantity $B$ is $\frac{1}{2}\Big({2k \choose k}\big(\frac{1}{2}\big)^{2k}\Big)$.
So it seems that Penrose is claiming that for all integers $k\ge 1$ we have $$\sum_{j=k}^{2k} {2k \choose j}\big(\frac{1}{2}\big)^{2k}-\frac{1}{2}=\frac{1}{2}\Big({2k \choose k}\big(\frac{1}{2}\big)^{2k}\Big).$$
But I'm wondering, how can one prove this identity? And is it even true? It seems to hold for the cases $k=1$ and $k=2$, but I haven't yet checked any others.
Answer: Take out the factor $(1/2)^{2k}$ and repeat the terms in reverse (we will have the middle term twice)
\begin{eqnarray*}
\sum_{j=k}^{2k} \binom{2k}{j} \left( \frac{1}{2} \right)^{2k} &=& \left( \frac{1}{2} \right)^{2k+1} \left( \sum_{j=0}^{2k} \binom{2k}{j} + \binom{2k}{k} \right) \\
&=& \left( \frac{1}{2} \right)^{2k+1} \left( 2^{2k} + \binom{2k}{k}\right) \\
 &=& \frac{1}{2}  + \binom{2k}{k} \left(\frac{1}{2} \right)^{2k}
\end{eqnarray*}
Comment: \begin{eqnarray*}
\sum_{j=k}^{2k} \binom{2k}{j}  &=& \frac{1}{2}  \left( \sum_{j=k}^{2k} \binom{2k}{j} + \sum_{j=k}^{0} \binom{2k}{j} \right) \\
\end{eqnarray*}
\begin{eqnarray*}
&=& \frac{1}{2} \left(\binom{2k}{k} +\sum_{j=0}^{2k} \binom{2k}{j} \right) \\
\end{eqnarray*}
Comment: This looks a little bit weird, I guess there is an error somewhere in your math mode ^^'. I just realized that my first question was nonsense


Move "Items per page" selector to the top of the content

Question: This is my problem of the day.
I would like to display the Items per page at the top of the content block.
I'm working on a View Block, this is an Exposed Filter with "Better Exposed Filter".
For now, I'm doing this the dirty way with jQuery and a unstable DOMSubtreeModified bind.
I have a twig with {{ exposed }}, but Drupal doesn't suggest me any deeper twig and if I had one, it wouldn't access the Content div I guess. So I have no idea about how to do this.
Here is the div organisation :

div.exposed-block

form.views-exposed-form

Filter-1
Filter-2
Items-per-page (select)

div.view-block (with my content)

So, the idea is to move Items-per-page to div.view-block.
Or into another that I can create, here is the twig part :

    {{ exposed }}

    {{ rows }}

How would you do this ?
Thanks in advance.
Answer: This is the answer I got from a forum.

    {{ exposed | without ('items_per_page') }}

    {{ exposed | without('my_first_other_filter', 'my_second_other_filter') }}
    {{ rows }}


Handle both singleClick and LongPress with GestureDetector in Android

Question: I have class that handles singleClickListener for RecyclerView. I am using GestureDetector to handle clicks. How can I add LongPressListener to same class to handle them both?
public class RecyclerViewItemClickListener implements RecyclerView.OnItemTouchListener {
    private OnItemClickListener mListener;

    public interface OnItemClickListener {
        public void onItemClick(View view, int position);
    }

    GestureDetector mGestureDetector;

    public RecyclerViewItemClickListener(Context context, OnItemClickListener listener) {
        mListener = listener;
        mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                return true;
            }

            @Override
            public boolean onDown(MotionEvent event) {
                // triggers first for both single tap and long press
                return true;
            }

            @Override
            public void onLongPress(MotionEvent event) {
                //...
                super.onLongPress(event);
            }
        });
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
        View childView = view.findChildViewUnder(e.getX(), e.getY());
        if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
            mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
        }
        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
    }

And I use this class like this in my activity:
recyclerView.addOnItemTouchListener(
                new RecyclerViewItemClickListener(this, new RecyclerViewItemClickListener.OnItemClickListener() {
                    @Override public void onItemClick(View view, int position) {
                        // TODO Handle item click
                        Log.d(TAG, "item clicket position: " + position);
                    }
                })
        );

Comment: Found answer for my question here http://stackoverflow.com/a/26826692/2098878
Answer: if you want to handle them both onInterceptTouchEvent, just use it like this.
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
private View childView;
private RecyclerView viewRecycle;

public interface OnItemClickListener {
    void onItemClick(View view, int position);

    void onLongItemClick(View view, int position);
}

GestureDetector mGestureDetector;

public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
    mListener = listener;
    mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            if (childView != null && mListener != null){
                mListener.onItemClick(childView, viewRecycle.getChildAdapterPosition(childView));
            }
            return true;
        }
        @Override
        public void onLongPress(MotionEvent e) {
            if (childView != null && mListener != null) {
                mListener.onLongItemClick(childView, viewRecycle.getChildAdapterPosition(childView));
            }
            super.onLongPress(e);
        }
    });
}

@Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
    AppHelper.AppLogger("inside");
    childView = view.findChildViewUnder(e.getX(), e.getY());
    viewRecycle = view;
    mGestureDetector.onTouchEvent(e);
    return false;
}

@Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {

}

@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

}


Apply jquery function for an ajax loaded content

Question: I have an issue.. the issue is jquery is not applying to a ajax content..
My jquery:-
$(document).ready(function() {

$('.mainWorkImage').hover(function() {
    $(this).find('.caption').fadeIn(200);
},
function() {
    $(this).find('.caption').stop(false,true).fadeOut(200);
});

});

Content : -
            echo "

PROJECT NAME:

".$mainResult['projectName']."

PROJECT TYPE:

".$mainResult['category']."

";

Whats happening here is i have a dropdown when the dropdown change the content will be fetched from DB using AJAX and displayed .. But the caption div is not displaying for the content loaded from AJAX . Please Help me . Thanks In Advance...
Comment: can u also paste the ajax part,i can't figure put only from the hover function.
Answer: depending on your jquery version take a look http://api.jquery.com/on/
Alternative use the "live" handler.
The .hover() handler does not work, because the target does not exist at the time it is applied.
Answer: you can either bind the functions on successful ajax load
i.e.
$.ajax{
url:
data:
    success(function){
     //put your bind elements here
    }
}

Alternatively you can use the on() api.
Comment: You're linking to the `.on()` documentation (which is good), although you talk about `.live()` (which is deprecated)
Answer: Try
$(document).ready(function() {

$('body').delegate('.mainWorkImage','hover',function() {
    $(this).find('.caption').fadeIn(200);
},
function() {
    $(this).find('.caption').stop(false,true).fadeOut(200);
});

});


Update database fields in form

Question: Hello so i'm learning php and basiclly i want that any field that has been already added to the database to be "editable"
Let me make it more clear with an example
My from looks like this (ver basic)

Firstname [input field]
Lastname [input field]
ZIP Code [input field]

send button
 <form method="post" action="">

                    Vorname
                    <input type="text" name="firstname">

                    Nachname
                    <input type="text" name="lastname">

                    PLZ
                    <input type="number" name="plz">

            <button type="submit" name="send">Send</button>
  </form>

When the send button is pressed the output is beeing shown in a table below like so
|---------------------|------------------|------------------|
|      Firstname      |     Lastname     |   Zip Code       |
|---------------------|------------------|------------------|
|       Tomas         |       Möller     |   123123         |
|---------------------|------------------|------------------|

and next to those to rows i still have these two (which didn't fit)
|---------------------|------------------|
|     Update          |     Delete       |
|---------------------|------------------|
|      update         |         delete   |
|---------------------|------------------|

                #
                First Name
                Last Name
                PLZ
                Delete
                Update

            <?php
            /**
             * @var $contact ContactDto
             */
            $contacts = $contactRepository->findAll();

            foreach ($contacts as $contact) {
                ?>

                    <?php echo $contact->getId()?>
                    <?php echo $contact->getFirstname() ?>
                    <?php echo $contact->getLastname() ?>
                    <?php echo $contact->getPlz() ?>
                    <a href=delete.php?id=<?php echo (int)$contact->getId()?> >Delete
                    <a href=update.php?id=<?php echo (int)$contact->getId()?> >Update

                <?php
                }
                ?>

So basicaly each row has this own update and delte button.
Here is my problem..im not sure how to do this the right way.
I want when the update is clicked, the value from to fields "go back" to the top field and when send is pressed again the values are updated.
Here is my query
public function update(ContactDto $contactDto) {

        $stmt = $this->pdo->prepare("UPDATE contacts SET firstname=:firstname,
                                                                  lastname=:lastname,
                                                                  plz=:plz
                                                                  WHERE id=:id");
        $stmt->bindValue(':firstname', $contactDto->getFirstname(), PDO::PARAM_STR);
        $stmt->bindValue(':lastname', $contactDto->getLastname(), PDO::PARAM_STR);
        $stmt->bindValue(':plz', $contactDto->getPlz(), PDO::PARAM_INT);
        $stmt->bindValue(':id', $contactDto->getId(), PDO::PARAM_INT);
        $stmt->execute();

    }

I did try and make a new update.php file where the data is send, and the fields get filled like so (but that didnt quite work)
this is my update.php file
$contactRepository = new ContactRepository(
    DatabaseConnection::getConnection()
);

$contactDto = new ContactDto();
$contactDto->setId($_GET['id']);
$contactDto->setFirstName($_POST['firstname']);
$contactDto->setLastName($_POST['lastname']);
$contactDto->setPlz($_POST['plz']);

$contactRepository->update($contactDto);

?>

<form method="post" action="update.php">
    <input type="hidden" name="id" value="<?php echo $contactDto->getId(); ?>" />
    <?PHP
    ?>

            First Name:

                <input type="text" id="vorname" name="firstname" placeholder="Dein Vorname" size="35" value="<?php echo $contactDto->getFirstName(); ?>">

            Last Name:

                <input type="text" id="nachname" name="lastname" placeholder="Dein Nachname" size="35" value="<?php echo $contactDto->getLastName(); ?>">

    <input type="submit" name="save" value="Update" >

Which leaves me with..
>

Notice: Undefined index: firstname in C:\xampp\htdocs\test\update.php on line >14
Notice: Undefined index: lastname in C:\xampp\htdocs\test\update.php on line >15
Notice: Undefined index: plz in C:\xampp\htdocs\test\update.php on >line 16
Answer: About the update.php page: the error messages you're getting are saying that 'firstname', 'lastname' and 'plz' are not defined.
This is because you tried to define them using POST:
$contactDto->setFirstName($_POST['firstname']);
$contactDto->setLastName($_POST['lastname']);
$contactDto->setPlz($_POST['plz']);
But in fact, the values of firstname, lastname and plz were not posted to this page. POST is only 'activated' when you click a submit button in a form where you wrote
<form method="POST"...

But you didn't get on the update.php page via a form, but via a hyperlink in this table you made:
        foreach ($contacts as $contact) {
            ?>

                <?php echo $contact->getId()?>
                <?php echo $contact->getFirstname() ?>
                <?php echo $contact->getLastname() ?>
                <?php echo $contact->getPlz() ?>
                <a href=delete.php?id=<?php echo (int)$contact->getId()?> >Delete
                <a href=update.php?id=<?php echo (int)$contact->getId()?> >Update

            <?php
            }
            ?>

This is not wrong tho! This table is very good.
But on the update.php page, you can't define 'firstname', 'lastname' and 'plz' using $_POST['....'].
The only thing on the update.php page that IS defined, is 'id'. This is because 'id' was the only thing that you sent to this page using the get method. Again: this is the right way to do it so don't change that.
**
What you DO need to change, is this:
**
change your code:
$contactDto = new ContactDto();
$contactDto->setId($_GET['id']);
$contactDto->setFirstName($_POST['firstname']);
$contactDto->setLastName($_POST['lastname']);
$contactDto->setPlz($_POST['plz']);

To this:
  $contactDto = new ContactDto();
    $contactDto->setId($_GET['id']);

So only 'id' is defined.
Now define 'firstname', 'lastname' and 'plz' by getting those values from your database, using a query.
Like this:
$getstuff = "SELECT * FROM yourtablename WHERE id = $thevariablethatcontainstheid";

(I guess the variable that contains the 'id' is $contactDto->setId();  ??)
Then execute the query on the next line:
$results = mysqli_query($yourconnectingthing,$getstuff);

And write this below:
$row = $results->fetch_assoc();

And then you can define 'firstname', 'lastname' and 'plz'! By writing this:
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$plz = $row['plz'];

Now the last thing you need to change is the values in the editing form.
This was your code:

            First Name:

                <input type="text" id="vorname" name="firstname" placeholder="Dein Vorname" size="35" value="<?php echo $contactDto->getFirstName(); ?>">

change it to:

            First Name:

                <input type="text" id="vorname" name="firstname" placeholder="Dein Vorname" size="35" value="<?php echo $firstname ?>">

Comment: in the form the echo should be wrapped in a isset() because if you load the page without clicking any edit button you will get an undefined error again

Update database fields in form


C# PDF table add row in wrong position

Question: [EDIT due to misunderstanding of the answer]
I'm doing a simple program in C# with PDF file creation with iText7.
In this PDF i'm adding a table whose first cell starts at a certain position in the file.
I don't know if I set the position correctly, but everytime I add another cell with tab.StartNewRow() the resulting new table is repositioned taking THAT last cell as position reference, putting the previously added cells from that point up, while I want to add the cells from that point down.
Which method should I use? That's my code:
Previously I set the position of the first table cell using tab1.SetFixedPosition(20, heigh, width);
and then, in order to add the other cells:
if (mylistbox.Items.Count > 0)
  {
     tab1.AddCell("FIRST CELL");
     tab1.StartNewRow();
     for (int i = 0; i < mylistbox.Items.Count; i++)
        {
          tab1.AddCell(mylistbox.Items[i].ToString());
          tab1.StartNewRow();
        }
        doc.Add(tab1);
  }

[EDIT #2] in order to explain my issue better
I have to put 5 tables, which have to grow from a certain point DOWN, positioned at equal distances, same height and width in the doc. This image explains how it should result:
Comment: That's indeed what `SetFixedPosition` does, it's documented as *The coordinates specified correspond to the bottom-left corner of the element and it grows upwards.*
Comment: so.... do you know a method which takes as reference the top of the table and makes it grow downwards?
Comment: false, it doesn't work. It puts the next table under the previous one because it calculates the position relative to the previous item
Comment: Have you considered creating a `Canvas` on the page in question with left, top, and right margins as you want them, and the bottom far enough down to allow any expected table size, and then adding the table without `SetFixedPosition` to that `Canvas`?
Comment: You mean creating a different canvas for every single table and then adding it to the doc with different positions? So, for example, if I have  5 tables, I have to use 5 canvas?
Comment: *"You mean ..."* - yes. It sounds a bit tedious but actually isn't that bad, two or three lines in code.
Comment: I'm sorry, I didn't want to be tedious, I'll try it out! Thanks! ;)
Comment: *"I didn't want to be tedious"* - no, no, i didn't mean you, i meant the procedure i proposed.
Comment: If you're interested, I put a draw to explain better what I mean @mkl
Answer: In a WPF application, I have a ListBox with 5 items, numbered 1 through 5. This should be very similar to WinForms.
The CreatePercentArray takes a size which is equal to the amount of columns in a row.
An interesting article about tables: link
  private void CreateListBoxTable(Document pdfDoc)
        {
            // Create an array where each item has an equal width, and use the entire pdf width
            // The CreatePercentArray takes a size which is equal to the amount of columns in a row
            // By using percentages, they will automatically adapt
            // Use CreatePointArray for exacter measurements
            var table = new Table(UnitValue.CreatePercentArray(2)).UseAllAvailableWidth();

            if (!MyListBox.Items.IsEmpty)
            {
                foreach (var listBoxItem in MyListBox.Items)
                {
                    table.AddCell(((ListBoxItem) listBoxItem).Content.ToString());
                }
            }
            // Adds table to document
            pdfDoc.Add(table);
            // Closes document
            pdfDoc.Close();
        }

Comment: Hello, I tried using your exact code without the `SetFixedPosition`and using a table with just 1 column. Adding the items your way even when the program is running does not affect the position of my table, it just adds items vertically and downwards. The first items added on top and the last items on the bottom. I still don't see what your exact problem is and how it is occurring.
Comment: Thank you for your answer, but I explained my issue badly, it's my fault, I'm not sure if you have understood my question. Anyway, I'll try out your method, if you may read my question again, I'll be very glad.
 Thank you very much!!
Comment: Doing this way, of course it works, but I want to put the tables at a certain positions in the document. So without using SetFixedPosition the problem is solved, but the table is positioned randomly
Comment: I need a method to put the first cell of the table at a customed position, and at the same time make it grow downwards
Comment: Hello, I edited my question improving my issue explaination and putting a draw to explain better how it should result, thanks for your patience @Mayfair

C# PDF table add row in wrong position


App component should place on top of all components in reactjs

Question: i am trying to develop reactjs app with some components. 'App.jsx' have navigation bar. I want that navigation bar should be in front of all child components. When i try to use margins, its not working properly. Please help me. Thanks. Here i have code.
App.jsx:
import React from 'react';
import { Route, NavLink, HashRouter } from "react-router-dom";
import Home from './pages/Home.jsx';
import Stuff from './pages/Stuff.jsx';
import Content from './pages/Contact.jsx';

class App extends React.Component {
 render() {
  return (
    <HashRouter>

<NavLink exact to="/">Home</NavLink>

<NavLink to="/stuff">Stuff</NavLink>

<NavLink to="/contact">Contact</NavLink>

                <Route exact path="/" component={Home} />
                <Route path="/stuff" component={Stuff} />
                <Route path="/contact" component={Contact} />

    </HashRouter>
  );
 }
}

export default App;

Home.jsx:
import React, { Component } from 'react';

class Home extends Component{

    render(){
        return(

        );
    }
}

export default Home;

By default, all child components are displaying on top of App component.
Comment: what is the expected behaviour
Answer: You're header is displayed behind the rest because he's declared before the rest.
You can use z-index property as follow:
.header {
  z-index: 1;
}

I'm not sure about what you are trying to achieve but maybe doing something like that could be better:
.header {
  position: fixed;
  top: 0;
  right: 0;
  left: 0
}

PS: The rule width:'100%' in {{ height:'100%', width:'100%', marginTop:-150 }} is useless. A
 is displayed as a block by default. It means that he will takes the whole width.


Vaadin 8 Grid scrollbars behave erratically when CSS is used for column widths

Question: I have a Grid in my Vaadin 8 application and sometimes the Grid's scrollbars appear when they aren't needed or disappear when they shouldn't. They can even get stuck in a loop. My Grid has five columns, and I only use built-in Renderers that come with Vaadin 8.
I use CSS to set the column width for the first column to 30%. The problem doesn't appear if I remove that line from my theme, but I need it. How can I get it to work?
Answer: Vaadin 8 Grid doesn't support configuring column widths via CSS, you should set any and all column width configurations programmatically (via myColumn.setWidth(pixelWidth);) or the client-side calculations break. Those calculations are crucial for determining the expected width for any columns that don't have a fixed width, and are consequently tightly tied into the scrollbar logic.
Unfortunately there is no built-in solution for setting a percentual width for a column, or for getting Grid's actual size from the server side, or for listening to Grid's size change. However, you can use SizeReporter add-on to help with the latter two (check the Code Samples tab for usage instructions), and calculate the required pixel width from there. GridScrollerExtension add-on also offers both functionalities, as well as querying the current column widths and other Grid-specific features.
For a slightly hackier solution you could also use a JavaScript callback to query the width:
        ui.getPage().getJavaScript().addFunction("gridSizeCallback",
                new JavaScriptFunction() {
                    @Override
                    public void call(JsonArray arguments) {
                        // set myColumn width as 30%
                        myColumn.setWidth(arguments.getNumber(0) * 0.30);
                    }
                });
        ui.getPage().getJavaScript()
                .execute("gridSizeCallback(document.getElementById('"
                        + grid.getId() + "').clientWidth);");

Note that this only gives you the initial width, and doesn't help with the resize problem. The solution for that depends on what all can trigger the Grid resize (e.g. repeating the second JavaScript call through ui.getPage().addBrowserWindowResizeListener when the browser is resized).
Answer: I wanted to extend the answer https://stackoverflow.com/a/67474239/1184842 of Anna Koskinen, but it's a little bit to much code for a comment, so no real separate answer here...
The SizeReporter can be used only as an idea how to send the client side sizes to the server, because one needs the inner width of the tableWrapper in the Escalator of the Grid. Otherwise the vertical scrollbar space might be used as space for the columns leading to wrong results and e.g. wrapping of columns.
I got this working by changing the implementation in an derived class of the Grid with an extended Connector. I changed the init method templating from the extend method from SizeReporterConnector this way:
    @Override
    protected void init() {
        super.init();

        this.extendedGridServerRpc = this.getRpcProxy(ExtendedGridServerRpc.class);

        final Element widget = getWidget().getEscalator().getTableWrapper();

        if (widget.getOffsetWidth() > 0 && widget.getOffsetHeight() > 0) {
            extendedGridServerRpc.innerSizeChanged(widget.getOffsetWidth(), widget.getOffsetHeight());
        }

        LayoutManager.get(this.getConnection()).addElementResizeListener(widget, new ElementResizeListener() {
            public void onElementResize(ElementResizeEvent event) {
                extendedGridServerRpc.innerSizeChanged(widget.getOffsetWidth(), widget.getOffsetHeight());
            }
        });
    }


Chrome e bug background fixed

Question: Estou com o seguinte problema:
Possuo algumas seções na página separadas em divs. Duas dessas divs recebem uma imagem como background e background-position:fixed, então quando rola a página as imagens devem rolar junto, fazendo aquele efeito Parallax simples.
Porém no Google Chrome, ao rolar a página, a imagem não segue e quebra toda.
No Firefox funciona e, por incrível que pareça, no IE também!
Acontece na página "sobre".

p, h3 {
    font-family: "Open Sans",sans-serif;
    font-weight: 200;
}
ul {
    list-style: outside none none;
}
.social p, a:hover, a:active {
    text-decoration: none;
}
h1, h2, .menu, .ver-mais {
    text-align: center;
}
.ver-mais, .promo-title, .header-bkg, .slide, .separator {
    background: none repeat scroll 0 0 #00011c;
}
.social img, nav li, .box-purple, .ver-mais, .gallery img, .ambiente img, .reside a {
    transition: all 1s ease 0s;
}
.promocoes, .wrapper-sobre, footer, .social p, a:hover, a:active, .menu ul li a {
    color: #fff;
}
.promo-title, .ambiente h1, .portfolio .ver-mais:hover {
    color: #ed297b;
}
.box-purple, .promocoes a, .ver-mais {
    display: block;
}
.ambiente h3 {
    border-bottom: 1px solid black;
    margin-bottom: 20px;
    padding-bottom: 5px;
}
.header-bkg, .slide .item, .ambiente img, .separator {
    width: 100%;
}
.box-purple, .promocoes a {
    padding: 10px 20px;
}
.promocoes ul li, .portfolio-item img, .contato {
    padding: 10px;
}
.promocoes ul li, .ambiente p {
    text-align: justify;
}
.ambiente a, .promo-title {
    font-weight: bold;
}
.ver-mais, .ambiente h1 {
    margin: 0 auto;
}
.galeria, .ambiente img, .atendimento, .sala-vip, .localizacao {
    padding: 20px;
}
.menu {
    font-size: 7em;
    margin-right: 5%;
    margin-top: 4%;
}
.header-bkg {
    height: 140px;
    opacity: 0.8;
    position: absolute;
    z-index: -1;
}
.slide {
    margin-top: -20%;
    z-index: -5;
}
.slide .item {
    max-height: 500px;
    opacity: 0.6;
}
.promo-bkg-img {
    background: url("../img/tattoo_2.jpg") repeat scroll 0 0 rgba(0, 0, 0, 0);
}
.promo-bkg-filter {
    background: none repeat scroll 0 0 rgba(0, 1, 28, 0.38);
}
.box-purple {
    background: none repeat scroll 0 0 #46132d;
}
.box-purple:hover {
    background: none repeat scroll 0 0 #7c2f57;
}
.promo-title {
    font-size: 62pt;
    letter-spacing: 0.7em;
    text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.5);
    text-transform: uppercase;
}
.promo-list {
    margin-bottom: 50px;
}
.portfolio-item img {
    width: 90%;
}
.ver-mais {
    color: #000;
}
.ambiente {
    padding-bottom: 20px;
    text-align: center;
}
.ambiente a {
    color: #37011d;
}
.ambiente h1 {
    border-top: 1px solid black;
    width: 50%;
}
.ambiente img {
    height: 300px;
}
.ambiente ul li {
    list-style-type: square;
    text-align: left;
}
.gallery img:hover, .ambiente img:hover {
    box-shadow: 0 0 50px #999;
}
.separator {
    height: 10px;
}
.social {
    background: none repeat scroll 0 0 #010240;
    text-align: center;
}
.social img {
    margin: 20px;
    width: 30%;
}
.social img:hover {
}
.sobre, .atendimento, .sala-vip {
    background: url("../img/texture-bkg.png") repeat scroll 0 0 rgba(0, 0, 0, 0);
}
.sobre h1, .atendimento h1, .sala-vip h1, .sobre h2, .atendimento h2, .sala-vip h2, .sobre p, .atendimento p, .sala-vip p {
    color: #000;
}
.sobre img, .atendimento img, .sala-vip img {
    margin: 2% 10%;
    width: 80%;
}
.atendimento p, .sala-vip p {
    color: #fff !important;
}
html {
    height: 100%;
    min-height: 100%;
}
body {
    min-height: 100%;
}
html, body {
}
@media not all {
.equips, .sala-vip {
    background-attachment: scroll;
}
}
.equips, .sala-vip {
    padding: 5% 0;
}
.equips h1, .sala-vip h1 {
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.25);
}
.equips {
    background: url("http://oi61.tinypic.com/2vs1en8.jpg") repeat fixed 0 0 rgba(0, 0, 0, 0);
}
.sala-vip {
    background: url("http://oi61.tinypic.com/dph8n6.jpg") repeat fixed 0 0 / 100% auto rgba(0, 0, 0, 0);
}
.contato {
    background: none repeat scroll 0 0 #000149;
    font-size: 15pt;
}
.contato span {
    font-size: 10pt;
}
input:focus, input:hover, textarea:focus {
    background: none repeat scroll 0 0 #010240;
    transition: all 0.5s ease-in 0s;
}
.footer {
    background: none repeat scroll 0 0 #232323;
    padding: 10px;
}
.reside {
    float: right;
}
.reside a {
    color: #d81900;
}
.reside a:hover {
    color: #fff;
}
.navbar-nav {
    height: 140px;
}
.pagina-ativa, .nav li:hover, .nav li:focus {
    background: none repeat scroll 0 0 #ed297b;
    height: 140px;
    margin-top: -47px;
    padding-top: 47px;
}
.nav .active, .nav li a:hover, .nav li a:focus {
    background: none repeat scroll 0 0 rgba(0, 0, 0, 0);
}
.form-control, .btn-send {
    background: none repeat scroll 0 0 #822c58;
    border: medium none;
    border-radius: 0;
    color: #fff !important;
    font-family: "Playball",cursive;
    font-size: 16pt !important;
    padding: 4px !important;
}
.form-control:-moz-placeholder, .btn-send:-moz-placeholder {
    color: #ecaacc;
}
.form-control::-moz-placeholder, .btn-send::-moz-placeholder {
    color: #ecaacc;
}
.btn-send {
    background: none repeat scroll 0 0 #dc64a1;
    color: #ecaacc !important;
}
.shot {
    display: none;
    opacity: 1;
}
.navbar-toggle .icon-bar {
    background: none repeat scroll 0 0 white;
}
@media screen and (min-width: 320px) and (max-width: 380px) {
#logo {
    margin-top: -20px;
    width: 50%;
}
.promo-title {
    font-size: 30pt;
    letter-spacing: 0.3em;
}
.promocoes a {
    padding: 10px 20px;
}
.promocoes ul li {
    padding-bottom: 1px;
}
.ambiente img {
    height: 200px;
    width: 80%;
}
}
@media screen and (max-width: 620px) {
.promocoes, .sobre, .galeria {
    background: url("../img/texture-bkg.png") repeat scroll 0 0 rgba(0, 0, 0, 0);
}
}
@media screen and (min-width: 410px) and (max-width: 620px) {
#logo {
    width: 40%;
}
.promo-title {
    font-size: 30pt;
    letter-spacing: 0.3em;
}
.promocoes ul li {
    padding-bottom: 1px;
}
}
@media screen and (min-width: 600px) and (max-width: 800px) {
#logo {
    width: 70%;
}
.navbar-nav {
    margin-top: -33px;
}
.slide {
    height: 420px;
    margin-top: -28%;
}
.promo-title {
    font-size: 40pt;
    letter-spacing: 0.5em;
}
.promocoes a {
    padding: 10px 20px;
}
.promocoes ul li {
    padding-bottom: 1px;
}
.ambiente img {
    height: 400px;
    width: 80%;
}
}
@media screen and (max-width: 760px) {
.container > .navbar-collapse {
    margin: 0 auto;
}
.navbar-collapse {
    padding: 20px 15px !important;
    width: 100%;
}
.navbar-nav {
    height: auto;
    margin: 0 auto;
}
.menu {
    background: none repeat scroll 0 0 #333349;
    font-family: Arial;
    font-size: 18pt;
    margin-top: 20% !important;
}
.menu li:hover {
    background: none repeat scroll 0 0 rgba(0, 0, 0, 0);
    height: auto;
    margin: 0;
    padding: 0;
}
.pagina-ativa {
    height: auto;
    margin: 0;
    padding: 0;
}
}
@media screen and (min-width: 1020px) {
.slide .item {
    max-height: 500px;
    width: 100%;
}
.ambiente img {
    height: 200px;
    width: 100%;
}
}
@media screen and (min-width: 1280px) {
.slide .item {
    max-height: 600px;
}
.ambiente img {
    height: 300px;
    width: 100%;
}
}
@media screen and (min-width: 1920px) {
.slide .item {
    max-height: 1000px;
}
}

Sobre

Há 6 anos o Jhony Bigu atua no mercado da tatuagem na Zona Norte e atualmente nas regiões do Itaim Bibi, Vila Nova Conceição e Vila Olímpia.

O Jhony Bigu esta altamente qualificados e apresenta um novo conceito de tatuagens personalizadas que segue um alto padrão de qualidade.

O tatuador Jhony Bigu é um profissional experiente e qualificado que está apto a ajuda-lo a encontrar ou criar o melhor desenho para sua tatuagem, prestando um atendimento personalizado desde a seleção de ideias até a elaboração da arte final para a tatuagem escolhida.

Studio

O Studio JB Tattoo está constantemente renovando seus equipamentos e materiais em busca da melhor tecnologia e qualidade disponível no mercado.

Equipamentos

                            Todos os matérias utilizados no Studio são totalmente descartáveis nas tatuagens, evitando-se o risco
                            de contaminação cruzada. O Studio conta com um ambiente aconchegante para que seus clientes sejam
                            atendidos de forma bastante à vontade, tendo o máximo de conforto durante a elaboração dos desenhos,
                            assim como na realização dos procedimentos de tatuagens.

Atendimento

Política de atendimento:

Cada sessão de tatuagem tem duração de 1 hora

Acima de uma sessão de tatuagem ocorrera com duração media de 3 horas (podendo variar de acordo com a resistência e condições de cada cliente).

Necessário o preenchimento de Termo de responsabilidade para todos os clientes.

Tatuagens para menores de idade somente na presença de um dos responsáveis e mediante o preenchimento do termo de responsabilidade e documentos de identificação com foto.

Sala Vip

                        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
                        tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                        quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
                        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
                        cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
                        proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Como fica ao rolar a página:

Pesquisando na net, achei essa possível solução:
 $(document).scroll(function(){
     $(this).find('.fixbg').hide().show(0);
 });

Porém com esse código, ao rolar a página, o Scroll não vai até o final, trava nas imagens e não desce mais.
Comment: editei sua pergunta colocando um "code snippet" que seria um executável de código html+css+js com seus códigos lá. porém o exemplo não se torna funcional por causa das imagens que não estão disponíveis, teria como você upar as imagens e atualizar a origem delas no snippet? ou se você não souber, comente aqui o link das imagens e depois que eu adiciona-las pode apagar o comentário.
Comment: Valeu!!! Vou colocar as imagens ali :D
Comment: tens certeza que adicionou todo o html e css necessários? pois não ficou igual a imagem que você demonstrou, deve estar faltando algo, acredito que seja CSS :D
Comment: Vish... Eu uso Less... Vou fazer o seguinte: Vou compilar e colocar ali pra ficar certinho. :D
Comment: Utilizo a Versão 38.0.2125.122 do chrome e funciona normal! testei em outros navegadores e fluiu. Testei seu código sem o javascript - Cara! Testei pelo link que enviou (http://server.gruporeside.com.br/jhonybigutattoo/public/index.php?canal=sobre) e aqui esta normal. O chrome não apresenta nada e anormalidade.
Comment: Opa, verifica por esse link Eduardo: http://server.gruporeside.com.br/jhonybigutattoo/public/index.php?canal=sobre
Comment: Cara! Testei pelo link que enviou (http://server.gruporeside.com.br/jhonybigutattoo/public/index.php?canal=sobre) e aqui esta normal. O chrome não apresenta nada e anormalidade.
Comment: Desculpe, acho que faltou foi minha informação... Acessa a página sobre e tenta rolar até o final... Ele trava antes do formulário do footer.
Comment: Não entendi exatamente onde tá bugando mas aqui pelo menos se você tirar a classe fixbg o scroll vai até o final, mas acho que o efeito que você quer não funciona.
Comment: Oi @haykou! Então, o efeito funciona no Firefox, IE e tudo mais... Só no Chrome que não vai...
Answer: Espero que já tenha achado uma outra solução.
No site em inglês, localizei alguém que fez a mesma pergunta.
Invés de "consertar", ele fez um workaround usando a proprieda clip e a position:fixed.
Veja a pergunta aqui e o jsfiddle que ele fez.
Espero que ajude nas próximas.

Chrome e bug background fixed


How to display entity reference field in User Profile Twig

Question: I asked this over on the Drupal.org forum, but I thought I'd give it a try here too.
I am using an taxonomy entity reference field to display author names on our site.  I added a 'published_name' field and referenced it to the Author taxonomy. What I'd like to do is make a custom user profile twig that shows that entity reference field value on the author's profile page, including it's link, so when the displayed name is clicked, it shows all the books connected to that author.
I made two different profile types using the Profile Module. Everyone gets a Public Profile, and the authors get a second one just for their custom information. The Writer Profile (machine name writer_profile) is the one with the field 'field_published_name'.
On the writer's profile page, In the manage display of admin/config/people/profile-types/manage/writer_profile, I added the Published name field, I set it as Format: Label; Link to the referenced entity. The field does show, and work when clicked on the User page, but I can't control where, and how, it looks without using a twig. I want to customize when, where, and how it would be displayed on the page.
I have tried in the user.html.twig:
<code>{% for item in items %}
  {{ item.content['#user'].field_published_name.value }}
{% endfor %}
</code>
Also:
<code><article{{ attributes.addClass('profile') }}>
  {% if content %}
    {{- content.field_published_name -}}
  {% endif %}
</article>
</code>
On admin/config/people/accounts/display I have it set to show the 'Public Profile profiles' and 'Writer Profile profiles' format as Rendered entity.
So far it just comes up empty while showing the rest of the user's info on their profile page.
Comment: In this case the field can be set to display the 'Label' and linked to the entity. There are not enough details here, but it is otherwise fairly standard Drupal field rendering. In the user profile twig, {{ content.field_published_name }} is all that is needed, and it needs to not be hidden on Manage Display.
Comment: I used the Profile Module to make the two different profile types. On the writer's profile page, In the manage display of admin/config/people/profile-types/manage/writer_profile, I set it as Format: Label; Link to the referenced entity. I am trying to find a way to display that field in the user.html.twig that is being used to display the rest of the user's info. I tried your suggestion of {{ content.field_published_name }} and it still shows as empty.
I added it like this:

`Author Name:
{{ content.field_published_name }}
`

so I could see where it should be.
Answer: The question is not really clear, at least for me.
If it is: "how I customize the display of an entity referenced via a entity reference field" you have at least two ways:

On the child entity - taxonomy term - configure a view mode in the way you want. On the parent entity display mode choose "Rendered entity" as display mode of the field, and choose the display set up above.
If necessary, you may override the twig of that "child entity" display to fine grain the customization

In the twig of the parent entity you can access the "child" entity either with

<code>{% set child_entity = content.field_reference.entity %}
{% set child_entity = drupal_entity('entity_type', entity_id') %} // using twig tweak module
</code>
Comment: Sorry for the confusion. I updated the original question in hopes of making it clearer. In the manage display of admin/config/people/profile-types/manage/writer_profile, I set it as Format: Label; Link to the referenced entity. I am trying to find a way to customize the way that field is displayed in the user.html.twig that is being used to display the rest of the user's info.
Comment: Have you tried to use `user` entity instead of `content`? There you should find _all_ the fields of the entity and not just the ones actually printed.
Comment: I tried user, and profile, instead of content, but neither worked.  If I add the same field to the default /admin/config/people/accounts/fields, I can add it into the user.html.twig manually using: {{ content.field_published_name.0 }}  This does work, but I'm trying to make it so only users with the role 'published writer' will be able to add to that field.    Everything I read says this should work from the writer profile - and published name: {{ content.writer_profile.entity.field_published_name }} but it dosen't.
Comment: if you debug the user entity what you get? Because the path is different front the content. E.g. do `{{ dd(user)}}` and from there try to get the writer_profile or the field_published_name
Comment: I added {{ dd(user)}} to user.html.twig and just got a Twig\Error\SyntaxError. Is that what you asked me to try? Trying not to sound stupid.
Comment: I installed devel and when I look for the published name in the field info, I see it listed as profile.field_published_name. I even tried that and it didn't work. I don't think I'm doing something right to get the data when I use {{ dd(user)}} or others. I thought I just add that to the twig somewhere to display the data.


Inequality of the probability of a sequence of events

Question: Let $(A_n)_{n\ge 1}$ be a sequence of events in a probability space $(\Omega,\mathcal{F},\mathbb{P})$ and
$$ A=\{ \omega\in \Omega: \omega\in A_n \text{ for infinitely many }n \}. $$
Show that
$$ \mathbb{P}(A)\le\sum_{k=n}^{\infty} \mathbb{P}(A_k) $$
for all $n$.
I tried to expresss $A$ as some combinations of $A_k$ but I cannot construct for arbitrary $n$. I also tried induction but had no clues.
Any hints are appreciated.
Answer: Hint
$$A=\bigcap_{n\in\mathbb N}\bigcup_{m\geq n}A_m.$$


How do I migrate this module?

Question: I just migrate my Drupal 6 website to Drupal 7 successfully, using migrate_d2d module. Is there an easy way to migrate Drupal 6 xml sitemap to Drupal 7 too?
Should I just install the XML sitemap module in Drupal 7 and it'll create its own?
Comment: Ideally you should install D7 version of XMLsitemap module and it will create it's own as you said..
Answer: Your D7 may not remain unchanged forever.  When it change, you will want its sitemap to change in concert with the site. In other words, you need something like XML Sitemap on your site.
You should therefore install the XML Sitemap module (as you suggest yourself).  The module actually has an upgrade path if you used the D6 version of the module to generate the D6 sitemap.
If your D6 sitemap was generated by some other means, or if you don't care about preserving the D6 settings for the sitemap, just install at as a fresh module on D7, and it will create a new sitemap.

How do I migrate this module?


sugarcrm users insert in magento

Question: Hi  I have a sugarcrm instance and magento instance they two are separate
i mean they have different databases.  My requirement is when i create a user in the sugarcrm ,it should also insert the admin users in magento  How can i do that in sugar,where the code has to be executed in sugar. Any other way is a
Answer: I would have to do some research on the Magento API, but in Sugar, you would want to create a logic hook in the Users module that triggers 'after_save'. You would point it to a custom class/method you've created that would use Magento's API for creating a new user.
Answer: You will need to use logic hooks and "after_save" will work for you. So add a logic in after_save. Write you code in simple PHP which will get data from Sugar bean fields and will create Magento user accordingly. Read this link for logic hook: http://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_7.9/Architecture/Logic_Hooks/#Module_Hooks

sugarcrm users insert in magento


How do I prove the sequence $s_{n}=\sqrt{n}$ diverges?

Question: I think this needs to be done as a counterexample:
Assume $s_{n}$ converges to $s$. Then $|s_{n} - s|<\epsilon$ for all $n>N$. And then I get stuck...
Comment: If this sequence converges, then the subsequence $\sqrt{n^2}=n$ also converges right?
Comment: I agree with the comment of @hamedp. Another way to argue is:
If $a_n\to s$, then $a_n^2\to s^2$ by the rule of products of limits. But $a_n^2=n$.
Answer: Well, if you are determined to use a counter example, then
$|s_{n} - s|<\epsilon$ so $s_n^2 - 2s_n*s + s^2 = n + s - 2s_n*s < \epsilon^2$
$|s_n| < |s - \epsilon|$ so $n + s \pm(s - \epsilon)*2*s < \epsilon^2$
$n <e^2 - s \mp (s - \epsilon)*2*s = V$ for some finite and constant V. So for all n > N then n < V which is ....
Answer: hint: Show that it is unbounded


Java HashMap with Int Array

Question: I am using this code to check that array is present in the HashMap:
public class Test {
    public static void main(String[] arg) {
        HashMap<int[], String> map = new HashMap<int[], String>();
        map.put(new int[]{1, 2}, "sun");
        System.out.println(map.containsKey((new int[]{1, 2})));
    }
}

But this prints False. How can I check that array is present in the HashMap?
Answer: The problem is because the two int[] aren't equal.
System.out.println(
    (new int[] { 1, 2 }).equals(new int[] { 1, 2 })
); // prints "false"

Map and other Java Collections Framework classes defines its interface in terms of equals. From Map API:

Many methods in Collections Framework interfaces are defined in terms of the equals method. For example, the specification for the containsKey(Object key) method says: "returns true if and only if this map contains a mapping for a key k such that (key==null ? k==null : key.equals(k))."

Note that they don't have to be the same object; they just have to be equals. Arrays in Java extends from Object, whose default implementation of equals returns true only on object identity; hence why it prints false in above snippet.

You can solve your problem in one of many ways:

Define your own wrapper class for arrays whose equals uses java.util.Arrays equals/deepEquals method.

And don't forget that when you @Override equals(Object), you must also @Override hashCode

Use something like List<Integer> that does define equals in terms of the values they contain
Or, if you can work with reference equality for equals, you can just stick with what you have. Just as you shouldn't expect the above snippet to ever print true, you shouldn't ever expect to be able to find your arrays by its values alone; you must hang-on to and use the original references every time.

See also:

Overriding equals and hashCode in Java
How to ensure hashCode() is consistent with equals()?
Understanding the workings of equals and hashCode in a HashMap

API

Object.equals and Object.hashCode

It's essential for a Java programmer to be aware of these contracts and how to make them work with/for the rest of the system
Answer: You are comparing two different references.
Something like this will work:
public class Test {
    public static void main(String[] arg)
    {
     HashMap<int[],String> map= new HashMap<int[],String>();
     int[] a = new int[]{1,2};
     map.put(a, "sun");
     System.out.println(map.containsKey(a));
    }
}

Since a is the same reference, you will receive true as expected. If your application has no option of passing references to do the comparison, I would make a new object type which contains the int[] and override the equals() method (don't forget to override hashCode() at the same time), so that will reflect in the containsKey() call.
Comment: Implementing only `equals()` is **not** enough, you need to implement `hashCode()` as well. See Chapter 3 of Effective Java (available online: http://java.sun.com/developer/Books/effectivejava/Chapter3.pdf)
Answer: I would use a different approach. As mentioned before, the problem is with arrays equality, which is based on reference equality and makes your map useless for your needs.
Another potential problem, assuming that you use ArrayList instead, is the problem of consistency: if you change a list after is has been added to the map, you will have a hashmap corruption since the position of the list will not reflect its hashcode anymore.
In order to solve these two problems, I would use some kind of immutable list. You may want to make an immutable wrapper on int array for example, and implement equals() and hashCode() yourself.
Comment: This is explained here - http://stackoverflow.com/questions/8777257/equals-vs-arrays-equals-in-java
Answer: I think the problem is your array is doing an '==' comparison, i.e. it's checking the reference. When you do containsKey(new int[] { ... }), it's creating a new object and thus the reference is not the same.
If you change the array type to something like ArrayList<Integer> that should work, however I would tend to avoid using Lists as map keys as this is not going to be very efficient.
Answer: The hashCode() implementation for arrays is derived from Object.hashCode(), so it depends on the memory location of the array. Since the two arrays are instantiated separately, they have different memory locations and thus different hashcodes. If you made one array it would work:
int[] arr = {1, 2};
map.put(arr, "sun");
System.out.println(map.containsKey(arr));

Answer: You've got two different objects that happen to contain the same values, because you've called new twice.
One approach you might use is to create a "holder" class of your own, and define that class's equals and hash methods.
Answer: Are you sure you don't want to map Strings to arrays instead of the other way around?
Anyway, to answer your question, the problem is you are creating a new array when you call containsKey().  This returns false between you you have two separately newed arrays that happen to have the same elements and dimension.  See Yuval's answer to see the correct way of checking if an array is contained as a key.
An alternative, more advanced, approach is to create your own class that wraps an array and overwrites hashCode() so that two arrays with the same dimension and elements will have equal hash codes.
Answer: The two instances of int[] are different and not equal.
A nice approach would be to convert the int array to String using Arrays.toString(arr):
HashMap<String, String> h = new HashMap<>();
int[] a = new int[]{1, 2};
h.put(Arrays.toString(a), "sun");
h.get(Arrays.toString(new int[]{1, 2})); // returns sun

Comment: new int[]{12} will also return the sun which would be false . So, instead of just converting it to string we can put some kind of identifier like #
So,
 int[]{1,2} will be #1#2 AND int[]{12} will be #12

Java HashMap with Int Array


No android qual a classe correspondende a classe Image do javaFX

Question: Tenho servidor de imagens implementado em javaEE, no javaFX faço uma requisição da imagem ao servidor que me retorna um array de bytes, com este resultado crio a imagem no lado cliente:
** Imagem no formato PNG.
byte buffer[] -> image bytes retornado pelo servidor

// no javaFX
Image image = new Image(new ByteArrayInputStream(buffer));

Como faço para criar a imagem a partir do array de bytes no android?
No servidor leio a imagem da seguinte forma:
private byte[] readImage(String imageName) throws FileNotFoundException
{
    File fle = new File(imageName);
    FileInputStream new FileInputStream(fle);

    byte buf[] = new byte[(int) fle.length()];

    rea.read(buf,0,buf.length);

    rea.close();

    return buf;
}

Answer: A classe usada no Android para trabalhar com imagens cujo formato representa um mapa de bits é Bitmap.
Tendo o array de bytes use o método decodeByteArray() da classe BitmapFactory para descodificar o array em um Bitmap.
Use assim:
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.lenght);

É possível redimensionar a imagem ao mesmo tempo que se descodifica passando um objecto BitmapFactory.Options ao método decodeByteArray(), veja nesta resposta como.
Comment: Não sei qual será o problema. Só posso dizer que se o *byte array* é uma representação válida de um JPEG ou PNG o método `BitmapFactory.decodeByteArray()` fará a descodificação para um *Bitmap*.
Comment: O problema estava no PNG. Salvei a imagem como JPG e o decode funcionou. Editei o PNG e salvei o decode funcionou. **** A imagem que eu estava usando como teste eu baixei de https://design.google.com/icons/.
Comment: Testei e o BitmapFactory retorna null. Imagino que o erro não esteja no byte array retornado pelo servidor porque no javaFX a imagem é criada corretamente. Será que tem mais algum segredo?
Comment: Que eu saiba não há mais segredo algum. Como é que você está a codificar o byte array?
Comment: Editei a pergunta e adicionei o método de leitura no servidor.


How can I blur the "repeated" part of background image?

Question: I am looking if there is way to blur the repeated part of a background image so that if it is background position'ed center than the side of image itself are blurry?
Comment: If this only has to be static and not animated or something, then I would simply go with [multiple background images](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Background_and_Borders/Using_CSS_multiple_backgrounds) - a blurry version that gets repeated, and on top of that the normal one, not repeated. No need to involve jQuery if you really want something that simple.
Comment: There is a way of blurring stuff with css but the support is terrible and it's really heavy for the browser. Another approach would be to use the canvas element to blur the repeated part but in this case I'd suggest you just make the background always expand to the size of the container https://css-tricks.com/perfect-full-page-background-image/
Comment: If you are bringing in an image that you want blurred then bring in a blurred version of the image. If you are not un-blurring the image at any point. Also you could fade it out a little bit by changing `opacity`
Comment: http://stackoverflow.com/questions/20039765/how-to-apply-a-css-3-blur-filter-to-a-background-image
Comment: @CBroe now that's something I find helpful. Thanks!
Comment: O.k., I added it as a (short) answer.
Answer: If this only has to be static and not animated or something, then I would simply go with multiple background images - a blurry version that gets repeated, and on top of that the normal one, not repeated. (background-position set to the same for both.)
No need to involve jQuery if you really want something that simple.


ADO.Net Entity Data Model does not appear in Add Item List

Question: I am going to start working with Entity framework but the problem is my Visual Studio 2008 Does not showing ADO.Net Entity Data Model in Items list.
Following is snapshot of my item list and Visual Studio.
Answer: Install VS.NET 2008 SP1