text:
Q: display the contents of a sqlite3 database according to the dates I use python 3.6 and sqlite3, and I have a problem when I want to read the content of the table between 2 variables
first, when I use two string format dates ("2019-01-01" and "2019-05-20") the following code works correctly :
#!/usr/bin/python3
# -*- coding: utf-8 -*-

from tkinter import *
import time
import calendar
import sqlite3
import datetime

fen = Tk()
fen.title('ILS system ')
fen.resizable(0,0)
largeur=920
hauteur=660
fen.geometry('{}x{}+0+0'.format(largeur,hauteur))

def CreateTable_releves():

    conn1_releves = sqlite3.connect('bdd/test.db')
    curseur1_releves = conn1_releves.cursor()
    curseur1_releves.execute('''CREATE TABLE IF NOT EXISTS releves (id INTEGER PRIMARY KEY,time_releves TEXT NOT NULL, monitor1_releves TEXT NOT NULL,monitor2_releves TEXT NOT NULL)''')
    curseur1_releves.close()

def Add_To_Table_releves():

    time_releves_get = str(date_choisie_ils35R)

    monitor1_releves_get = str(ent_releves_mesure_mon1_axe_loc35R.get())
    monitor2_releves_get = str(ent_releves_mesure_mon2_axe_loc35R.get())

    conn2_releves = sqlite3.connect('bdd/test.db')
    curseur2_releves = conn2_releves.cursor()
    curseur2_releves.execute('''INSERT INTO releves (time_releves,monitor1_releves,monitor2_releves) VALUES (?,?,?)''',(time_releves_get,monitor1_releves_get,monitor2_releves_get))
    conn2_releves.commit()
    curseur2_releves.close()

# CreateTable_releves()

def monitoring () :

    fen_monitoring=Toplevel(fen)
    fen_monitoring.title('ddm axe')
    fen_monitoring.geometry('450x400+300+150')

    s= Scrollbar(fen_monitoring)
    T= Text(fen_monitoring,bg='powder blue',width=450,height=400)
    s.pack(side=RIGHT, fill=Y)
    T.pack(side=LEFT, fill=Y)
    s.config(command=T.yview)
    T.config(yscrollcommand=s.set)

    def update_releves():

        T.delete('1.0', END)
        T.update()

        conn = sqlite3.connect('bdd/test.db')
        curseur = conn.cursor()
        for resultats in curseur.execute('SELECT * FROM releves  where  time_releves between "2019-01-01" AND "2019-05-20" ORDER BY time_releves DESC'):

            contenu_table_releves= str(resultats[1])+"\t\t"+ str(resultats[2])+"\t\t"+ str(resultats[3])+"\n"

            T.insert(END,contenu_table_releves)
        T.after(1000,update_releves)
        curseur.close()

    update_releves()

bt=Button(fen,text='click on\nthe button', command=monitoring)
bt.pack()

here is the image of the contents of the toplevel window :
enter image description here
but if I modify the code by input two variables (first_day) and (last_day) in the sql requet :
for resultats in curseur.execute('SELECT * FROM releves  where  time_releves between "first_day" AND "last_day" ORDER BY time_releves DESC'):

there is the complet modify code :
#!/usr/bin/python3
# -*- coding: utf-8 -*-

from tkinter import *
import time
import calendar
import sqlite3
import datetime

fen = Tk()
fen.title('ILS system ')
fen.resizable(0,0)
largeur=920
hauteur=660
fen.geometry('{}x{}+0+0'.format(largeur,hauteur))

#to calculate first and last day of the month:
now = datetime.datetime.now()
start_month = datetime.datetime(now.year, now.month, 1)
date_on_next_month = start_month + datetime.timedelta(35)
start_next_month = datetime.datetime(date_on_next_month.year, date_on_next_month.month, 1)
last_day_month = start_next_month - datetime.timedelta(1)
last_day=last_day_month.strftime('%Y-%m-%d')
first_day=start_month = datetime.datetime(now.year, now.month, 1).strftime('%Y-%m-%d')

def CreateTable_releves():

    conn1_releves = sqlite3.connect('bdd/test.db')
    curseur1_releves = conn1_releves.cursor()
    curseur1_releves.execute('''CREATE TABLE IF NOT EXISTS releves (id INTEGER PRIMARY KEY,time_releves TEXT NOT NULL, monitor1_releves TEXT NOT NULL,monitor2_releves TEXT NOT NULL)''')
    curseur1_releves.close()

def Add_To_Table_releves():

    time_releves_get = str(date_choisie_ils35R)

    monitor1_releves_get = str(ent_releves_mesure_mon1_axe_loc35R.get())
    monitor2_releves_get = str(ent_releves_mesure_mon2_axe_loc35R.get())

    conn2_releves = sqlite3.connect('bdd/test.db')
    curseur2_releves = conn2_releves.cursor()
    curseur2_releves.execute('''INSERT INTO releves (time_releves,monitor1_releves,monitor2_releves) VALUES (?,?,?)''',(time_releves_get,monitor1_releves_get,monitor2_releves_get))
    conn2_releves.commit()
    curseur2_releves.close()

# CreateTable_releves()

def monitoring () :

    fen_monitoring=Toplevel(fen)
    fen_monitoring.title('ddm axe')
    fen_monitoring.geometry('450x400+300+150')

    s= Scrollbar(fen_monitoring)
    T= Text(fen_monitoring,bg='powder blue',width=450,height=400)
    s.pack(side=RIGHT, fill=Y)
    T.pack(side=LEFT, fill=Y)
    s.config(command=T.yview)
    T.config(yscrollcommand=s.set)

    def update_releves():

        T.delete('1.0', END)
        T.update()

        conn = sqlite3.connect('bdd/test.db')
        curseur = conn.cursor()
        for resultats in curseur.execute('SELECT * FROM releves  where  time_releves between "first_day" AND "last_day" ORDER BY time_releves DESC'):

            contenu_table_releves= str(resultats[1])+"\t\t"+ str(resultats[2])+"\t\t"+ str(resultats[3])+"\n"

            T.insert(END,contenu_table_releves)
        T.after(1000,update_releves)
        curseur.close()

    update_releves()

bt=Button(fen,text='click on\nthe button', command=monitoring)
bt.pack()

the toplevel window appear but empty like in the next picture :
enter image description here

A: I modified the code so that it is clearer by integrating widget (entry, button), and then I added the setpoint of "R Spark". I had as a result the following code which apparently works for the moment. (I will redo other tests soon)
if there are any comments about this new this would be welcome.
The new code:
#!/usr/bin/python3
# -*- coding: utf-8 -*-

from tkinter import *
import time
import calendar
import sqlite3
import datetime

fen = Tk()
fen.title('ILS system ')
fen.resizable(0,0)
largeur=920
hauteur=660
fen.geometry('{}x{}+0+0'.format(largeur,hauteur))

#to calculate first and last day of the month:
now = datetime.datetime.now()
start_month = datetime.datetime(now.year, now.month, 1)
date_on_next_month = start_month + datetime.timedelta(35)
start_next_month = datetime.datetime(date_on_next_month.year, date_on_next_month.month, 1)
last_day_month = start_next_month - datetime.timedelta(1)
last_day=last_day_month.strftime('%Y-%m-%d')
first_day=start_month = datetime.datetime(now.year, now.month, 1).strftime('%Y-%m-%d')

def CreateTable_releves():

    conn1_releves = sqlite3.connect('bdd/test/test.db')
    curseur1_releves = conn1_releves.cursor()
    curseur1_releves.execute('''CREATE TABLE IF NOT EXISTS releves (id INTEGER PRIMARY KEY,time_releves TEXT NOT NULL, monitor1_releves TEXT NOT NULL,monitor2_releves TEXT NOT NULL)''')
    curseur1_releves.close()

def Add_To_Table_releves():

    time_releves_get = str(date_choisie.get())
    monitor1_releves_get = str(ent_mon1_mesure.get())
    monitor2_releves_get = str(ent_mon2_mesure.get())

    conn2_releves = sqlite3.connect('bdd/test/test.db')
    curseur2_releves = conn2_releves.cursor()
    curseur2_releves.execute('''INSERT INTO releves (time_releves,monitor1_releves,monitor2_releves) VALUES (?,?,?)''',(time_releves_get,monitor1_releves_get,monitor2_releves_get))
    conn2_releves.commit()
    curseur2_releves.close()

CreateTable_releves()

def monitoring () :

    fen_monitoring=Toplevel(fen)
    fen_monitoring.title('ddm axe')
    fen_monitoring.geometry('450x400+300+150')

    s= Scrollbar(fen_monitoring)
    T= Text(fen_monitoring,bg='powder blue',width=450,height=400)
    s.pack(side=RIGHT, fill=Y)
    T.pack(side=LEFT, fill=Y)
    s.config(command=T.yview)
    T.config(yscrollcommand=s.set)

    def update_releves():

        T.delete('1.0', END)
        T.update()

        conn = sqlite3.connect('bdd/test/test.db')
        curseur = conn.cursor()
        for resultats in curseur.execute('SELECT * FROM releves where time_releves between ? AND ? ORDER BY time_releves DESC;', (first_day, last_day)):

            contenu_table_releves= str(resultats[1])+"\t\t"+ str(resultats[2])+"\t\t"+ str(resultats[3])+"\n"

            T.insert(END,contenu_table_releves)
        T.after(1000,update_releves)
        curseur.close()

    update_releves()

ent_mon1_mesure=StringVar()
ent_mon2_mesure=StringVar()
date_choisie=StringVar()

ent_mon1=Entry(fen,textvariable=ent_mon1_mesure)
ent_mon1.pack(side=LEFT,anchor=NW,padx=10,pady=10)

ent_mon2=Entry(fen,textvariable=ent_mon2_mesure)
ent_mon2.pack(side=LEFT,anchor=NW,padx=10,pady=10)

ent_time_releve=Entry(fen,textvariable=date_choisie)
ent_time_releve.pack(side=LEFT,anchor=NW,padx=10,pady=10)

bt_valider=Button(fen,text='valider', command=Add_To_Table_releves)
bt_valider.pack(side=LEFT,padx=10,pady=10)

bt_monitoring=Button(fen,text='afficher monitoring', command=monitoring)
bt_monitoring.pack(side=LEFT,padx=10,pady=10)

fen.mainloop()

Thanks R Spark for help


text:
Q: Debug Error-Microsoft Visual C++ Runtime Library- VTM VVC Reference Encoder I am working with VTM -VVC encoder and I am getting debug error while running the encoder App.The build is successful. The screenshot of the error is given as below
Error Image(https://i.stack.imgur.com/Qaj1J.png)
Can some one help with a solution for the error

redpajama_set_name: RedPajamaStackExchange


text:
Q: Limit UITextField to one decimal point Swift How can I limit a UITextField to one decimal point with Swift? The text field is for entering a price, so I cannot allow more than one decimal point. If I was using Objective-C, I would have used this code:
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];

    NSArray *sep = [newString componentsSeparatedByString:@"."];
    if([sep count] >= 2)
    {
        NSString *sepStr=[NSString stringWithFormat:@"%@",[sep objectAtIndex:1]];
        return !([sepStr length]>1);
    }
    return YES;
}

But due a difference with how Swift uses ranges, I cannot convert this code to Swift. The first line gives me an error saying NSRange is not convertible to Range<String.Index>
EDIT: I ended up doing it like this before I saw the answer:
func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {
    let tempRange = textField.text.rangeOfString(".", options: NSStringCompareOptions.LiteralSearch, range: nil, locale: nil)
    if tempRange?.isEmpty == false && string == "." {
        return false
    }

    return true
}

I found this on a different post. This solution works fine but I'm not sure if it is the best way to do it but it is a short and clean way.

A: Swift 4 & Xcode 9.2
This solution allows only one decimal point to be input, therefore allowing a valid double.
// Only allows one decimal point
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
    let arrayOfString = newString.components(separatedBy: ".")

    if arrayOfString.count > 2 {
        return false
    }
    return true
}

A: Alexey got there before me, but seeing as I'd implemented a Swift version to check things out, here it is:
func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {

    // I'm explicitly unwrapping newString here, as I want to use reverse() on it, and that
    // apparently doesn't work with implicitly unwrapped Strings.
    if let newString = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string) {

        var decimalFound = false
        var charactersAfterDecimal = 0

        for ch in reverse(newString) {
            if ch == "." {
                decimalFound = true
                break
            }
            charactersAfterDecimal++
        }
        if decimalFound && charactersAfterDecimal > 1 {
            return false
        }
    }
    return true;
}

Note that the first line now explicitly casts the textField.text to an NSString. This is because the String version of stringByReplacingCharactersInRange takes a Swift range, not an NSRange like the one that's passed in.
I've also made the later code a lot more Swiftian, removing NSString operations. (I'm not convinced that this is wonderfully efficient, as reverse(String) might actually reverse the whole String rather than providing a simple backward iterator, but it looks like the most Swifty way of doing it.)

A: Your first line in Swift will look like:
var newString = NSString(string: textField.text).stringByReplacingCharactersInRange(range, withString: string)

A: I'm not sure about the performance but this is the simplest solution so far.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if let text = textField.text {
        // Allow only one dot character in the text field
        if text.contains(".") && string == "." {
            return false
        }
    }
}

A: I suggest using NSNumberFormatter's decimalSeparator property to split your String. Here's how to limit your input to one decimal place only using the NSNumberFormatter:
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

    if string.isEmpty { // back key
        return true
    }

    if let input = textField.text {
        let numberFormatter = NSNumberFormatter()
        let range = input.rangeOfString(numberFormatter.decimalSeparator)
        if let r = range {
            let endIndex = input.startIndex.advancedBy(input.startIndex.distanceTo(r.endIndex))
            let decimals = input.substringFromIndex(endIndex)
            return decimals.characters.count < 1
        }
    }

    return true
}

A: func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
            if (textField.text?.componentsSeparatedByString(".").count > 1 && string == ".")
            {
                return false
            }
            return string == "" || (string == "." || Float(string) != nil)
    }

A: Try this for one decimal entry:-
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

    if(string == "." ){
        let countdots = textField.text!.componentsSeparatedByString(".").count - 1

        if countdots > 0 && string == "."
        {
            return false
        }
    }
    return true

}

A: I hope it might help you:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

 let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)

 let stringArr: [String] =   newString.components(separatedBy: ".")

if stringArr.count < 2 || (stringArr.count == 2 && stringArr[1].count == 1){
     return true

  }
 return false
  }

A: // decimal points limit on numbers text fields
    @objc static func canEnterDigits(upTo decimalPoint: Int, text: String) -> Bool {

        if self.isNumber(text) || text == "" {

            let stringArr: [String] = text.components(separatedBy: ".")
            if stringArr.count >= 2 {
                let sepString = stringArr[1]
                if sepString.count > decimalPoint {
                    return false
                }
            }

            return true

        } else {
            return false
        }
    }

static func isNumber(_ value: String?) -> Bool {
        let nf = NumberFormatter()
        let isDecimal = nf.number(from: value ?? "") != nil
        return isDecimal
    }

A: Swift 4, Xcode 9.2
This will remove the last entered decimal point:
let numberOfDecimalPoints = textField.text.components(separatedBy: ".").count - 1

if numberOfDecimalPoints > 1 {
    textField.deleteBackward()
}


text:
Q: How to use fsyncLock() safely in backing up a single mongod I read from mongodb document:
important:
db.fsyncLock() may block reads, including those necessary to verify authentication
warning:
When calling db.fsyncLock(), ensure that the connection is kept open to allow a subsequent call to db.fsyncUnlock(). Closing the connection may make it difficult to release the lock.

In worst case, I use fsyncLock() to block database and suddenly lost connection to database (because of temporary network failure). I cannot reconnect because fsyncLock() block reader. My database will be blocked forever.
I am considering to shutdown mongodb to backup.
What is the most safest backup solution for single mongod ?

A: You could use a filesystem based snapshot (like LVM, EBS or similar) - as long as the snapshot is point-in-time and includes the journal then you do not need to lock the database at all when taking a backup.  Once the snapshot is complete, simply archive it off to your backup drive/host/cloud and then remove the snapshot.
Other options would require this to be a replica set. With a single node replica set you could use MMS backup (no other hosts required, but you do have to have an oplog, and it is not free).
If you added a second node (and an arbiter to break ties in voting), then your secondary could function as your backup.  You could take it down to make a backup without impacting your original node (again, as long as you have an arbiter), or you could use the techniques above also


text:
Q: how to concat year =2019 and period=6 to give 20106 and not 20196 number and year =2018 , period=3112 to give 20183112 i need to join two tables  based on tiemperiod . such that
table1.dateperiod =table2.(combination of period and year)
i.e 201906=201906     (year 2019 month is 6  both integers)
i.e 20183112=20183112
the problem is how to concat them while period is 6 and such that after concatenating it will be 201906 and not 20196
and
table 1
ID  NAME    DATE_PERIOD
1   conan   201906
1   conan   202012
1   conan   20183112
2   andy    201903

table2
ID  PROFILE YEAR    PERIOD
1   host    2019    6
1   writer  2018    3112
1   anchor  2020    12
2   sidekic 2019    3

please refer this db fiddle -here
select
 *
from table2 t2
inner join table1 t1 on t1.id = t2.id and t1.date_period= (t2.year*100+t2.period)

expected solution
ID  PROFILE YEAR    MONTH   ID  NAME    DATE_PERIOD
1   anchor  2020    12  1   conan   202012
1   host    2019    6   1   conan   201906
1   sidekick    2020    12  1   andy    202003
1   writer  2018    3112    1   conan   20183112

A: If they're both integer data types, you should be able to construct the six-digit variant from year and month by just using:
year * 100 + month

If they're character data types, Oracle provides an lpad function for just this purpose, something like:
concat(year, lpad(month, 2, '0'))

Sybase, on the other hand, can use replicate to do padding but it's much uglier, something like:
year || replicate('0', (2 - char_length(month))) || month

Not sure which one you want since you gave both tags.

And re your edit, where the month may also hold DDMM format, you can simply use modulo arithmetic to get the final two characters. I won't bother looking up the function for that in Oracle/Sybase, I'll leave that as an exercise for the reader. Suffice to say 3112 mod 100 is 12.

A: You need to use LPAD as follows:
select
 *
from table2 t2
inner join table1 t1
on t1.id = t2.id and t1.date_period= concat(year,LPAD(month,2,0))

See db<>fiddle
--UPDATE--
You can use CASE statement as follows:
select
 *
from table2 t2
inner join table1 t1 on t1.id = t2.id
and t1.date_period =  concat(year,
                             LPAD(period,
                                  case when length(period) <= 2
                                       then 2
                                       else 4
                                   end,
                                   0))

db<>fiddle

A: You can use the below to handle cases where the length of period is lesser or greater than four
    select
       *
       from table2 t2,table1 t1
       where t1.id = t2.id
           and t1.date_period =  concat(year,
                         LPAD(period,
                   decode(length(period),1,2,3,4,length(period))
                               ,
                               0));


text:
Q: Ordenar array por ela mesma dentro do indice em PHP Estou trabalhando com o datatables, e por um acaso do destino resolvi usar a função ajax dele, fiz todo o processo, mas falta uma coisa, conseguir reordenar a array, pois usando de processamento server-side o dataTables não interage client-side para reordenar.
A array retornada é um JSON disso (aqui está na ordem, mas eu preciso poder alterar essa ordem como eu quiser):
$arr = [
     [
     'linha 1 coluna 1 valor z',
     'linha 1 coluna 2 valor b',
     'linha 1 coluna 3 valor h',
     'linha 1 coluna 4 valor d',
     'linha 1 coluna 5 valor e'
     ],
     [
     'linha 2 coluna 1 valor b',
     'linha 2 coluna 2 valor c',
     'linha 2 coluna 3 valor r',
     'linha 2 coluna 4 valor i',
     'linha 2 coluna 5 valor l'
     ],
     [
     'linha 3 coluna 1 valor q',
     'linha 3 coluna 2 valor w',
     'linha 3 coluna 3 valor y',
     'linha 3 coluna 4 valor u',
     'linha 3 coluna 5 valor s'
     ]
];

O que eu preciso, é poder ordenar a linha pelo valor de qualquer uma das colunas com base no valor que ela mesmo possui.
Não estou conseguindo achar a função que eu possa fazer isso, bem é essa dúvida:

Como ordenar uma array quando não há indice e o valor é o proprio
  indice da segunda dimensão ?

Exemplo de como ficaria caso eu recebesse o comando para ordenar pela coluna 1:
$arr = [
     [
     'linha 2 coluna 1 valor b',
     'linha 2 coluna 2 valor c',
     'linha 2 coluna 3 valor r',
     'linha 2 coluna 4 valor i',
     'linha 2 coluna 5 valor l'
     ],
     [
     'linha 3 coluna 1 valor q',
     'linha 3 coluna 2 valor w',
     'linha 3 coluna 3 valor y',
     'linha 3 coluna 4 valor u',
     'linha 3 coluna 5 valor s'
     ],
     [
     'linha 1 coluna 1 valor z',
     'linha 1 coluna 2 valor b',
     'linha 1 coluna 3 valor h',
     'linha 1 coluna 4 valor d',
     'linha 1 coluna 5 valor e'
     ]
];

ATUALIZAÇÃO

Consegui com uma gambiarra, mas ainda acho que deve haver um jeito mais bonito:
$ordergin = $var['order_rule'];
foreach ($records['data'] as $key => $row) {
    $order_company[$key] = $row[1];
    $order_cnpj[$key] = $row[2];
    $order_tax_regime[$key] = $row[3];
    $order_responsible[$key] = $row[3];
    $order_status[$key] = $row[5];
}

if ($ordering == 'order_by_resp_desc') {
    array_multisort($order_responsible, SORT_DESC, $records['data']);
} elseif($ordering == 'order_by_resp_asc'){
    array_multisort($order_responsible, SORT_ASC, $records['data']);
}
//Seguindo daqui até todas as opções disponiveis de ordenamento

A: Com PHP 5.5.0 ou superior, você pode fazer uso da função array_multisort em conjunto com a array_column:
<?php

$arr = [['z', 'b', 'h', 'd', 'e'], ['b', 'c', 'r', 'i', 'l'], ['q', 'w', 'y', 'u', 's']];

// Ordena $arr pelo valor da coluna 0:
array_multisort(array_column($arr, 0), SORT_ASC, $arr);

print_r($arr);

Veja funcionando em Ideone | Repl.it
Resultando em:
Array
(
    [0] => Array
        (
            [0] => b
            [1] => c
            [2] => r
            [3] => i
            [4] => l
        )

    [1] => Array
        (
            [0] => q
            [1] => w
            [2] => y
            [3] => u
            [4] => s
        )

    [2] => Array
        (
            [0] => z
            [1] => b
            [2] => h
            [3] => d
            [4] => e
        )

)

Com a função array_column você irá criar a ordem dos valores com base na coluna desejada e essa ordem será mantida na ordenação dos outros arrays, que é o próprio $arr.

A: Fiz um pequeno exemplo, utilizei a função arsort que já existe no php só para exemplificar, mas você pode escolher a que você quiser, este código vai funcionar se a ordenação ordena também os índices.
Basicamente ele faz o seguinte, verifica o índice do primeiro do array ordenado e ordena os outros naquelas posições:
<?php

echo "<pre>";

$arr = [
    [
        'linha 1 coluna 1 valor a',
        'linha 1 coluna 2 valor b',
        'linha 1 coluna 3 valor c',
        'linha 1 coluna 4 valor d',
        'linha 1 coluna 5 valor e'
    ],
    [
        'linha 2 coluna 1 valor f',
        'linha 2 coluna 2 valor g',
        'linha 2 coluna 3 valor h',
        'linha 2 coluna 4 valor i',
        'linha 2 coluna 5 valor j'
    ],
    [
        'linha 3 coluna 1 valor k',
        'linha 3 coluna 2 valor l',
        'linha 3 coluna 3 valor m',
        'linha 3 coluna 4 valor n',
        'linha 3 coluna 5 valor o'
    ]
];

print_r($arr);

//Indice que vai ser ordenado
$indiceOrdenado = 0;

//Função de ordenação
arsort($arr[$indiceOrdenado]);

//Ordena os outros indices de acordo com o indice ordenado
foreach ($arr as $index => $item) {
    if ($index == $indiceOrdenado) {
        continue;
    }
    $i = 0;
    reset($arr[$indiceOrdenado]);
    $temp = $arr[$index][key($arr[$indiceOrdenado])];
    foreach ($arr[$indiceOrdenado] as $indice => $sub_item) {
        $arr[$index][$indice] = $arr[$index][$i];
        $i++;
    }
    $arr[$index][0] = $temp;
}

print_r($arr);

echo "</pre>";

Array inicial:
Array
(
    [0] => Array
        (
            [0] => linha 1 coluna 1 valor a
            [1] => linha 1 coluna 2 valor b
            [2] => linha 1 coluna 3 valor c
            [3] => linha 1 coluna 4 valor d
            [4] => linha 1 coluna 5 valor e
        )

    [1] => Array
        (
            [0] => linha 2 coluna 1 valor f
            [1] => linha 2 coluna 2 valor g
            [2] => linha 2 coluna 3 valor h
            [3] => linha 2 coluna 4 valor i
            [4] => linha 2 coluna 5 valor j
        )

    [2] => Array
        (
            [0] => linha 3 coluna 1 valor k
            [1] => linha 3 coluna 2 valor l
            [2] => linha 3 coluna 3 valor m
            [3] => linha 3 coluna 4 valor n
            [4] => linha 3 coluna 5 valor o
        )

)

Array Final:
Array
(
    [0] => Array
        (
            [4] => linha 1 coluna 5 valor e
            [3] => linha 1 coluna 4 valor d
            [2] => linha 1 coluna 3 valor c
            [1] => linha 1 coluna 2 valor b
            [0] => linha 1 coluna 1 valor a
        )

    [1] => Array
        (
            [0] => linha 2 coluna 5 valor j
            [1] => linha 2 coluna 2 valor g
            [2] => linha 2 coluna 3 valor h
            [3] => linha 2 coluna 2 valor g
            [4] => linha 2 coluna 1 valor f
        )

    [2] => Array
        (
            [0] => linha 3 coluna 5 valor o
            [1] => linha 3 coluna 2 valor l
            [2] => linha 3 coluna 3 valor m
            [3] => linha 3 coluna 2 valor l
            [4] => linha 3 coluna 1 valor k
        )

)

A: Respondendo a pergunta pra informar como ficou usando as respostas recebidas:
Recebendo os dados (passados pelo DataTables), e chamando uma função pra definir:
 $order_col = $_POST['order'][0]['column'];
 $order_dir = $_POST['order'][0]['dir'];
 $order_arr = self::get_order_dir($order_dir);

Função que define a ordem:
private static function get_order_dir($dir) {
    if ($dir == 'desc') {
        $rs['dir'] = SORT_DESC;
    } else {
        $rs['dir'] = SORT_ASC;
    }
    return $rs;
}

Fazendo o reordenamento com 'array_multisort' de acordo com indice solicitado:
array_multisort(array_column($records['data'], intval($col)), $order_arr['dir'], $records['data']);


text:
Q: python error not sure if it's bug or code problem I am working on a school project. The the project is about making a basic school registration no data base just pure simple code. My problem is, there is a part in my code " EDIT STUDENT DATA " that  should let you change the data like NAME , ADDRESS , PHONE , EMAIL. I got the part where you can change the NAME but when I change the ADDRESS , PHONE , EMAIL  the program will terminate and give error messages. enter code here
Thank you in advance guys.
I have already double check the codes and I can't Identify where the problem is.
https://docs.google.com/document/d/1OEvXrzY3oI8CpNyJPJmITHCcDi6613LXoqj7fRJfW7k/edit?fbclid=IwAR1wdj6i8jmhZ5f4BCurFZhdLr_JylpNlTP4XrA78AGm7I_VaoSeVYOpEqo
this URL redirects to my code

A: The problem is how you are storing your data and retrieving it. You seem to store your data in separate lists, but they share the same index. When you edit your data you forget this (data is the name of the person you are editing):
if (edit_num == '1'):
    new_value = input("Enter New Name: ")
    data_index2 = listStd1.index(data) # works because listStd1 has names
    listStd1[data_index2] = new_value
    print("Successful updated New Name is: ", listStd1[data_index2])
    return self.e_submenu()
elif (edit_num == '2'):
    new_value = input("Enter New Address: ")
    data_index2 = listAdd.index(data) # doesn't find because listAdd is addresses not names
    listAdd[data_index2] = new_value
    print("successful updated New Address is: ", listAdd[data_index2])
    return self.e_submenu()

If you look how your view data works you get the index of data in listStd1 and use that to reference the other lists:
data_index1 = listStd1.index(data)
print("\n")
print("Data for Student: {}".format(data))
print("1-First name and last name: {}".format(data)) # data is name
print("2-Address: {}".format(listAdd[data_index1])) # reference index of data in listStd1
print("3-Phone Number: {}".format(listPhone[data_index1])) # ditto
print("4-Email-Address: {}".format(listEmail[data_index1])) # ditto

So the fix would be to maybe define data_index2 outside of the if block and as it is defined in the first if
data_index2 = listStd1.index(data)
if (edit_num == '1'):
    new_value = input("Enter New Name: ")
    listStd1[data_index2] = new_value
    print("Successful updated New Name is: ", listStd1[data_index2])
    return self.e_submenu()
elif (edit_num == '2'):
    new_value = input("Enter New Address: ")
    listAdd[data_index2] = new_value
    print("successful updated New Address is: ", listAdd[data_index2])


text:
Q: Datastax Java Driver does not connect if one host is missing If I am not wrong, one can connect to a Cassandra cluster knowing at least one of the nodes that is in the cluster, and then the others can be discovered.
Lets say I have three nodes (1, 2 and 3) and I connect to those nodes like this:
Cluster.builder().addContactPoints("1,2,3".split(",")).build();
Then, if node 3 for example goes down, and the IP cannot be resolved, this line of code will throw an IllegalArgumentException as stated in the docs:
@throws IllegalArgumentException if no IP address for at least one of {@code addresses} could be found
Why would anyone want this behavior? I mean, if one of the nodes is down, I want the app to be able to run, as the Cassandra is still working fine.
I have checked this Cassandra Java driver: how many contact points is reasonable?
but that does not answer my question as it doesn't say anything about hosts than can't be reachable.
How should I handle this? Maybe this is changed in another version of the java driver? I am currently using cassandra-driver-core-3.0.3

A: As Nick mentioned, it's based on DNS resolution, not Cassandra server health.
If you remove hosts from your environment more often than you recompile your application, then you should consider not baking your contact points into the code, and instead, feed them in through some other means (environment variable, REST service, a single DNS name that always resolves to one live seed, etc).

A: This validation is only to make sure that all the provided hosts can be resolved, it doesn't even check if a Cassandra server is running on each host. So it is basically to ensure that you did not do any typos while providing the hosts as indeed it doesn't assume that it could be a normal use case to have a provided host that cannot be resolved.
As workaround in your case (host been removed from the DNS entries), you could simply call the method addContactPoint(String address) explicitly instead of using addContactPoints(String... addresses) (which behind the scene simply call addContactPoint(String address) for each provided address) and manage the exception by yourself.
The code could be something like this:
Cluster.Builder builder = Cluster.builder();
// Boolean used to check if at least one host could be resolved
boolean found = false;
for (String address : "1,2,3".split(",")) {
    try {
        builder.addContactPoint(address);
        // One host could be resolved
        found = true;
    } catch (IllegalArgumentException e) {
        // This host could not be resolved so we log a message and keep going
        Log.log(
            Level.WARNING,
            String.format("The host '%s' is unknown so it will be ignored", address)
        );
    }
}
if (!found) {
    // No host could be resolved so we throw an exception
    throw new IllegalStateException("All provided hosts are unknown");
}
Cluster cluster = builder.build();

FYI: I've just created a ticket to propose an improvement in the Java driver https://datastax-oss.atlassian.net/browse/JAVA-1334.

A: The documentation there is just in regards to "resolving" the contact points that are passed in. So converting hostnames to ip addresses. If you are specifying ip addresses to begin with, they will not be resolved, simply checked for validity. If you are using hostnames then each contact point will need to be resolvable. This doesn't mean that the cassandra machine needs to be running, just that a DNS lookup on the hostname returns any ip address. So the case where things would break would be if you removed a DNS entry for one of your contact points and restarted your application.


text:
Q: Generic "Killed" error in PHP script I am working on a CRON job that invokes a PHP script which does a lot of database work with loops.
It executes properly when I limit the data set, but when I run it against the full data set, the script errors out with a message:
Killed

set_time_limit is (0) and memory_limit is (-1)
Here is the code section where it consistently dies:
echo "I'm in _getMemberDemographicAttrs\n";
if (! empty ( $member_id )) {
    $query .= ' AND member_id = ' . $member_id;
}

$result = mysql_query ( $query, $this->_db );
if ($result) {
    while ( $rule = mysql_fetch_assoc ( $result ) ) {
        $rules [] = $rule;
    }
    if (! empty ( $rules )) {
        mysql_free_result ( $result );
        echo "I'm leaving _getMemberDemographicAttrs\n";
        return $rules;
    }
}

The output looks like this:
I'm in _getMemberDemographicAttrs

I'm leaving _getMemberDemographicAttrs

I'm in _getMemberDemographicAttrs

I'm leaving _getMemberDemographicAttrs

I'm in _getMemberDemographicAttrs

Killed

I've never seen this generic Killed error message and I'm wondering what is causing it to be killed?

A: You might be triggering the Linux out-of-memory (OOM) killer. Check dmesg for messages about it. It says which process was killed when this happens.

A: Simple way to reproduce this Killed error:
I was able to reproduce this error on Ubuntu 12.10 with PHP 5.3.10.
Create a PHP script called m.php and save it:
<?php
    function repeat(){
       repeat();
    }
    repeat();
?>

Run it:
el@apollo:~/foo$ php m.php
Killed

The program takes 100% CPU for about 15 seconds then halts with the Killed message.  Look at dmesg | grep php and there are clues:
el@apollo:~/foo$ dmesg | grep php
[2387779.707894] Out of memory: Kill process 2114 (php) score 868 or
sacrifice child

So in my case, the PHP program halted and printed "Killed" because it ran out of memory due to an infinite loop.
Solutions:

*

*Increase the amount of RAM available or amount of memory available to this PHP program.

*Break down the problem into smaller chunks that operate sequentially.

*Rewrite the program so it has smaller memory requirements or doesn't go so deep with recursion.

A: In my case on CloudLinux, PHP 7.1, it occurred when 2 processes were reading and writing to the same file without locks.


text:
Q: Telerik Report With WPF I used Telerik Report control with WPF(C#). I assinged data to Telerik Report but i don't want to open report but i need to print directly when it filled.

A: You can try with this code - based on PrintReport method
    function MyPrint()
    {
        <%=ReportViewer1.ClientID %>.PrintReport();
    }


text:
Q: How to get unique random values in Dynamic Add / Remove input Fields I have created Dynamic Add/Remove fields. Everything is working perfectly. The only problem is that there is a hidden field having name="auth_key[]".
For that, I want random values. So I use value="<?php echo rand(); ?>". However, it creates the same random values for all the fields that are added. I want unique random values for all the fields that are added.
Following is my code:

jQuery(document).ready(function($) {
  var wrapper = $("#member-fields");
  var add_button = $("#add-member-fields");

  var x = 1;
  var availableAttributes = <?php echo json_encode($get_user_emails); ?>;
  var previousValue = "";

  add_button.click(function(e) {
    e.preventDefault();
    x++;
    var element = $('

<input type="text" class="form-control" id="user_email" name="user_email[]" placeholder="">

<input type="text" class="form-control" name="user_role[]" placeholder=""><input type="hidden" class="form-control" name="user_status[]" value="Unverified" placeholder=""><input type="hidden" class="form-control" name="auth_key[]" value="<?php echo rand(); ?>" placeholder="">

<button type="button" class="btn btn-danger" id="remove_member_field"> Remove</button>

');

    element.fadeIn("slow").find("input[name^='user_email']").autocomplete({
      autoFocus: true,
      source: availableAttributes,
    });
    wrapper.append(element);
  });

  wrapper.on("keyup", "#user_email", function() {
    var isValid = false;
    for (i in availableAttributes) {
      if (availableAttributes[i].toLowerCase().match(this.value.toLowerCase())) {
        isValid = true;
      }
    }
    if (!isValid) {
      this.value = previousValue
    } else {
      previousValue = this.value;
    }

  });

  wrapper.on("click", "#remove_member_field", function(e) {
    e.preventDefault();
    $(this).parent().fadeOut(300, function() {
      $(this).closest('#user-fields').remove();
      x--;
    });
  });
});

    Team Members

Member's Registered Email

Role in Project

          <input type="text" class="form-control" name="user_email[]" placeholder="">

          <input type="text" class="form-control" name="user_role[]" placeholder="">
          <input type="hidden" class="form-control" name="user_status[]" value="Verified" placeholder="">
          <input type="hidden" class="form-control" name="auth_key[]" value="<?php echo rand(); ?>" placeholder="">

        <button type="button" class="btn btn-success" id="add-member-fields"> Add</button>

To add member please register new User, if already not registered.

<?php

    $user = wp_get_current_user();
    $args = array(
      'role'         => 'backer',
      'exclude'      => array( $user->ID ),
     );

    $users = get_users( $args );
    $get_user_emails = wp_list_pluck( $users, 'user_email' );

    ?>

Please help me. Thanks in advance.

A: You should do this in the JS part instead, inside the click event when you're adding the new field add the following code :
element.find('[name="auth_key[]"]').val( Math.floor(Math.random() * 10000) );

var wrapper = $("#member-fields");
var add_button = $("#add-member-fields");
var x = 1;
var availableAttributes = "";
var previousValue = "";

add_button.click(function(e) {
  e.preventDefault();
  x++;
  var element = $('

<input type="text" class="form-control" id="user_email" name="user_email[]" placeholder="">

<input type="text" class="form-control" name="user_role[]" placeholder=""><input type="hidden" class="form-control" name="user_status[]" value="Unverified" placeholder=""><input type="hidden" class="form-control" name="auth_key[]" value="<?php echo rand(); ?>" placeholder="">

<button type="button" class="btn btn-danger" id="remove_member_field"> Remove</button>

');

  element.find('[name="auth_key[]"]').val(Math.floor(Math.random() * 10000));

  console.log(element.find('[name="auth_key[]"]').val());
  wrapper.append(element);
});

wrapper.on("keyup", "#user_email", function() {
  var isValid = false;
  for (i in availableAttributes) {
    if (availableAttributes[i].toLowerCase().match(this.value.toLowerCase())) {
      isValid = true;
    }
  }
  if (!isValid) {
    this.value = previousValue
  } else {
    previousValue = this.value;
  }

});

wrapper.on("click", "#remove_member_field", function(e) {
  e.preventDefault();
  $(this).parent().fadeOut(300, function() {
    $(this).closest('#user-fields').remove();
    x--;
  });
});

    Team Members

Member's Registered Email

Role in Project

          <input type="text" class="form-control" name="user_email[]" placeholder="">

          <input type="text" class="form-control" name="user_role[]" placeholder="">
          <input type="hidden" class="form-control" name="user_status[]" value="Verified" placeholder="">
          <input type="hidden" class="form-control" name="auth_key[]" value="10" placeholder="">

        <button type="button" class="btn btn-success" id="add-member-fields"> Add</button>

To add member please register new User, if already not registered.

A: Your
value="<?php echo rand(); ?>"

is generating a random number on server side once requesting the site.
You have to use
Math.random()

from javascript.


text:
Q: How to terminate and iterate on nested ngFor in angular2 I need to show below UI template list using nested ngFor:

17th March, 2017:
07:26 AM   Item1,Item2,Item3
07:15 AM   Item6,Item5,Item4
07:10 AM   Item7,Item8,Item9
16th March, 2017:
08:26 AM   Item10,Item20,Item30
08:15 AM   Item60,Item50,Item40
06:10 AM   Item70,Item80,Item90

The challenge I've is I get a single JSON as below:
[{
"date":"17th March, 2017",
"time":"07:26 AM",
"items":"item1,item2,item3"
},{
"date":"17th March, 2017",
"time":"07:15 AM",
"items":"item6,item5,item4"
},{
"date":"17th March, 2017",
"time":"07:10 AM",
"items":"item7,item8,item9"
},{
"date":"16th March, 2017",
"time":"08:26 AM",
"items":"item10,item20,item30"
},{
"date":"16th March, 2017",
"time":"08:15 AM",
"items":"item60,item50,item40"
},{
"date":"16th March, 2017",
"time":"06:10 AM",
"items":"item70,item80,item90"
}
]

So can someone help/suggest me on how to form a nested template to show above list and to terminate the inner ngFor when date changes as per data.

A: Using two Pipe's, it could look like this:
Maybe StringToArrayPipe isn't needed, if you only want to show that string..
@Pipe({ name: 'stringToArray' })
export class StringToArrayPipe implements PipeTransform {
  public transform(value: string): string[] {
    if (!value) return [];
    return value.split(',');
  }
}

@Pipe({ name: 'mergeDuplicates' })
export class MergeDuplicatesPipe implements PipeTransform {
  public transform(values: any[]): any[] {
    if (!values || !values.length) return [];
    return values.reduce((prev, cur) => {
      const tmp = prev.find(v => v.date == cur.date);
      if (!tmp) {
        prev.push({
          date: cur.date,
          timeAndItems: [
            { time: cur.time, items: cur.items }
          ]
        });
      }
      else {
        tmp.timeAndItems.push({
          time: cur.time,
          items: cur.items
        });
      }
      return prev;
    }, []);
  }
}

@Component({
  selector: 'my-app',
  template: `

Hello {{name}}

         {{ d.date }}

            {{ timeAndItems.time }}
            {{ i }}

  `,
})
export class App {
  name:string;

  private _data = [
    {
      "date":"17th March, 2017",
      "time":"07:26 AM",
      "items":"item1,item2,item3"
    },{
      "date":"17th March, 2017",
      "time":"07:15 AM",
      "items":"item6,item5,item4"
    },{
      "date":"17th March, 2017",
      "time":"07:10 AM",
      "items":"item7,item8,item9"
    },{
      "date":"16th March, 2017",
      "time":"08:26 AM",
      "items":"item10,item20,item30"
    },{
      "date":"16th March, 2017",
      "time":"08:15 AM",
      "items":"item60,item50,item40"
    },{
      "date":"16th March, 2017",
      "time":"06:10 AM",
      "items":"item70,item80,item90"
    }
  ];

  constructor() {
    this.name = 'Angular2'
  }
}

live-demo: https://plnkr.co/edit/W1dJzqiSqhy83rmY4Xyc?p=preview

A: Use

{{outer.date}}

{{inner.time}}
 : {{inner.items}}

Outer loop gets unique dates
Inner loop displays time and items when inner.date = outer.date
Morever .. if items is a list then you need a third loop same logic as above


text:
Q: adding menu to jquery accordion Hi all here is my question
I am using jquery accordion in my website.
I was trying to add a small slide down menu in to the accordion head it is coming fine but the problem is whenever I am clicking the menu,
my slide down mu is coming and the same time accordion is also expanding.
I don't want accordion to be activated when I am clicking the small menu icon

A: Use stopPropagation, which will prevent the click from bubbling up to the accordion's click handler:
$('.small-menu-icon').click(function(e) {
    e.stopPropagation();
    // show menu
});


text:
Q: Sort array with duplicates by unique chunks I want elements of that:
['1','1','2','2','2','3','3','3','3','3','3','3','4']

to be grouped into chunks with unique values, to make it look like that:
['1','2','3','4','1','2','3','2','3','3','3','3','3']

First "chunk" '1','2','3','4' contain all unique values without duplicates, second '1','2','3' etc.

The biggest problem is that my array is not combined from simple numbers, it is two-dimensional associative array, something like that:
[['id'=>'xd1c',...],['id'=>'ab2c',...],['id'=>'xd1c',...],['id'=>'xd1c',...],['id'=>'ab2c',...],['id'=>'xd1c',...],['id'=>'687d',...],...]

I don't have a lot of experience with algorythmics and advanced sorting and I feel a bit overwhelmed. Please if you could point me out in right direction with that.

A: Try this code :

$current = array('1','1','2','2','2','3','3','3','3','3','3','3','4');
$new = array();
while(!empty($current)){
    foreach(array_keys(array_unique($current)) as $index){
        $new[] = $current[$index];
        unset($current[$index]);
    }
}
print_r($new);


text:
Q: Collapse and expand elements with CSS I'm trying to build a page where only headlines are visible when it is loaded, and
the tables beneath each title toggle between hidden and displayed state when the user clicks on the title.
The constraint I have is to do this in CSS only.
This is what I came up with so far:
https://jsfiddle.net/Argoron/c1ypx24c/6/
It doesn't work the way it should because every time I click on a title, the tables beneath the other titles are hidden. What I'm trying to accomplish is that each section behaves independently, meaning that for example table 1 should change its display state only when title 1 is being clicked.
Also, not sure why both alternative titles are displayed in section 3.

A: I will suggest use checkbox input and :checked instead of a and :target tags to trigger the event since the target will change always you click another link. Try this:

.tb {
    margin:10px 0;
}
.tb span+span, .collapsible {
    display:none;
}
.tb input[type="checkbox"]:checked ~ span {
    display:none;
}
.tb input[type="checkbox"]:checked ~ span+span{
    display:inline;
}
.tb input[type="checkbox"]:checked ~ .collapsible {
    display:table;
}

    <input type="checkbox"/>
    ShowHide

            Hello 1

    <input type="checkbox"/>
    ShowHide

            Hello 2

    <input type="checkbox"/>
    ShowHide

            Hello 3

Now if you don't want to see the checkbox you can use CSS. Check this Snippet

.tb {
  margin: 10px 0;
  position: relative;
}
input[type="checkbox"] {
  width: 100%;
  height: 23px;
  position: absolute;
  left: 0;
  top: 0;
  opacity: 0;
  z-index: 10;
  cursor: pointer;
}
input[type="checkbox"]:hover ~ span {
  background: black;
}
.tb span {
  position: relative;
  height: 23px;
  line-height: 23px;
  display: inline-block;
  background: red;
  color: white;
  transition: all .3s ease;
  padding: 0 10px;
  width: 100%;
}
.tb span+span,
.collapsible {
  display: none;
}
.tb input[type="checkbox"]:checked ~ span {
  display: none;
}
.tb input[type="checkbox"]:checked ~ span+span {
  display: inline-block;
}
.tb input[type="checkbox"]:checked ~ .collapsible {
  display: table;
}

  <input type="checkbox" />
  ShowHide

      Hello 1

  <input type="checkbox" />
  ShowHide

      Hello 2

  <input type="checkbox" />
  ShowHide

      Hello 3

Or the DemoFiddle

A: Your error was in #FirstC:target + #First . Also you misspelled the selector #ThirdE
https://jsfiddle.net/c1ypx24c/10/
table.collapsible {
    display: none;
}

#FirstE, #SecondE, #ThirdE {
    display: none;
}

#FirstC:target ~ #FirstE,
#SecondC:target ~ #SecondE,
#ThirdC:target ~ #ThirdE{
    display: inline;
}

#FirstC:target,
#SecondC:target,
#ThirdC:target{
    display: none;
}

#FirstC:target ~ #collapsible1,
#SecondC:target ~ #collapsible2,
#ThirdC:target ~ #collapsible3{
    display: inline;
}


text:
Q: Children.Remove and visiblity collapsed is same behavior? Is removing the children from the panel and collapsed the children visibility is the same behavior?
I mean, will memory releases when I remove or collapse the children from the panel. I am confused with the concept of visibility(Collapsed) and removing the children from the panel. Can anyone please suggest me and also please explain the performance about this case.
Thanks,
Santhiya

A: If you use Visiblity="Collapsed" then the object will not be removed from memory. But if you remove it using Children.Remove then object will be removed from memory.
For more Info see Optimise you UWP App Without Laziness

A: Removing elements from visual tree will free up memory. Setting it to Collapsed won't, but events like SizeChanged won't be raised so performance wise it still helps a bit.
In the Creators update there is a new x:Load feature available with data binding support, like <Button x:Load="{x:Bind Show, Mode=OneWay}"/>. When you set Show to False in code, the button will be completely removed from the visual tree.


text:
Q: trouble with for loops in R, replicating the Gram-Schmidt Orthonormalization algorithm I am trying to replicate the Gram-Schmidt orthonormalization algorithm for my linear algebra class in R. First I generate some data, and store it in matrix A
a1<-c(1,2,3,4,5,6)
a2<-c(4,5,2,9,1,2)
a3<-c(2,2,2,3,3,3)
A<-cbind(a1,a2,a3)

I then run the gram-schmidt orthonormalization algorithm to convert the columns of A into a orthonormal set, stored in the matrix Q.
R=matrix(0,nrow=ncol(A),ncol=ncol(A))
Q=A
R[1,1]=sqrt(sum(Q[,1]*Q[,1])) #calculate nrom of q1, store in R
Q[,1]=(1/R[1,1])*Q[,1] #transform q1 into a unit vector, using the norm stored in R.
for(j in 2:ncol(Q))
{
    for(i in 1:j-1)
    {
        R[i,j]=sum(Q[,i]*Q[,j])
        Q[,j]=Q[,j] - R[i,j]*Q[,i]
    }
    R[j,j]=sqrt(sum(Q[,j]*Q[,j]))#calulate the norm of qj, store in the main diagonal of R
    Q[,j]=(1/R[j,j])*Q[,j] #transform qj into a unit vector, using the norm stored in R.
}

My algorithm seems very similar to some of the ones coded here for R: Gram Schmidt with R
However, every time I run the algorithm it generates this error:
Error in Q[, j] = Q[, j] - R[i, j] * Q[, i] : replacement has length zero

I can't figure out what is wrong here. If I run the code line by line, and set i=1, j=2, it runs the first computation of this line just fine. Is there something wrong with how I have specified or nested my for loops? Bueller?

A: The range in the second loop should be 1:(j-1).
To illustrate the problem:
> 1:4-1
[1] 0 1 2 3

while
> 1:(4-1)
[1] 1 2 3


text:
Q: Codeception $env is not accessible in integrational test after upgading to 2.2.5 I have upgraded my codeception version from 2.1.7 to 2.2.5. In one integrational test case I am accessing current environment using:
$this->env
It was working fine in 2.1.7 version but in 2.2.5 version I am getting error:
Undefined property: tests\integrational\AutoBillerTest::$env

I checked in library and found that
vendor/codeception/codeception/src/Codeception/TestCase/Shared/Actor.php
file is not present in current version but it was present in previous version. This Actor class contains $env variable.
I tried to generate actor class using command:
$codecept build
Still that Actor class is not getting generated.

A: Test formats were completely refactored in Codeception 2.2 and that Actor trait is gone.
In 2.2 enviroment can be retrieved from \Codeception\Scenario in Cept and Cest formats and from \Codeception\Metadata in Unit format (Scenario gets it from Metadata too).
Unit format:
$this->getMetadata()->getEnv()

In Cept format $scenario variable is always available, so you can simply do
$scenario->current('env');

In Cest format $scenario variable must be injected
public function tryToTest(UnitTester $I, \Codeception\Scenario $scenario)
{
    $scenario->current('env');
}

Usage of Scenario is documented.


text:
Q: Wrapping c++ and CUDA code with cython I want to wrap c++ and CUDA code with cython.
I looked npcuda-example (https://github.com/rmcgibbo/npcuda-example) and I change setup.py as follows.
ext = Extension('MyWrap',
            sources=['src/my_code.cu', 'python/my_wrap.pyx'],
            library_dirs=[CUDA['lib']],
            libraries=['cudart'],
            language='c++',
            runtime_library_dirs=[CUDA['lib']],
            # this syntax is specific to this build system
            # we're only going to use certain compiler args with nvcc and not with gcc
            # the implementation of this trick is in customize_compiler() below
            extra_compile_args={'clang++': ['-std=c++11','-O3'],
                                'nvcc': ['-std=c++11','-gencode','arch=compute_30,code=sm_30']},
            include_dirs = [numpy_include, CUDA['include'], 'src'],
            extra_link_args=["-std=c++11"])

And, I run setup.py for my code,
but, I have a nvcc error "fatal error: 'mutex' file not found"
I guess "-std=c++11" option can not pass nvcc compiler.
How can I wrap c++ and CUDA code include c++11 code?

A: Thank you for answering.
I solved this problem. Command "distutils.util.get_platform()" return mac os x 10.5 on my Mac. So I change python anaconda to system default python, I can compile c++11 code. But I can not compile my all code.
In accordance with Saullo Castro's answer, first I build my code to library using CUDA_ADD_LIBRARY of CMake CUDA Package. And I compile only wrapper.pyx with this library. Then I can wrap my c++ code with cython.
Thank you!!


text:
Q: Alternatives to Parse for a Social App? I recently delved into app development on Xcode, and decided to develop a social app. I was using Parse as my mbaaS for a while, but unfortunately they are closing down. I was wondering in your experience what is(are) the best alternatives to Parse. Im basically using looking for something
1) easy to use
2) Well documented
3) Lots of tutorials
4) Can handle lots of RPS and users.
The app I am developing is a social app, so if you have any specific recommendation for an app of that type, that would help tremendously. Also it is important to note that I have no backend development experience, so it would be a challenge to develop my own.
Thanks again

A: There are several Parse alternatives out there right now:
AWS Mobile Hub - this is a direct Parse replacement that recently came out by AWS. Although this is in Beta, AWS is a well respected    platform that supports many huge companies like Netflix and Yelp
Firebase - (acquired by Google) Firebase offers a great solution for    real time communication and data storage. It's perfect if what you    are doing is mainly data & realtime (chat, game, collaboration,    etc...) but it's not very flexible for other things (e.g. payment,    SMS, push notifications etc...) firebase.com
RapidAPI - a backend platform that allows for saving data and integrating APIs. It is based on blocks so each basic action is represented by a block. You can combine blocks to create logic. It has a bit of a higher learning curve but it's probably more flexible
BackAnd - a platforms that allows you to create an AngularJS ready backend for your app. Its really good of you are working on AngularJS web apps and your data is stored on Amazon RDS.

A: Baasbox is a good alternative to Parse. A lot of features used in Parse are there (Push messaging etc), so migrating an app is relatively straightforward. They provide an API for Android, iOS and Javascript.
One of the main advantages it has over Parse is that it can be hosted yourself (Although there is a hosted option available, but it's not free).
http://www.baasbox.com
Out of all the available backends, we found this to be most similar to Parse.


text:
Q: Permanently remove sidebar that pops up every time I open a tab in Safari How can I permanently remove the sidebar that pops up every time I open a tab in  Safari 9.1.3 on OS X El Capitan?

A: Open a new tab, then go to View → Hide Sidebar ⇧⌘L.
The sidebar will be hidden on new tab pages until you show it again.

A: Scouring the web on this one - the only thing that seems to work is putting your Dock on the left side of the screen, then disabling the auto show of the dock in the terminal.
The answer by grgarside doesn't work at all.

A: I realize this question is 5 years old probably because Mac has mainstreamed this issue by having the solution easily accessible, but for anyone who still doesn't know how to stop this random sidebar pop-up its pretty simple. View> Hide Sidebar. For me the issue started randomly and I did not know they have a simple on and off feature.


text:
Q: How can I fix my PlayStation 3? I recently acquired a PS3 (120gb Slim CECH-3003A) with some sort of HDD problem.
The console would boot up, complain about having some sort of hard drive error that needs recovery, start recovering, and crash at 48%. But then the original owner decided to remove the hard drive and format it to NTFS.
Now the console doesn't even turn on. When the power button is pressed, the light goes green for 2-5 seconds, the just goes off and nothing happens.
How can I fix this?

A: If you do indeed have the usb-sata cable, plug the hard drive back in, and wipe the drive to remove all partitions, and don't format it afterwards - the PS3 will handle that. Once that's done, plug it back into the PS3 and see if it boots up to a "firmware not found" screen. If so, download the firmware from Sony's Website, copy it to a USB stick, and follow the on-screen prompts to get back in action (this question has that part covered alreay).
If that fails, the hard drive may be faulty - plug it back into the computer, and perform a full format to see if it finds any faulty sectors, or another hard drive testing utility (maybe even H2Testw - will write the whole capacity of the drive, then read it back for errors).


text:
Q: How to avoid copy/paste many event handlers My application cannot access a specific menu item unless some condition is true (DataRepository.IsAllDataLoaded). I came up with this code, which works great. It checks for the condition first. If it is not ready, it calls a timer, which waits some milliseconds and call the same method again. The Timer needs an ElapsedEventHandler.
public void FirstMenuItem_Click(object sender, RoutedEventArgs e)
{
  if (!DataRepository.IsAllDataLoaded)
  {
    WaitForDataLoading(FirstTimedEvent);
  }
  else
  {
    Dispatcher.BeginInvoke(new Action(() =>
   {
     IndividualEntryWindow Window = new IndividualEntryWindow();
     Window.Show();
   }));
  }
}
private void FirstTimedEvent(object source, ElapsedEventArgs e)
{
  FirstMenuItem_Click(null, null);
}

private static void WaitForDataLoading(ElapsedEventHandler timerEvent)
{
  Timer t = new Timer();
  t.Interval = 0.2;
  t.AutoReset = false;
  t.Elapsed += new ElapsedEventHandler(timerEvent);
  t.Start();
}

Initially, the FirstMenuItem_Click was the only method. I had to add FirstTimedEvent handler for my timer. Is there a way to avoid creating that ElapsedEventHandler? Can I create it inline in my FirstMenuItem_Click method?
I now have to use that same pattern for many other Item_Click methods. I wish I don't have to create a ElapsedEventHandler for each Item_Click method.

A: Use an anonymous lambda expression:
WaitForDataLoading((s,e) => FirstMenuItem_Click(null, null));

A: In the following code you can call the method CheckDataShowWindow() anytime you wish to show the windows when the data is ready. If you want to add it to another cick handler, you can just make another like so:
public void Another_Click(object sender, RoutedEventArgs e)
{
    CheckDataShowWindow();
}

Main code:
public void FirstMenuItem_Click(object sender, RoutedEventArgs e)
{
    CheckDataShowWindow();
}

private void CheckDataShowWindow()
{
    if (!DataRepository.IsAllDataLoaded)
    {
        Timer t = new Timer();
        t.Interval = 0.2;
        t.AutoReset = false;
        t.Elapsed += (s,e) => CheckDataShowWindow();
        t.Start();
    }
    else
    {
        Dispatcher.BeginInvoke(new Action(() =>
        {
            IndividualEntryWindow Window = new IndividualEntryWindow();
            Window.Show();
        }));
    }
}

Update
If you can edit the code of the datarepository you should add an event for when the data is done loading.
public delegate void DoneLoadingHandler(object sender, EventArgs e);
public class DataRepository
{
    public event DoneLoadingHandler DoneLoading;
    //Your loading function
    private void LoadAllData()
    {
        //Load like you do now

        //Now fire the event that loading is done.
        if(DoneLoading != null)
            DoneLoading(this, new EventArgs());
    }
}

Now in your other class:
public void FirstMenuItem_Click(object sender, RoutedEventArgs e)
{
    CheckDataShowWindow();
}

private bool AllReadyWaiting = false;
private void CheckDataShowWindow()
{
    if (!DataRepository.IsAllDataLoaded)
    {
        if(!AllReadyWaiting)
        {
            DataRepository.DoneLoading += (s,e) => ShowWindow();
            AllReadyWaiting = true;
        }
    }
    else
    {
        ShowWindow();
    }
}

private void ShowWindow()
{
    Dispatcher.BeginInvoke(new Action(() =>
    {
        IndividualEntryWindow Window = new IndividualEntryWindow();
        Window.Show();
    }));
}

A: You appear to be using WPF, based on your use of the Dispatcher class.  That being the case, there are nicer means for you to control the access to your UI.
Two of these are:

*

*bind your menu's Enabled property to ViewModel class, which would have a property to indicate whether the menu should be available.  When your long-running job is complete, set the property to true and the menu will be enabled.

*use an ICommand to drive the behaviour of your menu.  The command's CanExecute return false while your long-running job is active, which will cause the menu to automatically be disabled until the job is complete.
It's worth noting that this will subtly change the behaviour of your menu - but not, I think, in a bad way.  Your current code will wait for the job to complete before showing the dialog - but there's nothing to stop the user clicking the menu again in the meantime.  These multiple clicks will each wait for the job to complete, and each display their own dialog when the job completes.  In a trivial case this might mean that I see multiple dialogs appear; in a severe case the multiple timers that you're creating might badly affect the performance of the application.
Either of the methods suggested above would prevent the menu from being clicked while the job is running, which is not quite your current behaviour but, I think, would make more sense from a usability perspective.


text:
Q: Why am I getting this unpermitted params error? I have a PortStock model that looks like this:
class PortStock < ApplicationRecord
  has_many :closed_positions, dependent: :destroy
  accepts_nested_attributes_for :closed_positions, allow_destroy: true
end

My ClosedPosition model look like this:
class ClosedPosition < ApplicationRecord
  belongs_to :closer, class_name: "PortStock", foreign_key: "closer_id"
  belongs_to :closed, class_name: "PortStock", foreign_key: "port_stock_id"
end

In my PortStockController, my params looks like this:
def port_stock_params
  params.require(:port_stock).permit(:portfolio_id, :stock_id, :closed_position, closed_positions_attributes: [:num_units, :closer_id, :port_stock_id, :closed_price, :_destroy])
end

This is the form:
<%= simple_form_for @port_stock, url: port_stocks_sell_order_path, method: :post, html: { class: "form-inline" } do |f| %>

  <% @buy_port_stocks.each do |port_stock| %>
    <%= f.simple_fields_for @cp, html: { class: "form-inline" } do |c| %>
      <div class="form-group">
        <%= c.input_field :port_stock_id, as: :hidden, value: port_stock.id %>
        <%= c.input_field :num_units, id: "sell-ps-#{port_stock.id}", placeholder: "Number of Units", class: "form-control mx-sm-3" %>
         <%= c.input_field :closed_price, id: "sale-price-for-ps-#{port_stock.id}", placeholder: "Sale Price", class: "form-control mx-sm-3" %>
       </div>
   <% end %>
  <% end %>
<% end %>

This is my PortStock#Create action:
@port_stock = current_user.port_stocks.friendly.find(params[:id])
@stock = @port_stock.stock
@cp = @port_stock.closed_positions.build

This is the error when I try to do a create:
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"M/TCcc79QcfOvoIc3z/cIFn83sjA==", "port_stock"=>{"closed_position"=>{"port_stock_id"=>"10", "num_units"=>"25", "closed_price"=>"9"}}, "commit"=>"Sell Stock", "id"=>"CAC"}
  User Load (1.8ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 2], ["LIMIT", 1]]
  ↳ /.rvm/gems/ruby-2.5.1/gems/orm_adapter-0.5.0/lib/orm_adapter/adapters/active_record.rb:17
  PortStock Load (1.6ms)  SELECT  "port_stocks".* FROM "port_stocks" INNER JOIN "portfolios" ON "port_stocks"."portfolio_id" = "portfolios"."id" WHERE "portfolios"."user_id" = $1 AND "port_stocks"."ticker" = $2 LIMIT $3  [["user_id", 2], ["ticker", "CAC"], ["LIMIT", 1]]
  ↳ /.rvm/gems/ruby-2.5.1/gems/friendly_id-5.2.4/lib/friendly_id/finder_methods.rb:60
Unpermitted parameter: :closed_position

What could be causing this?

A: First,
as you accepts the closed_positions_attributes as nested attributes, thus no need to add closed_position in strong parameters. If you still want to access closed_position attribute in PortStock, then in the model use attr_accessor
Second, change the nested form like the following to get the required parameters.
f.simple_fields_for :closed_positions, @cp, html: { class: "form-inline" } do |c|

Hope it resolve the issue!


text:
Q: Problem of Critical Region and Significance Level (Statistics) An investment adviser states that the risk (standard deviation) when investing in a certain instrument is greater than $3.$ To corroborate the validity of this statement, he plans to realize: $H_0: \sigma=3$  vs.  $H_1: \sigma>3$ with an aleatory sample of $n = 29$ performance values.
Then he gets a sample mean of $\bar X =8$ and a sample variance of $S^2 = 16.$ What is the approximate value of the significance level of the test if the rejection region (critical region) given by $S^2$ is such that $S^2 \ge 13?$
Note: $\sigma$ denotes population standard deviation
and $S^2$ denotes sample variance.
My procedure: I looked up for the value 13 with 28 (29-1) degrees of freedom in the Chi squared table to know the significance level, but that did not work...  The answer is supposed to be: $.025<$ p-value $<.05.$

A: Comment continued. I assume you are using normal data. It is not possible to work such a problem without some assumption about the population distribution. At an elementary level, the background should have been covered to allow answering for normal data. For example, the assumption of normal data leads directly to the chi-squared distribution of $Q$ below.
The significance level is the probability of rejection $P(S^2 \ge 13)$ under the assumption that $\sigma = 3.$ I guess your assignment is to get an answer using the relationship in my Comment above:  With $Q = \frac{(n-1)S^2}{\sigma^2},$ you have
$Q \sim \mathsf{Chisq}(\nu),$ where $\nu = n-1 = 29-1 = 28$
degrees of freedom.
For your data with $n = 29, S^2 = 16$ and your null hypothesis $\sigma = 3,$ you have
$$Q = \frac{(n-1)S^2}{\sigma^2} = \frac{28(16)}{9} = 49.78.$$
Now, the critical value for a test is given as $S^2 > 13.$
But the printed chi-squared table is given in terms of $Q,$ which is the chi-squared random variable. So $S^2 > 13$ is equivalent
to
$$Q_c = \frac{28S^2}{9} = \frac{28(13)}{9} = 40.44.$$
So you reject $H_0,$ according to the stated critical region, either because $S^2 = 16 > 13$ or because $Q = 49.78 > 40.44.$
If you look at the row for DF = 28 in your printed chi-squared
table, you will find that 49.78 lies between the entries 48.27 and 50.99, in columns headed .01 and .005., indicating that the values cut about 1% and 0.5% from the upper tail of the relevant chi-squared distribution. So I get that the p-value lies between
1% and 0.5%, not between 5% and 0.25% as in the answer provided. The exact
p-value is 0.007, which lies between 0.01 and 0.005.
qchisq(c(.9, .95, .975, .99, .995), 28)
[1] 37.91592 41.33714 44.46079 48.27824 50.99338
1 - pchisq(49.78, 28)
[1] 0.006842861

The critical values implied by $S^2 \ge 13$ or $Q > 40.44$ are
not for a test at the 5% significance level.
The level based on those critical values is about 6%.
1 - pchisq(40.44, 28)
[1] 0.06038755

A test at
the 5% level would use $Q \ge 41.34$ or $S^2 = 9(41.34)/28 \approx 13.29.$
For verification, a simple simulation in R gets approximately these same results (6%, 13.3, 0.007), directly from the simulated distribution of $S^2,$ when $n = 29$ and $\sigma = 3.$
set.seed(1214);  m = 10^5;  n = 29;  sg = 3;  mu = 8
v = replicate(m, var(rnorm(n, mu, sg)))
mean(v > 13)
[1] 0.06023
quantile(v, .95)
     95%
13.26989
mean(v > 16)
[1] 0.00683

The figure below shows a histogram of the simulated values of $Q$ with the
density function of $\mathsf{Chisq}(28).$ The heavy vertical black line is at the
observed value of $Q$ corresponding to $S^2 = 16.$ Thin vertical brown and cyan
lines cut probabilities  5% and 1%, respectively, from the upper tail of the distribution.

So I don't get the alleged answer. I don't know whether we are dealing with a misinterpretation of the problem, with typgraphical/computational errors, or with an incorrect answer. Please check everything.
Notes: (1) In R statistical software the function pchisq denotes the CDF of a chi-squared distribution and the function qchisq indicates its inverse CDF or 'quantile' function. (2) In the simulation v is a vector of 100,000 simulated values of $S^2.$


text:
Q: Silhouette index on clusters of different intracluster variability / intercluster distances I am currently dealing with an issue regarding cluster validation.
I have a pairwise distance matrix (based on the hamming distance between a set of core genes of different strains of a bacterium). I performed k-medoids clustering on the pairwise distances, attempting to validate my initial suspicion that there are 3 clusters. Surprisingly, the average silhouette index is around 0.3 for k = 2 and around 0.2 for k = 3, suggesting that the clustering is "better" for the k = 2 case. I understand that the silhouette index is only one of many cluster validation methods and that the silhouette index cannot be wrong per se.
I have the suspicion that the silhouette index supports k = 2 over k = 3 because my putative clusters are of different inter-cluster distance as well as of different variability, as indicated by an nMDS plot as well as boxplots of (real) pairwise distances between clusters. Specifically, I appear to have two tight clusters that are close to each other (cluster 1 and 2), while the third cluster is further away and less well defined (cluster 3).

I believe that the average silhouette index is smaller for k = 2 as the neighbouring cluster in that case is far away (for both clusters), where in the k = 3 case the average index is smaller since the two well defined clusters' neighbouring cluster are much closer (the other well defined cluster, respectively).
I am aware that the nMDS representation is not necessarily representative of the true pairwise distances.
I would like to know how to find out whether it would be ok to dismiss k = 2 in favor of k = 3 and, if so, how to make that point in the most elegant fashion.

A: If my memory serves, silhouettes often tend to support smaller number of clusters, but there are bigger issues with your analysis. You're analyzing biological data and straying far from the best practices in the field.
In your case both 1+2 vs 3 and 1 vs 2 vs 3 are valid clusterings, so you'd be better off with the hierarchical clustering, (3, (1, 2)) in a Newick notation. UPGMA/NJ, if you don't have the computational resources, ML or bayesian phylogenetics otherwise.
In addition, Hamming distances can be applicable only for very close strains, where the distances would be on the order of single mutations. Otherwise use some distance metric aware of possible multiple mutations on a single site and different mutation rates. There are quite a few of those, as well as methods for choosing the best one using eg Bayesian information criterion. Kimura 2-param seems to be a safe choice.


text:
Q: Convert View to Bitmap (OutOfMemoryException) I have a Bitmap created from a View with the kotlin extesion drawToBitmamp(). It works fine in most cases, but in low end devices, it throws an OutOfMemoryException.
I've been doing research about how to handle Bitmaps efficiently, but I found nothing when it comes to bitmaps generated from View's. Does anyone know how to avoid that exception while handling it better?
Any suggestion is welcome.

A: Try this way to add
android:largeHeap="true" in application tag in manifest
and also add below line
dexOptions{ javaMaxHeapSize "4g" }
in app level gradle or jvmargs=-Xmx2048M
Hope it may help you


text:
Q: Return two collections in one how can  i add collection to another collection? I am returnging one collection _lastOpenedArticles and if that collection has less than 3 articles i need to add articles from allUsersArticles. However i keep getting article from collection _lastOpenedArticles 3 times. Can you help please.
 async Task ShowLastListenedAsync(List<Article> allUserArticles)
      {

            var downloadedArticles = LangUpDataSaverLoader.DeserializeAllOptimizationData();
            if (_lastOpenedArticles != null && _lastOpenedArticles.Count > 0)
            {
                foreach (var article in _lastOpenedArticles.Take(3))
                {
                    var filename = string.Format(SharedConstants.ArticleImageUrl, SharedConstants.ApiBaseUri, article.Id);

                    var newCell = new ArticleDetailData()
                    {
                        Author = article.Author,
                        Id = article.Id,
                    };
                    if (downloadedArticles.DownloadedArticles.Any(m => m.Id == article.Id))
                    {
                        newCell.BackgroundImage = article.Id.ArticleImageFile();
                    }
                    else
                    {
                        newCell.BackgroundImage = filename;
                    }
                    var sec = article.Category;
                    if (sec == null)
                    {
                        newCell.Section = " ";
                    }
                    else
                    {
                        newCell.Section = article.Category;
                    }

                    LastThreeArticles.Add(newCell);

                    if (_lastOpenedArticles.Count < 3)
                    {
                        foreach (var art in allUserArticles.Take(3))
                        {
                           filename = string.Format(SharedConstants.ArticleImageUrl, SharedConstants.ApiBaseUri, article.Id);
                            var cell = new ArticleDetailData()
                            {
                                Author = article.Author,
                                BackgroundImage = filename,
                                Id = article.Id,
                            };
                            sec = article.Category;
                            if (sec == null)
                            {
                                cell.Section = " ";
                            }
                            else
                            {
                                cell.Section = article.Category;
                            }
                            LastThreeArticles.Add(cell);
                        }
                        await  FillAnonymousArticles(allUserArticles);
                    }
                }
            }

            else
            {
               await  FillAnonymousArticles(allUserArticles);
            }
        }

A: Instead of checking the count in the for loop, I'd propose to move the check whether you already have 3 articles after the loop. So you avoid to get the articles 3 times (once for each run of the loop):
async Task ShowLastListenedAsync(List<Article> allUserArticles)
{
    var downloadedArticles = LangUpDataSaverLoader.DeserializeAllOptimizationData();
    if (_lastOpenedArticles != null && _lastOpenedArticles.Count > 0)
    {
        foreach (var article in _lastOpenedArticles.Take(3))
        {
            var filename = string.Format(SharedConstants.ArticleImageUrl, SharedConstants.ApiBaseUri, article.Id);
            var newCell = new ArticleDetailData()
            {
                Author = article.Author,
                Id = article.Id,
            };
            if (downloadedArticles.DownloadedArticles.Any(m => m.Id == article.Id))
            {
                newCell.BackgroundImage = article.Id.ArticleImageFile();
            }
            else
            {
                newCell.BackgroundImage = filename;
            }
            var sec = article.Category;
            if (sec == null)
            {
                newCell.Section = " ";
            }
            else
            {
                newCell.Section = article.Category;
            }
            LastThreeArticles.Add(newCell);
       }
       // Move this check out of the for loop
       if (_lastOpenedArticles.Count < 3)
       {
           foreach (var art in allUserArticles.Take(3))
           {
               filename = string.Format(SharedConstants.ArticleImageUrl, SharedConstants.ApiBaseUri, article.Id);
               var cell = new ArticleDetailData()
               {
                   Author = article.Author,
                   BackgroundImage = filename,
                   Id = article.Id,
               };
               sec = article.Category;
               if (sec == null)
               {
                   cell.Section = " ";
               }
               else
               {
                   cell.Section = article.Category;
               }
               LastThreeArticles.Add(cell);
           }
           await  FillAnonymousArticles(allUserArticles);
        }
    }
    else
    {
        await  FillAnonymousArticles(allUserArticles);
    }
}

In addition, you could use Linq to create a union of the lists. This will result in much shorter code, for example:
_lastOpenedArticles
    .Union(allUserArticles)
    .Take(3)
    .Select(x => ConvertToCell(x)) // You need this method that converts the articles to a cell
    .ToArray();                    // If you need a list, you can also use ToList()

A: _lastOpenedArticles.AddRange(allUserArticles)
_lastOpenedArticles.Concat(allUserArticles)

the last one returns IEnumerable<T> and first one is void. Take one that suits you better


text:
Q: Different shapes according to data in D3 force layout I am trying to have a force layout where there are two types of shapes: Circles and Triangles. However, I get an error- Cannot read property 'symbol' of undefined. This is the relevant code snippet:
var shape = {"action": "circle", "why-hard": "triangle"};

var node = g.append("g")
    .attr("class", "nodes")
    .selectAll("circle")
    .data(graph.nodes)
    .enter().append("circle")
    .attr("d", d3.svg.symbol().type(function(d) { return shape[d.type]; }))

A: You are likely using d3v4. D3v4 has a number of namespace changes that will break code from v3, and it appears your symbol code is from v3. In this example:
.attr("d", d3.svg.symbol().type(function(d) { return shape[d.type]; }))

will give the error: Uncaught TypeError: Cannot read property 'symbol' of undefined (as noted) in Chrome, and d3.svg is undefined in Firefox. Instead for v4 try something along the lines of:
 .attr("d", d3.symbol().type(d3.symbolCross));

To assign type dynamically in v4, the approach is essentially the same as you have:
 .attr("d", d3.symbol().type( function(d,i) { return d3.symbols[i];} ) )

See fiddle here.
See https://github.com/d3/d3-shape/blob/master/README.md#symbol for v4 documentation regarding shapes.


text:
Q: How to push data from database and see vote count after each data? What I'm trying to do is to allow students answer questions and see each vote after each question and then the teacher can push the next question. The votes will then be entered into the database which I can use to produce a chart. I currently have the student answering questions but I'm having problem on stopping the next question from coming so the poll vote can show and how to show the vote before the next question comes.
This gets the questions from the database:
function getQuestion(){
var hr = new XMLHttpRequest();
    hr.onreadystatechange = function(){
    if (hr.readyState==4 && hr.status==200){
        var response = hr.responseText.split("|");
        if(response[0] == "finished"){
            document.getElementById('status').innerHTML = response[1];
        }
        var nums = hr.responseText.split(",");
        document.getElementById('question').innerHTML = nums[0];
        document.getElementById('answers').innerHTML = nums[1];
        document.getElementById('answers').innerHTML += nums[2];
    }
}
hr.open("GET", "questions.php?question=" + <?php echo $question; ?>, true);
  hr.send();
function post_answer(){
var p = new XMLHttpRequest();
        var id = document.getElementById('qid').value;
        var url = "userAnswers.php";
        var vars = "qid="+id+"&radio="+x();
        p.open("POST", url, true);
        p.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        p.onreadystatechange = function() {
    if(p.readyState == 4 && p.status == 200) {
        document.getElementById("status").innerHTML = '';
        alert("Your answer was submitted"+ p.responseText);
        var url = 'quiz.php?question=<?php echo $next; ?>';
        window.location = url;
}
}

p.send(vars);
document.getElementById("status").innerHTML = "processing...";

}

On a different php file:
    require_once 'core/init.php';
$arrCount = "";
if(isset($_GET['question'])){
    $question = preg_replace('/[^0-9]/', "", $_GET['question']);
    $output = "";
    $answers = "";
    $q = "";
       $connection = mysqli_connect('localhost', 'root', '', 'alsp');
    $sql = mysqli_query($connection,"SELECT id FROM questions");
    $numQuestions = mysqli_num_rows($sql);
    if(!isset($_SESSION['answer_array']) || $_SESSION['answer_array'] < 1){
        $currQuestion = "1";
    }else{

$arrCount = count($_SESSION['answer_array']);
    }
    if($arrCount > $numQuestions){
        unset($_SESSION['answer_array']);
        header("location: start-quiz.php");
        exit();
    }
    if($arrCount >= $numQuestions){
        echo 'finished|
There are no more questions. Please enter your username and submit

                <form action="userAnswers.php" method="post">
                <input type="hidden" name="complete" value="true">
                <input type="text" name="username">
                <button class="btn btn-action" type="submit" value="finish">Submit</button>
                </form>';
        exit();
    }
    $singleSQL = mysqli_query($connection,"SELECT * FROM questions WHERE id='$question' LIMIT 1");
        while($row = mysqli_fetch_array($singleSQL)){
            $id = $row['id'];
            $thisQuestion = $row['question'];
            $type = $row['type'];
            $question_id = $row['question_id'];
            $q = '
'.$thisQuestion.'
';
            $sql2 = mysqli_query($connection,"SELECT * FROM answers WHERE question_id='$question' ORDER BY rand()");
            while($row2 = mysqli_fetch_array($sql2)){
                $answer = $row2['answer'];
                $correct = $row2['correct'];
                $answers .= '<input type="radio" name="rads" value="'.$correct.'">'.$answer.'
                <input type="hidden" id="qid" value="'.$id.'" name="qid">

                ';

            }
            $output = ''.$q.','.$answers.',<button onclick="post_answer()"class="btn btn-action">Submit</button>';
            echo $output;
           }
        }

I'm guessing rather than have a submit button that takes you to the next page, after clicking on a radio button, the vote should show and then the teacher can push the next question. That's were the main issue is.


text:
Q: Is there a way to create a dump file of what the Windows Resource Monitor records every second? Or basically, archive all activity of all tasks across a span of 1 hour?
What about all activity of a particular task?
And is there also a way to create a similar dump file for activity recorded on Task Manager?

A: Use the Performance Monitor. Under Data Set Collectors select System then System Performance.
It will write, once a second, to a log file under c:\perflogs until you tell it to stop or it runs out of disk space.


text:
Q: Не срабатывает mail() Не срабатывает mail(), не понимаю в чем причина, помогите пожалуйста разобраться!
<?php
    $___notjson=1;
    include 'inc/matras_cfg.php';

    //Форма сообщения
    $title = "Заказ с конструктора";
    $to = "dimastik86@gmail.com";
    $headers = "From: Матрасик <>\r\n";

    $massiv = unserialize(stripslashes($_GET['massiv']));

    $mess .= "Сверху:
";
    foreach($massiv as $mtr_up){
        $find_down = "_down";
        if(!strstr($mtr_up, $find_down) AND $mtr_up !=  $block){
            $mess .= $matras_name[$mtr_up]."
";
        }
    };

    if ($block){
        $mess .= "
Блок:
";
        $mess .= $matras_name[$block]."
";
    };

    if ($_GET[main]){
        $mess .= "
Основа:
";
        $mess .= $_GET[main]."
";
    };

    $mess .= "
Снизу:
";
    foreach($massiv as $mtr_down){
        $find_down = "_down";
        if(strstr($mtr_down, $find_down) AND $mtr_down !=  $block){
        $ms =  str_replace("_down", "", $mtr_down);
        $mess .= $matras_name[$ms]."
";};
    };

    $message = ''."\n";
    $message .=''."\n";
    $message .='<title>'.$title.' '.$_SERVER['HTTP_HOST'].'</title>'."\n";
    $message .=''."\n";
    $message .=''."\n";
    $message .= $message_text;
    $message .=''."\n";
    $message .='';

    $message_text = "
    Имя заказчика: ".$_GET['user_name']."

    Контактный номер: ".$_GET['user_tel']."

    Адрес доставки: ".$_GET['user_adress']."

    Стоимость заказа: ".$_GET['get_price']." руб.

Заказ:

    Размер: ".$_GET['size_x']."x".$_GET['size_y']."

".$mess;

    // если была нажата кнопка "Отправить"
    if ($_GET['user_name'] AND $_GET['user_tel']){
        if (mail($to, $title, $message_text, $headers)){
            print "
Спасибо!

Ваш заказ отправлен.

Наш менеджер свяжется с Вами в ближайшее время!
";
        }else{
             print "
Извините!

Произошла ошибка при отправке сообщения.
Свяжитесь с администратором сайта!
";
        //print $message_text."
".$_SERVER['REQUEST_URI']."
";
        };
    };
    $i_err="1";

    if (!$_GET['user_name']){
        $error_form .= "
".$i_err++.". Ведите имя!
";};
    if (!$_GET['user_tel']){
        $error_form .= "
".$i_err++.". Ведите номер телефона!
";};

    if ($error_form){
    ?>
Не все заполненно!
<?
    print $error_form;};
?>

A: во первых поменяйте
if (mail($to, $title, $message_text, 'From:'.$headers))

на
if (mail($to, $title, $message_text, $headers))

т.к. $headers уже содержит From:
и в From: должен быть email хотя-бы так:
From: Матрасик <>\r\n

попробуйте
function errorHandler($errno, $errstr, $errfile, $errline) {
    echo "Ошибка: $errno, $errstr, $errfile, $errline
";
}

set_error_handler("errorHandler");
if (mail($to, $title, $message_text, 'From:'.$headers)) {

должно выдать ошибку


text:
Q: warning: incompatible implicit declaration of built-in function 'lrint' I want to compile an opencv program on the Linux machine below:
sav@machine:/shared/sav/test$ uname -a
Linux machine 2.6.32-24-generic #43-Ubuntu SMP Thu Sep 16 14:58:24 UTC 2010 x86_64 GNU/Linux

My gcc command is the following:
gcc -I/shared/sav/opt/include -L/shared/sav/opt/lib -lopencv_core -lopencv_highgui -lopencv_imgproc -lm imagefilter.c -o imagefilter

After I run the program, I have the following warning:
In file included from /shared/sav/opt/include/opencv2/core/core_c.h:47,
from /shared/sav/opt/include/opencv/cv.h:63,
from imagefilter.c:1:
/shared/sav/opt/include/opencv2/core/types_c.h: In function 'cvRound':
/shared/sav/opt/include/opencv2/core/types_c.h:327: warning: incompatible implicit declaration of built-in function 'lrint'

How can I fix this warning?

A: *

*Firstly make sure that you have included the header math.h in your program.

*Use this -std=c99 option along with gcc to resolve this compiler issue.

Change
gcc -I/shared/sav/opt/include -L/shared/sav/opt/lib -lopencv_core -lopencv_highgui -lopencv_imgproc -lm imagefilter.c -o imagefilter

to
gcc -std=c99 -I/shared/sav/opt/include -L/shared/sav/opt/lib -lopencv_core -lopencv_highgui -lopencv_imgproc -lm imagefilter.c -o imagefilter

Refer this for more info on usage of lrint

A: Include the below header file (math.h).Usually this warnings are because of not including the header file where the function is defined.
#include <math.h>


text:
Q: vftable performance penalty vs. switch statement C++ question here.  I have a system where I'm going to have hundreds of mini-subclasses of a given superclass.  They all will have a "foo" method that does something.  Or... I'm going to have one class with an integer called "type" and use a giant switch statement to decide what to do when I foo.
Performance is a huge consideration here.  Extremely important.
The question is, what are the performance benefits/penalties of using a switch statement vs. letting C++ do it via the vftable?  If I have it as a switch statement, I can put the commonly occuring foo's up at the top of the switch statement and the less common ones at the bottom, hopefully shortcutting the comparison.  Trying to get an effect like this with the vftable is bound to be compiler dependent even if I can figure out how to do it...
On the other hand, my code would be a lot easier to deal with without these ugly switch statements.

A: The compiler determines how the switch statements are handled, but there are a few basic techniques they use.

*

*if-else binary-sort: The comparison is done as a series of if-else but in a binary-sort like fashion, performance is thus comparable to lookup in a map of N items

*jump table: if the items are close enough together a table of addresses will be produced. Lookup is then in constant time

Where the case statements are located in the switch statement makes no difference in either case.
Virtual functions have an overhead compared to direct call. It involves an additional offset and pointer lookup. For all but the most extreme performance considerations this cost is negligible. When comparing to a switch the overhead is not in the virtual lookup, but the function call itself. So a switch statement that simply calls functions in each case will perform basically the same as virtual functions.
So essentially the "dispatch semantics" of a switch statement (with jump table) compared to a virtual function call are nearly irrelevant.  If all your "foo" methods are relatively small and can be inlined the switch statement will start to perform better. The other advantage of switch is that you can put common code before the switch and get better register/stack optimizations.
However, there is a significant maintenance overhead. This should be your primary concern at this point.  Why? Because the performance bottle-neck in your code is  not likely the switching login, or even the function calls, but something else. Until you fix that something else there is no point in addressing these low-level performance issues. So stick with whichever provides more maintainable code at the moment.

A: To the other answers here I would add two more.
1) It is more difficult and less common for a compiler to perform classic optimizations (including enregistration) across a virtual function call interface than across case labeled statements in a switch statement in a single function.
2) Any performance difference in the dispatch is highly depedendent on the processor's branch prediction hardware.  Even a virtual function call target address (and return) may be correctly predicted and have negligible performance overhead in the pipeline of a modern out-of-order processor.
If the performance of this operation really matters, you really have to try it both ways and measure it, in the context of the real system.
Happy hacking!

A: There's been some research on this topic in the field of virtual machine design.  Generally, a switch statement is going to be faster, a lot of virtual machines use switch semantics as opposed to virtual lookup.  Theoretically, one would assume that a virtual table - being a constant time algorithm - will be faster, but we have to examine how the hardware sees a virtual table.
A switch statement is easier for the compiler to inline.  This is a huge consideration, the actual act of calling a virtual function is minimal, however, pushing and popping the entire stack frame is necessary because the compiler has no idea which function will be called at run-time.
Branch prediction and hardware prefetch should be easier on a switch statement, although modern architectures are getting better at predicting virtual calls.
A lot of code that uses virtual dispatch requires the use of heap based allocation schemes.  Dynamic memory allocation is a bottleneck in a lot C++ applications.

A:
If I have it as a switch statement, I can put the commonly occuring foo's up at the top of the switch statement and the less common ones at the bottom, hopefully shortcutting the comparison.

A switch statement is generally compiled to a jump table rather than a block of if-else conditionals as your question implies. In practice, the virtual table and the switch jump table should have similar performance, though test if you're really concerned.

A: Vtable should be faster in nearly all cases, but if performance is so critical, the right thing to ask is by how much.
Vtable call is triple indirection (three memory accesses to get the target CALL address). Cache misses should not be an issue if there're many calls. So, it is roughly 2-3 switch label comparisons (though the latter offer even less chance for CPU cache miss, but less for pipe usage).
You should of course not rely on anything I said here, and test it all with true performance measurements on your target architecture.


text:
Q: Python unittest, how to display TestCase's methods' docstring in report? The question title is self-explaining.
Is there a way for
class Foo(TestCase):
  def test_bar(self):
    """
    a docstring
    """

to make the UnitTest report display the whole docstring ?
I've read that the first line of the docstring would be printed (so writing
""" a docstring """

without line breaks works)
I've read the question : How to stop Python unittest from printing test docstring?
However, it's about removing the docstring, and I don't know how to override the shortDescription() to show the full docstring.

A: (I have not tried this)
In the the answer to the SO-linked question, it says

the responsible method is TestCase.shortDescription(), which you can
  override in your testcases.

The source of shortDescription is as follows:
doc = self._testMethodDoc
return doc and doc.split("\n")[0].strip() or None

So you might be able to modify the second line to
return doc

yielding
class MyTests(unittest.TestCase):
    #  ....
    def shortDescription(self):
        doc = self._testMethodDoc
        return doc

If you object to using the undocumented self._testMethodDoc, it is a direct copy of testMethod.__doc__, which is created in TestCase.__init__() via
testMethod = getattr(self, methodName)

There are very few variables for a TestCase. The chance of them being renamed is small, but you might ask the author (from the source, as well):
 47  __author__ = "Steve Purcell"
 48  __email__ = "stephen_purcell at yahoo dot com"


text:
Q: MySQL Add Row on SELECT Query My database structure: (table name is company_info)
 |comp_id | comp_name          | comp_nature
 | 001    | Citigroup, Inc.    | Bank
 | 002    | Harvard University | Academe
 | 003    | Western Union      | Courier
 | 004    | C.I.A.             | Government Agency

I wanted to create a query that would count comp_nature. But if comp_nature IS NOT "Bank" or "Academe", I wanted it to be categorized as "Other", so the result of the query should look something like this..
 | comp_nature       | count |
 | Bank              | 1     |
 | Academe           | 1     |
 | Other             | 2     |

I was able to use the COUNT keyword, but I couldn't seem to get how to create a "row" (Other) in a SELECT statement. (Or is this even possible in just one SELECT statement?).

A: It will be something like this:
select comp_nature, count(*) as cnt from
(
select
 case when comp_nature in('bank','acadme') then comp_nature
 else 'Other' end as comp_nature
from company_info
) as X
group by comp_nature
order by <whatever makes sense>

A: Select
    case
        when comp_nature not in ('Academe', 'Bank') then 'other'
        else comp_nature end as col,
    count(*) from t
group by col