text:
Q: Lifting projective Galois representation with condition Let $\bar{\rho}: G_K\to PGL_n(\mathbb{C})$ be projective representation of the absolute Galois group of a number field $K$ and $\varphi\in Aut(G_K)$.
A theorem of Tate tells us that we can always lift  $\bar{\rho}$ to some $\rho: G_K \to GL_n(\mathbb{C})$. I am wondering if there is a lift $\rho$ whose kernel is preserved by $\varphi$, i.e. $\varphi(\ker\rho)=\ker\rho$.
Edit. A better question would be: Do you have any idea about how to determine necessary and sufficient conditions for the existence of a lift with kernel stable under the automorphism $\varphi$?

A: $\newcommand\rhobar{\overline{\rho}}$
Assume that the projective image of $\rho$ is irreducible.
Suppose that $\varphi \ker(\rho) = \ker(\rho)$. I claim that $\varphi \ker(\rhobar) = \ker(\rhobar)$. The assumption $\varphi \ker(\rho) = \ker(\rho)$ implies that $\varphi$ acts via automorphisms on the image of $\rho$. The irreducibility assumption implies that the subgroup
$$Z = \ker \left(\mathrm{im}(\rho)  \rightarrow \mathrm{im}(\rhobar) \right)$$
is precisely the centre of $\ker(\rho)$, and so $Z$ is a characteristic subgroup of $\mathrm{im}(\rho)$, and is thus preserved by $\varphi$, and hence $\varphi$ must also act  on $\mathrm{im}(\rhobar)$ and hence fix $\ker(\rhobar)$. So the question is independent of which lift you choose.
For a number field $K$, there is an isomorphism (Neukirsch, 12.2.2):
$$\mathrm{Aut}(G_K)/\mathrm{Inn}(G_K) = \mathrm{Aut}(K)$$
Let us consider two cases:

*

*$\mathrm{Aut}(K)$ is trivial. In this case, any automorphism is inner, and so preserves normal subgroups, and so all lifts have the required property.

*$\mathrm{Aut}(K)$ is non-trivial. Let $E \subset K$ denote the (proper) field field of $\mathrm{Aut}(K)$, so $K/E$ is Galois. In this case, automorphisms of $G_K$ come from inner automorhpisms of $G_E$, and hence the requirement is that the fixed field of $\ker(\rhobar)$ (or of $\ker(\rho)$) is Galois over $E$. However, if $K \ne E$, there will always be irreducible $n$-dimensional representations of $G_K$ whose fixed field is not normal over $E$, and indeed this will be the generic situation.
For a very explicit example, take $K = \mathbf{Q}(\sqrt{2})$, take $n = 2$, and let $\rhobar$ be the representation with image $S_3$ coming from the splitting field of $x^3 + \sqrt{2} \cdot  x + 1$.

A: $\newcommand\A{\widetilde{A}}$
$\newcommand\Z{\mathbf{Z}}$
$\newcommand\Q{\mathbf{Q}}$
$\newcommand\rhobar{\overline{\rho}}$
This is in response to the comment of the OP: As far as I can see you are only showing that the stability of $\ker(\rho)$ is a necessary condition for having a lift with stable kernel, but not a sufficient one.
Yes, that is correct. And as far as I can see, your question was "[is] there a lift $\rho$ whose kernel is preserved by $\varphi$" and the above shows that the answer is "no," and moreover will always be no if the kernel of $\rhobar$ is not preserved by $\varphi$. I made no claim that $\ker(\rhobar)$ being preserved by automorphisms implies that there exists a lift with this property. Perhaps this is your actual question?
Question: Suppose  that $\ker(\rhobar)$ is preserved by automorphisms of $G_K$. Then can one find a lift $\rho$ such that $\ker(\rho)$ is preserved by automorphisms of $G_K$?
The answer to this question is no, in general.
Let $\A_5$ denote the perfect central extension of $A_5$ by $\Z/2\Z$.
Let $G$ be the semi-direct product of $\Z/2\Z$ by $H = (\A_5)^2$, where the action of $\Z/2\Z$ on $H$ is given by permuting the coordinates. Now suppose that $M/\Q$ is a Galois extension with Galois group $G$. Let $K$ be the corresponding quadratic subfield with fixed field $H$. There is a representation:
$$\rho: G_K \rightarrow \mathrm{Gal}(M/\Q) = H \rightarrow \mathrm{GL}_{6}(\mathbf{C})$$
which factors through the quotient $\A_5 \times A_5$ of $H$ (the latter group has a faithful representation of dimension $2 \times 3$). On one hand, the projective representation $\rhobar$ factors through $A_5 \times A_5$, and so the kernel of $\rhobar$ is Galois over $\Q$. On the other hand, the fixed field of $\ker(\rho)$ is not Galois over $\Q$. Since $\rhobar$ is irreducible, all other lifts are of the form $\rho \otimes \chi$ for some character $\chi$ of $G_K$ (Schur's Lemma). Because $H$ is perfect, the image of such a representation will be $\A_5 \times A_5 \times C$ for some cyclic group, and the same argument as above will apply to show that $\ker(\rho)$ is not normal in $G_{\Q}$.
(To make this complete, one should actually produce an extension of $\Q$ with Galois group $G$, but this should be easily enough to find by taking a generic $\A_5$ extension of some quadratic field.)
There may well be simpler examples, but the motivation behind this particular example is to find a group $H$ with a non-cyclic Schur multiplier with the property that $\mathrm{Out}(H)$ acts non-trivially on $H^2(H,\mathbf{C}^{\times})$.
Edit This is in response to follow up  comment of the OP:  I'm sorry for not being clear. My question was a 'short hand' for 'is there a lift stable under the automorphism? If the answer is not in general, can we find conditions to ensure the existence of such a lift?'
As noted before, a necessary condition is that the fixed field of $\ker(\rhobar)$ is Galois over $E$, where $E$ is the fixed field of $\Aut(K)$. If $K = E$ this is a sufficient condition. If $K \ne E$, one additional condition that ensures a lift with suitable properties is that the Schur multiplier of the image of $\rhobar$ is trivial, because then there will exist a lift with $\ker(\rhobar) = \ker(\rho)$. So this answers the third version of your question.
Wait, perhaps your question is actually (version 4): give complete necessary and sufficient conditions for the existence of a lift in all circumstances.
Indeed I certainly have some ideas about this, although at this point, I am no longer inclined to work out the details.


text:
Q: Better way to do this if statement I am trying to improve some of my JS skills.
I have a number of colours in hex which are in an object stored as foreground colours and background colours.
When the width of the webpage is a particular size i want to make sure that some specific colours are NOT used from the object to change the text colour.
How heres what I have so far. This works fine...and i know i could use a switch too but can anyone else improve the if || statemenent please?
 var colorThemes = [
        // Combo 1:
        { foreground: "#0A1C6B", background: "#5DF0AD" },
        // Combo 2:
        { foreground: "#C2F5FF", background: "#0A1C6B" },
        // Combo 3:
        { foreground: "#583985", background: "#CCCCF0" },
        // Combo 4:
        { foreground: "#FBBEA6", background: "#5839B5" },
        // Combo 5:
        { foreground: "#8A350D", background: "#FFDB0D" }
    ]

   var randomnumber = Math.floor((Math.random() * colorThemes.length));

   var selector = colorThemes[randomnumber]

   if (selector.foreground === "#0A1C6B" || selector.foreground === "#5DF0AD" || selector.foreground === "#C2F5FF" || selector.foreground === "#ABD1fA" || selector.foreground === "#FBBEA6" || selector.foreground === "#FACCD4" || selector.foreground === "#FF5919" ||  selector.foreground === "#D9F2AD" || selector.foreground === "#83BF25"){

            copyCount[i].style.color = selector.background;

            }
        }'

Thank you

A: You can create an array including all the colors and then check that the selected color is included in this array.

const colorThemes = [
  { foreground: "#0A1C6B", background: "#5DF0AD" },
  { foreground: "#C2F5FF", background: "#0A1C6B" },
  { foreground: "#583985", background: "#CCCCF0" },
  { foreground: "#FBBEA6", background: "#5839B5" },
  { foreground: "#8A350D", background: "#FFDB0D" }
]

const colors = colorThemes.reduce((acc, curr) => {
  acc.push(curr.foreground, curr.background);

  return acc;
}, []);

const randomnumber = Math.floor((Math.random() * colorThemes.length));

const selector = colorThemes[randomnumber]

if (colors.includes(selector.foreground)) {
  console.log('Success');
}

A: You could try with Array#filter
if (colorThemes.filter(a => (selector.foreground === a.foreground|| selector.foreground == a.background)).length > 0) {
  copyCount[i].style.color = selector.background;
} }

A: You could use Array#indexOf with an array for the colors.

var colorThemes = [{ foreground: "#0A1C6B", background: "#5DF0AD" }, { foreground: "#C2F5FF", background: "#0A1C6B" }, { foreground: "#583985", background: "#CCCCF0" }, { foreground: "#FBBEA6", background: "#5839B5" }, { foreground: "#8A350D", background: "#FFDB0D" }],
    randomnumber = Math.floor(Math.random() * colorThemes.length),
    selector = colorThemes[randomnumber],
    changeColors = ["#0A1C6B", "#5DF0AD", "#C2F5FF", "#ABD1fA", "#FBBEA6", "#FACCD4", "#FF5919", "#D9F2AD", "#83BF25"];

if (changeColors.indexOf(selector.foreground) !== -1) {
    console.log('change color!');
    //copyCount[i].style.color = selector.background;
}

With ES6 you could use Set for the colors

var colorThemes = [{ foreground: "#0A1C6B", background: "#5DF0AD" }, { foreground: "#C2F5FF", background: "#0A1C6B" }, { foreground: "#583985", background: "#CCCCF0" }, { foreground: "#FBBEA6", background: "#5839B5" }, { foreground: "#8A350D", background: "#FFDB0D" }],
    randomnumber = Math.floor(Math.random() * colorThemes.length),
    selector = colorThemes[randomnumber],
    colorSet = new Set(["#0A1C6B", "#5DF0AD", "#C2F5FF", "#ABD1fA", "#FBBEA6", "#FACCD4", "#FF5919", "#D9F2AD", "#83BF25"]);

if (colorSet.has(selector.foreground)) {
    console.log('change color!');
    //copyCount[i].style.color = selector.background;
} else {
    console.log('nothing has changed!');
}

A: Don't use an if statement.  They are code-smells.
var colorThemes = {
  "#0A1C6B": "#5DF0AD"
  , "#C2F5FF": "#0A1C6B"
  , "#583985": "#CCCCF0"
  , "#FBBEA6": "#5839B5"
  , "#8A350D": "#FFDB0D"
};

var foregroundColors = Object.keys(colorThemes);
var randomForegroundIdx = Math.floor(Math.random() * colorThemes.length);
var randomForeground = foregroundColors[randomForegroundIdx];
copyCount[i].style.color = colorThemes[randomForeground];

redpajama_set_name: RedPajamaStackExchange


text:
Q: CocoaPods ShareKit install issue I try to install ShareKit 2.2 using CocoaPods.
In command line I enter next:
touch Podfile
open -e Podfile

Edit my Podfile with lines below:
platform :ios, '5.0'
pod 'ShareKit', '~> 2.2'

Save file and enter pod install
After line Installing ShareKit (2.2) command line tool asks me to enter github account information. I have entered my account and got this message below:
[!] Pod::Executable clone  --mirror "https://github.com/dkuhnke/ShareKit.git" "/Users/developer/Library/Caches/CocoaPods/GitHub/a45caba117704c3f4cfa5f478a14e9305d2d5e9f"

Cloning into bare repository '/Users/developer/Library/Caches/CocoaPods/GitHub/a45caba117704c3f4cfa5f478a14e9305d2d5e9f'...
fatal: https://github.com/dkuhnke/ShareKit.git/info/refs?service=git-upload-pack not found: did you run git update-server-info on the server?

What did I do wrong?

A: The maintainers of ShareKit decided to remove the tag references that were used for the specs. Currently they want to be removed from the CocoaPods specs repo for now https://github.com/CocoaPods/Specs/pull/2280
I would recommend installing via their instructions https://github.com/ShareKit/ShareKit/wiki/Installing-sharekit
Edit: I have just removed the 2.1 and 2.2 specs https://github.com/CocoaPods/Specs/commit/c7ba46164cd76ef3a34a4036f2f3889ee0e0187c
The 2.0 spec is still available but you may still consider the official install instructions.
Update:
A ShareKit version 2.3 spec has been added to the repo if you still want to install ShareKit with CocoaPods https://github.com/CocoaPods/Specs/commit/e7b99c9913be9e8b31ea846a98a60f8f25acbd64

A: You are having this issue because your project path contained single quotes or spaces.
This issue has been already reported to cocoapods.


text:
Q: Angular HttpClient not sending the properties provided by a gettter student.ts
...

private _status: string;

...

get status() {
  return this._status;
}

...

student.service.ts
...

save(student: Student): Observable<Student> {
  const postStudentURL = 'http://localhost:8080/api/students';
  return this.httpClient.post<Student>(postStudentURL, student);
}

...

JSON sent to back-end
{
...

"_status": "Valid",

...
}

Why status is not sent and instead the private _status is sent ?

A: return this.httpClient.post<Student>(postStudentURL, student);

The line above sends json representation of student object.
so the request contains field instead of getter.
For confirmation you can manually create a instance of Student and then console.log(JSON.stringify(student))


text:
Q: what's wrong with this stack? I have a question about stacks...
I want to write a program with 3stacks and I want to add this operations on each of these stacks( I should use arrays):
1.create the stack
2. push number
3.pop number
4. display the top of each stack
I wrote the program but I encountered these errors:

Error 4   error LNK2019: unresolved external symbol "public: int
  __thiscall stack::IsFull2(void)" (?IsFull2@stack@@QAEHXZ) referenced in function "public: void __thiscall stack::Push2(void)"
  (?Push2@stack@@QAEXXZ)    C:\Users\Princess\Documents\Visual Studio
  2012\Projects\Project9\Project9\Source.obj
Error 5   error LNK1120: 1 unresolved
  externals C:\Users\Princess\Documents\Visual Studio
  2012\Projects\Project9\Debug\Project9.exe 1

what should I do in order to solve these errors?
#include <iostream>
using namespace std;
#define Max 100
class stack
{
private:
    int a[Max],b[Max],c[Max];
    int sp1,sp2,sp3;
public:
    void create1();
    void create2();
    void create3();
    int IsEmpty1();
    int IsEmpty2();
    int IsEmpty3();
    int IsFull1();
    int IsFull2();
    int IsFull3();
    void Push1();
    void Push2();
    void Push3();
    int Pop1();
    int Pop2();
    int Pop3();
    void Top();
    void Show();
    int menu();
};
//***************************************
void stack::create1()
{
    sp1=-1;
};
//***************************************

void stack::create2()
{
    sp2=-1;
}
//***************************************

void stack::create3()
{
    sp3=-1;
}
//***************************************
int stack::IsEmpty1(){
    return sp1==-1;
}
//***************************************
int stack::IsEmpty2(){
    return sp2==-1;
}
//***************************************
int stack::IsEmpty3(){
    return sp3==-1;
}
//***************************************

int stack::IsFull1()
{
    return sp1==Max-1;
}
//***************************************
void stack::Push1()
{
    if(IsFull1())
        printf("stack is full");
    else
    {
        int x;
        cout<<"Enter your number"<<endl;
        cin>>x;
        sp1++;
        a[sp1]=x;
    }
}
//***************************************
int stack::Pop1()
{
    if(IsEmpty1())
        cout<<"stack is empty"<<endl;
    else
    {
        int x=a[sp1];
        sp1--;
        return x;
    }
}
//***************************************
int stack::IsFull3()
{
    return sp3==Max-1;
}
//***************************************
void stack::Push2()
{
    if(IsFull2())
        printf("stack is full");
    else
    {
        int x;
        cout<<"Enter your number"<<endl;
        cin>>x;
        sp2++;
        b[sp2]=x;
    }
}
//***************************************
int stack::Pop2()
{
    if(IsEmpty2())
        cout<<"stack is empty"<<endl;
    else
    {
        int x=b[sp2];
        sp2--;
        return x;
    }
}
//***************************************
void stack::Push3()
{
    if(IsFull3())
        printf("stack is full");
    else
    {
        int x;
        cout<<"Enter your number"<<endl;
        cin>>x;
        sp3++;
        c[sp3]=x;
    }
}
//***************************************
int stack::Pop3()
{
    if(IsEmpty3())
        cout<<"stack is empty"<<endl;
    else
    {
        int x=c[sp3];
        sp3--;
        return x;
    }
}
//***************************************
void stack::Top()
{
    cout<<"the top of first stack"<<a[sp1]<<endl;
    cout<<"the top of second stack"<<b[sp2]<<endl;
    cout<<"the top of third stack"<<c[sp3]<<endl;
}
//***************************************
void stack::Show()
{
    for(int i=0;i<=sp1;i++)
        cout<<"the members of the first stack:"<<a[i]<<endl;
    for(int j=0;j<=sp2;j++)
        cout<<"the members of the second stack:"<<b[j]<<endl;
    for(int k=0;k<=sp3;k++)
        cout<<"the members of the third stack:"<<c[k]<<endl;
}
//***************************************

int stack::menu(){
    int x;
    cout<<"1.Add Item"<<endl;
    cout<<"2.Delete Item"<<endl;
    cout<<"3.Get Count"<<endl;
    cout<<"4.Show stack"<<endl;
    cout<<"5.Exit"<<endl;
    cout<<"Enter your choose:"<<endl;
    cin>>x;
    return x;
}
////***************************************
int main()
{
    stack st;
    st.create1();
    st.create2();
    st.create3();
    while(1)
    {
        switch(st.menu())
        {
            case 1:
                cout<<"first stack:"<<endl;
                st.Push1();
                cout<<"second stack:"<<endl;
                st.Push2();
                cout<<"third stack:"<<endl;
                st.Push3();
                break;
            case 2:
                cout<<"first stack:"<<endl;
                st.Pop1();
                cout<<"second stack:"<<endl;
                st.Pop2();
                cout<<"third stack:"<<endl;
                st.Pop3();
                break;
            case 3:
                st.Top();
                break;
            case 4:
                st.Show();
                break;
            case 5:
                return 0;
            default:
                cout<<"incorrect"<<endl;
        }
    }
    return 0;
}

A: Exactly what the error says: you did not define the stack::IsFull2 method in your code, but you use it inside the stack::Push2 method. You need to write the body of stack::IsFull2 or change your code so it does not call it (and then remove the declaration too).


text:
Q: Multicolumn vector How can I create a vector like this one?

It is similar to this question, but with additional columns.

A: Quick and dirty approach with pmatrix environment
The individual columns are separated by a & character, the next linebreak is achieved with \\
If one replaces pmatrix with bmatrix, the [ ] version is obtained
\documentclass[12pt]{article}

\usepackage{mathtools}

\begin{document}

\begin{equation*}
 A =  \begin{pmatrix}
   3 & 5 \\
   5 & 2 \\
   2 & 1 \\
   1 & 4 \\
   7 & 9
   \end{pmatrix}
\end{equation*}

\end{document}


text:
Q: Параметр/переменная в WHERE в IN Необходимо переделать процедуру, сейчас она формирует результат так :
dateDocument between @dateOne and @dateTwo, тут все понятно проблем нет.
 Я хочу что бы можно было формировать только по id, так
WHERE dataRegistr.id IN (@id)
Вопрос, как в @id передать несколько значений? Примитивно методом тыка не затащило :
declare @test varchar(200) = '85,86,87';
EXEC report @test

A: В SQL Server с версии 2008 есть Table-Valued Parameters, которые позволяют передавать в процедуры табличные данные.
Через них можно передать сразу пачку ID, примерно так:
CREATE TYPE IDList AS TABLE
( ID INT );
GO

CREATE PROCEDURE dbo.SomeProcedure
    @ids IDList READONLY
AS
    SET NOCOUNT ON
    SELECT * FROM SomeTable WHERE TaskID IN (SELECT Id FROM @ids)
GO

DECLARE @someIDs AS IDList;

INSERT INTO @someIDs
VALUES (1),(2),(3)

EXEC SomeProcedure @someIDs
GO

A: Я сделал так :
В процедуру передаю к примеру @test varchar(max) = '44,42,4,6,8' в процедуре :
Это в самом верху процедуры  :
select @test ='select '''+replace(@test , ',', ''' as val union all select ''')+''''
declare @t table(id int identity, val varchar(100))
insert into @t
exec (@test )

Во всех WHERE где есть IN делаю так, например :
 WHERE id IN (select val from @t where val!='')


text:
Q: how to copy some specific .jpg files to another directory? I want to copy some specific jpg files to another directory and I don't understand why it doesn't work? I have a lot of image and want to sort on certain categories for the moment only those that have the beginning name of 15_0_xxx.jpg respectively 15_1_xxx.jpg
import cv2

import sys
import os
import shutil
from os import listdir
from os.path import isfile, join

mypath = "c:/Users/Harum/Desktop/make dir/"
file_names = [ f for f in listdir(mypath) if isfile(join(mypath, f))]

print(str(len(file_names))+ ' images loaded')

cont_M =0
cont_F =0
m_age = "c:/Users/Harum/Desktop/make dir/M_15/"
f_age = "c:/Users/Harum/Desktop/make dir/F_15/"

input_m = []
input_mS =[]
input_fS =[]
input_f = []

def getZeros(number):
    if(number > 10 and number <100):
        return "0"
    if(number < 10):
        return "00"
    else:
        return ""

for i, file in enumerate(file_names):
    if file_names[i][0] == "15_0":
        cont_M +=1
        image = cv2.imread(mypath+file)
        input_m.append(image)
        input_mS.append(0)
        zeros = getZeros(cont_M)
        cv2.imwrite(m_age +"m_age"+str(zeros)+ str(cont_M)+ ".jpg",image)

    if file_names[i][0] == "15_1":
        cont_F +=1
        image = cv2.imread(mypath+file)
        input_f.append(image)
        input_fs.append(1)
        cv2.imwrite(f_age+"F_age"+str(zeros)+ str(cont_M)+ ".jpg",image)

`

A: Edit: forgot the copying part. You can use shutil for that
You would do better with glob and os:
from shutil import copyfile
import glob
import os

mypath = "c:/Users/Harum/Desktop/make dir/"
destination_path = "c:/Users/Harum/Desktop/copy/"
# using fstrings to add wildcard character to consider all files. You could add a
## file extension after, as in f"{mypath}15_*.jpg"
file_names = glob.glob(f"{mypath}15_*")

# skip the middle to the ifs
# (...)

# removed the enumerate as it doesn't seems like you're using the positional list index

for file in file_names:
    # getting only the filename (with extension)
    file_name = os.path.basename(file)

    # using the str().startswith() to check True or False
    if file_name.startswith("15_0"):
        cont_M +=1
        copyfile(file, f"{destination_path}{file_name}")
        # (...)

    elif file_name.startswith("15_1"):
        cont_F +=1
        copyfile(file, f"{destination_path}{file_name}")
        #(...)


text:
Q: iphone grabkit library trouble in xcode I am developing one iOS application in which I wan to integrate grabkit (excellent ) library.
I have tried to use in xocode 6 with 64 bit architecture but it shows me lots of error.
I have followed below instructions but still getting error
https://github.com/pierrotsmnrd/grabKit
Can you please advice me.
Thanks in advance

A: It seems like, You forget to add some frameworks, which mentioned on install and configure process.
Follow this two links,
install : github.com/pierrotsmnrd/grabKit/wiki/How-to-install-GrabKit
configure : github.com/pierrotsmnrd/grabKit/wiki/How-to-configure-GrabKit

A: Grabkit was build in 32bit XCODE..and now days as per apple rules iOS application must be build in 64bits else application get rejected. If we are trying to setup 32bit grabkit project in 64bits xcode then it got error. So now days we dont have to use Grabkit in any other project till the compatible version will be launch because of compatibility issue.


text:
Q: Why is creating ArrayList with initial capacity slow? Comparing creating large ArrayList with intialCapacity I found that it;s slower than creting it without one. Here is the simple program I wrote to measure it:
long start2 = System.nanoTime();
List<Double> col = new ArrayList<>(30000000); // <--- Here
for (int i = 0; i < 30000000; i++) {
    col.add(Math.sqrt(i + 1));
}
long end2 = System.nanoTime();
System.out.println(end2 - start2);
System.out.println(col.get(12411325).hashCode() == System.nanoTime());

The average result for new ArrayList<>(30000000): 6121173329
The average result for new ArrayList<>(): 4883894100
on my machine. I thought that it would be faster to create large array once rather than reacreating it once we go beyond the capacity of the current underlying array of ArrayList. Eventually we should have ended up with array size greater or equal than 30000000.
I thought it was optimization, but actualy pessimization. Why that?

A:
I ran the same program multiple times. It was not in a loop

Consider how you are profiling the code - if you include both a 'ramp up time' (to take into account things such as JIT) and average over several calls (to gather some statistics/distribution), the timing may lead you to a different conclusion. For example:
public static void main(String[] args){
    //Warm up
    System.out.println("Warm up");
    for ( int i = 0; i < 5; i++ ){
        dynamic();
        constant();
    }
    System.out.println("Timing...");
    //time
    long e = 0;
    long s = 0;
    int total = 5;
    for ( int i = 0; i < total; i++ ){
        long e1 = dynamic();
        System.out.print(e1 + "\t");
        e += e1;
        long s1 = constant();
        System.out.println(s1);
        s += s1;
    }
    System.out.println("Static Avg: " + (s/total));
    System.out.println("Dynamic Avg: " + (e/total));

}

private static long dynamic(){
    long start2 = System.currentTimeMillis();
    List<Double> col = new ArrayList<>();
    for (int i = 0; i < 30000000; i++) {
        col.add(Math.sqrt(i + 1));
    }
    long end2 = System.currentTimeMillis();
    return end2 - start2;
}

private static long constant(){
    long start2 = System.currentTimeMillis();
    List<Double> col = new ArrayList<>(30000000);
    for (int i = 0; i < 30000000; i++) {
        col.add(Math.sqrt(i + 1));
    }
    long end2 = System.currentTimeMillis();
    return end2 - start2;
}

On my system setting the initial capacity is always faster, though not by any orders of magnitude.
Edit: As suggested in a comment, consider reading through How do I write a correct micro-benchmark in Java?


text:
Q: Order of javascript execution I read that

JavaScript caches declared functions before any other variables, after
this, it goes back to the top of the scope and runs variable
definitions and functions calls in the order that they appear

And I don't understand this example
//bob first initialization
function bob()
{
    alert('bob');
}

//set jan to bob via reference
var jan = bob;

//set bob to another function
function bob()
{
    alert('newbob');
}

jan(); //alerts 'bob'
bob(); //alerts 'newbob'

both bob() function are declared and cached before execution. Why is it then that jan() alerts 'bob' and not 'newbob'? When jan was initialized bob() had already been re-declared.
Any ideas? THanks

A: because jan points to the first declaration of bob (as a pointer) and not the new declared bob you need to set jan = bob; after the second declaration
not so sure though.


text:
Q: My defualt text is appear first then after a few second my replacement text appears It looks awful.  Please have a look at absolute-websites.com/portfolio and you'll see what I mean.  What an I do to fix this please?

A: Are you referring to the Flash text at the top? Rasterize the text as JPG, GIF or PNG.


text:
Q: Retrieve RadGrid control dropdownlist selected value I have RadGrid with DropDownlist. I am trying to find the value of each control by looping through using javascript and I am getting findcontrol as 'null'. I have attached OnClientRatingSelectedIndexChanged in code behind for the dropdownlist.
 What could be wrong? I appreciate any suggestions.
  <telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="false" AlternatingItemStyle-HorizontalAlign="Left"
                               OnNeedDataSource="RadGrid1_NeedDataSource">
                                <MasterTableView DataKeyNames="level_id" PageSize="10">
                                    <Columns>
 <telerik:GridTemplateColumn UniqueName="TemplateColumn" HeaderText="Test"
                                            Visible="true">
                                            <ItemTemplate>
                                                <asp:Panel ID="Panel1" runat="server">
                                                    <asp:DropDownList ID="Drop1" runat="server"                                                                                AutoPostBack="true">
                                                    </asp:DropDownList>
                                                </asp:Panel>
                                            </ItemTemplate>
                                        </telerik:GridTemplateColumn>
                                  </Columns>
</MasterTableView>
</telerik:RadGrid>

Javascript
   function OnClientRatingSelectedIndexChanged(arg) {

        var grid = $find("<%=RadGrid1.ClientID %>");
        var MasterTable = grid.get_masterTableView();
        var Rows = MasterTable.get_dataItems();
        for (var i = 0; i < Rows.length; i++) {
            var row = Rows[i];
            var drop1 = row.findControl("Drop1");
            var val1 = drop1.selectedValue;
        }

A: Try this :
protected void Radgrid1_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
    {
        if (e.Item is GridDataItem)
        {
            GridDataItem item = (GridDataItem)e.Item;
            DropDownList list = (DropDownList)item.FindControl("DropDownList1");
            list.Attributes.Add("onChange", "OnSelectedIndexChange('" + item.ItemIndex + "');");
        }
    }

JS:
function OnSelectedIndexChange(rowindex) {
        var grid = $find("<%=Radgrid1.ClientID %>");
        var MasterTable = grid.get_masterTableView();
        var drop1 = MasterTable.get_dataItems()[rowindex].findElement('DropDownList1');
        alert(drop1.value);

    }


text:
Q: Compress/expand sound from Mp3 files in Linux server/terminal? In a python script on my Ubuntu server, i need to process many incoming mp3 audio files with sound compressor. E.g. a tool that reduces difference between the most quiet and most loud sound levels.
Is that possible? I believe i don't need to write a program for this.
If so, what utility i should use and how do i configure it?

A: FFmpeg has a filter for compressing or expanding the audio's dynamic range called compand. You can exec it from within your Python script. Check the documentation for usage examples.
Random example (for audio with whisper and explosion parts):
ffmpeg -i input.mp3 -af "compand=0|0:1|1:-90/-900|-70/-70|-30/-9|0/-3:6:0:0:0" output.mp3

meaning:
attack 0, decay 1, points -90/900, -70/-70, -30/-9. 0/-3, soft-knee 6, gain 0, volume 0, delay 0
To install it you can sudo apt-get install ffmpeg or compile it from source to get the latest features.

A: If you're merely looking for "a tool that reduces difference between the most quiet and most loud sound levels" then it sounds like you're looking for dynamic range compression, though I'd suggest you also investigate ReplayGain, which determines the optimal loudness level for an audio track (as opposed to making the soft parts louder and the loud parts softer).  For most uses, ReplayGain is preferable, though if you have hearing problems or merely want to maximize people's ability to understand a sound clip (rather than enjoying it), range compression makes more sense.
There are two ways to do either of these tasks: permanently and via metadata:
Permanently
This involves decompressing the audio, modifying it, and re-encoding it.  You will lose audio quality because MP3 is lossy, though this would be a minor hit if you use the exact same encoder at the exact same software version and the exact same configuration.  The fact that you must re-encode will also make this process significantly slower.
Via metadata
There is software out there that can evaluate your library and stick ReplayGain measurements into your media's metadata (in the case of MP3, this would be as an ID3 tag). Players that understand this format can then adjust the volume levels as you play the audio sample.  This is non-destructive and you will lose nothing.  It's also faster since you don't need to compress the audio back into an MP3.

There are plenty of implementations to choose from, at least for ReplayGain.


text:
Q: Build trigger don't get saved in Jenkins We have a nighly build that triggers build of many different projects to verify external testing like contracts and such to avoid triggering such tests on every checkin.
However lately we have encountered a problem, if you open a build configuration and enter any parameter or build triggers and then saves the configuration. Once you save it gives no indication as to an error or anything but if you open it again its not there, no build trigger or parameter gets saved.
We have managed to isolate it to pipeline build, freestyle builds still works.
We installed Blue Ocean recently and are not wondering if it somehow changes how a pipeline job definition is saved. It seems a bad decision if Blue ocean hinders such a basic setting but still. We haven't been able to create a pipeline job throught blue ocean either since our job isn't triggered by any SCM and blue ocean requires that.


text:
Q: SQL Server 2008 Error 18452 The login is from an untrusted domain and cannot be used with Windows authentication I am trying to figure out what is going on. Here is our setup:
We have four SQL servers that are in replication with each other.
We add a new user to Windows Active Directory and add them to a group that is in SQL Server that we have been using for ages.
The new user, when trying to authenticate using Windows authenication returns that error in the subject line.  But, any users that were previously in Active directory work fine.
At one point I had gotten SQL Server "caught up" becauuse we had a group of users that could not log in because of this error.  I did some changes to the SPNs and ended up making it so no one could log in.  Then I realized how the SPNs were supposed to look and fixed it.  Then I guess some magic happened and those users were able to authenticate.  I thought it was fixed, but it is obviously not as we had to add one new user and they cannot authenticate.
What is interesting is that the user can authenticate with three out of the four SQL Servers.  It is only this one server that is working incorrectly.  I set up two SPNs for the SQl Service on this sql server.
They look like -
MSSQLSvc/[servername].[domain].local:1433
MSSQLSvc/[servername]:1433
These are actually registered to the Service account that we use for the SQL Servers.  What is interesting is that I can't find the SPNs for the servers that are working anywhere.
Any help would be appreciated!
Edit: Also, another point to note is that if I try to add the user directly as a login into SQL server.  I right click Logins and click Add Login then click search.  I then type in [Domain]\[Username] and click check names.  It validates the name as being correct.  Then I click OK.  And then OK again, and it gives the Error Windows NT user or group '[Domain]\[Username]' not found.  Check the name Again.

A:
I thought it was fixed, but it is obviously not as we had to add one
  new user and they cannot authenticate.

The user has to relogin in order to pick up the new group.  Otherwise, it's kerberos ticket is still using the old group membership information in its PAC

These are actually registered to the Service account that we use for
  the SQL Servers. What is interesting is that I can't find the SPNs for
  the servers that are working anywhere.

I think what happen is that you have one SQL Server with SPN setup properly while the other three SQL Servers with no SPN setup at all.  So, you are going to use Kerberos on this particular server while NTLM on the other three.
As mentioned before, when you are using Kerberos, you have to either purge the ticket using some tools or you have to relogin in order to pick up the new group membership.  You can also try to lock the screen and then unlock it.  If I remember correctly, this should also refresh the ticket.
Unlike Kerberos, NTLM doesn't carry the group memberhsip data.  After SQL Server authenticated the user using NTLM, it will find the authenticated user's group membership, including the new group you just added.


text:
Q: class function(with a while(mysql_fetch_assoc) , in_array, and json_decode() methods ) not working properly inside a foreach I have this foreach loop
foreach($custom_time as $row) {
  echo "
";
    echo "$row	";
    $check_reservation = $reserve->is_reserved($row);
    if($check_reservation == "reserved"){
      echo "Reserved	";
    }
    else {
      echo "Available	";
    }
  echo "
";
}

Assuming that $custom_time is an array of time from 8:00 am to 10:00 pm. I would be like to display a table here. Next, I have this function inside the $reserve class.
public function is_reserved($time_custom_string){
  $array = $this->reserved_time;
  while($row = mysql_fetch_assoc($array)){
    if(in_array($time_custom_string , json_decode($row['reserve_time']))) {
      return "reserved";
    }
  }
}

Now, $this->reserved_time is a mysql_query result. Assuming that the result is a json_encoded array of 1:00 pm and 2:00 pm. I'm trying to display a table that would show the 1:00 pm and 2:00 pm row in the table as "Reserved", and the rest will be "Available". The problem is that the table is showing "Available" to all its tablerows. I edit the code like this:
foreach($custom_time as $row) {
  echo "
";
    echo "$row	";
    $check_reservation = $reserve->is_reserved($row);
    echo "$check_reservation	";
  echo "
";
}

And the function like this:
public function is_reserved($time_custom_string){
  $array = $this->reserved_time;
  while($row = mysql_fetch_assoc($array)){
    if(in_array($time_custom_string , json_decode($row['reserve_time']))) {
      return "reserved";
    }
    else {
      return "not reserved";
    }
  }
}

Now, the table only printed the first row as "Not Reserved". The succeeding tablerows are blank. I'm stuck with this for hours but I still can't see why my code is not working as I expected, I think my code seems right. Can someone help me with this?

A: mysql_fetch_assoc advances the internal pointer until it gets to the last row, at which point it returns false (therefore allowing your loop to exit).
Calling it again will just keep on returning false.
You can reset it with mysql_data_seek($array,0)


text:
Q: Sphere inversion in Riesz potential I am reading the paper: ``ON THE DISTRIBUTION OF FIRST HITS FOR THE SYMMETRIC STABLE PROCESSES" by Blumenthal, Getoor and Ray, (Trans. Amer. Math. Soc. 99 (1961), 540-554).
On page 546, the authors talk about the idea of Riesz regarding spherical inversions. In particular they say, for the sphere $\{u:|x-u| =r\}$, inversion is the change of coordinates
$$
u \mapsto v = x+r^2\frac{(u-x)}{|u-x|^2}.
$$
Then the authors explain
``Riesz noted that if $f(u)$ is a potential of exponent $\alpha$ in $R^N$, then after inversion in a sphere with center $x$, $(x —v)^{\alpha-N}f(v)$ is a potential."
I dont understand this sentence. Also later they use this idea to write some identities which I do not understand at all. For example, in page 547, they write ``if $|y| >1$, inverting along the sphere $\{u: |y-u|^2 = |y|^2-1\}$ yields
$$
\int _{|u| \le 1} (1-|u^2|)^{-\alpha/2} |u-y|^{\alpha-N}du = (|y|^2 -1)^{\alpha/2} \int_{|v| \le 1} (1-|v|^2)^{-\alpha/2} |v-y|^{-N}dv "
$$
I would be obliged if anyone can shed some light on these mysterious identities.

A: Well, you may like to have a look at the original M. Riesz's 1938 paper: it is a fantastic read!

In the language of these papers, a "potential" of exponent $\alpha$ is a function $f$ of the form
$$ f(x) = \int_{\mathbb{R}^N} |y - x|^{\alpha - N} \mu(dy) , $$
where $\mu$ is a non-negative measure. M. Riesz observed that if $f$ is a potential, then its Kelvin transform
$$ \mathcal{K} f(x) = |x|^{\alpha - N} u(x / |x|^2) $$
is again a potential. This corresponds to inversion in the unit sphere $B(0, 1)$, that is, the change of coordinates:
$$ x \mapsto y = x / |x|^2 . $$
Obviously, the above observation extends (by translation and change of scale) to arbitrary spheres, and this is precisely the result that Blumenthal, Getoor and Ray refer to.

The above observation is particularly useful when inversion in the corresponding sphere preserves the unit ball. Such a sphere have a form given in the second part of your question, and the identity you are asking about is proved by the corresponding change of variable.

All authors mentioned above (M. Riesz, Blumenthal, Getoor and Ray) used these kind of calculations a lot, and rarely provided details. I believe, mostly because these are direct extensions of the well-studied case corresponding to $\alpha = 2$.
I do not know good references which give all details. A book by Bliedtner and Hansen, and perhaps a book by Landkoff, have them, if I remember correctly, but I find them both rather unfriendly.


text:
Q: setting custom adapter in listview is causing the screen to load for too long I´m developing a game for android and my activity is taking too long to load a listview with custom adapter. I already tried to pass the list to the adapter by an AsyncTask and using a progressDialog to make the user wait, but even this is making the screen(the load screen) freeze for a long time until the list components are loaded. What´s worse is that, after the screen is loaded, scrolling through the listview is too slow and can lead to the famous "Skipped 60 frames! The application may be doing too much work on its main thread", which causes my Activity to, suddenly, reset.
The listview will only have 30 components at most, but how can I make this listView not take too long to load, make it not freeze the loading screen and how can I overcome the "Skipped 60 frames! The application may be doing too much work on its main thread" when I load the listView?


text:
Q: Force selenium to open desktop version of site rather than mobile I've written some code to scrape futures prices. On my work laptop, the website opens in mobile mode as opposed to desktop. This results in the DataFrame being return as a multi-index object, and throws an error saying "DataFrame has no attribute str". I've tried to drop the index, reset the index, etc. and no luck.
If I run this exact code on my personal laptop, it runs with no issue and returns exactly what I want it to. Any help on getting the Chrome webdriver to open the site in desktop mode would be greatly appreciated. I've tried setting the window size, and tried maximizing the page, yet nothing seems to work to open the desktop version.
from bs4 import BeautifulSoup
import requests
import os
from selenium import webdriver
import pandas as pd
import time
from selenium.webdriver.chrome.options import Options

driver = webdriver.Chrome(executable_path=r"C:\TEMP\ChromeDriver\chromedriver.exe")
driver.set_window_size(1920,1080)
driver.get('http://cmegroup.com/trading/agricultural/grain-and-oilseed/soybean.html')
time.sleep(3)
table = driver.find_element_by_css_selector('#quotesFuturesProductTable1').get_attribute('outerHTML')
soup = BeautifulSoup(table, 'html.parser')
df = pd.read_html(str(soup))[0]
df = df[df.Month.str[0:3]=='NOV']  **This is where it throws the error that DataFrame has no attribute string, yet exact code works on my personal laptop as the desktop version does not come back as a multi-index

print(df)
browser.quit()


text:
Q: Python while loop is pausing I am trying to do multiple while loops but somehow they don't work. I already searched the internet but none of the problems I found has the same issue.
So here is the code containing only the necessary information. I am basically opening a socket, giving an in input (i\n) and receiving the output in the first step. I want to continue receiving the output until I have some specific characters xxx in the output. Then I want to go to the elif statement in the next loop.
def netcat(h, p):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((h,p))

    i = 0
    a = True
    while a == True:
        socket_list=[sys.stdin, s]
        r,w,x = select.select(socket_list, [], [])

        if i==0:
            time.sleep(1)
            message = s.recv(1024)
            print(message)
            s.send("i\n")
            sys.stdout.flush()

            while "xxx" not in message:
                message = s.recv(1024)
                print(message)
            i+=1
        elif i==1:
            print("+++++++++++++++++++++++++++")
                        i+=1

        print("hello")

    server.close()

What I would expect the code to do is to print the message from the if statement, then print hello, then the message from the elif statement and then hello over and over again because the while loop is still active. So in summary this is the expected output:
message
hello
+++++++++++++++++++++++++++
hello
hello
hello
hello...

What it really prints is
message
hello

and then it finishes.
What I found out is that if I comment out the following lines:
                while "xxx" not in message:
                    message = s.recv(1024)
                    print(message)

it works as expected. The hello at the end of the code gets printed to the screen over and over again. I just don't get it why this second while loop has anything to do with it. I would really appreciate help here.
Since the working code was requested, here is also the full code. The hostname and port are from a CTF which is still working so you will be interacting with the CTF-server:
#!/usr/bin/env python

import socket
import time
import select
import sys

base64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ ="
hostname = "18.188.70.152"
port = 36150

def netcat(h, p):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((h,p))

    i = 0
    a = True
    b = True
    while a == True:
        socket_list=[sys.stdin, s]
        r,w,x = select.select(socket_list, [], [])

        if i==0:
            time.sleep(1)
            message = s.recv(1024)
            print(message)
            s.send("i\n")
            sys.stdout.flush()

            while "flag" not in message:
                message = s.recv(1024)
                print(message)
            txtfile = message[9:38]
            print(txtfile)
            i+=1
        elif i==1:
            print("+++++++++++++++++++++++++++")
            i+=1
        print("hello")

    server.close()

netcat(hostname, port)

A: You're mixing event-based code (select.select()) with blocking synchronous code (your small while loop with the s.recv()).
If you want your code not to block, every recv() needs to be paired up with a preceding select().
Not only that, but you must also check the returned values from select(). Only s.recv() if s was in the first returned list. If you s.recv() in any other case, the code will also block on the receive call.
Update:
Try something along the lines of:
not_done = True
while not_done:
    read_sockets, _, _ = select.select([sys.stdin, s], [], [])

    if s in read_sockets:
        message = s.recv(1024)
        print(message)

        ... more code ...

        if 'flag' in message:
            ... react on flag ...

        if 'quit' in message:
            not_done = False

    ... processing of other sockets or file descriptors ...

The important point being that there is only this one s.recv() in the if branch that checks for whether select detected something was received.
The outer while will just come back to the same if branch later when additional data was received.
Note that processing stdin alongside socket code is tricky and will likely also block at some point. You will likely have to put the terminal into raw mode or something first and then be ready to process partial lines yourself as well as maybe also echoing the input back to the user.
Update:
If you want to do something while no message was received, you can give a timeout to select() and then do other processing if there was nothing received on the socket. Something like this:
say_hello_from_now_on = False

not_done = True
while not_done:
    read_sockets, _, _ = select.select([s], [], [], 1)

    if s in read_sockets:
        message = s.recv(1024)
        print(message)

        say_hello_from_now_on = True

    elif say_hello_from_now_on:
        print("hello")

A: I'd check your indentation, try installing and running autopep8 on your code and see if that fixes any of your issues.
[edit] user has updated their question and it's clear that this isn't the answer.


text:
Q: Complex Non-liner First order ODE problem Good day people
I am modelling a "water bottle rocket" using basic Continuum Mechanics.
I have found a equation describing the acceleration of the rocket.  I need to integrate this function to find the velocity of the rocket at a point in time and then integrate it once more to find the distance it will have travelled by a certain time.
the equation :
$$\frac{dv}{dt} = \frac{1082.8}{vt} - 0.917\frac vt + \frac{11942.5}{0.231vt+0.013v^2t^2} + 4.9$$
Where $v(0) = 0$ and $791-3.6vt \geq 0$.
I have tried to solve this using Matlab, Wolfram Alpha and praying.  But non have produced an answer that I can integrate again.
Thank you for the help


text:
Q: Disable dates and time in a jquery time from mysql Update This is a complete update to my question
<!doctype html>

<meta charset="utf-8">

<meta name="author" content="Amsul - http://amsul.ca">
<meta name="viewport" content="width=device-width,user-scalable=no">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">

<title>Pickadate.js</title>

<link rel="stylesheet" href="../../lib/themes/default.css">
<link rel="stylesheet" href="../../lib/themes/default.date.css">
<link rel="stylesheet" href="../../lib/themes/default.time.css">

<?php
require 'connect-db.php';

   try{
    $stmt = $db->query("SELECT ddate FROM testdates");
$result = $stmt->fetchAll(\PDO::FETCH_ASSOC);
}catch(\PDOException $e){
    echo $e->getMessage();
}

$json_array = json_encode($result)

   ?>

        <form>
            <fieldset>

Pick a date.

                <input
                    id="datepicker_id"
                    class="datepicker"
                    name="date"
                    type="text"
                    value=""
                    data-value="">

Pick a time

                <input
                    id="timepicker_id"
                    class="timepicker"
                    value=""
                    type="time"
                    name="time">

            </fieldset>
        </form>

 // i must thank users in php chatroom for helping me fix the errors.

That above, is a page where you see a calendar, and some dates are disabled, which are fetched from the database. I'm using this picker
  disable: [
    [2015,29,9], // disables today strangely month -1 and only accepts yyy,mm,dd
    [some other array]

  ]
})

In my databese 'ddate' is varchar, no primary key, no unique id, nothing, containing
2015,9,30
2015,9,31
2015,10,30

*

*the values aren't being passed or something from mysql to javascript or something, and i guess i want multidimentional array.

*what i want the javascript array to have is month -1 because as I explained above, in disable option to disable this day, you have to enter last month number. and if first month, means 12.
Note I want to use the same for timepicker but I guess I could do on my own if I understand the issue with calendar

A: I assume, that your db content is:
ddate: varchar()

Values stored in table testdates (as strings):
2015-10-29
2015-10-15
2015-10-10

Select is still as is plus create a string for array build to js
try{
  $stmt = $db->query("SELECT ddate FROM testdates");
  $db_ddates = $stmt->fetchAll(\PDO::FETCH_ASSOC);

  $js_ddates = "";
  foreach ($db_ddates as $row => $record) {
    $js_ddates .= '"' . $record['ddate'] . '",';
  }

}
catch(\PDOException $e) {
  echo $e->getMessage();
}

Now use that inside building the script part
// take dates as array of strings from db
var ddates_str_arr = [ <?php echo $js_ddates; ?> ];
// build dates array for picker
var disdates = [];
for (var i = 0; i < ddates_str_arr.length; i++) {
  disdates.push(new Date(ddates_str_arr[i]));
}
// just use it in picker
var $input = $( '.datepicker' ).pickadate({
  formatSubmit: 'yyyy/mm/dd',
  min: true,
  container: '#container',
  // editable: true,
  closeOnSelect: true,
  closeOnClear: false,
  disable: disdates
});

ATTENTION: I have not test it but just write those lines from mind. There may some typing erratas but should work in general.

UPDATE:
Not sure about picker but give this a try too instead of the above script part
// just use it in picker
var $input = $( '.datepicker' ).pickadate({
  formatSubmit: 'yyyy/mm/dd',
  min: true,
  container: '#container',
  // editable: true,
  closeOnSelect: true,
  closeOnClear: false,
  disable: [ <?php echo $js_ddates; ?> ]
});


text:
Q: Use system channel instead of ringer channel when using EPSSampler in iOS I'm using EPSSampler to play some notes in my tiny iOS app. It works nicely, except that the sound is controlled through the ringer settings instead of the system volume settings. The problem is that, if the ringer is turned off, my app makes no sound.
The closest I could find was this SO question but I can't quite translate that solution into mine, as I can't match it to EPSSampler's code. Any insight?
EDIT To clarify, the only code that deals specifically with audio is contained in the EPSSampler class, my app merely instances it, loads an AUSampler preset, and calls the note-playing methods in EPSSampler, so a solution would need to change something in EPSSampler rather than in my app -- that's why I'm not posting any source code.

A: Turns out this had nothing to do with EPSSampler, and everything with configuring the audio session. The following code did the trick.
NSError *error = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];

That'll teach me to RTFM.

A: For swift(Use when initialising the music):
_ = try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)


text:
Q: Sum the nested dictionary values in python I have a dictionary like this,
data={11L: [{'a': 2, 'b': 1},{'a': 2, 'b': 3}],
22L: [{'a': 3, 'b': 2},{'a': 2, 'b': 5},{'a': 4, 'b': 2},{'a': 1, 'b': 5}, {'a': 1, 'b': 0}],
33L: [{'a': 1, 'b': 2},{'a': 3, 'b': 5},{'a': 5, 'b': 2},{'a': 1, 'b': 3}, {'a': 1, 'b': 6},{'a':2,'b':0}],
44L: [{'a': 4, 'b': 2},{'a': 4, 'b': 5},{'a': 3, 'b': 1},{'a': 3, 'b': 3}, {'a': 2, 'b': 3},{'a':1,'b':2},{'a': 1, 'b': 0}]}

Here i ll get rid of the outer keys, and give new key values 1, 2 , 3 so on, i want to get the result as shown below,
result={1:{'a':10,'b':7},2:{'a':11,'b':18},3:{'a':12,'b':5},4:{'a':5,'b':11},5:{'a':3,'b':9},6:{'a':3,'b':2},7:{'a':1,'b':0}}

I tried some thing like this, but i dint get the required result,
d = defaultdict(int)
for dct in data.values():
  for k,v in dct.items():
    d[k] += v
print dict(d)

I want the keys of result dictionary to be dynamic, like in the above data dictionary we have 44 which has highest with 7 key value pairs, hence we have the result dictionary with 7 keys and so on

A: You want to use a list here, and you want to perhaps use Counter() objects to make the summing that much easier:
from collections import Counter
from itertools import izip_longest

for dcts in data.values():
    for i, dct in enumerate(dcts):
        if i >= len(result):
            result.append(Counter(dct))
        else:
            result[i].update(dct)

Result:
>>> result
[Counter({'a': 10, 'b': 7}), Counter({'b': 18, 'a': 11}), Counter({'a': 12, 'b': 5}), Counter({'b': 11, 'a': 5}), Counter({'b': 9, 'a': 4}), Counter({'a': 3, 'b': 2}), Counter({'a': 1, 'b': 0})]

Counter() objects are subclasses of dict, so they otherwise behave as dictionaries. If you have to have dict values afterwards, add the following line:
result = [dict(r) for r in result]

Taking inspiration from Eric, you can transform the above into a one-liner:
from collections import Counter
from itertools import izip_longest

result = [sum(map(Counter, col), Counter())
    for col in izip_longest(*data.values(), fillvalue={})]

This version differs slightly from the loop above in that keys that are 0 are dropped from the counter when summing. If you want to keep 'b': 0 in the last counter, use:
[reduce(lambda c, d: c.update(d) or c, col, Counter())
    for col in izip_longest(*data.values(), fillvalue={})]

This uses .update() again.

A: izip_longest allows you to transpose the rows:
from itertools import izip_longest

print [
    {
       'a': sum(cell['a'] for cell in column),
       'b': sum(cell['b'] for cell in column)
    }
    for column in izip_longest(*data.values(), fillvalue={'a': 0, 'b': 0})
]

[{'a': 10, 'b': 7}, {'a': 11, 'b': 18}, {'a': 12, 'b': 5}, {'a': 5, 'b': 11}, {'a': 4, 'b': 9}, {'a': 3, 'b': 2}, {'a': 1, 'b': 0}]

Or combining that with counters:
print [
    sum(Counter(cell) for cell in column, Counter())
    for column in izip_longest(*data.values(), fillvalue={})
]

[Counter({'a': 10, 'b': 7}), Counter({'b': 18, 'a': 11}), Counter({'a': 12, 'b': 5}), Counter({'b': 11, 'a': 5}), Counter({'b': 9, 'a': 4}), Counter({'a': 3, 'b': 2}), Counter({'a': 1, 'b': 0})]

A: First find the length of the longest list among all the values (which are lists):
max_length = 0
for key in data.keys():
    if max_length < len(data[key]):
        max_length = len(data[key])

In your case, max_length = 7. Now iterate as follows:
result = {}
for i in range(max_length):
    result[i+1] = {'a': 0, 'b': 0} # i + 1 since the result starts with key = 1
    for key in data.keys():
        if i < len(data[key]):
            result[i+1]['a'] += data[key][i]['a']
            result[i+1]['b'] += data[key][i]['b']

You should get:
print result
{1: {'a': 10, 'b': 7}, 2: {'a': 11, 'b': 18}, 3: {'a': 12, 'b': 5}, 4: {'a': 5, 'b': 11}, 5: {'a': 4, 'b': 9}, 6: {'a': 3, 'b': 2}, 7: {'a': 1, 'b': 0}}

Edit: @user2286041 If you'd like the result dict to be reduced to
reduced_result = {'a': [10, 11,12,5,4,3,1], 'b': [7, 18,5,11,9,2,0]}

then you can try the following code:
reduced_result = {}
inner_keys = ['a', 'b']
for inner_key in inner_keys:
    temp = []
    for outer_key in result:
        temp.append(result[outer_key][inner_key])
    reduced_result[inner_key] = temp

I'm not sure though how to get the inner_keys in a more general way, aside from explicitly specifying them.


text:
Q: Possible to get pycharm-style "run with Python Console" functionality in VSCode? In PyCharm, there's a handy button next to if __name__... statements that runs a script,

with configurations for the run in a run configurations menu.
One of the options is to "Run with Python Console":

This is really handy, because I can run my in-progress script in the console without ponderously highlighting and ctrl-entering.  I'm then in the console, with everything I just did in memory, and I can go and continue writing my code using the REPL to check how things are working along the way.
In VScode, when I hit the run button

It just runs the script from the terminal.  I can see any output that it prints, but it doesn't drop me into a REPL interface like I'm accustomed with PyCharm.
Is this sort of functionality attainable with VSCode?

A: VSCode without this functionality, but it has some similar functionalities:

*

*Ctrl+A -> rightclick -> Run Selection/Line in Python Terminal.

*rightclick -> Run Current File in Interactive Window

A: I've been looking for exactly the same functionality. Following two other stackoverflow posts you can get the desired behaivor -> executing in an REPL ipython terminal (original links at the end of the post):
edit the terminal launchArgs in settings.json
(Preference: Open Settings JSON; or Preference -> Settings -> Search launchArgs -> edit in json):
"python.terminal.launchArgs": [
   "-i",
   "-m",
   "IPython",
   "--no-autoindent",
]

Reference Links:

*

*Link1

*Link2


text:
Q: How to add three different class in multiple div using jQuery? I am using jQuery for add three different classes in my div with same name classes. Here is my HTML:

here is my jquery code
$(document).ready(function() {
    var name=$(".myclass").length ;
    var selector = '.main-class';

    $(selector).ready(function(){
     for(var s=1;s<=name;s++)
       {
         if(s>3)
            {
                for(var z=1;z<=3;z++)
                {
                    alert(z);
                }
                s=s+2;

            }
            else
            {
              if(s==1)
                $('.myclass').addClass('red');
              if(s==2)
                $('.myclass').addClass('yellow');
              if(s==3)
                $('.myclass').addClass('gray');
            }

        }

    });
});

i want my output like this

but i got this

I am new in jQuery.

A: You could use addClass with a callback, and check the index

$('.myclass').addClass(function(i) {
  return i % 3 === 0 ? 'red' : (i % 3 === 1 ? 'yellow' : 'gray');
});
.red {color: red}
.yellow {color: yellow}
.gray {color: gray}

text

text

text

text

text

text

text

text

A: Try this!
By this way, you can add n number of class names to the array and the code will work.

var c = ['red', 'yellow', 'gray']
var counter = 0
$('.myclass').each(function(i, el){
  $(this).addClass(c[counter])
  if(counter < (c.length -1))
    counter++
   else
    counter = 0
})
.myclass{
  height: 20px
}
.red {
  background: red
}

.yellow{
  background: yellow
}

.gray{
  background: gray;
}

A: Use each() to iterate through your elements and addClass() as per your need.
var classArr = ['red', 'yellow', 'grey'];
var i=0;
$('.main-class').children().each(function(key, value){
  if(i == 3) { i=0; }
  $(value).addClass(classArr[i]);
  i++;
});

var classArr = ['red', 'yellow', 'grey'];
var i=0;
$('.main-class').children().each(function(key, value){
  if(i == 3) { i=0; }
  $(value).addClass(classArr[i]);
  i++;
});
.red
{
 color: red;
}
.yellow
{
 color: yellow;
}
.grey
{
 color: grey;
}

RED

YELLOW

GREY

RED

YELLOW

GREY

RED

YELLOW

A: UPDATE:  the code works fine now, you need to serve colors in array then loop over each .myclass element and set class name according to colors array
position witch reset if the .myclass index equal to colors length to repeat.

$(document).ready(function() {
  var colors = ["green", "red", "blue"];
var c = -1;
  $('.main-class .myclass').each(function() {
    c++;
    if(c==colors.length)c=0;
$(this).addClass(colors[c]);
//to test using .css();
    $(this).css({
      "color": colors[c]
    });
  });

});

colors

colors

colors

colors

colors

colors

colors

colors

code updated test snippet

A: You can use jquery .each() to iterate the elements and % to see the modulo with 3:
$('.myclass').each(function(index) {
    if (index % 3 === 0) {
        $(this).addClass("red");
    } else if (index % 3 === 1) {
        $(this).addClass("yellow");
    } else {
        $(this).addClass("green");
    }
});

Your mistake was that
$('.myclass').addClass('red');

adds red as a class to everything having the class of myclass.


text:
Q: Позиционирование фона в raphaeljs Всем привет.
Подскажите, пожалуйста, если фон для объекта path устанавливается так:
    pathElement.attr({
        'fill':'url("venice.jpg")',
        'stroke-width' : 0
    });

То как сдвинуть вон в объекте средствами raphaeljs?
A: pathElement.attr({
    'fill':'url("venice.jpg")',
    'stroke-width' : 0,
    'x': -1000,
    'y': -400
});

Так проверьте, вдруг я прав.


text:
Q: How to delete all lines containing fewer than two /'s in BASH? How can I delete all lines from a file containing only one or no /? E.g., file.txt:
This / line contains/ more than / one of the characters/.
This / line contains just one.
This / line/ also has/too many/.

The output would be:
This / line contains/ more than / one of the characters/.
This / line/ also has/too many/.

I tried grep ^[^/]*/*[^/]$ file.txt, but this seems to print everything.

A: try this:
awk -F/ 'NF>2' file

test:
kent$ (master|✔) echo "This / line contains/ more than / one of the characters/.
dquote> This / line contains just one.
dquote> This / line/ also has/too many/."|awk -F/ 'NF>2'
This / line contains/ more than / one of the characters/.
This / line/ also has/too many/.

A: You weren't too far away:
grep '/.*/' <<.eof
This / line contains/ more than / one of the characters/.
This / line contains just one.
This / line/ also has/too many/.
.eof

Results in:
This / line contains/ more than / one of the characters/.
This / line/ also has/too many/.

But I also like Kent's solution :-)

A: echo "This / line contains/ more than / one of the characters/.
This / line contains just one.
This / line/ also has/too many/." \
| sed -n '\@/.*/@p'

output
This / line contains/ more than / one of the characters/.
This / line/ also has/too many/.

The -n says "don't print by default. The regex in sed looks for lines with more than one / char and prints them.
Sed, being the variable tool that it is, may not like the leading \ char in \@, so if you get an error message, just use sed '@/.*@d'
IHTH

A: Yet another way:
perl -ne '
 chomp;
 if ( ( $n1 = () = $_ =~ /\//g) > 1 ) {
    print "$_\n";
 }' afile.txt

A: Here is another awk version:
awk 'gsub(/\//,"&")>1' file
This / line contains/ more than / one of the characters/.
This / line/ also has/too many/.

It tries to swap / with itself.  The output of gsub is the number of hits.


text:
Q: FreeRTOS excessive stack overflow I'm trying to implement the producer-consumer algorithm on ATMega323_WinAVR using FreeRTOS. I get this error in AVR Studio 4 when debugging:
AVR Simulator: Excessive stack overflow, stop sim
The stack pointer stops at this line:
static void prvCopyDataToQueue (
  xQUEUE *pxQueue, const void *pvItemToQueue, portBASE_TYPE xPosition){

Why does this error appears?
Thanks!

A: When you build a program, the linker defines where in RAM the stack will go, and the debugger will expect to find it there.  When you have the FreeRTOS scheduler running, the stacks will come from the FreeRTOS heap, as each task is allocated a stack when it is created.  The debugger will have no way of knowing if a task has overflowed its stack or not, because it does not know where the stack is, and has no knowledge of FreeRTOS.
I recommend turning that check in the debugger off, then turning the stack checking on in FreeRTOS (if you want to check for stack overflows at all, recommended during development only).
Regards.

A: Have a look at this thread. There may be an issue with the simulator's stack watcher.


text:
Q: How to parse it into a hashmap back I have a problem: I want to return a sorted hashmap but unfortunatelly it isnt a hasmap anymore. How could I parse it back to a hashmap ?
private HashMap<int[], Double> sortHashMap(HashMap<int[], Double> hashMap) {
            HashMap<int[], Double>  sortedHashMap = new HashMap<int[], Double>();
            List<Entry<int[], Double>> list = new ArrayList<>(hashMap.entrySet());
            list.sort(Entry.comparingByValue());
            // sortedHashMap = list.sort(Entry.comparingByValue()); // not working :(
            return sortedHashMap;
        }

A: Just sorting the list using sort will not give you back a map. You also cannot use a HashMap to build a sorted map. Use a LinkedHashMap to preserve the order when collecting the entries of the list:
private LinkedHashMap<int[], Double> sortHashMap(HashMap<int[], Double> hashMap) {
    List<Entry<int[], Double>> list = new ArrayList<>(hashMap.entrySet());
    list.sort(Entry.comparingByValue());
    return list.stream().collect(Collectors.toMap(Entry::getKey, Entry::getValue,
            (key1, key2) -> key2, LinkedHashMap::new));
}

Note that the third argument, (key1, key2) -> key2 is the merge function in case there are duplicate keys found by the collector (which should not happen in this case).


text:
Q: Example code of PSTricks in MikTeX everyone, in the past one hour, I have been fighting with the PSTricks package in MikTeX. I found a lot of example code here.
For example, I downloaded the gliding ball example tex and I ran it in Miktex, but it didn't compile even though I installed all kinds of pst packages. And I tried some other example tex code, and they didn't work in Miktex neither.
Can someone help me modify one of the example code in the link above to make it work in MikTeX?
I'll really appreciate that! Thank you very much!

A: To diagnose your problem whether or not you have properly installed MikTeX, compile the following by invoking the following command from the DOS window (type Win+R, type cmd and press enter to launch the DOS window).
latex input.tex
dvips input.dvi
ps2pdf -dAutoRotatePages#/None input.ps

% input.tex
\documentclass[pstricks,border=1pt]{standalone}
\SpecialCoor
\makeatletter
\degrees[4]
\begin{document}
\begin{pspicture}[showgrid](-2,-2)(2,2)
    \foreach \a in {65,66,...,68}{\rput{\a}(!1 \a\space \pst@angleunit PtoC){\char\a}}
\end{pspicture}
\end{document}

If you get the same result then everything is fine.


text:
Q: Can I store documents and key-value pairs in the same DynamoDB instance? This is probably an obvious question, but I'm not seeing it in Amazon's documentation.
Can I store documents and key-value pairs in the same DynamoDB instance? Or can an instance only have one type?
I also don't see how to specify the object type when writing an item.

A: The wording is confusing. The primary keys do need to be one Data type.

DynamoDB supports many different data types for attributes within a
  table. They can be categorized as follows:

*

*Scalar Types – A scalar type can represent exactly one value. The scalar types are number, string, binary, Boolean, and null.

*Document Types – A document type can represent a complex structure with nested attributes—such as you would find in a JSON document. The
  document types are list and map.

*Set Types – A set type can represent multiple scalar values. The set types are string set, number set, and binary set.
When you create a table or a secondary index, you must specify the
  names and data types of each primary key attribute (partition key and
  sort key). Furthermore, each primary key attribute must be defined as
  type string, number, or binary.
DynamoDB is a NoSQL database and is schemaless. This means that, other
  than the primary key attributes, you don't have to define any
  attributes or data types when you create tables. By comparison,
  relational databases require you to define the names and data types of
  each column when you create a table.

https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html


text:
Q: Using document.location=file_url.mp3 to trigger download from JS - incorrect? I'm looking at some legacy code here, and the way it triggers .mp3 file playback is like so:
document.location = file_url.mp3;

Which in turn prompts user to download a file or plays it (depending on a platform). I just feel this is super-incorrect way of allowing user to play .mp3 files. Can someone specify why exactly this approach is wrong?

A: Try this
$('a').click(function(e) {
e.preventDefault();  //stop the browser from following
window.location.href = 'file_url.mp3';
});

Download

Using preventDefault

A: You can create an empty and hidden HTML div

Then add this bit of JavaScript
function playMp3(stop) {
   var div = document.getElementById('player');
   if (stop) {
       div.innerHTML = '';
   } else {
       div.innerHTML = '<audio autoplay><source src="fule_url.mp3" type="audio/mpeg"></audio>';
   }
}

Now to play file
playMp3();

to stop playing call
playMp3(1);


text:
Q: how to display a certain subset of data on prettytable in a descending order i have a PrettyTable with two headers and over 500 rows, the structure is like this
Email Address     number of contacts
aaa@goo.com        99
aaa@foo.com        123

and my code:
  table =pt.PrettyTable(["Email Address", "Number of Contacts"])
  for n in g3.nodes():
     table.add_row([n.title(),g3.in_degree(n)])
  table.reversesort=True
  print table.get_string(sortby="Number of Contacts")

i'm trying to organise the table in a descending order by sorting the number of contacts. what i actually want, is a table that displays the 20 e-mail addresses with the highest number of contacts . i dont want the rest to be on the table. with the help of some other questions on here, i could do the descending order but im stuck there and couldn't find a way of doing what i want. i've looked here but couldn't find a solution either. any suggestions?


text:
Q: How to preserve XMP metadata in Objective C? I need my photo-editor app to preserve unknown metadata entries that were existing in the original photo that was opened by my app (for example, non-standard XMP meta-data)
I tried to use the Apple's built-in meta-data read/write meta-data, with no success.
Is there a way to just copy all existing meta-data to a buffer, write it as-is and then change only specific entries?

A: Yes.

*

*Use Adobe XMP SDK.

*Read the metadata from the image when you open it using:
SXMPFiles myFile;
ok = myFile.OpenFile(filename, kXMP_UnknownFile, opts);
myFile.GetXMP(_meta); // _meta is a data member of the class that represents your photo (probably a subclass of NSDocument).

*When saving the image, write the image content, then write _meta to the output file using SXMPFiles.PutXMP(...), and then set specific metadata entries that you like.
See Adobe XMP programming guide for more details about reading and writing XMP metadata.


text:
Q: replace wordpress login with my custom web application login I am developing a web application in which users can signup, login and social login. I need a blog too in the same application. I choose wordpress.
But the problem is if user already have account on my application, he/she can login with the same credentials on wordpress with same session management.
Is it possible and how to replace Wordpress login?

A: You can do the stuff in the following way:
Keep wordpress folder name blog/ in your project root dirtectory.
And then create wordpress user with same credentials such as your application.
Put the below code in your application when you create new login user:
require_once('blog/wp-blog-header.php');
require_once('blog/wp-includes/registration.php');
$newusername = 'xxxxxxxxxxx';
$newpassword = 'xxxxxxxxxxx';
$newemail = 'xxxxxxx@xxxxxxx.co.in';
// Check that user doesn't already exist
if ( !username_exists($newusername) && !email_exists($newemail) ){
   // Create user and set role to administrator
   $user_id = wp_create_user( $newusername, $newpassword, $newemail);
   if ( is_int($user_id) )      {
       $wp_user_object = new WP_User($user_id);
       $wp_user_object->set_role('contributor');
            echo 'Successfully created new user.';
    } else {
            echo 'No users were created.';
    }
} else {
    echo 'This user or email already exists. Nothing was done.';
}

Hope this will helps.

A: Not sure if i understood you right...
But you wrote: he/she CAN login with the same credentials on wordpress with same session management.
Sure you didn't meen can't ? Otherwise i don't see your problem...
But if you meant CAN'T... so, i don't know how wordpress is nowaday, but i tried the same thing maybe three years ago... it endet up that i coded my own blog, took me much less time than handle with all this wordpressstuff. And btw, writing your own blog application is really easy... There are 100 of tutorials and if you want i can help you, shouldn't be a problem..


text:
Q: android class cast excp relative layout i am getting class cast exception relative$layout here is the code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">

<RelativeLayout android:layout_height="wrap_content" android:id="@+id/relativeLayout1" android:layout_width="fill_parent">
    <Button android:text="Delete" android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/Button2" android:layout_alignParentTop="true" android:layout_alignParentRight="true"></Button>
    <Button android:text="Edit" android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/button1" android:layout_alignParentTop="true" android:layout_toLeftOf="@+id/Button2"></Button>
    <TextView android:text="TextView" android:id="@+id/textView1" android:layout_height="wrap_content" android:layout_width="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_toLeftOf="@+id/button1"></TextView>

</RelativeLayout>

</LinearLayout>

.
import java.util.List;

import android.app.ExpandableListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListAdapter;
import android.widget.TextView;

public class options extends ExpandableListActivity {

    ExpandableListAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list);

        mAdapter = new MyExpandableListAdapter();
        setListAdapter(mAdapter);
    }

    public class MyExpandableListAdapter extends BaseExpandableListAdapter{

        private String[] groups = { "People Names", "Dog Names", "Cat Names", "Fish Names" };
        private String[][] children = {
                { "Arnold", "Barry", "Chuck", "David" },
                { "Ace", "Bandit", "Cha-Cha", "Deuce" },
                { "Fluffy", "Snuggles" },
                { "Goldy", "Bubbles" }
        };
        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return children[groupPosition][childPosition];
        }
        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }
        @Override
        public View getChildView(int groupPosition, int childPosition,
                boolean isLastChild, View convertView, ViewGroup parent) {
            TextView textView = getGenericView();
            textView.setText(getChild(groupPosition, childPosition).toString());
            return textView;
        }
        @Override
        public int getChildrenCount(int groupPosition) {
            return children[groupPosition].length;
        }
        @Override
        public Object getGroup(int groupPosition) {
            return groups[groupPosition];
        }
        @Override
        public int getGroupCount() {
            return groups.length;
        }
        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }
        @Override
        public View getGroupView(int groupPosition, boolean isExpanded,
                View convertView, ViewGroup parent) {
            TextView textView = getGenericView();
            textView.setText(getGroup(groupPosition).toString());
            return textView;
        }
        @Override
        public boolean hasStableIds() {
            return true;
        }
        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }

        public TextView getGenericView() {
            // Layout parameters for the ExpandableListView
            //AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
            //        ViewGroup.LayoutParams.FILL_PARENT, 64);

            //TextView textView = new TextView(options.this);
           // textView.setLayoutParams(lp);
            // Center the text vertically
           // textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
            // Set the text starting position
            //textView.setPadding(60, 0, 0, 0);

            //TextView textView = (TextView) findViewById(R.id.textView1);

            //return textView;

            LayoutInflater inflater = (LayoutInflater)options.this.getSystemService
                      (Context.LAYOUT_INFLATER_SERVICE);

            View v = inflater.inflate(R.layout.row, null);

            TextView textView = (TextView) v.findViewById(R.id.textView1);

            return textView;

        }

    }
}

in the last getGenericView() code in comment works fine but i am trying to inflate from row.xml which gives me error.

A: Don't inflate row into a View.  At least go up to ViewGroup.  View doesn't have children, so the implementation of findViewById can't search for child views
This should work:
        ViewGroup v = (ViewGroup) inflater.inflate(R.layout.row, null);
        TextView textView = (TextView) v.findViewById(R.id.textView1);


text:
Q: Add reminder notification on apple watch with different different repeat interval I am working on an apple watch app where I need reminder user notifications to awake user.
I am able to Set UserNotification with make repeat: true and it will remind the user every day.
But what I need is on single-day app will notify as per user selection like below.
if the user selects 3 min ideal time that every 3 min user got a notification with a vibration on the watch.
same with 5 min, 10 min, and 15 min.
I am using the below code for UserNotification.
func scheduleNotification(at date: Date) {
        let calendar = Calendar(identifier: .gregorian)
        let components = calendar.dateComponents(in: .current, from: date)
        let newComponents = DateComponents(calendar: calendar, timeZone: .current, month: components.month, day: components.day, hour: components.hour, minute: components.minute)

        let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: true)

        let content = UNMutableNotificationContent()
        content.title = "Test Reminder"
        content.body = "Show More detail in Body!"
        content.sound = UNNotificationSound.default()
        content.categoryIdentifier = "myCategory"

        if let path = Bundle.main.path(forResource: "logo", ofType: "png") {
            let url = URL(fileURLWithPath: path)

            do {
                let attachment = try UNNotificationAttachment(identifier: "logo", url: url, options: nil)
                content.attachments = [attachment]
            } catch {
                print("The attachment was not loaded.")
            }
        }

        let request = UNNotificationRequest(identifier: "textNotification", content: content, trigger: trigger)

        UNUserNotificationCenter.current().delegate = self
        UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
        UNUserNotificationCenter.current().add(request) {(error) in
            if let error = error {
                print("Uh oh! We had an error: \(error)")
            }
        }
    }

By using the below trigger with repeats: true
let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: true)

it's repeating on next day same time.
Is there any way or method to set repeat after the specified interval as per user selection?
Any help will be appreciated!
Thanks in advance.

A: Try using a UNTimeIntervalNotificationTrigger instead of a UNCalendarNotificationTrigger.
For example:
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 2*60, repeats: true)

That would create a trigger that fires every 2 minutes. timeInterval is the number of seconds between firing each notification.


text:
Q: Weighted sampling as a way to eliminate specific source of variation? I am facing a problem of predicting probability of an event given two correlated predictors where only one of them is of interest. Thus, I'm trying to eliminate one of them from the model while making corrections in the training procedure to account for that.
Data is of e-commerce web tracking, where each individual datapoint is a display of an item in catalog.
Goal is to predict probability of a purchase of a specific item given some item in the catalog will be purchased. Available features are rank of an item in the catalog (its # position on the page), its price as well as some other variables. All items on the page are of the same type. Probability of purchase follows exponential distribution w.r.t. to both rank and price. The goal is to eliminate item's rank from the resulting model, since it is a variable we wish to control. However, there is a complication: almost all historic data was generated by displays where items were sorted by the price to begin with, so any effect of rank and price are most often entangled to indistinguishability.
Two approaches come to mind:

*

*Fit polynomial regression with interaction variables between price and rank, then simply drop terms related to rank. Since we generate predictions for the full page and normalise all predicted probabilities this should not be a problem.

*Try to eliminate the variation induced by item's rank from training data. To do so, I calculate P(purchase|rank) and then sample each training data point according to the inverse of it, 1/P(purchase|rank). With this data I train a model with all relevant variables except rank as predictors.
Approach 2 has some intuitive appeal, however it is hard to validate and hard to prove that it is doing what is required.
Hence, my question is: does this approach makes any sense, and is it maybe related to some existing statistical procedure?

A: Approach two is called "inverse probability of treatment weighting." It is a valid technique and it is popular in the "causal inference" literature. By "causal" I mean causal in the sense of Angrist and Pischke (2009) in Mostly Harmless Econometrics
I actually made an attempt for while to extend IPTW to high dimensional control variables and didn't meet much success. In fact I asked several questions about it on this site this past summer (~July 2014) that might be interesting.