text:
Q: Using a Morse function to find the number of points of each index During my Algebraic Topology course, we began to talk a bit about Morse functions. I was a bit lost on the topic, and my notes are lacking, so coming across this problem, I'm not really sure what to do:

Consider the sphere $S^2 = \{ (x,y,z) \in \mathbb{R}^3 \mid x^2 + y^2 +z^2 = 1 \}$ and the Morse function $f: S^2 \to \mathbb{R}$ defined by $f(x,y,z) = x^2 + 2y^2 +3z^2$. Find the numbers $a_0, a_1, a_2$ of points of indices $0,1,2$ respectively

I know that $a_0 -a_1 + a_2 = \chi({S^2}) = 2$, but other than that I have no idea how to proceed. My notes seem to indicate that the gradient of some function should be involved somehow, but the gradient of what? $\nabla f$? And even then, I'm not entirely sure what to do with it.

A: Backing up a moment, let's establish what we're trying to find.  First, we want to find all of the critical points of the function $f$ (restricted to its domain, namely $S^2$).  The statement "$f$ is a Morse function" includes that each critical point is nondegenerate — its second derivative (in the directions tangent to $S^2$) at each critical point should have no kernel.  Then the index of that critical point is the number of negative eigenvalues of the second derivative at that critical point.
Now, $S^2$ is 2-dimensional, so the second derivative at any critical point is a symmetric $2\times 2$ matrix.  So it has two eigenvalues, and hence index $0$ (if both eigenvalues are positive), $1$ (one eigenvalue of each sign), or $2$ (both eigenvalues are negative).  If both eigenvalues of the second derivative are positive at some critical point, then that point is a local minimum; if both are negative, local maximum; mixed is a saddle point.
So now we've translated the problem entirely into geometry.  We have the standard sphere $S^2$, and we want to find: ($0$) the local minima of $f$; ($1$) the saddle points of $f$; ($2$) the local maxima of $f$.
One way to find these is by the method of Lagrange multipliers.  But why work so hard?  You happen to have very nice functions here which we can draw.  So consider a level surface $\{f = c\}$ for various $c\in \mathbb R_{>0}$.  When $c \approx 0$ is very small, the level surface won't touch the sphere; ditto for $c \gg 0$ very large.  As $c$ starts small, eventually the level surface touches the sphere; these points are local minima.  Then it keeps growing.  At the end it clears the sphere at some of the local maxima.  In general, critical points are when some level surface is tangent to the sphere.
What's the geometry of a level surface $\{f=c\}$?  You can read it off: it's an ellipsoid, which is longest in the $x$-direction, shortest in the $z$-direction, and intermediate in the $y$-direction.  (Why?  Calculate the intersections of $\{f=c\}$ with the three axes.)  So the first time $\{f=c\}$ touches the sphere, it does so twice, at the two $x$-direction poles $(\pm 1,0,0)$.  Summarizing earlier remarks, these are some of the critical points of index $0$.
Then the level surface continues to grow, and it intersects the sphere along an oval centered at the $x$-poles.  This ellipse is wider in the $y$-direction than in the $z$-direction.  These two widening ovals eventually meet at the $y$-poles — they haven't grown as fast in the $z$-directions — forming a cross at each pole.  This meeting is indicative of critical points of index $1$ at $(0,\pm 1, 0)$.
After the ovals meet, the level surface continues to grow.  What happens to the intersections?  Near the $y$-poles, it looks like the family of hyperbolas $uv=c$ in the $u,v$ plane: the curves change who connects with whom.  So now there are two ovals centered that the $z$-poles.  They shrink as $c$ grows, eventually to points.  These are the final two critical points: $(0,0,\pm 1)$, of index $2$.  After this, the level surface clears the sphere, and there are no more critical points.
So that's the list of critical points.  Maybe we should confirm that it really is the list.  Claim: If at least two of $x,y,z$ are non-zero, then $(x,y,z)$ is not a critical point.  Proof: Suppose that $x,y\neq 0$.  Then you can increase $x$ by $\epsilon$ and decrease $y$ by $\epsilon x / y$, and up to order $\epsilon^2$ you haven't moved your point off the sphere, but you've changed $f$ by something of order $\epsilon \times (2-1)$.  So it's not a critical point.

The solution to the problem is $(a_0,a_1,a_2)=(2,2,2)$.  But perhaps I should remark that all we used about $\nabla f$ were its zeros (and the Hessians of $f$ at those points).  Morse theory, in the sense of the full Morse complex, requires more from $\nabla f$: an understanding of the gradient flow trajectories.  The notion of "gradient flow" depends on the metric, and for this problem it's convenient to use the round metric, as then you can read off the pertinent gradient flows: they follow the axes.  I mean, the only flows that matter are the ones connecting critical points of adjacent index, and thus they must either start or end at $(0,\pm 1,0)$, and these are just the flows along $x=0$ or along $z=0$.
Thus the Morse complex for this function is, up to some sign convention,
$$ \mathbb Z^2 \overset{\bigl(\begin{smallmatrix} 1 & -1 \\ -1 & 1 \end{smallmatrix} \bigr)} \to \mathbb Z^2 \overset{\bigl(\begin{smallmatrix} 1 & 1 \\ 1 & 1 \end{smallmatrix} \bigr)} \to \mathbb Z^2 $$
in degrees $2$, $1$, and $0$, and so the homology is $(\mathbb Z,0,\mathbb Z)$, as expected.


text:
Q: Fourier-Transformation of Operator I have an operator $\hat{L}$ which gives
$$\hat{L} f(x) = \lambda \cdot f(x)$$
where $\lambda$ is the eigenvalue.
Now I Fourier-Transform my function $f(x)$:
$$\mathcal{F}(f)(p) = g(p)$$
Question: How do I transform my operator $\hat{L}$ such that it gives the same eigenvalues $\lambda$ when I apply it to $g(p)$?
Example:
Let's consider the special-case $f(x)=x^m$ and $\hat{L}=x\cdot \partial_x$. Therefore we have
$$\hat{L} f(x) = m \cdot f(x)$$
Now the Fourier-Transformation
$$\mathcal{F}(f)(p) = g(p) = (-i)^m \sqrt{2\pi} \delta^{(m)}(p)$$
How does my Operator $\hat{L'}$ look like, such that
$$\hat{L'} g(p) = m \cdot g(p)$$
Thanks for help!

A: The Fourier transform is a unitary operator on your space. This means that its transpose is its inverse, $\mathcal F ^* = \mathcal F^{-1}$. The typical thing to do is to replace $T$ with $\mathcal F T \mathcal F^*$. Observe that with this convention, you have
$$
(\mathcal F T \mathcal F^*)\hat f=(\mathcal F T \mathcal F^*)\mathcal F f=\mathcal F Tf=\lambda\mathcal Ff=\lambda\hat f
$$
provided that $f$ is an eigenfunction for $T$ with eigenvalue $\lambda$.
Edit: The Fourier transform interchanges the role of differentiation and multiplication by $x$. If I recall correctly, $-i\partial_x \mathcal F f=\mathcal F (-x f)$ and $x\mathcal F f=\mathcal F (-i\partial_x f)$, which means that in your example,
$$
\mathcal F^* x\partial_x\mathcal F f=\mathcal F^* x\mathcal F (-i x f)=\mathcal F^* \mathcal F (-\partial_x (x f))=-\partial_x (x f),
$$
that is, $\mathcal F^* x\partial_x\mathcal F=-\partial_x x$.

A: For clarity I will use a slightly different notation. Starting from $L_xf(x)=\lambda f(x)$ is there an operator $L_p$ such that $L_p \hat{f}(p)=\lambda \hat{f}(p)$ ($\hat{f}(p)$ is the Fourier transform of $f(x)$) ? The particular example is $f(x)=x^m$ and $L_x = x\partial_x$. In this case $\hat{f}(p)=(-i)^m\sqrt{2\pi}\delta^{(m)}(p)$.
First a word of warning: Care has to be exercised when manipulating Fourier transform, in particular when reversing the order of operations. An excellent textbook which explains such things is Robert Strichartz: A Guide to Distribution Theory and Fourier Transforms.
   From the observation that $${\cal F}[xf(x)](p) = -i\partial_p\hat{f}(p)$$ and $${\cal F}[\partial_x f(x)](p) = -ip\hat{f}(p),$$ we are led to propose that for this particular example $$L_p=-\partial_p p,$$ hence $$L_p\hat{f}(p)=-\hat{f}(p)-p\hat{f}^{(1)}(p).$$ Let us now investigate if $L_p \hat{f}(p)=\lambda \hat{f}(p)$ holds. We start with the right-hand side. Since the Fourier transform of $x^m$ is given as the multiple derivative of a Dirac delta function, it is clear that we shall have to work with distributions. I will use the short-hand notation $$<f,\varphi>=\int_{-\infty}^{\infty} f(p)\varphi(p)dp,$$ where $\varphi$ is a suitable test function, notably allowing for integration by parts with vanishing boundary terms. This leads to the formula $$<\delta^{(m)},\varphi>=(-1)^m<\delta,\varphi^{(m)}>=\varphi^{(m)}(0).$$ We can therefore evaluate the right-hand term as follows: $$\lambda<\hat{f},\varphi>=m(-i)^m\sqrt{2\pi}<\delta^{(m)},\varphi>=mi^m\sqrt{2\pi}<\delta,\varphi^{(m)}>.$$ For the first term on the left-hand side we get $$<-\hat{f},\varphi>=-(-i)^m\sqrt{2\pi}<\delta^{(m)},\varphi>=-i^m\sqrt{2\pi}<\delta,\varphi^{(m)}>.$$ For the second term on the left-hand side we get $$<-p\hat{f}^{(1)},\varphi>=-(-i)^m\sqrt{2\pi}<\delta^{(m+1)},p\varphi>=i^m\sqrt{2\pi}<\delta,(p\varphi)^{(m+1)}>.$$ In order to calculate the derivative on the right we use the general Leibniz rule $$(fg)^n=\sum_{k=0}^n \binom{n}{k}f^{(n-k)}g^{(k)}.$$ In our case the expansion will truncate after two terms: $$(\varphi p)^{(m+1)}=\binom{m+1}{0}\varphi^{(m+1)}p+\binom{m+1}{1}\varphi^{(m)}=\varphi^{(m+1)}p+(m+1)\varphi^{(m)}.$$ For the second left-hand term we therefore get $$<-p\hat{f}^{(1)},\varphi>=i^m\sqrt{2\pi}\left(<\delta,\varphi^{(m+1)}p>+(m+1)<\delta,\varphi^{(m)}>\right).$$ However, $<\delta,\varphi^{(m+1)}p>=0$, so after combining terms we obtain $$<-\partial_p p \hat{f},\varphi>=mi^m\sqrt{2\pi}<\delta,\varphi^{(m)}>,$$ which is in fact identical to the right-hand term, so the relation $L_p \hat{f}(p)=\lambda \hat{f}(p)$ holds.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Appscript: button that time stamps in column when clicked Need to create a button on google sheets, when clicked it time stamps in column AA
Thanks alot.

A: The following script may help you
this code updates the timestamp in cell AA1 every time it runs
function setTimeStamp() {
  SpreadsheetApp.getActive().getSheetByName('Sheet1').getRange('AA1').setValue(new Date())
}

and this code adds a timestamp to the AA column each time it runs
function addTimeStamp(){
  let sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1')
  sheet.getRange('AA'+(sheet.getRange('AA:AA').getValues().filter(String).length+1)).setValue(new Date())
}

A: function addtstoaa() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getActiveSheet();
  const rg = sh.getActiveRange();
  const r = rg.getRow();
  sh.getRange(r,27).setValue(new Date());
}


text:
Q: How to pass data from ContentPage ViewModel to ContentView Viewmodel in Xamarin Forms with mvvmLight? I have a ContentPage with some controls and a custom navigationcontrol(ContentView). The contentpage and navigationcontrol both have their respective ViewModels which their BindingContext is set to. Now I need to pass information from the page to the navigationControl.
What I tried:
 <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 xmlns:controls="clr-namespace:AuditApp.Controls;assembly=App"
                 x:Class="App.Pages.MyPage"
                 x.Name="contentpage">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="9*"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
            ...other controls...
            <controls:PageNavigationControl Grid.Row="1" Page="{Binding Page}"/>
        </Grid>
    </ContentPage>

Page is a custom BindingProperty in my navigationControl. The property works, but the BindingContext is wrong, it tries to bind to a "Page" property in the navigationcontrol's ViewModel.
If I change it like so:
<controls:PageNavigationControl Grid.Row="1" Page="{Binding Page}" BindingContext="{x:Relative Name=contentpage"}/>

then it doesn't work either, because it tries to bind to the ContentPage itself instead of its ViewModel. What I would need is to bind it to the ContentPage's ViewModel which has the Page Property I want to read from.
Is my approach wrong altogether? Should I use the MessagingCenter? I'm quite new to Xamarin Forms. Can anyone tell me how to do this properly please?

A: For anyone stumbling over a similar issue, this is how I solved it. I'm not completely happy about the solution, but it works:
I have the control ViewModel as a Property in my page ViewModel and set it programmatically:
NavigationViewModel = App.VmLocator.PageNavigationViewModel;
in xaml I set the BindingContext of my custom control to the Property:
<controls:PageNavigationControl Grid.Row="1" BindingContext="{Binding NavigationViewModel}"/>

Now I have access to the control ViewModel in my PageView Model and can pass the data I need there.


text:
Q: Convert List of object into another List of object I have a list as
class Vachel
{
int id{get;set;}
int vachelid {get;set;}
string title {get;set;}
}

List of Vachel
as
id  vachelid  title
1   2         bus
1   3         truck
2   4         cycle
2   5         bike
2   5         bick

And I want to convert List<Vachel> to List<Result>
class Result
{
int id{get;set;}
string vachelid {get;set;}
string title {get;set;}
}

And the result must be as
   id   vachelid    title
    1   2,3         bus,truck
    2   4,5         cycle,bike,bick

I tried as
List<Vachel> V = getList();
List<Result> R = null;
 R = V.GroupBy(x=> new{x.vachelid})
    .Select
       (
       x=> new Result
         {
         id  =x.Key.id,
         vachelid =x.FirstOrDefault().vachelid,
         title   =x.FirstOrDefault().title
         }
       ).ToList();

Here I know I want to put something instead of .FirstOrDefault().vachelid and .FirstOrDefault().title but I don't know what to do.

A: R = V.GroupBy(x => x.id)
     .Select(g => new Result(){
        id = g.Key,
        vachelid = string.Join(",", g.Select(x => x.vachelid).Distinct()),
        title = string.Join(",", g.Select(x => x.title).Distinct()),
     }).ToList();


text:
Q: How to set or grant SELECTINAUTH for a schema in DB2 11.5 I'm running DB2 11.5 and want to grant select, insert, update or delete rights for all tables in a specific schema. SELECTINAUTH etc. seems to be perfect for this.
When I'm looking to the SYSCAT.SCHEMAAUTH Catalog View I can see the following columns:

*

*ALTERINAUTH

*CREATEINAUTH

*DROPINAUTH

*SELECTINAUTH

*INSERTINAUTH

*UPDATEINAUTH

*DELETEINAUTH

The first 3 privileges can be granted by e.g. GRANT ALTERINAUTH ON SCHEMA  TO USER . But this don't work for the last 4 columns.
The Knowledge Center tells that this are implicit privileges, but I can't find any hint, how a user or a group can get this privileges implicit or explicit.
Does anybody know when or how e.g. INYSERTINAUT is set to Y?

A: I got the following information from IBM: "So currently the usage of SELECTINAUTH, INSERTINAUTH, UPDATEINAUTH is only available in DB2 Warehouse" and "Schema authorization is one of these features and we have publicly stated (at IDUG conferences etc) that we will be brought to Db2 in an update to 11.5.".
It can be enabled with db2set DB2_ENABLE_SCHEMA_AUTHORIZATION=true, but it's not documented and therefore not supported yet. (as IBM explained).


text:
Q: Density of time events I am working on an assignment where I am supposed to compute the density of an event. Let's say that a certain event happens 5 times within seconds, it would mean that it would have a higher density than if it were to happen 5 times within hours.
I have in my possession, the time at which the event happens.
I was first thinking about computing the elapsed time between each two successive events and then play with the average and mean of these values.
My problem is that I do not know how to accurately represent this notion of density through mathematics. Let's say that I have 5 events happening really close to each other, and then a long break, and then again 5 events happening really close to each other. I would like to be able to represent this as high density. How should I go about it?
In the last example, I understand that my mean won't be truly representative but that my standard deviation will show that. However, how could I have a single density value (let's say between 0 and 1) with which I could rank different events?
Thank you for your help!

A: I would try the harmonic mean, which represents the rate at which your events happen, by still giving you an averaged time value. It is defined by :

I think its behaviour is close to what you expect as it measures what you want, but not between 0 and 1 and with inverse tendencies (small values mean dense, large values mean sparse). Let us go through a few of your examples :

*

*~5 events in an hour. Let us suppose for simplicity there is 10 minutes between each event. Then we have H = 6 /(6 * 1/10) = 10

*~5 events in 10 minutes, then nothing until the end of the hour (50 minutes). Let us suppose all short intervals are 2.5 minutes, then H = 6 / (5/2.5 + 1/50) = 6 * 50 / 101 = 2.97

*~5 events in 10 minutes, but this cycle restarts every half hour thus we have 20 minutes as the last interval instead of 50. Then we get H = 6 / (5/2.5 + 1/20) = 6 * 20 / 41 = 2.92
As you can see the effect of the longer and rarer values in a set is diminished by the fact that we use inverses, thus less weight to the "in between bursts" behaviour. Also you can compare behaviours with the same "burst density" but that do not happen at the same frequency, and you will get numbers that are close but whose ordering still reflects this difference.

A: For density to make sense you need to define 2 things:

*

*the range where you look at it,

*and the unit of time

After that you can say for example, that from 12:00 to 12:10 the density of the event was an average of 10/minute.
What makes sense in your case obviously depends on what your input data is. If your measurement lasts for 1 hour and you have millions of entries then probably seconds or milliseconds are better choice for unit. If you measure for a week and have a few entries then day is a better unit.


text:
Q: How to convert membership to dataframe Following code returns nodes in this format
> membership(cluster_edge_betweenness(g))
 2  3  4  5  6  9 10 11 12  1  7  8
 1  1  2  2  2  2  3  3  3  1  2  2

How do I convert community membership for each node to a data frame?
> data.frame(membership(cluster_edge_betweenness(g)))
Error in as.data.frame.default(x[[i]], optional = TRUE) :
  cannot coerce class '"membership"' to a data.frame

I intend to store it to csv later. Thanks for answer.


text:
Q: Using query in access (find the max in a row and display in new column) I have a table like this in MS access :
ID  Name     Date of Arrival
1   Apple    11/3/2014
2   Apple    10/5/2014
3   Orange   11/3/2014
4   Orange
5   Grape    19/3/2014
6   Pear     20/3/2014
7   Pear     11/3/2014
8   Pear     09/3/2014
I am hoping to have a query that can add a column name "latest arrival" which store 1 if it is the latest arrival and 0 if not.
the result should be
ID  Name     Date of Arrival    Latest Arrival
1   Apple    11/3/2014          0
2   Apple    10/5/2014          1
3   Orange   11/3/2014          1
4   Orange                      0
5   Grape    19/3/2014          1
6   Pear     20/3/2014          1
7   Pear     11/3/2014          0
8   Pear     09/3/2014          0
Thank you very much for helping me out!

A: You need two queries (or one query with a subquery if you're using VBA).  The first query gets the max date for each item
"select name, max([date of arrival]) as [max date] from arrival"

Then join that query (or use as a subquery) to
"select id, name, [date of arrival], iif([date of arrival] = [max date],1,0) as latest from (select name, max([date of arrival] from arrival)"

Let me know if you need a picture - I don't know if you're using VBA or the graphical interface.


text:
Q: Copying a fixed range of cells down a blank column until the last row of data in another column I have a worksheet (Sheet1) with 4 columns (A:D). In column A there is more than a 1000 lines of data and column D is blank.  On Sheet2 I have a range called Indicators (B2:B11) which I need to copy into column D on Sheet1 and repeat the process in the next empty cell in column D all the way down to the last row of data in column A.  This is the code I used to copy the range into column D but I have difficulty in repeating the process all the way down as I am not sure how to use the LastRow in this context.
Sub FillDownIndicators()
    Dim LastRow As Long
    LastRow = Sheet7.Cells(Rows.Count, 1).End(xlUp).Row

    Sheet3.Range("Indicators").Copy
    Sheet7.Range("D2").PasteSpecial Paste:=xlPasteValues
End Sub

In short once the range is copied into Column D (10 rows) it must be copied again in the next empty row in column D until the last row is reached in column A. Can someone please help?

A: Just use your variable LastRow to build that range
Sheet7.Range("D2:D" & LastRow).PasteSpecial Paste:=xlPasteValues

A: trying to pastespecial the content of n cells into m cells wouldn't fill the whole wanted range
so I came up with the following
Option Explicit

Sub FillDownIndicators()
    Dim LastRow As Long

    With Sheet7
        LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
        With .Range("D2:D" & LastRow)
            .ClearContents
            .Resize(Sheet3.Range("Indicators").Rows.Count).Value = Sheet3.Range("Indicators").Value
            With .SpecialCells(xlCellTypeBlanks)
                .FormulaR1C1 = "=R[-" & Sheet3.Range("Indicators").Rows.Count & "]C"
                .Value = .Value
            End With
        End With
    End With
End Sub

a more compact version of which would be:
Sub FillDownIndicators()
    With Sheet7.Range("D2:D" & Sheet7.Cells(Rows.Count, 1).End(xlUp).Row)
        .ClearContents
        .Resize(Sheet3.Range("Indicators").Rows.Count).Value = Sheet3.Range("Indicators").Value
        With .SpecialCells(xlCellTypeBlanks)
            .FormulaR1C1 = "=R[-" & Sheet3.Range("Indicators").Rows.Count & "]C"
            .Value = .Value
        End With
    End With
End Sub


text:
Q: normal integer combination How many combinbations can be made of the integers 0-9 using 3 digit combinations?

A: I would try wikipedia entry for Combinations.  However to answer your question:
120 = (10 * 9 * 8) / (3 * 2 * 1)

There are 120 combinations


text:
Q: Submit Button On React Form Doesnt Run Submit Function I am building a login form using react, however when pressing the submit button nothing occurs in the console
   import React from "react";

export class Login extends React.Component {

    constructor(props){
        super(props);
        this.submitHandler = this.submitHandler.bind(this);
        this.state = {
            username: '',
            password: '',
        }
    }
    changeHandler = (e) => {
        this.setState({[e.target.name]: e.target.value})
    }
    submitHandler = e => {
        e.preventDefault()
        console.log("worked")
        console.log(this.state)
    }

    render() {
        const {username, password} = this.state

        return

                       Username
                      <input type="text"
                      name="username"
                      value ={username}
                      placeholder="Username"
                      onChange={this.changeHandler}/>

                       Password
                      <input type="password"
                      name="password"
                      value={password}
                      placeholder="Password"
                      onChange ={this.changeHandler}/>

                <button type="submit" className="btn">Login</button>

    }
}

is there something that I am missing? I have tried moving the submit button into the form tags but that doesnt seem to work either

A: The onSubmit property is specific for forms not divs. You can either change the div to a form or change change the onSubmit to an onClick, and put the onClick to the button. Also, if you are defining class methods with arrow function, you do not need to bind it to this in the constructor. Hope that helps!
Edit: If using the form, the submit button must be inside the form's closing tag.

A: You need a form tag for onSubmit to work. Also, if you want to preventDefault, you need to pass in the event in the submitHandler.
So replace:

With:
<form className="form" onSubmit={this.submitHandler(event)}>

Also make sure you replace the closing
 with </form>


text:
Q: How to pass a dynamic comma separated string list to jenkins pipeline radio button input renderer? Problem-
I have a variable as follows def var1 = ['a','b','c'] and I want to render this variable as a radio button in the jenkins pipeline Input request stage. This variable is not static and the values inside it can change with each run i.e. the variable can be initialised as def var1 = ['q','w','e'] on the second run of the pipeline.
I am not able to display dynamic variable list as a radio button in jenkins.
What I used-
parameters: [extendedChoice(name: 'DeployTo', type: 'PT_RADIO', value: "$var1", visibleItemCount: 5, description: 'Select item')]

But this seems to print every item a,b,c or q,w,e in a single line instead of different radio buttons
PS- I'm fairly new to Jenkins and any help would be appreciated, thanks

A: You would indeed think that the type for the choice values would be list<string> because that is super intuitive, but for some reason it is a comma-delimited string instead:
String var1 = 'a, b, c'

and you will have the different choices displayed as desired.
Additionally, you may have had some complications by resolving the var1 like "$var1" which would force an implicit cast to a string since you are interpolating. You could avoid this by using the first class expression support value: var1.


text:
Q: Strange behaviour of the 'r' key on keyboard I have an Arch Linux machine whose 'r' key started misbehaving recently. This only happens when the language is set to English (in another language, it works correctly), which makes me suspect it's not a mechanical problem.
Basically, the 'r' key sometimes emits a '*' instead of an 'r'. This seems to happen absolutely at random without any rhyme or reason. This happens in all applications with equal randomness.
What could possibly cause this, and how would I go about diagnosing and fixing this?


text:
Q: read.zoo always prints out results - why? I am using read.zoo to read tab-separated datafiles into a zoo time series. I have the following code:
z <- read.zoo("poolBL03GD04_842_WMO_03862.tts", index=2:5, FUN = conv)

As far as I understand, this is assigning the result of the read.zoo function to the z variable, but it prints out the entire result of read.zoo as well. Why is this, and how can I stop it?
Updated with reproducible example:
library(chron)
library(zoo)

conv <- function(y,m,d,t) {
  date_str <- paste(m,"/", d, "/", y, " ", sep="")
  time_str <- paste(t, ":00", sep="")
  print(date_str)
  print(time_str)
  chron(date_str, time_str)
}

zz <- textConnection("51645  2000 04 11  00:00  2367.35   80.9   12.5
51645  2000 04 11  01:00  2370.38   88.8   13.7
51645  2000 04 11  02:00  2357.50   80.6   12.5
51645  2000 04 11  03:00  2360.38   87.2   13.5
51645  2000 04 11  04:00  2354.70   84.0   12.9
51645  2000 04 11  05:00  2345.91   79.3   12.2")
z <- read.zoo(zz, index=2:5, FUN = conv, header=F)

This is even more frustrating when trying to use read.zoo from within a function.
Does anyone have any idea why this is happening?

A: Comment the print lines in your conv function.
conv <- function(y,m,d,t) {
  date_str <- paste(m,"/", d, "/", y, " ", sep="")
  time_str <- paste(t, ":00", sep="")
#  print(date_str)
#  print(time_str)
  chron(date_str, time_str)
}

A: I don't know much about zoo, but it's worth noting that you can use capture.output to force anything to send it's output to a variable.


text:
Q: Changes to scala not appearing in jar I'm using ehiggs terasort.
The project is comprised of Java and Scala. I want to edit some of the Scala. Initially I'm only adding a println to com.github.ehiggs.spark.terasort.TeraGen.scala.
I made the change and saved the file.
I then ran mvn install as per the README. When I use the jar that gets created the additional println I added doesn't appear.
I also tried running variations of mvn clean install, mvn clean build, mvn clean package but had no luck. I even deleted the jar files to ensure that new ones would be generated.
Does anybody know why this might be?
EDIT
The println I added was to file TeraGen.scala.
In the section:
println("===========================================================================")
println("===========================================================================")
println(s"Input size: $size")
println(s"Total number of records: $numRecords")
println(s"Number of output partitions: $parts")
println("Number of records/output partition: " + (numRecords / parts))
println("===========================================================================")
println("===========================================================================")

I changed to:
println("===========================================================================")
println("===========================================================================")
println("===========================================================================")
println(s"Input size: $size")
println(s"Total number of records: $numRecords")
println(s"Number of output partitions: $parts")
println("Number of records/output partition: " + (numRecords / parts))
println("===========================================================================")
println("===========================================================================")

The third println never appears though.
Update
I tested the jar on a different server and it works as expected but it still doesn't work on my local machine. Is it possible that Spark is caching the job in some way?
Just as an extra piece of info. If I edit the scala file on my Mac and build the jar and run it on my local machine the change doesn't appear. If I then scp the jar to a remote server and run it the change appears. From this I feel certain the change is included in the jar but something is stopping it from appearing when I run on my local machine.

A: OK, I got to the bottom of this.
The new jar that I was tryig to run(which contained my changes) was getting run from one location. I noticed there was an earlier veraion of the jar in my spark/jars folder so I deleted it and restarted Spark. The new jar was then picked up.
FYI, I only noticed this when I deleted my new jar and ran the script again. Even though I got an error stating the jar could not be found, I could see from the jab log that some version of the jar was executing so I did a search on the hard drive for the jar name.


text:
Q: PostgreSQL alter type timestamp without time zone -> with time zone The question is short: if I already have data in a column type timestamp without time zone, if I set the type to timestamp with time zone, what does postgresql do with this data?

A: It keeps the current value in localtime and sets the timezone to your localtime's offset:
create table a(t timestamp without time zone, t2 timestamp with time zone);
insert into a(t) values ('2012-03-01'::timestamp);
update a set t2 = t;
select * from a;
          t          |           t2
---------------------+------------------------
 2012-03-01 00:00:00 | 2012-03-01 00:00:00-08

alter table a alter column t type timestamp with time zone;
select * from a;
           t            |           t2
------------------------+------------------------
 2012-03-01 00:00:00-08 | 2012-03-01 00:00:00-08

According to the manual for Alter Table:

if [the USING clause is] omitted, the default conversion is the same as an assignment cast from old data type to new.

According to the manual for Date/Time types

Conversions between timestamp without time zone and timestamp with time zone normally assume that the timestamp without time zone value should be taken or given as timezone local time. A different time zone can be specified for the conversion using AT TIME ZONE.

A: It is better to specify the time zone explicitly. Say, if your timestamps without timezone are supposed to contain the timestamp in the UTC timezone, you should be wary of the fact that the timezone of the client or server might be messing everything here.
The best way is to just specify the timezone to be used explicitly:
ALTER TABLE a_table
    ALTER COLUMN ts_column
    TYPE TIMESTAMP WITH TIME ZONE
        USING ts_column AT TIME ZONE 'UTC'

(And as always, you may want to run the DDL statements inside a transaction so that you can still revert the change with a single rollback)


text:
Q: ASP.NET and jQuery remove button permanently I have a link with button behavior (bootstrap built-in) that i need to remove once it's clicked.
Home Page

Currently i am using jQuery to remove the button e.g.
var btn = $('.btn');
btn.remove();

Actually this works just fine except that if you refresh the page the button as you guess it present on the page again. I want to remove it permanently though not sure if it's doable on the client side.
The project is an ASP.NET one-page web app.
Thank you

A: event.preventDefault() should help in this:
Home Page

$('.btn').click(function(event){
   event.preventDefault();
   $(this).remove();
});


text:
Q: load() and getscript() not always working On my index.php page I use the jquery load() to load other pages in a div "bodycontent". This works fine and dandy. I disable regular links, and must make the href the page name, without the php, and tag the php back on when the load() occurs. One of my pages I'm loading in the div I have dialog boxes pop up on links.
When you initially go to the page, this works fine, but if you steer away by clicking on "products" or any other link on the page at all, and then go back to "home" and click on a link "read more", the dialog boxes will not show up again. You have to refresh, and then it will work until you click a link again. Also, this works fine in my IE 9, ver9.0.8, but older IE at work (like 8), and at least one other persons chrome the dialog box will not come up at all. There are also IE9's at my work that this will just not work on, despite me deleting temp internet files, ect. On my computer it works fine on brand new downloads of firefox, chrome and IE, so I'm also wondering if my method is backwards compatible and cross browser, and if not what I can do to make it so. I'm also using get script in a function with the load to pull the jquery, jquery ui, and my javascript file for the dialog.
I've also looked at things like ajaxcomplete and such, but being mine initially works, I'm not really sure what to do.
My site main index page loading home.php initially (the news, ect)
Fiddle with my navigation javascript, which makes the pages inactive/active and load()/getscript in the div
dialog.js:
$(document).ready(function() {
$('#dialogbox').dialog({
    autoOpen: false,
    title: 'Loading title...',
    modal: true,
    width: 500,
    height: 400
});
});
function readMore(id,title,cat,desc,post,auth) {
//alert(id +","+ title +","+ cat +","+ desc +","+ post +","+ auth);
var $dialog = $('#dialogbox').html('Category: '+ cat +'
'+ desc +'
---------------------------------
Posted by: '+ auth +'
' + post);
$dialog.dialog('open');
$dialog.dialog("option","title",title);
}

How I pull to function readMore:
            <?php
                require('config/dbconfig.php');
                $query = "SELECT * FROM news ORDER BY id DESC LIMIT 4";
                if ($stmt = $mysqli->prepare($query)) {
                    /* execute statement */
                    $stmt->execute();

                    /* bind result variables */
                    $stmt->bind_result($idn, $titlen, $categoryn, $descn, $postdaten, $authorn);

                    /* fetch values */
                    while ($stmt->fetch()) {
                        //echo 'id: '. $id .' title: '. $title;
                        echo "
";
                        $shortDescLengthn = strlen($descn);
                        if ($shortDescLengthn > 106) {
                            $sDCutn = 106 - $shortDescLengthn;
                            $shortDescn = substr($descn, 0, $sDCutn);
                        } else {
                            $shortDescn = $descn;
                        }
                        echo "
$titlen
";
                        echo "
$shortDescn...
";
                        echo '
Read More
';
                        echo "
Written by: $authorn
";
                        echo '

';
                    }
                    echo "

";

                    /* close statement */
                    $stmt->close();
                }

                /* close connection */
                $mysqli->close();
            ?>

So again, basically I need to see why this isn't working after I click a link, and how it can be more cross browser and backwards browser compatible.

A: All I had to do was add:
$('#bodycontent').empty();

before the load(), and it works on every computer I've tried so far. I'm guessing the div needed to be emptied before loading new html in it, so going back it was keeping the js and such from getscript and messing up. Also only kept the single js file that was required only by home.php to be loaded, and put everything else in the index page (like it should have been anyways).


text:
Q: how to execute the date command in a python program The following is the code:
import os
#f=os.popen('date -d @1358193598 +%m/%d/%y')
f=os.popen('date')
print(f)

I tied both ways, and it gave me an error of "broken pipe". Do you happen to know how to deal with this situation? I also tried to use the subprocess module, and it does not work either. The error message is as the following:
Traceback (most recent call last):
  File "t_2.py", line 23, in <module>
    dates.append(transfer_date_format(raw_date))
  File "t_2.py", line 6, in transfer_date_format
    stdin=subprocess.PIPE)
  File "/usr/lib64/python2.6/subprocess.py", line 639, in __init__
    errread, errwrite)
  File "/usr/lib64/python2.6/subprocess.py", line 1228, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

A: You can try with os.system
f=os.system('date')

Here it will save exit code to the variable f
If you want to take output of executed command to the variable, try
f=os.popen('date').read()
print f


text:
Q: JS jquery replace multiple id attributes with values from array A page has a table with rows which all have id attributes.
(starting with number instead of letter shouldn't cause problems here, since it doesn't have to be selected by CSS).

    content
    content

    content
    content

    content
    content

    content
    content

    content
    content

We have a JS array which has exactly as many values as there are tr elements i.e. elements of the "whatever" class.
var arr=['0','1','2','3','4'];

How can I change all the tr id attributes to the ones of the arr array using jQuery or pure JS? The desired result should be:

    content
    content

    content
    content

    content
    content

    content
    content

    content
    content

Just to make it clear: The elements don't have to be re-arranged on the page. The order and everything stays the same, but just the id values should get replaced.
I would do a forEach. But from there I have no idea how to proceed and couldn't find anything.
function ReplaceIDsFromArray(val, index) {

  //do stuff

}

arr.forEach(ReplaceIDsFromArray);

Or maybe first all tr or "whatever" elements have to be selected and put into an array, and perform the forEach on that?

A: You can simply use querySelectorAll method and a forEach to replace your id with the array of id's numbers you have.
Live Demo:

var arr = ['0', '1', '2', '3', '4'];

var getTds = document.querySelectorAll('.whatever') //get all tr's
//Loop over and replace
getTds.forEach(function(td, i) {
  td.id = arr[i] //replace current id's
});

//New IDs
let newIds = document.querySelector("table").innerHTML
console.log(newIds) //shows HTML with new ID's

    content
    content

    content
    content

    content
    content

    content
    content

    content
    content

A: You can just iterate the array of identifiers and the table rows list in sync:

function assignIdentifiers(rows, ids) {
    // Use `Math.min` to avoid out of range addressing
    let len = Math.min(ids.length, rows.length);
    for (let i = 0; i < len; i++) {
        rows[i].id = ids[i];
    }
}

// demo
let rows = document.querySelectorAll("table .whatever");
assignIdentifiers(rows, [1, 2, 3, 4, 5]);
// Show result:
console.log(document.querySelector("table").innerHTML);

    content
    content

    content
    content

    content
    content

    content
    content

    content
    content


text:
Q: Excel 2007 - adding prices to a list of parts using a stock list and a price list I am certain that there is an easy way to do this, but for some reason this one is sitting in my blind spot...
I have a price catalogue that lists all possible part numbers, and their prices. I have a separate stock list that has been produced by a third party which lists all of the parts that they hold in stock. I need to write a formula that checks if the parts on the stock list are in the price catalogue, and if they are, add the price to the stock list.
For example, if the price catalogue has part number in column A and price in Column B, and I add the part numbers from the stock check to column C, I need to check if they are in A, and if they are, add the price into column D.
Does that make sense?
Thanks!

A: VLOOKUP is one formula which can help you resolve your problem.
A combination of INDEX-MATCH-MATCH is another formula which can get you the same result.
VLOOKUP is a VOLATILE function and takes longer time to work. However, this can be experienced only in large files.
Some experts have compared the working results of both these and have concluded that VLOOKUP is about 13 times slower than the INDEX-MATCH-MATCH formula combination.


text:
Q: Clarify "Insertion-sort if the priority-queue implemented with an ordered array", why 'ordered" required? Insertion-sort works also on unordered array, like the example here shows. This statement in the title (or here) for some odd reason requires that you have an ordered array to implement priority-queue for the insertion sort, why does it have such requirement? What does this Wikipedia -thing here actually mean (the below screenshot)?

A: The article relates the usage of priority queue for sorting and how different implementations of priority queue correspond with familiar sorting algorithms.
Let us consider ADT priority queue with operation pop() which takes out the "smallest" element as defined by a comparison function and push() which put a new element in the priority queue. Then sorting can be done by calling push() to push all elements in the unsorted array into the priority queue and calling pop() until the priority queue is empty and put the popped out element into an array (well, you can define a method empty() to check whether the ADT is empty).
Psuedocode:
unsorted[]
sorted[]
priority_queue q

foreach element in unsorted
    q.push(element)

i = 0
while !q.empty()
    sorted[i] = q.pop()
    i = i + 1

Then we talk about how to implement the priority queue. Typically, it is efficiently implemented with heap. However, it is not necessary to be heap - you can implement it in less efficient ways, which is with unordered array or ordered array as mentioned in Wikipedia article. As long as the implementation satisfy the requirement for the push() and pop() operations then it is fine.
For unordered array, you can push() by placing the element directly just after the last element - since it is unordered. When you pop(), since the array is unordered, you need to search through the whole array and pick out the largest element. (Removal can be done easily, by swapping the last element in the unordered array to the position of the element being popped out). It is similar to selection sort, since you are essentially go through the list of unsorted elements (which is in the priority queue) and pick out the largest element to put into sorted portion.
You can see that insertion operation in insertion sort is being done in the push() operation here.
For ordered array, you can pop() by just taking out the first element (removal can be done easily by maintaining a starting index). But push() will require you to find out where to place the element to maintain the order (since it is an ordered array). This is the part where it closely resembles insertion sort, since you are trying to insert the current element to the sorted portion (the priority queue implemented as ordered array).
You can see that selection operation in selection sort is being done in the pop() operation here.


text:
Q: Binding any bootstrap to dynamic HTML My question is not about binding a single event to a specific DOM element. My question is, how can you rebind your whole bootstrap library to dynamically generated DOM elements?
For my case I am using the Jquery method .load and I would like to rebind the HTML loaded by that method to my Metro UI bootstrap library. I don't think going to the loaded HTML, checking all the events and components used and re-binding them is an effective solution. I might as well prefer somehow refreshing all bindings after loading the dynamic HTML (if that is also possible). Any help there? Thank you!

A: After a while of trying I finally found a way to execute the script. I added another method to the callback function to the .load method:
$("#id").load( "dynamic.html", function(){
    $.getScript("boostrap.js");
} );

It may not be the most effective way to rebind elements, but at least I make sure all the JS code is re-binded as if the HTML had been loaded from the initial load.


text:
Q: Android Studio and Team Services Plugin: Change URL of Repository I installed the Team Services Plugin for Android Studio. I imported code into a new respository on Team Services.
I would like to push the new stuff I have created (classes, xml files, etc) into the created repository, but, the URL of this repository has been changed. When I try push the new stuff, I get an error saying the repository can't be found.
Is there a way I can change the current remote repository to the new one, on Team Services?
Thanks.

A: You can run "git remote set-url" command from your local git repository to update the URL of remote repository. Refer to this link for details: Changing a remote's URL.


text:
Q: HTML layout - making dimensions of cells in separate tables match Background
I'm trying to clone parts of a table and overlay the clones on top of the original table in order to create headers that are fixed on the page when scrolling.  I'm using a jQuery plugin: a modified version of datatables FixedHeader to do this.  I tried FixedColumns but it doesn't work the way I want.
I have the above working except that the cloned tables don't line up properly with the source table.  e.g. the top header has cells that are narrower than the cells in the real table.
I've tried setting the widths of the cells like the original FixedHeader code does, but this does not seem to have any effect.  Also, if manually set the widths in Firebug's Layout tab it updates the style="width: blah" in the element in the HTML view, but does not actually change the width of the cells.
Question
How do I set the widths of cells in a second table to match the widths of the cells in the original table so that they line up when I position the second table on top of the first table.
For a simpler version of the above, consider the following code.  Even though I have explicitly set the widths of the first two th elements in both tables, the second table's cells are too narrow.  I don't want to specify the widths of the cells in the original table.  I only want to set the widths of the cells in the second table to match the first.  How do I do this?

    <title>Layout</title>

          Test Name
          Reference Range
          26-07-2011 15:58
          26-07-2011 15:58
          26-07-2011 15:58
          26-07-2011 15:58
          26-07-2011 15:58
          26-07-2011 15:58
          26-07-2011 15:58
          26-07-2011 15:58
          26-07-2011 15:58
          26-07-2011 15:58
          26-07-2011 15:58
          26-07-2011 15:58
          26-07-2011 15:58
          26-07-2011 15:58
          26-07-2011 15:58
          26-07-2011 15:58
          26-07-2011 15:58
          26-07-2011 15:58

          This is the test
          123 - 456
          1
          2
          3
          4
          5
          6
          7
          8
          9
          0
          1
          2
          3
          4
          5
          6
          7
          8

          Test Name
          Reference Range
          26-07-2011 15:58
          26-07-2011 15:58
          26-07-2011 15:58
          26-07-2011 15:58
          26-07-2011 15:58
          26-07-2011 15:58
          26-07-2011 15:58
          26-07-2011 15:58
          26-07-2011 15:58
          26-07-2011 15:58
          26-07-2011 15:58
          26-07-2011 15:58
          26-07-2011 15:58
          26-07-2011 15:58
          26-07-2011 15:58
          26-07-2011 15:58
          26-07-2011 15:58
          26-07-2011 15:58

Edit: I've discovered that for the above code, setting the width of the second table to the same as the first table fixes the issue, but in my real code, the cells are still the wrong width.  How do I figure out where the problem is and how to fix it?

A: In your example you set two columns in the first table at an exact width. This results in the first two columns of your second table getting 'too narrow' because their width is relative instead of absolute, so the browser figures how wide they should be comparing to the other columns.
Your choice is simple: set both of the table columns with an exact width or both of them without. Otherwise, there will always be differences. If you don't (for both) the width of the header columns also depends on the width of the cells in the rows below them, which depends on what's in them. This means either you don't use exact width and you have to make the two tables exactly identical in terms of content (so two whole tables), or you specify exact column widths for both, in which case you can make do with only the header row for the second table.
If I would have to take care of this, I'd say generate one table and use jQuery or MooTools to make the duplicate header columns. So then you query the DOM, copy, paste, set width.


text:
Q: Rails Joins with Exclude certain IDs I have the following Query which pulls out set of results based on an array of IDs
User.joins(:memberships).
     where(plan_memberships: { user_id: attendee_ids, plan_id: plan.id })

Now i want to do another call which excludes attendee_ids and then concat with the above results to retain the order of the results with attendee_ids first then the rest.
Is there a way to retain the order of the results based on certain IDs first and then show the remaining results?

A: You could try injecting some SQL to cover your exclusion case.
User.joins(:memberships).
     where(plan_memberships: { user_id: attendee_ids, plan_id: plan.id }).
     where('plan_memberships.user_id not in (?)', banned_user_ids)

Note: This may be different depending on your choice of database

A: I think in your case the best way is to retrieve results separately by two db queries.
common_scope = User.joins(:memberships).where(plan_memberships: { plan_id: plan.id })

excluded = common_scope.where.not(plan_memberships: { user_id: attendee_ids })
encluded = common_scope.where(plan_memberships: { user_id: attendee_ids })

all_sorted = excluded + encluded

Answer to additional question:
If you want to retrieve a certain number of records you can do it this way:
common_scope = User.joins(:memberships).where(plan_memberships: { plan_id: plan.id })
excluded_scope = common_scope.where.not(plan_memberships: { user_id: attendee_ids })
encluded_scope = common_scope.where(plan_memberships: { user_id: attendee_ids })

number = 3

excluded = excluded_scope.limit(number)
size = excluded.size

if size < number
  encluded = encluded_scope.limit(number - size)
  all_sorted = excluded + encluded
else
  all_sorted = excluded
end

A: If you are using MySql there is an option to retain the order based on the ids you have got in an array.
field(user_id, [array of ids])

For more details, you can check here http://www.electrictoolbox.com/mysql-order-specific-field-values/


text:
Q: Threads and Handlers in server socket How is the new Handler(clientSocket); instantiated without an object?. Can somebody give some insight?
public class Server1 {

    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(15897);
            while (true) {
                Socket clientSocket = serverSocket.accept();

                new Handler(clientSocket);

            }
        } catch (IOException e)
        {
            System.out.println("problem here 1");
        }
    }
}

class Handler implements Runnable {

    int red;
    int reads, r;

    Socket clientSocket;

    Handler(Socket s)
    {
        this.clientSocket = s;

        new Thread(this).start();

    }

    public void run(){
        BufferedReader bufferedReader;
        try {

            bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

            String inputLine = bufferedReader.readLine();

A: Your code is incomplete, so it's difficult to say with certainty, but observe that in the Handler's constructor a thread is created and started, which executes run().
Inside that function (and therefore in a separate thread), the input stream is read from the socket into a BufferedReader, from which the first line is obtained.
The thread will block until a line is received over the socket connection.
Because your code is cut off from that point, I can't say what else it does.

A: In you code Server is made to keep listening the incoming Clients.
       Socket clientSocket = serverSocket.accept();

serverSocket.accept() waits until a connection or a client is found.
       If client is found then  accept() function returns a local socket which is connected to another socket at the client which is given to clientSocket in you code.
new Handler(clientSocket);

Now clientSocket is given to Handler class  in which you are using thread for reading the data given by that clientSocket.
The purpose of thread here is to  handle each incoming clientSocket seprately.

A: I am not sure what exactly does the code do but explaining it to you as per the concept of OOPs, it creates an instance of the Handler class everytime the while loop is executed.
Warning: The while(true) loop is bad code and when the project is run, it will run in an infinite loop.


text:
Q: heroku + android : database integration? I have a Heroku Rails app and am in the process of developing a mobile companion app.  I would like to use the same databases that I have on Heroku for the app.  What is the best way to go about doing this?  Are there any tutorials for beginners?
I know that Heroku used to have a Parse add-on, but it doesn't seem this exist anymore.
Thanks in advance for your help!

A: It depends on what kind of companion app you want. If you're building an Android one, you should probably add a REST API api to you main API that exposes the data your companion app needs. You could also look into just making your Rails app work really well in mobile browsers and not worry about building an actual native app.
Heroku has several resources that might interest you:

*

*Mobile category on Dev Center

*Getting started with iOS and Sinatra

*Helios, Open Source Framework for Mobile

A: I'm learning more about HTTP requests using android and found the following tutorial to be a good place to start:
http://mgmblog.com/2008/10/01/android-ruby-on-rails-app-setup-and-httpclient-hello-world/
Unfortunately, it was written 5 years ago and there are a lot of things that won't work anymore.  So I rewrote the example, which you can try out here:
https://github.com/ttseng/android-rails-example
Hope that's helpful to other beginners.


text:
Q: Cycles in $5×5$ Latin squares (solution found) One of my favorite puzzle formats is KenKen, in which you are to find an $n×n$ Latin square to be filled with whole numbers from 1 to $n$, given sums, differences, products or quotients of various groups of entries.  The puzzles come in various sizes, including $5×5$.
When I solve a $5×5$ puzzle I always seem to find at the end that at least two rows are cyclic permutations of each other.  Is this always true in $5×5$ Latin squares, or is there some weird coincidence going on?
Turns out I found the solution.  Over 90% of 5×5 Latin squares actually have at least one pair of cyclically permuted rows.  So, a 5×5 KenKen without such a cyclic permutations turns out to be relatively rare!

A: A counter example where none of the rows are a cyclic permutation of another:
$$\begin{bmatrix}
1&2&3&4&5\\
2&3&5&1&4\\
3&5&4&2&1\\
4&1&2&5&3\\
5&4&1&3&2
\end{bmatrix}$$
But, it turns out that there are only $5$ reduced Latin squares out of $56$ total for $5×5$ squares.  So, less than 10% of all $5×5$ solutions should be expected to lack such a cyclic row permutation.  Hence such solutions are hard to find.
Here are the other four reduced squares with no cyclic row permutations:
$$\begin{bmatrix}
1&2&3&4&5\\
2&5&1&3&4\\
3&1&4&5&2\\
4&3&5&2&1\\
5&4&2&1&3
\end{bmatrix}$$
$$\begin{bmatrix}
1&2&3&4&5\\
2&5&4&1&3\\
3&4&2&5&1\\
4&1&5&3&2\\
5&3&1&2&4
\end{bmatrix}$$
$$\begin{bmatrix}
1&2&3&4&5\\
2&4&5&3&1\\
3&5&2&1&4\\
4&3&1&5&2\\
5&1&4&2&3
\end{bmatrix}$$
$$\begin{bmatrix}
1&2&3&4&5\\
2&4&1&5&3\\
3&1&5&2&4\\
4&5&2&3&1\\
5&3&4&1&2
\end{bmatrix}$$


text:
Q: Kohana: why won't this route generate fully? I have the following route in my bootstrap:
Route::set('cycleadmin', '(<lang>/)cycleadmin(/<model>(/<action>(/<id>)))', array(
    'lang' => $lang_options,
    'model' => '[a-z_]{0,}',
    'action' => '[a-z_]+',
    'id' => '\d+',
))->defaults(array(
    'controller' => 'cycleadmin',
    'lang' => DEFAULT_LANG,
    'model' => 'cycle',
    'action' => NULL,
));

Then I have the following uri request to generate the route:
echo Route::get('cycleadmin')->uri(array('action' => 'add'));

But this ends up only returning: /cycleadmin
I'm using Kohana 3.1 (v3.1.1.1). This worked perfectly in Kohana 3.0.9.
What am I missing?

A: Try to also set <model> . Does it work?
Regards
Sorin

A: As of 3.1, the route::get()-method doesn't fill in the defaults - you have to manually specify every parameter. Don't ask me why, but it is intended behaviour (source: the official forums).


text:
Q: Dynamic bounty ad is broken The dynamic ad for bounties for a site is currently broken on movies.se. I haven't checked on other sites but I assume they are also broken.
Here's what it currently looks like on movies: https://movies.meta.stackexchange.com/a/2618/52

A: Thanks for the heads up! This issue has been fixed. rand al'thor was correct that it was an HTTP vs HTTPS issue.


text:
Q: "Go To Definition" from User Control in VS 2013 My project has a directory (e.g. ~/custom/) for User Controls (ASCX files) or custom pages (ASPX files), which do not exist as part of any Project in my Solution, but which make calls to routines and objects in the Solution (all in C#).
When I used Visual Studio 2008, I could still browse the source code of these files and jump to internal (in-Project) code with a simple "Go To Definition", but now that I've upgrade to Visual Studio 2013, whenever I select "Go To Definition" from one of these files, Visual Studio takes me to the "[from metadata]" class view.
I have tried some of the steps from similar questions, but most of the questions deal with using "Go To Definition" from code in one Project to another Project, so the solutions don't apply to my scenario.
How can I use "Go To Definition" from custom code into Project code?


text:
Q: Why my scheduled job is not working? I define a job with crontab like this
0 2 * * * dbadmin . /home/dbadmin/back.sh

it is not root I want to run this .sh file with dbadmin user.
but when I checked it is not working.
in the log it gives this:
Feb 22 21:16:01 localhost crond[14634]: (*system*) BAD FILE MODE (/etc/crontab)
Feb 22 21:16:01 localhost crond[14634]: (dbadmin) RELOAD (cron/dbadmin)
Feb 22 21:16:01 localhost crond[28451]: (dbadmin) CMD (dbadmin . /home/dbadmin/back.sh)

How can I fix this? thanks in advance

A: Using the crontab program, you normally have access only to the 5 scheduling fields (minute, hour, day of month, month and day of week).  However, with Vixie cron (usually on Linux) by editing the system crontab file (/etc/crontab, as well as files in /etc/cron.d) you can use the 6th field for the username.  For example, see How to specify in crontab by what user to run script?
If you use crontab to enter this line
0 2 * * * dbadmin . /home/dbadmin/back.sh
          ^^^^^^^

the "dbadmin" username is treated as the command to execute.  You can (as noted in crontab's manual page) use that line in /etc/crontab.  I pointed out that this is Vixie (also known as ISC) crontab.  Legacy systems such as Solaris have a less capable crontab which would not allow specifying the user to run under.
According to cron's manual page, it will send output via email.  Perhaps there was no email because the command "dbadmin" failed.

A: Make a crontab entry as dbadmin without the username in it:
0 2 * * * /home/dbadmin/movefolder.sh > /home/dbadmin/cron.out 2>@1

Each day the logfile /home/dbadmin/cron.out should be replaced by a new one.
When you are confident about the cron+movefolder, replace the outputfile with /dev/null.
When above fails, check calling the script as dbadmin:
sh /home/dbadmin/movefolder.sh

When this one works and cron fails, it might be the environment. Try saomething like
0 2 * * * . /home/dbadmin/.profile; /home/dbadmin/movefolder.sh > /home/dbadmin/cron.out 2>@1

A: You need to use sh command for executing sh file.like following
0 2 * * * dbadmin sh /home/dbadmin/movefolder.sh

Hope it works.
Thank you.


text:
Q: Capturing output from a background subshell in bash? I'm trying to run multiple subshells in a bash script and capture the stdout result to a variable. When I run the subshell in the background I would expect I can use wait to let the subshell complete and then use the variable the result is assigned to later in the program.... but it doesn't seem to work.
Simple example script:
l=$(ls) &
wait $!
echo "L=$l"

Then when I run it:
$ bash -x test2.sh
+ wait 16821
++ ls
+ l='test1.sh test2.sh'
+ echo L=
L=

The output from my test program would suggest the variable l should be assigned the result of the subshell, but when I use echo it is empty...
If I don't background the subshell (or use wait) then it works as expected...
l=$(ls)
echo "L=$l"

Results in:
$ bash -x test1.sh
++ ls
+ l='test1.sh test2.sh'
+ echo 'L=test1.sh test2.sh'
L=test1.sh test2.sh

Am I missing something obvious or ... ?

A: From bash manpage (emphasis mine):

Command substitution, commands grouped with parentheses, and
asynchronous commands are invoked in a subshell environment that is
a duplicate of the shell environment, except that traps caught by the
shell are re‐set  to  the values that the shell inherited from its
parent at invocation.  Builtin commands that are invoked as part of a
pipeline are also executed in a subshell environment.  Changes made to the
subshell environment cannot affect the shell's execution environment.

So, l=$(ls) & would be like (l=$(ls)) if not backgrounded.


text:
Q: SharePoint Authentication with Azure AD (no ACS available) We want to use SharePoint On-premise on Azure VMs. The users are synced to Azure AD.
I've read many articles about authenticating this users via Azure Access Control Services, but ACS isn't available at the new German Datacenters.
Does anybody have an idea for authenticating these users (a companion app maybe? Some custom code?)


text:
Q: Draggable not working in jqueryUI I have a simple progress bar for my <audio> element and I want to make it so the knob is draggable, so I decided to try the jquery UI .draggable method, but it does not work on my knob. All it does is prevent my knob from appearing when you hover over the player as if the code beneath is invalid as soon as that code is in there.
I've tried this for hours and cannot figure out what's wrong with my code. You can see the player below here: I've included a test audio file also so you can see it in action. (The knob is supposed to fade in when you hover over the player, but doesn't after the draggable method. Something is making it invalid, if you wish to see the knob, simply remove the code marked /** This does not work /** )
/**
    VARIABLES
**/

/** Elements **/

var player = $("#player");
var playerE = $("#player")[0];
var playerE = $("#player").get(0);
var playbutton = $("#playButton");
var scrubber = $(".scrubber");
var progress = $(".progress");
var buffered = $(".buffered");
var knob = $(".knob");

/** Variables **/

var isPlaying = 0;
var buffered = 0;
var progress = 0;

/**
    CONTROLS
**/

/** Scrubber and Time **/

playerE.ontimeupdate = function () {
    audioTimeUpdater();
};

function audioTimeUpdater() {
    var progress = playerE.currentTime / playerE.duration;
    var buffered = playerE.buffered.end(0) / playerE.duration;
    $(".progress").width((progress * 100) + "%");
    $(".buffered").width((buffered * 100) + "%");
}

/** This does not work **/

$("#.knob").draggable({
    axis: "x"
});

/** This also stops working after the above code, if I remove it, it works. **/

$(".player-small").mouseenter(function () {
    $(".knob").stop().fadeIn(200);
});
setTimeout(function () {
    $(".player-small").mouseleave(function () {
        $(".knob").stop().fadeOut(200);
    });
}, 3000);

/**
    EVENT HANDLERS
**/

/**
    FUNCTIONS
**/

function play(file, title) {
    playbutton.removeClass("playFailed");
    var filename = "/music/" + file;
    player.attr("src", filename).trigger("play");
    playerHasError();
    if (playerIsToggled === 0) {
        playerToggle();
    }
}

function playerHasError() {
    $("#player").on("error", function (e) {
        source = $("#player").attr('src');
        pushModal("We can't play that!", "Audio element error.", ("An error occured and " + source + " cannot be played. If this is an error that persists please contact the website administrator."), "Audio element returned error trying to play source.", 1);
        playbutton.addClass("playFailed");
    });
}

button {
    border: none;
    outline: none;
}

body,
nav,
ul,
li,
a {
    padding: 0;
    margin: 0;
    list-style: none;
    font-family: 'Roboto', sans-serif;
    text-decoration: none;
}

body {
    overflow-y: scroll;
}

::selection {
    background: rgba(255, 64, 129, 0.85);
    color: black;
    /* WebKit/Blink Browsers */
}

::-moz-selection {
    background: rgba(255, 64, 129, 0.85);
    color: black;
}
.player-small {
    height: 55px;
    width: 100%;
    background: #ff4081;
}

.player-height-anim {}

.player-small .left {
    height: 55px;
    float: left;
    width: 60%;
}

.player-small .right {
    height: 55px;
    float: right;
    width: 40%;
}

.transport {
    overflow: auto;
}

.play-button-con {
    height: 55px;
    width: 55px;
    float: left;
}

.play {
    padding-top: 3px;
    width: 55px;
    height: 55px;
    font-size: 18px;
    padding-right: 4px;
    text-align: center;
}

.playFailed {
    color: rgba(255, 255, 255, 0.17)!important;
    pointer-events: none;
}

.next-button-con {
    height: 55px;
    width: 55px;
    float: left;
}

.next {
    padding-top: 2px;
    padding-right: 8px;
    width: 55px;
    height: 55px;
    text-align: center;
    letter-spacing: -3px;
    font-size: 11px;
    padding-bottom: 2px
}

.scrubber-con {
    float: left;
    height: 55px;
    width: calc(100% - 111px);
}

.scrubber {
    width: calc(100% - 40px);
    margin: auto;
    margin-top: 25px;
    height: 5px;
    background: rgba(0, 0, 0, .04);
    cursor: pointer;
}

.scrubber .knob {
    float: right;
    height: 13px;
    width: 13px;
    position: relative;
    bottom: 4px;
    left: 5px;
    background: white;
    border-radius: 50px;
    display: none;
}

.scrubber .knob:hover {
    cursor: grab;
}

.scrubber .knob:active {
    cursor: grabbing;
}

.scrubber .progress {
    height: 100%;
    float: left;
    background: white;
    width: 0%;
    position: relative;
    z-index: 1;
    transition: ease 300ms;
}

.scrubber .buffered {
    height: 5px;
    position: relative;
    width: 0%;
    background: rgba(0, 0, 0, .09);
    transition: ease 1000ms;
}

.player-small button {
    color: white;
    float: left;
    background: rgba(0, 0, 0, .04);
    cursor: pointer;
}

.player-small button:hover {
    background: rgba(0, 0, 0, .12);
}

                                    <button class="play" id="playButton">►</button>

                                    <button class="next">►►   </button>

                            <audio id="player" src="http://c1d20c5c.ngrok.io/music/test.mp3" controls="controls" preload="none"></audio>

So as you see the knob doesn't even appear, and if you make it appear, it is still not draggable. I tested the lint and everything is OK and should be working, but it isn't. What am I doing wrong?

A: Your selector is wrong:
$("#.knob").draggable({...});

#.knob won't work, you can either select via an id using #idname or via a class using .classname.
In your html, knob is a class, so using
$(".knob").draggable({
    axis: "x"
});

Should work, but be aware that this selects all html elements with the knob class.


text:
Q: how to make a custom atributte w3 valid? I have the following code that is used to open a menu over the account anchor:
echo "
Account"
";

the data-flexmenu='account' inform what menu should be shown, in that case, the account menu.
The problem is that im getting error on w3 validator: there is no attribute "data-flexmenu"
Is there a way to make that valid?

A: I wouldn't worry too much about validation. I think validated HTML is important but if your code works in all browsers and still doesn't validate then what's the point? Custom attributes will work in all browsers, even Internet Explorer 6. Custom attributes can also be parsed by Javascript and there's no need for the HTML5 doctype to be able to do that.
There's a great article by Nicholas Zakas, where he explains the value of validation using custom attributes as an example. See http://www.nczonline.net/blog/2010/08/17/the-value-of-html-validation/

A: Your current doctype doesn't allow the attribute data-flexmenu. Either remove this attribute or switch to a HTML5 doctype.
In HTML5 data-flexmenu should be valid. You can define a HTML5 doctype like in this example:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>This is a HTML5 Doctype</title>

Account"

Where this is the HTML5 doctype:
<!DOCTYPE html>

You can also define the charset like this if you whish to make it shorter:
<meta charset="utf-8">

And define the language of your document like this:

It's possible to make the HTML5 document even shorter but you'll find a lot of information on that.


text:
Q: How can you use ggplot to superimpose many plots of related functions in an automatic way? I have a family of functions that are all the same except for one adjustable parameter, and I want to plot all these functions on one set of axes all superimposed on one another.  For instance, this could be sin(n*x), with various values of n, say 1:30, and I don't want to have to type out each command individually -- I figure there should be some way to do it programatically.
library(ggplot2)

define trig functions as a function of frequency:  sin(x), sin(2x), sin(3x) etc.
trigf <- function(i)(function(x)(sin(i*x)))

Superimpose two function plots -- this works manually of course
ggplot(data.frame(x=c(0,pi)), aes(x)) + stat_function(fun=trigf(1)) +  stat_function(fun=trigf(2))

now try to generalize -- my idea was to make a list of the stat_functions using lapply
plotTrigf <- lapply(1:5, function(i)(stat_function(fun=function(x)(sin(i*x))) ))

try using the elements of the list manually but it doesn't really work -- only the i=5 plot is shown and I'm not sure why when that's not what I referenced
ggplot(data.frame(x=c(0,pi)), aes(x)) +plotTrigf[[1]] + plotTrigf[[2]]

I Thought this Reduce might handle the 'generalized sum' to add to a ggplot() but it doesn't work -- it complains of a non-numeric argument to binary operator
Reduce("+", plotTrigf)

So I'm kind of stuck both in executing this strategy, or perhaps there's some other way to do this.

A: Are you using version R <3.2? The problem is that you actually need to evaluate your i parameter in your lapply call. Right now it's being left as a promise and not getting evaulated till you try to plot and at that point i has the last value it had in the lapply loop which is 5. Use:
plotTrigf <- lapply(1:5, function(i) {force(i);stat_function(fun=function(x)(sin(i*x))) })

You can't just add stat_function calls together, even without Reduce() you get the error
stat_function(fun=sin)  + stat_function(fun=cos)
# Error in stat_function(fun = sin) + stat_function(fun = cos) :
#   non-numeric argument to binary operator

You need to add them to a ggplot object. You can do this with Reduce() if you just specify the init= parameter
Reduce("+", plotTrigf, ggplot(data.frame(x=c(0,pi)), aes(x)))

And actually the special + operator for ggplot objects allows you to add a list of objects so you don't even need the Reduce at all (see code for ggplot2:::add_ggplot)
ggplot(data.frame(x=c(0,pi)), aes(x)) + plotTrigf

The final result is

A: You need to use force in order to make sure the parameter is being evaluated at the right time.  It's a very useful technique and a common source of confusion in loops, you should read about it in Hadley's book http://adv-r.had.co.nz/Functions.html
To solve your question: you just need to add force(i) when defining all the plots, inside the lapply function, before making the call to stat_function. Then you can use Reduce or any other method to combine them. Here's a way to combine the plots using lapply (note that I'm using the <<- operator which is discouraged)
p <- ggplot(data.frame(x=c(0,pi)), aes(x))
lapply(plotTrigf, function(x) {
  p <<- p + x
  return()
})


text:
Q: How to print external images from ActionScript 2? i have this script:
on (release) {
imprime = new PrintJob();
imprime.start();
imprime.addPage(papel_mc);
imprime.send();
delete imprime;

}
But, here i only print an MovieClip on my Stage called papel_mc. My Question is: How i can print an external JPG??

A: You need to load it as a Bitmap and after you can add it to your papel_mc and print.
I'm not familiar with as2, so connot provide with a code, but i think here at kirupa they almost solve the problem.


text:
Q: Add and commit files in a tree to SVN I have a directory tree under SVN control, and I want to add and commit several new files in the tree.  Some of the files are already under SVN, and others are not.  Sometimes not even the parent directories of the new files are under SVN yet.  I have the names of all the new files, but I do not know which ones are under SVN yet and which ones are not.
I'm looking for a simple way to add and commit all these files.
Adding the files which are not under SVN yet is actually easy: I do svn add --parents --quiet FILES....  This will add all those files which are not under SVN and do nothing for those which are already registered.  But there doesn't seem to be a similar operation for svn commit.  When I do svn commit on a file that has just been added, it complains that the parent directory is not yet under SVN control.  There does not seem to be a --parents option for svn commit.
Any suggestions?

A: AFAIK, svn commit is recursive by default. Commit from the root directory of the tree, and everything should be committed at once.

A: svn add --force
svn commit -m "yes the damn thing works"


text:
Q: csp-algorithm for context-free grammars I'm trying to solve a CSP (Constraint-Satisfaction-Problem), which is based on arbitrary context-free grammars. A quick example: Let's say we have a context-free grammar with the following production rules: S->A, S->B, S->AB, A->Aa, A->a, A->aa, B->Bb, B->b, B->bb.
Now I'm looking for a word, which uses specific (sub-sequences of) production rules. For example:
"B->b" must be used 3 times in the whole derivation-sequence
If "S->AB" is used, it must be followed by "B->Bb"
If "S->Aa" is used, it must directly be followed by "A->a"

I know the problem is a CSP, but I couldnt find a specific algorithm on how to solve this. Any ideas, which (concrete) algorithm could be used? Also, I'm thinking about the right data-strucure. Should I rather use an n-Tree or an array (CYK-Table)?


text:
Q: How to use IMemoryCache in a application with multiple instances I'm using IMemoryCache in my ASP.Net core web application hosted by a cloud foundry.
The application has 3 instances.
Everything works fine, but when I want to remove the cache, it removes the cache logically only on one instance and the other two instances have still the old (cached) value.
My code looks like:
Startup.cs
    public void ConfigureServices(IServiceCollection services)
    {
       // other code...
       services.AddMemoryCache();
       // other code...
    }

ExampleController.cs
    private IMemoryCache cache;

    public ExampleController(IMemoryCache cache)
    {
        this.cache = cache;
    }

    private void ClearCacheByKey(string key)
    {
        this.cache.Remove(key);
    }

How can I handle the problem with the cache and multiple instances of my application?

A: Memory cache uses the memory of your application to cache things.
So you have three instances of memory cache, one on each instance of your application. Each one of them is independent of the others. If you write to one it won't write to the other instances, and the same is valid for deleting.
That being said, it would be better I think if you use a centralized caching mechanism. So that all the instances of your application call the same cache instance.
Alternatively, but I wouldn't recommend doing this, you can create an endpoint to clear the cache that you need to invoke when invalidating the cache on a machine, to invalidate it on all the other instances of the application.


text:
Q: Неправильная кодировка в AJAX Знаю, вопрос уже был, но решения я не нашёл, передаю перменные, в одной пермененной русский текст (rName), перегоняю её в windows-1251, вывожу на экран - всё норм. Пробую добавить в БД ошибка (Unknown column 'ыкрурк' in 'field list') везде кодировка windows-1251, есть ещё один скрипт - там тоже русский текст, всё норм работает. Разница только перемененные из AJAX, в том передаю
`data: "rKod="+rKod+"&rLogin="+rLog...`

а здесь
data: {rKod:rKod, rEmail:rEmail, rLogin:rLogin, rPass:rPass, rPass2:rPass2, rName:rName}

в этом скрипте почему-то первым способом не доходит одна переменная (неважно какая, но одна не доходит)
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    header("Content-type: text/html; charset=windows-1251");
    if ($_SESSION['secpic'] == trim($_POST['rKod'])) {
        $rLogin = trim($_POST['rLogin']);
        $rPass  = trim($_POST['rPass']);
        $rPass2 = trim($_POST['rPass2']);
        $rEmail = trim($_POST['rEmail']);
        $rName  = iconv("utf-8", "windows-1251", $_POST['rName']);

        if ($rLogin == '') {
            die("Невірний логін
\n");
        } elseif (!preg_match("/^\w{3,}$/", $rLogin)) {
            die("Логін містить недопустимі символи, або їх менше трьох!
\n");
        }
        if ($rName == '') {
            die("Невірне Ім'я
\n");
        } elseif (!preg_match("/^[а-яА-Я]{3,}$/", $rName)) {
            die("Ім'я містить недопустимі символи, або їх менше трьох!
\n");
        }
        if ($rEmail == '') {
            die("E-mail не знайдено
\n");
        } elseif (!preg_match("/^[a-zA-Z0-9_\.\-]+@([a-zA-Z0-9\-]+\.)+[a-zA-Z]{2,6}$/", $rEmail)) {
            die("E-mail введено невірно
\n");
        }
        if ($rPass == '' || $rPass2 == '') {
            die("Пароль не введено
\n");
        } elseif ($rPass !== $rPass2) {
            die("Другий раз пароль введено невірно
\n");
        } elseif (!preg_match("/^\w{3,}$/", $rPass)) {
            die("Пароль має недопустимі символи!
\n");
        }

        $mdPassword = md5($rPass);
        $time       = time();
        $inc        = 1;
        include("min/1.php");
        mysql_query("SET NAMES 'cp1251'");
        mysql_query("SET character_set_client = cp1251");
        mysql_query("SET collation_connection=cp1251_general_ci");
        mysql_query("SET character_set_results = cp1251");
        echo $rName . '
';
        mysql_query("INSERT INTO users (login, pass, email, timestamp, name) VALUES ('$rLogin','$mdPassword','$rEmail',$time, $rName)", $connect);

        echo mysql_error($connect) . '
';

        if (mysql_error($connect) != "") {
            die("Пользователь с таким логином уже существует, выберите другой
\n");
        }

    ...

    }
}

A: Если данные отправлены через AJAX, то на сервер они придут в UTF-8, используйте iconv, чтобы привести их необходимой кодировке.
A: mysql_query("INSERT INTO users (login, pass, email, timestamp, name) VALUES ('$rLogin','$mdPassword','$rEmail',$time, $rName)", $connect);

какого .... тут $rName без кавычек а???


text:
Q: making ajax button with django-secretballot and intercooler.js I'm making a vote up button using django-secretballot and django-likes and i want to use intercooler.js to make the ajax call and don't reload the whole page.
The problem is when i click on the vote button the element contain the ( vote_total ) disappear and nothing happen but if i reload the page the vote happen
image 1 : the button without click
image 2 : the button after i click
image 3 : the button after i reload the page

this is "likes.html" template on django-likes app
{% load i18n %}
{% load static %}

{% if import_js %}

{% endif %}

{% if likes_enabled %}
  {% if can_vote %}

        <svg width="10" height="9" viewBox="0 0 9 8" xmlns="http://www.w3.org/2000/svg" class="upvoteIcon_f942d"><path d="M9 8H0l4.5-8L9 8z" fill-rule="evenodd"></path></svg>

                {{content_obj.vote_total }}

  {% else %}

        <svg width="10" height="9" viewBox="0 0 9 8" xmlns="http://www.w3.org/2000/svg" class="upvoteIcon_f942d"><path d="M9 8H0l4.5-8L9 8z" fill-rule="evenodd"></path></svg>

            {{content_obj.vote_total }}

  {% endif %}
{% endif %}

Note : if there is noway to make intercooler.js working with django-secretballot and django-likes can you please give me ajax code to make the button don't reload the whole page thanks

A: The problem was on the id of the span; it must be unique so I solve it like this

             {{content_obj.vote_total }}


text:
Q: Angular 2 how to call markAsDirty() on control inside ControlValueAccessor

I have a Date of birth custom control, with 3 inner inputs.
I only want the parent control to be marked as dirty, when all 3 inputs are dirty.
I need to access the control of the NgModel from within the Custom value accessor, How can I achieve this? The code isn't neccessary, but is below:
@Directive({
  selector: '[validateDateOfBirth][formControlName],[validateDateOfBirth][formControl],[validateDateOfBirth][ngModel]',
  providers: [
  { provide: NG_VALIDATORS, useExisting: forwardRef(() => DateOfBirthValidator), multi: true }
  ]
})
export class DateOfBirthValidator implements Validator {
  constructor(@Attribute('validateDateOfBirth') public validateDateOfBirth: string) {

  }
  validate(c: AbstractControl): { [key: string]: any } {
    let v: DateOfBirthVm  = c.value;
    let valid = false;
    if(v && v.month && v.year) {
      return null;
    }
    return {
      validateDateOfBirth: false
    }
  }
}

<date-of-birth
  validateDateOfBirth
  ngDefaultControl
  [(ngModel)]="model.dateOfBirth"
  #dateOfBirth="ngModel"
  name="dateOfBirth"></date-of-birth>

export class DateOfBirth implements ControlValueAccessor {

  @Input() name: string;

  private _viewModel: DateOfBirthVm = new DateOfBirthVm();

  private _yearOptions: Array<number> = [];
  private _monthInputValue: string = '';
  private _monthControl: FormControl = new FormControl();
  private _yearInputValue: string = '';
  private _yearControl: FormControl = new FormControl();

  constructor(private _appSettings: AppSettings) {
    this._monthControl.valueChanges.subscribe((value: string) => {
      this._viewModel.month = value;
    });
    this._yearControl.valueChanges.subscribe((value: string) => {
      this._viewModel.year = value;
    });
  }

  ngOnInit() {
    for(let i=(this._appSettings.currentYear-18); i>1909; i--) {
      this._yearOptions.push(i);
    }
  }

  //Interface specific stuff.
  //To notify external component's that the model has changed, we must call our
  //registeredOnChange handler. (e.g _onChanged()). Simply calling it, informs other components.
  registerOnChange(fn: any) { this._onChanged = fn; }
  registerOnTouched(fn: any) { this._onTouched = fn; }
  private _onChanged = (value) => { };
  private _onTouched = () => { };
  //write value is called when an external component writes to our model.
  //e.g if another component with ([ngModel])="myAutoCompleteValue", calls myAutoCompleteValue = '';
  writeValue(vm: DateOfBirthVm) {
    if(!vm) {
      this._viewModel.month = '';
      this._viewModel.year = '';
    } else {
      this._viewModel = vm;
      this._monthInputValue = vm.month;
      this._yearInputValue = vm.year;
      this._onChanged(vm);
    }
  }

}

A: Just don't call _onChanged() or _onTouched() when not all are changed yet.


text:
Q: Cannot link custom IBDesignable class to UIButton on storyboard How do I connect IBDesignable custom class to UIButton?
Code
import UIKit

@IBDesignable class MyButton: UIView {
    @IBInspectable var borderColor: UIColor = UIColor.clear {
        didSet {
            layer.borderColor = borderColor.cgColor
        }
    }

    @IBInspectable var borderWidth: CGFloat = 0 {
        didSet {
            layer.borderWidth = borderWidth
        }
    }

    @IBInspectable var cornerRadius: CGFloat = 0 {
        didSet {
            layer.cornerRadius = cornerRadius
        }
    }
}

The name of the file is MyButton.swift

It doesn't show MyButton as the class? How would I fix this problem?

A: You probably need MyButton to inherit from UIButton, rather than UIView.

A: You can only link custom classes to objects of the same type, or a type it inherits from. Instead of
@IBDesignable class MyButton: UIView {

you probably want
@IBDesignable class MyButton: UIButton {

or link it to a UIView object instead


text:
Q: NSRequiresCertificateTransparency = YES makes https fail in iOS 9 simulator I'm trying to enable NSRequiresCertificateTransparency flag from App Transport Security for my ios app to achieve better security. I tested and it works fine on my device having iOS 10 and in simulator with iOS 10. But it makes https connections fail in simulator with iOS 9.3. If I just turn off this particular flag, it becomes working again.
The problem is not in server I connect to, because I was able to reproduce it even with www.apple.com. Here is the settings from Info.plist that I use:
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>www.apple.com</key>
        <dict>
            <key>NSRequiresCertificateTransparency</key>
            <true/>
        </dict>
    </dict>
</dict>

And here is the code:
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:@"https://www.apple.com/"] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    if (error) {
        NSLog(@"fail");
    }
}];
[task resume];

The error I see in log is:
NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9802)
Maybe it happens only in simulator with iOS 9? Unfortunately I don't have device with iOS 9 at hand to test it.
UPDATE:
I don't see anything helpful in log after setting CFNETWORK_DIAGNOSTICS=3 env variable. Here is part where it says about error:
    Response Error
    Request: <CFURLRequest 0x7f8d0f668d00 [0x108314a40]> {url = https://www.apple.com/, cs = 0x0}
      Error: Error Domain=kCFErrorDomainCFNetwork Code=-1200 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, kCFStreamPropertySSLPeerTrust=<SecTrustRef: 0x7f8d0f590a80>, _kCFNetworkCFStreamSSLErrorOriginalValue=-9802, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9802, kCFStreamPropertySSLPeerCertificates=<CFArray 0x7f8d0f50dfb0 [0x108314a40]>{type = immutable, count = 2, values = (
                0 : <cert(0x7f8d0f66ef10) s: www.apple.com i: Symantec Class 3 EV SSL CA - G3>
                1 : <cert(0x7f8d0f637e60) s: Symantec Class 3 EV SSL CA - G3 i: VeriSign Class 3 Public Primary Certification Authority - G5>
             )}}
    } [3:22]
Jan 31 17:09:13  test2[34612] <Notice>: CFNetwork Diagnostics [3:23] 17:09:13.125 {
               Did Fail
                 Loader: <CFURLRequest 0x7f8d0f737670 [0x108314a40]> {url = https://www.apple.com/, cs = 0x0}
                  Error: Error Domain=kCFErrorDomainCFNetwork Code=-1200 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, kCFStreamPropertySSLPeerTrust=<SecTrustRef: 0x7f8d0f590a80>, _kCFNetworkCFStreamSSLErrorOriginalValue=-9802, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9802, kCFStreamPropertySSLPeerCertificates=<CFArray 0x7f8d0f50dfb0 [0x108314a40]>{type = immutable, count = 2, values = (
                            0 : <cert(0x7f8d0f66ef10) s: www.apple.com i: Symantec Class 3 EV SSL CA - G3>
                            1 : <cert(0x7f8d0f637e60) s: Symantec Class 3 EV SSL CA - G3 i: VeriSign Class 3 Public Primary Certification Authority - G5>
                         )}}
    init to origin load: 0.00299901s
             total time: 0.156503s
            total bytes: 0
    } [3:23]

UPDATE 2:
Here is the view of error object in the debugger.

A: The NSRequiresCertificateTransparency key was introduced in iOS 10, so I'm not sure why this would be failing.  It is definitely not failing because of Certificate Transparency, since iOS9 wouldn't check it, but iOS 10 would (since iOS 10 understands the NSRequiresCertificateTransparency key).
I did confirm that this fails on physical devices running iOS 9.  But it doesn't fail for all servers.  www.google.com, for example, works on iOS 9 in the simulator and physical devices.
I would recommend turning on ATS verbose network logging to determine if the SSL failure is caused by your ATS configuration or if something else is failing. See details of how to turn on verbose logging here. I suspect there is another error that is causing the SSL error.
Also, delete all your entries related to App Transport Security from your info.plist and see if it works in iOS 9.  At least eliminate the setting as the root cause.
The only other thing I can think is that iOS9 is confused by the fact that you have an exception domain with no valid (as far as iOS 9 is concerned) keys underneath it, although I doubt this is it.  Maybe add an NSAllowsArbitraryLoads key with a value of false in under your apple.com exception domain entry.
I would recommend turning the flag off until you no longer need to support iOS 9 devices.


text:
Q: Beamer output without frames I'm trying to get beamer to output the contents of the frames without the actual frames. The idea is to have the handouts produced as normal A4/Letter papers. I already have my content arranged in sections, subsections and proper itemization etc.

A: This sounds like you want the article mode which is a way of incorporating the beamer frames into a normal LaTeX article.
The details of how to use it are in Section 21 (particularly 21.2) in the beamer manual.


text:
Q: How to set a Reminder on iOS5 for a location AND date? I'd like to set a Reminder on iOS5 for my iPhone 4 for when I leave work on Friday... However, the app seems to allow only location OR date/time notifications (or you can have both independently). Is there any way to get them to work in conjunction with one another as I'd like?

A: This is not currently possible. The Location and Time conditions are applied in a disjunctive manner.


text:
Q: How to loop inside of array in php I want to loop data inside of array, without loop array, anyone can help me with this problem?
this is my code..
<?php
$arrUtil = array();
while($dtRoomsUtil = mfa($roomsUtil)){
    $arrUtil[] = array(
        "id" => $dtRoomsUtil['id'],
        "name" => $dtRoomsUtil['name'],
        "label" => $dtRoomsUtil['label'],
        "type" => $dtRoomsUtil['type']
    );
}
while($dtUtils = mysql_fetch_array($quUtils)){
$arrData = array(
 foreach($arrUtil as $value){
  $value['name'] => $dtUtils[$value['name']]
 }
}
);
?>

thats give me error, and i think because a foreach function, anybody know about the other ways to solve this problem?
Thanks for help..

A: You can't init array in such way. Make it like so:
$arrData = array();
 foreach($arrUtil as $value) {
  $arrData[$value['name']] = $dtUtils[$value['name']];
 }

A: you can push your data into array,
use array_push($array,$element) in the loop


text:
Q: Multiple instances of IdentityServer4 with signing credentials from AzureKeyvault My identityserver4 is deployed into AKS with replicas to 1. But when I set the replica count to more than 1, I started seeing problems.
Sometimes authentication validation works sometimes it doesn't. As per the documentation from IdentityServer4 portal, if we use more than one instance of the identityserver is running then we have to make sure that the same signing credentials should be used across all the instances. I have used Azure keyvault Keys to for signing credentials following this article.
But I'm still facing the problem. I have also made sure that the discovery url is same even when there are multiple instances runnings as per this link. Please advise.
sample Startup code for fetching the Keys from Azure keyVault -
var keyClient = new KeyClient(
        new Uri(""), // e.g. https://scottbrady91-test.vault.azure.net/
        new ClientSecretCredential(
            tenantId: "",
            clientId: "",
            clientSecret: ""));

    Response<KeyVaultKey> response = keyClient.GetKey(""); // e.g. IdentityServerSigningKeyEcc

    AsymmetricSecurityKey key;
    string algorithm;

    if (response.Value.KeyType == KeyType.Ec)
    {
        ECDsa ecDsa = response.Value.Key.ToECDsa();
        key = new ECDsaSecurityKey(ecDsa) {KeyId = response.Value.Properties.Version};

        // parse from curve
        if (response.Value.Key.CurveName == KeyCurveName.P256) algorithm = "ES256";
        else if (response.Value.Key.CurveName == KeyCurveName.P384) algorithm = "ES384";
        else if (response.Value.Key.CurveName == KeyCurveName.P521) algorithm = "ES521";
        else  throw new NotSupportedException();
    }
    else if (response.Value.KeyType == KeyType.Rsa)
    {
        RSA rsa = response.Value.Key.ToRSA();
        key = new RsaSecurityKey(rsa) {KeyId = response.Value.Properties.Version};

        // you define
        algorithm = "PS256";
    }
    else
    {
        throw new NotSupportedException();
    }

    services.AddIdentityServer()
        .AddTestUsers(TestUsers.Users)
        .AddInMemoryIdentityResources(Config.Ids)
        .AddInMemoryApiResources(Config.Apis)
        .AddInMemoryClients(Config.Clients)
        .AddSigningCredential(key, algorithm);

A: Another thing that might give you issues is the Data Protection API, it is in charge of protection the session cookies involved. If you want the session cookies to be valid across the instances, then they need to share the same encryption keys (key ring).
See Configure ASP.NET Core Data Protection
I also did blog about this here:
Storing the ASP.NET Core Data Protection Key Ring in Azure Key Vault