Second countable space $\implies [x_n\to a, f(x_n)\to L \implies \lim\limits_{x\to a}f(x)=L]$

Question: Let $f:S\to Y$ where $S\subset X$. I wanted to know if $\lim\limits_{x\to a}f(x) = L$ (where $a$ is a limit point of $A$) was equivalent to $\lim\limits_{n\to \infty}f(x_n) = L$ for all sequences $x_n\to a$. I think that the first implies the second. Indeed I have to show that if I fix an open $V\subset Y$ arbitrary then $\exists N$ such that $f(x_n)\in V, \forall n>N$. Now form the definition of $\lim\limits_{x\to a}f(x) = L$, there exists an open $U$ such that $a\in U\subset S$ and $f(U)\subset V$. But then since $x_n\to a$ and $U$ contains $a$, there exists a natural $N$ such that $n>N\implies x_n\in U$. So for $n>N f(x_n)\in f(U) \subset V$ and we are done.
Now for the converse, I read from the internet that the space needs to be second countable, so with a countable basis. I don't really understand how the second countability plays a role here.
Answer: Actually, we only need $S$ to be first countable. Suppose $S$ is first countable, and let $(U_n)_{n=1}^\infty$ be a local basis of the point $a$. We would like it to be monotone, so let's define $W_n=\cap_{k=1}^n U_k$ for every $n$.
Now we can show that the second condition implies the first. Indeed, suppose $\lim_{x\to a} f(x)\ne L$. Then there must be some neighborhood $y\in V\subseteq Y$ such that for every neighborhood $U$ of $a$, the image $f(U)$ is not contained in $V$. In particular, for every $n\in\mathbb{N}$ there is a point $x_n\in W_n$ such that $f(x_n)\notin V$. Note that we have $x_n\to a$. Indeed, let $U$ be a neighborhood of $a$. Then there is some $n$ such that $U_{n_0}\subseteq U$. And then for every $n>n_0$:
$x_n\in W_n=\cap_{k=1}^n U_k\subseteq U_{n_0}\subseteq U$
So indeed we eventually have $x_n\in U$. However, $f(x_n)$ obviously can't converge to $L$, so we have a contradiction.
This direction is not true without first countability. For example, define the co-countable topology on $X=\mathbb{R}$. A sequence converges in this topology if and only if it is eventually constant. So in that case $x_n\to a$ always implies $f(x_n)\to f(a)$, for any function $f$. If that would imply the first condition of your statement then it would mean every function $f:X\to Y$ is continuous. But this is not true, for example take $Y=X$ with the discrete topology. The identity map $f:X\to Y$ is not continuous.
Comment: Thank you @Mark for this very nice explanation! I was reading a bit about [sequential spaces](https://en.wikipedia.org/wiki/Sequential_space). This is an even weaker assumption than first countable right?
Comment: @roi_saumon Yes, this is weaker. First countable spaces are sequential.


MYSQL - Use longblob with 4GB despite max_allowed_packet of 1GB

Question: Recently I was given an old application using MySQL 5.6 which has a problem with big files.
I found many threads stating that max_allowed_packet cannot be set to more than 1GB as this is the defined limit for MySQL. However there is this datatype LONGBLOB which is defined as supporting sizes up to 4GB.
As I can't imagine, that they defined a datatype, that you can't use - how is it possible to save Blobs this size despite max_allowed_packet being 1GB?
Answer: The only way to do this is to split the blob being uploaded into chunks which are equal or smaller to the max_allowed_packet size. They are uploaded via multiple calls to the MySQL C API function mysql_stmt_send_long_data() (q.v.). The MySQL command line client should handle this for you. In your own code you may have to check whether your preferred language's API handles this or whether you have to do so yourself.
Comment: Thanks, I had hoped of an easier approach, but I guess that doesn't exist. As the application is written in Java, I told the devs, that they should look for something alike the function you mentioned.
Answer: There are a lot of practical reasons for not trying to use a full 4GB.

It would take a long time to perform the query.* Slow
What if tomorrow's blob is 5GB long?
It clogs up replication.
For things like images/videos, it is likely to be better to put the blob in a file, then let html handle it via  (etc).
Cluttering RAM (that might be better used for caching, etc)

Anyway, you are losing only the range between 1G and 4G.  16M..1G works; so does less than 16M (as well as MEDIUMBLOB, etc).
Comment: I'm with you, but still - why create a datatype that is nearly impossible to use. It gives people false hope and/or leads them in the wrong direction.
The mentioned application uses longblob and obviously the original devs had files up to 4GB in mind. Now I'm stuck with their application and have to find a way to handle this.
Comment: @Picl - I can _guess_ that 25 years ago, it "seemed like a good idea".  Then the implementation of things somewhat ignored the issue.  Remember, very few computers had even 2GB of RAM back then.  I do give them praise for having very few "hard" limits.


Induction on finite subset of natural numbers

Question: Can we use induction to prove that a statement $P(n)$ is true for all $n \in \mathbb{N} $ such that $n \leq s$, where $s \in \mathbb{N}$? Specifically, in the second induction step, is it enough to show that
$$P(n) \implies P(n+1),$$
by assuming $n<s$ and $n+1 \leq s$?
Comment: Yes: this can be done. Actually many proofs follow this idea (for example when working in some finite dimensional vector space)
Answer: Yes, in the sense that it will prove the claim. Though it is important to understand that such a scenario is not a proof by induction, since it does not require to invoke the principal of induction in order to prove such a claim. The principal of induction takes the claims $P(1)$ and $P(n)\implies P(n+1)$ for all $n\ge 1$, which is a recipe for infinitely many proofs, one for each $n$, and accepts that that recipe for infinitely many proofs actually constitutes a single finite proof. The case that you are considering, while technically similar, is different. Here you establish that $P(1)$ and that $P(n)\implies P(n+1)$ for all $1\le n< s$. This is a recipe for creating a single proof, that of $P(n)$ for all $1\le n\le s$. For the given $s$ is given, we know just how to construct a proof of $P(s)$, i.e., $P(1)$ is true. Since $P(1)\implies P(2)$, it follows that $P(2)$ is true, and so on. The "and so on" here only hides a finite portion of the proof, so it is short-hand. In actual proof by induction such a "and so on" hides a portion of proof of variable length, depending on the $n$ being considered. The latter is a strictly stronger principal than the former.
Comment: I, too. Your answer is illuminating, although I'll have to look at it more thoroughly when i get the chance.
Comment: I wonder what the reason for the down vote is.
Answer: Yes, you can. It is equivalent to using regular induction (the version that proves that something is true for all natural numbers) to prove that the statement
$$Q(n) = ((n\leq s)\implies P(n))$$
is true for all natural numbers.


Flatten a Parent/Child hierarchy

Question: I'm trying to understand a concept here:
From an object structure like
class Parent
{
    public string ParentID { get; set; }
    public List<Child> Children { get; set; }
}

class Child
{
   public string ChildID { get; set; }
}

Assuming a fully populated parent object, I would like to use Linq to Xml to obtain the following Xml output:
<Mappings>
   <Mapping ID='ParentID1' ChildID='ChildID1'>
   <Mapping ID='ParentID1' ChildID='ChildID2'>
</Mappings>

How do I unwind the original object nested to obtain this mapping list?
EDIT
Example with a parent such as :
ParentID = 'Parent1', Children = new [] { "Child1", "Child2", "Child3" }

I am expecting 3 mappings :
<Mapping ID='Parent1' ChildID='Child1' />
<Mapping ID='Parent1' ChildID='Child2' />
<Mapping ID='Parent1' ChildID='Child3' />

Comment: It appears the genius that edited the title of this question managed to remove a huge part of the context, that is that I would like a solution in linq-to-xml syntax. One solution would have sufficed as a sample input and output was provided. This being too broad is just lunacy.
Comment: `Assuming a fully populated parent object`, How about posting it?
Comment: I don't understand what you are hoping to see. This is a conceptual question. The actual string literals that will populate the ParentID and ChildID values are inconsequential to the solution. As such, there is nothing to post.
Comment: What have you tried so far in your attempts to generate this type of file?  What problems, specifically, are you having with that implementation?
Comment: I don't understand how to effectively build it in the linq-to-xml syntax because when creating the first "Mapping" XElement I need a ChildID value for each entry, but I don't know how to express it in the syntax.
Comment: @ L.B. Please spare me your brazen one liners. If you don't want to help please move on. Otherwise tell me exactly what you need because I don't understand where you're coming from. I'm certainly not interested in providing you a medium to vent your daily frustrations.
Comment: Why are people down voting !?
Answer: EDIT
The following code will flatten the hierarchy :
var list = new List<Parent>
{
    new Parent
    {
        ParentID = "parentID1",
        Children = new List<Child> {new Child {ChildID = "childID1"}, new Child {ChildID = "childID2"}}
    },
    new Parent
    {
        ParentID = "parentID2",
        Children = new List<Child> {new Child {ChildID = "childID3"}, new Child {ChildID = "childID4"}}
    }
};

IEnumerable<XElement> list1 = (from parent in list
    from child in parent.Children
    select
        new XElement("Mapping", new XAttribute("ID", parent.ParentID),
            new XAttribute("ChildID", child.ChildID)));

string @join = string.Join(Environment.NewLine, list1);

Output :
<Mapping ID="parentID1" ChildID="childID1" />
<Mapping ID="parentID1" ChildID="childID2" />
<Mapping ID="parentID2" ChildID="childID3" />
<Mapping ID="parentID2" ChildID="childID4" />

Here's an example on how to achieve it :
Note : this won't work, it will generate an exception saying 'Duplicate attribute'
List<Parent> list = new List<Parent>
{
    new Parent() {ParentID = "parentID1", Children = new List<Child>() {new Child() {ChildID = "childID1"},new Child() {ChildID = "childID2"}}},
    new Parent() {ParentID = "parentID2", Children = new List<Child>() {new Child() {ChildID = "childID3"},new Child() {ChildID = "childID4"}}}
    };
IEnumerable<string> enumerable = xElements.Select(s => s.ToString());

IEnumerable<XElement> xElements = list.Select(s => new XElement("Mapping", new XAttribute("ID", s.ParentID), s.Children.Select(t => new XAttribute("ChildID", t.ChildID))));
IEnumerable<string> enumerable = xElements.Select(s => s.ToString());
var @join = string.Join(Environment.NewLine, enumerable);

This one will because it will use the overload of Select that uses the index of the current object :
var list = new List<Parent>
{
    new Parent
    {
        ParentID = "parentID1",
        Children = new List<Child> {new Child {ChildID = "childID1"}, new Child {ChildID = "childID2"}}
    },
    new Parent
    {
        ParentID = "parentID2",
        Children = new List<Child> {new Child {ChildID = "childID3"}, new Child {ChildID = "childID4"}}
    }
};

IEnumerable<XElement> xElements =
    list.Select(
        s =>
            new XElement("Mapping", new XAttribute("ID", s.ParentID),
                s.Children.Select((t, u) => new XAttribute(string.Format("ChildID_{0}", u), t.ChildID))));
var @join = string.Join(Environment.NewLine,xElements);

Result : not what you've been expecting, right ?
<Mapping ID="parentID1" ChildID_0="childID1" ChildID_1="childID2" />
<Mapping ID="parentID2" ChildID_0="childID3" ChildID_1="childID4" />

Why I've used this overload ?
Because parent has a list of childrens, while the first code would work with one children it would not with many of them.
Conclusion :
Not sure about what you're trying to achieve,
Why don't you just keep the structure of your objects as it is currently ?
Comment: Thanks for the help, I'm here to figure something out not to win question of the month although I still don't get what happened.
Comment: I am trying to obtain the sample XML I posted, in essence a (ParentID, ChildID) mapping, from data organized in the objects above. Changing either the data structure or the XML format is not an option unfortunately.
Comment: Okay but as I've explained in my answer keeping such structure won't work with multiple childrens or are you expecting many mappings to be generated such as Parent1 -> Child1, Parent1 -> Child2 as the output ?
Comment: Effectively flatten that hierarchy and get all rows: I included an example as an edit in original post.
Comment: Okay, take a look at my edit.
Comment: Ok, I get it, I should've started with a list query when building that segment. I was thinking I needed something similar like a CROSS-APPLY in SQL.
Comment: Glad it helped you :D Sorry but I can't really make any suggestions with SQL, my knowledge about it is non-existent. Just ignore these down-voters that don't even comment, your question was legitimate and deserved an answer.
Comment: It's just that some members of this community are very stressed,  IMO people at http://dsp.stackexchange.com/, http://gamedev.stackexchange.com/ or http://graphicdesign.stackexchange.com/ are on overall way cooler, they don't down-vote you right from the start; they try to understand by commenting first.

Flatten a Parent/Child hierarchy


Can someone explain SMTP Callbacks when BATV is enabled, and when to issue the verification?

Question: This Wikipedia article describes how SMTP verification of the MFROM may have issues if BATV is enabled.

Servers that reject all bounce mails (contrary to the RFCs). To work around this problem, postfix, for example, uses either the local postmaster address or an address of "double-bounce" in the MAIL FROM part of the callout. This work-around, however, will fail if Bounce Address Tag Validation is used to reduce backscatter.[3] Callback verification can still work if rejecting all bounces happens at the DATA stage instead of the earlier MAIL FROM stage, while rejecting invalid e-mail addresses remains at the RCPT TO stage instead of also being moved to the DATA stage.1[2]

The resolution is to verify the address in the "Data".  Since the Data isn't verified (assuming DKIM isn't being used), can't this be spoofed and isn't this a weak workaround?
Answer: Let's split it per statement

Servers that reject all bounce mails (contrary to the RFCs).

Yes, this misconfigured server rejects all email with sender <>.

To work around this problem, postfix, for example, uses either the local postmaster address or an address of "double-bounce" in the MAIL FROM part of the callout.

Yes, this workaround will prevent misconfigured remote server reject email with sender <>.

This work-around, however, will fail if Bounce Address Tag Validation is used to reduce backscatter.

BATV was technique to verifying the bounce email to preventing backscatter. It works by rewrite the original sender to some cryptographic token. BATV checker only check the recipient address of an email if the sender was set to  <>. If some MTAs used postmaster@ address to perform callback verification, the system won't pass the email to BATV checker (because it's not bounce) but rejecting them because the recipient doesn't exist (only BATV checker can verify if the recipient was match its cryptographic token).

Callback verification can still work if rejecting all bounces happens at the DATA stage instead of the earlier MAIL FROM stage, while rejecting invalid e-mail addresses remains at the RCPT TO stage instead of also being moved to the DATA stage.

Note: This statement doesn't have relation with BATV. It addressed the first problem (Servers that reject all bounce mails (contrary to the RFCs)).
So, we has two rejection process here, because 1) the recipient doesn't exist or 2) it is bounce address (identified by  <>). After a client (the verifier) issued RCPT TO, the server will perform a checks to verify that the recipient address was exist. If the recipient was exist then server will reply with code 2XX OK.
Because of that, the verifier will assume that the address was OK and it will disconnect. However, the real bounce email will enter DATA stage (the email header/body haven't been sent yet...), in this stage server will reject it because of bounce email.

The resolution is to verify the address in the "Data". Since the Data isn't verified (assuming DKIM isn't being used), can't this be spoofed and isn't this a weak workaround?

No, it doesn't verify the address in the DATA (maybe you mean the address in the email header). In fact, the header haven't been sent but the server already rejected it.
Here the illustration to explain where the rejection occurs. The original source
<code>R: 220 BBN-UNIX.ARPA Simple Mail Transfer Service Ready
S: HELO USC-ISIF.ARPA
R: 250 BBN-UNIX.ARPA

S: MAIL FROM:<firstname.lastname@example.com>
R: 250 OK

S: RCPT TO:<firstname.lastname@example.com>
R: 250 OK             <--- "non existed address" rejection occurs here

S: DATA
R: 354 Start mail input; end with <CRLF>.<CRLF> <--- "bounce" rejection occurs here
S: Blah blah blah...   <--- email header and body
S: ...etc. etc. etc.
S: .
R: 250 OK

S: QUIT
R: 221 BBN-UNIX.ARPA Service closing transmission channel
</code>


Why does Flexmojos produce a different size swf to mxmlc?

Question: I am compiling a very simple app, Main.mxml:
<?xml version="1.0" encoding="utf-8"?>
<s:Application
    xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark">

    <s:Label
        text="Flex"/>

</s:Application>

With mxmlc (SDK 18.104.22.16859):
mxmlc
-context-root=a
-services=.\src\main\webapp\WEB-INF\flex\services-config.xml
src\main\flex\Main.mxml
-output src\main\webapp\Main.swf

And also with Flexmojos 3.9 & 4.0-RC2, using SDK 220.127.116.1159:
<configuration>
    <output>src/main/webapp/Main.swf</output>
    <services>src/main/webapp/WEB-INF/flex/services-config.xml</services>
    <contextRoot>a</contextRoot>
</configuration>

The output from both builds creates a valid swf file that works as expected, yet the swf file from mxmlc is much smaller than the Flexmojos version:
mxmlc      Main.swf   43k
flexmojos  Main.swf  367k

This is quite worrying because I am developing in Eclipse (which uses mxmlc) yet my master build script (which uses flexmojos) is producing a totally different file.
Can anyone tell me why this is, and how to rectify it?
Thanks
Answer: It seems, that compilation with flexmojos includes flex framework classes in output swf. And compilation with mxmlc in your case uses framework swfs as RSL.
Comment: Thanks, I suspected as much. But do you know how to tell flexmojos to do the same?
Comment: false does not work.
Comment: In principle I agree with what you are saying... but trying to get flexmojos to actually do it is a different matter!
Comment: @chris, could you make some changes in flex-config.xml and watch, if compiled swf would be affected by those changes? If it will (means, that flexmojos really uses that flex-config.xml), please attach the flex-config.xml content to your question.
Answer: MXMLC will be pulling in the flex-config.xml from the Flex SDK install that specifies the default linkage (mostly RSL) for the Flex runtime - meaning a smaller SWF file.
I'm not familiar with how Flexmojos work, so you'll need to learn how to set up the equivalent arguments. It may be possible to tell Flexmojos to use the same default config XML file.
I implemented a Flex build using Gradle and we have different file sizes even though we're supposed to be using the same compiler and the same settings as in Flash Builder (Eclipse) - though the difference is very small and our dependencies are linked as expected.
Comment: Flexmojos does actually use the same flex-config.xml file (or a copy of anyway) which is why it is strange that the compilation would be different.


Order of operations for dereference and bracket-ref in C

Question: If I do *ptr[x], is that equivalent to *(ptr[x]), or (*ptr)[x]?
Answer: *(ptr[x])
See the Wikipedia operator precedence table, or, for a more detailed table, this C/C++ specific table.
Comment: Wikipedia also has a comprehensive C(++)-specific [precedence table](http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence).
Comment: that link doesn't mention pointer dereferencing... but it does say array access binds most tightly
Comment: The `*` is in the 2nd row of the table, after `[]` in the 1st row.
Comment: Ah, I see how this could be confusing, since `*` could mean multiplication or pointer dereference.  Multiplication goes after though, in row 3 of the table.
Comment: ah yes, reading comprehension for the win. i was scanning the text for mention of the word 'pointer' and didn't realize it's just a unary operation too.
Comment: @Matthew: Thanks, incorporated this table into my post.
Comment: Yay, my favorite table. ( http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence )
Answer: In C, all postfix operators have higher precedence than prefix operators, and prefix operators have higher precedence than infix operators.  So its *(ptr[x])
Answer: Using the counter-clockwise movement of analyzing and parsing that simple example

1. starting with ptr, work in counter-clockwise until you hit asterisk operator
2. asterisk, in counter-clockwise until you hit subscript operator
3. we arrive here, at subscript operator [x]

Since [] has higher precedence than the asterisk as per this table , that makes it *(ptr[x])
Comment: That's for parsing type specifiers and declarations. But in the question `*ptr[x]` is an expression, and so all you need to know is operator precedence.
Comment: So the counter-clockwise thing *doesn't* apply to expressions?  I would *strongly* drop mentioning that, as operator precedence is all that matters here.
Comment: where does this counterclockwise method come from?
Comment: @Claudiu: It's a well known technique for parsing and analyzing C expressions...it is found in 'Expert C Programming - Peter Van der Linden', see http://stackoverflow.com/questions/2305255/pointer-array-syntax-char-p-pn-in-c-c


When should I use "graph" vs. "plot"?

Question: My ODEs textbook uses both graph and plot but I can't figure out how it chooses one over the other.
From the book:

Sketch the graph of the solution in the x1x2-plane for t ≥ 0.
  [this one was referring to a continuous function]

Also from the book:

Plots of the solution and a tangent line approximation for the initial value problem (11).
  [this one referring to a continuous solution]

Is there a formal, to some degree, distinction between the two terms? When do I call it a plot and when do I call it a graph?
Comment: ...In all of my math classes (I'm a math major), we talk about plotting points, but we graph functions. You can plot specific points in the graph of a function, but you don't just plot a function. Generally, plot, as a noun, refers to a set of points that may or may not be connected by a line, but that cannot be represented as a function. I don't know if there's some technical ground behind this, but if there is, one of us is being confused...
Comment: There used to be graphics printers called *line plotters* which joined lines.  *Graph* just means *draw* (as a verb) and I would take it to be more general than *plot*.
Comment: So you're saying plotting is discrete and graphing is continuous?  (or at least piecewise continuous?)
Comment: That's my impression, but I have nothing to back it up except my own observations, which is why I left a comment instead of an answer.
Comment: I just checked my ODEs book and it labels a "plot" of a sine wave.  (which is continuous)  Interestingly, it asks you to "sketch the graph of..." a continuous function.  The book uses both terms in similar ways but I can't figure out how it chooses one over the other.
Comment: Also "figure", and occasionally "chart". Special case: "histogram" (used a lot in particle physics to mean a generic plot because of the (pernicious?) influence of [PAW](http://paw.web.cern.ch/paw/) and [Root](http://root.cern.ch/drupal/)).
Comment: There are so many other definitions of 'plot' and 'graph' that do not overlap, that it is hard to think of them as synonymous.
Comment: I don't really think they're synonymous.  I'm just trying to figure out when to use one over the other.
Comment: @kitukwfyer, you should make it an official answer.  This is the right difference.  This is why electronic point printers are also called plotters.  See also a plot of land: a small surface, a spot.  You draw a graph from mathematical analysis and for empirical functions, you measure or compute points and you plot them.
Comment: @kitukwfyer - I'm only a physicist but we say plot, as in "plot y as a function of x" - in fact I can't think of when I would use graph as a verb. It might also be a UK/US thing?
Comment: @mgb: It's possible. I would understand "plot y as a function of x," but it sounds a little funny to me. I would use "graph" there preferentially. Still, I would understand it. It could also be a math/physics thing. My calc III professor never tires of warning us about the inherent dangers of using physicists' notation. XP I'm sure he'd be happy to extend it to language. :)
Comment: @kitukwfyer - come over to the dark side, we have cooler toys!
Comment: This has been migrated to Math as requested by the OP himself.
Comment: @RegDwight:  awesome - thank you!
Comment: see also: "chart"
Answer: As per @Alain Pannetier's advice, I'm making my comment into an answer. (To lazy to rephrase now, but I'll most likely try to make it pretty and more answer-y later.)
...In all of my math classes (I'm a math major), we talk about plotting points, but we graph functions. You can plot specific points in the graph of a function, but you don't just plot a function. Generally, plot, as a noun, refers to a set of points that may or may not be connected by a line, but that cannot be represented as a function. I don't know if there's some technical ground behind this, but if there is, one of us is being confused...
So, in short, "plot" is used for a finite set of points, while a "graph" is used for a function comprised of infinite points.
Comment: I'm not sure I believe this.  (Particularly the "function comprised of infinite points" part.)
Comment: @Czechnology Oh God, now I feel old. But yes, laziness always wins lol.
Comment: Also, there is such a thing as discrete functions.  The [Mandelbrot set](http://en.wikipedia.org/wiki/Mandelbrot_set) is one example.
Comment: Yeah, I'm tired and writing a German essay while listening to Korean music. Who knows where my brain's at? Apparently not where I keep my definition of continuity. Editing, and probably not for the last time...Also, plotting all of the points of a function whose domain is all real numbers would take a while...
Comment: I like that 8 years later the laziness is still winning! :)
Answer:
we plot points, but we graph functions

this is useful guidance since:
"plot"  is to draw a graphic representation with respect to measurements or coordinates
"graph" is to illustrate connections between several things by plotting dots and lines
Answer: A graph in the sense of the object "a graph of a function" often has the specific definition, for a real-valued function $f$ of being the set of points $\{(x,y)|y=f(x)\}$.  That is, graph can be used as a noun to mean literally the set of ordered pairs.  It is interesting to note that this is also sometimes the definition of the function itself.
Beyond that one specific technical meaning, I do not think that (in the context of ODEs, calculus, or precalculus mathematics) there is a formal distinction between the two words.  Informally, I use each word a bit differently.
The word graph in the sense of the action "graph a function" means to make a drawing of the set of points in the (noun) graph of the function.  This sometimes has the connotation of a careful, precise drawing.  In contrast, "sketch the graph" sometimes has the connotation of being a less-formal illustration showing key features of the graph of the function without necessarily being as precise.
The word plot in the sense of the object "a plot of a function" means a visual representation.  There are other types of plots, such as scatter plots and line plots, that would not typically be referred to as graphs.  I would say that graphs are a specific type of plot, but I'm not sure that's quite right.
The word plot in the sense of the action "plot the graph of a function" or "plot some points" typically means drawing with the connotation of precision.  I generally would not use the phrasing "plot the graph."
Answer:
'Plot' (verb) has a more active, tangible connotation than 'graph' (verb), ie a person or machine placing ink on paper, a surveyor doing measurements and markings, a computer monitor radiating visible light producing some representation or figure, , and so on.  Obviously, 'plot' is associated with 'plotting devices' which evokes all sorts of technologies.  I would not be surprised if the word 'plot' has its roots in surveying, navigation, and astronomy, in that order.
'Graph' (verb) has a more abstract intangible connotation than 'plot'.  When this word is used the resulting 'graph' (as a noun) is by design a representation of some mathematical object (see below).  And this object is the goal, not the representation itself.  For example, a teacher may graph $y = x^2$ on a dusty blackboard, but once he starts talking about the graph, it's usually not the chalk he's talking about anymore, he's talking about a mathematical object.
'Graph' (noun) is closely related to 'function'.  In mathematics, functions are often equated with their graphs, IE a function $f: X \rightarrow Y$ is just the choice of two sets $X$ and $Y$ and an appropriate subset of $f \subset X \times Y$, the latter being 'the graph' in the formal sense.  When visualized in the usual way, with elements from X as the independent variables, we can call these the traditional graphs.
Finally, from wikipedia: graphs, plots, and charts.  In the first link,  graphs are of the 'traditional' sort.  In the second link, a large number of plot types are given, including box plots and scatter plots.  However, in addition there are many graphs of the traditional sort, but with modified/scaled axes.  The entry on charts also has many examples which may be called either graphs or plots.
Answer: Although I am not a native English speaker, I believe plotting refers to drawing a diagram of any kind. So you can plot a function, an architectural design , a software class diagram etc.
Graph is a more specific term that refers to plotting by using a system of axes. So while both are correct, graph is more precise.
To add to the confusion, there are also the notion of graph from graph theory. In my native language (Greek) we use graph only in relation with graph theory and grapheme for the drawing/plot/graph of a function. However, grapheme has a different meaning in English.
In conclusion, you could call a quick drawing on a blackboard that is not very precise a plot but not a graph. A precise drawing using axes can be called a graph and a plot.

When should I use "graph" vs. "plot"?


Group and index columns when at least one object in vector matches with at least one object in other vector r dplyr

Question: I am trying to find a way to group rows and assign an index to each group without using a loop. The difficulty is that the grouping variable num has no unique identifier; num is a vector of numbers (defined as character). I want to group all rows that match at least by any of the numbers in the vector. The vectors are of different lengths and include up to 20 numbers.
Let me give an example:
I have a dataframe like this:
df <- data.frame(id = c(1:5), num = c('111;222', '333;111;444', '000;88888;1', '9999;111', '1'))
I split num by the separator ; such that every row becomes a vector:
library(dplyr)
df <- df %>%
  mutate(num = str_split(num, ';'))

I want to index all rows for which at least one number in the vector matches with the same index. The result should look as follows:
id     num               group_index
1  c('111','222')             1
2  c('333','111','444')       1
3  c('000','88888','1')       2
4  c('9999','444')            1
5  '1'                        2

The example illustrates another difficulty: Group 1 is identified by '111' as well as '444', even though row 1 is part of group 1 and does not contain '444' in num.
If num was just a string, I would do the following
df <- group_by(num) %>%
  mutate(group_index = group_indices(.,num))

Now, I thought I should perhaps start by identifying groups. A first approach, which does not work is:
df <- df %>%
 group_by_if(num, any(num, str_c(num, collapse = '|')) == T)

I know that I could start by writing a loop. However, R is not very efficient with loops, so I would prefer a solution without a loop – if there is any? Any hints would help!
Comment: In that case, all would be of group 1.
Answer: Ok, this answer can probably be shortened (probably a lot), but I think the use of igraph keeps every nice and visible for visual inspection of the number of groups.
library( data.table )
library( igraph )
#make df a data.table
setDT(df)
#split num-column to v1, v2, ... ,vn
df[, paste0("v", 1:length( tstrsplit(df$num, ";"))) := tstrsplit( num, ";")]
#    id         num   v1    v2   v3
# 1:  1     111;222  111   222 <NA>
# 2:  2 333;111;444  333   111  444
# 3:  3 000;88888;1  000 88888    1
# 4:  4    9999;111 9999   111 <NA>
# 5:  5           1    1  <NA> <NA>

#now melt to long format
df.melt <- melt(df, id.vars = "id", measure.vars = patterns("^v[0-9]"), value.name = "from" )
#create links
df.melt[, to := shift( from, type = "lead"), by = .(id)][]
#drop inomplete rows
df.melt <- df.melt[ complete.cases(df.melt), ]
#    id variable  from    to
# 1:  1       v1   111   222
# 2:  2       v1   333   111
# 3:  3       v1   000 88888
# 4:  4       v1  9999   111
# 5:  2       v2   111   444
# 6:  3       v2 88888     1

g = graph_from_data_frame( df.melt[ , .(from, to)])
# plot(g)

looks like we have two separate groups to work with. let's find out which node (number) belongs to which group, and use this info on the original df
dt.lookup <- as.data.table( components(g)$membership, keep.rownames = TRUE )
#       V1 V2
# 1:   111  1
# 2:   333  1
# 3:   000  2
# 4:  9999  1
# 5: 88888  2
# 6:   222  1
# 7:   444  1
# 8:     1  2

#go back to the molten data of the original df
df.melt <- melt(df, id.vars = "id", measure.vars = patterns("^v[0-9]"))
df.melt <- df.melt[ complete.cases(df.melt), ]
#perform update join to get the groupnumber
df.melt[ dt.lookup, group := i.V2, on = .(value = V1) ]
#    id variable value group
# 1:  1       v1   111     1
# 2:  2       v1   333     1
# 3:  3       v1   000     2
# 4:  4       v1  9999     1
# 5:  5       v1     1     2
# 6:  1       v2   222     1
# 7:  2       v2   111     1
# 8:  3       v2 88888     2
# 9:  4       v2   111     1
# 10: 2       v3   444     1
# 11: 3       v3     1     2

#summarise to go back to oroiginal df form
df.melt[, .(num = paste0( value, collapse = ";"),
            group = paste0( unique(group), collapse = ",")),
        by = .(id) ][]

final output
#    id         num group
# 1:  1     111;222     1
# 2:  2 333;111;444     1
# 3:  3 000;88888;1     2
# 4:  4    9999;111     1
# 5:  5           1     2

Comment: Thanks a lot, @Wimpel! That looks great!


How to do binary logistic regression on people (couples) clustered within homes?

Question: I am looking at the relationship between housing characteristics and a health outcome. To make the example simple, I have data for a continuous predictor (exposure) collected from 1000 homes and health outcomes S (a binary outcome) for 2000 people (1000 couples) living in each of those homes. I would like to look at the relationship between S and E using binary logistic regression.  Apart from sharing the same exposure, there is no mechanistic reason to believe that status of partner 1 in the couple can affect the status of partner 2 e.g. its not a transmissible disease etc.
Can I do an ordinary logistic regression? Or must I take into account the fact that people are clustered within homes? If so, why? What syntax would be appropriate in Stata, xtlogit with i(house)? or some kind of xtmixed?
Many thanks
Comment: Is it possible to observe $(0,1)$ or $(1,0)$ as an outcome or both members always have the same binary outcome?
Comment: @Procrastinator: Given that the outcome is a non-transmissible disease, it seems reasonable to assume that members of the same household can have differing outcomes.
Comment: `xtmixed` is intended for continuous data; you need to use `xtlogit` or `xtmelogit` with binary data.
Answer: For me, this sounds like a (more or less typical) dyadic data set and I would definitely control for dyadic dependencies (i.e. at the houshold level) via multilevel/structural equation modeling.
David Kenny owns a great website on Dyadic Analysis. He also is co-author of a book on Dyadic Data Analysis that is highly recommanded.
Since you seem to use Stata, I would use the xtmelogit command (see here for more information).
Comment: I can't see how this is a dyadic data... The dependent variable isn't related to the relationship of a couple. It seems perfect for a hierarchical model to me (aka random effects, like the one suggested by jthetzel).
Comment: @Manoel Galdino: "The dependent variable isn't related to the relationship of a couple". Well, that's an empirical question, isn't it? At least, both share the same risk ("predictor (exposure) collected from 1000 homes"). Also, I agree that you could use a hierarchical model (aka multilevel model) but a SEM also works fine (especially if you have distinguishable dyads).
Answer: One assumption of fixed-effects general linear models (e.g. "ordinary" logistic regression) is that observations are independent of each other. However, there is likely some dependency in the observations in your study. For example, two people living in the same household are more likely to have similar diets and similar levels of physical activity than two people living in separate households.
I would consider modelling the data using either a logistic or Poisson mixed-effects model. The fixed effects would be your measured exposure covariates. The random effect would be the household. I am not particularly famililar with Stata's mixed effects syntax. In R, for a logistic mixed-effects model, I would call glmer(outcome ~ exposure1 + exposure2 + (1|household), data = study.data, family = binomial).  A quick Google search suggests that the equivalent in Stata would be xtmelogit outcome exposure1 exposure2 || household.
Answer: I see two possibilities. One would be to apply separate models (one for the female and one for the male member of the couple).  The second possibility would be to have one model with an indicator variable to distinguish the male member from the female member of the couple.
Comment: What is wrong with this answer?
Comment: Why do you ask that? Due to the fact that no one up voted it? I wouldn't say it's wrong, I just think it's not particularly helpful to deserve an up vote. For example, your second suggestion is just a fixed effect model and it would be better if you pointed so. Also, you could argue why it would be better than the random effects suggested above. This would deserve an up vote, at least by me.


Como faço minha table com scroll infinito?

Question: Tenho a seguinte situação: quero que ao chegar ao fim da table faça uma requisição Ajax e retorne mais 10 linhas na minha table. Por exemplo:
<!DOCTYPE html>

    <title></title>

        Make
        Model
        Color
        Year

        Ford
        Escort
        Blue
        2000

        Ford
        Escort
        Blue
        2000

        Ford
        Escort
        Blue
        2000

        Ford
        Escort
        Blue
        2000

        Ford
        Escort
        Blue
        2000

        Ford
        Escort
        Blue
        2000

        Ford
        Escort
        Blue
        2000

        Ford
        Escort
        Blue
        2000

hey

Faço a requisição Ajax quando o scroll chega ao final da table para o arquivo teste3.php mas quando o valor é retornado os anteriores somem, quero que a lista table só vá aumentando.
Segue o código do arquivo teste3.php:
<?php

$row = $_POST['row']+1;
echo "

        heye
        Escort
        Blue
        2000

";

Comment: acho que você precisa utilizar um append: https://api.jquery.com/append/
Comment: vou tentar @CezarCruz
Answer: É só consultar o manual e ver que o método .html() possui duas funções: uma é pegar o HTML interno e outra é substituir o HTML interno de um elemento.
Ao fazer $("tbody").html(response); você está substituindo o conteúdo (HTML interno) do tbody, ou seja, em vez de acrescentar novas linhas, você está substituindo as linhas existentes.
No caso do scroll infinito, você deveria usar o método .append(), que acrescenta novo conteúdo no final do elemento, ou seja:
$("tbody").append(response);

Comment: bem isso, obrigada!
Answer: Olá, segue um exemplo com append, e scroll: auto, acredito que seja a melhor alternativa neste caso. no lugar do botão, é só colocar um "for" ou "while".
Execute aqui mesmo para testar.

$(document).ready(function(){
  $("#btn2").click(function(){
    $("ol").append("
Appended item
");
  });
});

<!DOCTYPE html>

The overflow Property

overflow: auto:

     Aqui dentro vai sua tabela!!

List item 1

List item 2

  <button id="btn2">Novo item da tabela</button

Comment: usei o append e funciona, obrigada!
Comment: legal, se quiser marcar positivo a resposta então, valeu xp


Android Recylcerview set Position of Item programmatically

Question: i created a recylcerview for myChats. In this Recyclerview i can see a thumb, the last message and the name. if i send or receive a new message the item should go to first position, like in whatsapp.  to receive the new message i created the following method:
 private void getLastMSG(final String userId, final TextView lastMSG){
    String userid = FirebaseAuth.getInstance().getCurrentUser().getUid();
    DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users").child(userid).child("connections").child("matches").child(userId);
    ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if(dataSnapshot.exists()){
                String lastMsg = dataSnapshot.child("lastMsg").getValue().toString();
                    lastMSG.setText(lastMsg);

            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

Now i want to set this item to first position but i dont know how
Answer: You need to call:
notifyItemMoved(oldPos, newPos) in your recyclerview adapter.
Note that you need to update your data model before that, in order to bind correct view in onBindViewHolder method.
Referece to adapter documentation.
Comment: what do you mean with updating my data model?#
Comment: Your data model should be list of `Items` that you talked in the post.


How to simulate right-censored Weibull PH survival times with time-varying covariate?

Question: I am trying to simulate data coming from a joint model of longitudinal and survival data. Basically, my thought process is this.

I need to define a maximum follow-up time, F.
I need to define coefficients ($\boldsymbol{\beta}$, $\sigma_t$,generate X from some distribution, W from some distributions and define $\alpha$ and $\gamma$)
I need to use the max follow-up time to solve for integrals using the uniroot function.

For each individual i, I generate survival probabilities from the uniform distribution.
\begin{equation} \label{eq:uniroot1}
            S(t|W, X) \sim U(0,1)
   \end{equation}
For each individual, I am trying to solve:
\begin{equation}
\int_0^F h(u|\textbf{W}, m_i(u)) \partial u + \log U(0,1) = 0
\end{equation}
where I define here  $\textbf{W}$ are baseline covariates and $m_i(u)$ is the time-varying covariate that is essentially "longitudinal marker" without the error term defined as follows:
\begin{equation}
y_i(t) = m_i(t) + \epsilon_i(t) \\
m_i(t) = (\beta_0 + b_{i0}) + (\beta_1 + b_{i1})t + (\beta_2 X_{2i}) + \beta_3X_{2i}t \\ \end{equation}
And the form of the Weibull PH is as follows:
\begin{equation} \label{eq:weibullPH}
(\sigma_t \exp(\alpha m_i(t) +\boldsymbol{\gamma}^T\textbf{W}_i))t^{\sigma_t-1}\\
\end{equation}
Once I solve this equation, I can just generate C from Uniform(0, Max.FollowUpTime)to perform uniform censoring.
My questions are:
A. Does this seem like the right way to get survival times?
B. How do I define the maximum follow-up time such that it is a reasonable upper bound survival time for the values I defined in point 2.
Thank you for any pointers!
Answer: Question A. Although I haven't compared every detail, it looks like your approach is the same as that used by the R simsurv package. See the vignette on the technical background to the package, and the section of a vignette dealing specifically with joint modeling. I don't know that you need to define a maximum follow-up time, but that's certainly allowed for. My sense is that the numerical methods used by the package avoids some of the problems with evaluating the cumulative hazard out to long times, but I don't have experience with that.
Question B. I think that the choice of maximum follow-up time will based on either (1) your understanding of the underlying subject matter related to a maximum time likely to be found in practice, or (2) trial and error on a data set that covers the ranges of predictors and coefficients that you have in mind.


How do I get a specific string value from a string in PHP?

Question: I have to get a value which contains "#" in the string.
Ex:
$string = '#1234 Lorem ipsum is placeholder text commonly used in the graphic, #rm1345 print, and publishing industries for previewing layouts and visual mockups';

Expected results:
 #1234 and #rm1345

How should I get the above results from the $string?
I tried the below method, but it doesn't help me.
$contents = str_word_count($string, 2);
echo 'contents:
';print_r($contents);echo '
';

Please help me out.
Thanks!
Answer: Heres your regex and generated string
$string = '#1234 Lorem ipsum is placeholder text commonly used in the graphic, #rm1345 print, and publishing industries for previewing layouts and visual mockups';

$temp = preg_match_all('/(?<!\w)#\w+/', $string, $matches);

echo implode(' and ', $matches[0]);

Output:
#1234 and #rm1345

Working demo.
Regex testing link.(preg_match_all to match all # appended words).
Source link.
Comment: It works! Thank you!
Comment: @RameshMoorthy Welcome. If this answer or any other one solved your issue, please mark it as accepted.


Max Heapify issue

Question: I have been trying to debug this code for hours. I don't know why it is not rearranging the terms. I have tried everything I can think of. Can someone help? Thanks.
public void heapify(int i)  // utility routine to percolate down from index i
{
    printHeap();
    int left, r, min;
    Process tmp;

    left = lchild(i);           // left child
    r = rchild(i);                  // right child

    if(left < size() && A[left].compareTo(A[i])<0)      // find smallest child
        min = left;                 // save index of smaller child
    else
        min = i;

    if(r < size() && A[r].compareTo(A[min])<0)
        min = r;                // save index of smaller child

    if(min != i)                // swap and percolate, if necessary
    {
        tmp = A[i];             // exchange values at two indices
        A[i] = A[min];
        A[min] = tmp;
        heapify(min);

        // call heapify
    }// end if
printHeap();
}// end method heapify

private int lchild(int i) {
    return 2 * i + 1;
}

private int rchild(int i) {
    return 2 * i + 2;
}

Even when I call heapify on every element of the heap it doesn't work :/
Here is the compareTo. It is supposed to arrange max heap using priority first then if there is a tie it goes to a unique time arrived value.
public int compareTo(Process o) {
    int val;
    if (this.priority > o.getPriority()) {
        val = -1;
    } else if (this.priority == o.getPriority()) {
        if (this.arrivalTime < o.getArrivalTime()) { //Earlier time
            val = -1;
        } else {
            val = 1;
        }
    } else {
        val = 1;
    }

    return val;
}

Comment: It works when I try to run it. What is your test example where it doesn't?
Comment: What exactly are you trying to do here? Are you trying to rearrange the items in an array (`A` in your example) so that they form a valid binary heap?
Comment: The SO would have to know; I took this comment to tell the story: "utility routine to percolate down from index i", could be mistaken.
Comment: I was hoping that what it would do is organize the max heap if I run it for every element. Is this correct? If not how would I organize my entire max heap? Thanks.
Comment: I believe for your method to organize a heap correctly you will have to call it on all elements in the first half of the array *backwards*: `for (int index = A.length / 2; index >= 0; index--) { heapify(index); }`. Not sure about the exact place to start (+/- 1), and with length 0 the code I just gave will throw an ArrayIndexOutOfBoundsException, so at least adjust to that.
Answer: The fastest known way to organize an array into a heap is called Floyd's Algorithm. You start at the middle of the array and move towards the root, sifting each item down as required. In your case:
for (int i = size()/2; i >= 0; --i)
{
    heapify(i);
}

You should be able to call the heapify function that you supplied.
To see how this works, take a look at https://stackoverflow.com/a/39020777/56778
Comment: @ryBear Perhaps you should edit your question to show the actual code you're using, the input array, the expected output, and the actual output. That way we would have enough information to diagnose the problem.
Comment: Thank you. I appreciate you looking at it. It still doesn't seem to be sorting properly but I will keep looking at it.
Comment: Thank you. I appreciate you looking at it. It still doesn't seem to be sorting properly but I will keep looking at it. Maybe it is. I could just be mis reading the debugger.
Answer: I figured it out. It wasn't a problem in this method after all. Thanks everyone!

Max Heapify issue


Passing javascript values into JSX

Question: I want to achieve this functionality using ternary operator. Here iconElement is an
javascript variable contains JSX. I am getting error like this (Screenshot included).
How to achieve this?

    {
        inputField ? inputField :
            {iconElem}
            <input
                {...otherProps}
                className = 'InputField'
                value = {value}
                onChange = {clicked}
                autoComplete = 'off' />

    }

Answer: You have syntax error before while using the ternary operator:

  {inputField ? (
    inputField
  ) : (
    <>
      {iconElem}
      <input
        {...otherProps}
        className="InputField"
        value={value}
        onChange={clicked}
        autoComplete="off"
      />
    </>
  )}

Comment: I want to execute both iconElem variable and input field only when ternary condition is false
Comment: You can only return a single React element, therefore you should add a fragment, see updated answer
Answer: If the input field should be visible in both cases I would do something like this instead to avoid having to duplicate components:

   {!inputField && iconElem}
      <input
        {...otherProps}
        className="InputField"
        value={value}
        onChange={clicked}
        autoComplete="off"
      />
  )}

Passing javascript values into JSX


Redirect node/id to node/path-auto-alias

Question: Using Drupal 8
I need to set various links between my content types and so far I'm setting the link using their path-auto-generated-alias, but that's terrible practice because if I change the pattern one day I will have to change every single existance of the out of date url alias.
I've seen plenty of answers for Drupal 7 with module Global Redirect but it states that it's deprecated for Drupal 8 and to use Redirect instead. I installed the module and I'm presented with this:

I have no idea what's amitted in there, tokens? If someone could direct me to a documentation where I can learn to use the module I'd really appreciate it since I'm at a loss.
The reason why I'm in that part is because I have the following Global Settings and it's not redirecting /node/id to expected Path Auto URL alias.
Answer: Found my mistake, you can't have Check access to the redirected page enabled in the global REDIRECTS.
Comment: if your nodes are published and accessible then it should still work with the access check. I also don't fully get what you're doing with links. Drupal should be able to generate the correct link  in most cases, be it an entity reference field, a link field. This should only come in to play if someone manually goes to node/1, links on the page should use the correct alias, as you otherwise have a redirect which makes it slower. If you have links inside body fields, have a look at pathologic, that might help.
Comment: Yes, you can either use pathologic, which will display the correct alias already and if you are using redirect and pathauto, then redirect will also automatically register a redirect for the old alias anyway.
Comment: I wanted to have the Global Redirects because sometimes (not always) in the body of my nodes I like to link to other nodes, and when inserting that link in the body I use the target node's PathAuto generated URL. Toady I realized that if I were to change that target node's URL Pattern in PathAuto ( say instead of /story/this-is-it to story/funny/this-is-it ) then I'd have to manually change the link I used in the body. But if I place the link with node/id then thanks to Global Redirect, I won't have to worry about it.
Comment: I am using Redirect to display the alias if it exists, but it won't work unless I  uncheck the "Check access to the redirected page" for some reason.


How to append style sheet with close element using zend?

Question: I am using zend. When i use below code,
<?=  $this->headLink()
            ->appendStylesheet(BASE_URL . 'css/css.css');
 ?>

This outputs like below with out close element.
<link href="/ecomos3/css/css.css" media="screen" rel="stylesheet" type="text/css" >

so this one fails in w3 validation and getting "end tag for "link" omitted, but OMITTAG NO was specified"
i want the link tag should be
<link href="/ecomos3/css/css.css" media="screen" rel="stylesheet" type="text/css" />

How can i do it in zend ? Kindly advice on this.
Comment: You need to set the doctype to xhtml
Comment: @vascowhite I have given  in my page.
Answer: You need to specify the docType using the doctype helper
You can do it in your bootstrap if you wish:-
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
    protected function _initDoctype()
    {
        $this->bootstrap('view');
        $view = $this->getResource('view');
        $view->doctype('XHTML1_STRICT');
    }
}

Or add this line to your config.ini file:-
resources.view.doctype = "XHTML1_STRICT"


How to generate a custom json response with Jbuilder & Rails

Question: In my Ruby on Rails app, bike rental companies can manage all their bikes (reservations, payments etc.).
Context
I would like to offer a bike rental companies (shops) the option to implement a booking form on their own website, so they can let customers make a reservation for a bike.

This booking form would then show bike_categories of which bikes are available for a given arrival and departure date.

Question
In order to manage this, I would like to generate an API controller action showing the  availability for a certain bike_category displaying the count for the number of available bikes belonging to this bike_category.
According to this post
Design RESTful query API with a long list of query parameters
I should be able to deal with queries in my api, but how do I return the count in the view using Jbuilder ?
Code
models
class Shop < ApplicationRecord
  has_many :bike_categories, dependent: :destroy
  has_many :bikes, through: :bike_categories
  has_many :reservations, dependent: :destroy
end

class Reservation < ApplicationRecord
  belongs_to :shop
  belongs_to :bike
end

class Bike < ApplicationRecord
  belongs_to :bike_category
  has_many :reservations, dependent: :destroy
end

class BikeCategory < ApplicationRecord
  belongs_to :shop
  has_many :bikes, dependent: :destroy
end

routes
  namespace :api, defaults: { format: :json } do
    namespace :v1 do
      resources :shops, only: [ :show ]
      resources :reservations, only: [ :show, :create ]
      resources :reservation_contacts, only: [:show, :create]
      resources :reservation_options, only: [:show, :create]
      resources :bike_categories, only: [:index, :show] do
        get :availability, on: :member
      end
    end
  end

controllers/api/v1/bike_categories_controller.rb
class Api::V1::BikeCategoriesController < Api::V1::BaseController
  acts_as_token_authentication_handler_for User, only: [:show, :index, :availability]

  def availability
    @user = current_user
    bike_category = params[:bike_category]
    if @user.shop.bike_categories.include? bike_category
      arrival = params[:arrival]
      departure = params[:departure]
      shop = bike_category.shop
      reservations_overlap = shop.reservations.where("reservations.arrival >= ? AND ? >= reservations.arrival", arrival, departure)
      .or(shop.reservations.where("reservations.arrival <= ? AND ? <= reservations.departure", arrival, arrival)).distinct
      unavailable_bikes = []
      reservations_overlap.each do |res|
        if !unavailable_bikes.include? res.bike && res.bike.bike_category == bike_category
          unavailable_bikes << res.bike
        end
      end
      bikes = bike_category.bikes
      @count = (bikes - unavailable_bikes).length
    else
      error
    end
  end

end

views/api/v1/bike_categories.json.jbuilder
# How to return @count?

Comment: Wouldn't it be easier to just render json using default json adapter to the client?
Comment: Thanks for your comment Roman. I'm not that familiar with this. How would that work? Just include ```render json: count: @count``` in the ```controllers/api/v1/bike_categories_controller.rb```?
Answer: your code here...
if @user.shop.bike_categories.include? bike_category
      arrival = params[:arrival]
      departure = params[:departure]
      shop = bike_category.shop
      reservations_overlap = shop.reservations.where("reservations.arrival >= ? AND ? >= reservations.arrival", arrival, departure)
      .or(shop.reservations.where("reservations.arrival <= ? AND ? <= reservations.departure", arrival, arrival)).distinct
      unavailable_bikes = []
      reservations_overlap.each do |res|
        if !unavailable_bikes.include? res.bike && res.bike.bike_category == bike_category
          unavailable_bikes << res.bike
        end
      end
      bikes = bike_category.bikes
      @count = (bikes - unavailable_bikes).length
      render json: @count, status: :ok, adapter: :json
    else
      error = ...some code here...
      render json: error, status: unprocessed_entity, adapter: :json
    end

I would do something like this


Como verificar se Data X é mais nova que Data Y?

Question: Tenho as seguintes variáveis:
$dt_local: que está guardando valor do BD;
$dt_remoto: que está guardando valor de uma fonte externa;
Até aqui tudo ótimo, preciso comparar as duas e manter a data mais atual no BD, ambas as variáveis estão vindo como String.
Como posso resolver de forma mais rápida e simples?
Comment: Relacionada ou até repetida: https://pt.stackoverflow.com/questions/33469/como-comparar-datas-em-php
Comment: qual o formato da data? dd/mm/yyyy?
Answer: Supondo que você possua essas datas em algum formato definido, você pode utilizar a classe DateTime do PHP:
$dt_local = DateTime::createFromFormat('d-m-Y', '03-04-2017');
$dt_remoto = DateTime::createFromFormat('d-m-Y', '01-04-2017');

if ($dt_local > $dt_remoto) {
    echo "Local é mais recente", PHP_EOL;
} else if ($dt_local < $dt_remoto) {
    echo "Remoto é mais recente", PHP_EOL;
} else {
    echo "Datas são iguais", PHP_EOL;
}

A saída seria: Local é mais recente.
Se a data poderá estar em qualquer padrão definido na documentação do PHP, utilize o próprio construtor da classe:
$dt_local = new DateTime('03-04-2017');
$dt_remoto = new DateTime('01-04-2017');

if ($dt_local > $dt_remoto) {
    echo "Local é mais recente", PHP_EOL;
} else if ($dt_local < $dt_remoto) {
    echo "Remoto é mais recente", PHP_EOL;
} else {
    echo "Datas são iguais", PHP_EOL;
}

Em teoria, qualquer formato previsto na tabela abaixo será aceito pela aplicação.
Comment: mas como é que se joga as datas vindas de post dentro da função DateTime?
Comment: @LeoCaracciolo algo como `$dt_local = new DateTime($_POST['dt_local'])`.
Comment: @LeoCaracciolo O que aconteceu?
Comment: não li as notações localizadas e estava entrando com as datas no formato errado e daí estava dando erro.
Answer: Uma forma de se verificar é usando a função max ( $valor1 , $valor2 ) (PHP 4, PHP 5, PHP 7)
onde $valor1 e $valor2 são valores compatíveis no formato dd/mm/aaaa ou dd-mm-aaaa.
Manual
<?php
function inverteData($data){
    if(count(explode("/",$data)) > 1){
        return implode("-",array_reverse(explode("/",$data)));
    }elseif(count(explode("-",$data)) > 1){
        return implode("/",array_reverse(explode("-",$data)));
    }
}

if  (($_POST["dt_local"])&&($_POST["dt_remoto"])){

    $dt_local=inverteData($_POST["dt_local"]);

    $dt_remoto=inverteData($_POST["dt_remoto"]);

    if ($dt_local!=$dt_remoto){
       $maior = max(array($dt_local,$dt_remoto));
       echo inverteData($maior);
    }else{
       echo "as datas são iguais";;
    }
}
?>

Comment: pronto editei a resposta, duas cabeças pensam melhor que uma né não?
Comment: Apenas um detalhe: utilizando `max`, a data retornada em `$maior` seria `05-04-2017`, pois tratando-se de *string*, é comparado de forma alfabética caractere a caractere. Neste caso, sendo o primeiro caractere igual, ao verificar o segundo, o PHP considera 5 maior que 3, retornando a primeira data como maior, ou seja, nem chega a verificar o restante da *string*. Para este método funcionar bem, a data deverá estar no formato `Y-m-d`, assim ele verificaria o mês antes de verificar o dia, não considerando o dia 05/04 maior que 03/05.


Canvas size - text rendering

Question: Is there any way how to determine the optimal canvas size for text rendering?
The input is a string with newlines, I want to contruct the canvas to fit (no insets) while using both font types - proportional and non-proportional, these types will be never mixed.
Thanks.
Answer: From the Java Tutorial Measuring Text
<code> FontMetrics metrics = graphics.getFontMetrics(font);
 int hgt = metrics.getHeight();
 int adv = metrics.stringWidth(text);
 Dimension size = new Dimension(adv+2, hgt+2);
</code>
You probably need to do this line by line of your text and detect whether your font changes between lines.

Canvas size - text rendering


Only join rows that meet certain criteria (left join of data that is left joined)

Question: I have users that have FacebookPage and Application entities associated to them. FacebookPage entities also have Application entities associated with them.
    $qb = $this->createQueryBuilder('u')
        ->addSelect('p', 'a')
        ->leftJoin('u.facebook_pages', 'p')
        ->leftJoin('p.applications', 'a')
        ->leftJoin('a.editors', 'e', 'WITH', 'e = :user')
        ->where('u = :user')
        ->setParameter('user', $user)
        ->orderBy('p.name', $order)
        ;

    $u = $qb->getQuery()->getSingleResult();

    return $u->getFacebookPages();

I want to return all of the user's Facebook pages and then show a count of applications associated with that page. I only want to count the applications where the user is an editor.
When run my current query, the pages have a count with all the page's applications (so the count includes applications where the user is not an editor).
If I change the a.editors leftJoin to a join, I get the correct counts for the pages, but it only lists pages that actually have any applications.
How can I show all the pages and only join the applications where the user is an editor?
Comment: I think it might help if I could somehow leftJoin the applications with `:user IN (a.editors)`
Comment: I also tried creating a query builder on the Facebook Page entity and left joining the applications where the editors include the user, but this only shows me the pages where the user is an editor and not all of the user's pages.
Comment: just to give you a direction: you need to use group by "pages" and then count aplications and make a if-else to set counter to 0 if non aplication found.
Answer: I solved this by adding a new query to get app ids for the applications where user is an editor.
    $user_apps = $this->getEntityManager()->getRepository('Application')->getUserApps($user);
    $app_ids = array();
    foreach($user_apps as $app) {
        $app_ids[] = $app->getId();
    }

    $qb = $this->createQueryBuilder('u')
        ->addSelect('p', 'a')
        ->leftJoin('u.facebook_pages', 'p');

    if(count($app_ids)) {
        // join with IN statement to include only apps where user is an editor
        $qb->leftJoin('p.applications', 'a', 'WITH', sprintf('a.id IN (%s)', implode(',', $app_ids)));
    } else {
        // join empty anyway to avoid db calls when iterating over pages
        $qb->leftJoin('p.applications', 'a');
    }

    $qb
        ->where('u = :user')
        ->setParameter('user', $user)
        ->orderBy('p.name', $order)
        ;

    try {
        $u = $qb->getQuery()->getSingleResult();
    } catch (Exception $e) {
        throw $e;
    }

    return $u->getFacebookPages();

This now returns all the user's Facebook pages and only join applications where user is an editor. I am probably going to change this to a DQL query so I can move the ids in IN to a subquery.


What's the best way to notate this syncopation?

Question: Trying to write out the first measure to "When I Get Low I Get High", I've read this answer, https://music.stackexchange.com/a/59262/63723, is this the best approach?
Comment: I agree that this is the best way - as I've learnt it like this! ;) The criteria was: the half or the middle of the bar should be recognizable.
Answer: There's nothing wrong with what's  in the picture. All major subdivisions are respected so one can play it at sight. The tied Cs make it clear that there is a note held from beat 2 to beat 3.
Answer: As I said in my comment: make the middle of the bar visible.
But ths will be difficult in a 3/8 like this:
https://en.wikipedia.org/wiki/Syncopation


If $(a_n)$ is any real sequence , then $(\frac{a_n}{1+|a_n|})$ has a convergent subsequence

Question: Consider the following two statements :
$S_1$: If $(a_n)$ is any real sequence , then $(\frac{a_n}{1+|a_n|})$ has a convergent subsequence .
$S_2$ : If every subseqeunce of $(a_n) $ has convergent subsequence , then $(a_n)$ is bounded .
Which is of the follwoing statement is true ?
(A) Both $S_1$ and $S_2$ are true .
(B) Both $S_1$ and $S_2$ are false .
(c) $S_1 $ is false but $S_2$ is true .
(D) $S_2$ is false and $S_1$ is true .
My work : $1+|a_n|\geq 1+a_n>a_n$ . So $|(\frac{a_n}{1+|a_n|})|\leq 1$
. So it is a bounded sequence and via Bolzano-wietrass theorem it has a convergent subsequence .
$a_{2n}$ and $a_{2n-1}$ are convergent . So they are bounded . Let the bounds be $M $ and $L$ respectively .
Hence $a_n \leq M+L $ .So $a_n$ is bounded .
So both $S_1$ and $S_2$ are true .
Answer: You are right about $S_1$, and your proof is correct.
Your proof for $S_2$ is wrong, since $(a_{2n})$ and $(a_{2n+1})$ does not represent every subsequence.
Plus, they can not be bounded in general, since $(a_n)$ can be anything.
What you can do instead:
If $(a_n)$ is not bounded, then there exist a subsequence $(b_n)$ such that
$$\vert b_n\vert \to \infty.$$
And this sequence $(b_n)$ can not have a convergent subsequence.
So $S_2$ is true.
Comment: Well, you can guarantee that $|b_n| \to \infty$.
Comment: @Omnomnomnom I think you can choose $(b_n)$ such that either $b_n\to +\infty$ or $b_n\to -\infty$. But you are right, may be it is more clear that way.
Comment: I'm not sure about clarity, but using $|b_n|$ means you don't have to consider two separate cases.
Answer: Your assessment of $S_1$ is correct: the statement is true.
Note that your approach for $S_2$ is incorrect: we cannot assume that the particular subsequences $(a_{2n}), (a_{2n-1})$ are convergent; all we know is that these subsequences have their own convergent subsequences in turn.
However, the statement is indeed true. I find it's easiest to prove by contrapositive: suppose that $(a_n)$ is not bounded.  Then for every $k \in \Bbb N$, there exists an $n_k \in \Bbb N$ such that $|a_{n_k}| > k$ (that is, we can construct a sequence with $|a_{n_k}| \to \infty$).  If we construct such a subsequence $(a_{n_k})$, then this subsequence can have no convergent subsequence (why is this the case?).
So, if $(a_{n})$ is such that every subsequence has a convergent subsequence, $(a_n)$ must be bounded.
Answer: Your work on the first statement looks good.
On the second, the problem statement says
S2 : If every subseqeunce of $(a_n)$ has convergent subsequence , then $(a_n)$ is bounded.
So we don't know at $a_{2n}$ and $a_{2n+1}$ are convergent, only that they have a convergent subsequence.
Comment: You are right . But how about this approach : $a_{2n}$ is a subsequence of $a_n$  .So $a_{4n}=a_{2(2n)} $ and $a_{2(2n+1)} $ are subsequences of $a_{2n}$ and hence bounded by $M_1 $ and $M_2$ respectively . Similarly $a_{4n+1}=a_2{2n}+1$ and $a_{4n+3}=a_{2{2n+1}} $ are bounded by $M_3$ and $M_4$ .
So $a_n$ is bounded by $M_1+M_2+M+M_3+M_4$ . Does it work ?
Comment: @SumanKundu now you're assuming that $a_{2(2n)}$ is convergent, which isn't necessarily the case.
Comment: That still doesn't work because, for $a_{2n}$, for example, we know that it has *some* convergent subsequence, not that *every* subsequence is convergent. So it may happen at $a_{4n}$ is not convergent, but some other subsequence is.
Comment: Ahh ! Now i understand . Thank you .


My installer package throws 3010 or 1641 when run from SCCM. Works fine if i run as admin

Question: I have a installaer package (mySoftware.exe) which is working fine without any issue when i run manually as admin. But i am getting exit code 3010,1641 when i install the package via SCCM. My code skips the next steps if it gets other than "0" exit code. Right now, my installer consider "0" as Success. Non-Zero are error codes.
Do i need to modify installer script to consider "0","3010","3011","1641","1604" as Success exit code ? Do we need to change anything at SCCM end?
Do i need to consider to add any other exit code as Success? Do we have any other workaround for this issue.
mySoftware.exe /s /v" /quiet ADDLOCAL="mySoftwareConfig" /L*v "%mySoftwareLogFile%" /clone_wait

> My installer script has the following actions:
  1)First uninstall existing package on the system.
> 2. Install the new package.  (Exit code 3010,1641 returns during installing the new package)
> 3. Configure the package.

Comment: Does the installer require admin permission to work correctly? What happens if you run in manually without admin permission?
Comment: I works fine without admin access as well. I always go to C:\Windows\System32\Cmd -> and launch the installer form this location like how SCCM use the system user.
Answer: Reboot: Those are generally just standard reboot message and you should handle them in your batch file as you suggest yourself.
This is just a mock-up sample (I am no expert at this anymore):
msiexec.exe /I Setup.msi ALLUSERS=1 /L*V %MSILOG% /qb-! ADDLOCAL=ALL
if %errorlevel% == 3010 goto REBOOT

<..stuff here..>

:REBOOT
echo MSIEXEC returned exit code 3010 which means that a reboot is required to complete installation >> %LOGFILE%

Some info on errorlevel:

https://ss64.com/nt/errorlevel.html
https://devblogs.microsoft.com/oldnewthing/20080926-00/?p=20743

MSI Error Messages: https://learn.microsoft.com/en-us/windows/win32/msi/error-codes

0 - ERROR_SUCCESS - The action completed successfully.
1604 - ERROR_INSTALL_SUSPEND - Installation suspended, incomplete.
1641 - ERROR_SUCCESS_REBOOT_INITIATED - The installer has initiated a restart. This message is indicative of a success.
3010 - ERROR_SUCCESS_REBOOT_REQUIRED - A restart is required to complete the install. This message is indicative of a success. This does not include installs where the ForceReboot action is run.

And from other sources:

3011 (0xBC3) - ERROR_SUCCESS_RESTART_REQUIRED - The requested operation is successful. Changes will not be effective until the service is restarted.
Comment: I am writing some flat-file in the << -- Stuff Here --> section after the successful installation of my installer. Since i am getting exit code3010 or 1641, it directly goes to exit and skips mine <> section. I wanted to execute <<--Stuff Here --> section though after i get any of the exit code 0,3010,3011,1604,1641 since it is not really a failure on the installer?


How resize Tab control programmatically?

Question: I want programmatically resize tab Control on my winform.
tabCtrl.Size.Width = Convert.ToInt32(numericUpDown1.Value);
tabCtrl.Size.Height= Convert.ToInt32(numericUpDown2.Value);

But I get error:

Cannot modify the return value of 'System.Windows.Forms.Control.Size' because it is not a variable

Any idea how can I resize Tab control programmatically?
Answer: Use this. Note the (int) cast because NummericUpdown.Value is a decimal value.
tabCtrl.Size = new Size((int)numericUpDown1.Value, (int)numericUpDown2.Value);


How to attach css classes to the  title attributes if node_is_page() dynamically?

Question: To preprocess the node title field is obviously not the easiest. It has its place in the node.tpl.php and in the page.tpl.php by default and it has its own status in Drupal core, which makes it not fieldable as simply as other fields and entities in a given content type bundle.
That's why there are many discussions going on at drupal.org and some little helper modules are also around already, to make the title field more flexible in different scenarios like field translation, label design, field order and much more. So if this is your problem you will easely find a little module helping you.
But what if you don't want to touch the behaviour of the title field as designed in core but only want to preprocess the title to change the markup dynamically? Suddently google keeps silent. Unlike others I agree with some core contributors who explain wisely why the title field has its reasonable difficulties and why the decision to make it simply a "field like others" is not THAT easy to make. So for some reasion I need a solution in template.php
This is how the page.tpl.php looks like in my case:
// page.tpl.php

<?php print render($title_prefix); ?>
    <?php if ($title): ?>
        <?php if ($page): ?>

            <h1 <?php print $title_attributes; ?>>
                <?php print $title; ?>

        <?php endif; ?>
    <?php endif; ?>
<?php print render($title_suffix); ?>

And this the place where we obvisously should try to make it happen:
// template.php

function YOURTHEME_process_page(&$variables) {
    if ($variables['view_mode'] == 'full' &&
        node_is_page($variables['node'])) {
            // do something with $variables['title']['attributes'][];
    }
}

But to be honest, I am a little bit lost here, since I only want to change the rendering of
 to
. Does anybody has an idea of how to achieve this?
The attributes class seems not to exist this way, because I get an Unknown index warning and the class gets not attached. Or maybe I have to point to $title another way? Maybe something like $node->title ? I know how to wrap the title with a new container, or how to change the suffix/prefix. But here would really appreciate your thoughts. Thank you very much ...
Comment: Okay, another idea: a little bit dirty since this is far away from the way it is supposed to be, but hiding '$title' in page.tpl.php and removing the IF NOT PAGE condition from the standart node.tpl.php (like in Bartik) makes it possible to access the title-attributes array, since node.tpl.php seems to know title-attributes, page.tpl.php not (as you sad) - But in this case I have to reimplement the node is page node list switch between h1 and h2 programmatically in template.php somehow again, sonce $title in page.tpl.ph did this before. Let's wait and see if this makes sense. I'll try.
Comment: I think this is going to be impossible to answer here - `$title_attributes` is not added by Drupal core (see the source of [page.tpl.php](https://api.drupal.org/api/drupal/modules!system!page.tpl.php/7)), so it must be a theme/module specific to your installation that's adding it. WIthout knowing what the theme/module is I don't see how this can be answered
Comment: Thanks Clive. So you think there is also no chance to achieve this rather  in preprocess_node or preprocess_field? It is an own custom theme. So nothing where I have to stick with the way the tpl. files are build. I can change it to the needs. In Bartiks node.tpl.php there is a title_attributes placeholder but this doesn't affect the full node page title anyway, so I also will have no luck with the two other preprocess functions, I guess. :(
Comment: If it's there, and it's got there in any sort of 'Drupal' accepted manner, then you should be able to alter it in _either_ `hook_preprocess_page()` or `hook_process_page()`, depending on which one's actually been used in the first instance. I'd search through your custom theme/modules for the term `$vars['title_attributes']` or `$variables['title_attributes']` to see if you can find where it's being set. From there it should be easy
Answer: Okay, as commented under the question, I've tried out another idea: a little bit dirty since this is far away from the way it is supposed to be, but hiding '$title' in page.tpl.php and removing the IF NOT PAGE condition from the standart node.tpl.php (like in Bartik) makes it possible to access the title-attributes array, since node.tpl.php seems to know title-attributes, but page.tpl.php not...
But in this case I have to reimplement the programmatically "node is page OR node list switch" toggling of h1 and h2 again, since if-page $title in page.tpl.php did this before:
After removing the complete if-title-title part (in Bartik it looks like this, near the $content) from page.tpl.php,
<?php print render($title_prefix); ?>
  <?php if ($title): ?>

      <?php print $title; ?>

  <?php endif; ?>
<?php print render($title_suffix); ?>

... I have added (exchanged) this in the node.tpl.php:
//node.tpl.php

// usually we have something like the following here
/*
<?php if (!$page): ?>
   <h2<?php print $title_attributes; ?>>
      <a href="<?php print $node_url; ?>"><?php print $title; ?>

<?php endif; ?>
*/

// but we exchange it with this ...

<?php print render($title_prefix); ?>

  <?php if ($page): ?>
    <h1<?php print $title_attributes; ?>>
       <a href="<?php print $node_url; ?>">
          <?php print $title; ?>

  <?php endif; ?>

  <?php if (!$page): ?>
    <h2<?php print $title_attributes; ?>>
      <a href="<?php print $node_url; ?>">
         <?php print $title; ?>

  <?php endif; ?>

<?php print render($title_suffix); ?>

Now I do have my title inside of my wanted scope, where I can theme it programmatically inside the main content container. Thanks to Clive for his support on my question, and special thanks to Digidog from drupal.org, who gave me the final hint per mail.
Answer: This is how I add classes to titles from page.tpl.php:
In page.tpl.php:
<?php if ($title): ?><h1 <?php print $title_attributes; ?> id="page-titles"><?php print $title; ?>
<?php endif; ?>

Note that $title prints the title itself. Note that $title_attributes prints out class='' where included classes are found in $title_attributes_array['class'][].
You can add classes the following way.
In template.php:
/**
 * Implements template_preprocess_page().
 */
function hook_preprocess_page(&$vars) {

  $vars['title_attributes_array']['class'][] = 'element-invisible';

}

Note that the hook_preprocess_page function should be [your_theme_name]_preprocess_page.
What's interesting is that $title_attributes does not exist in the available variables. Drupal does some magic to allow $title_attributes to print as class='class1 class2' based on what $title_attributes_array contains.
Comment: I'm on my tablet, but I think $title_attributes comes from a hook_process and not a preprocess, so that is why you don't see it.
Answer: If you are okay with using jQuery, then you can achieve this using the addClass method.:
 function YOURTHEME_process_page(&$variables) {

   if ($variables['view_mode'] == 'full' && node_is_page($variables['node'])) {

       drupal_add_js('
       jQuery(document).ready(function(){
            $('jQery SELECTOR OF H1').addClass('my_css_class');
        });

    ', 'inline');

}

}
Comment: Thanks sandesh yadav. This is a very smart solution, but sadly I have to care about accessibility and users who have js turned off. The new markup I need in here is sadly essential for the readability of the node. But it's a very nice solution and it will help me on other questions. :) Thank you
Comment: welcome.Most of the users have js turned on now a days. But still you cant rely 100% on it. :)
Answer: This is how I made it work:
template.php
/**
 * Implements template_preprocess_page.
 */
function my_theme_preprocess_page(&$vars) {
  $node = isset($vars['node']) ? $vars['node'] : '';
  // Set class name for the page's title.
  $vars['class_name'] = node_is_page($node) && $node->type == 'node_type' ? ' title-class-name' : '';
}

page.tpl.php
<?php if ($title): ?>
  <h1 id="page-title" class="title<?php print $class_name; ?>"><?php print $title; ?>

<?php endif; ?>

Alternatively you may use the Display Suite module which, of course, exceeds the limits of just adding a class to a title.


Question about tribute band 'etiquette'

Question: I've been practicing the vocal part to a particular rock band that I really like, with the aim of either joining or starting a tribute band. However, there is already a tribute band for that group playing in my city; although they don't seem to be hugely active (playing approx. 1 gig every month or two, it seems).
So, I'm wondering whether I should try to contact them first and see if they could use another singer, or whether I should just advertise and try to start a new tribute band with some fresh people?
I'm a little concerned that, if I approach them, it might come across as if I'm trying to 'muscle in' on their gig or push out their incumbent singer. However, if I just ignore them and start a new band, could that come across as a bit rude, if they might have been interested in looking at another singer (in case their current one can't make a gig, for example)?
Perhaps I'm over-thinking this a bit, but I lack experience of the tribute band 'scene' and would appreciate some advice.
Comment: Well, you ARE attempting to 'muscle in' to either the existing singer's or the whole band's field, aren't you!   You might be able to do this amicably, but don't be too surprised if it turns into a bit of a turf war.
Comment: There is nothing more rival-like than two tribute bands playing the same music in the same area. I've seen it happen before with Queen tributes, they really don't seem to like eachother because you're practically cutting the demand for both of the bands in half, so I think your concerns are accurate. I don't think a stage manager would be thrilled to book two tribute bands of the same artist in a short timespan. That being said, I think you should be able to do whatever you want. Put up your fists, though.
Comment: They're not going to like it either way. And if you joined as dep. singer, you may get a couple of gigs a year - if it went well. They might be happier with you, who knows? Better forming your own band. They might hear you - and nick your guitarist...
Comment: @Laurence Payne I was hoping we can just all be friends! Lol ..
Comment: If they're only getting one gig a month, I doubt they'll be content that 'there's enough work for both of us'.
Comment: @Laurence Payne Perhaps. I think it depends on the reason for the low gig rate. It could be low demand, or perhaps they're just busy with other projects or they're amateur musicians and have busy non-music schedules. I don't know their situation.
Comment: @Rick van Osta something that occurs to me is that there is always competition in whatever you do. If I was going to open a cafe or bakery, there would be competition, right? I think this is why the level of demand is a key question - is there enough demand in the area to support two tributes?
Answer: I think maybe one of the most professional ways to handle this is to try out for their band, like you said, but if they decline you, then it would be acceptable to start a competing band. The existing band will see that you didn't really have a choice, and no one should be able to be angered by you doing what you enjoy doing. Do try to avoid antagonizing them beyond necessary, however.
Comment: Thanks. I will at least scout them out, but it might be hard to actually try out for them, if they haven't got an opening. I do agree though, that I should be able to play the music I want to play somehow.
Answer: I'm going to post a possible solution as an answer to my own question. From some of the comments, it sounds like I was right to be concerned that there might be some 'friction', if I was to try to start a tribute band when there is already another one in my area.
I guess I'm not really afraid of a 'turf war', if it comes to that. I feel really driven to do this, and I think I could do a good job of it. Although, my main motivations are to have some fun; perhaps make some friends and maybe even entertain some people, not to piss other people off. So, I would rather avoid friction, if possible.
Perhaps a good first step would be to go and see the other band perform. That way, I can see what they are like and get a feel for the audience and the 'scene' for that tribute. Perhaps I can also talk to some band members and get a better idea of why they aren't gigging more regularly and what the demand level is like. If there is more local demand than they can meet, then things might not feel so claustrophobic with two tributes on the scene.
Otherwise, I guess it's not going to hurt to advertise for some other musicians and start practicing. Some of them might have some more experience of the local rock gig scene and might be able to give some advice. Another idea is that perhaps we could start out as a more 'general' covers band that just happens to lean heavily towards that artist's style and their music could form a good slice of the set. That way, I can get some experience of the local scene and test the water, without it coming across as a direct, frontal assault on their turf?

Question about tribute band 'etiquette'


python - how do I specify allowed patterns for **kwargs?

Question: As the title suggests, I want to accept if the arguments fit a certain pattern, otherwise return an error message. The order of arguments doesn't matter, as I am using (forcing to use) keyword arguments anyway.
for example, let's say I have the following patterns:

hex_list
int_list
int_list, size
hex_list, size
from_file

※ size, hex_list, int_list, and from_file are keyword arguments.
※ I have to use only one of the above patterns for the arguments I will send.
※ e.g. from_file, size is not allowed!
※ Normally there are more arguments, but I also reduced the number of arguments to reduce confusion.
As you can see most use only one argument but I still have some argument patterns that use multiple (2) arguments.
for use case:
class Calculator:
  def __init__(self, *args, **kwargs):
    if args:
      raise ValueError("Calculator can only be called with keyword arguments")

    allowed_keys = "size", "hex_list", "int_list", "from_file"

    for keyword in kwargs.keys():
      if keyword not in allowed_keys:
        raise ValueError("wrong keyword!")

    hex_list = kwargs.get("hex_list")
    int_list = kwargs.get("int_list")
    from_file = kwargs.get("from_file")
    size = kwargs.get("size")

    if from_file:
      if hex_list or int_list or size:
        raise ValueError("When 'from_file' is specified, you cannot give any other args")
      # do stuff
    elif hex_list:
      if int_list or from_file:
        raise ValueError("When 'hex_list' is specified, you can only give a value to the 'size' arg")
      # do stuff
    elif int_list:
      if hex_list or from_file:
        raise ValueError("When 'int_list' is specified, you can only give a value to the 'size' arg")
      # do stuff
    else:
      raise ValueError("wrong arg(s)")

    # do more stuff ...

It seems okay for this specific example, but as I mentioned above I normally have a lot more arguments. Therefore, the amount of or operator I will write increases and it becomes difficult to read, like:
if from_file:
  if hex_list or int_list or size or from_bits or byte_list or from_string or etc.:

That's why I wanted to create a specific list of patterns and follow it.
Is this okay to do this way? If it is why? I mean doesn't this look like spaghetti code?
And once again, how can I specify the patterns for **kwargs?
Answer: Lots of possibilities here - you could do something like this
    allowed_keys = (
        {"hex_list", "size"},
        {"int_list", "size"},
        {"hex_list"},
        {"int_list"},
        {"from_file"},
    )

    if set(kwargs.keys()) not in allowed_keys:
        raise ValueError("wrong keyword!")

Essentially comparing the list of arguments as one instead of individually, and using sets to ignore order.
Comment: Nope, that can go as you can equate entire sets
Comment: I don't need the for loop in this case, do I?


Creating an exposed filter on a view as a list with taxonomy terms

Question: I have categories of photographs and each photograph is categorised. So to expose the filter to the anonymous user they can click on a category and it shows that categories images.
How would I replace the select list or auto complete exposed filter with this so I can then style the list as a horizontal small menu above the view?
Answer: Better Exposed Filters would be helpful for that.  It allows you to replace the select/autocomplete with normal anchors that can be styled however you prefer.
After installing and enabling BEF, add your exposed filter and save it (you only have the standard options at this point).  Then, go to the views advanced settings and change "Exposed form style" to Better Exposed Filters.  Then you will have a BEF Settings option, this is where you will see the options below.
Advanced settings:

This is the setting you're looking for:
Comment: I don't seem to have this option in my Exposed Filter settings when adding the filter Content: Has taxonomy terms (with depth). I'm using taxonomy terms to filter and trying to expose this.
Comment: I've added some more specific details to the answer.  In short, those options are available under the BEF settings rather than the exposed filter settings.


Turbine doesn't know contextPath of each application through Eureka

Question: When deploying Spring Cloud-enabled microservices on JBoss, we have to use a contextPath. Turbine doesn't seem to fetch the contextPath from eureka and eureka doesn't seem to ask it to the microservices.
Some more details:
Every microservice has its own Jboss, and its own contextPath defined in the war, as such:
hostname1:port1/products
hostname2:port2/users
hostname3:port3/orders

Endpoints (actuator and our own) are exposed after the contextPath (not using management.context-path):
hostname1:port1/products/env
hostname1:port1/products/info
hostname1:port1/products/books
hostname1:port1/products/books/123

Eureka only cares about the hostname and port. It allows us to define a different UrlPath to info and health although this is not part of the data Turbine needs to get to hystrix.stream:
eureka:
  instance:
    statusPageUrlPath: ${server.contextPath}/info
    healthCheckUrlPath: ${server.contextPath}/health

Is there a way to tell Turbine which contextPath is used for which application? These are different per application so a cluster-wide fix described here wouldn't be sufficient I suppose.
Comment: I turbine "cluster" is for instances of a service, so all of "products" or "users", so it should work for your case.
Comment: Since clusters cannot be aggregated into a single stream, it would mean ops need to have a dashboard open for every type of microservice. Is that manageable in your experience? Would the dashboard perhaps only be looked at during deployment of a specific cluster?
Comment: You can only view one cluster at a time in normal turbine.  With https://github.com/spring-cloud/spring-cloud-netflix/tree/master/spring-cloud-netflix-hystrix-amqp we aggregate all statistics via rabbitmq (not http), so you can see everything at once.
Comment: Wow great piece of information! I'd like to accept your comment as answer but I don't think that's possible.
Well either way thanks for the fast and helpful feedback Spencer :)
Comment: moved my comment to an answer
Answer: You can only view one cluster at a time in normal turbine. With spring-cloud-netflix-hystrix-amqp we aggregate all statistics via rabbitmq (not http), so you can see everything at once.


Changing default UPN for iPhone/ActiveSync seamless Setup: any downsides?

Question: Setting up a brand-new domain and want to achieve ActiveSync/Autodiscover Nirvana: no certificate warnings, no having to enter in Server Names or Domains, just pure Contoso-like buttery bliss.
Have ad.mycompany.com as the current default UPN suffix; from what I've been reading, in order to have iPhones get added with just email address and password, I need to add an alternative UPN suffix and set it for any new or current users.
Seems simple enough, but are there any downsides or pitfalls to setting up alternative UPN suffixes as the default?  I'm assuming that both suffixes will be valid (ad.mycompany.com and mycompany.com) regardless of authentication method and device, but this is entering into the Dark Arts of AD that I'm not familiar with.
Answer: In general you will be fine. I'm not 100% sure if all possible UPNs work or just the configured suffix and the suffix matching the actual domain name of the domain, but both of those definitely will work for normal user logons (just tested on my domain). And that is the only possible pitfall.
See: Why can a user log in via more than one UPN
Edit: Only the configured UPN and the implicit UPN will work (in addition to DOMAIN\user). So if you add more UPN suffixes in the future your users will still only have two options to logon: whichever one is configured for their account and the implicit one (unless they are the same in which case that's their only UPN option). I followed one of the links in the above link.
Comment: By the way, you get a lot more than just iPhone configuration ease. Any ActiveSync device and Outlook/Outlook AnyWhere will also auto configure. And it's required for federation with Microsoft cloud services. And if you haven't seen it yet, you can test AutoDiscover and Outlook Anywhere here (best to use a test account you can disable): https://testconnectivity.microsoft.com