Is there a way to pass an Angular 2 attribute directive a function

Question: In Angular 1, you could pass a function as an argument to an attribute directive using &. I know you can pass a function as input to an element directive (component) in Angular 2 using the
<custom-component [callback]="myCallbackFuncton">
..etc
</custom-component>

syntax, but is there a way to do this with an attribute directive only? I can only get a string (which does allow me to look the function up off the scope) but would prefer to pass the function in all in one go.
So I would like to be able to write something like this in my template
 <form custom-submit="ctrl.register">
 ...etc
 </form>

and in the directive js,
@Directive({
    selector: '[custom-submit]',
})
@Inject('$element', '$attrs')

export default class CustomSubmit {
    constructor($element, $scope, $attrs) {
        this.$element = $element;

        $element[0].addEventListener('submit', () => {
          // custom validation behaviour
          $attrs.customSubmit();
        });
   }
}

Instead of having to write something like
 $scope.ctrl[$attrs.customSubmit]()

Answer: try this:
@Output is better
Use @Output Plunk online demo @Output
app/custom-submit.directive.ts
import { Directive, Output, HostListener, EventEmitter } from '@angular/core';

@Directive({
  selector: '[custom-submit]'
})
export class CustomSubmit {
  constructor(
    // ...
  ) { }

  @Output('custom-submit') customSubmit: EventEmitter<any> = new EventEmitter();

  @HostListener('submit', ['$event'])
  onSubmit(e) {
    e.preventDefault();
    console.log('call this');
    this.customSubmit.emit(e);
  }
}

app/app.component.ts
import {Component} from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <form (custom-submit)="onSubmit($event)">

        {{item}}

      <button type="submit">Submit</button>

Status {{ message }}

    </form>
  `
})
export class AppComponent {
  message: string = '';

  onSubmit(e) {
    console.log(e);
    this.message = 'submitted';
  }
}

USE @Input Plunk online demo @Input()
app/custom-submit.directive.ts
import { Directive, Input, HostListener } from '@angular/core';

@Directive({
  selector: '[custom-submit]'
})
export class CustomSubmit {
  constructor(
    // ...
  ) { }

  @Input('custom-submit') customSubmit: Fn;

  @HostListener('submit', ['$event'])
  onSubmit(e) {
    e.preventDefault();
    console.log('call this');
    this.customSubmit();
  }
}

app/app.component.ts
import {Component} from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <form [custom-submit]="onSubmit">

        {{item}}

      <button type="submit">Submit</button>

Status {{ message }}

    </form>
  `
})
export class AppComponent {
  message: string = '';
  constructor() {
    // be careful when pass method to other Component Input
    this.onSubmit = this.onSubmit.bind(this);
  }
  onSubmit() {
    console.log('submitted');
    this.message = 'submitted';
  }
}

Comment: Thanks for the reply - I get the same result with that - the input is passed as a string not a reference to the function
Comment: `the input is passed as a string not a reference to the function` i don't think so, just log `console.log(this.customSubmit);` you will get real function, not string
Comment: Nice one thanks very much for the demo - I'm not using typescript and must have translated incorrectly the first time :)
Comment: great news, i'm newbie in Angular/Typescript too.


UIAlertView not getting displayed at right time

Question: I have a button in a simple view with on click function :
@IBAction func watchAlert(sender: AnyObject) {
    showAlert()
    for i in 1...2{
    AudioServicesPlaySystemSound (1005);
    sleep(2)
    }

}

func showAlert(){
    var alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
    self.presentViewController(alert, animated: true, completion: nil)
    alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: dismissAlert ))

}

func dismissAlert(alertView: UIAlertAction!)
{
    println("User click ok button")
}

Even though I am trying to call showAlert() before playing the audio, I could only see the alert getting displayed only after sound gets played. I want the alert to be present first and then sound should play.
Any help is appreciated.
Answer: Take out the sleep command (you must never sleep the main thread - the Watchdog process will kill you dead, and besides, you are wrongly freezing the whole interface). Instead: show the alert, then use delayed performance (as in my delay utility here) to play a sound.
(There are other problems with your code; in particular, you will also need to find a new way to play the sound twice, since you must not use sleep; this, too, can be accomplished using delay - nested.)
Comment: This seems good! But i have a question, How do i go about dismissing the music in such a case of using delay (i.e kill all other further plays of tone).


Clearing cookies via PHP

Question: How to clear cookies via php?
I need a php code that will clear the cookies and then refresh the page.
I need some link  and when I click it, the cookies are cleared and page refreshed.
Comment: This is available in the PHP manual. You could have checked it before you post it here.
Comment: Do you have specific cookies that you want to clear or are there too many to do each individually?
Comment: I include only one information about language used on the site.
"PHPSESSID"
Comment: Then the answer below by John Conde will work just fine
Answer: From the PHP manual (which you should be reading before coming here to ask for help)
Example #2 setcookie() delete example
When deleting a cookie you should assure that the expiration date is in the past, to trigger the removal mechanism in your browser. Examples follow how to delete cookies sent in previous example:
<?php
// set the expiration date to one hour ago
setcookie ("TestCookie", "", time() - 3600);
setcookie ("TestCookie", "", time() - 3600, "/~rasmus/", "example.com", 1);
?>

Answer: You will only be able to delete cookies that had an expiration time set.  If you set them with an expire time of 0, that means "the cookie will expire at the end of the session (when the browser closes)," and the browser will keep them despite receiving delete headers.  (Firefox 13, anyway).
See php setcookie()

Clearing cookies via PHP


Prediction with log scaled

Question: i think i'm with a little problem. I was working with a dataset but the dependent variable was not normally distributed, so i decided to used log in that variable. To see the difference between them i made a model with log transformation and a model without the log transformation.
So in my model with the log transformation i made the linear regression, predicted the values and then back transformed with exp. While visually speaking the prediction went better, the mean squared error get very worse. I'm doing something wrong along the way?
Comment: Welcome to Cross Validated! I have some good news: you don't need the $y$ variable to have a normal distribution (the common normality assumption is about the error term), so it might be that you did it have to take the log at all!
Answer: so without more details its hard to decide, but
a) exponentiating will cause small errors to be magnified.
b) your problem could be bias induced by exponentiating
see https://stats.stackexchange.com/a/361240.
you need E[y|x], but its not $\exp(E[\ln(y)|x])$
a simple approximate solution is multiplying  your prediction by $\exp(.5 mse)$ as detailed in the linked answer

Prediction with log scaled


How to interpret model diagnostics graphics after R linear regression?

Question: I am interested in understanding the graph plots we get after running lm() command (for linear regression) in R like, for example
lm.mod1 = lm(y ~ x1 + x2)

I then get the do the summary by:
summary(lm.mod1)

I get the result as:
 Residuals:
  Min      1Q  Median      3Q     Max
 -750.32 -160.54  -49.83  115.83 2923.74

 Coefficients:
                           Estimate Std. Error     t value Pr(>|t|)
(Intercept)               -345.1552      37.0393   -9.319   <2e-16 ***
         x1                52.9091       2.4929    21.224   <2e-16 ***
         x2                8.9669        0.5395    16.620   <2e-16 ***

Residual standard error: 274.4 on 1985 degrees of freedom
Multiple R-squared: 0.2059, Adjusted R-squared: 0.2051
F-statistic: 257.3 on 2 and 1985 DF,  p-value: < 2.2e-16

I then do the plotting by
par(mfrow = c(2,2))
plot(lm.mod1)

I get 4 graphs (I can't post the graphs since I am a new user and my experience level is below 10. :/)
My questions are :

How do they calculate F-statistics and t-value?
Could someone explain me the what do we interpret with the last two graphs i.e. $\text{Scale-Location vs. (Standardized residuals)}^{1/2}$ and $\text{Residuals vs. Leverage}$. What do you mean by Leverage?
What do you mean by Cook's Distance? I saw it on wikipedia but I didnt get it.
How could we suggest if our model is a good model or not?
Comment: [I answered](http://stats.stackexchange.com/questions/28688/how-to-interpret-model-diagnostics-when-doing-linear-regression-in-r/28697#28697) many of these questions last week. You will learn more if you search for similar questions from other sources.
Comment: An even better discussion here: http://stats.stackexchange.com/questions/5135/interpretation-of-rs-lm-output
Comment: These are good questions, but as the comments and attempted replies indicate, they cover too much ground.  Please focus on one at a time, perform some research, and be specific about what you're looking for. "I didn't get it" doesn't give us enough clues to provide the information you need.
Answer: I rarely do this, but your question is so general, and covers so many topics, that I don't see any other choice than to point you to something like this:
http://cran.r-project.org/doc/contrib/Faraway-PRA.pdf
And tell you to simply read.
There is a newer version for this book here:
http://www.amazon.com/Linear-Models-Chapman-Statistical-Science/dp/1584884258/
Comment: For some great books on regression diagnostics there is the book from the 1980s by Belsey, Kuh and Welsch (published by Wiley)  Somewhat later Dennis Cook published some regression books that emphasize graphics and regression diagnostic including his own Cook's distance.  These books tended to cover concept and not specific software.  This was way before the R revolution and some even before S became popular.
Answer: As @TalGalili said .... you need to read a good book on regression. Faraway's book is fine. There are many other good ones. One that I like, that is R-specific, and has a new edition is by Fox and Weisberg. A more general and somewhat more advanced book is Frank Harrell's Regression Modeling Strategies, which also uses R.
Comment: Hi Peter.  Regression Modeling Strategies is great, but would you send a novice to it?! :)
Fox's book is also a good suggestion!
Comment: Hi @TalGalili you're right, RMS is not for novices. I did say "more advanced" but perhaps I shouldn't even have mentioned it in this context.


Can I use p-test or F-test to test for significance in this example?

Question:
I'm confused at why there would be limitations to using one test or the other
Answer: The question is a little vague. Generally, in simple linear regression
$$
t ^ 2 = F,
$$
hence it does not matter which one to use to test significance. However, as this problem describes a simple linear model that was fitted for a time series, the $\epsilon$ may bear an auto-correlation of some order, hence the $t$ and $F$ statistic are not really distributed $\mathcal{T}$ and $\mathcal{F}$.


Angular UI Router controllers instantiated multiple times - Direct route

Question: I have a parent / child route set up, and everything works great when I change the state in code using state.go().  The problem arises when I try to go directly to the child route using only a URL.  When I do this, the controllers get initialized multiple times.
Here is my app.js
    $stateProvider
    .state('home', {
        url: "/",
        templateUrl: "Views/home.html",
        controller: 'HomeController',
        controllerAs: 'vm'
    })
    .state('ticketsMaster', {
        abstract: true,
        templateUrl: "Views/tickets-master.html",
        url: "^/performances?featureCode&theatreId",
        controller: 'TicketsMasterController',
        controllerAs: 'vm'
    })
    .state('ticketsMaster.performances', {
        url: "^/performances?featureCode&theatreId",
        templateUrl: "Views/performances.html",
        controller: 'PerformancesController',
        controllerAs: 'vm'
    })
    $locationProvider.html5Mode({
        enabled: true,
        requireBase: false
    });

home.html is my master page where I have my ui-view
I also have another ui-view on my tickets-master.html where this loads my child views (performances).
When going directly to /performances?featureCode=1111&theatreId=1 it loads my TicketsMasterController, and Performances controller 2 or 3 times.
Any help would be appreciated.
Comment: what's the point of routing them to ```"^/performances?featureCode&theatreId",``` in two different states?
Comment: that was a genuine question, do you have to declare a url in every state to load a template?
Comment: That is a good question - I only put it there because I can only get it off of the ticketsMaster state.  If I put it only on the ticketsMaster.performances state, I am not able to see them at all.  I get rid of the url completely on the master one, and I still have the same problem.
Answer: I found the answer here:
https://github.com/angular-ui/ui-router/issues/372

add this line to app.config:
$locationProvider.html5Mode(true).hashPrefix('!')
and include this line in the head of index.html:
<base href="/">


Hibernate 5.2 get natural id properties from metamodel

Question: Since SessionFactory#getClassMetadata(java.lang.Class) was deprecated, I am not able to use ClassMetadata. I would like to access to the following methods:

org.hibernate.metadata.ClassMetadata#getNaturalIdentifierProperties
org.hibernate.metadata.ClassMetadata#hasNaturalIdentifier

According to the documentation, I should replace getClassMetada with  EntityManagerFactory.getMetamodel(). However, the metamodel does not contain methods to get natural-id. I am using xml mapping for natural-id and I would like to get the property names of the natural-id to create a dynamic query.
<class name="User">
  <cache usage="read-write"/>
  <id name="id">
    <generator class="increment"/>
  </id>
  <natural-id>
    <property name="name"/>
    <property name="org"/>
  </natural-id>
  <property name="password"/>
</class>

Is there a way to use those methods to get the natural id mapping?
Is there another way to get a ClassMetadata instance?
Is it possible to get an instance of entityMetamodel to replace the ClassMetadata?
Answer: Well, knowing that SessionFactory#getClassMetadata(java.lang.Class)  was deprecated, the option is using sessionFactory.getMetamodel(). Checking into hibernate code, this was my solution:
MetamodelImplementor metamodel = (MetamodelImplementor) sessionFactory.getMetamodel();
ClassMetadata classMetadata = (ClassMetadata) metamodel.entityPersister(entityName);

First, one part important to know is what entityName is. It could be the name of the mapped entity or Entity.class.getName(). Knowing that, to replace SessionFactory#getClassMetadata(java.lang.Class) with should get the name of the class and pass it as an string.
String entityName = EntityClass.class.getName();

Second, Hibernate has an implementation of JPA metamodel, named MetamodelImplementor.
Additionally, metamodel.entityPersister() returns an EntityPersister interface. Hibernate implements it using AbstractEntityPersister. And that is an abstract class which implements Lockable and ClassMetadata interfaces.

EntityPersister (interface) --> Lockable (interface) -->
  AbstractEntityPersister (abstract class)
ClassMetadata (interface) --> AbstractEntityPersister (abstract class)

So, it is possible to cast AbstractEntityPersister to ClassMetadata. And in that way return same object.
This is a portion of code of Hibernate in SessionFactoryImpl:
public ClassMetadata getClassMetadata(String entityName) throws HibernateException {
    return (ClassMetadata) getMetamodel().entityPersister( entityName );
}


Is a bass line the same as a bass progression?

Question: In alot of songs there's a chord progression. Say we have a 4 chord progression. Each chord can correspond to a note the bass plays. So now the bass is playing a 4 note progression. Is that called a bass line (are they one in the same?) Is a 'line' and a 'progression' the same thing?
The reason I ask is when I'm trying to figure out a song by ear, I like to think in terms of bass notes (not chords b/c thinking of a single note is easier), and then I later convert them to chords based on if they sound major or minor, etc. Note that sometimes these bass notes aren't the roots of the chord, it's just the "essence" of the chord at the time (it's the note that sounds most like the chord). Sometimes I'll hit the seventh of a chord for example.
Comment: Your method of converting bass notes to chords will fail as soon as you try to transcribe a boogie-woogie song. That's the most prominent subgenre I can think of that consistently has a walking bass with plentiful nonchord tones.
Comment: @Dekkadeci I'm not trying to figure out lines/walking basses (as those are easier), rather chord progressions. been using chordchord.com as practice.
Answer:
Is a bass line the same as a bass note progression?

"Bass note progression" is not a term that I've ever heard. Generally, we speak of a "bass line" and a "chord progression." They are separate but related things.
The chord progression consists of the sequence of chords. I have heard the term "root progression" used to refer to the movement of the roots of the chords in the progression. This is a theoretical term used to analyze the way the chords related to each other and the overall tonality/harmony of the piece.
"Bass line" on the other hand tends to have a more practical meaning. It refers specifically to the melodic line the the bass instrument or voice is playing. Sometimes this is very simple and consists solely of the root notes, but it often includes additional chord tones and passing tones.
Comment: @foreyez That can be a problem, but most of the time, in most forms of music, the note that the bass instrument plays on the downbeat of a chord change will be the root of the chord. So if a particular song has a complicated bassline, it can be helpful to focus on just the notes on those downbeats.
Comment: Thing is when I turn the chord progression into tones (by trying to play by ear) they might not necessarily be the roots. It's the tone that most captures the essence of the chord. Could be a seventh note on that chord for example.
Answer: No, not in general. The bass line is the sequence of lowest (in general as usual) notes. The chord progress is the sequence of chord roots (and usually any chord modifiers.)
The bass line usually moves more quickly than the root of the chords do.
This is a modern (after 1700) development. Modern analysis would show the chords C-E-G followed by C-E-A as a root position C-major chord followed by a first inversion A-minor chord. Earlier (figured bass or general bass) would treat the two a E with a major third and perfect fifth followed by E with a major third and major sixth.
Answer: You have a lot of terms in the question: the bass, bass line, bass progression, chord, chord progression, bass note, root.
Some of the terminology is synonymous.

Each chord can correspond to a note the bass plays.

Yes, but 'correspond' is vague. We should try to be specific with terms and distinguish between what is concrete and what is conceptual/abstract. The concrete is what actually is played. The conceptual is basically analysis of what is played.

The bass: this really can mean two things either the musical part that is the lowest, or the instrument that is playing that part. The bass guitar will usually play the bass part. Concrete.
Bass note, bass line, bass progression: these would simply be the notes of the bass part, note being singular, progression being a series of notes could be just a progression of two (D2 to A1) or could be for a section (D2 A1 B1 G1). Concrete.
Chord: this can be both concrete - like when the guitar plays a D chord - or it can be more abstract - like when a group is play linear parts and chords result from the combination of parts. While the former is straight forward the later could be open to analysis and interpretation depending how independent are the linear parts. Things can be further complicated when chord instruments like guitars and keyboards play over a bass part combining to form extended chords, like a guitar playing a D chord over a B in the bass. The resulting chord might be analyzed as Bm7. You could refer to the guitar chord as an incomplete Bm7 - conceptual - or call in a D chord, because in concrete terms that is what the guitar is playing in isolation.
Chord progression: when you get past the complications of identifying the chords, the chord progression is a series of chords.
Root: lowest tone of a chord when all chord tones are arranged in ascending thirds, not necessarily what the bass part plays, a chord root can occasionally be omitted and implied. Conceptual.

Is a bass line the same as a bass progression?

Yes. Bass line, bass progression, the bass part, bass note(s) all are just synonymous terms for the notes the bass plays. Bass progression might not be the best choice of words, because it could be confused with the more common terms chord progression and root progression. All three of those terms have different meanings.
Answer: The bass is hardly going to be playing one note per bar - or even one note per chord if that stays staic for a few bars. Wouldn't call that a line or a progression. It's a chord progression - any line of chord changes is that. And while the bass often plays the root on beat one, it won't always, so don't take that note as the root necessarily.
A bass line or progression is more of a run type of thing, perhaps like a walking bass leading to the next chord.
Comment: so from your answer you're saying there is no term for what I am describing.
Answer: The bass line is a simple concept, where there is clearly a designated bass instrument - it's what's actually played by that instrument.
A chord progression is a more abstract concept. "The sequence of chords" is a simplification of all the notes being played in the piece. A chord progression might not actually capture all the information about the harmony of the piece.
If you're figuring out a piece by ear, you need to decide if you are just trying to work out a chord progression, or if you are trying to actually transcribe/hear each of the instrumental parts accurately.
It sounds more like you are trying to work out chord progressions? If so, the bassline often provides good clues. But not always - and it won't always even be possible to come up with a chord progression that seems to capture the essence of a piece.
Answer: Yes, working out the bass line first can be a good approach to discovering what chords fit a song.
Beyond that, we're just discussing labels.  You've invented a term 'Bass progression'.  OK, you invented it, YOU tell us what it means!
Are all sets of chord a 'progression'?  Or do we reserve that term for a set that does something functional?    C, D7, G7, C is clearly a 'progression' if anything is.  What about Cm9, B♭m9 repeated ad infinitum?   And does it matter?  We want to know what the chords are.  Who cares whether we label them a 'progression' or not?


Incorrect elementary row operation in an augmented coefficient matrix

Question: When solving the matrix
$$\left(\begin{array}{ccc|c}
1 & 1 & 1 & 4\\
1 & 3 & 1 & 4\\
-1 & 2 & 3 & -2\end{array}\right)$$
I somehow made an error with the elementary row operations, but I cannot see it:
$$\left(\begin{array}{ccc|c}
1 & 1 & 1 & 4\\
0 & 5 & 4 & 2\\
0 & 5 & 4 & 2\end{array}\right)\begin{array}{c}
\\
R_2+R_3\\
R_3+R_2\end{array}
\Leftrightarrow\left(\begin{array}{ccc|c}
1 & 0 & 1/5 & 18/5\\
0 & 1 & 4/5 & 2/5\\
0 & 0 & 0 & 0\end{array}\right)\begin{array}{c}
R_1-R_2/5\\
R_2/5\\
R_2-R_3\end{array}$$
This solution is wrong because when substituting the set of solutions $\left\{\begin{array}{c}
x=\frac{18}{5}-\frac{1}{5}t\\
y=\frac{2}{5}-\frac{4}{5}t\\
z=t\end{array}\right.$ into row 2 or 3, I do not get 4 or -2 respectively. I do however note that I could have used a different elementary row operation in the third row of the first calculation:
$$\left(\begin{array}{ccc|c}
1 & 1 & 1 & 4\\
0 & 5 & 4 & 2\\
0 & 3 & 4 & 2\end{array}\right)\begin{array}{c}
\\
R_2+R_3\\
R_3+R_1\end{array}
\Leftrightarrow\left(\begin{array}{ccc|c}
1 & 0 & -1/3 & 10/3\\
0 & 1 & 4/5 & 2/5\\
0 & 0 & 8/5 & 4/5\end{array}\right)\begin{array}{c}
R_1-R_3/3\\
R_2/5\\
R_3-3R_2/5\end{array}
\Leftrightarrow\left(\begin{array}{ccc|c}
1 & 0 & 0 & 7/2\\
0 & 1 & 0 & 0\\
0 & 0 & 1 & 1/2\end{array}\right)\begin{array}{c}
R_1+5R_3/24\\
R_2-R_3/2\\
5R_3/8\end{array}$$
and this solution is correct.
So, what went wrong the first time round?
Answer: Both rows in your first expansion are the same, i.e. $R_2 + R_3$ and $R_3 + R_2$. This means that your first transformation is not reversible. Elementary operations are reversible, i.e. If you can transform $A$ to $A'$ using elementary operations, you can also transform $A'$ to $A$ using elementary operations.
In order to avoid doing such a mistake, always perform only one operation at a time. Thus, you would first transform the third row into $R_2 + R_3$, and in the second step, even if you transformed the second row into $R_2 + R_3$, it would not be equal to the third row.


SQL statement to count with a condition

Question: I am a beginner in SQL, and I need help to get the solution for this condition.
For each attraction, output the number of people visiting this attraction during 2013.
create table visitor(
visitID         char(n),
name            char(n) not null,
primary key (visitID)
);

create table ticket(
ticketID        char(n),
ticketType      char(n),
day             int(n),
month           char(n),
year            int(n),
seasonID        char(n),
visitID         char(n),
primary key (ticketID), foreign key (seasonID) references seasonPerClass, foreign
key (visitID) references visitor
);

create table attractionVisit(
attractionID        char(n),
ticketID        char(n),
foreign key (attractionID) references attraction, foreign key (ticketID) references
ticket
);

create table attraction(
attractionID        char(n),
attractionName  char(n) not null,
primary key (attractionID)
);

I am unable to test my code, but so far I have
SELECT AttractionName, count(distinct VisitID)
FROM (Visitation NATURAL JOIN AttractionVisit)
WHERE year = 2013;

I don't know if this is right or not. Please help.
Comment: What rdbms do you have? what's with these `(n)`s everywhere? have any sample data?
Comment: I dont see a table by name `Visitation`
Comment: in which table you are storing year?
Answer: You need a group by in your query:
SELECT AttractionName, count(distinct VisitID)
FROM (Visitation NATURAL JOIN AttractionVisit)
GROUP BY AttractionName
WHERE year = 2013;

Answer: select att.attractionName, count(att.attractionId) as count
from visitor v inner join ticket t on ( v.visitID = t.visitID)
inner join attractionVisit av on (t.ticketID = av.ticketID)
inner join attraction att on (av.attractionID = att.attractionID)
where t.year = 2013
group by att.attractionName`

Hope this is help.

SQL statement to count with a condition


Multiline Cell in Silverlight DataGrid

Question: I am using the standard DataGrid control in Silverlight 4.
All data is readonly, i.e. no cell is editable.
Does anybody know how to display text in a cell such that it automatically wraps to the next line(s) (in the same cell) when the cell border is reached?
Any feedback is much appreciated.
Answer: In the column definition set the TextWrapping property to "Wrap":
    <sdk:DataGridTextColumn
        Header="Address"
        Width="150"
        Binding="{Binding Address}" >
        <sdk:DataGridTextColumn.ElementStyle>

        </sdk:DataGridTextColumn.ElementStyle>
    </sdk:DataGridTextColumn>

Source
Comment: Thanks Chrisf for your quick response. Your suggestion works. Well, kinda. What happens is that the text wraps when i manually narrow the width of the column. However, the column height remains even when i widen the column again (such that no wrapping would be necessary). Any suggestions on that?
Comment: @hhwh - I don't know off hand. I'd have to experiment, but looking at the resize events would be the best place to start.
Comment: Yes, I have started doing that. It does get rather involved, tho. There is no specific column header resize event. I can capture it in LayoutUpdated event but it gets rather messy to extract the info I am looking for. Which makes me think that there should be a more simple way I am not (yet) getting. I am fairly new to Silverlight. I will keep trying and learning in the process but any pointers you or anybody else may have would be greatly appreciated. Cheers.
Answer: I don't think this is going to work.  Try using a template column, put the TextBlock in there set HorizontalAlignment and VerticalAlignment to stretch and make sure to set the margins.
Comment: thanks for the suggestion, rhooligan. tried it but row heights remain at their highest, even when i change column width manually such that wrapping is not needed.

Multiline Cell in Silverlight DataGrid


puma:restart cap production deploy service not found

Question: Rails 7.0.4
Puma 6.0
I am so close to getting cap production deploy to work in production but I'm stuck on puma:restart
I have an active service on the server
deploy@reports:~/apps/R7-reporting-2022/current$ sudo systemctl status R7-reporting-2022_puma_production.service
[sudo] password for deploy:
● R7-reporting-2022_puma_production.service - Puma HTTP Server
Loaded: loaded (/etc/systemd/system/R7-reporting-2022_puma_production.service; enabled; vendor preset: enabled)
Active: active (running) since Sun 2022-11-06 19:24:32 UTC; 1h 3min ago
Main PID: 612 (puma)
Tasks: 10 (limit: 4575)
Memory: 177.7M
CPU: 2.258s
CGroup: /system.slice/R7-reporting-2022_puma_production.service
└─612 "puma 6.0.0 (unix:///home/deploy/apps/R7-reporting-2022/shared/tmp/sockets/R7-reporting-2022-puma.sock)" "" "" "" "" "" ">

Nov 06 19:24:32 reports systemd[1]: Started Puma HTTP Server.

When I run bundle exec cap production deploy I get the following error
00:24 puma:restart
01 /bin/systemctl --user restart R7-reporting-2022_puma_production
01 Failed to restart R7-reporting-2022_puma_production.service: Unit R7-reporting-2022_puma_production.service not found.

I'm wondering if the --user part of the command is what's causing the issue?
after further testing I can run the command without --user flag on the server.
/usr/bin/env /bin/systemctl restart R7-reporting-2022_puma_production
Multiple identities can be used for authentication:
 1.  user (user)
 2.  deploy user,,, (deploy)
Choose identity to authenticate as (1-2): 2
Password:
==== AUTHENTICATION COMPLETE ===```

Answer: I switched from puma to passenger using the following guide. Great instructions, simple implementation. Props to the writer.
Rails Deploy on Ubuntu using Capistrano


Fabric js Hovering doesn't function

Question: I have few elements (triangles) and I want to be able to highlight(setShadow) them as I hover above each one (mouse:over/mouse:move), and reset highlight when mouse not over.
I tried this, but it doesn't do anything. Below is my code:
var canvas = new fabric.Canvas('canvas');

var petal1 = new fabric.Triangle({
  width: 200,
  height: 300,
  fill: '#DBDBDB',
  left: 500,
  top: 350,
  angle: 200,
  strokeLineJoin: 'round',
  strokeWidth: 20,
  stroke: '#DBDBDB'
});

var petal2 = new fabric.Triangle({
  // same options as above
});

var petal3 = new fabric.Triangle({
  // same options as above
});

  canvas.on('mouse:over', function(e) {
    e.target.set('fill', 'red');
    canvas.renderAll();
  });

  canvas.on('mouse:out', function(e) {
    e.target.set('fill', 'green');
    canvas.renderAll();
  });

canvas.add(petal1, petal2, petal3);

I added console.log(e.target);, but it printed nothing.
Answer: Your snippet works and check target before setting property to it.
DEMO

var canvas = new fabric.Canvas('canvas');
var options = {
  width: 100,
  height: 200,
  fill: '#DBDBDB',
  strokeLineJoin: 'round',
  strokeWidth: 20,
  stroke: '#DBDBDB'
};
var petal1 = new fabric.Triangle(options);
var petal2 = new fabric.Triangle(options);
var petal3 = new fabric.Triangle(options);

canvas.on('mouse:over', function(e) {
  if(e.target){
    e.target.set('fill', 'red');
    canvas.requestRenderAll();
  }
});

canvas.on('mouse:out', function(e) {
  if(e.target){
    e.target.set('fill', 'green');
    canvas.requestRenderAll();
  }
});

canvas.add(petal1, petal2, petal3);
canvas{
  border:1px solid;
}

<canvas id="canvas" width="300" height="300"></canvas>

Fabric js Hovering doesn't function


Função hnp - Pacote hnp do R

Question: O meu modelo foi criado com a função glmer, do pacete lme4. É um modelo linear generalizado misto, com resposta Binomial.
form=status~(A1+A2+  B1 + ... + B10 +  (1 | escola))

Mod1 <- glmer(form, data = dadosesc, family = binomial, control = glmerControl(optimizer =  "optimx", optCtrl=list(method="nlminb")),
        nAGQ = 25)

Sendo status 0 ou 1, A1 e  A2 e escola  categoricas e as demais continuas.
Estou tentando utilizar a função hnp, do pacote hnp, para criar um envelope simulado da seguinte forma
hnp(Mod1, xlab="Half-normal scores", ylab="Deviance residuals", pch=3)

mas está apresentando o seguinte erro:
Error in simulate(object)[, 1][, 1] : incorrect number of dimensions.

Somente consigo quando utilizo uma binomial simples formado com GLM.
Comment: Que esquisito. O modelo parece ter sido bem definido. Teria como editar o post mais uma vez com o resultado de `dput(dadosesc)`? Assim, o teu conjunto de dados seria partilhado conosco e seria possível, para a gente, reproduzir o teu problema.
Comment: Edite a sua pergunta e disponibilize o código utilizado para ajustar o GLMM Binomial. Pode ser que haja uma má especificação do modelo e esta seja a razão do erro. Até onde sei, a função `hnp` trabalha de maneira correta com os objetos da classe glmerMod.
Comment: @MarcusNunes, fiz a alteração sugerida,
Answer: No help da função hnp (páginas 11 e 12 deste documento), você pode ver a lista de modelos que podem ser utilizado. Modelos feitos com o pacote glmer não constam nessa lista.
Pelo help, você pode ver também que é possível construir este gráfico para um modelo não implementado. Neste caso você precisará fornecer três funções:

simfun: simula números aleatórios com a distribuição do modelo
fitfun: ajusta um modelo novamente
diagfun: calcula a medida de diagnóstico para a qual você quer fazer o envelope.

Por exemplo, considere o seguinte banco de dados:
df <- data_frame(
  x1 = runif(100, min = 0, max = 0.5),
  x2 = runif(100, min = 0, max = 0.5),
  y = as.factor(rbinom(n = 100, size = 1, prob = x1 + x2))
)
df
# A tibble: 100 × 3
           x1         x2      y
        <dbl>      <dbl> <fctr>
1  0.05263752 0.44304477      1
2  0.23866105 0.38094325      1
3  0.16474934 0.12541530      0
4  0.47944698 0.46145428      1
5  0.31256457 0.01484219      1
6  0.28411475 0.17338685      1
7  0.34083505 0.35194770      0
8  0.30603019 0.40298573      1
9  0.22193441 0.44697690      1
10 0.36469374 0.34312517      1
# ... with 90 more rows

Neste exemplo y é diretamente relacionado a x1 e x2.
Ajustando um modelo misto neste caso, e rodando a funçãpo hnp obtenho o mesmo erro que você:
fit_glmer <- glmer(y ~ x1 + x2 + (1 | x1), data = df, family = "binomial")
hnp(fit_glmer)
Binomial-normal model
Error in `[.default`(simulate(object)[, 1], , 1) :
  incorrect number of dimensions

Isso acontecxe porque nenhum método está implementado para lidar com objetos do tipo glmer. Vamos então implementar as funções necessárias para a construção do gráfico:
diagfun <- function(obj) {
  resid(obj, type="pearson")
}

simfun <- function(n, obj) {
  as.factor(rbinom(n, size = 1, prob = predict(obj, type = "response")))
}

fitfun <- function(y.) {
  glmer(y. ~ x1 + x2 + (1 | x1), data = df, family = "binomial")
}

Agora você pode chamar a função hnp desta forma:
hnp(fit_glmer, newclass=TRUE, diagfun=diagfun, simfun=simfun, fitfun=fitfun)

Ela produzirá o seguinte gráfico:

Claro, este é apenas um exemplo, você precisará adaptar este código para o seu problema específico. A princípio, acredito que o único lugar que você precisa mexer é na função fitfun. Talvez você precise mexer na função diagfun, se quiser que o tipo de resíduo não seja Pearson por exemplo (vi na legenda do seu gráfico que você usa resíduos deviance).

Função hnp - Pacote hnp do R


2x2 Anova with simple generated data

Question: I have generated data to understand a (repeated measures) 2x2 Anova better, however the results leave me baffled. The data is really simple: I am assuming I have 30 subjects, I am assuming that there are two medical tests, one in body region A, and one in body region B.
I have created now the data as follows:

Test1, region A: normal vector with mean 0.5 and standardeviation of 0.2
Test1, region B: normal vector with mean -0.5 and standardeviation of 0.2
Test2, region A: normal vector with mean -0.5 and standardeviation of 0.2
Test2, region B: normal vector with mean 0.5 and standardeviation of 0.2

This is quite observations we really have: Test1 shows excitation of some substance in region A but inhibition in region B, while Test2 shows excitation of some other substance in region B but inhibition in region A.
Now the results of the ANOVA does show significant interaction of test and body region, however there is no significant main effect of region (p=0.86) - how can that be...? For both tests, the regions have clearly different measurement values.
Help appreciated
Answer: This is sometimes called a cross-over interaction, and if you plot the data you will immediately understand why:

(I generated normally distributed data according to your specified values of mean and SD)
The plot clearly shows that the effect of "region" is in different directions depending on "test". Moreover, the effects not only are in different directions, but they also have the same size. Hence, if you look at the effect of "region" averaged over the two levels of "test" the difference A vs. B would disappear. So the reason why you don't find a significant main effect of "region" (or of "test") is that is not there!
Edit: A main effect of "region" would indicate that there is evidence for a systematic difference between measurements taken in region A and B, regardless of the test used (test 1 vs. test 2). Plotting the same data from the above figure without considering the factor "test" makes it clear that there is no evidence for such difference in the data.
Comment: Yes, the main effect of a factor is computed by integrating over all the levels of the other factors or predictors. If $A_1$, $A_2$ and $B_1$ and $B_2$ are the values of test 1 and 2 in region A and B, respectively, a significant main effect of "region" would indicate that $\frac{{\left( {{A_1} + {A_2}} \right)}}{2}$ is different from $\frac{{\left( {{B_1} + {B_2}} \right)}}{2}$
Comment: Aha, so do I understand correctly that one basically compares 1. average region over test1 to 2. average region over test2? And these averages would be basically 0 in both cases?

2x2 Anova with simple generated data


load routes via component from external api and add them to the router

Question: I would like to load my routes from an external API. Some users might not have the permissions to access a module.
So my navbar makes an API call and gets all the modules returned. These module objects contain the path to the view file.
I tried to create a small sandbox to reproduce the problem
https://codesandbox.io/s/vue-routing-example-i5z1h
If you open this url in your browser
https://i5z1h.codesandbox.io/#/First
you will first get the following error

Url /First not found

but after clicking on the First module link in the navbar, the First view should get rendered.
I think the problem is related to the fact that the page has not yet started the navigation created event after loading and the module page is therefore not found. After changing a router URL the navigation component had enough time to add all the required routes to the router.
How can I load these URLs before the router leads to the first route and responds a 404 error?
Comment: @hrp8sfH4xQ4 See the [difference in behavior](https://hjxj0.codesandbox.io/#/first) when you setup the routes in `router.js`.
Comment: The first answer of this question might help you: https://stackoverflow.com/questions/46341016/how-to-use-addroutes-method-in-vue-router
Solution is basically to initialize the Vue instance after the routes have been loaded
Comment: Thanks Simon but I think the given example uses the same code as I do no? I use `this.$router.addRoutes` too. Would you mind providing an example for `Solution is basically to initialize the Vue instance after the routes have been loaded`
Comment: @hrp8sfH4xQ4 Your router setup is rather unusual. The routes are added lazily in `Navbar.vue`. Why do you setup the routes there instead of in `router.js`?
Answer: The key idea here is to load the routes asynchronously which means you must defer loading of your SPA till that time. In your index.js or main.js, your code would be something like this:
// Some functions are assumed and not defined in the below code.
import Vue from 'vue';
import VueRouter from 'vue-router';

// Application root component
import App from './App.vue';
import { getRoutes } from './api';

// Register Vue plugins
Vue.use(VueRouter);

// Make API call here

// Some animation before the app is fully rendered.
showLoader();

getRoutes(/* Optional User data */)
  .then((routesData) => {
    // Stop the animation
    stopLoader();
    return routesData;
  })
  .then((routesData) => {

    // processRoutes returns an array of `RouteConfig`
    const routes = processRoutes(routesData);

    const router = new Router({
      routes: [
        ...routes,
        {
          path: '*',
          component: NotFound
        }
      ]
    });
  })
  .then((router) => {
    const app = new Vue({
      el: '#app',
      router,
      template: '<App/>',
      components: { App }
    });
  });

Additionally, there are a few things you need to do:

Routing is generally the higher-level concern. So if you consider DIP - Dependency Inversion and the stateful + singleton nature of the router, then it makes sense to bootstrap it at the very beginning. Thus, anything that router needs should be available. This means that the navbar component should not be responsible for making the API call. You must take it out.
Another possible solution is to use $router.addRoutes() method. But it is inadequate for your needs. It will not work considering authorization in mind. It will not prevent navigation.
On a philosophical level, when you are using SPA with client-side routing, then client-side routing is its own source of truth. It is reasonable to know all the routes upfront and hence most routers are designed with this idea in mind. Thus, a requirement like this is a poor fit for this paradigm. If you need something like this, then a server should possess the knowledge of client-side routes and during page refresh, the server should decide what to do - Load the SPA or reject with 404/403 page. And if the access is allowed, the server should inject routing data in the HTML page which will then be picked by Vue.js on the browser side. Many sophisticated SSR - Server-Side Rendering techniques exist to achieve this.

Alternative strategy: Use guards

Define all the routes upfront in your router for all the possible views of all the users.
Define guards for each authorized routes. All these guards would be resolved asynchronously.
Instead of loading routing data from API, use the API to return an Authorization Matrix. Use this API response in your route guards to determine the access.
To prevent calls to the same API multiple times, you can use some sort of caching like Proxy, Memoization, store etc. Generally, for a user, the Auth Matrix will not vary between the calls.

As an advantage of this, you can still load the application partially if required leading to meaningful user experience by reducing the user's time to interact with the application.


How can i extract values from bs4.element.?

Question: So far I managed to make this:
from bs4 import BeautifulSoup
import requests

def function():
    url = 'https://dynasty-scans.com/chapters/liar_satsuki_can_see_death_ch28_6#6'
    soup = BeautifulSoup(requests.get(url).text, 'html.parser')

    script = soup.find_all('script')
    print(script[1])

output:

I'm trying to extract values of "image" as strings
example:    "/system/releases/000/036/945/7.png"
How can I do it ?
Answer: you can use a regular expression to extract the variable "pages"
import re, json, requests

url = 'https://dynasty-scans.com/chapters/liar_satsuki_can_see_death_ch28_6#6'
r = requests.get(url)

# extract the data
match = re.search('var pages = (\[.*?\]);', r.text).group(1)

# parse it into json
match_json = json.loads(match)

# iterate through it to get the links
images = [img['image'] for img in match_json]

output:
['/system/releases/000/036/945/1.png',
 '/system/releases/000/036/945/2.png',
 '/system/releases/000/036/945/3.png',
 '/system/releases/000/036/945/4.png',
 '/system/releases/000/036/945/5.png',
 '/system/releases/000/036/945/6.png',
 '/system/releases/000/036/945/7.png',
 '/system/releases/000/036/945/credits.png']

Comment: You bested me by 1 second. :)
Comment: @Firelord it happens to me all the time :D


How many particular solutions to a second order linear differential equation?

Question: If I have the differential equation
$$y''-y'-2y=3x+2,$$
I can make the guess that a particular solution is of the form
$$y = Ax+B,$$
and determine the coefficients. Do I always have exactly one particular solution (which can be comprised of different additive terms depending on the function on the right side of the differential equation) or can I have more than one particular solution?
Comment: You need two independant solutions for the general solution of the homogeneous ODE. Then, you need to add only one particular solution (any one) of the non-homogeneous ODE in order to obtain it's general solution.
Answer: Suppose $y=A(x)$ and $y=B(x)$ are solutions of $y''-y'-2y=3x+2$, then you can check that $y=A(x)-B(x)$ is a solution of $y''-y'-2y=0$, which is the related homogeneous equation.
So any two different particular solutions differ by a solution of the related homogeneous equation. So you may as well find the simplest solution you can.


Sprite Kit: create centred sprites in grid

Question: I want to create a new sprite in a grid if the field is empty. I also want this new sprite to be centred in the empty field. Let's say the field is:
1 1 1
1 1 0
1 1 1

Whenever I click on one of the fields that is filled with a 1, the sprite disappears (this is what I want and this works fine).
Whenever I click on the 0, a new sprite is added with the following code:
UITouch *touch = [touches anyObject];
CGPoint positionInScene = [touch locationInNode:self];
SKSpriteNode *touchedNode = (SKSpriteNode *)[self nodeAtPoint:positionInScene];
if(touchedNode.position.x == 0) { // x is 0 when I click an empty field, aka background
    [self addThing:positionInScene];
}

And:
-(void)addThing:(CGPoint)newLocation{
    SKSpriteNode *thing = [SKSpriteNode spriteNodeWithImageNamed:@"thing"];
    thing.location = newLocation;

    [self addChild:thing];

    thing.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:thing.size.width/2];
    thing.physicsBody.dynamic = NO;
    thing.physicsBody.categoryBitMask = somethingCategory;
    thing.physicsBody.contactTestBitMask = somethingElseCategory;
    thing.physicsBody.collisionBitMask = 0;

}

However, this sprite is centred in the exact coordinates I click, rather than the centre point of the empty field. How can I make this happen?
Answer: The following creates an N x M grid with a sprite at each row and column. When the user touches one of the sprites, it rotates the sprite and then removes it from the scene. If a sprite is not found at the touch location, a sprite is added there.
#define kBoardMinX      25
#define kBoardMinY      25
#define kNumCols        3
#define kNumRows        3
#define kSpacing        40

-(id)initWithSize:(CGSize)size {
    if (self = [super initWithSize:size]) {
        /* Setup your scene here */

        self.backgroundColor = [SKColor colorWithRed:0.15 green:0.15 blue:0.3 alpha:1.0];

        [self addPiecesToScene];

    }
    return self;
}

// Convert row and col to the appropriate point (in scene coordinates) in the grid
- (CGPoint) pointFromRow:(NSInteger)row andCol:(NSInteger)col
{
    return CGPointMake(kBoardMinX+col*kSpacing, kBoardMinY+(kNumRows-row-1)*kSpacing);
}

// If a sprite is found at (row, col) rotate it, else add a sprite there
- (void) rotatePieceAtRow:(NSInteger)row andCol:(NSInteger)col
{
    SKSpriteNode *node = (SKSpriteNode *)[self nodeAtPoint:[self pointFromRow:row andCol:col]];
    if (node && (SKNode *)node != self) {
        SKAction *rotate = [SKAction rotateByAngle:M_PI*2 duration:2];
        SKAction *remove = [SKAction removeFromParent];
        SKAction *rotateThenRemove = [SKAction sequence:@[rotate,remove]];
        [node runAction:rotateThenRemove];
    }
    else {
        [self addPieceAtRow:row andCol:col];
    }
}
- (void) togglePieceAtTouchLocation:(CGPoint)location
{
    // Convert touch location to row and column
    NSInteger col = (NSInteger)roundf((location.x - kBoardMinX) / kSpacing);
    NSInteger row = kNumRows - (NSInteger)roundf((location.y - kBoardMinY) / kSpacing) - 1;
    // Check if the touch was within the grid
    if (col >= 0 && col < kNumCols && row >= 0 && row < kNumRows) {
        [self rotatePieceAtRow:row andCol:col];
    }
}
- (void) addPieceAtRow:(NSInteger)row andCol:(NSInteger)col
{
    CGSize size = CGSizeMake(32, 32);
    SKColor *color = [SKColor whiteColor];
    SKSpriteNode *node = [SKSpriteNode spriteNodeWithColor:color size:size];
    node.position = [self pointFromRow:row andCol:col];
    [self addChild:node];
}

- (void) addPiecesToScene
{
    for (int row=0;row<kNumRows;row++) {
        for (int col=0;col<kNumCols;col++) {
            [self addPieceAtRow:row andCol:col];
        }
    }
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    /* Called when a touch begins */

    for (UITouch *touch in touches) {
        CGPoint location = [touch locationInNode:self];
        [self togglePieceAtTouchLocation:location];
    }
}


What are the advantages of football boots with blades rather than traditional studs?

Question: Having seen various articles about football managers and coaches who believe bladed football boots to be a safety hazard and knowing that some football teams have banned their use, I was wondering what the supposed advantages of blades are?
Is there an actual advantage to the use of blades rather than studs or is it perhaps more of just a fashion choice by the manufacturer?
Comment: I have never understood the use of blades.  I tried them for soccer, baseball, rugby, and football.  You just feel wobbly on them and then if it rains they stick.  IMO the worst adopted sports gear of all time.  (there have been far worse example that weren't really adopted)
Answer: While the blades do provide better traction than studs due to a larger surface area, the blades are typically preferred on harder ground because there are more points of contact between the bottom of your foot and the ground which disperses the weight more evenly.  Running a lot on hard ground with studs can cause pain in your underfoot and possibly injure some tendons.
Studs are generally preferred in wet conditions where you will sink into the ground.  In this scenario, the studs will not be supporting your weight (you will sink to the sole of your foot). Also, the lack of surface area is beneficial here because your studs will not gather clumps of mud as easily as the blades would.
Answer: I think most of the answers were regarding the long Soft Ground studs as opposed to the conical studs found on something like the Copa Mundials. Both the Copa studs and bladed studs are referred to as Firm Ground studs in most cases. The bladed FG studs provide better traction on the ground whereas the conical studs allow more mobility with quicker realeases. There are hybrids which can be found in both the Nike Tiempos, where you find conical in the front and blades at the back, and on all the new Adidad models, where they have all their studs in a sort of triangular shape.
Answer: The little I know on the matter is that the blades are generally assumed/claimed to have better grip when the pitch is too dry/hard for the studs to have a proper grip on.
I have played both with studs and blades, on amateur leagues, and can't really claim to have a remarkable difference. I would argue that the fit of the shoe is much more significant than the type/shape of the "teeth". That being said I also accept that my knowledge on the subject is rather little, and would like to see a more complete answer, with references.
(great question btw, stands to show that not all equipment questions are off-topic/subjective)
Answer: I prefer screw ins myself, have tried blades, but to be honest, felt more like I was "sliding" or "skating" forwards, whereas I feel more sure footed with screw ins. The main problem with screw ins for me, is stud pressure pain though, when going from changing room to pitch.


how to use ajax with graphql using get method?

Question: I am trying to follow this documentation about django and graphql
https://www.techiediaries.com/django-graphql-tutorial/graphene/
I am only half way to where we can do testing with the graphql view and make our queries.
Then I stopped and trying to do some front end work to make query with ajax
been reading
https://blog.graph.cool/how-to-use-graphql-with-jquery-51786f0a59cb
Even though in that blog, it's using post.  I believe using get shouldn't be too much different.
So I tried making query into a string then JSON.stringify them to pass it over to the backend django but I keep on getting error
this is the error I have
XMLHttpRequest cannot load localhost:8000/graphql/?{"query":"query { allProducts {id sku title description } }"}. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
this is the html + jquery
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title></title>

    <button class="graphql-test">CLICK</button>

Comment: did my answer below solve it for you?
Comment: @MikeGorski no luck :(
Answer: Looks like you need to change your ajax call to include the full URL.
Change
url: 'localhost:8000/graphql/'

To
url: 'http://localhost:8000/graphql/'

Comment: got me going though :D another stupid mistake I had that's why it's not working


Can a process with a stochastic drift be a martingale?

Question: In general, a process with a deterministic non-zero drift cannot be a martingale. What if the process has a stochastic drift, that has an expectation of zero? Could such a process ever be a martingale?
I am aware that the zero expectation of the stochastic drift is not a sufficient condition for the process to be a martingale, but is there a general mathematical theorem or a result that would prove that a process with any non-zero drift  (stochastic or deterministic) cannot be a martingale?
I provide a "counterexample" below (process with a zero-expectation stochastic drift, that is NOT a martingale).
Question: Could anyone either provide an example of a process with a stochastic drift that is a  martingale or alternatively reference a theorem or a result that shows that all processes with a drift can't be martingales?
Let: $$X_t:=\int_{h=0}^{h=t}W_hdh+\int_{h=0}^{h=t}1dW_h=\int_{h=0}^{h=t}W_hdh+W_t$$
We clearly have a zero-expectation drift term with:
$$\mathbb{E}\left[\int_{h=0}^{h=t}W_hdh+\right]=\int_{h=0}^{h=t}\mathbb{E}[W_h]dh=0$$
And in fact we have that:
$$\mathbb{E}[X_t|\mathcal{F}_0]=X_0$$
But, $\forall 0< s <t$:
$$\mathbb{E}[X_t | \mathcal{F}_s]=\mathbb{E}\left[\int_{h=0}^{h=s}W_hdh+\int_{h=s}^{h=t}W_hdh+W(t-s)+W(s) \mid \mathcal{F}_s\right]=\\=\int_{h=0}^{h=s}W_hdh+W_s+\mathbb{E}\left[\int_{h=s}^{h=t}W_hdh+W(t-s) \mid \mathcal{F}_s\right]=\\=X_s+\int_{h=s}^{h=t}\mathbb{E}[W_h|\mathcal{F}_s]dh=\\=X_s+W_s\int_{h=s}^{h=t}dh=\\=X_s+W_s(t-s)\neq X_s$$
So $X_t$ is not a martingale.
Comment: If $X=Y+Z$ is martingale with $Z$ a martingale and $Y$ a drift, then $X-Z=Y$ is also martingale. But martingale that's of finite variation is? Do you know something telling you that such martingales are of specific type?
Comment: @user408858 no instead bound it by the full integral of the absolute value. That is finite by definition of being integrable.
Comment: An integrable function need not to be bounded. What you are using does not always work, while the integral bound does work.
Comment: @JanStuller: Do you want a proof in an answer or is Shashi's comment enough? (Although his comment is practically a proof)
Comment: @UBM: if you can post an answer with a proof, I will happily up vote & accept :)
Comment: @Shashi: UBM already provided a great answer. However, I forgot, why the process $A_t:=\int_0^ta_udu$, which he defines below is of finite variation. Could please explain? I think there was a theorem, which states that a stochastic integral with a integrator of finite variation, is from finite variation itself. Is this true? Thank you in advance!
Comment: Literally write the definition of being bounded variation and use triangle inequality.
Comment: @Shashi: Is the following right? In the case that $a_u$ is continuous in $u$:$\sum_i|\int_0^{t_i}a_udu-\int_0^{t_{i-1}}a_udu|=\sum_i|\int_{t_{i-1}}^{t_i}a_udu|\le\sum_i\int_{t_{i-1}}^{t_i}|a_u|du\le t \max_{u\in [0,t]} |a_u| <\infty $ for all $t\ge 0$.
Comment: Ok, but this is almost the same, isn't it? $\int_0^t |a_u| du\le \max_{u\in[0,t]}|a_u| \int_0^t du = t \max_{u\in[0,t]}|a_u|$. But, of course, if $a_u$ is integrable, then $\int_0^t |a_u| du <\infty$ would be a bound, too.
Answer: I will prove it for an Ito process of the type
$$X_t = X_0 + \int_0^ta_udu + \int_0^tb_udW_u, \quad 0 \leq t \leq T. \tag{1}$$
We will need the following two theorems.
Theorem 1. Let M and N be local martingales. Then the sum $M+N$ is also a local martingale.
Theorem 2. Let $c \mathscr{M}_{0,loc}$ denote the space of continuous
local martingale that starts at zero. Let $M \in c \mathscr{M}_{0,loc}$ be of finite variation. Then $M \equiv 0$ a.s.
Answer: Let $X$ be a continuous local martingale of the type SDE(1). Then the drift must be zero.
Proof.
We know the process $\int_0^t b_udW_u, 0 \leq t \leq T,$ is a continuous local martingale. Then the process
$$A_t := \int_0^ta_udu= X_t - X_0  - \int_0^tb_udW_u, \quad 0 \leq t \leq T $$
is a sum of continous local martingales and, by Theorem 1, is also a continuous local martingale. Also, note that $A_0 = 0,$ so $A \in c \mathscr M_{0,loc}^2.$  But the process $A$ is of finite variation, so by Theorem 2, must be zero. This is the same as saying that $\int_0^ta_udu=0$ for all $0 \leq t \leq T.$ Since this integral is defined path by path, by elementary calculus we have that $a_t = 0$ for all $0 \leq t \leq T.$


Can the IntelliJ IDEA run tab have color?

Question: I am running a spring boot application inside IntelliJ IDEA and noticed a difference if I run it via the run tab (run menu) and via manual command from the terminal tab.
If I run it through a maven run target (play button), I do not see any colors inside the 'run' tab. If I run it via 'mvn spring-boot:run from the 'terminal' tab I see the pretty color highlights. The maven run configuration also runs the same command, spring-boot:run.
Application started from the play button/run configuration (run tab):

Application started from the terminal tab via mvn spring-boot:run (terminal tab):
Answer: Inside build.gradle, add the following block to get colorized log output when running your Spring Boot app inside IntelliJ IDEA via gradle bootRun.
bootRun {
    jvmArgs = ["-Dspring.output.ansi.enabled=ALWAYS"]
}

Answer: It's supported for the Spring Boot Run/Debug configuration type. It explicitly passes
-Dspring.output.ansi.enabled=always

JVM option enabling the color output.
As far as I know, ANSI colors support is not available when you run it in IntelliJ IDEA using Maven or Gradle configurations in the built-in console. Feature request is welcome.
Comment: Best answer, but not completly right about the Maven/Gradle integration: I think you can always add the System Property mentioned above to your VM arguments, so Maven and Gradle configurations will also become colorful ;-)
Answer: In IDEA 2017.1 EAP I'm getting colours even if I'm just running the application with the standard run command

Edit:
Might be that Community edition doesn't support Spring Boot at all (https://www.jetbrains.com/idea/features/editions_comparison_matrix.html)
Comment: Yes, I knew it doesn't support it officially, but it's strange the colors don't show up in the run window and they do in the Terminal :) Just verified that they also don't show up in the Ultimate edition for a Maven or Application run configuration. Only way to get them is to run through a Spring Boot configuration in Ultimate or through Maven in the Terminal tab.
Comment: Is that a Spring or Spring Boot run configuration type? I am on the Community Edition and that run configuration type is not available. I can only run the project through Maven (spring-boot:run) or the main method like any Java regular application. Do you still see the colors in the run tab if you start the application as mentioned above?
Comment: It's Spring Boot, that's what's automatically generated from the when I press  Shift+Ctrl+F10. And I'm running Ultimate edition, but for the EAP I think they are the same.
Comment: Unfortunately they are also separate and there is a Community Edition EAP version. I guess I can try the Ultimate version in trial mode to see if that is the issue. If it is, that's really strange that they would enforce this on purpose--no color on Maven/Java Application run configurations in the run tab.
Comment: See my edit, I think you're right about the community edition.
Answer: You can obtain the very same output also in the Community Edition with the previously mentioned option:
-Dspring.output.ansi.enabled=always

Simply go to "Run" -> "Edit Configurations..." and add the option in the "VM options:" field for your main class.


Layout detail node + ckeditor layout

Question: When I create a node of content type Proposal like this:

I can add images, paragraphs, ... . But it looks like this on the detail page of the node:

No image, no paragraphs, ... . What could be the problem of this?
I'm using the Filtered html text format. When I check the html of the paragraph there is no image, nothing. Just text ... .
These are my settings of context filter filtered html:
Comment: Have a look at Limit allowed HTML tags, maybe img, p, etc is not allowed tags?
Comment: Have a look at your text filter, see this post for reference http://stackoverflow.com/questions/8069162/drupal-media-wysiwyg-ckeditor-inserting-image-issues
Comment: I don't get that option that they suggest, and I also don't the image (html) in my source.
Comment: Could you edit your question with the name of the text filter you use on your field and the settings of that text filter that is found under admin/config/content/formats?
Comment: updated my topic
Comment: That was the problem! The img tag wasn't allowed. Thanks!
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/16422/discussion-between-pontus-nilsson-and-nielsv).
Answer: Have a look at Limit allowed HTML tags in the setting for your text filter. Make sure img is among the allowed HTML tags.
The settings are found under admin/config/content/formats.

Layout detail node + ckeditor layout


MySQL vs SQLite on Amazon EC2

Question: I have a Java program and PHP website I plan to run on my Amazon EC2 instance with an EBS volume. The program writes to and reads from a database. The website only reads from the same database.
On AWS you pay for the amount of IOPS (I/O requests Per Second) to the volume. Which database has the least IOPS? Also, can SQLite handle queries from both the program and website simultaneously?
Comment: How big is the database?  If you can cache the whole thing in memory for the web (read-only) side you can almost eliminate I/O on that side.  You could do that in the server code or using an in-memory SQLite database.
Comment: The Java app would work against a database on disk.  The web app would cache that database in memory, either updating periodically or receiving instructions from the Java app when something needed to be updated in memory.  Would probably work at 1GB but probably not at 5GB.
Comment: The database will be about 1-5GB. If it's in the memory of the Java application, how would the webserver access it?
Answer: The amount of IO is going to depend a lot on how you have MySQL configured and how your application uses the database. Caching, log file sizes, database engine, transactions, etc. will all affect how much IO you do. In other words, it's probably not possible to predict in advance although I'd guess that SQLite would have more disk IO simply because the database file has to be opened and closed all the time while MySQL writes and reads (in particular) can be cached in memory by MySQL itself.
This site, Estimating I/O requests, has a neat method for calculating your actual IO and using that to estimate your EBS costs. You could run your application on a test system under simulated loads and use this technique to measure the difference in IO between a MySQL solution and a SQLite solution.
In practice, it may not really matter. The cost is $0.10 per million IO requests. On a medium-traffic e-commerce site with heavy database access we were doing about 315 million IO requests per month, or $31. This was negligible compared to the EC2, storage, and bandwidth costs which ran into the thousands. You can use the AWS cost calculator to plug in estimates and calculate all of your AWS costs.
You should also keep in mind that the SQLite folks only recommend that you use it for low to medium traffic websites. MySQL is a better solution for high traffic sites.
Comment: as of 2016, sqlite handles volume really well. For high traffic sites, we did get lock errors quite a bit and had to use WAL (write ahead log `pragma journal_mode = WAL`)  along with a daily cron to checkpoint databases (to prevent runaway wal files)
Answer: Yes SQLite can handle queries from both the program and website simultaneously. SQLite uses file level locking to ensure consistency.
In memory SQLite is intended for standalone or embedded programs.
Do not use in memory only SQLite:

when you share the db between multiple processes
when you have a php based website in which case you won't be able to leverage php fastcgi

MySQL vs SQLite on Amazon EC2


Criando uma especie de falso clique

Question: Bom, eu tenho um box, esse box tem algumas abas, clicando na aba o conteúdo do box muda. O conteudo é alterado quando clico em um dos links que chama a aba. Eis o codigo:

    3º Passo
    2º Passo
    1º Passo

      Conteúdo que aparece ao clicar no link 1º passo

      Conteúdo que aparece ao clicar no link 2º passo

      Conteúdo que aparece ao clicar no link 3º passo

Então, o conteúdo do box muda somente quando clica em cima de alguns dos links que estão dentro do p id="slid", e eu gostaria de automatizar isso, fazendo com que mesmo que se não clicar em nenhum desses links o conteúdo do box se altere como se tivesse clicado.
O script que uso pra fazer a alteração do conteúdo do box é:
$.quickslidl = function ()
  {
    /* Elements */
    var slidl = 'p#slid';
var cont_slid = 'ul#slidcontents';

/* Hide all post */
    $(cont_slid + ' li').hide();

/* Display the first tab */
    $(cont_slid + ' li:first-child').show();

/* When user click a tab */
    $(slidl + ' a').click(function()
{
        /* Remove slidselected class on all post */
        $(slidl + ' a').removeClass('slidselected');

        /* Add a slidselected tab class */
        $(this).addClass('slidselected');

        /* Hide all opened tags */
        $(cont_slid + ' li').hide();

        /* Display the clickec tab */
        $(cont_slid +  ' ' + $(this).attr('href')).show();
        /* End :D */
    return false;
});
};

/* When all is ready */
$(document).ready(function()    {
/* Start function */
$.quickslidl();

});

Answer: Teste assim:
$(document).ready(function () {
    var galeria, i = 0;
    var links = $('#slid a').get().reverse();
    var slides = $('#slidcontents li');
    $(links).on('click', function (e) {
        e.preventDefault();
        slides.removeClass('mostrar');
        slides.eq(links.indexOf(this)).addClass('mostrar');
        if (e.which) clearInterval(galeria);
    });
    galeria = setInterval(function () {
        i++;
        $(links).eq(i).click();
        if (i == links.length) i = 0;
    }, 1000);
});

Exemplo: http://jsfiddle.net/E84UF/
Teste assim:
$(document).ready(function () {
    var galeria, i = 0;
    var links = $('#slid a').get().reverse();
    var slides = $('#slidcontents li');
    $(links).on('click', function (e) {
        e.preventDefault();
        slides.removeClass('mostrar');
        slides.eq(links.indexOf(this)).addClass('mostrar');
        if (e.which) clearInterval(galeria);
    });
    galeria = setInterval(function () {
        $(links).eq(i).click();
        i++;
        if (i == links.length) i = 0;
    }, 1000);
});

Exemplo: http://jsfiddle.net/E84UF/1/
O código em cima tem duas partes. A parte que trata do clic e faz mudar o
, e em baixo um setInterval que dispara clics programáticos nos elementos e assim fazendo a primeira parte correr. Para distinguir o clic real do falso usei if (e.which) clearInterval(galeria);. Assim um clic real faz parar o slide.
Comment: @ivanveloso, tem razão tinha uma linha trocada. Aqui: http://jsfiddle.net/E84UF/1/
Comment: @ivanveloso fazer a transição fica um pouco mais complexo, tem de criar elementos que estão por cima uns dos outros e fazer transição da `opacity`
Comment: Funciono perfeitamente.
Comment: Só mais uma pergunta. Na hora do loop, ele nunca volta pro primeiro link, volta sempre pro segundo. Porque isso? Ate no seu exemplo ele faz isso. Ele começa no link 1, vai pro link 2 depois pro 3 e pula pro segundo link de novo
Comment: Ah, como eu poderia teria como aplicar também efeito de transição no script, eu já tentei mas não fui bem sucedido.
Comment: Ta tranquilo, precisa da transição não, só de mudar já ta otimo. Aqui, porque que quando se clica em cima de um dos links o efeito para de funcionar e ele só voltar a funcionar se da refresh na pagina?
Comment: @ivanveloso, ele para de rodar porque eu escreví isto nó código: `if (e.which) clearInterval(galeria);` se tirar já não pára.
Answer: Você pode usar o event.preventDefault() do JQuery, que vai remover o comportamento padrao daquele link (que seria ir para uma url ali definida no atributo href da tag a) e adicionar seu comportamento customizado. Voce criaria handlers para os seus links (por meio dos ids deles ou pegando qualquer tag de link mesmo se preferir como mostra o exemplo abaixo).
Veja exemplo de uso abaixo:
<!doctype html>

  <meta charset="utf-8">
  <title>event.preventDefault demo</title>

default click action is prevented

Mais informações sobre este comando: http://api.jquery.com/event.preventdefault/
E você criar ações de click usando o comando click() do Jquery tambem
$( "#other" ).click(function() {
  $( "#target" ).click();
});

Mais informações sobre o comando click(): http://api.jquery.com/click/
A funcionalidade do cronometro você pode implementar usando a função setInterval, que seria chamada a partir do handler adequado. Um exemplo de uso bem simples segue abaixo:
//exibe um alert na tela a cada 5 segundos
setInterval(function(){alert(" Teste do cronometro ")}, 5000);

Mais exemplos de uso do setInterval veja aqui: http://www.w3schools.com/jsref/met_win_setinterval.asp
Comment: Mas e a questao do tempo? como posso fazer?
Comment: a questao do tempo voce resolve usando setTimeInterval (função nativa do JavaScript)
Comment: e no seu caso,  a função setTimeInterval seria chamada a partir de um dos seus handlers jquery =)
Comment: vou adicionar isso na resposta pra ela ficar mais completa ;-)
Comment: Não funciono muito bem (ou eu que não consegui aplicar)... Vou reeditar a pergunta pra voce entender melhor.
Comment: se puder mostrar o código que tentou, fica mais fácil de ajudar =)
Comment: Pergunta reformulada

Criando uma especie de falso clique


Check if session variable is defined

Question: I need to count the number of views. I am using a session variable to avoid duplicate count. I need to check if session view_count isset  and then it is set to  false and increment the view  count
$currentPost = Post::where('slug',$slug)->first();
$comments =  \App\Comment::where('post_id',$currentPost->id)->get();

if(\Session::get('view_count')) {
    \Session::put('view_count', false);
    $currentPost->view_count = $currentPost->view_count + 1;
    $currentPost->save();
}

Comment: Your logic assumes that the user is viewing just a single post. How do you intend to handle view count for a different post or a new session is created by the same user?
Answer: Can't you just do
if (Session::has('your_key'))
{
  //your code here
}

Update answer
Determining If An Item Exists In The Session
To determine if an item is present in the session, you may use the has method. The has method returns true if the item is present and is not null:
if ($request->session()->has('users')) {
    //
}

To determine if an item is present in the session, even if its value is null, you may use the  exists method. The exists method returns true if the item is present:
if ($request->session()->exists('users')) {
    //
}

Comment: How to check if it has not  key
Comment: I explain more comfortable for you
Comment: $request  is not defined in the method
Comment: Use Request $request in controller function on top put  use Illuminate\Http\Request;
Answer: I am assuming you want to check whether a visitor has viewed a certain blog post, in which case, I'd probably do something like this.
$currentPost = Post::where('slug', $slug)->first();

// You should also probably set up your relationship with Comments
$comments = \App\Comment::where('post_id', $currentPost->id)->get();

if(! in_array($currentPost->id, session()->get('posts_viewed', []))) {
    session()->push('posts_viewed', $currentPost->id);

    // Your increment could also be simplified as follows
    $currentPost->increment('view_count');
}

In your particular case, you will only be able to track whether the user has viewed one particular blog post. However, if you use an array and keep pushing viewed blog posts into it, you would be able to track views across many blog posts.

Check if session variable is defined


Flutter wrapping Row in SingleChildScrollview ruins spaceBetween

Question: I have aRow of buttons which have a parent of SingleChildScrollView, horizontally.
After wrapping the SingleChildScrollView the elements of the row don't respect the mainAxisAlignment, specifically spaceBetween, they are together with not space in between...
How can I make the spaceBetween work again?
SingleChildScrollView(
  scrollDirection: Axis.horizontal,
  child: Row(
    mainAxisAlignment: MainAxisAlignment.spaceBetween,
    mainAxisSize: MainAxisSize.max,
    children: const [
      TransportModeButton(
        iconPath: 'images/icons/walking_icon.png',
        text: 'Walking',
      ),
      TransportModeButton(
        iconPath: 'images/icons/bicycle_icon.png',
        text: 'Bike & eScooter',
      ),
      TransportModeButton(
        iconPath: 'images/icons/public_transport_icon.png',
        text: 'Public transport',
      )
    ],
  ),
),

Comment: Try to wrap your `TransportModeButton` inside `Expanded` or `Flexible` Widget hope its help to you.
Comment: Unfotunately it doesn't work... I get an width constrainsts are unbounded error...
Answer: you can solve it by wrapping your Row inside a BoxConstraints like:
Container(
        child: SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: ConstrainedBox(
              constraints: BoxConstraints(
                maxWidth: MediaQuery.of(context).size.width,
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                mainAxisSize: MainAxisSize.max,
                children: const [
                  Text("test1"),
                  Text("test2"),
                  Text("test3"),
                ],
              ),
            )),
      ),

Edit:
to get the constraints from the parents for your SingleChildsScrollView you can do so using LayoutBuilder, so the code would look like:
LayoutBuilder(
                builder: (BuildContext context, BoxConstraints constraints) {
              return SingleChildScrollView(
                  scrollDirection: Axis.horizontal,
                  child: ConstrainedBox(
                    constraints: BoxConstraints(
                      maxWidth: constraints.maxWidth,
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      mainAxisSize: MainAxisSize.max,
                      children: const [
                        Text("test1"),
                        Text("test2"),
                        Text("test3"),
                      ],
                    ),
                  ));
            })

Comment: You're right that only solves the problem in the example, I think the only solution would be to generate spacing while building, or even by adding padding or margin to the children.
Comment: if you limit the width to the width of the screen , why even use SCSV?
Comment: did you set the `maxWidth` ?
the above code  would give you something like below, I tested it on DartPad.

https://drive.google.com/file/d/1EEU7LixVT5ad_SBwGu0iJx6vnumRqkFR/view?usp=sharing
Comment: I edited the solution to solve this issue
Comment: It seems that adding
BoxConstraints(
                        minWidth: constraints.maxWidth)

makes it work again
Comment: Nothing happens if I add the ContrainedBox... Still no space between
Comment: Yeah sorry, I would need to somehow make a ConstrainedBox with the width of the parent and not of the entire context... I get some space between but to much...
Comment: @tareqalbeesh I just noticed now that doing this causes the scroll to fail, so If I resize my window to make that widget scrollable, then it just gives me an overflow without making it scrollable, it's like not having SCSV
Comment: Yea, please replace "maxWidth: constraints.maxWidth" by "maxWidth: constraints.minWidth," in the example above.
Answer: When you wrap your Row with SCSV, there is actually no width to the row, since it is infinite.
It does not rely on the width of the screen or any other width of to calculate the space between.
If you really want to enable the space between I would suggest 2 ways:

To wrap the Row with a Container/SizedBox/BoxConstraints and give it a width.
To add SizedBox / wrap your TransportModeButton with Padding, which will create the spaces, manually, between the buttons.
Answer: Row/Column takes as much space as needed, meaning it can go beyond available height if need be and if there are no constraints.
Your row is taking the needed space and not more. Hence, the MainAxisAlignment is actually working(but not how we want to). Put a SizedBox with width for a space if you want.
My advice is provided is use ListView if you know how many widgets are available and if you're not using the whole screen for this only.
Single Child Scroll View
Scaffold(
  appBar: AppBar(),
  body: SafeArea(
    child: SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: const [
          Icon(
            Icons.nordic_walking,
            size: 50,
          ),
          SizedBox(
            width: 20,
          ),
          Icon(
            Icons.nordic_walking,
            size: 50,
          ),
          SizedBox(
            width: 20,
          ),
          Icon(
            Icons.nordic_walking,
            size: 50,
          ),
          SizedBox(
            width: 20,
          ),
          Icon(
            Icons.nordic_walking,
            size: 50,
          ),
          SizedBox(
            width: 20,
          ),
          Icon(
            Icons.nordic_walking,
            size: 50,
          ),
          SizedBox(
            width: 20,
          ),
          Icon(
            Icons.nordic_walking,
            size: 50,
          ),
          SizedBox(
            width: 20,
          ),
          Icon(
            Icons.nordic_walking,
            size: 50,
          ),
          SizedBox(
            width: 20,
          ),
          Icon(
            Icons.nordic_walking,
            size: 50,
          ),
          SizedBox(
            width: 20,
          ),
          Icon(
            Icons.nordic_walking,
            size: 50,
          ),
          SizedBox(
            width: 20,
          )
        ],
      ),
    ),
  ),
);

ListView
Scaffold(
  appBar: AppBar(),
  body: SafeArea(
    child: ListView(
      scrollDirection: Axis.horizontal,
      children: const [
        Icon(
          Icons.nordic_walking,
          size: 50,
        ),
        SizedBox(
          width: 20,
        ),
        Icon(
          Icons.nordic_walking,
          size: 50,
        ),
        SizedBox(
          width: 20,
        ),
        Icon(
          Icons.nordic_walking,
          size: 50,
        ),
        SizedBox(
          width: 20,
        ),
        Icon(
          Icons.nordic_walking,
          size: 50,
        ),
        SizedBox(
          width: 20,
        ),
        Icon(
          Icons.nordic_walking,
          size: 50,
        ),
        SizedBox(
          width: 20,
        ),
        Icon(
          Icons.nordic_walking,
          size: 50,
        ),
        SizedBox(
          width: 20,
        ),
        Icon(
          Icons.nordic_walking,
          size: 50,
        ),
        SizedBox(
          width: 20,
        ),
        Icon(
          Icons.nordic_walking,
          size: 50,
        ),
        SizedBox(
          width: 20,
        ),
        Icon(
          Icons.nordic_walking,
          size: 50,
        ),
        SizedBox(
          width: 20,
        ),
      ],
    ),
  ),
);

Comment: I need a constrainedBox that inherits it's width from the parent and not the width of the entire context
Answer: No need to use singlechildscrollview(SCSW) to counter the spacing scenario. It seems like a bad Ux for users to scroll the tile. You can let flow vertically using something like softwrap. If you still want to use SCSW then you can try to put constraints on SCSW by wrapping the child of SCSW in ConstrainedBox.
constraints: BoxConstraints(maxWidth: MediaQuery.of(context).size.width)
Comment: I need a constrained box with the size of the parent... Which is actually a flexible column


How to rsync a list of files from current directory to the home directory of a remote user?

Question: I want to deploy a list of file from inside a file let's say files.lst:
+ .profile
+ .hg/hgrc
+ .mc/*
- /*

rsync -vvltr . --include-from 'files.lst' . destdir

Desired behaviour:

copy recusively all the files and directories from .mc
copy only .hg/hgrc file to destination, ignoring other files that could exist in that directory
copy .profile
Comment: Could you define `doesn't work proper`? Wrong files? To many files? Wrong location?  Because the `--include-files file.LIST` // `--include FILE` is the way to go.
Comment: Did you really ask anyone in here to test before post? Is this a joke?!
Comment: You mean `john@server:` right?  Otherwise, it would try to sync to a directory called 'john@server' and fail.
Comment: @pfo it wasn't a joke, it's so easy to add a meaningless comments instead of verifying that what you think really works.
Comment: -1 for thinking this was an "Average User" site.
Answer: Finally, I managed to make it working, definitely I would never recommend rsync to any average PC user (the one that never heard of man or SF).
+ .profile
+ .mc
+ .mc/***
+ .hg
+ .hg/hgrc
- /***

Explanations:

you need to specify the directory first because otherwise it skip them
the last line tells rsync to exclude everything that wasn't explicitly included.
Comment: I would recommend `rsync` to any Linux/UNIX system user for this purpose, it's a fantastic tool.  Like most fantastic tools, it requires some patience and learning.
Comment: Dude, you have an attitude problem which we call trolling, `man` was the first thing I opened and it does not include information about the patters and how they work. Instead I managed to find the solution on another question on SF, but after spending too much time for a simple problem like this.
Comment: You mean any average user who doesn't know how to RTFM.
Comment: What would you recommend? Windows Exploder?
Comment: I must agree with @SorinSbarnea: Only above-average people use `rsync`. ;-) .
Comment: That is odd the rsync man page on my system has a large section called `INCLUDE/EXCLUDE PATTERN RULES`. That section it also happens to be in the web-based man page which you find if you search for `man rsync`.  http://linux.die.net/man/1/rsync
Comment: I was agreeing with you that a lazy user is probably not a good candidate for this utility. I do not believe it is above anyone who is willing to read the manual to figure out the rest. Knowing the ins and outs of rsync should be in the toolbelt of almost anyone who considers themselves an IT professional or systems engineer. Now as for going back and down voting some of my previous answers... yeah that's not cool, but do what you like.
Answer: You want the --files-from option.
rsync --files-from=files.lst destination:/location/
man rsync


AMC 2011 Coloring Problem

Question: A 40 X 40 white square is divided into 1 X 1 squares by lines parallel to its sides. Some of these 1 X 1 squares are coloured red so that each of the 1 X 1 squares, regardless of whether it is coloured red or not, shares a side with at most one red square (not counting itself). What is the largest possible number of red squares?
What I did is as following(R is red, w is white), There are only 400 red squares. The answer should be more. (Sorry, the previous diagram was wrong, I missed every empty White lines. Now I fixed it. ):
RRwwRRwwRRww...RRww
wwwwwwwwwwww...wwww
wwRRwwRRwwRR...wwRR
wwwwwwwwwwww...wwww
RRwwRRwwRRww...RRww
wwwwwwwwwwww...wwww
wwRRwwRRwwRR...wwRR
...................
RRwwRRwwRRww...RRww
wwwwwwwwwwww...wwww
wwRRwwRRwwRR...wwRR
wwwwwwwwwwww...wwww
Comment: But the 3rd square in the top row borders two red squares, doesn't it?
Comment: Welcome to MSE. Your question is phrased as an isolated problem, without any further information or context. This does not match [many users' quality standards](http://goo.gl/mLWc8), so it may attract downvotes, or be put on hold. To prevent that, please [edit] the question. [This](http://goo.gl/PlJyVQ) will help you recognise and resolve the issues. Concretely: please provide context, and include your work and thoughts on the problem. These changes can help in formulating more appropriate answers.
Comment: You can't have two red squares that touch diagonaly.
Comment: You can colour the bottom-left square red, for $401$. But I have no idea whether this is maximal.
Comment: There are $40\times40=1600$ squares all told, right? And you're coloring half of them red, right? So, that's $800$, not $400$, isn't it?
Comment: Sorry, the previous diagram was wrong, I missed every empty White lines. Now I fixed it.
Comment: I took the liberty of changing your W's to lower-case w's. I think you will agree it's easier to follow.
Comment: I've posted a solution below. Is it true that this problem came from a 2011 math competition? Which one? Would it be possible to look up a reference to this competition online?
Answer: User Samwise posted a solution with $420$ red squares at this Yahoo link 9 years ago. The idea is to start at the top left, and write the pattern R R w w in a spiral, leaving a blank row between consecutive turns of the spiral. Here it is for a $16\times 16$ board:
R R w w R R w w R R w w R R w w    8
. . . . . . . . . . . . . . . R    1
w w R R w w R R w w R R w w . R    7
R . . . . . . . . . . . . R . w    2
R . w w R R w w R R w w . R . w    6
w . R . . . . . . . . R . w . R    3
w . R . w w R R w w . R . w . R    5
R . w . R . . . . R . w . R . w    4
R . w . R . w . . R . w . R . w    4
w . R . w . R R w w . R . w . R    5
w . R . w . . . . . . R . w . R    3
R . w . R R w w R R w w . R . w    6
R . w . . . . . . . . . . R . w    2
w . R R w w R R w w R R w w . R    7
w . . . . . . . . . . . . . . R    1
R R w w R R w w R R w w R R w w    8

On the right are the numbers of red squares in each row. They add up to $8\cdot 9=72$ (note that the odd-numbered rows decrease from $8$ to $1$, and the even-numbered rows increase from $1$ to $8$). For a $40\times 40$ board, we get $20\cdot 21=420$ red squares.
In fact this procedure works for a square board of any size. Here it is for a $9\times 9$ board:
R R w w R R w w R    5
. . . . . . . . R    1
w w R R w w R . w    3
R . . . . . R . w    2
R . w w R . w . R    3
w . R . . . w . R    2
w . R w w R R . w    3
R . . . . . . . w    1
R w w R R w w R R    5

There are $25$ red squares. In general, for an even-sized board of size $2n$ we get $n(n+1)$ red squares; and for an odd sized board of size $2n+1$ we get $(n+1)^2$ red squares if $n$ is even and $n(n+2)$ if $n$ is odd.
It still remains to be shown whether these patterns are the best possible.
Comment: Thank you for posting this! Below, I've posted a solution that shows that the number of red squares must be strictly less than $421$. If you hadn't posted your solution, I may not have been able to get this problem. Thank you!
Comment: Amazing solution
Comment: Looking at this in the cold light of day, it might have been simpler if I had drawn those figures as concentric squares. Oh well, I'm not going to change it now.
Answer: In a separate answer, user TonyK has shown that it is possible to have as many as $420$ red squares on the board, and that it remains to show that the number of red squares is strictly less than $421$. Below I will complete the proof by showing that the number of red squares must be strictly less than $421$. To see how it is possible to have $420$ red squares, you can look at user TonyK's answer, or you can click the link in his answer, which will take you to this website on Yahoo.
Suppose we have a $40\times40$ white board, and we color some of the squares red, so that each square shares a side with at most one red square. Let $R$ be the number of red squares. It has been shown that there is a way of doing this with $R=420$. Our goal is to show that $R<421$.
Since the board is $40\times40$, the board consists of $1600$ $1\times1$ squares. Let $\mathcal{S}$ be the set of all $1600$ of these $1\times1$ squares. For each $x\in\mathcal{S}$, let $f(x)$ be the number of red squares that share a side with $x$. We'll start be examining the sum
$$\sum_{x\in\mathcal{S}}f(x).$$
The number of times a red square is counted in this sum depends on whether the red square is a corner square, an edge square, or an interior square. So let $C$ be the number of red corner squares. Let $E$ be the number of red edge squares, and let $I$ be the number of red interior squares. In the above sum, red corner squares are counted twice; red edge squares are counted three times, and red interior squares are counted four times. Hence
$$\sum_{x\in\mathcal{S}}f(x)=2C+3E+4I.$$
Since each squares shares a side with at most one red square, we have that $f(x)\le1$ for each $x\in\mathcal{S}$. So
$$\sum_{x\in\mathcal{S}}f(x)\le1600.$$
Hence $2C+3E+4I\le1600$. We want to maximize $R=C+E+I$ subject to the constraint that $2C+3E+4I\le1600$. We haven't gotten enough information yet to show that $R<421$ so we will have to examine the problem further to come up with some additional constraints.
We can get the constraints we need by considering the squares on the border of the board, i.e. the corner and edge squares. In user TonyK's answer, it is shown that is possible to have as many as $78$ red squares on the border. This is done by working your way around the border, coloring two squares red and then leaving two squares white, until half the border is red. If the border had more than $78$ red squares, then it follows from the pigeon-hole principle that there would be $4$ consecutive border squares, $3$ of which are red, which would contradict the fact that no square shares a side with more than one red square. Hence $C+E\le78$.
For our last constraint, we can use the fact that there are four corners. So $C\le4$.
So we want to maximize
$$R=C+E+I$$
given that
$$2C+3E+4I\le1600$$
$$C+E\le78$$
$$C\le4$$
$$C,E,I\ge0.$$
Readers familiar with linear programming will recognize that this a problem that can be solved with the simplex method. However, our goal is just to show that $R<421$, which can be done without the simplex method. If we add the the three $\le$ constraints, we get that $4C+4E+4I\le1682$.
Hence $R=C+E+I\le\frac{1681}{4}=420.5.\;$ So $R<421$. $\;\square$
Acknowledgments: I would like to thank user TonyK for showing me that it was possible to have $R=420$. Without his help, I may not have been to get this problem. I would also like to thank user Rob Pratt, who provided a substantial simplification.
Closing Remark: If we modify the problem slightly, then the configuration mentioned in the original problem will in fact be optimal. Suppose that the original $40\times40$ board were inscribed on a torus instead of a just a $40\times40$ square. Now the squares on the bottom row share sides with squares on the top row, and squares on the leftmost column share sides with squares on the rightmost column. It follows that
$$\sum_{x\in\mathcal{S}}f(x)=4R.$$
Hence $R\le400$. So the configuration mentioned in the original problem would be optimal.
Comment: Alternatively, multiply each of the three $\le$ constraints by 1/4 and add them up, yielding $C+E+I \le 420.5$.
Comment: @RobPratt Wow! That's a huge improvement! Thank you!
Comment: Great complement.
Comment: And I thank you for finishing this off.

AMC 2011 Coloring Problem


Citrix XenApp 6, cannot connect to licenceserver

Question: i try to install Citrix XenApp, first install Webinterface und XenApp to one Server and licence-manager to an other server. I can connect to Port 27000 on licenceserver with telnet and can go to Webinterface from licence-server. On the XenApp Server i run Delivery Service Console and check the policy Licenceserverhost and port.
When i connect to XenApp Server i get the message cant connect to licence server. But i don't know why, can anyone tell me how i can debug this. On the licenceserver there are no errorlogs.
Regards
Rene
Answer: The Message comes because i remove the Startup-License. I upload my own license-file and replace the startup-license. So the connection to license-server does'nt work. When i copy my startup-license back to the license-server all works well.
Regards
Rene