Evaluating series using operator

Question: Consider,
$$ S= \sum_{k=0}^{k=\infty} \frac{ k!}{x^{k}} (-1)^k$$
now this is, $$ S = ( 1 +D+D^2 +D^3...) ( \frac{1}{x})$$
using geometeric series
$$ 1+D+D^2.. = \frac{1}{1-D}$$
So, $$ S= \frac{1}{1-D} \frac{1}{x}$$
$$ S = \frac{1}{x-1}$$
Therefore , for x<1
$$ S= \sum_{k=0}^{k=\infty}(-1)^k \frac{ k!}{x^{k}}=\frac{1}{x-1}$$
Is this proof correct? Can I find an expression for l.h.s for x>1 ?
Comment: This is a divergent series.  Manipulations with divergent series, assuming the same properties as convergent series, often leads to nonsensical results.
Comment: How do you define $D$?
Comment: $D$ is the derivative operator.
Comment: D is the big D notation of derivative. It was made by oliver heaviside
Comment: @DDD4C4U your idea is good ,,,,but you have recheck about series of differential operators! You have to change some!
Answer: The equation
$$
S= \frac{1}{1-D} \frac{1}{x}
$$
should be interpreted as the inverse operator
$$
S = (1-D)^{-1}\frac{1}{x} .
$$
It would mean
$$
(1-D)S = \frac{1}{x} .
$$
Solve the differential equation $S(x) - S'(x) = \frac{1}{x}$ to get
$$
S = \operatorname{Ei}_1(x)\;e^x ,
$$
involving an exponential integral function.  This is, indeed, (almost) the Borel sum of the divergent series $S$.
Comment: can you give more detail on borel sum/ how you solved that differential equation
Comment: I added a link on Borel summation.

Evaluating series using operator


In the Hanon piano exercises, why is there a beam joining two groups of 16th notes?

Question: The first measure of the Hanon exercises has a set of four 16th notes that make up a quarter note, and another set of 4 16th notes that make up another quarter note.  This adds to 2 quarter notes for the measure, which is the time signature.
But why are the first 4 sixteenth notes joined to the next 4 sixteenth notes with a line?
Answer: I believe that that's just to do with the typesetting and not at all to do with anything technical. If anything, then I think that it may be to help you group those 8 notes together and think about them as a group.


User registration silently fails - how to debug?

Question: On our Drupal 7 site, user registration silently fails.
Drupal doesn't even reach the form's validation functions.
What we checked:

disabling javascript didn't help.
Removing installed modules related to registration such as : logintoboggan, user_registrationpassword didn't help.
Error logs show nothing.
The user module is of course enabled, people are able to login as usual.

Please advise where to put tests to see where execution is stopped.
Thanks in advance
Amnon
Comment: did you check the error logs in watchdog?
Comment: Yes, error logs show nothing. I've updated the question.
Answer: Recommended steps to trace the error:

Look at watchdog (which you did)
Look at the systems php and apache (or whatever you use) error logs
Take a local copy of the site and start digging

You can find your system logs (php and apache) by looking at the php info under "Admin > Reports > Status > PHP".
For local debugging: http://ratatosk.net/drupal/tutorials/debugging-drupal.html
My first point of entry would be the form definition. You could try for example to add an <code>#after_build</code> callback that get's called once the form has been fully build, and then check which validation and submit handlers are registered.
In your case I would suppose though, that you don't need to go that far. It's probably pretty basic error that will show of in the system logs.


Overlapping bars with JQPlot

Question: I am creating a chart with JQPlot. The chart will contain several series, each series with two bars. The second bar of each series should be partly covered by the first bar. I tried to achieve this goal by setting barPadding to a negative value:
seriesDefaults:{
    renderer:$.jqplot.BarRenderer,
    rendererOptions: {
        varyBarColor: false,
        fillToZero: true,
        barPadding: -5,      // number of pixels between adjacent bars in the same group (same category or bin).
        barDirection: 'vertical', // vertical or horizontal.
        barWidth: 20,     // width of the bars.  null to calculate automatically.
        shadowOffset: 0    // offset from the bar edge to stroke the shadow.
    },
},

This indeed makes the bars overlapping but the second bar overlaps the first one.

I would like it vice versa.
Is this possible with JQPlot or does anyone know another library with this possibility?
Comment: `barPadding` is doing what it is intended to do. what do you want to do?
Answer: There is no such configuration in jqplot. However there is a hacky way to do it by setting the z-index.
$('#chart .jqplot-series-canvas:first').css( "z-index", 99999);

Demo

Overlapping bars with JQPlot


Python: Turn off automatic output in console/shell between asking user for input

Question: when I run the code below, I'm constantly hammered by a load of object creation confirmations printing between user inputs... I would love if there was some way I could silence the console while the user focuses on inputting answers. I've found some sketchy solutions, but they seem too convoluted for how simple the issue is. Code snippet and sample output below. Thanks!
Code:
#Engages in battles until user quits
def battle(self):

    battles_threshold = min([a.battles_fought for a in self.artists])
    contenders = [a for a in self.artists if
        a.battles_fought == battles_threshold]
    noncontenders = list(set(self.artists)-set(contenders))
    print(noncontenders)
    contenders.append(random.choice(contenders))
    contender1=contenders.pop(random.choice(range(len(contenders))))
    contender2=contenders.pop(random.choice(range(len(contenders))))
    elo1 = contender1.elo
    elo2 = contender2.elo
    outcome = ''
    while (outcome != 'y' and outcome != 'n' and
        outcome != 'm' and outcome != 'q'):
        outcome = \
        raw_input('Do you like "' + contender1.name +
            '" more than "' + contender2.name + '"?\n')
    if outcome == 'q':
        return None
    elif outcome == 'y':
        contender1.elo_calc(1,contender2.name,elo2)
        contender2.elo_calc(0,contender1.name,elo1)
    elif outcome == 'n':
        contender1.elo_calc(0,contender2.name,elo2)
        contender2.elo_calc(1,contender1.name,elo1)
    else:
        contender1.elo_calc(0.5,contender2.name,elo2)
        contender2.elo_calc(0.5,contender1.name,elo1)
    pickle.dump(music_battler, open(self.path_name +
        'music_battler.p','wb'))
    self.battle()

Output:
Do you like "basshunter" more than "lil wayne"?
y
[<__main__.Artist instance at 0x10dc91ab8>, <__main__.Artist instance at      0x10dc7b050>, <__main__.Artist instance at 0x10dcdb878>, <__main__.Artist instance at 0x10dc82098>, <__main__.Artist instance at 0x10dc830e0>, <__main__.Artist instance at 0x10dc7b908>, <__main__.Artist instance at 0x10da15d88>, <__main__.Artist instance at 0x10dcd1128>, <__main__.Artist instance at 0x10dc7b950>, <__main__.Artist instance at 0x10da0c170>, <__main__.Artist instance at 0x10dccf998>, <__main__.Artist instance at 0x10dc911b8>, <__main__.Artist instance at 0x10dcd89e0>, <__main__.Artist instance at 0x10da1f050>, <__main__.Artist instance at 0x10da0d200>, <__main__.Artist instance at 0x10dc8b1b8>, <__main__.Artist instance at 0x10dab4c68>, <__main__.Artist instance at 0x10dcd1a70>, <__main__.Artist instance at 0x10dcd8290>, <__main__.Artist instance at 0x10dc8b878>, <__main__.Artist instance at 0x10dc9f320>, <__main__.Artist instance at 0x10dcd1dd0>, <__main__.Artist instance at 0x10dc91b00>, <__main__.Artist instance at 0x10dc7b488>, <__main__.Artist instance at 0x10da0d320>, <__main__.Artist instance at 0x10da22b48>, <__main__.Artist instance at 0x10dc85098>, <__main__.Artist instance at 0x10da0bb48>, <__main__.Artist instance at 0x10dcd1c20>, <__main__.Artist instance at 0x10dc7bcb0>, <__main__.Artist instance at 0x10dc85a70>, <__main__.Artist instance at 0x10da1dc68>, <__main__.Artist instance at 0x10dc85e18>, <__main__.Artist instance at 0x10daee488>, <__main__.Artist instance at 0x10dc9fcb0>, <__main__.Artist instance at 0x10dcd14d0>, <__main__.Artist instance at 0x10dc91cf8>, <__main__.Artist instance at 0x10da39d88>, <__main__.Artist instance at 0x10dccfdd0>, <__main__.Artist instance at 0x10dc915f0>, <__main__.Artist instance at 0x10dc91908>, <__main__.Artist instance at 0x10dcddea8>, <__main__.Artist instance at 0x10da2aa70>, <__main__.Artist instance at 0x10dc916c8>, <__main__.Artist instance at 0x10dc85ef0>, <__main__.Artist instance at 0x10dccf710>, <__main__.Artist instance at 0x10dc85758>, <__main__.Artist instance at 0x10da11f80>, <__main__.Artist instance at 0x10dc7bfc8>, <__main__.Artist instance at 0x10dc9f7e8>]

Do you like "alesso" more than "taking back sunday"?

Comment: There is also no such thing as automatic output :)
Answer: print(noncontenders) is the line that is giving you the printout [<__main__.Artist instance at 0x10dc91ab8>, <__main__.Artist instance at... removing it should eliminate that.
Comment: Wow 8 hours of coding obviously fried my brain. Sorry for the idiocy.


Find $\int \limits_0^1 \int \limits_x^1 \arctan \bigg(\frac yx \bigg) \, \, \, dx \, \, dy$

Question: Find $$\int \limits_0^1 \int \limits_x^1 \arctan \bigg(\frac yx \bigg)dx \, \, dy$$
So obviously using cylindrical is the way to go to give $\theta r$ inside the integral (after considering the jacobian term).
But how can the limits of $x$ be $(x,1)$. I am guessing it is meant to say $dy \, \, dx$ right so those limits are for $y$? Please tell me if you disagree.
But even if this is the case, it is not possible to compute the integral.
After sketching out $x<y<1$ and $0<x<1$, I realised that the region is the triangle bounded by origin, $(0,1)$ and $(1,0)$. So the limits of $r$ and $\theta$ are $(0,1/\cos\theta)$ and $(\pi/4 , \pi /2)$. So we have $$\int \limits_{\pi/4}^{\pi/2} \int \limits_0^{1/\cos\theta} r\theta \, \, \, dr \, \, d\theta$$ which gives $$\int \limits_{\pi/4}^{\pi/2} \frac 12 \theta \sec^2 \theta \, \, \,  d\theta$$
The integral of $\sec^2 \theta $ is $ln |\cos \theta |$ and one of the limits is $\pi/2$ which is undefined. Please help.
Comment: let me post my answer :)
Comment: You are correct about the bounds of integration.  However, despite the way the integral looks, you don't want to convert to polar.  Use integration by parts to do the $y$ integral.
Comment: I think you have a small mistake in your domain when changing into polar coordinates. the upper limit for the first inetgral I think should be  $ \frac{1}{\sin \theta}$ and not  $ \frac{1}{\cos \theta}$. More over, I think as you suggest it should be  $dy dx$.
Comment: @Nizar The limits of x is 0<x<1 which gives 0<r<1/cos.
Comment: but also you have  $x<y<1$, then $r \sin \theta < 1$ !
Comment: @Nizar Oh yeah... that makes it so ambiguous then since choosing either one makes sense until the final calculation.
Answer: Let $I=\int_{0}^{1} \int_{x}^{1} arctan(\frac{y}{x}) dy dx  $, then considering polar coordinates we have the foolowing region :
so as we see  from  the picture, the region is bounded by $\theta$ between  $\frac{\pi}{4} $ and  $\frac{\pi}{2} $. Now taking a ray from the origin crossing the region, we recignize that it starts from origin and finaly left the region meeting the line $y=1$, so that  $r\sin \theta= 1$, i.e. $ r $  is bounded  between $0$ and  $\frac{1}{\sin \theta}$. so
$$I = \int_{\frac{\pi}{4} }^{\frac{\pi}{2}} \int_{ 0}^{\frac{1}{\sin \theta} } r \theta dr d\theta = \int_{\frac{\pi}{4} }^{\frac{\pi}{2}} \frac{\theta}{ 2 sin^2 \theta } d\theta= - \frac{\theta}{2\tan \theta } \mid_{\frac{\pi}{4}}^{\frac{\pi}{2}} + \int_{\frac{\pi}{4} }^{\frac{\pi}{2}}  \frac{d\theta}{2\tan \theta } = -\lim_{\theta \rightarrow \frac{\pi}{2} }   \frac{\theta}{2\tan \theta } + \frac{\pi}{8 }  + \frac{1}{2} \ln (\sin \theta)\mid_{\frac{\pi}{4}}^{\frac{\pi}{2}}=  \frac{\pi}{8 } -\frac{1}{2} \ln (\sin \frac{\pi}{4}). $$
Comment: You still end up with an indeterminate so its the same either way (with my limits and your limits). Since you have to evaluate with limits.


Function onReady instead on Button Click

Question: I have a working function on button click,
I need to remove the button and run the function as the page loads completely.
Could somebody help me to do that. I am doing this on wix.
export function button1755_click(event) {
$w("#ddCabinet").selectedIndex = 15;
$w("#dropdown25").selectedIndex = 0;
$w("#dropdown26").selectedIndex = 1;
$w("#inteldropdown1").selectedIndex = 0;
$w("#ddGraphiccard").selectedIndex = 1;
$w("#ddGraphiccardQty").selectedIndex = 0;
}

Comment: try using **window.onload** in JavaScript. also: [window.onload vs document.onload](https://stackoverflow.com/questions/588040/window-onload-vs-document-onload)
Answer:
Using the $( document ).ready() jquery function, you can execute your code when page load:

$( document ).ready(function() {
    console.log( "ready!" );

    // your code here

});

Comment: is that applicable for wix ???
as i have seen there scripts start from $w??
I m new in programming
Comment: and where should i put my rest codes i mentioned???
as you closed the function
Comment: `$w` is apparently an alias for jQuery on your site. You'd use it instead of just `$`, which is the default alias for `jQuery`.
Comment: Your code would replace the sample console log code, inside the `.ready` function.


Adding a computed column in Postgres SQL based on a date

Question: Here my table.
CREATE TABLE annual_goals (
  id INTEGER PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
  content TEXT NOT NULL,
  complete BOOLEAN DEFAULT false,
  date_created TIMESTAMP DEFAULT now() NOT null,
  date_modified TIMESTAMP DEFAULT now() NOT null
);

I want to alter it such that I can add a new column called month_num that returns the number of the month given date_created (i.e. if the date_created of an entry is 5/31/2019, I want the month_num to automatically populate 5).
I tried the following but I'm getting an error that states "ERROR:  syntax error at or near "A
S"
ALTER TABLE annual_goals
    ADD year_num
        AS year(date_created);

Any help is greatly appreciated. Thanks
Comment: Are you sure you're using MySQL? It doesn't use `IDENTITY`, it uses `AUTO_INCREMENT`.
Comment: And that's also not how it reports syntax errors. Maybe you're using SQL-Server?
Comment: It's not SQL Server either. Postgres, maybe, from the `PRIMARY KEY GENERATED BY DEFAULT` syntax?
Comment: Ah, I am using postgres
Answer: You have two errors in the code.  One is that MySQL requires the type.  The second is that the expression needs to be surrounded by parentheses:
ALTER TABLE annual_goals ADD year_num int AS ( year(date_created) );

EDIT:
In Postgres, you can use the syntax:
alter table annual_goals
    add year_num int generated always as (extract(year from date_created)) stored;

Here is a db<>fiddle.
Comment: Hey Gordon, appreciate the help here.  I made those two changes. I continue to get the same error. Any chance there's somewhere else I should look?
Comment: @johlee . . . You did not tag your question correctly, so you did not get appropriate answers.
Comment: Yes, understood. Learning!
Answer: You could try this:
ALTER TABLE annual_goals
    ADD year_num int;

UPDATE annual_goals
SET year_num=year(date_created);


CATextlayer set line spacing?

Question: I have a problem with CATextlayer. I set wrapped == YES for CATextlayer and it auto set multi line for this. But the line spacing is very small and look it verry bad.
Is there any way to set line spacing for CATextlayer? Thanks.
Answer: I think CATextLayer is only intended for lightweight uses. You can set its string property to an NSAttributedString to alter some attributes like font and size but many others are ignored, including line height and spacing.
For finer control over how text in a layer is rendered you can use a regular CALayer and  NSAttributedString's drawing methods; for example:
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
    [NSGraphicsContext saveGraphicsState];
    [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithGraphicsPort:ctx flipped:YES]];
    [self.someAttributedString drawInRect:layer.bounds];
    [NSGraphicsContext restoreGraphicsState];
}

Answer: Like @spinacher I noticed that CATextLayer ignores paragraph styles like line spacing. I solved this by subclassing CALayer and draw the attributed string more directly. Much of the code is copied from this article
class CAAttributedTextLayer: CALayer {

    public var attrString = NSAttributedString(string: "")

    override func draw(in ctx: CGContext) {

        // Flip the coordinate system
        ctx.textMatrix = .identity
        ctx.translateBy(x: 0, y: bounds.size.height)
        ctx.scaleBy(x: 1.0, y: -1.0)

        let path = CGMutablePath()
        path.addRect(bounds)

        let framesetter = CTFramesetterCreateWithAttributedString(attrString as CFAttributedString)
        let frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, attrString.length), path, nil)
        CTFrameDraw(frame, ctx)
    }
}

Comment: how to use above code? can you please give any code example to use
Comment: @HardikThakkar Just add the class to your code, and replace your CATextLayer with CAAttributedTextLayer. Then set the attrString property to an attributed string
Answer: CATextLayer lineheight depends on your fonts native height of 1 unit
usually expressed with a typographical unit-type named "Geviert".
If you are able to edit your font - you are also able to set the lineheight of course. Because the unit size of one signets maximum unit size is used when Quartz will interpret/render your font.

sorry the screenshot in german, of a font-editing with setting for a font that will have only 6 pixel height and a linespacing of two pixels. Even in font creation software it is not obvious to read out the line height as you can see. Nowhere is 2 pixels given as linespace.. instead the unit-size Geviert is given here.
So yes there is no other way that CATextLayer could print other lineheights in a native way. You will always have to use a workaround by reading out the "\n" of your NSString and re-allocate another CATextLayer for the next line or going with other Classes to print text on screen like the example from torof with a CAAttributedTextLayer that can express NSAttributedStrings
Lineheight for Quartz Rendering is a relative size depending on the Font.
Some fonts need more linespace because they are heavy in circles and underscore graphics. If this relative lineheight would not exist, you would have to give a lineheight on every text printing instead using the standard 1 unit * Geviert size + size below any sign (screenshot "Unterlänge")
When you can edit your font file and set the mentioned Geviert size to a value you wish than CATextLayer will always render in perfect line height. Which is very handy when you create image buffers for LCD or other low pixel displays.
Comment: ps: the screenshot is made from within glyphs mini.
Answer: You can refer following tutorial :
Height-for-width layout with CATextLayer
Comment: This doesn't answer the question at all. The question is about changing the line spacing of a `CATextLayer`, not about calculating the height for a specific width...

CATextlayer set line spacing?


Bayes Factors for McNemar Test

Question: I am currently analyzing data from a within-subjects study in which all participants completed a standard and experimental task.
Responses were binary (pass = 1; fail = 0).
I believe that the appropriate statistic to use here is the McNemar Chi Square in frequentist statistics.
However, I am not sure that a Bayes equivalent exists.
How can I compute Bayes Factors for a McNemar test?
Any help is deeply appreciated!
Answer: I have not seen any Bayesian factor counterpart to the McNemar test. However, there are some Bayesian counterparts which can be viewed as the McNemar test.
Keep in mind that there are several variations of the McNemar test, each of which has their own merits/pitfalls.
For the exact McNemar test, which is arguably the most widely-used test in this family, there are several solutions. One simple approach is to use the beta-binomial conjugate to simply calculate the posterior probability)
One drawback of the beta-binomial conjugate is that it only considers two states from events A and B: either A > B and A < B. So, this test throws away the samples that A and B have the same value (both success or both fail.) To take into account the equality of A and B, you should use the Dirichlet-trinomial test which can be find here.
The third approach is to use the Bayesian Sign test. If you set p=0.5 in the McNemar exact test, then it is equivalent to the Sign test. The Bayesian Sign test's implementation can be found here.
I hope this helps. Unfortunately, I could not post more than two link. You can google various frequentist McNemar test (asymptotic, asymptotic with continuity correction, exact, mid-p) and you can find suitable resources for the beta-binomial conjugate.

Bayes Factors for McNemar Test


Why is $H^1(\text{Gal}(\overline{K}/K),A)=\lim_{\rightarrow}H^1\left(L/K, A^{\text{Gal}(\overline{K}/L)}\right)$

Question: I'm doing a course on elliptic curves, and I'm stuck on this.
Here are the definitions:
Let $G$ be a group and let $A$ be a $G$-module (that is, a $\mathbb{Z}[G]$-module). We have the "cochains" $$C^1(G,A)=\{\text{maps }: \; G \rightarrow A\},$$ and "cocycles" $$Z^1(G,A)=\{(a_\sigma)_{\sigma \in G}\; | \; a_{\sigma \tau}=\sigma a_\tau+a_\sigma \},$$ and "coboundaries" $$ B^1(G,A)=\{(\sigma b-b)_{\sigma \in G}\}.$$ we have $$C^1(G,A) \supset Z^1(G,A) \supset B^1(G,A).$$ We then define the 1st cohomology group $$H^1(G,A)=\frac{Z^1(G,A)}{B^1(G,A)}.$$ For any normal subgroup $H \leq G$, we also have the inflation map $$ \text{inf}: H^1\left(\frac{G}{H}, A^H\right)\rightarrow H^1(G,A).$$
Let $K$ be a perfect field. Then $G=\text{Gal}(\overline{K}/K)$ is a topological group with basis around the identity given by the subsets $\text{Gal}(\overline{K}/L)$ where $[L:K]< \infty$. (I think we also want $L/K$ to be Galois, but the lecturer didn't say this.)
We then impose that the stabiliser of any $a \in A$ is an open subgroup of $G$, and that the "cochains" are continuous w.r.t. the discrete topology for $A$.
Then the lecturer claims that $$H^1(\text{Gal}(\overline{K}/K),A)=\lim_{\rightarrow}H^1\left(L/K, A^{\text{Gal}(\overline{K}/L)}\right).$$
I can't see why this is true. I'm really struggling to get a hold of the RHS. Here the direct limit is taken over finite extensions $L$ of $K$ with respect to the inflation map.
Edit: here is my attempt at proving $$Z^1(\text{Gal}(\overline{K}/K),A)=\lim_\rightarrow \; Z^1\left( \text{Gal}(L/K),A^{\text{Gal}(\overline{K}/L)}\right).$$
I think what I want to show is that a cocyle $(a_\sigma)\in Z^1(\text{Gal}(\overline{K}/K),A)$ is induced by a cocyle in $Z^1( \text{Gal}(L/K),A^{\text{Gal}(\overline{K}/L)})$ for some $[L:K]<\infty$.
Now, by the continuity we can find a finite extension of $K$, $L_1$, such that the coset of $\text{Gal}(\overline{K}/L_1)$ is contained in the preimage of $0=a_1$. Since this coset contains $1$, it is actually just $\text{Gal}(\overline{K}/L_1)$.
By the condition about stabilisers, we can find $L_2$ such that a coset of $\text{Gal}(\overline{K}/L_2)$ fixes $a_1$, and again this coset is just $\text{Gal}(\overline{K}/L_2)$.
Take $L$ to be the Galois closure of the compositum $L_1L_2$.
Suppose $\sigma, \sigma' \in \text{Gal}(\overline{K}/K)$ such that $\sigma|_L=\sigma'|_L$. Then $\sigma^{-1} \sigma'=\tau \in \text{Gal}(\overline{K}/L)$. So $$a_\sigma'=a_{\sigma \tau}=\sigma a_\tau+a_\sigma =a_\sigma.$$
Thus $a_\sigma$ depends only on $\sigma|_L$.
So for $\tau \in \text{Gal}(\overline{K}/L)$, $a_{\tau \sigma}=a_\sigma$. So $\tau(a_\sigma)=a_{\tau \sigma}-a_\tau=a_\sigma$. Thus each element of $\{a_\sigma: \sigma \in \text{Gal}(\overline{K}/K)\}$ is fixed by $\text{Gal}(\overline{K}/L)$, as required.
Answer: First of all, in the definition of the profinite topology, it doesn't matter whether or not you restrict to $L$ that are Galois over $K$.  (The one set of subgroups is cofinal in the other.)
As for your main question, have you tried checking the analogous statement for $C^1$, $Z^1$, or $B^1$?   (If you do, then the statement about $H^1$ that you want should follow from the fact that passing to direct limits is exact.)
Comment: Do you know if is the Galois condition  necessary in order to define an action of $Aut(K/\mathbb{Q})$ on a elliptic curve of the type   $$Aut(K/\mathbb{Q})\times E({K})\longrightarrow E({K})$$
$$(\sigma,(x,y))\longmapsto (\sigma(x),\sigma(y))$$
$$(\sigma,O)\longmapsto O$$


"Please select category" as default value in a select list

Question: Similar to how the search box on many sites has a default value of "search", how do I give a select list a default value without making that value a valid option in the list of options. See example below:
Answer: For adding text to your input field, write a custom module and place the code in there
<code>function yourmodule_form_alter(&$form, &$form_state, $form_id){
    if($form_id == "your_form"){
     $form['some_element']['#attributes']['placeholder'] = t('Select Category');
}
</code>
Comment: isn't placeholder an HTML5 attribute?
Answer: you are looking for #empty_value attribute
If #required is TRUE and there is no #default_value, an empty option is added to the select control to force the user to make an active choice.
If #empty_value or #empty_option is set and #required is FALSE (default), an empty option is added to the select control, allowing the user to choose nothing.
If none of #required, #empty_value, #empty_option, and #default_value are set, then no empty option is added to the select control. This leaves the control in a slightly illogical state, since all user agents automatically preselect the first available option. There's no way for the user to select nothing, and the user is also not forced to make an active decision.
https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#empty_value


Number of zeros of $ z^7+4z^4+z^3+1$

Question: How many zeros does $z^7+4z^4+z^3+1$ have in each of the regions |z|<1 and |z|<2?
I know I should use Rouche's Theorem but I can't find a $|f(z)| > |p(z)-f(z)|$ and $f(z)$ have equal number of solutions as $p(z)$.
Can anyone explain the question with details?
Comment: The answers are 4 and 7 respectively.
Answer: Note that if $|z| \ge 2$, then $|z|^7 - (4 |z|^4+|z|^3+1) \ge 55$, hence all of the roots lie inside $|z|<2$.
Note that if $|z|=1$, then $4 |z|^4+|z|^3+1 - |z|^7 \ge 5$.

 Hence $z \mapsto 4z^4+z^3+1$ and $z \mapsto z^7+4z^4+z^3+1$ have the same number of zeros inside $|z|=1$.

Note that if $|z|=1$, then $4 |z|^4-(|z|^3+1) \ge 2$.

 Hence $z \mapsto 4z^4+z^3+1$ and $z \mapsto 4z^4$ have the same number of zeros inside $|z|=1$ (that is, four).
Comment: Thank you so much! I just figure out I can set f(z)=4z^4 for |z|<1 and f(z)=z^7 for |z|<2. It gives the answers 4 and 7 like you said.

Number of zeros of $ z^7+4z^4+z^3+1$


Java SWT - Transparent background on canvas?

Question: Is it possible to fill a rectangle and an oval over a drawn image and having the oval being a "window" to the image behind it?
e.gc.drawImage(//...);
e.gc.setBackground(//black);
e.gc.fillRectangle(//over the image);
e.gc.setBackground(//SWT.TRANSPARENT?);
e.gc.fillOval(somewhere on the canvas);

this snippet obviously isn't working for me, but can this even be achieved with SWT?
Answer: I managed to do it,
what I did was create a new shell with the SWT.NO_TRIM property (it's parent is the canvas/costume widget) and use setRegion() on it.
The trick was the region itself, it has a  subtract()  method,
so I found a method that produces a polygon and I subtracted it from the region.
Than I set it and voilà.
I had to add resize and move listeners so it would look "natural" (i.e, part of the canvas and not a new shell).
It works really well actually.
Answer: Instead of using fillOval() and fillRectangle(), use drawOval() and drawRectangle() to draw the outline instead of filling the area.
Here's the JavaDoc:

Draws the outline of an oval, using the foreground color, within the specified rectangular area.

Whereas fillOval() does:

Fills the interior of an oval, within the specified rectangular area, with the receiver's background color.
Comment: Yes I'm aware to these options, I should have mentioned that the rectangle has to cover the image, while the oval needs to be transparent.
Comment: @omm118 Well, then use `fillRectangle()` and `drawOval()`
Comment: @omm118 Or do you want the oval to "remove" parts of the rectangle?
Comment: If I'll use    fillRectangle  and than    drawOval the oval's background would be the rectangle, and if I'll use    drawOval and than    fillRectangle the rectangle would just cover the oval too.
Comment: @omm118 Don't know how to do that. You may need to draw a polygon yourself


Define a function given some constraints

Question: I try to define a two-variable function $f(x,y) \ge 0$ with both $x,y \in [0,1]$ which satisfies the following constraints:

$f$ is increasing in both $x$ and $y$
if $x=0$ then $f(x,y)=0$
if $y=0$ then $f(x,y)=0$ only if $x=0$

Any suggestion?
Answer: Would the function $f(x,y)=x(y+1)$ work?
Comment: thanks for the suggestion. Is it possible to not to involve some arbitrary constant $\alpha \gt 0$ (such as $\alpha = 1$ here)? The inconvenience is that I have to justify for the particular choice of $\alpha$ here.
Comment: @skyork: $f(x,y)=x\cdot g(y)$ should work for any function $g$ that is increasing on $[0,1]$ with $g(0)>0$.  I'm not sure that any particular choice of $g$ is any less arbitrary that $g(y)=y+1$, though.
Answer: How about $f(x,y) = xe^y$? No arbitrary constant as required!


SSRS 2008R2 Upgrade to 2016 Performance Issues

Question: We recently did an SSRS upgrade and migration going from 2008R2 to 2016 Standard SP1 on a new server. The migration was done with a ReportServer DB restore, so all the 2008 RDLs were copied over.
One of the reports is taking about 20 seconds longer to render (based on the average TimeRendering value from ExecutionLog) on the new server compared to the old one. The report has a footer, so all the pages render at runtime. There is about 1800 pages worth of data, and there are many tables with groupings / logic. There are probably ways to optimize the report, but shouldn't the same report run at least as fast on my new server?
Below is a list of things I looked at / noticed, but at this point I don't know where else to look to see why there could be a performance difference.
Old Server:

2008R2
Report data source on same server
96GB RAM
4 core CPU
64 bit 2008R2 Windows Server

New Server:

2016 SP1
Server on same SAN / physical location as report data source
128 GB RAM
4 core CPU
64 bit 2016 Windows Server

Things I tried (none of which made a difference):

Opening the RDL in VS 2015 / upgrading the RDL to new version
Running the report in Chrome vs IE 11
Running the report on RDP
Add new report site to compatibility list in IE
Running a version of the report without the footer, and the render time goes down to 1 second, but the TimeProcessing increases, so the overall runtime is still the same. This was very confusing...

Things I noticed:

Old server will use more CPU than new server. There are other processing running, so could be due to that, but new server (ssrs only) CPU will never go over 30% usage. Could this be a config somewhere?
Answer: What are the data retrieval and processing times from the execution logs? Those might point you in the right direction.


WSAECONNRESET (10054) error using WebDrive to map to a Subversion/Apache WebDAV share

Question: I'm using WebDrive to map a drive letter to a WebDAV share running on Subversion with the SVNAutoversioning flag enabled. The Subversion server is running CollabNet Subversion Edge with LDAP authentication.
When trying to connect using WebDrive, I get:
Connecting to site myserver
Connecting to http://myserver/webdrive/
Resolving url myserver to an IP address
Url resolved to IP address 192.168.0.12
Connecting to 192.168.0.12 on port 80
Connected successfully to the server on port 80
Testing directory listing ...
Connecting to 192.168.0.12 on port 80
Connected successfully to the server on port 80

Unable to connect to server, error information below

Error: Socket receive failure (4507)
Operation: Connecting to server
Winsock Error: WSAECONNRESET (10054)

The httpd.conf file running on the server contains the following section:
<Location /webdrive/>
    DAV svn
    SVNParentPath "C:\Program Files\Subversion\data\repositories"
    SVNReposName "My Subversion WebDrive"
    AuthzSVNAccessFile "C:\Program Files\Subversion\data/conf/svn_access_file"
    SVNListParentPath On
    Allow from all
    AuthType Basic
    AuthName "My Subversion Repository"
    AuthBasicProvider csvn-file-users ldap-users
    Require valid-user
    ModMimeUsePathInfo on
    SVNAutoversioning on
</Location>

and in the Apache error_yyyy_mm_dd.log file on the server, I'm seeing this when I try to connect via WebDAV:
[Mon Jan 10 14:53:22 2011] [debug] mod_authnz_ldap.c(379): [client 192.168.0.50] [5572] auth_ldap authenticate: using URL ldap://mydc/dc=mydomain,dc=com?sAMAccountName?sub
[Mon Jan 10 14:53:22 2011] [debug] mod_authnz_ldap.c(484): [client 192.168.0.50] [5572] auth_ldap authenticate: accepting dylan.beattie
[Mon Jan 10 14:53:22 2011] [info] [client 192.168.0.50] Access granted: 'dylan.beattie' OPTIONS webdrive:/
[Mon Jan 10 14:53:22 2011] [debug] mod_authnz_ldap.c(379): [client 192.168.0.50] [5572] auth_ldap authenticate: using URL ldap://mydc/dc=mydomain,dc=com?sAMAccountName?sub
[Mon Jan 10 14:53:22 2011] [debug] mod_authnz_ldap.c(484): [client 192.168.0.50] [5572] auth_ldap authenticate: accepting dylan.beattie
[Mon Jan 10 14:53:22 2011] [info] [client 192.168.0.50] Access granted: 'dylan.beattie' PROPFIND webdrive:/
[Mon Jan 10 14:53:25 2011] [notice] Parent: child process exited with status 3221225477 -- Restarting.
[Mon Jan 10 14:53:25 2011] [debug] util_ldap.c(1990): LDAP merging Shared Cache conf: shm=0xcd0f18 rmm=0xcd0f48 for VHOST: myserver.mydomain.com
[Mon Jan 10 14:53:25 2011] [debug] util_ldap.c(1990): LDAP merging Shared Cache conf: shm=0xcd0f18 rmm=0xcd0f48 for VHOST: myserver.mydomain.com
[Mon Jan 10 14:53:25 2011] [info] APR LDAP: Built with Microsoft Corporation. LDAP SDK
[Mon Jan 10 14:53:25 2011] [info] LDAP: SSL support unavailable: LDAP: CA certificates cannot be set using this method, as they are stored in the registry instead.
[Mon Jan 10 14:53:25 2011] [notice] Apache/2.2.16 (Win32) DAV/2 SVN/1.6.13 configured -- resuming normal operations
[Mon Jan 10 14:53:25 2011] [notice] Server built: Oct  4 2010 19:55:36
[Mon Jan 10 14:53:25 2011] [notice] Parent: Created child process 4368
[Mon Jan 10 14:53:25 2011] [debug] mpm_winnt.c(487): Parent: Sent the scoreboard to the child
[Mon Jan 10 14:53:25 2011] [debug] util_ldap.c(1990): LDAP merging Shared Cache conf: shm=0xca2bb0 rmm=0xca2be0 for VHOST: myserver.mydomain.com
[Mon Jan 10 14:53:25 2011] [debug] util_ldap.c(1990): LDAP merging Shared Cache conf: shm=0xca2bb0 rmm=0xca2be0 for VHOST: myserver.mydomain.com
[Mon Jan 10 14:53:25 2011] [info] APR LDAP: Built with Microsoft Corporation. LDAP SDK
[Mon Jan 10 14:53:25 2011] [info] LDAP: SSL support unavailable: LDAP: CA certificates cannot be set using this method, as they are stored in the registry instead.
[Mon Jan 10 14:53:25 2011] [error] python_init: Python version mismatch, expected '2.5', found '2.5.4'.
[Mon Jan 10 14:53:25 2011] [error] python_init: Python executable found 'C:\\Program Files\\Subversion\\bin\\httpd.exe'.
[Mon Jan 10 14:53:25 2011] [error] python_init: Python path being used 'C:\\Program Files\\Subversion\\Python25\\python25.zip;C:\\Program Files\\Subversion\\Python25\\\\DLLs;C:\\Program Files\\Subversion\\Python25\\\\lib;C:\\Program Files\\Subversion\\Python25\\\\lib\\plat-win;C:\\Program Files\\Subversion\\Python25\\\\lib\\lib-tk;C:\\Program Files\\Subversion\\bin'.
[Mon Jan 10 14:53:25 2011] [notice] mod_python: Creating 8 session mutexes based on 0 max processes and 64 max threads.
[Mon Jan 10 14:53:25 2011] [notice] Child 4368: Child process is running
[Mon Jan 10 14:53:25 2011] [debug] mpm_winnt.c(408): Child 4368: Retrieved our scoreboard from the parent.
[Mon Jan 10 14:53:25 2011] [info] Parent: Duplicating socket 288 and sending it to child process 4368
[Mon Jan 10 14:53:25 2011] [info] Parent: Duplicating socket 276 and sending it to child process 4368
[Mon Jan 10 14:53:25 2011] [debug] mpm_winnt.c(564): Child 4368: retrieved 2 listeners from parent
[Mon Jan 10 14:53:25 2011] [notice] Child 4368: Acquired the start mutex.
[Mon Jan 10 14:53:25 2011] [notice] Child 4368: Starting 64 worker threads.
[Mon Jan 10 14:53:25 2011] [debug] mpm_winnt.c(605): Parent: Sent 2 listeners to child 4368
[Mon Jan 10 14:53:25 2011] [notice] Child 4368: Starting thread to listen on port 49159.
[Mon Jan 10 14:53:25 2011] [notice] Child 4368: Starting thread to listen on port 80.
[Mon Jan 10 14:53:25 2011] [debug] mod_authnz_ldap.c(379): [client 192.168.0.50] [4368] auth_ldap authenticate: using URL ldap://mydc/dc=mydomain,dc=com?sAMAccountName?sub
[Mon Jan 10 14:53:25 2011] [debug] mod_authnz_ldap.c(484): [client 192.168.0.50] [4368] auth_ldap authenticate: accepting dylan.beattie
[Mon Jan 10 14:53:25 2011] [info] [client 192.168.0.50] Access granted: 'dylan.beattie' PROPFIND webdrive:/
[Mon Jan 10 14:53:28 2011] [notice] Parent: child process exited with status 3221225477 -- Restarting.
[Mon Jan 10 14:53:28 2011] [debug] util_ldap.c(1990): LDAP merging Shared Cache conf: shm=0xcd4f90 rmm=0xcd4fc0 for VHOST: myserver.mydomain.com
[Mon Jan 10 14:53:28 2011] [debug] util_ldap.c(1990): LDAP merging Shared Cache conf: shm=0xcd4f90 rmm=0xcd4fc0 for VHOST: myserver.mydomain.com
[Mon Jan 10 14:53:28 2011] [info] APR LDAP: Built with Microsoft Corporation. LDAP SDK
[Mon Jan 10 14:53:28 2011] [info] LDAP: SSL support unavailable: LDAP: CA certificates cannot be set using this method, as they are stored in the registry instead.
[Mon Jan 10 14:53:28 2011] [notice] Apache/2.2.16 (Win32) DAV/2 SVN/1.6.13 configured -- resuming normal operations
[Mon Jan 10 14:53:28 2011] [notice] Server built: Oct  4 2010 19:55:36
[Mon Jan 10 14:53:28 2011] [notice] Parent: Created child process 5440
[Mon Jan 10 14:53:28 2011] [debug] mpm_winnt.c(487): Parent: Sent the scoreboard to the child
[Mon Jan 10 14:53:28 2011] [debug] util_ldap.c(1990): LDAP merging Shared Cache conf: shm=0xda2bb0 rmm=0xda2be0 for VHOST: myserver.mydomain.com
[Mon Jan 10 14:53:28 2011] [debug] util_ldap.c(1990): LDAP merging Shared Cache conf: shm=0xda2bb0 rmm=0xda2be0 for VHOST: myserver.mydomain.com
[Mon Jan 10 14:53:28 2011] [info] APR LDAP: Built with Microsoft Corporation. LDAP SDK
[Mon Jan 10 14:53:28 2011] [info] LDAP: SSL support unavailable: LDAP: CA certificates cannot be set using this method, as they are stored in the registry instead.
[Mon Jan 10 14:53:28 2011] [error] python_init: Python version mismatch, expected '2.5', found '2.5.4'.
[Mon Jan 10 14:53:28 2011] [error] python_init: Python executable found 'C:\\Program Files\\Subversion\\bin\\httpd.exe'.
[Mon Jan 10 14:53:28 2011] [error] python_init: Python path being used 'C:\\Program Files\\Subversion\\Python25\\python25.zip;C:\\Program Files\\Subversion\\Python25\\\\DLLs;C:\\Program Files\\Subversion\\Python25\\\\lib;C:\\Program Files\\Subversion\\Python25\\\\lib\\plat-win;C:\\Program Files\\Subversion\\Python25\\\\lib\\lib-tk;C:\\Program Files\\Subversion\\bin'.
[Mon Jan 10 14:53:28 2011] [notice] mod_python: Creating 8 session mutexes based on 0 max processes and 64 max threads.
[Mon Jan 10 14:53:28 2011] [notice] Child 5440: Child process is running
[Mon Jan 10 14:53:28 2011] [debug] mpm_winnt.c(408): Child 5440: Retrieved our scoreboard from the parent.
[Mon Jan 10 14:53:28 2011] [info] Parent: Duplicating socket 288 and sending it to child process 5440
[Mon Jan 10 14:53:28 2011] [info] Parent: Duplicating socket 276 and sending it to child process 5440
[Mon Jan 10 14:53:28 2011] [debug] mpm_winnt.c(564): Child 5440: retrieved 2 listeners from parent
[Mon Jan 10 14:53:28 2011] [notice] Child 5440: Acquired the start mutex.
[Mon Jan 10 14:53:28 2011] [notice] Child 5440: Starting 64 worker threads.
[Mon Jan 10 14:53:28 2011] [debug] mpm_winnt.c(605): Parent: Sent 2 listeners to child 5440
[Mon Jan 10 14:53:28 2011] [notice] Child 5440: Starting thread to listen on port 49159.
[Mon Jan 10 14:53:28 2011] [notice] Child 5440: Starting thread to listen on port 80.

Browsing http://myserver/webdrive/ from a web browser is working fine, and I have a similar set-up working perfectly on a different SVN server that isn't running Collabnet but has had Subversion and Apache installed and configured separately.
Any ideas? The python version error might be red herring - I've seen it in a couple of places in the log files and in other scenarios it doesn't appear to be breaking anything...
Answer: Solved - thanks to this post on the CollabNet forums.
I was trying to connect to http://myserver/webdrive/ - which won't work.
Add the name of a repository - http://myserver/webdrive/reponame/ - on the end of the URL, and it connects without any problems.
Comment: Accept your answer and enjoy the rewards of figuring it out through another avenue.


Pathauto conditions

Question: Is it possible for Pathauto to have one pattern for a content type, and a different pattern for the same content type based on the value of a field in that content type? I have a checkbox field and if its checked I want to use a different pathauto setting. Right now the only condition Pathauto has is based on content type. Is there a hook that can do this.
Answer: Yes. There exists hook_pathauto_pattern_alter() for this purpose. Per the docs:

Alter the pattern to be used before an alias is generated by Pathauto.
This hook will only be called if a default pattern is configured (on
  admin/config/search/path/patterns).

A hook invocation takes arguments in which you can inspect the type and alter &$pattern accordingly.
Comment: Thanks Shawn, I found a good example of this hook here: https://www.mediacurrent.com/blog/pathauto-less-traveled/

Pathauto conditions


Filter View by Entity Reference Value From Current Node

Question: I've been trying to figure this out for a while now, I believe that this should be easy but I still can't solve it. I'm a beginner at this. -_-
I have 3 Content types

Venue
Food
Package

I have a List of Venue that will be used as reference for the Food. So, The Food content type has an entity reference field -> field_venue
The Food will only be available to the venue it referenced.
The Package Content type has the entity reference Venue and Food. It shows the venue and the food available.
I use Entity Reference View Widget for the Entity reference on Package Content Type. The Venue is working well.
My Problem is the Food.
I need an Entity Reference View Widget (VIEW) that shows the available food for the Venue.
On the form, the user will only be able to answer the Venue field. After that the form will be saved and the entity reference field for Food will display on the page, that is the place where the user will answer that field.
On the entity reference view widget Food, I have the following:
Filter Criteria:
Content Type: Food
Relationship:
Entity Reference: Referenced Entity (field_venue) marked as required
The problem is that the view shows all the food even if the chosen venue is not available for that food. I don't know where to put that condition. Either on contextual filter or Filter Criteria. I'm not sure. I just need the view to get the Answer of the Venue from that same form/node so that the Food will filter automatically.
Is there anyone that will be able to help?
Thank you very much!!!
Answer: I got this working with this set up:
Contextual Filter: field_venue
-> Provide default value
 ->PHP Code
  -> PHP contextual filter code

$node=menu_get_object();
  return $node->field_venue_for_catering['und'][0]['target_id'];

"field_venue" is the venue field from "Food"
"field_venue_for_catering" is the venue field from "Package".
Answer: Not exactly what you want, but you could try adding a filter criterion on Venue to the Food View and expose the criterion.  That way the user can filter Food manually in the widget.
Comment: Thank you for your answer, I've tried that. But I think the form will become redundant..? because the user will need to choose the venue twice. But thank you for your suggestion! ^_^
Answer: I needed to filter a view based on a Taxonomy field in a content type. I found a way to do that and it's very easy.
1- make a contextual filter -> select provide default value.
2- select type -> Taxonomy term id from url, you will get new checkboxes appeared below it.
3- check the following:  Load default filter from term page,  Load default filter from node page, that's good for related taxonomy blocks, Limit terms by vocabulary.
4- select the Vocabulary you want to filter based on.
5- Multiple-value handling: Filter to items that share all term.


Change field value with hook_views_pre_render()

Question: I'm using Views in 8.4.0 and attempting to change the output of a field value with  hook_views_pre_render(). The default value of the field is a node ID. The intent is to replaced the value with a static string depending on a whether or not it's contained in a predefined array using in_array().
The aforementioned is relatively straightforward.
I begin by looping through the results:
<code>  for ($i = 0; $i < count($view->result); $i++) {
    if (isset($view->result[$i]->node_field_data_node__field_lesson_nid)) {
      $viewed = in_array($view->result[$i]->node_field_data_node__field_lesson_nid, $viewed) ? 'yes' : 'no';
      // Replace the default Node ID value with $viewed.
      ...
    }
  }
</code>
The array $viewed contains a list of predefined node IDs. If the node ID exists in the array "yes" is output otherwise "no".
The problem is how to output the value for each row of results within the View object.
I tried the following at the above ellipsis:
<code>      $view->field['nid_2']->options['alter']['text'] = $viewed;
      $view->field['nid_2']->options['alter']['alter_text'] = TRUE;
</code>
"nid_2" is the token for node_field_data_node__field_lesson_nid.
The problem is this changes the field value for every row. The last row in the results determines the value. (The View also has multiple joins (relationships) which further compounds the complexity.)
So my dilemma is where to replace the value within each row of the $view->result.
Answer: I was trying to do something similar as well. I had an integer field and I wanted to replace the integer column with a string value. That was not working. So I had to add a separate string field, maintained the integer field as a hidden field and then overwrote the string field. The code that worked is given below.
<code>function module_views_pre_render(ViewExecutable $view) {
  // Change the comments column in the list of filings table in the view case
  if ($view->id() == 'my_view') {
    foreach ($view->result as $key => $value) {
      $custom_id = $value->_entity->get('custom_id')->value;
      $string = convert_id_to_string_get_user_name($custom_id);
      $value->_entity->set('string_field', $string);
    }
  }
}
</code>
There is documentation and sample snippets here but looks like it needs more documentation.
https://api.drupal.org/api/drupal/core!modules!views!views.api.php/function/hook_views_pre_render/8.2.x


Corporate website, each page different style

Question: I need to create a corporate business website under Drupal 7, and on each page (home, about, sevices, contact, etc.) the design is really different.
What would be the best way to structure/build this in Drupal? I'm used to Wordpress theme per page, but this does not look like it's built in Drupal.
Like thi theme: http://demo.drupalizing.com/?theme=corporateclean
http://drupal.org/project/corporateclean
The design change quite a bit for each page. But when I download the theme, I don't see how they did that, since there's only that general page...
Answer: You can create a new theme using one of the many starter themes, and then override templates to get as specific as you please.
For example, to override a particular content type's look, you'd edit node--contenttype.tpl.php where contenttype is your custome content type.
The template guide contains further info, including naming conventions to get your templates applied in the right place.
Comment: Thats a very informative finding.
Answer: In such case what I do is: I write the following code in my template.php of the theme
<code>function themename_preprocess_page(&$vars) {

     if (isset($vars['node']->type)) {

     $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;

 }
    }
</code>
Then I create a page.tpl.php for each content-type. For example if it is for content-type hotnews, then I create a page--hotnews.tpl.php file in my templates folder. In page--hotnews.tpl.php I write  the things that I want to appear in my hotnews page.
For the front page, I create page--front.tpl.php. And I write  the things like menu, header and footer that are common in all pages, in html.tpl.php.


What would be an efficient way to select float in a finite sized array that is more close to zero?

Question: For each function, I get/have a finite sized array of floats that I need to pick.
So if I have something like
1)
 {-0.02, 0.5, 0.98, -0.15, etc... }

I would pick "-0.02" from this list.
2)
 {-0.78, 0.003, 0.1, -1.8, etc... }

and now, I would pick "0.003" from this list.
This is just an example. In my real program, I have floats with 5-6 decimal points.
Comment: What I tried: I made a temporary array. I went go through each elements, if it is negative, I multiply it by -1 and put them into this temporary array.
And then check for < 0. AGAIN!!! so yes, it is not efficient and I am not sure if I will lose precision too in doing so.
Answer: std::min_element has an overload that takes a comparison function object; that's what I'd use here:
float val = *std::min_element(std::begin(v), std::end(v),
    [](float a, float b) { return fabs(a) < fabs(b); } );

Comment: @jbchichoko Jerry Coffin's algorithm is perhaps the nicest solution, I upvoted it. However, **your program will crash if you run it on an empty array**. Make sure you it never happens in your code.
Comment: @jbchichoko: Yes -- it's an iterator, not an index. You can subtract `your_container.begin()` to get an index (assuming it's a random access iterator, which mostly translates to the container being an array, vector or deque).
Comment: I am sure it might be the one I am looking for. But I am new to C++ so could explain briefly what it is doing exactly? what does the fabs() function do ?
Comment: @jbchichoko: `fabs` will return the absolute value for the given parameter (it differs from `abs` in the fact that `abs` only works on integral value, while `fabs` works exclusively on floating point values). `min_element` will return the element, which has the smallest value according to the comparison (given as third parameter of the function), so the smallest absolute value (distance from zero) in this case.
Comment: @jbchichoko: Grizzly has already answered most of your question -- just one minor addition. `std::min_element` returns an iterator to the chosen element. The `*` right before `min_element` dereferences the iterator it returns to get the value it's pointing it.
Comment: @JerryCoffin Also, if I now just want the element index in that array, I am sure removing the "*" won't work, right? Still getting my heads around the min_element.
Answer: You have to go through every number on the array anyway so the most efficient answer will be in O(n).
Once you know this, you realize that just going through each number and checking if it's closer to zero that the last one you selected does the deal.
Answer: Use std::min_element with a compare function should archive what you want.
template<class T>
const T& abs_min(const T& a, const T& b)
{
    return (fabs(a) < fabs(b)) ;
}

const SIZE = 5;
float v[SIZE ] {-0.78, 0.003, 0.1, -1.8, 0.8};
float val = *std::min_element(v, v+SIZE , min_abs);

Answer:
if you HAVE to use an array and it is small in size - simply iterate like std::min_element
if you have freedom to pick an ordered container use std::set<>. then use it=std::set::lower_bound(0) and compare *it with *(it+1). this would scale better for big data sizes


Prove that $v$ is a linear combination of $v_1,...,v_n$ if it is a linear combination of $w_1,...,w_m$

Question: How should I do this? Should I use the definition of linear independence?
Answer: Actually this is completely independant of any consideration of linear independance of the two family of vectors given. You just need to write down what it means to be a linear combination and the result will follow.
Every $w_i$ is a linear combination of $v_1,\dots,v_n$, thus there real numbers $\alpha_{ij}$ such that
$$w_i=\sum_{j=1}^n \alpha_{ij}v_j,\quad \forall 1\leq i\leq m.$$
Now $v$ is a linear combination of $w_1,\dots,w_m$, thus there exist real numbers $\beta_i$ ($1\leq i\leq m$) such that
$$v=\sum_{i=1}^m\beta_i w_i.$$
Now if you replace every $w_i$ by its expression given in the first equation, you get
$$v=\sum_{i=1}^m\beta_i \left(\sum_{j=1}^n \alpha_{ij}v_j\right),$$and because addition in vector space is commutative and associative, and because of the distributivity and "associativity" of scalar multiplication, this can be rewritten as
$$v=\sum_{i=1}^m\beta_i \left(\sum_{j=1}^n \alpha_{ij}v_j\right)=\sum_{j=1}^n\left(\sum_{i=1}^m \alpha_{ij}\beta_i\right)v_j,$$
which shows that $v$ is a linear combination of $v_1,\dots ,v_n$.
If all this seems unclear to you, try to write down some small examples to see how it works in a particular case.


Using View to List a Member's Organic Group with Inherited membership

Question: I am looking to create a view which will return any content a user has membership to.
Following steps from another post, I managed to return content which matches users membership. But this doesn't take into account content where membership is inherited. So a node which is linked to another node's audience doesn't appear in the view.
Steps taken:

Add new view. Show -> OG membership (important!)
Then in some display add a contextual filter:
OG membership: Entity id.
Provide default value: Type -> User ID from logged in user
Next to get the actual titles of the groups (as the base table is OG
membership, not node),
Add a relationship -> Group Node from OG membership.
Add a field -> Content: Title. Relationship -> Group node from OG
membership.

Using Views to List a Member's Organic Groups (7.x-2.3)
Answer: After digging around in the default views, I found a work around for my problem.
I cloned the view OG User groups (OG membership) which is normally attached to the user profile. I then filtered content against some custom fields to resolve my problem.
Its a work around admittedly, but I would advise people to check some of the other default views or the og_extras module for additional views.


Attempt at computing various values given a joint PDF

Question: Let the joint PDF of $(X, Y)$ be defined by
$$f(x, y) = \frac{c}{y} \text{exp}\left(-y -\frac{x}{y}\right) $$
for $x > 0$ and $y > 0 $

(a) Determine the constant $c$
(b) Find the marginal PDF of $Y$
(c) Find the conditional pdf of $X$ given $Y = y$
(d) Compute $\mathbb{E}[X^2 \mid Y = y]$

(a)
Ok, so using the fact that the sum of probability density functions equals $1$, I computed the value of $c$ as follows:
$$
\begin{align*}
1 = c \int_{0}^{\infty}\int_{0}^{\infty} \frac{1}{y} \text{exp}\left(-y - \frac{x}{y}\right) \mathop{dx} \mathop{dy} \\
= c\int_{0}^{\infty} \frac{1}{y} \int_{0}^{\infty}\text{exp}\left(-y - \frac{x}{y} \right) \mathop{dx} \mathop{dy} \\
c\int_{0}^{\infty} \text{exp}(-y) \mathop{dy} \\
= c \\
\Longleftrightarrow \boxed{c = 1}
\end{align*}
$$
(b) I compute the marginal PDF of $Y$ as follows:
$$
\begin{align*}
f_{Y}(y) = \int_{0}^{\infty} f(x, y) \mathop{dx} \\
= \int_{0}^{\infty} \frac{1}{y} \text{exp} \left(-y - \frac{x}{y}\right) \mathop{dx} \\
= \frac{1}{y} \int_{0}^{\infty} \text{exp}\left(-y - \frac{x}{y} \right) \mathop{dx} \\
= \frac{1}{y} \cdot y = 1,
\end{align*}
$$
but I'm pretty sure this is wrong. Can someone please check this part of the work for me? If it's right, then I'd have
$$
\begin{align*}
f_{X|Y} = \frac{f(x, y)}{f_{Y}(x, y)} = \frac{1}{y} \text{exp} \left(-y - \frac{x}{y}\right)
\end{align*}
$$
for $x, y > 0$ for part $(c)$.
(d): To compute $\mathbb{E}[X^2 \mid Y = y]$, we use the conditional pdf of $x$ given $Y = y$. So,
$$E[X^2 \mid Y = y] = \int_{0}^{\infty}x^{2}\cdot \frac{\text{exp}(-x/y)}{y} \mathop{dx} = 2y^{2}$$
(I omitted the steps for integration).
Comment: When computing the marginal PDF you seem to have lost a factor of $\exp(-y)$.
Answer: Part $(a)$ is correct.
In part $(b)$ you have made a mistake whilst calculating the integral.
\begin{align*}
f_{Y}(y) &= \int_{0}^{\infty} f(x, y) \mathop{dx} \\
&= \int_{0}^{\infty} \frac{1}{y} \text{exp} \left(-y - \frac{x}{y}\right) \mathop{dx} \\
&= \frac{1}{y} \int_{0}^{\infty} \text{exp}\left(-y\right)  \text{exp}\left(-\frac{x}{y} \right) \mathop{dx} \\
&= \frac{\text{exp}(-y)}{y} \int_{0}^{\infty} \text{exp}\left( - \frac{x}{y} \right) \mathop{dx} \\
&= \frac{\text{exp}(-y)}{y} \cdot y \\
&= \text{exp}(-y).
\end{align*}
For part $(c)$ you would then have that
$$
f_{X|Y}(x) = \frac{f(x, y)}{f_{Y}( y)} = \frac{\frac{1}{y} \text{exp} \left(-y - \frac{x}{y}\right)}{\text{exp}(-y)}
$$
which reduces to (I'll leave the details up to you)
$$f_{X|Y}(x) = \frac{\text{exp}(-x/y)}{y}.$$
Try and do part $(d)$.
Comment: Can you please check? I've updated my post.
Comment: Indeed, looks right to me!


JSON Templating

Question: As a bit of background, I'm in the early design phases of a large RoR
project for the company I work for and we're planning on sticking with
Rails for the next 5-10 years.  We're at this point in the project
we're trying to get some good practices and customize the framework to
work for what we're going to be needing need.  We've considered the
pros/cons of going with a full blown web-app (Backbone.js style) vs. a
static limited JS based Rails app.  While we would have loved to go
with a webapp, I've determined that going with Backbone.js would
cause:

Complete duplication of views and routes (a maintenance issue in the long run)
Difficulty tracking polymorphic associations and their routes
Wouldn't allow us to use the view helpers on the client side
(maintenance issue)
Duplication of some of the model information
Slow client-end computers (beyond our control), which would have
difficulty running it

To try and reduce this, we're decided to go with a more hybrid
approach but to push more of the logic back to the server side while
still maintaining a RESTFUL architecture as an API as best as
possible.  We're planning on having the initial page loads done
normally using Rails, and then any manipulations on the page send the
request via AJAX and receiving back a JSON object which contains the
rendered partial, and some additional information (ie. flash updates,
JSON representation of the object, additional JS includes if
necessary, etc.)
The problem we're running into, is that from my understanding, we
cannot maintain the RESTFUL architecture and have multiple
partials/views for that same data.  As an example of this, if I wanted
to request a list of Orders from the server via orders/index, it would
return only one view of the data.  If I had an extended table, a list,
or some other view/partial/widget which I wanted the requested partial
to be used for.
To that end, I've added a params[:partial] (which is either an add-on
on the route, or a url parameter) that provides the server both with
the information that is being requested, as well as the view which I
am expecting it to come in.  This would work well on it's own, however
I'd also like to have any additional information sent down from the
server at the same time (ie. flash updates, JSON representation of the
data, etc.).  Ideally we want this to be flexible, fast, and sent down
from the server in JSON format.
To that end, I've overriden the existing JSON responder as follows,
and you may notice the hack I've had to use to have it render the
HAML/ERB templates inside of the JSON:
<code>module ExtraFunctions
 def partial_options
   params.include?(:partial) ? { :partial => params[:partial] } : {}
 end

 def flash_options
   { :file => 'layouts/_flash.html.haml' }
 end
end

ApplicationController.send :include, ExtraFunctions

#I would love to be using the ERB templating and views
#instead of this kludge.  But this will have to do.

ActionController::Renderers.add :json do |json, options|

 #Change the format so we can render the html templates
 self.formats = [:html]
 options = { :layout => false }

 partial_opt = options.merge(self.respond_to?(:partial_options) ? self.partial_options : {})
 flash_opt   = options.merge(self.respond_to?(:flash_options) ? self.flash_options : {})

 obj = {
   json: json.as_json,
   partial: render_to_string(partial_opt),
   flash: flash,
   flash_partial: render_to_string(flash_opt),
   user: @current_user
   #js-includes: #Working on this
 }

 #Change the format back
 self.formats = [:json]

 json = obj.to_json(options) unless obj.kind_of?(String)
 json = "#{options[:callback]}(#{json})" unless options[:callback].blank?

 self.content_type ||= Mime::JSON
 json
end
</code>
You'll notice there is a spot in there for js-includes, the reason for
that is that I want the ability to have dynamic includes late in the
game using head.js.  This would be for easier dependency management,
as the initial view would not be including some of the partials that
are requested via AJAX (ie. if I grabbed a form to enter a new
address, and that form has some AJAX checking on it as included in the
top of it using a content_for tag).  Ideally, what I'd really like
this to be is a JSON layout to look something like (though with a more
sugar coated syntax I would hope):
<code>** json/application.json.erb **
{
   json: <%= json.as_json %>,
   partial: <%= render_to_string(partial_opt) %>,
   flash: <%= flash %>,
   flash_partial: <%= render_to_string(flash_opt) %>,
   user: <%= @current_user =>,
   js-includes: <%= yield :js_includes %>,
   <%= yield =>
}
</code>
I've been working on these considerations/issues for a while, and my
questions are two:
1)  Is there anything blatantly screamingly stupid about what we're
doing?  Is there a better or more standard solution?
2) Is there a way to have ERB render the templates for JSON?
Thanks!
Answer: Bottom line, this is a common problem that there isn't yet a strong opinion on solving.
David Heinemeier Hansson talked about this problem a bit at RailsConf 2011 when he introduced the new Asset Pipeline in Rails 3.1, noting that they've started using what they call pjax to handle refreshing parts of a page and suggested it'd be part of Rails in time.
37signals has also built Cinco (all-js mobile-app framework) and was planning on open sourcing it, but I believe they've started growing away from some of the ideas they were building it with, so I don't know what the status is.
Comment: Interesting, thanks.  I had watched the Keynote, however had forgotten about PJAX.  It looks interesting, though the issue as I see it is that with a RESTful architecture you are specifying the data you need, however with someone like PJAX (or my above solution), you're now also requesting that it be pre-rendered in a specific format for different uses.  I suppose if there is no better solution, I will continue work on this as best I am able.  Thanks!

JSON Templating


Executar .BAT em segundo plano ao iniciar Windows

Question: Como posso rodar esse script BAT em segundo plano ou invisível ou sem janela? Adicionei o .bat em Startup, ele mostra o terminal em execução, mas não quero mostrar janela alguma, já usei ferramenta de conversão de .bat para .execom opção de inivisível mas não funcionou.
cd c:\xampp\htdocs\public_html\simrede

c:\xampp\php\php.exe -S localhost:8000

Comment: Dê uma olhada aqui https://www.thewindowsclub.com/run-batch-files-silently-on-windows
Comment: É um script para rodar pelo agendamento, por onde?
Comment: @rbz quero que ele inicie junto com o sistema, ele já inicia, mas não quero que seja visualizada janela executando, entende?
Comment: Ele inicia junto do sistema como? Onde? Detalhe ao máximo, pois a forma que chama seu .bat é fundamental para saber!
Comment: @rbz Coloquei ele na pasta `Startup`, assim quando faço login ele inicia, mas fica mostrando a janela do terminal, e não quero que seja mostrada janela
Comment: START /B linha_de_comando.bat
Comment: @DanielOmine, não funcionou
Comment: Dependendo dos recursos e ambiente, uma solução pode ou não funcionar. Como são muitas variantes, procure esses termos "run bat file in background" no google.
Comment: Fico me perguntando o que leva um ser a negativar uma pergunta clara como essa
Comment: Olá @LeandroAngelo já resolvi, minha resposta está abaixo. Obrigado
Comment: Então marque-a como tal... para não deixar essa pergunta aberta
Comment: Só posso marcar minha própria resposta após dois dias de publicada.
Answer: No meu caso, eu uso um script disparando-o por período, e então executo com outro usuário: Executar script PHP minimizado ou oculto, pelo Agendador de Tarefas
Você pode fazer dessa forma que fiz, e usar a opção "Ao fazer logon" para disparar:
Comment: Esta opção não serve pois o usuário teria que configurar em sua máquina, como é para implementar em um instalador não é interessante
Comment: Achei que fosse algo para server, então dei a alternativa mais prática. Mas neste caso, a melhor forma mesmo seria converter, como na resposta do Laércio.
Answer: Para o meu caso fiz o seguinte:
Criei um script em .vbs com o seguinte conteúdo e adiciono em Startup para iniciar no logon:
set objSh = CreateObject("WScript.Shell")
objSh.Run "cmd /k c:\xampp\htdocs\simrede\inicia-PHP-xampp.bat", 0

Criei outro script com os comandos que desejo que sejam executados, e salvando  com nome inicia-PHP-xampp.bat, na pasta c:\xampp\htdocs\simrede\
Assim o script inicia-PHP-xampp.bat inicia em segundo plano.
Answer: Isso não é possível sem outros recursos como o VBS que você contornou, a menos que você volte no tempo aquém do Windows XP, quando os SOs da Microsoft eram apenas uma interface rodando no MSDOS.
Mas tem coisas que você pode fazer para minimizar esse efeito:
CMD /C "MODE con cols=14 lines=1 & @SeusComandosAqui"

Esse código executa um comando no MSDOS e fecha logo que acaba, também reduz ao máximo o tamanho da janela. Você copia esse código e cria um novo atalho com ele, a seguir marque no atalho para iniciar MINIMIZADO.
Agora ele:

inicia minimizado,
com janela mínima e
encerra logo que executa.

Agora você pode colocar esse atalho na pasta INICIALIZAR do menu iniciar, e toda a vez que você logar, ele vai rodar.
Ou então você pode criar uma tarefa agendada:

Windows - %windir%\system32\taskschd.msc /s
Prompt - schtasks /create /? - veja as opções de onlogon/onstart.
Talvez o parâmetro onstart até mesmo execute antes de carregar a tela de logon igual faz CHKDSK que checa a integridade do disco.

Mas de qualquer forma, pra que precisa(va) de um batch-script pra isso? Basta criar um atalho com os parâmetros desejados para iniciar seu servidor


Como montar SELECT em lambda C#?

Question: Recentemente pedi ajuda para montar um SELECT para trazer o preço dos produtos
Como montar SELECT
Me deram essa solução que funcionou perfeitamente:
SELECT P.PROCODIGO, P.PRONOME, H.HISPRECO
FROM PRODUTO P
INNER JOIN HISTORICO H ON P.PROCODIGO = H.PROCODIGO
WHERE H.HISDATA = (SELECT MAX(HISDATA) FROM HISTORICO WHERE PROCODIGO = P.PROCODIGO)

Porém agora preciso montar esse mesmo SELECT em lambda com C#, pois comecei a usar Entity. Alguém pode me ajudar?
Obrigado!
Comment: você esta usando contexto?
Comment: Uso, mas também uso unidade de trabalho e repositórios.
Answer: Ficaria assim:
var produtos = db.Historicos
                 .Include(h => h.Produto)
                 .OrderByDescending(h => h.HistoricoData)
                 .GroupBy(h => h.ProdutoId)
                 .Select(group => group.FirstOrDefault())
                 .ToList();

No Entity Framework não se deve pensar como no SQL. A maneira de fazer as coisas é diferente. O SQL gerado possivelmente não será igual, mas o resultado será.
Comment: Faz: http://pt.stackoverflow.com/a/80696/2999
Comment: Entendi, mas no caso eu estou usando repositório da unidade de trabalho, faz diferença?
Comment: Eu estou tentando criar um método no meu repo, mas o Include pede uma string path. No caso o Históricos deve ser um DbSet?
Comment: Pode ser um string ou uma expression. Não use repositório sobre EF. Você leu o link que eu te mandei?
Comment: Sim, mas o meu projeto já está montado com repos e unidade de trabalho então por enquanto não vou mudar. Mas no meu include não aceita expression, o db no caso é um DbContext?
Comment: Bom, você irá trabalhar com limitações e seu projeto terá problemas em breve por sua decisão. Aceitaria o `Include` se você tivesse feito do jeito certo. O db é sim um `DbContext`.
Comment: Eu vou mudar meu projeto, só preciso ler melhor o que você me passou e estudar um pouco mais. Mas eu tive que fazer com linq o Select, mesmo assim muito obrigado pela ajuda!

Como montar SELECT em lambda C#?


setCompoundDrawables button android not showing images

Question: I want to create button with image in grid view below is my code:
My FragmentHome.java:
package com.erlanggastudio.myagri.fragments;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.erlanggastudio.myagri.R;
import com.erlanggastudio.myagri.adapters.AdapaterGridView;
import com.erlanggastudio.myagri.adapters.AdapterGridViewItem;
import com.erlanggastudio.myagri.adapters.AdapterImageSlider;

import java.util.ArrayList;

public class FragmentHome extends Fragment implements ViewPager.OnPageChangeListener {

    //For Page Viewer Dots
    //private ImageButton btnNext, btnFinish;
    private ViewPager intro_images;
    private LinearLayout pager_indicator;
    private int dotsCount;
    private ImageView[] dots;
    private AdapterImageSlider mAdapter;
    private int[] mImageResources = {
            R.drawable.image_header_1,
            R.drawable.image_header_2,
            R.drawable.image_header_3
    };

    GridView gridview;
    AdapaterGridView gridviewAdapter;
    ArrayList<AdapterGridViewItem> data = new ArrayList<AdapterGridViewItem>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.fragment_home, container, false);

        intro_images = (ViewPager) v.findViewById(R.id.viewPage1);

        pager_indicator = (LinearLayout) v.findViewById(R.id.viewPagerCountDots);

        mAdapter = new AdapterImageSlider(getActivity(), mImageResources);
        intro_images.setAdapter(mAdapter);
        intro_images.setCurrentItem(0);
        intro_images.setOnPageChangeListener(this);
        setUiPageViewController();

        gridview = (GridView) v.findViewById(R.id.gridView1);

        data.add(new AdapterGridViewItem(getResources().getString(R.string.menu_product), ContextCompat.getDrawable(getActivity(), R.drawable.ic_product),0));
        data.add(new AdapterGridViewItem(getResources().getString(R.string.menu_cart), ContextCompat.getDrawable(getActivity(), R.drawable.ic_cart),1));
        data.add(new AdapterGridViewItem(getResources().getString(R.string.menu_checkout), ContextCompat.getDrawable(getActivity(), R.drawable.ic_checkout),2));
        data.add(new AdapterGridViewItem(getResources().getString(R.string.menu_info), ContextCompat.getDrawable(getActivity(), R.drawable.ic_info),3));
        data.add(new AdapterGridViewItem(getResources().getString(R.string.menu_profile), ContextCompat.getDrawable(getActivity(), R.drawable.ic_profile),4));
        data.add(new AdapterGridViewItem(getResources().getString(R.string.menu_about), ContextCompat.getDrawable(getActivity(), R.drawable.ic_about),5));

        setDataAdapter();

        return v;
    }

    // Set the Data Adapter
    private void setDataAdapter() {
        gridviewAdapter = new AdapaterGridView(getActivity(), R.layout.lsv_item_mainmenu, data);
        gridview.setAdapter(gridviewAdapter);
    }

    private void setUiPageViewController() {

        dotsCount = mAdapter.getCount();
        dots = new ImageView[dotsCount];

        for (int i = 0; i < dotsCount; i++) {
            dots[i] = new ImageView(getActivity());
            dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));

            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
            );

            params.setMargins(4, 0, 4, 0);

            pager_indicator.addView(dots[i], params);
        }

        dots[0].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        for (int i = 0; i < dotsCount; i++) {
            dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
        }

        dots[position].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}

Adapter code is :
package com.erlanggastudio.myagri.adapters;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;

import com.erlanggastudio.myagri.R;
import com.erlanggastudio.myagri.activities.ActivityAbout;
import com.erlanggastudio.myagri.activities.ActivityCart;
import com.erlanggastudio.myagri.activities.ActivityCheckout;
import com.erlanggastudio.myagri.activities.ActivityInformation;
import com.erlanggastudio.myagri.activities.ActivityMenuCategory;
import com.erlanggastudio.myagri.activities.ActivityProfile;

import java.util.ArrayList;

public class AdapaterGridView extends ArrayAdapter<AdapterGridViewItem> {
    Context mContext;
    int resourceId;
    ArrayList<AdapterGridViewItem> data = new ArrayList<AdapterGridViewItem>();

    public AdapaterGridView(Context context, int layoutResourceId, ArrayList<AdapterGridViewItem> data) {
        super(context, layoutResourceId, data);
        this.mContext = context;
        this.resourceId = layoutResourceId;
        this.data = data;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        View itemView = convertView;
        ViewHolder holder = null;

        if (itemView == null) {
            final LayoutInflater layoutInflater = (LayoutInflater) mContext
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            itemView = layoutInflater.inflate(resourceId, parent, false);

            holder = new ViewHolder();
            holder.btnItem = (Button) itemView.findViewById(R.id.buttonMenu);
            holder.txtItem = (TextView) itemView.findViewById(R.id.name);
            itemView.setTag(holder);
        } else {
            holder = (ViewHolder) itemView.getTag();
        }

        final AdapterGridViewItem item = getItem(position);
        holder.btnItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (item.getPoss() == 0) {
                    mContext.startActivity(new Intent(mContext, ActivityMenuCategory.class));
                } else if (item.getPoss() == 1) {
                    mContext.startActivity(new Intent(mContext, ActivityCart.class));
                } else if (item.getPoss() == 2) {
                    mContext.startActivity(new Intent(mContext, ActivityCheckout.class));
                } else if (item.getPoss() == 3) {
                    mContext.startActivity(new Intent(mContext, ActivityInformation.class));
                } else if (item.getPoss() == 4) {
                    mContext.startActivity(new Intent(mContext, ActivityProfile.class));
                } else {
                    mContext.startActivity(new Intent(mContext, ActivityAbout.class));
                }
            }
        });
        holder.btnItem.setCompoundDrawables(null, item.getImage(), null,null);
        holder.txtItem.setText(item.getTitle());

        return itemView;
    }

    static class ViewHolder {
        Button btnItem;
        TextView txtItem;
    }

}

And layout code is :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical"
            android:paddingTop="10dp">

            <Button
                android:id="@+id/buttonMenu"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:background="@drawable/button_bg"
                android:paddingTop="20dp"/>

            <TextView
                android:id="@+id/name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dp"
                android:gravity="center_horizontal"
                android:textSize="16sp"
                android:paddingTop="10dp"/>
        </LinearLayout>
</RelativeLayout>

I'm try to show dinamicly image in button using :
holder.btnItem.setCompoundDrawables(null, item.getImage(), null,null);

But the image in button not showing, this is my result:

any wrong with my code or i'm miss shomething.....???
Comment: Why you need to show compound drawable? you can change this button to ImageView..
Comment: i'm using button cause i need button hover when user pressed the button, and i don't wan't to using imageview and using hover for image.....
Comment: You can use the ImageView or ImageButton, just search for it you get answer..
Answer: Try this,
 holder.btnItem.setCompoundDrawablesWithIntrinsicBounds(0,item.getImage(),0,0);

Comment: nit: two dots `.` here inside `btnItem..setCompound...`, I tried to edit this answer, but SO says: `Edits must be at least 6 characters; is there something else to improve in this post?`


AWS SSL vs Comodo (or other)

Question: Is there an advantage or reasons for choosing to use a paid SSL certificate from Comodo (or another) over using the new AWS Certificate Manager (free SSL certificates)?
I'm specifically talking about Domain Validated SSL (not Organizational or Extended Validation)
Answer: Well AWS free certificates can only be deployed either on an ELB or aws cloudfront. If you intend to use the certificate in either one of them then AWS certificates is the best option, other wise for any other web server you have to opt a paid SSL certificate, AWS certificate won't work their.

AWS SSL vs Comodo (or other)


Parâmetro embutido na action do form não é passado via GET

Question: Tenho o seguinte código HTML, e na action seto o endereço obedecendo a minha query string:
<form name="searchCard" class="serachCard" method="get" action="painel.php?spv=nav/buscarCard">
    <fieldset>
        <legend>Pesquisar:</legend>
        Buscar:
        <input type="text" name="consulta" />
        <input type="submit" name="" class="btnSearch" value="Buscar" />
    </fieldset>
</form>

E realizo o submit no form (esperando que ele vá para a pagina indicada no action e leve em GET o valor "azul" digitado no form):

Mas o que acontece é que ele não leva o parâmetro spv que fazia parte da query string no action, e fica na home do projeto (painel.php).

Alguma sugestão?
Comment: Quando possível poste o código e não a imagem dele, alguns proxys podem bloquear ela.
Answer: Há um problema conceitual no código. Vejamos as opções para submissão de formulários HTML:
POST
<form method="post" action="painel.php">

Os valores dos campos do formulário são enviados no corpo da requisição. A URL fica "livre" para você colocar parâmetros adicionais, mas cuidado para não usar os mesmos nomes de campos do formulário.
GET
<form method="get" action="painel.php">

Os valores dos campos são concatenados na URL:

painel.php?campo1=valor1&campo2=valor2

O corpo da requisição vai vazio e parâmetros colocados "manualmente" no action são perdidos. Isso está de acordo com a especificação do HTML.
Solução para incluir parâmetros adicionais em formulários GET
Campos ocultos (hidden):
<input type="hidden" name="campo" value="valor"/>

Limitações do método GET
Não é recomendável usar URLs muito grandes, pois isso pode causar erros. Por exemplo, o Internet Explorer suporta apenas 2048 caracteres na URL. O servidor HTTP Apache possui um limite de 4000. Veja mais detalhes sobre limitações em navegadores e servidores HTTP neste link. Um limite "seguro" apontados por alguns é limitar a URL em até 2000 caracteres.
Deve-se tomar cuidado quando há muitos campos em formulários que usam o método GET, pois rapidamente se alcança um tamanho grande.
Answer: Se entendi bem, o seu problema é que o parâmetro spv não está sendo passado, certo? Eu sugiro colocar ele em uma entrada escondida (hidden input):
<form method="get" action="painel.php>
    <fieldset>
        <input type="hidden" name="spv" value="nav/buscaCard" />
        ...
    </fieldset>
</form>

Comment: @Luitame Disponha, e não se esqueça que você pode marcar uma resposta como aceita se ela resolve o seu problema. Quanto à barra, isso é normal - ela simplesmente foi "escapada" para ser corretamente passada na URL. O seu código do servidor (php) vai receber uma `/` corretamente, como é esperado.
Comment: dessa forma deu certo! Obrigado... Só o barra passado no valor do input hidden que ficou assim "spv=nav%2FbuscaCard&consulta=azul". Mas enfim deu certo acho que deva ser algo relacionado ao charset! Vlw
Answer: Na sua action deixa apenas o nome do arquivo.
<form method="get" action="painel.php">

e no php verifique se o valor foi definido e contem algo.
if(isset($_GET['consulta']) && !empty($_GET['consulta'])){
  echo 'valor preenchido';
}else{
  echo 'valor vazio';
}


Electric guitar tone control fault

Question: I've got Epiphone LP Special II for two years.
Some time ago I noticed that tone pot set at maximum or minimum was cutting all lows or highs and the guitar lost power (volume doesn't changes while I was increses vol at amp and it was audible on distortion). Next all sound disappeared and then I decided to change the potentiometer. I bought the same value, but smaller size in local electrical shop and soldered new one in the same way as previous was. I also changed the capacitor.
Now guitar sound ok on bottom string at clean, but at top two, or while playing chords it sound like overdriven though low gain at amp. At distorion it sound like phone call - lows and highs are cutted.
What can I check now? Maybe pickups are guilty?
Comment: LPs have two pups. Is this problem with one in particular, and the other is normal?
Comment: Nope, the problem is with both pickups singly and together.
Comment: Did you change one or both tone pots?
Comment: One, 'cause in Special II I have just one for tone and one for vol.
Comment: You say you bought the same value potentiometer, but did you buy the same type?  I.e. either logorithmic or linear, see this article: http://www.diyguitarmods.com/potentiometer.php
Comment: No, no, I bought the same type too :) I'm a little in electronics, so it wasn't mystery to me. Only one difference is in size of this pot, 'casue oryginal one had longer knob and now I can't screw new one to the oryginal hole. I'm wondering how and where look for clue.
Comment: either way, different type potentiometer wouldnt cause this, it would just be different in terms of response, not audio quality
Answer: When you say it "sounds ok on bottom string," are you are talking about the bottom pickup (the bridge pickup) or "treble"/down position on the 3-way switch?  If that sounds okay, and it is only the middle and top positions (middle uses both pickups, top "rhythm" uses just the neck pickup), then it sounds like your problem might be something involving the neck pickup or its wiring. The first thing to do would be to double check all your soldering, and check it against the LP Special II wiring diagram:

If you have an electronic multi-meter you can use it to check the resistance (in Ohms) of the pot you changed.  In a LP guitar typically 500k pots are used, but depending on where you buy the pot they can often be off by a little bit, or a lot if they are lower quality, and that could cause tone loss. You could also replace the 3-way switch, as those are fairly inexpensive, and upgrade the output jack if you are comfortable with wiring and soldering. It's not guaranteed that this would fix the problem but if you do it right it can't hurt.  You also can check continuity with the meter, and make sure all the ground wires are connected to the right places. As far as the details go of troubleshooting an electric guitar's electronics, check here for a previous answer.
If you can't find any problems with your soldering and your wiring looks correct, I would recommend taking it to a guitar shop to have a qualified tech take a look at it. On the other hand, if you could conclusively determine it was a problem with the neck pickup, you could take this opportunity to upgrade that pickup.  For about $50-$100 you can get a new pickup that would probably make your guitar sound a lot better (at least when using rhythm or middle setting), or you could get a pair of pickups and replace both for under $150.  Again, don't do that unless you can confirm it is in fact the neck pickup to blame.
In the long run though, if you can't fix it yourself, then either paying for a guitar tech to fix it or buying new pickups might not be the way to go, because either of those options could cost $100 or more.  It might make more sense to get a new guitar if you are serious about playing. New pickups in that thing would cost about as much as the whole guitar did in the first place, and for not much more money you could step up to something like an Epiphone Les Paul 100 that I have heard pretty good things about.
Comment: I dont know what's your experience with guitar, but bottom strong usually means the low E or if bottom strings is said, it usually refers to the 3 wounded strings, E,A and D, so i don't think this can be a pickup issue, since your answer is based on that low string statement
Comment: I thought it was a typo and he meant bottom pickup.  But if its just one string that is the issue, that could still be a pickup problem. Usually a problem with the pots will effect all the strings.  Either way the rest of my answer still applies as he will want to troubleshoot the entire electronic system of the guitar to find the problem (check continuity, check all the solder joints, check component values with a multimeter, as I also mentioned in my answer).
Answer: What is the capacitor you bought? Did you get one of the same type as the one that was there before? Good capacitors for audio, especially guitar applications, are not easy to find, there is a big counterfaction market in electronic components, and audio is one of the applications where you actually note the difference between originals and counterfeits...
My suggestion is that first you double check the soldering, the ground on a pot can be hard to solder if you're not experienced, then check the pins of the pot and if you have a multimeter check for continuity with ground on every pin, the initial volume problem could be something like this.
If you see everything is okay, try buying a new capacitor from a decent supplier, also, if possible, buy an indicated capacitor for audio. It should be a non polarized capacitor because you have both negative and positive signs going through it.
This should be a cheap repair, provided that you can change it yourself...
If the problem persists, try to seek assistance from someone experienced, either a  qualified technician at a store, someone you know is good with electronics or just someone that has been playing guitar for a long time, maybe they have run into somethign similar and can give you an insight...
Answer: This might not be it, but it might be worth a try.
You said that the guitar is a couple of years old.
My friend knows a luthier that works almost exclusively on G&L's.
When my friend asked if he should use WD-40 to clean his pots, the luthier said no.
He said to take each pot, and dial it from 0-10 and back to 0 again, 40 times.  Each pot.
What will happen is the oxidation will simply fall off the pot.
Worth a try.
Comment: Good idea.. there is also electrical contact cleaner that is made for this purpose. It doesn't leave any residue and it's safe for electrical components.

Electric guitar tone control fault


Manipulação de data frame

Question: Olá,
Estou tentando manipular uma base de dados com 300+ observações, mas cada observação tem um número diferente de colunas. O problema é que a partir de determinado ponto, as colunas passam a se repetir, mas possuem diferentes valores e eu queria de alguma forma junta-las.
O que eu quero essencialmente é, dentro de um objeto, salvar as informações de cada observação de uma forma que ajude na visualização.
Por exemplo:
            a   b   c   d    e  c   d   e   c     d    e
    Obs_1   AA  BB  CC  8.3  A  SSD 2.3 RN  S76   5    A
    Obs_2   SS  DA  LL  5    A  SDD         AD23  8.2  A

E eu gostaria de transformar em algo assim:
         a   b    c      d   e
Obs_1   AA  BB  CC76    8.3  A
                SSD89   2.3  RN
                S76      5   A
Obs_2   SS  DA  LL       5   A
                SDD
                AD23    8.2  A

É possível fazer isso de uma maneira não braçal no R? Note ainda que existem valores no banco de dados que não possuem valor, alguns valores o R completa com NA, outros ele simplesmente deixa em branco.
Comment: Por favor, se a data.frame se chamar `dados`, edite a pergunta com a saída de `dput(head(dados, 20))`, para termos uma cópia exata da estrutura dos dados.
Comment: Do jeito que foi feita a pergunta, sem um conjunto de dados de exemplo, e difícil entender exatamente a natureza do problema.
Answer: Veja se esse código ajuda. Estou testando com o mtcars. Você precisa instalar os pacotes dplyr, tidyr e janitor
mtcars
# renomeia as colunas para ficar parecido com seu exemplo
names(mtcars) <- c("a", "b", "c", "d", "b", "c", "d", "a", "b", "c", "d")

mtcars %>%
  slice(c(1, 2))

# A tibble: 2 x 11
      a     b     c     d     b     c     d     a     b     c     d
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1   21.    6.  160.  110.    6.  160.  110.   21.    6.  160.  110.
2   21.    6.  160.  110.    6.  160.  110.   21.    6.  160.  110.

res <- mtcars %>%
  # pega as primeiras linhas para ficar parecido com seu exemplo
  head(2) %>%
  # transforma os nomes em unicos
  janitor::clean_names() %>%
  # empilha todos os dados
  gather() %>%
  # separa as colunas respectivas e os respectivos índices
  separate(key, c("letra", "numero"), sep = "_", fill = "right") %>%
  # substitui NA por 1 no caso da primeira separação
  replace_na(list(numero = "1")) %>%
  # completa as combinacoes de indices e letras que nao apareceram
  complete(letra, numero) %>%
  # essa parte nao sei se precisa
  group_by(letra, numero) %>%
  summarise(res = first(value)) %>%
  ungroup() %>%
  # espalha as letras nas colunas
  spread(letra, res)

res

# A tibble: 3 x 5
  numero     a     b      c      d
  <chr>  <dbl> <dbl>  <dbl>  <dbl>
1 1        21.  6.00 160.   110.
2 2         0.  3.90   2.62  16.5
3 3        NA   1.00   4.00   4.00

Manipulação de data frame


Fall in confusing about binomial distribution... really need help please.

Question: I am wondering that whether binomial distribution can be expressed as conditional probability. For example, is equation $P_{X\mid N}(x)=\Pr(X=x\mid N=n)$ where variable $X$ is number of successful trials and $N$ is number of total trials correct? In my text book, binomial distribution is expressed as conditional probability. Please see image bellow,
image. They have $P(X_1=i, X_2=j\mid X=i+j)=\begin{pmatrix}{i+j}\\i\\ \end{pmatrix}p^i(1-p)^j$. Does this mean $P_{X\mid N}(x)=Pr(X=x\mid N=n)$ is correct? I know this question is somehow pointless, but I really hope to know.
Answer: If $X$ and $Y$ are independent Poisson-distributed random variables with respective expected values $\alpha$ and $\beta$ then the conditional distribution of $X$ given $X+Y$ is a binomial distribution with parameters $X+Y$ and $\dfrac \alpha {\alpha+\beta}$.


VeeValidate multiple password constraints

Question: I'm wondering if it's possible to have multiple password requirements passed to VeeValidate in order to display which requirements a user is missing.
For instance, if we require that a user's password should have at least one uppercase letter and at least one number and be at least 5 characters long, and the user types in "a1bb", we'd like to be able to display two error messages; one associated with the length requirement not being met and one related to the uppercase requirement not being met.
Ultimately, we'd like to be able to do something like this:

Would that be possible with VeeValidate? Or are there any examples of a similar approach?
Comment: I don't have time to write an answer now, but I think you should give a look at https://baianat.github.io/vee-validate/guide/components/validation-provider.html#scoped-slot-data
Comment: I'm also interested if someone have already done what you asked
Comment: You might find [Reference - Password Validation](https://stackoverflow.com/q/48345922/3600709) useful.
Answer: VeeValidate allows you to display multiple errors fields but you need to disable the fastExist config option first:

VeeValidate only generates one message per field by default as it uses
  a fast-exit strategy when running the validation pipeline. [...] To disable this behavior you may want to configure the
  fastExit option in VeeValidate's config or use the continues modifier. (source)

For the rules you want to apply to password, you can use the existing min rule for the minimum length.
For the other rules (check upcase, lowercase, special char and digit), it's about regex check. VeeValidate actually provides a regex rule but in your case you need multiple ones.
So you need to define custom rules. I put some examples in the snippet below in the created hook but you also can define them globally.

In my example, I create a method to return a css class error by checking the errors by rule name.(source)
Now the style is yours.

const config = {
  fastExit: false
}
Vue.use(VeeValidate, config)

new Vue({
  el: "#app",
  data() {
    return { password: '' }
  },
  created() {
    this.$validator.extend('upCase', {
      getMessage: () => "One uppercase character",
      validate: value => value.match(/[A-Z]/g) !== null
    })
    this.$validator.extend('number', {
      getMessage: () => "One number",
      validate: value => value.match(/[0-9]/g) !== null
    })
  },
  methods: {
    errorClass(rule) {
      return {
        'error': this.errors.firstByRule('password', rule)
      }
    }
  }
})
li {
  color: #B1B1B1;
}
li.error {
  color: #262626;
}

  <input type="text" v-validate="'min:8|number|upCase'" name="password" >

One uppercase character

One number

8 characters minimum

Answer: check this solution
make a custom rule form VEEVALIDATE
STRONG PASSWORD VALIDATION
http://frankclark.xyz/veevalidate-strong-password-and-confirmation-validation


Not getting file URL from bundle

Question: I am loading PDF file in PDFView but unable to get PDF File URL from Bundle.
Please check below code :
let pdfView = PDFView(frame: self.view.bounds)
let myFileName = "sample"
guard let url = Bundle.main.url(forResource: myFileName, withExtension: "pdf") else {
         return
}
pdfView.document = PDFDocument(url: url)

self.view.addSubview(pdfView)

Every time I am getting nil in url.
Edit :
Here is my Project Window:

Am I making any silly mistake ?
Please guide me.
Thanks in Advance.
Comment: Can you edit your question to show your project window?  I'd like to see if/how you are including your `sample.pdf` into your application bundle.
Comment: I have added my Project Window please check my updated question.
Answer: I got problem not sure it's in Latest XCode but in XCode 9.5(Beta) while you adding any external file in your project and select bundle target still its not adding into bundle.
Solution :
You need to click on file which you want to add into your target bundle and check manually from property window.
Please check below screen shot from more detail:
While adding file into project I have checked it but still its not adding in selected target.

Now what I need only check related target and its working as expected.

Not sure its a bug or new update in Latest XCode.
But my problem is solved.
Thanks.
Answer: No, you're not making a silly mistake.
I believe you simply need to add your pdf file as a resource to be copied.
Go into your Project's Build Phases and click on "Copy Bundle Resources" and then add "sample.pdf" to the list of files being copied, like this:

And then make sure it appears in that list, like this:
Comment: Right.  Adding the pdf file as a "target member" is essentially doing the same thing as what I did up above.
Comment: Thanks @Michael I have solved my problem but with different approach and yes your solution also works well to solve my problem.

Not getting file URL from bundle


How to onclick open WhatsApp in iPhone or Android with number like +55 (51) 9988-7766

Question: How to onclick in some link in page, open WhathsApp in iPhone or Android with number like +55 (51) 9988-7766 to start a conversation?
Answer: After some test its working for me:

   (51) 9988-7766