text:
Q: Subclass of Django Model Not Accessible from Superclass I'm trying to create an inherited model in Django like that below. I should be able to call, for an instance superclass = Superclass(), I should be able to call superclass.subclass, and access the requisite fields. When I do that, I'm told that '1 argument was expected, and 8 were given': any idea where I'm going wrong?
class Superclass(models.Model):
        pass

class Subclass(Superclass):
        def __init__(self):
                super(Subclass, self).__init__()

A: The problem here is that you need *args and **kwargs in the subclass constructor and superclass constructor. These two fields will take in the arguments and objects: these include the field information for the superclass, as well as the object manager, among other things. This should do the trick:
class Subclass(Superclass):
    def __init__(self, *args, **kwargs):
            super(Subclass, self).__init__(*args, **kwargs)


text:
Q: Can a bash shell script open a text file with less and then execute less commands from the script? I would like to write a shell script that would call less to open a text file.
less filename.txt

I then would like the script to search forward through the file using /'search string' or search back using ?'search string'. I also want the script to read the results into variables.
I can get a script to call less to open the file , but how do I get bash to call a series of less commands once the file is opened?  Can this be done?

A: I suspect you may be able to do this more easily with awk if you showed us how your file is structured. You would start at the top, and each time you encountered a new book, you would note the book name. Each time you encountered a chapter, you would note the chapter name. Then each time you encountered a word you wanted, you would print the last book, chapter etc that you had seen.
Imagining your file looks something like this:
Book:Book 1
Chapter:Chapter 1
Word word word word
Word word word
Chapter:Chapter 2
Word word interesting word

Then, to find 'interesting'
awk -v x="interesting" -F':' '
    /^Book/    {book=$2}
    /^Chapter/ {chapter=$2}
    $0 ~ x     {print book,chapter,$0} ' OFS=":" YourFile

Untested - as I am on my iPad - but probably pretty close :-)
That says... set the variable x to the word interesting. When reading lines, use colons to separate fields, so everything up to the first colon is field 1 ($1), everything between the first and second colon is field 2 ($2). If you see a line starting with Book, remember the second field in the variable book. If you see a line starting with Chapter, remember the second field in the variable chapter. On any other lines, where the whole line ($0) contains the word interesting, print out the variable book, chapter and the entire current line. Oh, and by the way, separate anything I print out with colons. And do this on a file called YourFile.
You could keep track of the verse number yourself by incrementing it every time you encounter a new line and resetting it to zero every time you encounter a new chapter...
awk -v x="interesting" -F':' '
               {verse++}
    /^Book/    {book=$2}
    /^Chapter/ {chapter=$2;verse=0}
    $0 ~ x     {print book,chapter,verse,$0} ' OFS=":" YourFile

Output:
Book 1:Chapter 2:1:Word word interesting word

A: You can use
less -pbazorka filename.txt

-ppattern or --pattern=pattern
  The -p option on the command line is equivalent to specifying +/pattern; that is, it tells less to start at the first occurrence of pattern in the file.
  — http://linux.die.net/man/1/less

A: You cannot do it with less from within a script. There is no language that would control less once you turn control over to it. In order to do what you want, the easiest way is to use grep. For example, you can read the matching text into an array in bash with:
declare -a results
IFS=$'\n'                                # set IFS to only break on newline
results=( $(grep $srchterm $filename) )  # read results into array
<parse as necessary>

A second option would be to use while read -r line; do... done <<< $(grep $srchterm $filename) to essentially do the same thing.
In either case, this allows you to get the wanted lines of text into variables into your script. You can then further parse the lines into additional variables using pattern matching and substring extraction. If you do not use grep, then your alternative is to read the file line-by-line and manually search for the text of interest. grep simply automates the search part of the process for you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I remove the rest of a string after a character in a dataframe column? I have a dataframe that contains userdata. There is a column that includes filenames that users have accessed. The filenames look like this:
blah-blah-blah/dss_outline.pdf
doot-doot/helper_doc.pdf
blah-blah-blah/help_file.pdf

My goal is to chop off everything after and including the / so that I can just look at the top-level programs people are examining (which the numerous different files are organized under).
So, I'm having two challenges:
1 - How do I 'grab' everything up to the '/'? I've been looking at regex, but I'm having a hard time writing the correct expression.
2 - How do I replace all of the filenames with the concatenated filename? I found that I could use df['Filename'] = df['Filename'].str.split('/')[0] to grab the proper portion, but it won't apply across the series object. That's the logic of what I want to do, but I can't figure out how to do it.
Thanks

A: You may use \/.*$ to match the part you don't need and remove it: DEMO
This matches a forward slash and any following character till the end of the string (be careful to use a multiline flag if your engine needs it!).
OR you may use ^[^/]+ to match the part you want and extract it: DEMO
This matches any consecutive characters except / from the beginning of a string (again, multiline needed!).

A: You have lot of solutions handy:
1) Just with split() method:
>>> df
                             col1
0  blah-blah-blah/dss_outline.pdf
1        doot-doot/helper_doc.pdf
2    blah-blah-blah/help_file.pdf

>>> df['col1'].str.split('/', 1).str[0].str.strip()
0    blah-blah-blah
1         doot-doot
2    blah-blah-blah

Name: col1, dtype: object
2) You can use apply() + split()
>>> df['col1'].apply(lambda s: s.split('/')[0])
0    blah-blah-blah
1         doot-doot
2    blah-blah-blah
Name: col1, dtype: object

3) You can use rsplit() + str[0] to strip off the desired:
>>> df['col1'].str.rsplit('/').str[0]
0    blah-blah-blah
1         doot-doot
2    blah-blah-blah
Name: col1, dtype: object

4) You can use pandas native regex With extract():
>>> df['col1'] = df['col1'].str.extract('([^/]+)')
>>> df
             col1
0  blah-blah-blah
1       doot-doot
2  blah-blah-blah

OR
# df.col1.str.extract('([^/]+)')

A: Use df.replace
df.replace('\/.*$','',regex=True)

              col
0  blah-blah-blah
1       doot-doot
2  blah-blah-blah

A: Use series.apply():
>>> import pandas
>>> data = {'filename': ["blah-blah-blah/dss_outline.pdf", "doot-doot/helper_doc.pdf", "blah-blah-blah/help_file.pdf"]}
>>> df = pandas.DataFrame(data=data)
>>> df
                         filename
0  blah-blah-blah/dss_outline.pdf
1        doot-doot/helper_doc.pdf
2    blah-blah-blah/help_file.pdf
>>> def get_top_level_from(string):
...     return string.split('/')[0]
...
>>> series = df["filename"]
>>> series
0    blah-blah-blah/dss_outline.pdf
1          doot-doot/helper_doc.pdf
2      blah-blah-blah/help_file.pdf
Name: filename, dtype: object
>>> series.apply(get_top_level_from)
0    blah-blah-blah
1         doot-doot
2    blah-blah-blah
Name: filename, dtype: object

Code:
def get_top_level_from(string):
    return string.split('/')[0]

results = df["filename"].apply(get_top_level_from)


text:
Q: CakePHP - Controller Delete Action does not receive Post Data I seem to have run into an issue in which my controller is not receiving the post data being sent to it via the postLink form helper.
I have multiple controllers, all of which seem to run OK with this action, however, this specific one will not.
I have attempted to debug, and have found that the Delete action does not seem to be receiving any Post data.
View postLink code:
echo $this->Form->postLink(__('Delete'), array('controller' => 'tokens', 'action' => 'delete', $data['token']['id']), null, __('Are you sure you want to delete this data?'));

Controller code:
public function delete($id = null) {
    $this->request->allowMethod(['post', 'delete']);

    if (!$this->request->is('post')) {
       throw new MethodNotAllowedException();
    }

    $this->Token->id = $id;
    if (!$this->Token->exists()) {
       throw new NotFoundException(__('Invalid Token'));
    }

    if ($this->Token->delete()) {
        $this->Session->setFlash(__('The token has been deleted.'));
    } else {
        $this->Session->setFlash(__('The token could not be deleted. Please, try again.'));
    }

    $this->redirect(array('controller' => 'accounts', 'action' => 'addToken'));
}

I'm really not sure where I'm going wrong or what could be causing it, I've been racking my brain and testing different theories all day but nothing seems to change.  All componenets, helpers, etc. are loaded in the same manner the other controllers.
Any help is greatly appreciated!
(CakePHP Version 2.6.2)
EDIT
It looks like there is something going on with a session redirect, in which Cake is redirecting me to /accounts/users/sessionStatus.
I'm have no idea why this is happening.
EDIT
After further digging, I have noticed that when I enter the URl directly into the address bar, everything works as expected, however, clicking the link that was generated by the postLink method prevents the post data from being available.
I'm open to any suggestions/questions/help, this is driving me crazy!

A: After 8 long hours, I finally determined the cause.
The javascript function handling the form is treating a zero (0) as a null so while the var exists and isset, no value is being passed.
If someone knows/understands more about this, please share!


text:
Q: Ordenação de todos os elementos de uma matriz (array) multidimensional Preciso ordenar o array abaixo em ordem alfabética usando a chave numérica:
Array
(
    [AM] => Array
        (
            [1] => Array
                (
                    [localidade] => Arena da Amazonia
                    [cidade] => MANAUS
                    [estado] => Amazonia
                    [acronym] => AM
                )

            [2] => Array
                (
                    [localidade] => Ponto de Apoio
                    [cidade] => MANAUS
                    [estado] => Amazonia
                    [acronym] => AM
                )

        )

    [BA] => Array
        (
            [4] => Array
                (
                    [localidade] => Arena Fonte Nova
                    [cidade] => SALVADOR
                    [estado] => Bahia
                    [acronym] => BA
                )

            [3] => Array
                (
                    [localidade] => Ponto de Apoio
                    [cidade] => SALVADOR
                    [estado] => Bahia
                    [acronym] => BA
                )

        )

    [DF] => Array
        (
            [7] => Array
                (
                    [localidade] => Estádio Mané Garrincha
                    [cidade] => BRASILIA
                    [estado] => Distrito Federal
                    [acronym] => DF
                )

            [8] => Array
                (
                    [localidade] => Ponto de Apoio
                    [cidade] => BRASILIA
                    [estado] => Distrito Federal
                    [acronym] => DF
                )

        )

    [MG] => Array
        (
            [10] => Array
                (
                    [localidade] => Mineirão
                    [cidade] => BELO HORIZONTE
                    [estado] => Minas Gerais
                    [acronym] => MG
                )

            [9] => Array
                (
                    [localidade] => Ponto de Apoio
                    [cidade] => BELO HORIZONTE
                    [estado] => Minas Gerais
                    [acronym] => MG
                )

            [6] => Array
                (
                    [localidade] => Estádio Mané Garrincha
                    [cidade] => BRASILIA
                    [estado] => Belo Horizonte
                    [acronym] => MG
                )

            [5] => Array
                (
                    [localidade] => Ponto de Apoio
                    [cidade] => CONFINS
                    [estado] => Belo Horizonte
                    [acronym] => MG
                )

        )

    [RJ] => Array
        (
            [24] => Array
                (
                    [localidade] => Ponto de Apoio
                    [cidade] => NITEROI
                    [estado] => Rio de Janeiro
                    [acronym] => RJ
                )

            [15] => Array
                (
                    [localidade] => Ponto de Apoio
                    [cidade] => NOVA IGUACU
                    [estado] => Rio de Janeiro
                    [acronym] => RJ
                )

            [18] => Array
                (
                    [localidade] => Barra - Centro de Golfe
                    [cidade] => RIO DE JANEIRO
                    [estado] => Rio de Janeiro
                    [acronym] => RJ
                )

            [19] => Array
                (
                    [localidade] => Barra - Parque olimpico
                    [cidade] => RIO DE JANEIRO
                    [estado] => Rio de Janeiro
                    [acronym] => RJ
                )

            [21] => Array
                (
                    [localidade] => Barra - Parque olimpico e Copacabana - Forte de Copacabana
                    [cidade] => RIO DE JANEIRO
                    [estado] => Rio de Janeiro
                    [acronym] => RJ
                )

            [17] => Array
                (
                    [localidade] => Barra - Pontal
                    [cidade] => RIO DE JANEIRO
                    [estado] => Rio de Janeiro
                    [acronym] => RJ
                )

            [20] => Array
                (
                    [localidade] => Barra - Rio Centro
                    [cidade] => RIO DE JANEIRO
                    [estado] => Rio de Janeiro
                    [acronym] => RJ
                )

            [28] => Array
                (
                    [localidade] => Barra / Copacabana e Maracanã
                    [cidade] => RIO DE JANEIRO
                    [estado] => Rio de Janeiro
                    [acronym] => RJ
                )

            [12] => Array
                (
                    [localidade] => Copacabana - Arena do Volei
                    [cidade] => RIO DE JANEIRO
                    [estado] => Rio de Janeiro
                    [acronym] => RJ
                )

            [11] => Array
                (
                    [localidade] => Copacabana - Estadio da Lagoa
                    [cidade] => RIO DE JANEIRO
                    [estado] => Rio de Janeiro
                    [acronym] => RJ
                )

            [23] => Array
                (
                    [localidade] => Copacabana - Forte de Copacabana
                    [cidade] => RIO DE JANEIRO
                    [estado] => Rio de Janeiro
                    [acronym] => RJ
                )

            [13] => Array
                (
                    [localidade] => Copacabana - marina da Glória
                    [cidade] => RIO DE JANEIRO
                    [estado] => Rio de Janeiro
                    [acronym] => RJ
                )

            [25] => Array
                (
                    [localidade] => Deodoro - Centro de Tiro / Estadio Olimpico / Centro Hoquei / Centro Aquatico / Arena da Juventude / Hipismo / Parque Radical
                    [cidade] => RIO DE JANEIRO
                    [estado] => Rio de Janeiro
                    [acronym] => RJ
                )

            [22] => Array
                (
                    [localidade] => Maracana - Estádio Olimpico
                    [cidade] => RIO DE JANEIRO
                    [estado] => Rio de Janeiro
                    [acronym] => RJ
                )

            [26] => Array
                (
                    [localidade] => Maracanã - Maracanazinho / Maracanã
                    [cidade] => RIO DE JANEIRO
                    [estado] => Rio de Janeiro
                    [acronym] => RJ
                )

            [16] => Array
                (
                    [localidade] => Maracana - Maracanazinho/Maracana
                    [cidade] => RIO DE JANEIRO
                    [estado] => Rio de Janeiro
                    [acronym] => RJ
                )

            [27] => Array
                (
                    [localidade] => Maracana - Sambodromo
                    [cidade] => RIO DE JANEIRO
                    [estado] => Rio de Janeiro
                    [acronym] => RJ
                )

            [14] => Array
                (
                    [localidade] => Ponto de Apoio
                    [cidade] => RIO DE JANEIRO
                    [estado] => Rio de Janeiro
                    [acronym] => RJ
                )

        )

    [SP] => Array
        (
            [30] => Array
                (
                    [localidade] => Ponto de Apoio
                    [cidade] => GUARULHOS
                    [estado] => São Paulo
                    [acronym] => SP
                )

            [29] => Array
                (
                    [localidade] => Arena Corinthians
                    [cidade] => SAO PAULO
                    [estado] => São Paulo
                    [acronym] => SP
                )

            [31] => Array
                (
                    [localidade] => Ponto de Apoio
                    [cidade] => SAO PAULO
                    [estado] => São Paulo
                    [acronym] => SP
                )

        )

)

A saída deve ser mais ou menos assim:
array (
                              'AM' => array (
                                1 => array (
                                  'cidade' => 'MANAUS',
                                  'estado' => 'Amazonia',
                                  'acronym' => 'AM',
                                  'localidade' => 'Arena da Amazonia',
                                ),
                                2 => array (
                                  'cidade' => 'MANAUS',
                                  'estado' => 'Amazonia',
                                  'acronym' => 'AM',
                                  'localidade' => 'Ponto de Apoio',
                                ),
                              ),
                              'BA' => array (
                                3 => array (
                                  'cidade' => 'SALVADOR',
                                  'estado' => 'Bahia',
                                  'acronym' => 'BA',
                                  'localidade' => 'Ponto de Apoio',
                                ),
                                4 => array (
                                  'cidade' => 'SALVADOR',
                                  'estado' => 'Bahia',
                                  'acronym' => 'BA',
                                  'localidade' => 'Arena Fonte Nova ',
                                ),
                              ),
                              'DF' => array (
                                5 => array (
                                  'cidade' => 'BRASILIA',
                                  'estado' => 'Belo Horizonte',
                                  'acronym' => 'DF',
                                  'localidade' => 'Estádio Mané Garrincha',
                                ),
                                6 => array (
                                  'cidade' => 'BRASILIA',
                                  'estado' => 'Distrito Federal',
                                  'acronym' => 'DF',
                                  'localidade' => 'Estádio Mané Garrincha',
                                ),
                                7 => array (
                                  'cidade' => 'BRASILIA',
                                  'estado' => 'Distrito Federal',
                                  'acronym' => 'DF',
                                  'localidade' => 'Ponto de Apoio',
                                ),
                              ),
                              'MG' => array (
                                8 => array (
                                  'cidade' => 'CONFINS',
                                  'estado' => 'Belo Horizonte',
                                  'acronym' => 'MG',
                                  'localidade' => 'Ponto de Apoio',
                                ),
                                9 => array (
                                  'cidade' => 'BELO HORIZONTE',
                                  'estado' => 'Minas Gerais',
                                  'acronym' => 'MG',
                                  'localidade' => 'Ponto de Apoio',
                                ),
                                10 => array (
                                  'cidade' => 'BELO HORIZONTE',
                                  'estado' => 'Minas Gerais',
                                  'acronym' => 'MG',
                                  'localidade' => 'Mineirão',
                                ),
                              ),
                              'RJ' => array (
                                11 =>  array (
                                  'cidade' => 'RIO DE JANEIRO',
                                  'estado' => 'Rio de Janeiro',
                                  'acronym' => 'RJ',
                                  'localidade' => 'Copacabana - Estadio da Lagoa',
                                ),
                                12 => array (
                                  'cidade' => 'RIO DE JANEIRO',
                                  'estado' => 'Rio de Janeiro',
                                  'acronym' => 'RJ',
                                  'localidade' => 'Copacabana - Arena do Volei',
                                ),
                                13 => array (
                                  'cidade' => 'RIO DE JANEIRO',
                                  'estado' => 'Rio de Janeiro',
                                  'acronym' => 'RJ',
                                  'localidade' => 'Copacabana - marina da Glória',
                                ),
                                14 => array (
                                  'cidade' => 'RIO DE JANEIRO',
                                  'estado' => 'Rio de Janeiro',
                                  'acronym' => 'RJ',
                                  'localidade' => 'Ponto de Apoio',
                                ),
                                15 => array (
                                  'cidade' => 'NOVA IGUACU',
                                  'estado' => 'Rio de Janeiro',
                                  'acronym' => 'RJ',
                                  'localidade' => 'Ponto de Apoio',
                                ),
                                16 => array (
                                  'cidade' => 'RIO DE JANEIRO',
                                  'estado' => 'Rio de Janeiro',
                                  'acronym' => 'RJ',
                                  'localidade' => 'Maracana - Maracanazinho/Maracana',
                                ),
                                17 => array (
                                  'cidade' => 'RIO DE JANEIRO',
                                  'estado' => 'Rio de Janeiro',
                                  'acronym' => 'RJ',
                                  'localidade' => 'Barra - Pontal',
                                ),
                                18 => array (
                                  'cidade' => 'RIO DE JANEIRO',
                                  'estado' => 'Rio de Janeiro',
                                  'acronym' => 'RJ',
                                  'localidade' => 'Barra - Centro de Golfe',
                                ),
                                19 => array (
                                  'cidade' => 'RIO DE JANEIRO',
                                  'estado' => 'Rio de Janeiro',
                                  'acronym' => 'RJ',
                                  'localidade' => 'Barra - Parque olimpico',
                                ),
                                20 => array (
                                  'cidade' => 'RIO DE JANEIRO',
                                  'estado' => 'Rio de Janeiro',
                                  'acronym' => 'RJ',
                                  'localidade' => 'Barra - Rio Centro',
                                ),
                                21 => array (
                                  'cidade' => 'RIO DE JANEIRO',
                                  'estado' => 'Rio de Janeiro',
                                  'acronym' => 'RJ',
                                  'localidade' => 'Barra - Parque olimpico e Copacabana - Forte de Copacabana',
                                ),
                                22 => array (
                                  'cidade' => 'RIO DE JANEIRO',
                                  'estado' => 'Rio de Janeiro',
                                  'acronym' => 'RJ',
                                  'localidade' => 'Maracana - Estádio Olimpico',
                                ),
                                23 => array (
                                  'cidade' => 'RIO DE JANEIRO',
                                  'estado' => 'Rio de Janeiro',
                                  'acronym' => 'RJ',
                                  'localidade' => 'Copacabana - Forte de Copacabana',
                                ),
                                24 => array (
                                  'cidade' => 'NITEROI',
                                  'estado' => 'Rio de Janeiro',
                                  'acronym' => 'RJ',
                                  'localidade' => 'Ponto de Apoio',
                                ),
                                25 => array (
                                  'cidade' => 'RIO DE JANEIRO',
                                  'estado' => 'Rio de Janeiro',
                                  'acronym' => 'RJ',
                                  'localidade' => 'Deodoro - Centro de Tiro / Estadio Olimpico / Centro Hoquei / Centro Aquatico / Arena da Juventude / Hipismo / Parque Radical',
                                ),
                                26 => array (
                                  'cidade' => 'RIO DE JANEIRO',
                                  'estado' => 'Rio de Janeiro',
                                  'acronym' => 'RJ',
                                  'localidade' => 'Maracanã - Maracanazinho / Maracanã',
                                ),
                                27 => array (
                                  'cidade' => 'RIO DE JANEIRO',
                                  'estado' => 'Rio de Janeiro',
                                  'acronym' => 'RJ',
                                  'localidade' => 'Maracana - Sambodromo',
                                ),
                                28 => array (
                                  'cidade' => 'RIO DE JANEIRO',
                                  'estado' => 'Rio de Janeiro',
                                  'acronym' => 'RJ',
                                  'localidade' => 'Barra / Copacabana e Maracanã',
                                ),
                              ),
                              'SP' => array (
                                29 =>
                                array (
                                  'cidade' => 'SAO PAULO',
                                  'estado' => 'São Paulo',
                                  'acronym' => 'SP',
                                  'localidade' => 'Arena Corinthians',
                                ),
                                30 =>
                                array (
                                  'cidade' => 'GUARULHOS',
                                  'estado' => 'São Paulo',
                                  'acronym' => 'SP',
                                  'localidade' => 'Ponto de Apoio',
                                ),
                                31 =>
                                array (
                                  'cidade' => 'SAO PAULO',
                                  'estado' => 'São Paulo',
                                  'acronym' => 'SP',
                                  'localidade' => 'Ponto de Apoio',
                                ),
                             ),
                        );

Tentei estes métodos e nenhum funcionou:
public function arraySortByColumn(&$arr, $col, $dir = SORT_ASC)
    {
        $sort_col = array();
        foreach ($arr as $key=> $row) {
            $sort_col[$key] = $row[$col];
        }
        array_multisort($sort_col, $dir, $arr);
    }

    public function findMultiIfArray($array, $field, $value)
    {
        while(isset($array[key($array)])){
            if(strpos($array[key($array)][$field], $value) !== false){
                return key($array);
            }
            next($array);
        }
        return -1;
    }

    public function sortKeyLocality($a, $b)
    {
        if ($a['localidade'] == $b['localidade']) {
            return 0;
        }
        return ($a['localidade'] < $b['localidade']) ? -1 : 1;
    }

    function arraySort($array, $on, $order=SORT_ASC){

        $new_array = array();
        $sortable_array = array();

        if (count($array) > 0) {
            foreach ($array as $k => $v) {
                if (is_array($v)) {
                    foreach ($v as $k2 => $v2) {
                        if ($k2 == $on) {
                            $sortable_array[$k] = $v2;
                        }
                    }
                } else {
                    $sortable_array[$k] = $v;
                }
            }

            switch ($order) {
                case SORT_ASC:
                    asort($sortable_array);
                    break;
                case SORT_DESC:
                    arsort($sortable_array);
                    break;
            }

            foreach ($sortable_array as $k => $v) {
                $new_array[$k] = $array[$k];
            }
        }

        return $new_array;
    }

    public function arraySortByColumnRecursive(&$arr, $col, $dir = SORT_ASC) {
        $sort_col = array();
        foreach ($arr as $key=> $row) {
            if (is_array($row)) {
                $sort_col[$key] = $row[$col];
                $this->arraySortByColumnRecursive($row, $col, $dir);
            }
        }
        array_multisort($sort_col, $dir, $arr);
    }

Para auxiliar outras pessoas, vou colocar aqui, o método que fiz para trazer a lista desse select optgroup:

public function collectionLocais($collection)
    {
        $ufs = array("AC","AL","AM","AP","BA","CE","DF","ES","GO","MA","MT","MS","MG","PA","PB","PR","PE","PI","RJ","RN","RO","RS","RR","SC","SE","SP","TO");
        $ufs = array_values(array_map('current', $ufs));
        foreach ($ufs as $uf) {
            foreach($collection as $k => $local) {
                if ($uf == $local['uf']) {
                    $new_collection[$uf][$local['id']] = array(
                        'localidade' => $local['locality'],
                        'cidade' => $local['city'],
                        'estado' => $local['state'],
                        'acronym' => $uf
                    );

                }

            }
        }
         return $new_collection;
    }

A: Com ksort:
Array testado:
$array = array(
    'AM' => array(
        2 => array(
            'localidade' => '1Arena da Amazonia',
            'cidade' => 'MANAUS',
            'estado' => 'Amazonia',
            'acronym' => 'AM',
        ),
        1 => array(
            'localidade' => '2Arena da Amazonia',
            'cidade' => 'MANAUS',
            'estado' => 'Amazonia',
            'acronym' => 'AM',
        ),
    ),
    'BA' => array(
        5 => array(
            'localidade' => '3Arena da Amazonia',
            'cidade' => 'MANAUS',
            'estado' => 'Amazonia',
            'acronym' => 'AM',
        ),
        3 => array(
            'localidade' => '4Arena da Amazonia',
            'cidade' => 'MANAUS',
            'estado' => 'Amazonia',
            'acronym' => 'AM',
        ),
        '4' => array(
            'localidade' => '5Arena da Amazonia',
            'cidade' => 'MANAUS',
            'estado' => 'Amazonia',
            'acronym' => 'AM',
        ),
    ),
    'DF' => array(
        7 => array(
            'localidade' => '6Arena da Amazonia',
            'cidade' => 'MANAUS',
            'estado' => 'Amazonia',
            'acronym' => 'AM',
        ),
        '8' => array(
            'localidade' => '7Arena da Amazonia',
            'cidade' => 'MANAUS',
            'estado' => 'Amazonia',
            'acronym' => 'AM',
        ),
        6 => array(
            'localidade' => '8Arena da Amazonia',
            'cidade' => 'MANAUS',
            'estado' => 'Amazonia',
            'acronym' => 'AM',
        ),
        9 => array(
            'localidade' => 'zzzz9 da Amazonia',
            'cidade' => 'MANAUS',
            'estado' => 'Amazonia',
            'acronym' => 'AM',
        ),
    ),
);

Ordenação:
foreach($array as $key => $arr) {
    ksort($arr);
    $array[$key] = $arr;
}
ksort($array);
echo '<pre>', print_r($array), '</pre>';

A: Nos comentários foi citado o método asort(), porém ele ordena por valor, no seu caso, como a ordenação é feita por chave então deveria usar o ksort(), que tem o mesmo objetivo, porém ordena por chaves, ficaria assim:
<?php
// array
$data =
    array
    (
        'BA' => array
        (
            4 => array
            (
                'localidade' => 'Arena Fonte Nova',
                'cidade' => 'SALVADOR',
                'estado' => 'Bahia',
                'acronym' => 'BA'
            ),
            3 => array
            (
                'localidade' => 'Ponto de Apoio',
                'cidade' => 'SALVADOR',
                'estado' => 'Bahia',
                'acronym' => 'BA',
            )

        ),
        'AM' => array
        (
            2 => array
            (
                'localidade' => 'Arena da Amazonia',
                'cidade' => 'MANAUS',
                'estado' => 'Amazonia',
                'acronym' => 'AM'
            ),
            1 => array
            (
                'localidade' => 'Ponto de Apoio',
                'cidade' => 'MANAUS',
                'estado' => 'Amazonia',
                'acronym' => 'AM'
            )
        )
    );

   // resultado será o array normal
    var_dump($data);

    ksort($data);

    foreach($data as $key => $value)
    {
        ksort($data[$key]);
    }

    var_dump($data);

A saída do array ordenado será:
array (size=2)
  'AM' =>
    array (size=2)
      1 =>
        array (size=4)
          'localidade' => string 'Ponto de Apoio' (length=14)
          'cidade' => string 'MANAUS' (length=6)
          'estado' => string 'Amazonia' (length=8)
          'acronym' => string 'AM' (length=2)
      2 =>
        array (size=4)
          'localidade' => string 'Arena da Amazonia' (length=17)
          'cidade' => string 'MANAUS' (length=6)
          'estado' => string 'Amazonia' (length=8)
          'acronym' => string 'AM' (length=2)
  'BA' =>
    array (size=2)
      3 =>
        array (size=4)
          'localidade' => string 'Ponto de Apoio' (length=14)
          'cidade' => string 'SALVADOR' (length=8)
          'estado' => string 'Bahia' (length=5)
          'acronym' => string 'BA' (length=2)
      4 =>
        array (size=4)
          'localidade' => string 'Arena Fonte Nova' (length=16)
          'cidade' => string 'SALVADOR' (length=8)
          'estado' => string 'Bahia' (length=5)
          'acronym' => string 'BA' (length=2)

Veja: Ordenando array na documentação do PHP para ver uma tabela com todos métodos de ordenação e sua função.


text:
Q: Stack memory inside the Linux kernel I recently tried to imagine how stack memory is probably dealt with inside the Linux kernel but could not come up with anything solid. I know the kernel uses its own functions for dynamic memory management but I have no idea how it manages just normal C stack memory because after all, that can be implemented with normal C and compiled with normal GCC. As far as I have it, stack memory allocation is normally dealt with by a form of libc when dealing with operating systems and even on something like AVR. As far as I have it though the Linux kernel does not depend on libc?
I am not entirely sure how stack memory management is delegated to libc in the first place though as it appears to be a built in language feature. All that I can imagine is that it is somehow generically compiled (or implemented) so that a provider can be assigned either afterwards or possibly as part of the compilation process. Could someone please shed some light on this for me?

A: stack memory is allocated (the whole stack) during the link step.
The stack memory is (normally) placed in the .stack segment (which is nothing more than an offset and length, with no contents).
The .startup code (usually a assembly function in some library, I'm not sure which library) finds the name of the .stack section within the loaded code, adds the length value to get the top address of the stack (stacks grow downward) and (amongst several other operations) sets the sp and bp registers.
When the OS is running (I.E. not in 'user' mode) it (typically) has its' own stack space and uses its' own values for the sp and bp registers.
The switching between the 'user' mode and 'privileged' mode and the swapping of register values is handled in the transitions between what you wrote and the code in the kernel.
Most of this kind of switching is handled in the wrapper functions in the libc library and the resulting control transitions through a table of jumps into kernel routines.
Note:  other CPUs and OSs have differing details about how things are accomplished, but the results are very similar.

A: A stack can be any block of read/write memory. There is nothing special about a stack. An operating system creates a stack—i.e., it allocates the memory and assigns it location to the stack pointer register—because one is needed to start the a process, but it does not manage the stack.
In unix-land, running a program is a two step process. First, you clone the a parent process. Thus, the new process has the same stack setup as the parent.
Finally, you execute the program. The program load gets the desired stack size from the executable file which in turn gets the information from the linker (see the "stack" option for the ld command, for example).
After starting up, an application could call a system service to allocate pages of memory and have the stack pointer register reference that. Then that becomes the program stack.
Keep in mind that this all refers to the USER stack. The operating system maintains a KERNEL stack for each process that it uses for its own purposes.

A:
As far as I have it, stack memory allocation is normally dealt with by
  a form of libc …

This program illustrates that nothing from libc is used for stack memory allocation:
// compile with: gcc -nostdlib nolibc.c -o nolibc
_start()
{
    int a[9999];
    *a = 0;
    asm("   mov %0,%%ebx\n\
            mov $1,%%eax\n\
            int $128" : : "r" (*a));    // _exit(*a);
}

If the allocated stack space is exceeded, a fault occurs and the kernel's fault handler can allocate more space, unless there is a limit reached or a fixed size used.


text:
Q: How to replace mail adresses in table input column with Pentaho I'm quite new to PDI and currently facing a challenge where I have to replace mail adresses read from the email column of an incoming table (extracted by the Table Input step in Kettle) with other mail adresses.
e.g. user.test@example.com should become abc[seq. number]@example.com.
The goal is to "anonymize" the incoming adresses for further work with the data.
I currently have no solution for this and am hoping you guys have one. :-)
Thank you!

A: There exists a "Replace in String" step under the "Transform" section exactly for your case.
Nevertheless, I recommend you to read some documentation first.

A: I solved it. I just took the long way with adding constants, sequences and concatenating eventually.

A: You can implement a Java class, or you can do the following, after the table entry, you create a sequence, then with the step, split rows you process the mail, takes as delimiter the @, in the configuration of the step you create two fields, One that will contain the initial part of the email and the other with the domain (gmail.com for example), then take the field of the sequence you created earlier, concatenate it with a constant @ (in the split rows you lose the symbol), And concatenate with field of the domain, in the end you will get 1@gmail.com, 2@hotmail.com, ect.solo are 4 steps I hope it helps you, greetings


text:
Q: How to associate forums & forum posts with the menu structure in Drupal 7 I've created a members area using organic groups.
This group has a submenu using the menu block module which displays a link to my private forum
How can I get the forum topics to be linked into the menu structure so that when I click into a forum post the submenu stays there. (It dissapears because the forum post isn't in the menu tree)
I could do achieve this by setting a menu link and adding 'forum' as the parent each time, but this is not a suitable solution.
Thanks.

A: Maybe module Reference with autocomplet or select forum topic? But this is not clean solution


text:
Q: Accessing information in [AnyHashable : Any] as NSDictionary I am in the process of converting my code from Objective C to Swift. I have a code the calls an objective C method from a swift method. The obj C method returns an NSDictionary. Apparently Swift see this object as a type [AnyHashable : Any]. How do I read the information for this type? For example for a NSDictionary I would say NSString *s = [dict objectForKey:"key"]. What do I call in Swift to access the value in type [AnyHashable : Any]?
Thanks

A: try to use code below to unwrap your result:
if let dict = dict as NSDictionary? as! [String:Any]? {
  print(dict[key])
}

A: Regarding AnyHashable, if you'll look at the documentation they give an example:
let descriptions: [AnyHashable: Any] = [
    AnyHashable(""): "emoji",
    AnyHashable(42): "an Int",
    AnyHashable(Int8(43)): "an Int8",
    AnyHashable(Set(["a", "b"])): "a set of strings"
]
print(descriptions[AnyHashable(42)]!)      // prints "an Int"

In my case I was parsing the response headers from a website so I had a key which was a string and the value was another JSON object.
The solution was straightforward, using the above syntax to obtain the entire object and cast it to string and use JSONSerialization to map it to a [String : Any] type:
if let jsonString = payload[AnyHashable("Key")] as? String,
   let data = jsonString.data(using: .utf8) {
   do {
       if let json = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [String : Any] {
           // json is now a [String : Any] type
   }
       else {
              print("JSON is invalid")
       }
      }
    catch {
           print("Exception converting: \(error)")
    }
}

A: You can use subscripts as in Objective-C.
Swift:
let s = dict["key"]

Objective-C:
NSString *s = dict["key"] //is equivalent to [dict objectForKey:"key"]

A: You can get like this:
let strShareLink = dict["key"] as! String

in swift
Hope, others will get help from this


text:
Q: how to change colour of arrow in uitableview I want that the arrow of Tablecell is visible permanently. currently it is visible only on selection.
secondly i want to change its colour from white to orrange.
How i will do this.
Regards
Nauman k

A: You can find your answer here:
Which is the best way to change the color/view of disclosure indicator accessory view in a table view cell in iOS?


text:
Q: Сколько максимально одновременных подключений может держать сервер? В стать https://habrahabr.ru/post/50028/ говориться что были сервера способные держать 1 000 000 пользователей. А как такое возможно если портов всего 2^16?

A: Соединение характеризуется следующей конструкцией из 5 элементов:
IP клиента, Порт клиента, IP сервера, Порт сервера, Протокол

Например:
10.0.0.1:1234 192.168.0.1:80 TCP
10.0.0.1:1235 192.168.0.1:80 TCP
10.0.0.1:1236 192.168.0.1:80 TCP
...
10.0.0.2:1234 192.168.0.1:80 TCP
10.0.0.2:1235 192.168.0.1:80 TCP
10.0.0.2:1236 192.168.0.1:80 TCP
...

Последние 3 элемента имеют фиксированное значение, а вот первые 2 изменяются и в комбинации могут давать огромные значения. С одного IP может подключиться до 64k клиентов, с другого ещё столько же и т.д. Таким образом, теоретическое максимальное число соединений может быть равно число клиентских IP адресов * число портов на клиенте (64k).
С практической же точки зрения, ресурсы сервера (RAM, CPU, I/O) ограничены, и в зависимости от реализации сервера, он может обрабатывать лишь какое-то N-ное число одновременных соединений, которое меньше теоретического IP*64k.
Чем эффективнее написан сервер (т.е. чем эффективнее он использует ограниченные ресурсы железа), тем больше соединений он сможет держать. Самые неэффективные реализации создают по процессу на каждое входящее соединение, более эффективные используют один процесс и создают по потоку (thread) на соединение, а ещё более эффективные умеют обходиться фиксированным числом процессов и потоков, выполняя асинхронную обработку запросов.

A: Порты не имеют никакого отношения к одновременному колличеству подключений. Порт - это просто место, куда приходит запрос\подключение. Что именно обработает запрос на этот порт - вот это уже важно. И там говорится не про сервера, а про функциональный язык программирования Erlang, на котором можно написать проект, максимально задействующий ресурсы машины, что в свою очередь может дать до миллиона одновременных коннектов.
Итак, ответ на ваш вопрос - дело вообще не в портах.


text:
Q: Swift - Get iBeacon - external class I have built a class that should receive ibeacons.
As far as I know, I'm doing everything right. But it doesn't work.
My App doesn't ask for location permissions and the location manager doesn't start updating.
I have also set the attributes in the plist.
NSLocationWhenInUseUsageDescription
NSLocationAlwaysUsageDescription
It only works when I initialize everything right in the AppDelegate.
As in the tutorial here.
http://ibeaconmodules.us/blogs/news/14702963-tutorial-swift-based-ibeacon-app-development-with-corelocation-on-apple-ios-7-8
But I want to outsource this Service to a class.
I don't know what I'm doing wrong. I'm new with Swift, in Objective-C it has always worked.
Can anyone help me?
Here The Code-
ViewController
import UIKit
class ViewController: UIViewController,BeaconServiceProtocolDelegate {
override func viewDidLoad() {
    super.viewDidLoad()

    //Set BackgroundImage and hide Navigationbar
    self.view.backgroundColor = UIColor(patternImage: UIImage(named:"bg"));
    self.navigationController?.navigationBar.hidden = true

     ////////////////////////create new Beacon Service which is looking for beacon which are given with the parameters
    var beaconAdvertiseService = BeaconService(parauuidString: "F0018B9B-7509-4C31-A905-1A27D39C003C",parabeaconIdentifier:"iBeaconTalentTeamAudi");
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}

//Notification if our service found a beacon
func sendLocalNotificationWithMessage(message: String!) {
    let notification:UILocalNotification = UILocalNotification()
    notification.alertBody = message
    UIApplication.sharedApplication().scheduleLocalNotification(notification)
}

//Delegate from BeaconService
func foundBeacon() {
    println("Found Beacon")
}

}
and of course the class - BeaconAdvertiseService
import Foundation
import CoreBluetooth
import CoreLocation

//BeaconService Delegate
protocol BeaconServiceProtocolDelegate
{
    func foundBeacon()
}

import Foundation
import CoreBluetooth
import CoreLocation

//BeaconService Delegate
protocol BeaconServiceProtocolDelegate
{
    func foundBeacon()
}

class BeaconService: NSObject, CLLocationManagerDelegate{

    let beaconServiceDelegate:BeaconServiceProtocolDelegate?

    let uuidString:String//UUID Beacon as String
    let beaconIdentifier:String//Identifier Beacon
    let beaconUUID:NSUUID//UUID Beacon
    let beaconRegion:CLBeaconRegion//Beacon Region
    let locationManager:CLLocationManager ////location manager

     ////////////////////////Init class (constructor) // Params UUID as String & and Identifier from beacon
    init(parauuidString:String,parabeaconIdentifier:String) {

        self.uuidString         = parauuidString
        self.beaconIdentifier   = parabeaconIdentifier
        self.beaconUUID         = NSUUID(UUIDString: self.uuidString)
        self.beaconRegion       = CLBeaconRegion(proximityUUID:self.beaconUUID,identifier: self.beaconIdentifier)
        self.locationManager         = CLLocationManager();

        super.init()
        self.initLocationMangager()

    }

    ////////////////////////Init location manager
    private func initLocationMangager()
    {
        println(self.locationManager)

        if(self.locationManager.respondsToSelector("requestAlwaysAuthorization")) {
            locationManager.requestAlwaysAuthorization()
        }

        self.locationManager.delegate = self
        self.locationManager.pausesLocationUpdatesAutomatically = false

        self.locationManager.startMonitoringForRegion(beaconRegion)
        self.locationManager.startRangingBeaconsInRegion(beaconRegion)
        self.locationManager.startUpdatingLocation()
    }

    //////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////
    ////////////////////////LocationManager Delegates
    //////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////

    ////////////////////////LocationManager didStartMonitoringForRegion
    func locationManager(manager: CLLocationManager!, didStartMonitoringForRegion region: CLRegion!) {
        manager.startRangingBeaconsInRegion(region as CLBeaconRegion)
        println("Did Start")
    }

    ////////////////////////LocationManager didEnterRegion
    func locationManager(manager: CLLocationManager!, didEnterRegion region: CLRegion!) {
        manager.startRangingBeaconsInRegion(region as CLBeaconRegion)
    }

    ////////////////////////LocationManager didRangeBeacons
    func locationManager(manager: CLLocationManager!, didRangeBeacons beacons: [AnyObject]!, inRegion region: CLBeaconRegion!) {

            var message:String = ""

            if(beacons.count > 0) {
                let nearestBeacon:CLBeacon = beacons[0] as CLBeacon

                switch nearestBeacon.proximity {
                case CLProximity.Far:
                    message = "Far"
                case CLProximity.Near:
                    message = "Near"
                case CLProximity.Immediate:
                    message = "Immediate"
                case CLProximity.Unknown:
                    return
                }
            } else {
                message = "No Beacons"
            }

            //Call BeaconServiceDelegate
            beaconServiceDelegate?.foundBeacon()
    }

    ////////////////////////LocationManager monitoringDidFailForRegion
    func locationManager(manager: CLLocationManager!, monitoringDidFailForRegion region: CLRegion!, withError error: NSError!) {
        println(error)
    }

    ////////////////////////LocationManager didExitRegion
    func locationManager(manager: CLLocationManager!, didExitRegion region: CLRegion!) {
        manager.stopRangingBeaconsInRegion(region as CLBeaconRegion)

    }

}

A: I see at least one thing very simple.  It looks like the initLocationMangager() method never gets called.  You should probably add a call to this method from the init(parauuidString:String,parabeaconIdentifier:String) method.

A: Sorry I forgot that, i had taken out.
But it also does not go with the calling
self.initLocationMangager()

A: It looks like you are assigning your advertise service to a local variable at the end of your viewDidLoad. This instance will be destroyed at the end of this method (one line later ;))
Please make sure to assign your advertiser to an instance variable or property and assign self (your viewcontroller) as a delegate to your advertiser.
This should do the trick.


text:
Q: Sql: choose all baskets containing a set of particular items Eddy has baskets with items. Each item can belong to arbitrary number of baskets or can belong to none of them.
Sql schema to represent it is as following:
tbl_basket
- basketId

tbl_item
- itemId

tbl_basket_item
- pkId
- basketId
- itemId

Question: how to select all baskets containing a particular set of items?
UPDATE. Baskets with all the items are needed. Otherwise it would have been easy task to solve.
UPDATE B. Have implemented following solution, including SQL generation in PHP:
SELECT basketId
FROM   tbl_basket
JOIN   (SELECT basketId FROM tbl_basket_item WHERE itemId = 1  ) AS t0 USING(basketId)
JOIN   (SELECT basketId FROM tbl_basket_item WHERE itemId = 15 ) AS t1 USING(basketId)
JOIN   (SELECT basketId FROM tbl_basket_item WHERE itemId = 488) AS t2 USING(basketId)

where number of JOINs equals to number of items.
That works good unless some of the items are included in almost every basket. Then performance drops dramatically.
UPDATE B+. To resolve performance issues heuristic is applied. First you select frequency of each item. If it exceeds some threshold, you don't include it in JOINs and either:

*

*apply post-filtering in PHP

*or just don't apply filter by particular itemId, giving a user approximate results in a resonable amount of time

UPDATE B++. Seems that current problem have no nice solution in MySQL. This point raises one question and one solution:

*

*(question) Does PostgreSQL have some advanced indexing techniques which allows to solve this problem without doing a full scan?

*(solution) Seems that it could be solved nicely in Redis using sets and SINTER command to get an intersection.

A: I think the best way is to create a temporary table with the set of needed items (procedure that takes the item ids as parameters or something along those lines) and then left join it with all of the above tables joined together.
If for a given basketid you have NO nulls on the right side of the left join, the basket contains all the needed items.

A: -- the table definitions
CREATE TABLE basket ( basketid INTEGER NOT NULL PRIMARY KEY);
CREATE TABLE item ( itemid INTEGER NOT NULL PRIMARY KEY);
CREATE TABLE basket_item
        ( basketid INTEGER NOT NULL REFERENCES basket (basketid)
        , itemid INTEGER NOT NULL REFERENCES item (itemid)
        , PRIMARY KEY (basketid, itemid)
        );

-- the query
SELECT * FROM basket b
WHERE NOT EXISTS (
        SELECT * FROM item i
        WHERE i.itemid IN (1,15,488)
        AND NOT EXISTS (
                SELECT * FROM basket_item bi
                WHERE bi.basketid = b.basketid
                AND bi.itemid = i.itemid
                )
        );

A: If you are going to provide the list of items, then edit id1, id2, etc. in below query:
select distinct t.basketId
from tbl_basket_item as t
where t.itemID in (id1, id2)

will give all baskets containing a set of items. No need to join any other tables as your requirements don't need them.

A: The simplest solution is to use HAVING clause.
SELECT basketId
FROM   tbl_basket
WHERE itemId IN (1,15,488)
HAVING Count(DISTINCT itemId) = 3 --DISTINCT in case we have duplicate items in a basket
GROUP BY basketId


text:
Q: Conversions of different data types I am new to C and trying to create an analogue of the dictionary, and ran into a typing problem. My dictionary knows how to create a key-value only for const char, I wanted to expand the program so that it could also use values of other data types, tried to use a pointer to void, but the problem remained and I had a few questions:
Is it possible to make so that the function has converted the dictionary different types of data?
How can I do this?
main code:
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdio.h>

#define MAXSIZE 5000

struct base
{
    uint8_t *up;
    uint8_t size;
};

typedef struct
{
    struct base key[MAXSIZE];
    struct base data[MAXSIZE];
    uint8_t index;
} dict_t;

static dict_t *init (uint8_t s_key, uint8_t s_data)
{
    dict_t *dict;

    dict = (dict_t *) malloc(sizeof(dict_t));
    dict -> key -> up = (uint8_t *) malloc(s_key);
    dict -> data -> up = (uint8_t *) malloc(s_data);

    dict -> key -> size = s_key;
    dict -> data -> size = s_data;
    dict -> index = 1;

    return dict;
}

dict_t *newDict (const char *key, const char *data)
{
    dict_t *dict;
    uint8_t s_key;
    uint8_t s_data;

    s_key = strlen(key);
    s_data = strlen(data);

    dict = init(s_key, s_data);

    memcpy(dict -> key, key, s_key);
    memcpy(dict -> data, data, s_data);

    return dict;
}

void printDict (dict_t *dict)
{
    for (int i = 0; i < dict -> index; i++)
    {
        fwrite(dict -> key, sizeof(uint8_t), dict -> key -> size, stdout);
        fwrite(": ", sizeof(char), 2, stdout);
        fwrite(dict -> data, sizeof(uint8_t), dict -> data -> size, stdout);
    }
}

main function
#include "dict.c"

int main ()
{
    dict_t *dict;

    dict = newDict("key", "data\n");
    printDict(dict);

    return 0;
}

Thanks a lot.

A: Short answer: You can't (but look at long answer).
Long answer:
There are two tricks you can use, although they are not perfect.
The first one is void pointers.
Void pointers have no type, so can be used to point to a value of any pointer. However, the pointer does not store the type of the value it points to. This can  cause issues as you have to use a type cast to dereference it, which requires you to know the type before hand. You could use a struct to store the type as well as the pointer, then use if statements to dereference it appropriately:
enum Type {
    Int,
    Str
    //add more types
}
struct base {
    enum Type type;
    void *value;
}

The second trick is using unions. Very similar to the first one, just using a union instead of a void pointer:
enum Type {
    Int,
    Str
    //add more types here
}
struct base {
    enum Type type;
    union {
        int i;
        char s[20];
        //add more types here
    } values;
}

You would again use if statements to choose the correct field of the union.


text:
Q: What are questions to ask when planning database backups? Examples:

*

*Was is the operating environment?

*How large of a dataset?

*Are offline backups acceptable?

*Is point-in-time restoration a requirement?

*What storage engine?

CONTEXT: Want to ask how to do MySQL backups on CentOS, but want to make sure I understand what I should be asking first. If you have any questions, just ask -- thanks!!

UPDATE: Just a note to say thanks for ALL the great input so far, really glad I asked. Again, thanks!!

A: *

*What is the budget we can spend on?

*What is the acceptable downtime?

*Where will the backups be located?

A: Also

*

*How long do I have to take the backups

*How long do I have to restore the backups

Coupled with the size of the dataset that'll give you the minimum transfer speed you need, which should help you identify how you have to back it up.

A: I think in your examples you should ask the business type question (i.e. is point-in-time recovery needed - but in business speak) but not the others which are technical and should be figured out later once the business needs are clear.
Managers may well then ask how much more PIT recovery would cost. On investigation you will probabably find it is not that much more expensive nowadays.
Also as well as the other very good answers already:
1)
How long should long term backups be kept? For example in your country there might be a law that financial data be kept for a certain number of years. Or conversely there could be a law that transitory personal data be deleted after a certain number of years. This should be in the SLA mentioned by Tom.
If you are required to take very long term backups you also need to consider how to get the information back again if the metadata (sorry I do not know MS SQL so not sure if it is called a schema there) has changed in the meantime. Therefore you may want to long term back up the schema or perhaps take occasional exports as well as backups.
2)
Get a disaster recover exercise put in the plan at an early stage otherwise management may not include it in the budget. You may find you need both onsite backups (for quick recovery as in most cases it will not be a complete disaster) and offsite (for disaster recovery in case the whole site is unavailable).

A: What are the service level agreements for downtime. The only reason to backup is to recover so make sure you understand the recovery requirements before you plan backup.


text:
Q: Android mpandroidchart line chart with cut-off points I would like to visible some data in LineChart with mpandroidchart in Android. But the datas have cut-off points. How can I resolve this problem, and visible the cut-off points in the chart too?

A: LimitLine is what you are looking for,
LimitLine line = new LimitLine(1013.25f);
line.setLabel("1 atm - 1013.25hPa");
mChart.getAxisLeft().addLimitLine(line);

Please check the documentation for further details.


text:
Q: Symfony routing bundle - remove trailing slash from locale in URL: /en/ → /en I have the following setup:

*

*Symfony 3.1

*JMSTranslationBundle

*JMSI18nRoutingBundle
Everything works fine. But there's a small problem I can't figure out:

*

*routes are translated correctly and routes end without a trailing slash:
test.com/en/contact

*unfortunately the homepage route has a trailing slash:
test.com/en/ should be test.com/en

*also calls to test.com or test.com/en are redirected to test.com/en/
How can I get rid of this trailing slash?

Here's my configuration:
I have setup the locales in parameters.yml:
parameters:
    locale: de
    locales: [de, en]

I have configured the JMS Routing bundle in config.yml:
jms_i18n_routing:
    default_locale: "%locale%"
    locales: "%locales%"
    strategy: prefix

My routes in routing.yml:
app:
    prefix: /
    resource: '@AppBundle/Controller/AppController.php'
    type: annotation
    options: { i18n: true }

And my index/default action is annotated like this:
/**
 * @Route("/", name="homepage")
 */
public function indexAction(Request $request) {}

The .htaccess file in /web is the boilerplate file that comes with Symfony 3.1

I already tried to remove the / in the annoation (@Route("", name="homepage")) but without any luck.

A: I think this is due to how the relative URLs work, when using:
Homepage

The generated link has to be "/" or it would not work, it would go to the same actual page instead of going to the homepage.

A: Here's my solution. First you have to define route translations as empty string. I'm using yaml configuration.
# AppBundle/Resources/config/routing.yml
homepage:
  path:     /
  defaults: { _controller: AppController:Page:index }

# AppBundle/Resources/translations/routes.de.yml
# AppBundle/Resources/translations/routes.en.yml
# and other routes translation files...
homepage: ''

Now the trailing slash is removed but when we try to access the page without locale parameter (www.mypage.com) it's redirected first to www.mypage.com/en/ and then to www.mypage.com/en.
It's caused by JMS\I18nRoutingBundle\EventListener\LocaleChoosingListener, the last line of onKernelException method:
     $event->setResponse(new RedirectResponse($request-   >getBaseUrl().'/'.$locale.'/'.($params ? '?'.http_build_query($params) : ''))); this part to be more precise: '$locale' . '/'.
What we can do is overriding this listener. I've done it this way:
# AppBundle/Resources/config/services.yml
parameters:
  jms_i18n_routing.locale_choosing_listener.class: AppBundle\EventListener\LocaleChoosingListener

# AppBundle/EventListener/LocaleChoosingListener
<?php

namespace AppBundle\EventListener;

use JMS\I18nRoutingBundle\EventListener\LocaleChoosingListener as BaseListener;
use JMS\I18nRoutingBundle\Router\LocaleResolverInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;

/**
 * Removing trailing slash from homepage requests
 * {@inheritdoc}
 */
class LocaleChoosingListener extends BaseListener
{
    private $defaultLocale;
    private $locales;
    private $localeResolver;

    public function __construct($defaultLocale, array $locales, LocaleResolverInterface $localeResolver)
    {
        parent::__construct($defaultLocale, $locales, $localeResolver);

        // If these properties were protected, we could remove the constructor.
        $this->defaultLocale = $defaultLocale;
        $this->locales = $locales;
        $this->localeResolver = $localeResolver;
    }

     public function onKernelException(GetResponseForExceptionEvent $event)
    {
        if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
            return;
        }

        $request = $event->getRequest();

        if ('' !== rtrim($request->getPathInfo(), '/')) {
            return;
        }

        $ex = $event->getException();

        if (!$ex instanceof NotFoundHttpException || !$ex->getPrevious() instanceof ResourceNotFoundException) {
            return;
        }

        $locale = $this->localeResolver->resolveLocale($request, $this->locales) ?: $this->defaultLocale;

        $request->setLocale($locale);

        $params = $request->query->all();
        unset($params['hl']);

        $event->setResponse(new RedirectResponse($request->getBaseUrl().'/'.$locale.($params ? '?'.http_build_query($params) : '')));
    }
}

A: php bin/console debug:router
    ru__RG__main                   ANY      ANY      ANY    /
    en__RG__main                   ANY      ANY      ANY    /en/
    ua__RG__main                   ANY      ANY      ANY    /ua/

create translations files
routes.ru.yml
routes.en.yml
routes.ua.yml

added this ('main' - it's my route name)
main: ''
    php bin/console debug:router

    ru__RG__main                   ANY      ANY      ANY    /
    en__RG__main                   ANY      ANY      ANY    /en
    ua__RG__main                   ANY      ANY      ANY    /ua


text:
Q: Need jQuery Content Slider I am unable to get the correct title for this, please change the title if you get appropriate one :)
This is what i am having

         Div content Here  [ always either embed or object or image ]

     xtra noise

         Div content Here

     xtra noise

         Div content Here

     xtra noise

Now, what i need is this
http://sketchfu.com/drawing/876520-what-do-i-need-
Note sketchfu is pathetic for drawing.
Is there any jQuery plugin which can do this?

A: Here is a list of content sliders: http://visionwidget.com/inspiration/web/295-jquery-content-sliders.html
I have used and like: http://cssglobe.com/post/5780/easy-slider-17-numeric-navigation-jquery-slider


text:
Q: SQL query for pivot table I have table with two columns, Name and countries visited:
Name   Subjects
mike   england
maria  china
james  russia
mike   mexico
maria  france
laurel england
...    ...

Now I want to write a query which will display the number of people who visited two countries, three, four and so on up to ten.
The final result should look like:
Number of countries -> number of people
10                  -> 5
9                   -> 13
8                   -> 24
and so on.

So how do I proceed with this?
Any suggestion?

A: Considering the following schema for you table (I named it subjects and the id column was added for the sake of unique key)
CREATE TABLE `subjects` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`country` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1

following query can achieve your desired result
SELECT a.c AS num_of_countries, COUNT(*) AS num_of_people
FROM
    (SELECT `country`, COUNT(*) AS c FROM subjects GROUP BY 1) a
GROUP BY 1

A: Try this :
SELECT t2.number_of_country,
       count(t1.Name) number_of_people
FROM tableName t1
INNER JOIN
    (SELECT Name, count(Subjects) number_of_country
     FROM tableName
     GROUP BY Name) t2 ON t2.Name = t1.Name
GROUP BY t2.number_of_country


text:
Q: ASP: Redirect to headless page and return I have an .aspx page that generates a report using the ReportViewer control. It is typically invoked from another page using Response.Redirect.
This page can be used in several ways. As long as the page generates a response, such as a MIME attachement, it works as expected. However, now I added the ability to generate the report and send it as an email attachement. In this scenario, the page is headless and does not produce a response on its own. Instead, I want to redirect back to the calling page and show a success message, as in:
Caller page -> Button Click -> Response.Redirect(Report page) -> process report -> Response.Redirect(Caller Page)
This works as intended in Chrome, but not in IE (8). The report is processed and the email is sent, but the 2nd redirect does not work and the browser times out. I considered using Server.Transfer for the redirect to the ReportViewer page. The timeout still occured in IE.
Can there not be 2 redirects in one request? What am I missing, and is there a better way to do this?
This quoting from RFC1945 makes me think that the approach should be ok:

A user agent should never automatically
     redirect a request more than 5 times, since such redirections usually
     indicate an infinite loop.

FYI, I want to keep all the report processing logic in the code-behind of the ReportViewer page if possible, because it interacts with the Response object in the normal scenario where the report is streamed back to he browser.

A: Might I propose an alternate approach?
Caller page -> Button Click -> POST -> process report -> GetRequestStream (i.e., "OK/Error") -> Do something

A: The fix for this was rather mundane. The method that renders the report and writes it to a file did a Response.ClearContent(). This was existing code that I brought over from a different application where this was required. Once I removed the call, the subsequent redirect began to work even in IE.
The final solution looks like this:
Caller page -> Button Click -> Validation -> Server.Transfer(Report page) -> process report -> Response.Redirect(Caller Page)
The caller page refreshes and shows a success message.


text:
Q: Error caused by interaction between minted, footnotes, babel and "(double quote) I'd like to put some inline code using minted but when I try to typesent the empty string "" I get an "undefined control sequence" error.
Sample code:
\documentclass[a4paper,10pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[italian]{babel}
\usepackage{minted}

\begin{document}
\footnote{\mint{bash}/""/}
\end{document}

The pdf is created anyway but I get this instead of the expected "":
\def {\futurelet \protect \let \relax }\def {\futurelet \protect \let \relax }

(Yes, I really mean that the above commands are printed in the footnote in the pdf).
Commenting out babel solves the problem, but I need babel in my real TeX file.
Also I do not want to use `` and '', since they give an output that does not match with the code inserted using \inputminted.
Is there a way to fix this? Eventually how can I put real a doublequote(a.k.a. ASCII 34)?
Note that \mint is like \verb so normal LaTeX commands are ignored.
On a side note I'm using this answer to typeset inline code with minted, but it is not the cause of the problem.

A: If you don't have to use minted, you could try my pythontex package, which uses the same Pygments highlighting library. It provides a \pygment command for inline use, and this seems to work fine in footnotes, except that # and % characters don't work (the # and % work fine outside footnotes in normal text, and it wouldn't be hard to get around the footnote issue if these characters are needed). The package also provides a pygments environment and an \inputpygments command.
\documentclass[a4paper,10pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[italian]{babel}
\usepackage{pythontex}

\begin{document}
\footnote{Quotes: \pygment{bash}/""/.  More: \pygment{bash}/echo ${a[$i,$j]}/.}
\end{document}

More explanation and patch for minted
The ultimate issue is that minted uses verbatim content (ShortVerb from fancyvrb), and that's problematic in footnotes. My package uses a different approach, and also caches all highlighted content to increase speed.
Here's a rough patch for minted that should give you what you want. It makes \mint into an inline command. It's based on some things I did in my package, so it should work in footnotes as well as my package does.  I had to make new versions of \minted@savecode and \minted@pygmentize to get rid of excess spaces (added lots of %), and to temporarily swap Verbatim for BVerbatim.  It's very important to avoid any extra spaces hanging around for inline use; the examples show that regular text can be right up against highlighted content.
Comment on performance:  If you are going to redefine \mint for inline use (or, perhaps better, define a new command for that purpose), you will presumably use inline code fairly frequently.  On my system, compiling takes about 12 s when \mint{bash}/""/ is used 40 times; it's about 23 s for 80 times.  pythontex takes about 3.5 s for 40 uses of \pygment{bash}/""/ (this involves running pdflatex, then the pythontex script, and then pdflatex again, to bring back highlighted results).  It's about the same for 80 uses, about 5.5 s for 800 uses, and about 23 s for 8000.  And all of those numbers are only when pythontex actually has to highlight everything; since results are saved, the pythontex script and second pdflatex run are only needed when code is modified.  If you are recompiling after editing non-code text, you only need to run pdflatex, and should get more or less normal pdflatex speeds.

\documentclass[a4paper,10pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[italian]{babel}
\usepackage{minted}

\makeatletter
\renewcommand\mint{%
  \begingroup
  \let\do\@makeother\dospecials
  \catcode`\{=1
  \catcode`\}=2
  \@ifnextchar[{\endgroup\mint@i}{\endgroup\mint@i[]}}
\def\mint@i[#1]#2{%
  \minted@resetoptions
  \setkeys{minted@opt}{#1}%
  \gdef\mint@lang{#2}%
  \begingroup
  \let\do\@makeother\dospecials
  \mint@ii}
\def\mint@ii#1{%
  \endgroup
  \def\mint@iii##1#1{%
    \endgroup
    \expandafter\edef\csname FV@SV@minted@verb\endcsname{\detokenize{##1}}%
    \minted@savecode@inline{\FV@SV@minted@verb}%
    \minted@pygmentize@inline{\mint@lang}%
    \DeleteFile{\jobname.pyg}}%
  \begingroup
  \let\do\@makeother\dospecials
  \mint@iii}

\newcommand\minted@savecode@inline[1]{%
  \immediate\openout\minted@code\jobname.pyg
  \immediate\write\minted@code{#1}%
  \immediate\closeout\minted@code}

\newcommand\minted@pygmentize@inline[2][\jobname.pyg]{%
  \RecustomVerbatimEnvironment{Verbatim}{BVerbatim}{}%
  \def\minted@cmd{pygmentize -l #2 -f latex -F tokenmerge
    \minted@opt{gobble} \minted@opt{texcl} \minted@opt{mathescape}
    \minted@opt{startinline} \minted@opt{funcnamehighlighting}
    \minted@opt{linenos} -P "verboptions=\minted@opt{extra}"
    -o \jobname.out.pyg #1}%
  \immediate\write18{\minted@cmd}%
  % For debugging, uncomment:
  %\immediate\typeout{\minted@cmd}
  \ifthenelse{\equal{\minted@opt@bgcolor}{}}%
   {}%
   {\begin{minted@colorbg}{\minted@opt@bgcolor}}%
  \input{\jobname.out.pyg}%
  \ifthenelse{\equal{\minted@opt@bgcolor}{}}%
   {}%
   {\end{minted@colorbg}}%
  \DeleteFile{\jobname.out.pyg}}
\makeatother

\begin{document}

Before environment
\begin{minted}{bash}
""
\end{minted}
After environment

Before inline\mint[]{bash}/""/After inline

Before note\footnote{Before\mint{bash}/""/After}

\end{document}

Edit 2013/07/30
I am now maintaining minted, and have incorporated code similar to the patch here to create a new inline command, \mintinline, in the development version on GitHub.


text:
Q: passing global variables to another file in Python? I have
# file1.py
global a, b, c, d, e, f, g

def useful1():
   # a lot of things that uses a, b, c, d, e, f, g

def useful2():
   useful1()
   # a lot of things that uses a, b, c, d, e, f, g

def bonjour():
   # a lot of things that uses a, b, c, d, e, f, g
   useful2()

and
# main.py   (main file)
import file1

# here I would like to set the value of a, b, c, d, e, f, g  of file1 !

bonjour()

How to deal with all these global variables ?
PS : I don't want to add a, b, c, d, e, f, g for ALL functions, it would be very redundant to have to do :
def useful1(a, b, c, d, e, f, g):
...
def useful2(a, b, c, d, e, f, g):
...
def bonjour(a, b, c, d, e, f, g):
...

A: You don't need to pass them. If you've done import file1 at the top of main.py, you can just refer to file1.a etc directly.
However, having this many global variables smells very bad. You probably should refactor using a class.

A: The canonical way to share information across modules within a single program is to create a special module (often called config or cfg). Just import the config module in all modules of your application; the module then becomes available as a global name. Because there is only one instance of each module, any changes made to the module object get reflected everywhere. For example:
config.py:
x = 0   # Default value of the 'x' configuration setting

mod.py:
import config
config.x = 1

main.py:
import config
import mod
print config.x

A: Use a dict to wrap those global variable, then only one param for functions


text:
Q: Should I have one big angular file for my entire website? I'm building a website that will have facebook-ish features (friends and what not) along with a marketplace and some forums. I've decided to use bootstrap as I'm not a good designer and rather than using Jquery I've come across a replacement for their plugins written in angular (UI bootstrap is the name).
Should I just have one giant angular file for my entire website, aka the plugins for UI one and add whatever else I need to do that, or should I load in two different files? One will be the pre-written plugins and the other one will be the web app needed for that page (for example having the marketplace web app in its own file and include both of them on the same page).
This is my first website so I'm trying to make it as efficient as possible, thanks for the input!

A: I'd do one for the scripts that you wrote and another for the vendor scripts.
But if you are starting new to gulp or grunt you should really consider using a scaffolding tool such as yeoman. If you use angular-fullstack generator you will see some good examples for both angular and grunt, as well as node.

A: Definitely not, you should only have one angular component per file. Working with a scaffolding tool such as Yeoman or Slush will make this much easier.
Additionally, I would recommend reading some of the AngularJS styleguides out there. John Papa's guide and Todd Motto's guide are good places to start. Here's a full list of AngularJS resources to get you started. Good luck!


text:
Q: Action of U(1) on a sphere bundle, non-vanishing vector fields on odd-dimensional manifolds (This question has been asked on Stack Exchange: https://math.stackexchange.com/questions/89920/action-of-u1-on-a-sphere-bundle)
Suppose $N$ is a closed, $n$-dimensional, orientable smooth manifold. Moreover, $n$ is odd.
Consider the tangent bundle $TN$ of $N$. By adding a point at infinity to each tangent space I define a sphere bundle $E$ over $N$.
Notice, that every fiber is homeomorphic to $S^{n}$ and that odd-dimensional spheres admit a free action of $U(1)$ (coming from standard embedding into $\mathbb{C}^k$).
Is it possible to make $U(1)$ act on $E$, such that the action is free on every fiber? Can you define the action in such that locally over $N$ there exist trivializing charts for $E$ where the action is isomorphic to the standard action of $U(1)$ on $S^n$? (Isomorphism in this case probably should mean equivariant homeomorphism.)
I do not care if the action is smooth. Since this is MO I will explain the motivation for asking this question. I am trying to construct a non-vanishing vector field on a manifold $N$ as above (with possibly some more assumptions). This would imply that it has Euler number $0$. Is there any "geometric" way of doing this? By "geometric" I mean a way that makes it clear that odd-dimensionality is crucial.

A: Here is a proof that a compact oriented manifold $M$ of dimension $n$ with zero Euler characteristic has a nowhere vanishing vector field. There a vector field $X$ on $M$ with all zeroes non-degenerate. Since $\chi(M)=0$, we can split the zeroes into pairs such that in each pair there are points of indices $1$ and $-1$.
Take a ball $B$ containing one such pair in its interior. Identify $B$ with the unit ball in $\mathbb{R}^n$ and $TM|B$ with $TB$. We can write the field restricted to $S=\partial B$ as $x\mapsto f(x)$ where $x\in S$ and $f(x)\in\mathbb{R}^n$; since $X$ no zeroes on $S$, $f$ gives after normalizing a map $g:S\to S$, which has degree 0, since the vector field has two zeroes of the opposite signs inside $B$. By Hopf theorem (= maps between spheres of the same dimension are classified by their degrees up to homotopy; this can be proven with or without obstruction theory), $g$ is homotopic to a constant map $S\to S$. We can use the homotopy to extend $X|S$ to a nowhere vanishing field in $B$.
After doing this for each pair of zeroes of $X$ we are done.
Regarding the original question: introducing a $U(1)$-action seems (to me) to be a very expensive way of getting a non-zero vector field! I'm not sure this is always possible, but can't think of any examples either.

A: A very closely related question is discussed here:
nowhere vanishing vector field on a manifold


text:
Q: Pivoting DataFrame with multiple columns for the index I have a dataframe and I want to transpose only few rows to column.
This is what I have now.
   Entity   Name        Date  Value
0     111  Name1  2018-03-31    100
1     111  Name2  2018-02-28    200
2     222  Name3  2018-02-28   1000
3     333  Name1  2018-01-31   2000

I want to create date as the column and then add value. Something like this:
   Entity   Name  2018-01-31  2018-02-28  2018-03-31
0     111  Name1         NaN         NaN       100.0
1     111  Name2         NaN       200.0         NaN
2     222  Name3         NaN      1000.0         NaN
3     333  Name1      2000.0         NaN         NaN

I can have identical Name for two different Entitys. Here is an updated dataset.
Code:
import pandas as pd
import datetime

data1 = {
         'Entity': [111,111,222,333],
         'Name': ['Name1','Name2', 'Name3','Name1'],
         'Date': [datetime.date(2018,3, 31), datetime.date(2018,2,28), datetime.date(2018,2,28), datetime.date(2018,1,31)],
         'Value': [100,200,1000,2000]
    }
df1 = pd.DataFrame(data1, columns= ['Entity','Name','Date', 'Value'])

How do I achieve this? Any pointers? Thanks all.

A: From unstack
df1.set_index(['Entity','Name','Date']).Value.unstack().reset_index()

Date  Entity   Name  2018-01-31 00:00:00  2018-02-28 00:00:00  \
0        111  Name1                  NaN                  NaN
1        111  Name2                  NaN                200.0
2        222  Name3                  NaN               1000.0
3        333  Name1               2000.0                  NaN

Date  2018-03-31 00:00:00
0                   100.0
1                     NaN
2                     NaN
3                     NaN

A: Based on your update, you'd need pivot_table with two index columns -
v = df1.pivot_table(
        index=['Entity', 'Name'],
         columns='Date',
         values='Value'
).reset_index()
v.index.name = v.columns.name = None

v
   Entity   Name  2018-01-31  2018-02-28  2018-03-31
0     111  Name1         NaN         NaN       100.0
1     111  Name2         NaN       200.0         NaN
2     222  Name3         NaN      1000.0         NaN
3     333  Name1      2000.0         NaN         NaN


text:
Q: Is "present perfect" more common with special verbs? I wrote this sentence

We have implemented the proposed system as a visual tool for wrapper generation.

Maybe I could say:

We implemented the proposed system as a visual tool for wrapper generation.

Because I feel, maybe "implementation" is not something that needs to be continued to the present.
Are there some rules here?

A: The perfect does not necessarily imply that the action of its lexical verb continues into the present; with a telic verb (one which has a goal or endpoint 'built in' to its sense) it implies a current state which arose from the action of the lexical verb.
Whether you employ a simple past or a present perfect depends on your discourse context.


text:
Q: While moving GPS Lat/Long values intermittantly don't change I have been using the SIM28 GPS module and have a problem. The problem is that the GPS latitude and longitude values don't change while the device moves, sometimes the latitude and longitude values remain the same for up to two minutes or longer.  This occurs around 50% of the time the GPS unit is running.  When the GPS values recover (start changing again) there is a large jump to the actual position.
My configuration is:

*

*Two SIM28 GPS modules running in tandem.

*Each module has a good antenna (http://php2.twinner.com.tw/files/onshine/ANT555-2006-NEW.pdf).  The GPS antenna is mounted inside a radio controlled RC sailboat with a thin plastic hull (but had the same problem when mounted outside).

*The baud rate is set to 9600

*The NMEA rate is 4 Hz

*The NMEA sentences returned are GGA and RMC.

The funny thing is that both GPS units do the same thing at similar times.
One thing that could be a factor could be the roll of the sailboat (how the sailboat rolls to the side when the wind blows), but I did some analysis and I don't see a correlation here. Update: The SIM28 module also has this problem in clear open area with direct view of the sky.
Below is an example of the output (of just one receiver and only GGA sentence).  The "good" values are labeled with #:
    $GPGGA,212131.500,3648.5591,S,17445.0304,E,2,11,0.86,3.0,M,26.5,M,0000,0000*7C #
    $GPGGA,212131.750,3648.5591,S,17445.0304,E,2,11,0.86,3.0,M,26.5,M,0000,0000*7B #
    $GPGGA,212132.000,3648.5590,S,17445.0305,E,2,11,0.86,3.0,M,26.5,M,0000,0000*7A #
    $GPGGA,212132.250,3648.5590,S,17445.0306,E,2,11,0.86,3.0,M,26.5,M,0000,0000*7E #
    $GPGGA,212132.500,3648.5590,S,17445.0307,E,2,11,0.86,3.0,M,26.5,M,0000,0000*7D #
    $GPGGA,212132.750,3648.5590,S,17445.0307,E,2,11,0.86,3.0,M,26.5,M,0000,0000*7A #
    $GPGGA,212133.000,3648.5590,S,17445.0308,E,2,11,0.86,3.0,M,26.5,M,0000,0000*76 #
    $GPGGA,212133.250,3648.5590,S,17445.0309,E,2,11,0.86,3.0,M,26.5,M,0000,0000*70 #
    $GPGGA,212133.500,3648.5590,S,17445.0310,E,2,11,0.86,3.0,M,26.5,M,0000,0000*7A #
    $GPGGA,212133.750,3648.5590,S,17445.0310,E,2,11,0.86,3.0,M,26.5,M,0000,0000*7D #
    $GPGGA,212134.000,3648.5590,S,17445.0311,E,2,11,0.86,3.0,M,26.5,M,0000,0000*79
    $GPGGA,212134.250,3648.5591,S,17445.0311,E,2,11,0.86,3.0,M,26.5,M,0000,0000*7F #
    $GPGGA,212134.500,3648.5591,S,17445.0312,E,2,11,0.86,3.0,M,26.5,M,0000,0000*7E #
    $GPGGA,212134.750,3648.5591,S,17445.0312,E,2,11,0.86,3.0,M,26.5,M,0000,0000*79 #
    $GPGGA,212135.000,3648.5592,S,17445.0312,E,2,11,0.86,3.1,M,26.5,M,0000,0000*78
    $GPGGA,212135.250,3648.5592,S,17445.0312,E,2,11,0.86,3.1,M,26.5,M,0000,0000*7F #
    $GPGGA,212135.500,3648.5592,S,17445.0312,E,2,11,0.86,3.1,M,26.5,M,0000,0000*7D
    $GPGGA,212135.750,3648.5592,S,17445.0312,E,2,11,0.86,3.1,M,26.5,M,0000,0000*7A
    $GPGGA,212136.000,3648.5592,S,17445.0312,E,2,11,0.86,3.1,M,26.5,M,0000,0000*7B
    $GPGGA,212136.250,3648.5592,S,17445.0312,E,2,11,0.86,3.1,M,26.5,M,0000,0000*7C
    $GPGGA,212136.500,3648.5592,S,17445.0312,E,2,11,0.86,3.1,M,26.5,M,0000,0000*7E
    $GPGGA,212136.750,3648.5592,S,17445.0312,E,2,11,0.86,3.1,M,26.5,M,0000,0000*79
    $GPGGA,212137.000,3648.5592,S,17445.0312,E,2,11,0.86,3.1,M,26.5,M,0000,0000*7A
    $GPGGA,212137.250,3648.5592,S,17445.0312,E,2,11,0.86,3.1,M,26.5,M,0000,0000*7D
    $GPGGA,212137.500,3648.5592,S,17445.0312,E,2,11,0.86,3.1,M,26.5,M,0000,0000*7F
    $GPGGA,212137.750,3648.5592,S,17445.0312,E,2,11,0.86,3.1,M,26.5,M,0000,0000*78
    $GPGGA,212138.000,3648.5592,S,17445.0312,E,2,11,0.86,3.1,M,26.5,M,0000,0000*75
    $GPGGA,212138.250,3648.5592,S,17445.0312,E,2,11,0.86,3.1,M,26.5,M,0000,0000*72
    $GPGGA,212138.500,3648.5592,S,17445.0312,E,2,11,0.86,3.1,M,26.5,M,0000,0000*70

A: It appears the problem is with the SIM28 GPS module.  I have used the u-blox NEO-6M module and it works well.
My guess is the SIM28 has some buggy noise filtering.  The u-blox is tends to noisier, but I prefer to be able to filter the noise myself than let the GPS unit do it.


text:
Q: how to limit the login attempts for users in laravel 4 am trying to work on a project in laravel 4.2 but now, i would like to limit on the number of login attempts for users.most solutions are laravel 5 and am not familiar with 5. so anyone with an idea please i need your help. thank you.
 $data = Input::all();
    $rules = array(
        'username' =>'required|',
        'password' => 'required|min:6'
    );
    $validator = Validator::make($data, $rules);
    if($validator->passes())
    {
        $user = array(
            'username'=> Input::get('username'),
            'password' => Input::get('password'),
            'active'=>1,
        );

        if(Auth::attempt($user))
        {
               if((Auth::user()->isBuyer()))
                {
                    return Redirect::route('customer')->with(['success' => 'Welcome '.Auth::user()->name .'']);
                }
                elseif((Auth::user()->isSeller()))
                {
                    return Redirect::route('seller')->with(['success' => 'Welcome '.Auth::user()->name .'']);

                }
                else
                {
                    return Redirect::route('dashboard')->with(['success' => 'Welcome '.Auth::user()->name.' ']);

                }
        }
         return Redirect::back()
            ->with(array(
                'error' => 'Your email and password combination is invalid or Verify your email first'
            ));

    }
    return Redirect::back()
        ->withInput()
        ->withErrors($validator);

}

that is my controller function for logging in

A: There is so many way to do that. But below are common and i usually do.
1.) Add column "attempt" to users table and increment each time the user is failed to log on. Reset the column back to 0  if the user is successfully logged in.
2.) Create session "attempt" and  increment each time the user is failed to log on. Reset the session back to 0 if the user is successfully logged in. You can also block user to log in for x number of minutes.
But i prefer the option 1 so the user cannot log in even if he uses different browser.


text:
Q: How do I build a query to find ownership through transaction history? I'm currently working on a feature that can contract all objects that a certain user owns, by only using a transaction history.
This is how the transaction table looks like:
TRANSACTION
- id
- sender (User)
- recipient (User)
- object_id
- created_on
- modified_on
I've been trying creating a query for this, but I can't seem to figure it out. How can I track which objects belongs to a given user.
Many thanks in advance!
Geoffrey