How to use Instagram Direct message Api

Question: I am looking for Instagram Direct message API, I tried some private API libraries but I couldn't find any direct message API
How I can use Instagram Direct message API correctly?
I had a look at other posts, but they did not solved my problem
Comment: Does this answer your question? [How to use instagram direct api](https://stackoverflow.com/questions/34676432/how-to-use-instagram-direct-api)
Comment: it did not work to me  @KrishnaSony
Answer: There is no Instagram API for direct messages, I guess there won't be any. You may be able to use the Instagram node.js Private API library
I have to warn you though, that I did try to use the PHP library and Instagram didn't
If you are able to use node.js, it seems that Thread.configureText can be used for sending direct messages on the node.js library.
https://github.com/dilame/instagram-private-api
Alternatively, I would suggest using a headless web scraper like Selenium or Cypress
Comment: @KavehGarshasp Instagram deprecated most of the API
Comment: it did not work to me

How to use Instagram Direct message Api


How can i change the language of flutter app?

Question: I want to make a dropdown item list of different languages and when user selects one of these app language should change. I don't know what logic to apply for changing language please help me.
Answer: I have found translator's:

https://pub.dev/packages/translator
https://pub.dev/packages/flutter_translate
https://pub.dev/packages/google_translator

By the plugins I writtend you have documentations but you also can go to youtube and look a tutorial about them.
Next time you can simple google what you want to have or go to pub.dev and writte in the search bar what you want.
I wish you a good day!
Comment: Two of the solutions proposed are based on the assumption that you want to use an automated translation service, which may not be what the OP wanted.
Answer: This is the topic of internationalization: https://docs.flutter.dev/development/accessibility-and-localization/internationalization


What do these chord annotations mean?

Question: What do the chords in parentheses mean, and how could you play Bm7 and B♭M7 at the same time?
Comment: (In case it's not obvious, this is Autumn Leaves, and at the start of the line would be a treble clef and two flats.)
Comment: The whole progression is `| Cm | F7 | BbΔ | EbΔ | Aø | D7alt | Gm |`. For those wondering what the rest of this reharm looks like, it's typically: `| Cm | F7 | Bm E7 | Bbm Eb7 | Am D7 | Abm Db7 | Gm |`.
Answer: To me it looks like the chords above in parentheses are an alternative progression you can play instead of the ones below them.
It's either:

| Bbmaj7 | Ebmaj7 |

or

| Bm7 E7 | Bbm7 Eb7 |
Comment: @ggcg correct. The answer in fact suggests that they are *not* played at the same time, by using the term "alternative," and it was already accepted when I left my comment. But the question "how *could* you play them at the same time" may be answered without regard to what one would actually do; the answer could say a few words about that. It's probably not necessary, since most musicians experienced in jazz and "western" classical music will know that playing the chords at the same time is impractical at best and would sound fairly awful.  My comment was largely intended to be humorous. :-)
Comment: @awelotta, true but BbMaj7 and B-7 don't form a useful poly chord.  It is more likely that some form of tri-tone sub and cycle extension are in play.
Comment: @phoog, the answer does not suggest that they are played at the same time.  Though it doesn't really illuminate the reason that such a sub would be there.
Comment: All the jazz composers were really out there thinking in polychordal progressions.
Comment: @phoog, I see now.  Very nice.
Comment: I think it is worth pointing out that if one just reads the root notes as though it were a bass line, the Bb -> Eb of the last two bars is merely converted to a B->E -> Bb->Eb, i.e. played once a half-step higher and then once in the normal key - this is a common technique players will often use even in spite of what's written, but here the composer (or arranger) has helped by adding additional harmonic ideas with the minor->major(err..mixolydian) development within each bar in the alternate version.
Comment: @DarrenRinger, that is a nice technique! It's not quite what's happening here--note that the chord qualities have changed (major to minor / dominant 7th). These two bars are part of a larger series of half-step descending ii-V's that end on Gmin. The original progression is `| Cm | F7 | BbΔ | EbΔ | Aø | D7alt | Gm |`. The whole reharm is typically `| Cm | F7 | Bm E7 | Bbm Eb7 | Am D7 | Abm Db7 | Gm |.`
Answer: Several answers point out that this is an alternative progression.  An important point is to question why.  You definitely do NOT play them at the same time.  When this type if choice is given you may have one of them during the solo section to provide more "harmonic texture" if that's a term, or they may be for different endings.  It would help to see the next line to know where the chromatic ii-V's are going.  Is the tune modulating to Ab?  This type of device is very common in Wes tunes as the head may have a simpler set of changes and the solo filled up (chromatic ii-V's are common in Jazz and Bop).  The other common use is for the ending of the song (i.e. "on the final time through the head").
Comment: The tune here is Autumn Leaves, so the whole progression is `| Cm | F7 | BbΔ | EbΔ | Aø | D7alt | Gm |`. This is part of a fairly common reharmonization that goes: `| Cm | F7 | Bm E7 | Bbm Eb7 | Am D7 | Abm Db7 | Gm |`. The half-step descending ii-V's sound good, like you mention, because they form tritone substitutions for secondary dominants. (This is a common form of back cycling.) Without the ii chords or the tritone substitutions, the progression would be: `| Cm | F7 | B7 | E7 | A7 | D7 | Gm |.` Or you could look at it (pre-tritone sub) as: `| Cm | F7 | Bb7 | Eb7 | Ab7 | Db7 | Gm |`.
Answer: The simpler version is the lower one. If one wanted to be a little more adventurous, one could use the chords in parentheses. There are many examples of this in real and fake books. And after this, there are probably many more options of different chords that one may utilise.
Answer: They are just alternate chords NOT TO BE PLAYED SIMULTANEOUSLY.  It is a ii V7 chromatic progression which is very common in jazz.
It is a "longer" way to get to the I chord. So instead of playing a boring Dm7 to a G7 to a C, you can play, Ebm7 Ab7 Dm7 G7 C. Or Em7 A7 Dm7 G7 C.  Or . . . there are dozens of variations. You can do whatever you like.  That is what will make you you.
Listen to players like Oscar Peterson, Art Tatum, Dick Hyman, Peter Nero and Adam Makowicz, they are all prolific ii V players.  So instead of playing the written ii V they will go up a half or whole step, a third or a fourth,  and work down to the I.
All music is littered with two fives.  It is the base of the circle of fourths.  As far as standards go, SATIN DOLL or LOVER are loaded with them.
As an exercise, pick a V7 chord and use four chords to two five down to it.
Answer: It means you could play either of the two chords Bm7 or BbM7. Many chords can replace another while still maintaining the qualities or jazz music.

What do these chord annotations mean?


How can I automate letsencrypt certificates with apache and standalone authentication?

Question: I have many letsencrypt certificates with apache authentification. They are very well updated automatically.
I have one certificate (xmpp), that has standalone authentification. This one always fails because I have to stop apache in order to use it.
Now, to solve my problem I could add a cronjob that stops apache, runs certbot certonly -d xmpp.host.de --standalone --non-interactive and restarts apache. The problem is that in 99% I'm stopping apache without reason, because the cert isn't expired.
I didn't find a really good solution to that problem. How do you solve that?
Comment: Why don't you use dns authentication instead? or configure a vhost in apache that allows you to update the certificate?
Answer: Configure a vhost in apache for xmpp.example.com that is used by certbot for authentication. You don't have to place any actual content there. I use this to renew the certificate for dovecot.
I then use the renew-hook of certbot to restart or reload the correct service, depending on the domain that has been renewed. You can see a basic script for this in my answer here.


Prove the sum of exponential random variables converges almost surely

Question: Let $X_1,X_2,... $ be independent exponentially distributed random variables such that $X_n$ has parameter $\lambda_n$. Let $S_n:=\sum_{i=1}^n X_i$. Show that if $\sum_{n=1}^\infty \frac{1}{\lambda_n}<\infty$, then $S_n\rightarrow S$ almost surely, where $S$ is some random variable which is almost surely finite.
It seems this can be proved by using Kolmogorov three series theorem but I'm not sure if this is the easiest way to prove it. Could somebody give any hints, thank you.
Comment: $E(S)=\lim_{n\to\infty}E(S_n)=\sum_{n=1}^{\infty}\lambda_n^{-1}<\infty$ - hence $S<\infty$ a.s.
Comment: Yes, Kolmogorov's three-series theorem is (almost always) the easiest way to show that a sum converges almost surely. Which of the three series are you having trouble proving convergence of?
Answer: HINTS:  Let $A = 1$.
i)  To show that $\sum \mathbb{P}(|X_n| \geq 1)$ converges, note that $e^{-x} < \frac{1}{x}$ for all $x > 0$.
ii) To see that $\sum \mathbb{E}\left(X_n \mathbf{1}_{X_n \leq 1} \right)$ converges, note that $\mathbb{E}\left(X_n \mathbf{1}_{X_n \leq 1} \right) \leq \mathbb{E} X_n$.
iii) To see that $\sum \text{Var}\left(X_n\mathbf{1}_{X_n \leq 1}\right)$ converges, note that $\text{Var}\left(X_n\mathbf{1}_{X_n \leq 1}\right) \leq \text{Var}\left(X_n\right)$ and that if $\{a_n\}$ is positive, then $\sum a_n < \infty$ implies $\sum a_n^2 < \infty$.
Comment: Thank you very much, now I understand the convergence. :)
Answer: $$\infty > \sum_{n} \frac{1}{\lambda_n} = \sum_{n} E[X_n] = E[\sum_{n} X_n]$$
$$\to \infty > \sum_{n} X_n = \lim_m \sum_{n=1}^{m} X_n = \lim_m S_m = \lim_n S_n$$
Choose $S_n = \sum_{n} X_n$


Let $A,B$ be $2\times2$ matrices. Given that we know $\text{Tr}(A)$, $\text{Tr}(B),\text{Tr}(AB)$, how do I find $A$ and $B$ that have those traces?

Question: Let $A,B$ be $2\times 2$ matrices. Given that we know $\operatorname{Tr}(A)$, $\operatorname{Tr}(B),\operatorname{Tr}(AB)$  how do I find $A$ and $B$ that have those traces?
Naively, I would let $A$ be the diagonal matrix with entries $\operatorname{Tr}(A)/2$ and the diagonal entries of $B$ be $\operatorname{Tr}(B)/2$ but this just doesn't work.
(I know those traces do not uniquely determine $A,B$ but I just need one instance of $A,B$)
Comment: There's a formula that relates various products of traces of various products for 2x2 matrices.  I'm not sure if it can answer your question, but in case anyone can find a way to use it: https://math.stackexchange.com/questions/2303322/abba-trba-trab-trab-tratrbi-2
Answer: Edit: I've revamped the answer to include the determinate of $1$ condition.
For an elementary approach: Let $Tr(A)=x$, $Tr(B)=y$, and $Tr(AB)=z$. For some $a,b$, we have
\begin{align*}
A&=\begin{pmatrix}a&a_1\\a_2&x-a\end{pmatrix}&
B&=\begin{pmatrix}b&b_1\\b_2&y-b\end{pmatrix}
\end{align*}
This gives us
$$AB=\begin{pmatrix}ab+a_1b_2&\square\\\square&a_2b_1+(x-a)(y-b)\end{pmatrix}$$
Therefore, $$z=ab+a_1b_2+a_2b_1+(x-a)(y-b)\implies a_1b_2+a_2b_1=z-ab-(x-a)(y-b).$$
Now, if we want the added condition that $|A|=1$ and $|B|=1$, then
\begin{align*}
a(x-a)-a_1a_2=1&\implies a^2-ax+a_1a_2+1=0\\
b(y-b)-b_1b_2=1&\implies b^2-by+b_1b_2+1=0
\end{align*}
Hence,
$$a=\frac{x\pm\sqrt{x^2-4a_1a_2-4}}{2}\quad\text{ and }\quad b=\frac{y\pm\sqrt{y^2-4b_1b_2-4}}{2}.$$

As an example, say $Tr(A)=7$, $Tr(B)=-2$, and $Tr(AB)=4$. Then
\begin{align*}
a_1b_2+a_2b_1&=4-ab-(7-a)(-2-b)\\
&=18-2ab+7b-2a\\
\end{align*}
We have the conditions that
$$a=\frac{7\pm\sqrt{45-4a_1a_2}}{2}\quad\text{ and }\quad b=-1\pm\sqrt{-b_1b_2}.$$
We will just take the "$+$" solution. Therefore, we can substitute these values and simplify (quite a bit) to get
\begin{align*}
a_1b_2+a_2b_1=11-\sqrt{4a_1a_2b_1b_2-45b_1b_2}
\end{align*}
At this point, we have many choices, so let $a_2=0$, $b_1=0$, $b_2=-1$. Then we have
\begin{align*}
a_1=-11
\end{align*}
We can now solve for $a$ and $b$:
$$a=\frac{7+3\sqrt{5}}{2}\quad\text{ and }\quad b=-1.$$
Therefore, we have the matrices
\begin{align*}
A&=\begin{pmatrix}\frac{7+3\sqrt{5}}{2}&-11\\0&7-\frac{7+3\sqrt{5}}{2}\end{pmatrix}&
B&=\begin{pmatrix}-1&0\\-1&-1\end{pmatrix}
\end{align*}
Indeed, both of the matrices have a determinate of $1$. Moreover,
$$AB=\begin{pmatrix}-\frac{7+3\sqrt{5}}{2}+11&\square\\\square&-7+\frac{7+3\sqrt{5}}{2}\end{pmatrix},$$
giving us a trace of $4$.


Using sed command in shell script

Question: This is my simple shell script
sample.sh
LOCALCONFIGDIR="Install"
CONFLOC="$LOCALCONFIGDIR/server.conf"
echo "Enter Web Url:"
read  weburl
echo "sed 's/^\(ServerName\)$/\1 "$weburl"/' "$CONFLOC
sed "'s/^\(ServerName\)$/\1 "$weburl"/' "$CONFLOC

When I run this code, I get the result in echo command as following.
sed 's/^\(ServerName\)$/\1 www.weburl.com/' Install/server.conf

But when executing sed command in the next line, It says the below error.
sed: -e expression #1, char 1: unknown command: `''

I tried the command produced in echo statement from Terminal screen, It is working. But Line number 5, doesn't working from shell script
Answer: You need to use one set of quotes, not two, and since you want the $weburl variable expanded, you need to use double quotes:
sed "s/^\(ServerName\)$/\1 $weburl/" "$CONFLOC"

That'll be OK as long as $weburl doesn't contain any slashes.  If it does, you need to use a different character than /, such as %, to separate the parts of the substitute command:
sed "s%^\(ServerName\)$%\1 $weburl%" "$CONFLOC"

Comment: I just removed a stray `$` in the second `sed`; if you'd used that, it would have stopped the match working.  If that isn't the problem, then maybe your configuration file has spaces before or after `ServerName` on the configuration line, or maybe the file doesn't have a line containing just `ServerName`.
Comment: Perhaps sed commands are best served by using single quotes and exposing the double quoted shell variables i.e. `sed 's/.../'"${var}"'/' file`. The reason being that meta-characters unwittingly used in the sed command(s) my be interpolated by the shell.
Comment: It works. sed "s%$^\(ServerName\)$%\1 www.weburl.com%" Install/server.conf . But It doesn't add the text www.weburl.com after the ServerName.
Comment: @potong: What you wrote is what I'd usually do, but it isn't crucial this time.

Using sed command in shell script


jquery Datepicker code

Question: I'm wondering if anyone can help me troubleshoot my jquery datepicker code.
I changed themes in shopify and now this datepicker doesn't come up with the calendar view. It just has a text box for text (not even dates). Thank you!
{{ 'http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css' | stylesheet_tag }}
{{ '//ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js' | script_tag }}

    Delivery Date of {{ item.title }} (Please allow at least 2 days for delivery):
    <input id="date{{i}}" type="text" name="attributes[date{{i}}]" value="{{ cart.attributes.date }}" onkeyup="d_date.value=this.value" class="required" data-error="Please tell us which date you want your delivery for" />
    <input type="hidden" id="d_date" name="properties[date]" />

Comment: Your code works fine for me. It displays a datepicker when you click inside the text field. If you don't want the text field at all, you could [display the datepicker inline](http://jqueryui.com/datepicker/#inline). Perhaps you could provide a screenshot or a link to a demo site showing the issue you're having.
Answer: Thank you for your help Steph.
I finally discovered through a lot of questions that the theme I was using in Shopify does not support the date picker in the product pages. I have no idea why that is. It does support a date picker snippet. Only, not on each product page.

jquery Datepicker code


How do I create a View filter by a parent taxonomy term?

Question: I've got a taxonomy that is set up as such, which I am using with Taxonomy Term Templates:
Manufacturer>>Model>>Colour
Eg:
Honda>>Accord>>Red
I'd like to create a View that displays all siblings of a Taxonomy, eg if I am on the Accord page I'd like the view to return other Honda models (eg: Civic, CR-X, HR-V, Odyssey).
I've tried using the %term:parent as a contextual filter, but have had no luck - no results display.
Would anyone know how I might go about this?
Answer: Please follow such steps for getting your result (Child Items)
1)Add Taxonomy term: Term ID in CONTEXTUAL FILTERS.
2)Add Taxonomy term: Parent term in RELATIONSHIPS. (leave Require this relationship unchecked.)
3)Add Taxonomy term: Parent term in filter section. select great than 0.
4)Do not forget to filter your taxnonmy term in mycase Taxonomy vocabulary: Machine name (= airports).
5)Add Taxonomy term: Rendered Taxonomy term to your fields , select relationship to parent , check the Exclude from display.
6)In setting, under FORMAT section. In grouping field 1, select (Parent) Taxonomy term: Rendered Taxonomy term.
You should good to go. you can use view tpl to add more class base on the group.
 I have enclose my screenshot for references.
Comment: Any idea how to exclude the current term? ('Accord' in my example above)
Comment: Yea Melting , According your example if you want to show other related honda model and your URL is car/%/model then please follow such steps :
1. In contextual filter choose "(term) Taxonomy term: Term ID"
Comment: Yea Melting , According your example if you want to show other related honda model and your URL is car/%/model then please follow such steps :
1. In contextual filter choose "(term) Taxonomy term: Term ID"
2. Provide default value and set "Raw value from URL".
3. select path component is "2" or you can set aacording URL % sign
4. In validation critria select "specific validation critria"
5. Check yout taxonomy there


Proving equations involving the powers of a complex cube root of unity ω

Question: The question in this homework problem is to show
$ω^4 + ω^5 = -ω^6$
given that $ω$ is a complex cube root of unity.
I am also required to show that $(1 - ω)^2 = -3ω$, but if I am assisted with the approach to take with this kind of problem I think I could manage on my own.
I know the complex cube roots of unity to be $\frac{-1}{2} ± \frac{\sqrt{3}}{2}i$, but I feel as if picking one and plugging it in instead of $ω$ would be an unnecessarily complicated way of proving the equations given.
I also know that if $ω$ is a complex cube root of unity, $ω^2$ is the other, i.e. the complex conjugate of $w$, and that the sum of the three cube roots of unity is 0.
Comment: Any cube root of unity $w$ satisfies $w^3 = 1$ so automatically you know that $w^4 + w^5 + w^6 = w + w^2 + 1$. Now if $w\neq 1$ then by the factorisation $x^3 - 1 = (x-1)(x^2 + x + 1)$ we know that $1+w+w^2 = 0$ and we are done!
Answer: As $\displaystyle x^3=1\implies (x-1)(x^2+x+1)=0$ and $\displaystyle \omega\ne1 $
$\displaystyle \omega,\omega^2$ are the roots of $x^2+x+1=0$
Applying Vieta's formula to find $\displaystyle \omega+\omega^2$ and $\omega\cdot \omega^2=1$
Now, $\displaystyle \omega^4+\omega^5=\omega\cdot1+\omega^2\cdot1=\cdots$
Answer: From Vieta's formula, $\omega_1+\omega_2+1 = 0$, where $\omega_1,\omega_2$ are two distinct complex roots of unity.
You already knew $\omega_1 = \omega_2^2$ and $\omega_2=\omega_1^2$. Either way you get
$\omega+\omega^2+1 = 0$, and multiply both sides by $\omega^4$ to get the result.


NSTableView: programmatically adding one row results in selection of many rows with the same values?

Question: now, i've been reading just about everything about NSArrayController.
i have properly setup my xib, the NSArrayController, NSTableView and the bindings -- everything's working except for one odd behavior of my NSTableView.
First some code to picture the scene:
@implementation MyAppDelegate

@synthesize arrayController, dataArray;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    self.dataArray = [NSMutableArray array];
}

- (IBAction)myControllerAddAction:(id)sender {
    NSString *val = [[NSDate date] description];
    NSMutableDictionary *item = [NSMutableDictionary dictionaryWithObjectsAndKeys:val, @"date", nil];
    [serversController addObject:item];
}

- (IBAction)myArrayAddAction:(id)sender {
    NSString *val = [[NSDate date] description];
    NSMutableDictionary *item = [NSMutableDictionary dictionaryWithObjectsAndKeys:val, @"date", nil];
    [[self mutableArrayValueForKey:@"dataArray"] addObject:item];
}

@end

using -mutableArrayValueForKey:@"myNSArrayControllerStore" and adding objects via the returned NSMutableArray proxy's -addObject:myDictionary the array controller instructs the table view to draw the new content but it'll select all rows with the same values in their NSCells:

using the array controller's -addObject:myDictionary it'll draw the new row and select the newly added one:

(on both screens i've been continuously clicking multiple times per second)
Why is that?
Do i need to handle proper row selection on my own when using [NSMutableArray -addObject:]?
Or is this a bug?

Mac OS 10.7.3
  Xcode 4.3
  Base SDK 10.7
  Deployment target 10.6
Comment: I don't understand these screenshots. In the first screenshot, it's selecting all the :17 lines, the ones which match the first item added. In the second, there's only a single item with the given value. I take it in the first case, each click expands the original selection until the time changes to the next second, and in the second case, the selection moves after each click?
Comment: @noa yes, that's correct... any clue?
Answer: Using an array controller's -addObject: method is the right way to handle insertion. It ensures the controller sends the right messages to objects which are bound to it.
It sounds like the array controller approach is working correctly.
It would be useful to be able to bind array controllers to mutable arrays, and for them correctly to monitor insertions to the bound arrays, but I don't think they are designed to work in this manner.
Comment: yes. i know. but according to [this](http://stackoverflow.com/questions/5236060/how-does-updating-nstableview-from-this-mutable-array-work-in-cocoa) and [other resources](http://forums.macrumors.com/showthread.php?t=914414) i've read the other approach should be working as well since it is kvo-compliant.  i'd really like to know why there's this visual oddness...
Comment: Thanks for posting those links – helps me understand what you're attempting. Your approach *is* working, in that the items are showing up. It's `selectsInsertedObjects` which isn't behaving correctly. What results do you get when the items you insert are unique (e.g. more than one second apart)?


Change Text Color From NSAttributedString When UITableViewCell is Selected/Highlighted

Question: I want to be able to change the text in my UITableView cells when they are tapped on (selected/highlighted). The content from each cell is derived from an NSAttributedString. Here is that code:
-(NSAttributedString*)formattedSubject:(int)state {
    if(formattedSubject!=nil) return formattedSubject;
    NSDictionary *boldStyle = [[NSDictionary alloc] init];
    if(state==1) {
        boldStyle = @{NSFontAttributeName:[UIFont fontWithName:@"Helvetica-Bold" size:16.0],NSForegroundColorAttributeName:[UIColor colorWithRed:0.067 green:0.129 blue:0.216 alpha:1.0]};
    }
    else {
        boldStyle = @{NSFontAttributeName:[UIFont fontWithName:@"Helvetica-Bold" size:16.0],NSForegroundColorAttributeName:[UIColor whiteColor]};
    }
    NSDictionary* normalStyle = @{NSFontAttributeName: [UIFont fontWithName:@"Helvetica" size:14.0]};
    NSMutableAttributedString* articleAbstract = [[NSMutableAttributedString alloc] initWithString:subject];
    [articleAbstract setAttributes:boldStyle range:NSMakeRange(0, subject.length)];
    [articleAbstract appendAttributedString:[[NSAttributedString alloc] initWithString:@"\n"]];
    int startIndex = [articleAbstract length];
    NSTimeInterval _interval=[datestamp doubleValue];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:_interval];
    NSDateFormatter *_formatter=[[NSDateFormatter alloc]init];
    [_formatter setDateFormat:@"MM/dd/yy"];
    NSString* description = [NSString stringWithFormat:@"By %@ on %@",author,[_formatter stringFromDate:date]];
    [articleAbstract appendAttributedString:[[NSAttributedString alloc] initWithString: description]];
    [articleAbstract setAttributes:normalStyle range:NSMakeRange(startIndex, articleAbstract.length - startIndex)];
    formattedSubject = articleAbstract;
    return formattedSubject;
}

As you can see, I would like the boldStyle text to be a certain color (given by [UIColor colorWithRed:0.067 green:0.129 blue:0.216 alpha:1.0]) when the state is "1", and white otherwise. I've currently tried the following modifications in cellForRowAtIndexPath, as well as didSelectRowAtIndexPath:
cellForRowAtIndexPath:
NSIndexPath *path = [tableView indexPathForSelectedRow];
if(path) {
    cell.textLabel.attributedText = [news formattedSubject:1];
}
else {
    cell.textLabel.attributedText = [news formattedSubject:0];
}

What I am doing here is checking if a cell is selected, and if so then I changed that cell's "attributedText" to the "0" format. However, this didn't work, and I suspected it was because the modification had to be made when the cell was actually selected. So I tried the following in didSelectRowAtIndexPath:
didSelectRowAtIndexPath:
News *news = newsArray[indexPath.row];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.textLabel.attributedText = [news formattedSubject:0];

However, it seems like the change is never made. I put an NSLog in the "else" part of the boldStyle if/else statement, and it was never written to the console.
Neither of my attempts at a solution have worked, and I've run out of ideas. How can I get the NSAttributedString to change when a cell is highlighted?
Update: It's also interesting that normalStyle text, which is by default black, does turn white when the cell is highlighted/selected when I add cell.textLabel.highlightedTextColor = [UIColor whiteColor]; in cellForRowAtIndexPath, but boldStyle text does not.
Answer: I have problem the same, and..
cell.textLabel.enable = NO;
It just resolved
Answer: In your cellForRowAtIndexPath method you are checking if a selectedIndexPath in this tableView exists.
NSIndexPath *path = [tableView indexPathForSelectedRow];
if(path) {

I think you want to compare your indexPath and your selectedIndexPath. You should use isEqual: for that.
NSIndexPath *selectedIndexPath = [tableView indexPathForSelectedRow];
if([selectedIndexPath isEqual:indexPath]) {

Comment: I tried `News *news = newsArray[indexPath.row];` with `[path isEqual:news]` in the if statement, this made the `boldStyle` text white by default.
Comment: Your **cellForRowAtIndexPath** has a NSIndexPath parameter called indexPath. In this method you want to check if the current **cellForRowAtIndexPath:** is selected. You get the NSIndexPath of the tableView's **indexPathForSelectedRow**. Then you compare the two NSIndexPaths (with isEqual:).
`[path isEqual:news]` does not work because you are comparing a _NSIndexPath_ with _News_
Comment: Thanks, but I'm still getting the same result. The text is just white by default.


What I do wrong? Django objects filter

Question: I try show post only from 30 days. What I do worng?
@login_required
def dashboard(request):
    days = 30
    posts = Post.objects.filter(Post.publish < timezone.now() - timedelta(days=days))
    #posts = Post.objects.all()
    return render(request, 'account/dashboard.html', {'section': 'dashboard', 'posts': posts})

error
TypeError at /account/
unorderable types: DeferredAttribute() < datetime.datetime()

Comment: You could have solved the problem by yourself reading the documentation...
Answer: Intead of < sign inside filter method you should use __lt lookup attached to field name:
posts = Post.objects.filter(publish__lt=timezone.now() - timedelta(days=days))

Comment: @JestemPokrowcem Double underscore, not single. That's how you access these methods.
Comment: FieldError at /account/
Cannot resolve keyword 'publish_lt' into field. Choices are: author, author_id, body, id, location, publish, title

What I do wrong? Django objects filter


How to make jquery mobile page responsive?

Question: I have the following code snippet for a login home page. I want it to be responsive. how do I make it responsive using jQuery mobile?
Does jqm provide any default css for it?
    <!DOCTYPE html>

<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css">

<link rel="stylesheet" href="./css/custom.css">

                <form id="HLogin" method="POST">

                        Username:*
                        <input class="required" id="Lusername" name="uid_r" type="text" value="">

                        Password:*
                        <input id="Lpassword" name="pwd_r" type="password" value="">

                <button data-theme="b" type="submit">Login</button>
                </form>

custom.css:

    .ui-block-a {
    width:70% !important;
}
.ui-block-b {
    width:30% !important;
}

Comment: Aren't they responsive ? Could you please elaborate ? Thanks!
Comment: @Smitha: Jquery mobile is already built in responsive design. see this link:1) http://www.slideshare.net/rockncoder/responsive-design-24339494 (2)http://www.codeproject.com/Articles/652004/Responsive-Web-Design-with-jQuery-Mobile
Comment: I tried to change the screen resolution for the above page and it doesn't fit in. The login item overlaps on 70% block a. So just wanted to chcek what's going wrong.
Comment: Looks like you missed `` tag in head.
Answer: Here you can add your css according screen and add min-width, which you want.
 @media screen and (min-width: 320px) {
   .ui-block-a {
      width:0% !important;
   }
   .ui-block-b {
      width:100% !important;
  }

}

@media screen and (min-width: 620px) {
   .ui-block-a {
     width:70% !important;
   }
   .ui-block-b {
      width:30% !important;
   }

}


Elasticsearch - exclude filter from aggregations

Question: I query the following:
{
  "query": {
    "bool": {
      "filter": {
        "terms": {
          "agent_id": [
            "58becc297513311ad81577eb"
          ]
        }
      }
    }
  },
  "aggs": {
    "agent_id": {
      "terms": {
        "field": "agent_id"
      }
    }
  }
}

I would like the aggregation to be excluded from the filter. In solr there is an option to tag a filter and use this tag to exclude this filter from the fact query.
How can I do the same in Elasticsearch.
Answer: You can use post_filter for elasticsearch. Post filter excludes the scope of the filters from the aggregations and is perfect to build an eCommerce search for drilled down aggregations count on filters
you can build a query like the following
{
    "aggs": {
        "agent_id": {
            "terms": {
                "field": "agent_id",
                "size": 10
            }
        }
    },
    "post_filter": {
        "bool": {
            "terms": {
                "agent_id": [
                    "58becc297513311ad81577eb"
                ]
            }
        }
    }
}

Thanks
Comment: But what if I want to apply other aggregations to the bool query specified in the post_filter? It should not be possible then, right?
Answer: One way to approach this problem is to use post_filter as described here.
It might be performance concern, so if it doesn't fit your SLA there is alternative approach using global bucket and described here.


Practicing the ability to play piano while looking at the score: start with already memorized pieces or new ones?

Question: I've learned some pieces by myself. When I first learn a new piece, I look at each bar carefully, then I can just remember the notes after a few repetitions. Once I can play through it, I just repeat by memory, rarely looking at the score again. So far my memory has served me well.
I noticed some comments in another recent thread that tells the op that playing the piano while looking at the keys is the wrong way to learn piano.
I'm talking more about being able to look at the score while playing, versus simply playing without looking at the keys (e.g. keeping your eyes closed). In other words, doing two things at the same time
So question: Should I begin to try this on the pieces I've already memorized, or only with my next brand new piece?
Comment: I found that my reading ability was helped more by following "difficult" music-scores with LP / cassette (no guessing my age!) than "official music practice"
Answer: Both are valuable, and they reinforce each other.
Pieces already memorized
Since your hands and ears already know the feel and sound of the music, it makes it easier to associate the experience with what you're taking in visually. This also allows for the possibility of playing music that might otherwise be too difficult to read fluently.
"Reading" music you've already memorized helps develop the visual part of reading.
Brand new pieces
With brand new pieces it's important to start very, very simple. In general, learning visual cues is faster than associating those cues with physical or auditory experience. That is, recognizing by sight that two notes are a third apart is easier than developing the feeling of a third in one's hand or the sound in one's ear. This isn't true of everyone, and might not be true of you, but it's the most common situation.
Playing the simplest pieces lets you develop the association between what you see, what it sounds like, and how to move to play it without undo complexity.  If one also have to contend with complex rhythms, intricate technique, or other musical factors, there's not enough room in one's mind to take everything in and play it at sight.
"Easy music", for me, means easy enough to play the entire at or near performance level after, at most, three readings. Reading 1 gives the basic idea of the music; Reading 2 allows for integrating the things noticed but not executed during Reading 1, and by Reading 3, "real" music is being produced (within the musical limits imposed by the simplicity of the music).
Brand new pieces develop the kinetic/tactile/auditory part of reading music.
Comment: @GrandAdagio Part of my definition for "easy music" would include being easy enough to use accurate fingering at sight. What I call "reading 1", "reading 2", and "reading 3" above, when dealing with a less easy piece, become "phase 1", "phase 2", and "phase 3", each potentially involving multiple readings of the piece. Fingering would be worked out as part of "phase 2" as part of playing the piece rather than a separate operation.
Comment: If I do sight reading for a brand new piece, the fingering I will use would be different from what I would use if I had gone through the piece and marked the preferred fingering, since by sight reading I can't tell in advance the next few notes in order to choose the best fingering. And if I sight read more than once, I'll likely have a different set of fingering each time. So it seems beside the sight reading to train the eyes and finger correspondence, one still needs to go through the whole piece marking a preferred fingering for lasting memory?
Comment: Thanks, appreciate your quick reply. May try it on some Clementi sontatina pieces which I just started to learn.
Answer: The real ability you need for that is the ability or muscle memory to know exactly how you'd need to move to get from one thing to the other. For this doing new pieces is implicitely beneficial as these will force you to look at the score and might have transitions you never had before.
But what I'd suggest for practice is to start practicing the two hands separately. Try to play while doing other things and stuff, until you do not concentrate on where the keys are anymore. Then you can start practicing with both hands.


How I can secure some Git Repositories in AIX?

Question: I want to secure some git repositories and using only users and groups is not sufficient.
I'm thinking about using ACLs to control the access.
The access to the repositories is local, the users have shell access.
Answer: You should check out AIX acls.
Answer: I was going to suggest looking at the options provided by git init --shared=, but you preempted that by saying "using only users and groups is not sufficient."  So I think your options are:

ACLs, as suggested by everyone.
removing local access, and using gitosis to control access via SSH keys.
Answer: Please be more specific. How are the users getting to the repositories as it is? Why are users and groups insufficient?
Comment: there are more users in the group than users needing the repository access and I don't have control of how the groups are created or asigned. and the users access the repositories in the same machine
Answer: Reflecting the comment on the previous, ACLs might indeed be the way to go. It's fairly easy either to grant users access individually, or to give the group access and block certain users. The tutorial here may be useful.


How to install Spring Roo add-ons while offline

Question: At work, our dev environment is an internal network with no connectivity to the internet.
I'm currently trying to use Spring Roo's database reverse engineer function but can't seem to get the add-on org.springframework.roo.wrapping.mysql-connector-java to install correctly offline. I have tried the following:

Following this link jtds driver addon problem

I used the roobot.xml to find the url for the wrapping.mysql-connector-java and downloaded the jar.
According to Roo docs Roo Docs Packaging & Distribution I used the following command to load the osgi jar.
roo> osgi start --url file:///<path-to-addon-project/target/<addon-bundle-name>.<version>.jar
But that resulted in the following errors:
org.osgi.framework.BundleException: Unresolved constraint in bundle org.springframework.roo.wrapping.mysql-connector-java[75]: Unable to resolve 75.0: missing requirement [75.0] package; (package=org.slf4j)

We have an internal repo with the slf4j jars but I can't figure out how to configure Roo to point to it.
I copied the ROO_HOME of an installation I did on a home computer with the requested mysql add-on but when I tried running it in my work environment I get multiple:
Auto-deploy install: org.osgi.framework.BundleException: Bundle symbolic name and version are not unique:...

Any help would be appreciated, thanks
Answer: I would recommend creating a maven repository manager on your dev network and seeding it with all of your dependencies. I was unable to use Spring/Roo offline without it as I kept running into the type of trouble that you are. I used Sonatype Nexus OSS. It was a pain to seed the repository, but it made Roo usable offline. Hope that helps.


reverting push'd git commit

Question: I've got a repo with two branches-- master and dev. I was working on the master branch and pulled, and got a message that the repo was up to date. I committed my changes, and pushed to the remote repo (on github). I got a message saying that some changes were rejected.
I then did a git pull origin dev, which apparently was the wrong thing to do-- since it merged the dev branch with my master, and like an idiot I didn't notice this until I'd already pushed again. So the last commit shows Merge branch 'dev' of github.com:myuser/myrepo.
I can get back to the last known good status on my local repo by doing a git reset --hard [sha], with [sha] being the commit before the merge (though I'm not sure how to then make that change to the origin)-- or from what I've read I can also do a git revert -m and then commit/push that change.
Can anyone walk me through the "right way" to undo my merge, and restore both branches back to where they were prior to the merge?
Thanks-- if it matters this is a shared repo with only two developers, so it's not under heavy changes.
Edit to add: please talk to me as if I were a child. I have to admit this Git stuff still confuses me, so I'm far from a power user! Thanks
Answer: The git reset --hard [sha] will correct the branch on your local repository. To force this push to work, you can do a git push origin +master:master. The + sign will force the non-linear push to work.
If the other developers have already pulled you wrong commit, they will have to do a git remote update, then a git reset --hard origin/master (provided that they are on their master branch, and have not made any other commits.
Please use these commands with some caution :-). Good luck.
Comment: @Noufal: You don't really have to back up the whole repo - just create a branch at the old position of master.
Comment: Risky but if there are just two developers, I think it's okay. Might make sense to backup atleast one copy of your repo before doing this just in case you mess up.
Comment: thanks felipefg-- looks like that worked perfectly! I appreciate the clear answer.
Comment: Hello,I'm having the same problem. I want to cancel a merge that I pushed to the origin.

I already did `git reset --hard [sha]` but now I can't push to the origin, event with `-f` or `+recette:recette`.

Git is telling me :
`remote: error: denying non-fast-forward refs/heads/recette (you should pull first)
To ssh://my-git-repo
 ! [remote rejected] recette -> recette (non-fast-forward)
error: failed to push some refs to 'ssh://my-git-repo'`
Answer: FelipeFG's answer works fine in a two-developer context where you can easily coordinate redoing the other guy's local repository, but you're actually better off using git revert -m<parent id of mainline branch, 1 in this case> <commit ref>. Then, when you're finished fixing it, just git revert <revert commit>, and git merge dev (it's important to revert your revert for this case, because otherwise git merge dev will not consider your old merge an ancestor, and this will lead to conflicts that have to be resolved).
The history will be ugly, but it will also support fast-forwarding, and you won't have to worry about some poor sap untangling a mess of local conflicts thanks to your history revision.
See http://opensource.apple.com/source/Git/Git-26/src/git-htmldocs/howto/revert-a-faulty-merge.txt for details.

reverting push'd git commit


ElasticSearch how to do a sub aggregation in a sum aggregation

Question: Hello I have an index in ElasticSearch with:
Plant, Department, Date, Value
I am trying to do a query in elasticsearch
1) Group by Plant and Date in specific departments and sum Value:
es = Elasticsearch('elasticsearch:9200')
body = Dict({"query": {
                "bool": {
                    "must_not": {
                        "match": {
                            "Department": "Indirect*"}}}},
             "aggs": {
                "group_code": {
                    "terms": {
                        "field": "Plant.keyword", "size":10000},
                     "aggs": {
                        "group_date": {
                            "terms": {
                                "field": "Date"},
                             "aggs": {
                                "group_value": {
                                    "sum":{
                                       "field": "Value"}}}}}}}})

2) Group by Plant and Range of Dates, and get avg and median:
es = Elasticsearch('elasticsearch:9200')
body = Dict(
    {"query": {
            "bool": {
                "must_not": {
                    "match": {
                        "Department_Substrate": "Indirect*"}}}},
     "aggs": {
         "group_code": {
             "terms": {
                 "field": "Plant.keyword",
                 "size": 10000},
             "aggs": {
                 "group_date": {
                     "range": {
                         "field": "Date",
                         "ranges": datelist},
                     "aggs": {
                          "Median": {
                              "percentiles": {
                                  "field": "Value",
                                  "percents": [25]}},
                          "Mean": {
                               "avg": {
                                  "field":
                                  "Value}}}}}}}})

it works too but in this case i didn't do the grouping by plant and date before, so mixing both i have something like:
body = Dict({"query": {
                "bool": {
                    "must_not": {
                        "match": {
                            "Department_Substrate": "Indirect*"}}}},
             "aggs": {
                "group_code": {
                    "terms": {
                        "field": "Plant.keyword", "size":10000},
                     "aggs": {
                        "group_date": {
                            "terms": {
                                "field": "Date"},
                             "aggs": {
                                "group_value": {
                                    "sum":{
                                       "field": "Value"},
                                    "aggs": {
                                        "group_date": {
                                            "range": {
                                                "field": "Date",
                                                "ranges": datelist},
                                            "aggs": {
                                                 "Median": {
                                                     "percentiles": {
                                                         "field": "Value",
                                                         "percents": [25]}},
                                                 "Mean": {
                                                      "avg": {
                                                         "field":
                                                         "Value"}}}}}}}}}}}})
res = es.search(index=self.index, doc_type='test', body=body)

I have this:
TransportError: TransportError(500, 'aggregation_initialization_exception', 'Aggregator [group_value] of type [sum] cannot accept sub-aggregations')

So it exists a way to do this?
if it could help my code python before was:
data = test[~test.Department.str.startswith('Indirect')]
group1 = data.groupby(['Plant', 'Date'])['Value'].sum()
group2 = pd.DataFrame(group1.reset_index()).groupby(['Plant', pd.Grouper(key='Date', freq='W')])['Value'].median()

Answer: The error is clear:"Aggregator [group_value] of type [sum] cannot accept sub-aggregations"
When you do 'sum' aggregation you can't split the result anymore.
So you'd better change the position of sum aggs.
i.e.:
{
"query": {
    "bool": {
        "must_not": {
            "match": {
                "Department_Substrate": "Indirect*"
            }
        }
    }
},
"aggs": {
    "group_code": {
        "terms": {
            "field": "Plant.keyword",
            "size": 10000
        },
        "aggs": {
            "group_date": {
                "terms": {
                    "field": "Date"
                },
                "aggs": {
                    "group_date": {
                        "range": {
                            "field": "Date",
                            "ranges": "sdf"
                        },
                        "aggs": {
                            "Median": {
                                "percentiles": {
                                    "field": "Value",
                                    "percents": [
                                        25
                                    ]
                                }
                            },
                            "aggs": {
                                "group_value": {
                                    "sum": {
                                        "field": "Value"
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

Comment: I know, i will change my question to, is there a way to do an subaggregation in a sum aggregation
Comment: AFAIK, you can't do that.:)


Spring JPA + CRUD - custom query doesn't allow _ characters?

Question: I'm having troubles in creating a custom query within spring, because my Entity contains an "_" character in it's parameter's name: "game_date".
My table has a column named "game_date" as well.
I have created following method:
List<Games> findByGame_dateAndOpponent(@Param("game_date") Date game_date, @Param("opponent") String opponent);
but when I start my app, it's crashing with exception of kind: "org.springframework.data.mapping.PropertyReferenceException: No property gamedate found for type Games!". After changing a parameter name to the "gameDate" both in Entity and Query method, it stopped complaining, and is actually returning expected entries. But at the same time, it doesn't return values from the column "game_date", in the search queries, which is a simple regular column of a Date type. I have no idea what's going on with all this thing.
DB I'm using is MySql.
Here comes the code itself:
Entity:
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
@Table(name = "games")
public class Games {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id_game")
    private int id;

    @Column(name = "game_date", columnDefinition = "DATE")
    @Temporal(TemporalType.DATE)
    private Date gameDate;

    public Date getGame_date() {
        return gameDate;
    }

    public void setGame_date(Date _game_date) {
        this.gameDate = _game_date;
    }
}

And a repository:
import java.sql.Date;
import java.util.List;

import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource
public interface GamesRepository extends CrudRepository< Games , Integer > {

    List< Games > findById( @Param( "id" ) int id );
    List< Games > findAll( );
    List<Games> findByGameDateAndOpponent(@Param("game_date") Date game_date, @Param("opponent") String opponent);

}

Answer: The underscore is a reserved keyword in Spring Data JPA. It should be enough to remove it from your property and from its getters and setters and Hibernate will do the rest:
@Entity
@Table(name = "games")
public class Games {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id_game")
    private int id;

    //Getter and setters for id

    @Column(name = "game_date")
    private Date gameDate;

    public Date getGameDate() {
        return gameDate;
    }

    public void setGameDate(Date gameDate) {
        this.gameDate = gameDate;
    }
}

Also, in general, try to use java naming convention for variable and field names, which is mixed case with lowercase first.
See also:

Spring Data JPA repository methods don't recognize property names with underscores
Comment: I haven't noticed I forgot to change getter and setter.. Thank you!
Comment: Remember you can mark the question as answered or upvote it if useful ;-)


The command eval $(minikube docker-env) is not working because of error that says "Cannot connect to docker daemon"

Question: I have started minikube using the following command
minikube start --insecure-registry k8s.gcr.io --insecure-registry registry-1.docker.io --insecure-registry gcr.io --insecure-registry registry.gitlab.com
After it starts I check the status using minikube status and the output is the following
host: Running
kubelet: Running
apiserver: Running
kubectl: Correctly Configured: pointing to minikube-vm at 192.168.99.107

Afterwards I run the command eval $(minikube docker-env) so that it can use the docker daemon that minikube is using.
That command runs as is expected. When I check the DOCKER_HOST I get the following value tcp://192.168.99.107:2376
The problem starts when I run a docker command.
For example, when I run docker run hello-world, the command will hang for a while and then I get the following output
docker: error during connect: Post https://192.168.99.107:2376/v1.39/containers/create: Service Unavailable.

One thing you might notice is that the DOCKER_HOST uses TCP will docker run will use HTTPS. I don't know but maybe it might help in getting this issue fixed.
Answer: HTTPS can run over any reliable stream transport protocol. Normally that's TCP.
1. Check if your image is built.
To run docker images in Kubernetes you can simply use
$ kubectl run hello-world --image=... --port=... --image-pull-policy=...
But you have to set on Docker daemon as well.  More information you can find here: docker-daemon
2. Check 2376 port if it is not already in use.
3. Try to run your command as root:
Run it as sudo docker ... instead of docker ....
The user that you are running as may not have permissions to talk to /var/run/docker.sock on that system.
4. Which version of minikube you use ? In minikube v0.10.0 the --insecure-registry flag is ignored if the machine already existed.). First check if --insecure-registry= is correctly copied into /var/lib/boot2docker/profile in the new VM. You must first minikube delete if you want new flags to be respected.
I hope it helps.


How to find files differing only by extension

Question: Suppose I have multiple random .txt files, and in the same directory I have nearly-identically-named files like filename.sql and filename.txt. How would I find those .sql and their counterpart .txt files without selecting any other .txt files? (The intent here is to move them to a separate folder. There is a guaranteed 1:1 relationship between the relevant .sql and .txt files, meaning that I'm not worried about moving one of the random .txt files mentioned initially.)
Answer: Very simple:
$ mv `ls *.sql|sed s/.sql$/.txt/g` dir

To see and understand how it works, how the shell expands the line before executing mv, start the line with echo:
$ ls
a.sql b.sql a.txt b.txt c.txt
$ echo mv `ls *.sql|sed s/.sql/.txt/g` dir
mv a.txt b.txt dir

Something more "robust" if the file names have spaces (generally not a good idea in Unix, but happens) or you have hundreds of files in the directory:
$ for f in *.sql; do mv "$(echo $f|sed s/.sql$/txt/)" dir; done

To move the .sql files along with the corresponding .txt files:
$ for f in *.sql; do mv "$f" "$(echo $f|sed s/.sql$/txt/)" dir; done

Comment: Select all .sql files in the current directory, replace `.sql` in their names to `.txt` and move files having resulting names to `dir`
Comment: @verbsintransit `sed` does not modify the filenames at all, it only modifies the output provided by `ls`.  So when `ls` would print `foo.sql`, sed will cause it to instead print `foo.txt`, so that `mv` can move the correct file.
Comment: To be slightly more robust (i.e. only substitute `.sql` for `.txt` at the end of the filename) use `s/.sql$/.txt/`.  The `g` at the end of the substitution is unnecessary because each filename from `ls` will be on its own line anyway.
Comment: No, you didn't understand. To see what's happening prepend `echo` to the line and see how shell expands this.
Comment: Well. Don't I feel clever. I mean it would be pedagogically nice to do it in one command, but it's not necessary in my current situation.
Comment: Thank you. Can you or someone walk me through this? (It's not "simple" to me :) I see that all .sql files are selected and then piped to sed, which somehow substitutes something and then I don't understand.
Comment: So once moved to 'dir', all files will have a '.txt' extension...? I think I wasn't clear in my question then. I wish to preserve the extensions.
Comment: robust? will break if the filename contains a space. ;)
Comment: OK, sorry to bring this back to life, but I tried your setup just now. I see that it does move a.txt and b.txt in the destination directory. But I also want the corresponding a.sql and b.sql files. When I tried basically inverting it: `mv 'ls *.txt|sed s/.txt$/.sql/g' dir` it tried to find the nonexistent c.sql. Advice?
Comment: Just move all .sql files separately
Comment: You want to move all .sql files, right? That's simple: `mv *.sql dir`. Or do you need to do both things in one command???...
Comment: Don't worry, happens :)
Answer: piokuc's answer works great, but if you get an argument list too long error (happens if you're moving a lot of files at once), this works as well:
ls *.sql | sed s/.sql/.txt/g | xargs -I% mv % /path/to/new/directory

Explanation:

List all files name ending with .sql extension.
Replace .sql with .txt in the filename list (this doesn't rename the files, just operates on the piped input).
xargs

xargs is a program that runs other programs. We are going to run the mv (move file) command through it.
The -I option tells xargs to run the mv command individually for every single file name being passed by sed.
The % refers to actual object/filename being passed to xargs, so upon each iteration this is going to be one of the substituted file names.
Notice that there are 2 %: one is attached next to -I, which tells xargs to use the ampersand character as a token for a file name. The second occurrence is with mv, where the actual (and by now changed) file name gets substituted for the token.

Esentially, xargs is saying, "For each one of the piped-in file names, run mv NEW_FILE_NAME.txt /path/to/new/directory."
Comment: +1 yeah, I was just thinking about adding a comment like that. Similarly one could do something like `for f in *.sql; do mv `echo $f|sed s/.sql$/txt/` dir; done`
Comment: can't show it properly with the formatting in a comment, will copy to my answer


Is this spectrum-shifting operator well-defined?

Question: Consider a separable Hilbert space (over $\mathbb{C}$), and let $U(t)$ be a one-parameter group of unitary operators so that
$$
 U(t)=e^{iHt}
\tag{1}
$$
for some densely-defined operator $H$ as in Stone's theorem. Let $A$ be any bounded (everywhere-defined) operator on the Hilbert space, and define
$$
 A(t) = U(t)A U(-t).
\tag{2}
$$
For real numbers $\omega$ and $\epsilon$ with $\epsilon>0$, I want to define
$$
 B :=
  \int_{-\infty}^\infty dt\
    \exp(-i\omega t-\epsilon t^2) A(t).
\tag{3}
$$
Question: Is $B$ a well-defined operator on the Hilbert space? If not, is it at least densely defined? If the answer is "it depends," then is there a simple necessary-and-sufficient condition on $A$ and $H$ such that $B$ is at least densely defined for all $\omega$ and all $\epsilon>0$?
For whatever it's worth, here's the reason for the words "spectrum-shifting" in the title of the question: At least naively, equation (3) implies  $HB=B(H+\omega)+O(\epsilon)$. In physics jargon, if $H$ is the energy operator, then applying $B$ to an "eigenstate" of $H$ shifts its energy by $\omega$, up to an arbitrarily small term of order $\epsilon$. That's the motive, but I don't know when (3) is actually well-defined.
Answer: Because $A$ is bounded, then $\|A(t)\| \le \|A\|$ is bounded for all $t$. So the operator $B$ defines a bounded linear operator for $\epsilon > 0$, and
$$
           \|B\| \le \int_{-\infty}^{\infty}dt e^{-\epsilon t^2}\|A\|.
$$
Comment: @ChiralAnomaly Yes. Norm distributes over the integral in this way; and you have uniform bound for $\|A(t)\|$. So the resulting integral is a bounded linear operator.
Comment: I believe that you also need to make sure that the integrand is measurable (in some sense) in order for the integral to be well defined. Here it is, as $t\mapsto U(t)$ is strongly continuous.
Comment: Thank you. To make sure I understand: If $B=\int dt\ f(t) A(t)$ then $\|B\|\leq \int dt\ \|f(t) A(t)\|$? And that's sufficient to ensure that $B$ is well-defined on the whole Hilbert space, given that the integrand is for each $t$?
Comment: @Mogget : That's correct, $A(t)$ is strongly continuous.


Should $X$ be full column rank in normal Gauss Markov model to make $(\mathbf{y'y},\mathbf{X'y})$ be a complete statistic?

Question: Suppose normal Gauss-Markov model $\mathbf{y=Xb+e}$ where $y\sim N(\mathbf{Xb},\sigma^2 \mathbf{I})$, the pdf of y in exponential family:
Set $\theta=(\mathbf{b},\sigma^2)$:
$$ \begin{aligned} f _ { \mathbf { Y } } ( \mathbf { y } \mid \mathbf { \theta } ) & = ( 2 \pi ) ^ { - n / 2 } \left( \sigma ^ { 2 } \right) ^ { - n / 2 } \exp \left\{ - ( \mathbf { y } - \mathbf { X } \mathbf { b } ) ^ { \prime } ( \mathbf { y } - \mathbf { X } \mathbf { b } ) / 2 \sigma ^ { 2 } \right\} \\ & = ( 2 \pi ) ^ { - n / 2 } \left( \sigma ^ { 2 } \right) ^ { - n / 2 } \exp \left\{ - \mathbf { y } ^ { \prime } \mathbf { y } / 2 \sigma ^ { 2 } + \mathbf { y } ^ { \prime } \mathbf { X } \mathbf { b } / \sigma ^ { 2 } - ( \mathbf { X } \mathbf { b } ) ^ { \prime } \mathbf { X } \mathbf { b } / 2 \sigma ^ { 2 } \right\} \\ & = ( 2 \pi ) ^ { - n / 2 } \left( \sigma ^ { 2 } \right) ^ { - n / 2 } \exp \left\{ - ( \mathbf { X } \mathbf { b } ) ^ { \prime } \mathbf { X } \mathbf { b } / 2 \sigma ^ { 2 } \right\} \exp \left\{ - \mathbf { y } ^ { \prime } \mathbf { y } / 2 \sigma ^ { 2 } + \mathbf { b } ^ { \prime } \mathbf { X } ^ { \prime } \mathbf { y } / \sigma ^ { 2 } \right\}
\\&= h(\mathbf{y})c(\theta)\exp\{\sum_{i=1}^2 w_i(\theta)t_2(\mathbf{y})\}
\end{aligned} $$
where $w_1(\theta)=-\frac{1}{2\sigma^2},w_2(\theta)=\frac{\mathbf{b}}{\sigma^2}$ and $t_1(\mathbf{y})=\mathbf{y'y},t_2(\mathbf{y})=\mathbf{X'y}$.
Seems the family is full ranks and apply

In a exponential family, the statistic $$ T=T(\mathbf{X})= \left( \sum _ { j = 1 } ^ { n } t _ { 1 } \left( X _ { j } \right) , \sum _ { j = 1 } ^ { n } t _ { 2 } \left( X _ { j } \right) , \ldots , \sum _ { j = 1 } ^ { n } t _ { k } \left( X _ { j } \right) \right)$$ is complete if the parameter space $$ \left\{ \boldsymbol { \eta } = \left( \eta _ { 1 } , \eta _ { 2 } , \ldots , \eta _ { k } \right) : \eta _ { i } = w _ { i } ( \boldsymbol { \theta } ) ; \boldsymbol { \theta } \in \Theta \right\} $$ contains an open set in $\mathcal{R}^k$. For the most part, this means the dimension $d=k$.

hence $(\mathbf{y'y},\mathbf{X'y})$ will be a complete statistic and hence $\mathbf{\hat{b}}=\mathbf{(X'X)^gX'y}$ will be a UMVUE for $\mathbf{b}$. However if $\mathbf{X}$ isn't full column rank,
$$
E[\mathbf{(X'X)^gX'y}]=\mathbf{(X'X)^gX'Xb}
$$
can't be $\mathbf{b}$.
I think that may because if $\mathbf{X}$ isn't full column rank, then there is some $\mathbf{a}$ such that $\mathbf{Xa=0}$, that suggests $\mathbf{b'a}=0$. Then
$$  \left\{ \boldsymbol { \eta } = \left( \eta _ { 1 } , \eta _ { 2 } , \ldots , \eta _ { k } \right) : \eta _ { i } = w _ { i } ( \boldsymbol { \theta } ) ; \boldsymbol { \theta } \in \Theta \right\}  $$
does not contain an open set in $\mathcal{R} ^{p+1}$($\mathbf{X}$ is $N\times p$ )?Is this sounds reasonable? And I still curious about why $\mathbf{X}$ be not full column rank will result to the family be not full rank.
Answer: Now I have an answer, when $\mathbf{X}$ is not full column rank, the statistic is still complete, but $\mathbf{\hat{b}}$ is a UMVUE for its expectation, not equal to b.


Indentifying $\sin(mx) = 2\cos(x)\sin\left[(m-1)x\right] - \sin\left[(m-2)x\right]$

Question: I encountered in a work of Joseph Fourier's the identity:
$$\sin(mx) = 2\cos(x)\sin\left[(m-1)x\right] - \sin\left[(m-2)x\right]$$
which holds for all real $m$ and $x$.
I had trouble, however, locating this in common lists of trigonometric identities.  Does this identity have a name, and where can I find it listed?  If it is not actually a common identity, how is it derived?
Comment: Most of these types of formulae come from $e^{i y}=\cos(y)+i\sin(y)$.
Comment: https://en.wikipedia.org/wiki/List_of_trigonometric_identities#Chebyshev_method
Answer: We have
$$\sin A+\sin B=2\sin\frac{A+B}{2}\cos\frac{A-B}{2}$$
(sum-to-product identities)
Now set $A=mx,B=(m-2)x$.
Answer: or just observe:
$$
\sin ((m-1)x \pm x) = \sin(m-1)x \cos x \pm \sin x \cos(m-1)x
$$
and add the two equations together


How do i embed only certain parts of my R command into R markdown document using `r `?

Question: I am creating a hypothesis test and confidence interval using this command:
```{r}
t.test(urtak1$fermetraverd ~ urtak1$matssvaedi)
```

And I need to embed the t-value and p-value as well as the confidence interval (seperately) into text for my R markdown document. How do I do this using ' r ' ?
Here is my output:
Welch Two Sample t-test

data:  urtak1$fermetraverd by urtak1$matssvaedi
t = 1.0812, df = 96.784, p-value = 0.2823
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -12.02648  40.80856
sample estimates:
   mean in group Hagar mean in group Kringlan
          348.5697               334.1787

Answer: You can do this using the broom package. I do not have the data you are using your questione, so I set up something quickly with iris.
In a first chunk you do the analysis and create an object that holds the "tidy" version of your t-test output. For example
```{r}
library(dplyr)
library(broom)

example <- iris %>%
  filter(Species != "setosa") %>%
  droplevels()

result <- t.test(example$Sepal.Length ~ example$Species)

tidy_result <- tidy(result)

```

Have a look at tidy_result: the magic of the broom package is that it extracts all the output of your t-test (and many others!) in a tidy dataframe, that you can use elsewhere.
Now you can use this in your text, evaluating r tidy_result$statistic to show your t-statistic and r tidy_result$p.value to show your p-value (the back-ticks are not showing correctly, but should be placed in front of the 'r' expressions in  with the tidy_result objects.
In your Rmarkdown it might look like this:
the t-test resulted in a t-statistic of `r tidy_result$statistic`
with a p-value of `r tidy_result$p.value`

To look at all the parameters you can include, evaluate tidy_result in your console. You will see:
> tidy_result
  estimate estimate1 estimate2 statistic      p.value parameter   conf.low  conf.high                  method alternative
1   -0.652     5.936     6.588 -5.629165 1.866144e-07  94.02549 -0.8819731 -0.4220269 Welch Two Sample t-test   two.sided

So you can choose any of the following:
"estimate"    "estimate1"   "estimate2"
"statistic"   "p.value"     "parameter"
"conf.low"    "conf.high"   "method"      "alternative"

Notice that your to get your confidence interval, you have the low (conf.low) and the high (conf.high) value at your disposal.
Comment: Thanks, this worked. I have not figured out how to embed the confidence interval into Rmarkdown yet, i tried `r tidy_result$conf.int` without any luck.
Comment: There is no value called `conf.int` in the tidy_result data.frame. But you do have access to the low and high boundaries of your confidence interval directly. I've update the question to make it more clear what you have available to work with after using broom.


Why computing $\sin(x)$ is not backward stable?

Question: It is said in Trefethen's Numerical Linear Algebra that computing $\sin(x)$ shall not be expected to be backward stable, because "the function has derivative equal to zero at certain points", for example at $x=\pi/2$. However, I am not satisfied with the arguments therein. In particular, suppose $x=\pi/2-\delta$. When $\delta$ is sufficiently small, we will have $\tilde{f}(x)=1=f(\tilde{x})$ with $\tilde{x}=\pi/2$. Thus $\|\tilde{x}-x\|/\|x\|=\delta/\|x\|\rightarrow0$ as $\delta\rightarrow0$. Then why is computing $\sin(x)$ not backward stable (at $x=\pi/2$)?
I would also like to know if it is a general rule, that if a function $f(x)$ has zero derivative at certain points then computation will not be backward stable.
Thanks for any comment.
Note: Here is the definition of backward stability in Trefethen's book.
We say that an algorithm $\tilde f$ for a problem $f:X\rightarrow Y$ is backward stable if for each $x\in X$, there exists some $\tilde x$ with
$$\frac{\|\tilde x-x\|}{\|x\|}=O(\epsilon_{machine})$$
such that $\tilde f(x)=f(\tilde x)$.
Answer: The issue is not at $x=\frac\pi2$ 'exactly' (where, yes, 1.0 can be correctly evaluated) but rather in the vicinity. Note that the actual $\tilde{x}$ for which $\sin(\tilde{x})=1-\epsilon$ is $\frac\pi2+\sqrt{2\epsilon} + O(\epsilon)$. Now, if we look at values of $x$ around $x=\frac\pi2+\frac{\sqrt{2}}2\sqrt{\epsilon}$ in the midpoint of this range, for instance, then either $\tilde{f}(x)=1$, so $\tilde{x}=\frac\pi2$, and $|x-\frac\pi2|\approx C\sqrt{\epsilon}\not\in O(\epsilon)$, or $\tilde{f}(x)=1-\epsilon$, so $\tilde{x}=\frac\pi2+\sqrt{2}\sqrt{\epsilon}+O(\epsilon)$, and again $|x-\tilde{x}|\approx C\sqrt{\epsilon}\not\in O(\epsilon)$.
And yes, you're exactly right that computation won't be backwards stable for any 'sufficiently nice' function $f(x)$ in the vicinity of zeros of $f'(x)$. This is because of the Taylor expansion: Near one of these zeros $x_0$, we have $f(x_0+\delta)=f(x_0)+\delta f'(x_0)+O(\delta^2) =f(x_0)+O(\delta^2)$ and so the 'area of confusion' for values differing by $\epsilon$ is of size $\Theta(\sqrt{\epsilon})$.
Comment: Now I get the point. Nice answer. I also notice an interesting thing, that near the zeros of $f'(x)$ computation is not backward stable, while near the zeros of $f(x)$ with $x\neq 0$, the problem is ill-conditioned.
Comment: Should be also be worried about getting impossible values? This is not going to be a problem for $\sin x$ because $1.0$ can be represented exactly as a floating-point number. But if we're evaluating $f(x) = \sqrt2 \sin x$ at or near $x = \frac\pi2$, it's possible that we'll get a floating-point representation of $\sqrt2$ and it will "round up". In that case, $\tilde{f}(x)$ will not be $f(\tilde{x})$ for **any** $\tilde{x}$, because $\tilde{f}(x) > \sqrt2$ and $f(\tilde{x}) \le \sqrt2$ for all $\tilde{x}$.
Comment: @MishaLavrov That is another way of failing backwards stability — and the two are closely related; the easiest way to get impossible values, as you've noted, is to multiply an extreme value of $f()$ by a 'non-representable' value, and such extrema of $f()$ will tend to correlate with zeros of $f'()$.
Comment: Er, maybe this is the CS in me, but surely $C\sqrt{\epsilon}$ is bounded above by some constant times $\epsilon$ (i.e., $\in O(\epsilon)$)?
Comment: @D.BenKnoble As $\epsilon\to\infty$, yes, but these $O()$ families are to be taken the other way; and $\sqrt{\epsilon}\not\in O(\epsilon)$ as $\epsilon\to 0$.


Adapt Boost Thread / Process for non supported platform

Question: Background
this  documentation says that it is possible to adapt the library to new (unsupported) operation system. Because the OS (a real time OS) I would like to support is close to Win32, I would expect little code changes. I have no experience with Boost Thread and Boost Interprocess .
Questions

Would you recommend to use Boost's Thread and Boost's Interprocess, if the
plattform is not supported?
What are the benefits and drawbacks?
Which alternatives would you consider?
Comment: Boost development is not for the faint of heart, but you can probably exploit some of the existing test-cases.
Comment: It' RTX form Interval Zero.
Answer: All this depend on your needs. Using a portable library has the obvious advantages. Stabilizing a new platform could take some time.
I would suggest you to create tickets for each one of the features that doesn't work for the specific platform and work closely with the Boost authors.


Variável não exibe resultado correto em C

Question: Tenho o seguinte problema para resolver:
Escreva um programa que faz a leitura de duas matrizes de 10 linhas e 2 colunas. Cada linha da
matriz armazena duas notas de um aluno. A primeira matriz armazena as notas de G1 e a segunda as
notas de G2. Após a leitura das duas matrizes calcule a média final de cada um dos alunos e
armazene em um vetor de 10 posições. Importante a média das notas é aritmética. Escreva o vetor
resultante na tela. Importante: a nota final de G1 é obtida pela média das duas notas da matriz G1. A
nota de G2 é obtida pela média das duas notas da matriz de G2.
Realizei o que foi pedido, no entanto na hora de exibir o resultado da media[i] só é mostrado o valor 0 em todas os índices do vetor.
#include <stdio.h>
#include <string.h>

main()
{
int m1[10][2], m2[10][2];
int soma[10], soma2[10], media[10], result[10], result2[10];
int l, c, i, j;

printf ("\n Notas G1 \n");
for (l=0; l<10; l++)
{
    for (c=0; c<2; c++)
    {
        printf ("\n Aluno [%d], nota [%d]: ", l+1,c+1);
        scanf ("%d", &m1[l][c]);
        soma[l] += m1[l][c]; //soma notas g1
        result[l] = soma[l] / 2;
    }
}

printf ("\n Notas G2 \n");

for (i=0; i<10; i++)
{
    for (j=0; j<2; j++)
    {
        printf ("\n Aluno [%d], nota [%d]: ", i+1,j+1);
        scanf ("%d", &m2[i][j]);
        soma2[i] += m2[i][j]; // soma notas g2
        result2[i] = soma2[i] / 2;
    }
}

for (i=0; i<10; i++)
{
    media[i] = (result[i] + result2[i])/2; //media
}

for (i=0; i<10; i++)
{
    printf ("\n Media dos aluno [%d]: %.2f", i,media[i]);
}
}

Comment: Como está a tipagem das variáveis?
Answer: Os vetores media, result e result 2 deveriam ser do tipo float.
Outra coisa que pode causar problemas: levando em consideração que
soma[l] += m1[l][c];

é a mesma coisa que
soma[l] = soma[l] + m1[l][c]

e não foi atribuído um valor a soma[l], soma[l] pode receber um valor aleatório, então sugiro que você atribua o valor 0 a soma[l] antes de somar as notas:
printf ("\n Notas G1 \n");
for (l=0; l<10; l++)
{
    soma[l] = 0;
    for (c=0; c<2; c++)
    {
        printf ("\n Aluno [%d], nota [%d]: ", l+1,c+1);
        scanf ("%f", &m1[l][c]);
        soma[l] += m1[l][c]; //soma notas g1
        result[l] = soma[l] / 2;
    }
}

Comment: Mas como fazer com que o vetor soma[l] receba 0?
Comment: depois de entrar no loop for (l=0; l<10; l++) e antes de entrar no loop for (c=0; c<2; c++), você coloca, soma[l] = 0, vou editar minha resposta pra você ver.
Comment: Entendi, mas continua não exibindo o resultado :/
Comment: a saída ainda é zero pra todos os itens do vetor?
Comment: mude os tipos das matrizes m1 e m2 e dos vetores soma e soma2 para float também
Comment: Para esse problema, modifique todas as variáveis que vão participar do cálculo para a tipagem float.
Comment: Deveriam mesmo ser do tipo `float`? Notas não são as melhores coisas para se por em ponto flutuante, normalmente seria usado ponto fixo mesmo.


How to union two ordered queries in the same table

Question: I have events table with columns
'title',
'description',
'start_date',
'end_date'.
I want to get ordered list live and future  events, depends on 'start_date' and 'end_date'.
I try
(
    select *
    from `events`
    where `start_date` < NOW() and `end_date` > NOW()
    order by `start_date` desc
)
union all
(
    select *
    from `events`
    where `start_date` > NOW()
    order by `start_date` desc)

but result have not that ordering which I want. I want at first ordered list by start_date live events after that ordered list by start_date future events.
Comment: See http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-query
Answer: I think you do not need union in this one.
Just put a OR condition in your basic query.
Then, to split the result into "this one is live" and "this one is future" you can use a flag
SELECT *, start_date < NOW() AS flag
FROM `events`
WHERE (`start_date` < NOW() and `end_date` > NOW())
   OR `start_date` > NOW()
ORDER BY flag DESC, start_date

Nota : the DESC is here to show you you want live before future event. Otherwise just put ASC.
Comment: Wouldn't we want the `flag` to be sorted in descending order so that live events are first?
Comment: @AcatnamedMidnight, artragis, thanks for yours answers. Both are work.   But I have one more question, how can I get the same result but in this time I want order live events by 'desc', and future events by 'asc'.
Comment: See my updated answer. You can apply the same `CASE` statement in an `ORDER` clause idea to either mine or @artragis answer.
Comment: your `ORDER BY` can look like `ORDER BY flag DESC, start_date ASC`
Answer: Try this:
select * from (
(
    select start_date, end_date, 'Live' as event_type
    from `events`
    where `start_date` < NOW() and `end_date` > NOW()
)
union
(
    select start_date, end_date, 'Future' as event_type
    from `events`
    where `start_date` > NOW() ) ) a
ORDER BY event_type desc
, case when event_type = 'Live' then start_date end desc
, case when event_type = 'Future' then start_date end asc;

Comment: Thank you very much. It is what I want.
Comment: Great! Keep in mind that it doesn't do any good to have `ORDER BY` inside of what you are unioning, because it will essentially be ignored. You have to do any ordering on the results of the union.
Answer: Why can't you just select  all events ordered by start_date?
select *
from `events`
where (`start_date` < NOW() AND `end_date` > NOW())
or (`start_date` > NOW())
order by `start_date` desc

Anyway live events will be first, then future events
Comment: This is not what i want. Because I first want to get ordered list of live events (where `start_date` < NOW() and `end_date` > NOW() ), and after future events (  where `start_date` > NOW() ).
Comment: Sorry, I fixed the query, now it should be what and you want
1) select ALL (live OR future) events
2) order by `start_date`
Live events will be first, future events seconds, because live events have `start_date`NOW()


Views and CSS : how to exclude the exposed filters from CSS?

Question: I'm using CSS to make a masonry effect in Views. And it works, but... The exposed filters and the pager get "caught" in the masonry effect instead of being on top (and bottom) of the results.
Question : how to set the CSS so that the exposed filters and the pager stay out of the results.
Thanks!
ps.: I know about Masonry views, but I prefer CSS.
The CSS:
In Views "Other" : CSS Class
<code>.brick-user {
    margin: 1.5em 0;
    padding: 0;
    -moz-column-gap: 10px;
    -webkit-column-gap: 10px;
    column-gap: 3em;
    font-size: .85em;
}
</code>
Settins : Row class
<code>.brique-user-item {
    display: inline-block;
    background: #fff;
    border: 1px solid lightgrey;
    padding: 15px;
    margin: 0 0 1.5em;
    text-align: center;
    width: 100%;
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;

}
</code>
Answer: You could use the "Exposed form in block" setting under Advanced settings to get the exposed filter out of the masonry markup and put it a region above or beneath your masonry view.


Interpreting regression coefficients in R

Question: I'm trying to fit a x*log(x) model to the data. The fitting is performed successfully but I have difficulties in interpreting the resulting coefficients. Here a snapshot of my code.
x <- c(6, 11, 16, 21, 26, 31, 36, 41, 46, 51)
y <- c(5.485, 6.992, 7.447, 8.134, 8.524, 8.985, 9.271, 9.647, 10.561, 9.971)

fit <- lm(y ~ x*log(x))
coef(fit)
> (Intercept)           x      log(x)    x:log(x)
3.15224227  0.10020022  1.12588040 -0.01322249

How I should interpret these coefficients? Let's call them a,b,c,d. Where I should put them in the formula "x*log(x)"?
Comment: StackOverflow is intended more for programming questions. Help with interpreting statistical models might be a better fit for crossvalidated.com.
Comment: The documentation in `?lm` has a detailed description of the meaning of model formula, I suggest you read it carefully. Specifically, `*` has a special (non-arithmetic) meaning in that context.
Comment: Sorry, I was not clear in my question. I don't mean interpreting the values itself of the coefficients. Let's call the 4 coefficients a,b,c,d: the fitting is actually for what function? for instance, a + b*xlog(c*x)?
Answer: As written, the model you are fitting is
E(y) = a + b*x + c*log(x) + d*x*log(x)

If you really did want to fit the model a + b*x*log(c*x) you would need to figure out that a + b*x*(log(c)+log(x)) = a + b*log(c)*x + b*x*log(x), fit y ~ x + x:log(x), and back-calculate the parameters accordingly.
Or you might be interested in y~I(x*log(x))?
What is the model you actually want to fit?
Comment: The model I want to fit is "a+b*x*log(c*x)". So your answer is perfect, thanks a lot!
Comment: +1 Just beat me there. The only other thing I was going to suggest was that maybe they are really wanting to use `nls`, if they want a coefficient inside the log function.


Views with taxonomy contextual filter not working in Russian language in Drupal 7

Question: I have a View which works perfectly in English.
It has a contextual filter, with options
Content: Has taxonomy term ID ,
filters by taxonomy term with term name converted to term Id.
But when I put in the URL the term in Russian, Раздел, it does not show the content.
When I check the SQL, to my surprise and dismay, this is what I find: search_index.word = 'razdel'.
Clearly there has been a transliteration. Maybe this is why it does not work. I do not really what to do.
Answer: It's probably the collation of your fields and tables in database, try to check to see if all the tables collation is set to utf8_general_ci
you can google to find an script to bulk update your tables and or fields collation
Comment: Yes, the collation was right. The problem was that I preprocessed the data coming from the URL, and I had missed the following line of code in the return of the function: $taxonomy = urldecode($taxonomy); Later I did a return of $taxonomy. Still, as the View admin is not intercepted by this function, I cannot understand the problem with the transliteration, it is very strange. So I have the situation that the site is working fine (with that correction), but when I edit the View and try to replicate the same behaviour in the View display, I got empty results and that strange transliteration. Ma
Comment: Also about the views part, there may be a table left for views still having the same problem, try to check your whole database and make sure, otherwise there must be something wrong with your views


Extract the consecutive words from the middle of a string in R

Question: Ok, so I'm new to regexpr and my brain is about to fry. What I would like to do is extract words two and three from a string. For example:
sentence <- "Certified 2017 Mazda CX-5 AWD Touring"
TheFunction(sentence)

should return "2017 Mazda"
My initial attempt is using something like:
sub("\\s\\S+\\s\\S+\\s", "\\1", sentence)

but is failing miserably. My idea is to find the first pattern that matches "space-word-space-word-space"
Comment: `stringr::word(x, 2, 3)`
Comment: I'd use `strsplit(sentence, split = "\\s")[[1]][2:3]`
Comment: See https://ideone.com/cra6QZ
Comment: `gsub('(^\\w+\\s)(\\w+\\s\\w+)(^|\\s.*)', '\\2', sentence)`
Answer: You can use strsplit then paste the 2nd and 3rd word together
paste(strsplit(sentence, split = '\\s')[[1]][2:3], collapse = " ")


Can't update via composer because of lock file

Question: I am trying to install Lightning 8.1.0. I am currently at 8.1.00-rc5. When I run composer require drupal/lightning:8.1.0 I get the following response:
± |master ✓| → composer require drupal/lightning:8.1.0
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
    1/1:  http://packagist.org/p/provider-latest$aa4f1da6acef0b15640bc1cace21327f5342dbb88c61b4605f0b1b0ff21d7399.json
    Finished: success: 1, skipped: 0, failure: 0, total: 1
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Can only install one of: drupal/entity_browser[8.1.x-dev, 8.1.0-alpha3].
    - Can only install one of: drupal/entity_browser[8.1.0-alpha3, 8.1.x-dev].
    - drupal/lightning 8.1.00 requires drupal/entity_browser 8.1.0-alpha3 -> satisfiable by drupal/entity_browser[8.1.0-alpha3].
    - Installation request for drupal/lightning 8.1.0 -> satisfiable by drupal/lightning[8.1.00].
    - Installation request for drupal/entity_browser (locked at 8.1.x-dev) -> satisfiable by drupal/entity_browser[8.1.x-dev].

Installation failed, reverting ./composer.json to its original content.

The only way I get around this is that I have to remove the composer.lock file before I run composer require drupal/lightning:8.1.0. Does this sound like the right way to do it?

composer.json: http://pasted.co/f2561b5d
composer.lock: http://pasted.co/573a945e
Comment: Delete the lock file and run `composer install` again.
Comment: You only need to do `composer require` if you are adding a dependency to your application. You probably are thinking of `composer update drupal/lightning:8.1.0` if I recall correctly.
Comment: If I run `composer update drupal/lightning:8.1.0` I get Package "drupal/lightning:8.1.0" listed for update is not installed. Ignoring.
Comment: If the above doesn't work then you should attach your computer.json file above.
Comment: @Eyal I added links to the files.
Comment: Remove the `drupal/entity_browser` line. Remove the computer.lock file. And try to run composer install
Comment: @Eyal  Thanks! It does work when removing the lock file but I thought that is the wrong way.
Comment: The lock file is only needed for deployment. To make sure the production server will have the exact same packages as the development server.
Answer: The way I updated is I manually updated composer and set Lightning to 8.1.0 and then ran composer update drupal/lightning.
Comment: This is the right way :)
Comment: @Chapabu Do you think there is a way to do this via composer command?   Some kind of force flag or something like that.
Comment: If you set the version for Lightning to `8.1.*` then running `composer update` will get the latest patch release if one is available.
Comment: @Chapabu What about if I have the full version inside my composer file already.  Reason I do that is that I want all my sites to always be at the same version.
Comment: What do you mean you have the full version in your composer file already? If you change `8.1.0` to `8.1.*` you'll still be getting the full version, it'll just be the latest patch release (depending on your `minimum-stability`).
Comment: But what if I have 8.1.0 in my composer and I want to update to 8.1.2. The only way would be to update the composer file to 8.1.2 or 8.1.*.  I'm inclined to use the full version (8.1.2 instead of 8.1.*) because I want every single site to have the same version. Let me know if you think that is bad?
Comment: `8.1.*` IS the full version, it just the latest patch release.
Comment: This might be of use: https://getcomposer.org/doc/articles/versions.md
Comment: @albertski if you want to do this without manually editing you composer.json file, just pass the `--no-update` flag to your composer require command. Then run `composer update` afterwards: `composer require drupal/lightning:8.1.13 --no-update`. Then `composer update`
Answer: If you're dealing with a top level dependency, you can remove the old version and then install the new version:
composer remove drupal/lightning
composer require drupal/lightning:8.1.0

Comment: Oh yeah! I was simply trying to `composer require provision-ops/yaml-tests` to upgrade it and kept getting dependency issues even though that was the only package that was requiring things. Composer didn't tell me which package only that the problem package was "locked at 1.7.1" or something like that. Your technique worked!
Answer: I had a similar case due to security reasons on a GitHub repository.
I solved updating the dependency to a specific version like this:
composer require phpseclib/phpseclib:2.0.31

If you are working with virtual environments like docker containers (ddev, lando, etc..) before running it you should connect to the container with a:
ddev ssh


ConEmu with Git Bash - Show folder in tab bar

Question: I'm usually running Git Bash in ConEmu tabs.  It would be really handy to show the name of the current directory in the tab bar for each instance of Git Bash, but if I set the tab template to %d or %f, I always get my Windows home directory, no matter where I cd to in Git Bash.
Is there a way to display the path in the tab bar?  As you can see from the attached screenshot, I'm navigated to the banana folder, but ccook (my home dir) is shown in the tab.
The Title (%s) seems to contain the full path, but that's too long for my tabs.

The best I'm currently able to achieve is to use %s and add MINGW64 as a Skipped word from title, but that still gets me the full path instead of just the current folder.  If there was a way to specify a regex I could exclude everything but the text after the final /.
Comment: Would you mind sharing how you do it.  I'm reading the documentation and it's still not clear.
Comment: RTFM https://conemu.github.io/en/ShellWorkDir.html
Comment: Ah, that's got it, thanks - I hadn't found that page.  Bit harsh on me, though.
Answer: For Cygwin users, add PROMPT_COMMAND='ConEmuC -StoreCWD' to the .bashrc.
Per suggestion from @Jeffrey-Harmon

if [[ -n "${ConEmuPID}" ]]; then
        PROMPT_COMMAND='ConEmuC -StoreCWD'
fi

edit:
Looking at the documentation page, this suggestion is there as well now.
https://conemu.github.io/en/ShellWorkDir.html#bash_and_other_cygwin_shells
Comment: This worked with Git Bash as well, but you should wrap this in an if statement, so if you ever open the shell outside of ConEmu, it won't display an error after every command about not being able to find ConEmuC.

    if [[ -n "${ConEmuPID}" ]]; then
      PROMPT_COMMAND='ConEmuC -StoreCWD'
    fi


Como desabilitar/habilar botão(button) quando input file estiver vazio/selecionado?

Question: Então, tenho um formulário simples de upload de imagens que eu deixo  button desabilitado. Queria que, quando eu selecionar uma foto ou arquivo no input file, o button habilitar!

    <button id="btnEnvia" name="btnEnvia" class="save abre_load" disabled="true">
        SALVAR
    </button>

    SELECIONAR FOTOS
    <input id="img" type="file" name="img[]" multiple required/>

Answer: É possível obter os detalhes do input file pelo evento change e então habilitar o botão, algo como:

$("#img").change(function(){
  $("#btnEnvia").attr("disabled", false);
});

    <button id="btnEnvia" name="btnEnvia" class="save abre_load" disabled="true">SALVAR</button>

    SELECIONAR FOTOS
    <input id="img" type="file" name="img[]" multiple required/>

Comment: Moçada eu resolvi, coloquei o script abaixo de outros scripts no footer, provavelmente era alguma outra importação de Jquery que tava me avacalhando!
Answer: Você pode verificar pelo files.length usando jquery:
if ($('#img').get(0).files.length === 0) {
    //aqui você desativa o seu botão
    document.getElementById("btnEnvia").disabled = true;
    }
else
    {
      //aqui você habilita o botão
      document.getElementById("btnEnvia").disabled = false;
    }

Comment: Sugestão: https://jsfiddle.net/c3n17ufd/
Comment: Show cara, resolvido aqui!
Comment: Que bom que resolveu, não esquece de marcar como resposta.


Drupal's attach behaviours : react on all newly loaded content?

Question: I've got two different modules which in many ways work together. One of the things they work together on is that module A loads content via AJAX, and module B needs to attach event listeners to the content loaded.
However, it appears that when content is loaded via AJAX by module A, only the 'attach' function of Drupal.behaviours.a gets invoked, and not the 'attach' function of Drupal.behaviours.b. Both functions gets invoked on page load, but not on subsequent AJAX content loading.
// This runs every time module A loads new content.
Drupal.behaviors.a = {
  attach: function(context, settings) {
    alert('a:attach');
  }
}

// This only runs on page load, but never when module A loads new content.
Drupal.behaviors.b = {
  attach: function(context, settings) {
    alert('b:attach');
  }
}

How do i make the 'attach' function of Drupal.behaviours.b run every time any module loads new content?
Comment: If you want a catch-all solution `$('body').ajaxSuccess(Drupal.attachBehaviors);` will probably work
Comment: Have you tried adding `Drupal.attachBehaviors();` to the ajax success callback?
Comment: No, but should that not be taken care of automatically? I thought that was the whole idea of the 'attach' function; that it should be called on page load and page update? It does seem, however, that only the 'attach' function for the invoking module gets called on page update though?
Comment: That was my understanding yes, I haven't ever looked into it too deeply though. I know there's been times when after an AJAX call I've needed to reattach behaviours so I just assumed it was required
Comment: Looking at drupal.js :

"Drupal.attachBehaviors is added below to the jQuery ready event and so runs on initial page load. Developers implementing AHAH/Ajax in their solutions should also call this function after new page content has been loaded, feeding in an element to be processed, in order to attach all behaviors to the new content."

It does seem that I need to invoke the attachBehaviours myself. But; it puzzles me that module A's 'attach' function runs even though I haven't invoked attachBehaviours in the AJAX success callback...?  Why just for the invoking module, and not all modules?
Comment: That puzzled me too a bit, it's hard to say without seeing the code in that module's attach function though
Comment: Well, the code in module A's 'attach' function does not really do anything but add a couple of listeners on various elements. There is nothing to indicate that Drupal.attachBehaviours() should be invoked for that module's 'attach' function. However, could it be that the AJAX functionality in Drupal somehow automatically invokes the 'attach' function for the module responsible for the AJAX? Could it be that Drupal somehow keeps track of which module set up which event listener?
Comment: I believe i found the reason. Module B's JavaScript was not quite right. It started out with (function($) {
Drupal.behaviors.b = { attach: [...] }})(jQuery); After having fixed it to simply Drupal.behaviours.a { attach : [...] }; things worked better. @Clive : you're welcome to post one of your comments, I'll accept it as an answer since you did after all contribute to the discussion which again lead to me looking further into details.
Answer: This, from the comments in misc/drupal.js, explains how it's supposed to work:

Drupal.attachBehaviors is added below to the jQuery ready event and so
runs on initial page load. Developers implementing AHAH/Ajax in their
solutions should also call this function after new page content has been
loaded, feeding in an element to be processed, in order to attach all
behaviors to the new content.
Answer: Try adding this in Drupal.behavior.b:
Drupal.attachBehaviors($(this));


How to balance between running search in frontend and backend?

Question: I have an angular app that runs on a Rails app api.
I do most of my searches using Angular in the frontend, but I feel like there is going to be a bottleneck when I reach a huge number of users.
Should I go with the backend Rails api search or stick with the frontend even if my users reach 5000 users.
Answer: If you are going to have 5000 users in a searchable list, you're likely going to need to handle things on the server. Obviously hard to answer without more I for about your app, but once you start getting into thousands of potential angular bindings, it starts to crawl.
Comment: Thanks @Mike, this the kind of answer I was looking for. I don't really have that much more, it's as simple as a directory of names and users in my app.


Removing another role when a specific role added is detected with Discord.js

Question: I'm wondering if anyone can help me out with Discord.js snippet of code from my current bot.
I'm looking to add to these lines of codes below to Remove a Role --- So basically my bot is detecting when a role change happens specific to this role being added. Then once it happens, it strips away one of the roles -- if that makes sense?
if
  (!oldMem.roles.find(x => x.name === "Inactive") && newMem.roles.find(x => x.name === "Inactive"))
      client.channels.get("547932494259814410").send(`:bell: ${newMem} THere is a new inactive <@&662373687726440461>...`);

The role I want to strip from the user is the role ID of 560860499894337538 - Not everyone will have this role although, so I'm hoping this can be done without the BOT erroring out as well.
Comment: Could you show the error?
Answer: The code I've added will try to find the role you want to remove and then remove it if it was found.
if (!oldMem.roles.find(x => x.name === "Inactive") && newMem.roles.find(x => x.name === "Inactive")) {
    client.channels.get("547932494259814410").send(`:bell: ${newMem} There is a new inactive <@&662373687726440461>...`);

    const role = message.member.roles.get('560860499894337538');

    if (role) newMem.roles.remove(role).catch(console.log);
}


Resizing TextView does not shrink its height on Android 3.1

Question: I have a TextView which can be resized dinamically (I use setTextSize()). It correctly expands and shrinks its bounds on Android 2.2. But on Android 3.1, when the text become smaller, the height of area is not shrink.
Here is the short video that demonstrates that.
The layout is just simple vertical LinearLayout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="0dip">
...
<TextView
    android:id="@+id/track_number"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    style="@style/tcTrackNo"
    android:padding="5dp" />
    ...

So, what extra should be done to make the TextView reduce its height accordingly to its font size on Honeycomb?
PS. Again, on Android 2.2 the text area collapses until the smallest height without any issue. The video how it's intended to work.
Answer: Might be a bit late it's from a bug
http://code.google.com/p/android/issues/detail?id=17343
http://code.google.com/p/android/issues/detail?id=22493
But there is a workaround by appending a non width character at the end of your text.
Any of these work
final String DOUBLE_BYTE_SPACE = "\u3000";
final String DOUBLE_BYTE_WORDJOINER = "\u2060";
final String ZERO_WIDTH_SPACE = "\u200b";
textview.append(ZERO_WIDTH_SPACE);

Answer: i know this is an old thread.
but all these characters listed above did not worked properly with me, i faced this issue with 5.0.1 and the fix was to set the textview gravity to center vertical.
hope this help anyone :)