Q: Array permutations in multidimensional array keeping the keys PHP For two days I've been running crazy trying to accomplish this, maybe you can enlighten me. This is for a horse betting permutation. Every time a user plays, I get a multidimensional array (2 levels). The first level contains the race ID, the the second level contains thee horses selected by the user for that race. It looks like this:
$play = array
(
    '4' => array(7, 32),
    '8' => array(4),
    '2' => array(9),
    '12' => array('5'),
    '83' => array('10', '11', '12', ''),
    '9' => array('3'),
);

I need to know what are all the possible combinations for that play. Which is easily done with this function:
function permutations(array $array)
{
    switch (count($array)) {
        case 1:
            return $array[0];
            break;
        case 0:
            throw new InvalidArgumentException('Requires at least one array');
            break;
    }

    $a = array_shift($array);
    $b = permutations($array);

    $return = array();
    foreach ($a as $key => $v) {
        if(is_numeric($v))
        {
            foreach ($b as $key2 => $v2) {
                $return[] = array_merge(array($v), (array) $v2);
            }
        }
    }

    return $return;
}

This returns an array with all the possible combinations beautifully. So far so good, and the result looks like this:
Array
(
    [0] => Array
        (
            [0] => 7
            [1] => 4
            [2] => 9
            [3] => 5
            [4] => 10
            [5] => 3
        )

    [1] => Array
        (
            [0] => 7
            [1] => 4
            [2] => 9
            [3] => 5
            [4] => 11
            [5] => 3
        )

    [2] => Array
        (
            [0] => 7
            [1] => 4
            [2] => 9
            [3] => 5
            [4] => 12
            [5] => 3
        )

    [3] => Array
        (
            [0] => 32
            [1] => 4
            [2] => 9
            [3] => 5
            [4] => 10
            [5] => 3
        )

    [4] => Array
        (
            [0] => 32
            [1] => 4
            [2] => 9
            [3] => 5
            [4] => 11
            [5] => 3
        )

    [5] => Array
        (
            [0] => 32
            [1] => 4
            [2] => 9
            [3] => 5
            [4] => 12
            [5] => 3
        )

)

My problem: I need the array "key" for every horse to be the "race ID", not 0,1,2,3. I need the result to be like this:
Array
(
    [0] => Array
        (
            [4] => 7
            [8] => 4
            [2] => 9
            [12] => 5
            [83] => 10
            [9] => 3
        )

    [1] => Array
        (
            [4] => 7
            [8] => 4
            [2] => 9
            [12] => 5
            [83] => 11
            [9] => 3
        )

    [2] => Array
        (
            [4] => 7
            [8] => 4
            [2] => 9
            [12] => 5
            [83] => 12
            [9] => 3
        )

    [3] => Array
        (
            [4] => 32
            [8] => 4
            [2] => 9
            [12] => 5
            [83] => 10
            [9] => 3
        )

    [4] => Array
        (
            [4] => 32
            [8] => 4
            [2] => 9
            [12] => 5
            [83] => 11
            [9] => 3
        )

    [5] => Array
        (
            [4] => 32
            [8] => 4
            [2] => 9
            [12] => 5
            [83] => 12
            [9] => 3
        )

)

How can I accomplish this? I know its a long post but I needed to graph this. I am having problems to wrap my head around the function recursion and I get totally lost in each loop.

A: I've got the same problem and Danny's solution wasn't good for me.
I manage thousand of permutation and store them in memory is damn expensive.
Here my solution:
/**
 * Calculate permutation of multidimensional array. Without recursion!
 * Ex.
 * $array = array(
 *   key => array(value, value),
 *   key => array(value, value, value),
 *   key => array(value, value),
 * );
 *
 * @copyright Copyright (c) 2011, Matteo Baggio
 * @param array $anArray Multidimensional array
 * @param function $isValidCallback User function called to verify the permutation. function($permutationIndex, $permutationArray)
 * @return mixed Return valid permutation count in save memory configuration, otherwise it return an Array of all permutations
 */
function permutationOfMultidimensionalArray(array $anArray, $isValidCallback = false) {

    // Quick exit
    if (empty($anArray))
        return 0;

    // Amount of possible permutations: count(a[0]) * count(a[1]) * ... * count(a[N])
    $permutationCount = 1;
    // Store informations about every column of matrix: count and cumulativeCount
    $matrixInfo = array();
    $cumulativeCount = 1;

    foreach($anArray as $aColumn) {

        $columnCount       = count($aColumn);
        $permutationCount *= $columnCount;

        // this save a lot of time!
        $matrixInfo[] = array(
            'count'           => $columnCount,
            'cumulativeCount' => $cumulativeCount
        );

        $cumulativeCount  *= $columnCount;
    }

    // Save the array keys
    $arrayKeys = array_keys($anArray);
    // It needs numeric index to work
    $matrix = array_values($anArray);
    // Number of column
    $columnCount = count($matrix);
    // Number of valid permutation
    $validPermutationCount = 0;
    // Contain all permutations
    $permutations = array();

    // Iterate through all permutation numbers
    for ($currentPermutation = 0; $currentPermutation < $permutationCount; $currentPermutation++) {

        for ($currentColumnIndex = 0; $currentColumnIndex < $columnCount; $currentColumnIndex++) {
            // Here the magic!
            // I = int(P / (Count(c[K-1]) * ... * Count(c[0]))) % Count(c[K])
            // where:
            // I: the current column index
            // P: the current permutation number
            // c[]: array of the current column
            // K: number of the current column
            $index = intval($currentPermutation / $matrixInfo[$currentColumnIndex]['cumulativeCount']) % $matrixInfo[$currentColumnIndex]['count'];

            // Save column into current permutation
            $permutations[$currentPermutation][$currentColumnIndex] = $matrix[$currentColumnIndex][$index];
        }

        // Restore array keys
        $permutations[$currentPermutation] = array_combine($arrayKeys, $permutations[$currentPermutation]);

        // Callback validate
        if ($isValidCallback !== false) {
            if ($isValidCallback($currentPermutation, $permutations[$currentPermutation]))
                $validPermutationCount++;
            // *** Uncomment this lines if you want that this function return all
            //     permutations
            //else
            //  unset($permutations[$currentPermutation]);
        }
        else {
            $validPermutationCount++;
        }

        // Save memory!!
        // Use $isValidCallback to check permutation, store into DB, etc..
        // *** Comment this line if you want that function return all
        //     permutation. Memory warning!!
        unset($permutations[$currentPermutation]);
    }

    if (!empty($permutations))
        return $permutations;
    else
        return $validPermutationCount;
}

//
// How to?
//

$play = array(
    '4'  => array(7, 32),
    '8'  => array(4),
    '2'  => array(9),
    '12' => array('5'),
    '83' => array('10', '11', '12', ''), // <-- It accept all values, nested array too
    '9'  => array('3'),
);

$start = microtime(true);

// Anonymous function work with PHP 5.3.0
$validPermutationsCount = permutationOfMultidimensionalArray($play, function($permutationIndex, $permutationArray){

        // Here you can validate the permutation, print it, etc...
        // Using callback you can save memory and improve performance.
        // You don't need to cicle over all permutation after generation.
        printf('
%d: %s
', $permutationIndex, implode(', ', $permutationArray));

        return true; // in this case always true
    });

$stop = microtime(true) - $start;

printf('

Performance for %d permutations

       Execution time: %f sec

       Memory usage: %d Kb
',
       $validPermutationsCount,
       $stop,
       memory_get_peak_usage(true) / 1024);

If someone has a better idea i'm here!

A: Here's what you need. I have commented as necessary:
function permutations(array $array)
{
    switch (count($array)) {
        case 1:
            // Return the array as-is; returning the first item
            // of the array was confusing and unnecessary
            return $array;
            break;
        case 0:
            throw new InvalidArgumentException('Requires at least one array');
            break;
    }

    // We 'll need these, as array_shift destroys them
    $keys = array_keys($array);

    $a = array_shift($array);
    $k = array_shift($keys); // Get the key that $a had
    $b = permutations($array);

    $return = array();
    foreach ($a as $v) {
        if(is_numeric($v))
        {
            foreach ($b as $v2) {
                // array($k => $v) re-associates $v (each item in $a)
                // with the key that $a originally had
                // array_combine re-associates each item in $v2 with
                // the corresponding key it had in the original array
                // Also, using operator+ instead of array_merge
                // allows us to not lose the keys once more
                $return[] = array($k => $v) + array_combine($keys, $v2);
            }
        }
    }

    return $return;
}

See it in action.
By the way, calculating all the permutations recursively is neat, but you might not want to do it in a production environment. You should definitely consider a sanity check that calculates how many permutations there are and doesn't allow processing to continue if they are over some limit, at the very least.

A: I improved Jon's function by merging his algorithm with the one I had initially. What I did, was check if the function was doing a recursion, if so, I use the original array_merge() (which was working), else I use Jon's array_combine() (to keep the arrays keys).
I'm marking Jon's answer as correct since he proposed a slick solution to keep the array keys intact.
function permutations(array $array, $inb=false)
{
    switch (count($array)) {
        case 1:
            // Return the array as-is; returning the first item
            // of the array was confusing and unnecessary
            return $array[0];
            break;
        case 0:
            throw new InvalidArgumentException('Requires at least one array');
            break;
    }

    // We 'll need these, as array_shift destroys them
    $keys = array_keys($array);

    $a = array_shift($array);
    $k = array_shift($keys); // Get the key that $a had
    $b = permutations($array, 'recursing');

    $return = array();
    foreach ($a as $v) {
        if(is_numeric($v))
        {
            foreach ($b as $v2) {
                // array($k => $v) re-associates $v (each item in $a)
                // with the key that $a originally had
                // array_combine re-associates each item in $v2 with
                // the corresponding key it had in the original array
                // Also, using operator+ instead of array_merge
                // allows us to not lose the keys once more
                if($inb == 'recursing')
                    $return[] = array_merge(array($v), (array) $v2);
                else
                    $return[] = array($k => $v) + array_combine($keys, $v2);
            }
        }
    }

    return $return;
}

Tested successfully with several array combinations.


Q: SUMIF SQL MS Access SELECT [doc type], [Open Amount],
    [customer number],
    COUNT([customer number]) As CountCustomerNumber,
    SUM(IIF([Open Amount]>'0', [Open Amount], 0)) AS sum_open_amount_pos,
    SUM(IIF([Open Amount]<'0', [Open Amount], 0)) As sum_open_amount_neg
FROM
(
    SELECT d.[customer number] & d.[membership number] AS CustMemb,
    d.[customer number],
    agg.[Open Amount],
    agg.[doc type],
    SUM(agg.[TotalSubOpenAmount]) AS SumOpenAmount
    FROM
    (
        SELECT [doc type],
        [customer number],
        SUM([Open Amount]) AS TotalSubOpenAmount
        FROM data
        WHERE [doc type] = 'RU'
        GROUP BY [doc type], [customer number], [Open Amount]
    ) agg
    INNER JOIN [data] d
    ON  d.[customer number] = agg.[customer number]
    GROUP  BY d.[customer number] & d.[membership number],
    d.[customer number],
    agg.[doc type],
    agg.[Open Amount]
) AS sub
GROUP BY [doc type], [customer number]
HAVING COUNT([customer number]) = 1

I am getting a Parameter Input on MS Access - Open Amount.
How do I reference the open amount in the from query?


Q: Did Brainiac ever appear in Lois and Clark? Did Brainiac ever appear in the Lois and Clark series in the '90s.  I do recall Mister Mxyzptlk appeared, and so did Zod and Luthor; but did Brainiac?

A: No.  He is not credited on IMDB.  Nor do I remember him appearing on the show.  A search on the Wikia devoted the show turns up nothing about Brainiac either.


Q: Navigationview Set SelectedItem for sub-menu item in UWP app I trying to set default selected item for navigationview by
DashboardMenuItem.IsExpanded = true;
 Microsoft.UI.Xaml.Controls.NavigationViewItem selectedItem =(Microsoft.UI.Xaml.Controls.NavigationViewItem)DashboardMenuItem.MenuItems[0];
NavView.SelectedItem = selectedItem;

Here is my XAML
<MUXC:NavigationView.MenuItems>
                <MUXC:NavigationViewItem
                    x:Name="DashboardMenuItem"
                    Content="{x:Bind DashboardLabel}"
                    Foreground="#FFFFFF"
                    ToolTipService.ToolTip="{x:Bind DashboardLabel}">
                    <MUXC:NavigationViewItem.Icon>
                        <FontIcon FontFamily="Segoe MDL2 Assets" Glyph="" />
                    </MUXC:NavigationViewItem.Icon>
                    <MUXC:NavigationViewItem.MenuItems>
                        <MUXC:NavigationViewItem
                            x:Name="ListofPersonMenuItem"
                            Content="{x:Bind ListofPersonLabel}"
                            Foreground="#FFFFFF"
                            ToolTipService.ToolTip="{x:Bind ListofPersonLabel}" />
                        <MUXC:NavigationViewItem
                            x:Name="ListofDiedPersonsMenuItem"
                            Content="{x:Bind ListofDiedPersonsLabel}"
                            Foreground="#FFFFFF"
                            ToolTipService.ToolTip="{x:Bind ListofDiedPersonsLabel}" />
                    </MUXC:NavigationViewItem.MenuItems>
                </MUXC:NavigationViewItem>

But my menu item just have a highlight background only, still don't have the left bar like when we select by clicking. Picture link below (sorry because I cannot post the image yet)
https://i.gyazo.com/f2953c8f092534ea26ceb7fef0120de2.png
So, do you have any suggestion for this please?
Thank in advance

A:
Navigationview Set SelectedItem for sub-menu item in UWP app

During the testing, the problem is expend animation block select animation that make item indicator dismiss. Currently we have a workaround that add a task delay before set SelectedItem. It will do select animation after DashboardMenuItem expend.
DashboardMenuItem.IsExpanded = true;
Microsoft.UI.Xaml.Controls.NavigationViewItem selectedItem = (Microsoft.UI.Xaml.Controls.NavigationViewItem)DashboardMenuItem.MenuItems[0];
await Task.Delay(100);
MainNavigation.SelectedItem = selectedItem;


Q: Background disappears when expanding an element CSS? When I add a new element in (using JavaScript event listener to set display from none to grid) the background of the body behind and around the element (which is set to 80% width) goes solid white. If I remove html tag from the following code it fixes it but then the body background image doesn't fill the entire screen on mobile. Really stuck on a fix if anyone can help?
photo below after the code
Thank you
body css
body, html {
    padding: 0;
    background: url(/resources/clearday.jpg);
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    height: 100%;
    width: 100%;
    margin: 0 auto;
}

element css
.extraForecast {
    display: grid;
    align-items: center;
    grid-template-columns: repeat(4, 1fr);
    grid-template-rows: repeat(4, 4fr) 1fr;
    width: 80%;
    margin: 0 auto;
    padding: 0;
    font-size: 2.15rem;
    text-align: center;
    background-color:white;
    opacity: 0.7;
    border-radius: 8px;
    margin-top: 2rem;
    padding: 0;
}

image of the issue

A: I've only tested quickly on mobile, but stopping the background image from scrolling with the page seemed to fix it.
To do this I added
background-attachment: fixed;

to the CSS for body, html


Q: Upgrading NC30 M16 C Compiler: va_arg issue In my NC30 M16C compiler version 5, I had the following macros used by previous programmer. We use this macros in the "printf()", "sprintf()" etc functions.
typedef unsigned char * va_list;
#define va_start( args, first ) args = (va_list) ( (unsigned short) &first + sizeof( first ) )
#define va_arg( args, type ) *( (type *) args )++
#define va_end( args )

When I compile this code with NC30 M16C compiler version 6, then it is giving me the error "Invalid lvalue".
Here is the part of the entire error message:
clib.c(253) :  C2700 (E) invalid lvalue
===>    unum = va_arg( args, unsigned int );
clib.c(293) :  C2700 (E) invalid lvalue
===>    fch = va_arg( args, far char * );
clib.c(299) :  C2700 (E) invalid lvalue
===>    nch = va_arg( args, char * );
clib.c(305) :  C2700 (E) invalid lvalue
===>    unum = va_arg( args, unsigned int );
clib.c(323) :  C2700 (E) invalid lvalue
===>    ulong = va_arg( args, unsigned long );
clib.c(341) :  C2700 (E) invalid lvalue
===>    llong = va_arg( args, unsigned long long );
clib.c(359) :  C2700 (E) invalid lvalue
===>    ulong = va_arg( args, unsigned long );
clib.c(377) :  C2700 (E) invalid lvalue
===>    unum = va_arg( args, unsigned short );
clib.c(382) :  C2700 (E) invalid lvalue
===>    ft = va_arg( args, float );
clib.c(519) :  C2694 (E) unknown variable source
===>    *source++ = zeropad ? '0' : ' ';
clib.c(527) :  C2694 (E) unknown variable source
===>    *source++ = '%';
clib.c(532) :  C2700 (E) invalid lvalue
===>    snum = va_arg( args, signed int );
clib.c(550) :  C2694 (E) unknown variable source
===>        *source++ = *tempptr;
clib.c(556) :  C2700 (E) invalid lvalue
===>    fch = va_arg( args, far char * );
clib.c(558) :  C2694 (E) unknown variable source
===>        *source++ = *fch++;
clib.c(564) :  C2700 (E) invalid lvalue
===>    nch = va_arg( args, char * );
clib.c(566) :  C2694 (E) unknown variable source
===>        *source++ = *nch++;
clib.c(572) :  C2700 (E) invalid lvalue
===>    unum = va_arg( args, unsigned int );

Here is one of the function in which we have used these micros. This function is the same function as "printf" but named it zwPrintf():
int zwPrintf( far char * format, ... ) {
    zwVAList args;
    unsigned int unum;
    unsigned char temp[ FIELD_BUFF_SIZE + 1 ];      /* for formatting numbers (max length for long decimal) */
    unsigned char * tempptr;
    int zeropad, minfield, counter;
    far char * fch;
    char * nch;
    unsigned long ulong;
    int negative;
    float ft, mantissa;
    unsigned long long llong;
    //unsigned char mychar;
    //unsigned char *mychar_p;
    //unsigned int *mytest_p;

    va_start( args, format );

    while( *format ) {
        if( *format == '%' ) {
            format++;
            zeropad = 0;
            minfield = 0;
            negative = 0;
            if( *format == '0' )
                zeropad = 1;            /* we want zero padding to field width */
            while( *format >= '0' && *format <= '9' ) {
                /* we are specifying field width */
                minfield *= 10;
                minfield += *format - '0';
                format++;
            }
            if( minfield > FIELD_BUFF_SIZE ) {      /* we want a field width greater than our field buffer, pad misc */
                for( counter = 0; counter < minfield - FIELD_BUFF_SIZE; counter++ )
                    zwPutc( (unsigned char) ( zeropad ? '0' : ' ' ) );
                minfield = FIELD_BUFF_SIZE;
            }
            switch( *format ) {
                case '%':   /* literal % */
                    zwPutc( '%' );
                break;

                case 'd':   /* signed decimal output */
                    unum = va_arg( args, unsigned int );        /* pull unsigned, and do math ourselves (to avoid confusion) */

                    //mychar='a';
                    //mychar_p = &mychar;
                    //mytest_p = ((unsigned int*)mychar_p);
                    //mytest_p++;
                    //unum = *mytest_p;
                    //unum = (*((unsigned int*)args))++;
                    //unum = (*((unsigned int*)args))++;

                    /* convert to decimal (backward) */
                    if( unum >= 0x8000 ) {      /* number is -'ve */
                        negative = 1;
                        unum = ~unum + 1;           /* make number +'ve */
                    }

                    tempptr = &temp[ FIELD_BUFF_SIZE ];
                    counter = 0;
                    do {
                        if( unum )
                            *tempptr-- = ( unum % 10 ) + '0';
                        else {
                            if( negative && ( zeropad == 0 ) ) {
                                *tempptr-- = '-';
                                negative = 0;
                            }
                            else
                                *tempptr-- = ( zeropad || counter == 0 ) ? '0' : ' ';
                        }
                        unum /= 10;
                        counter++;
                    } while( unum || counter < minfield );
                    /* output the string */
                    if( negative )
                        zwPutc( '-' );
                    for( tempptr++; tempptr <= &temp[ FIELD_BUFF_SIZE ]; tempptr++ )
                        zwPutc( *tempptr );
                break;

                case 's':   /* far char * */
                    fch = va_arg( args, far char * );
                    while( *fch )
                        zwPutc( *fch++ );
                break;

                case 'S':   /* near char * (extension) */
                    nch = va_arg( args, char * );
                    while( *nch )
                        zwPutc( *nch++ );
                break;

                case 'x':   /* hexadecimal */
                    unum = va_arg( args, unsigned int );
                    /* convert to hexadecimal (backward) */
                    tempptr = &temp[ FIELD_BUFF_SIZE ];
                    counter = 0;
                    do {
                        if( unum )
                            *tempptr-- = zwHexToAsc( (unsigned char) unum & 0x0F );
                        else
                            *tempptr-- = ( zeropad || counter == 0 ) ? '0' : ' ';
                        unum >>= 4;
                        counter++;
                    } while( unum || counter < minfield );
                    /* output the string */
                    for( tempptr++; tempptr <= &temp[ FIELD_BUFF_SIZE ]; tempptr++ )
                        zwPutc( *tempptr );
                break;

                case 'i':   /* unsigned long int decimal (extension) */
                    ulong = va_arg( args, unsigned long );
                    /* convert to decimal (backward) */
                    tempptr = &temp[ FIELD_BUFF_SIZE ];
                    counter = 0;
                    do {
                        if( ulong )
                            *tempptr-- = (unsigned char)( ulong % 10 ) + '0';
                        else
                            *tempptr-- = ( zeropad || counter == 0 ) ? '0' : ' ';
                        ulong /= 10;
                        counter++;
                    } while( ulong || counter < minfield );
                    /* output the string */
                    for( tempptr++; tempptr <= &temp[ FIELD_BUFF_SIZE ]; tempptr++ )
                        zwPutc( *tempptr );
                break;

                case 'L':   /* unsigned long long decimal (extension) */
                    llong = va_arg( args, unsigned long long );
                    /* convert to decimal (backward) */
                    tempptr = &temp[ FIELD_BUFF_SIZE ];
                    counter = 0;
                    do {
                        if( llong )
                            *tempptr-- = (unsigned char)( llong % 10 ) + '0';
                        else
                            *tempptr-- = ( zeropad || counter == 0 ) ? '0' : ' ';
                        llong /= 10;
                        counter++;
                    } while( llong || counter < minfield );
                    /* output the string */
                    for( tempptr++; tempptr <= &temp[ FIELD_BUFF_SIZE ]; tempptr++ )
                        zwPutc( *tempptr );
                break;

                case 'h':   /* unsigned long int hexadecimal (extension) */
                    ulong = va_arg( args, unsigned long );
                    /* convert to hexadecimal (backward) */
                    tempptr = &temp[ FIELD_BUFF_SIZE ];
                    counter = 0;
                    do {
                        if( ulong )
                            *tempptr-- = zwHexToAsc( ( (unsigned char) ulong ) & 0x0F );
                        else
                            *tempptr-- = ( zeropad || counter == 0 ) ? '0' : ' ';
                        ulong >>= 4;
                        counter++;
                    } while( ulong || counter < minfield );
                    /* output the string */
                    for( tempptr++; tempptr <= &temp[ FIELD_BUFF_SIZE ]; tempptr++ )
                        zwPutc( *tempptr );
                break;

                case 'c':
                    unum = va_arg( args, unsigned short );
                    zwPutc( (char) unum );
                break;

                case 'f':
                    ft = va_arg( args, float );
#if 0
                    /* convert to decimal (backward) */
                    if( ft < 0 ) {      /* number is -'ve */
                        negative = 1;
                        ft = -ft;
                    }

                    tempptr = &temp[ FIELD_BUFF_SIZE ];
                    counter = 0;

                    /* split float to integer and mantissa part */
                    ulong = ft / 1;
                    mantissa = ft - ( float )ulong;

                    /* get integer part */
                    do {
                        if( ulong ){
                            *tempptr-- = (unsigned char)( ulong % 10 ) + '0';
                        }
                        else {
                            *tempptr-- = ( zeropad || counter == 0 ) ? '0' : ' ';
                        }
                        ulong /= 10;
                        counter++;
                    } while( ulong || counter < minfield );

                    if ( negative ) {
                        temp[ 0 ] = '-';
                        zwMemcpy( &temp[ 1 ], &temp[ FIELD_BUFF_SIZE - counter ], counter );        //change to right position
                        counter++;
                    }
                    else
                        zwMemcpy( &temp[ 0 ], &temp[ FIELD_BUFF_SIZE - counter ], counter );

                    temp[ counter++ ] = '.';

                    /* get mantissa part */
                    tempptr = &temp[ counter ];
                    do {
                        unum = ( mantissa * 10 ) / 1;
                        if( unum ){
                            *tempptr++ = (unsigned char)( unum ) + '0';
                        }
                        else {
                            *tempptr++ = '0';
                        }

                        mantissa = ( float ) ( mantissa * 10.0 - ( float )unum ) * 10.0;
                        counter++;
                    } while( mantissa > 0 || counter < minfield );

                    for( unum = 0; unum < counter; unum++ )
                        zwPutc( temp[ unum ] );

                    /* convert to decimal (backward) */
                    if( ft < 0 ) {      /* number is -'ve */
                        negative = 1;
                        ft = -ft;
                    }

                    tempptr = &temp[ FIELD_BUFF_SIZE ];
                    counter = 0;
                    do {
                        if( ft >= 1.0 ){
                            *tempptr-- = ( ft % 10.0 ) + '0';
//                          *tempptr-- = ( ft * 10 - ( ( ft * 100 ) / 10 ) ) + '0';
                        }
                        else {
                            if( negative && ( zeropad == 0 ) ) {
                                *tempptr-- = '-';
                                negative = 0;
                            }
                            else
                                *tempptr-- = ( zeropad || counter == 0 ) ? '0' : ' ';
                        }
                        ft /= 10;
                        counter++;
                    } while( ft >= 1.0 || counter < minfield );

                    /* output the string */
                    if( negative )
                        zwPutc( '-' );

                    for( tempptr++; tempptr <= &temp[ FIELD_BUFF_SIZE ]; tempptr++ )
                        zwPutc( *tempptr );
#endif
                break;

                case 0:     /* end of string (malformed string anyway) */
                    va_end( args );
                    return -1;      /* error */
                break;
            }
        }
        else
            zwPutc( *format );

        format++;
    }

    va_end( args );

    return -1;
}

Please guide me, what should I do to correct this issue.
Thanks in advance.

A: Could you try to replace:
#define va_arg( args, type ) *( (type *) args )++

with
#define va_arg( args, type ) *( (type *) args ), args += sizeof (type)

Explanation:
You get the compilation error because this expression:
((type *) args )++

is invalid in C: the result of a cast is not a lvalue and the postfix ++ operator requires its operand to be a lvalue. A lot of compilers are lax with this constraint but apparently yours is not (or the new version is stricter).
Also note that the proposed workaround should work in you program with simple assignment expressions like:
unum = va_arg( args, unsigned int );

because = has higher precedence than the comma operator.
EDIT:
another (maybe even better) solution: you should be able to bypass the fact the result of a cast is not a lvalue using this solution:
#define va_arg( args, type ) *( *(type **) &args )++


Q: Calling ls or less in bash based on file type I often accidentally perform ls on a file, when I meant to do less.
Is there a way to make an alias, or a function, that will perform ls on a directory, and less on a file.

A: The basic thing you want might look something like this:
function my_less()
  {
  obj=$1
  shift
  test -d $obj && ls $obj $@
  test -f $obj && less $obj $@
  }

Then
my_less thing

will do an ls or a less depending on the type.
The obj=$1 grabs the first argument to the function. The shift shifts the remaining arguments "to the left" and $@ is the current argument list.
If you want to have some rudimentary processing of switches, you can extend this function something like this:
function my_less()
  {
  switches=
  obj=
  while true
  do
    case $1 in
      -*)
        switches="$switches $1"
        shift
        ;;
      *)
        obj=$1
        shift
        break
        ;;
    esac
  done
  test -d $obj && ls $switches $obj $@
  test -f $obj && less $switches $obj $@
}

This will collect all the leading switches and set obj to the first non-switch.  This, will do the wrong thing frequently, but it is just a suggestion for a next step.


Q: Angular 4.3 HttpClient - How to use HttpHeaders and interceptor properly? I need to send headers to my HttpRequest.
I already searched here and I have already tried with a few answers I have found, but none of them worked.
The headers are not being sent to api and if I inspect the clonedRequest object, it does not show the headers. That is my code:
public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  // Clone the request to add the new header.
  const clonedRequest = req.clone();

  clonedRequest.headers.set("ModuleId", this.dnnContext.moduleId);
  clonedRequest.headers.set("TabId", this.dnnContext.tabId);

  // Pass on the cloned request instead of the original request.
  return next.handle(clonedRequest);
}

What am I missing?

A: Thats because the instances of classes from the new HttpClient module are immutable. So you need to reassign all the properties that you mutate. This translates into the following in your case:
public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  // Clone the request to add the new header.
  const headers = req.headers.set("ModuleId", this.dnnContext.moduleId).set("TabId", this.dnnContext.tabId);
  const clonedRequest= red.clone({
   headers: headers
  });

  // Pass on the cloned request instead of the original request.
  return next.handle(clonedRequest);
}

A: I have faced similar issue & figured out your 2nd(TypeError: CreateListFromArrayLike called on non-object) issue, for some
reason if you pass number type(it has type check but if var type is any it allows & it was the case for me) value in header(ModuleId or TabId in your case) it throws this error so you can convert it
to string while passing like:
const authReq = req.clone({
  headers: req.headers.set('ModuleId', this.dnnContext.moduleId.toString()).set('TabId', this.dnnContext.tabId.toString())
});
// Pass on the cloned request instead of the original request.
return next.handle(authReq);

Also replied on your github issue.


Q: this between square brackets I'm new to C++ and while learning and documenting about the subject, I stumbled accross something that intrigued me :
[this](type argument)
{
    // code
}

What does [this] stand for in this function ?
Here's the whole function in which I found this :
  void do_accept()
  {
    acceptor_.async_accept(socket_,
        [this](boost::system::error_code ec)
        {
          if (!ec)
          {
            std::make_shared<chat_session>(std::move(socket_), room_)->start();
          }

          do_accept();
        });
  }

(It's one of the boost.asio's asynchronous server example)


Q: Keyboard is moving view little too up I made simple solution, textfield is pressed, open keyboard and move view up. But the problem is, it is moving it a little too hight and covering first textField. I do not want to make scrollView for this. is there any other solutions?
Like this I do what I described above:
NotificationCenter.default.addObserver(self, selector: #selector(RegisterViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(RegisterViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

func keyboardWillShow(notification: NSNotification) {

        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            if self.view.frame.origin.y == 0{
                self.view.frame.origin.y -= keyboardSize.height
            }
        }

    }

    func keyboardWillHide(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            if self.view.frame.origin.y != 0{
                self.view.frame.origin.y += keyboardSize.height
            }
        }
    }

Here you can see what it does:

A: You have some options: for example:

*

*move the labels differently depending on the  texfield tapped (less if the first field, more for the last)

*change your Interface so that all your text fields use just the space available when keyboard is up

A: There are many third party libraries available like https://github.com/hackiftekhar/IQKeyboardManager or https://github.com/michaeltyson/TPKeyboardAvoiding.
You can use any of them, and forgot about keyboard handling by yourself. These cool libraries take care of most of the things.


Q: 'ClientFilter' validation failed: client view is too loose . each client should include one project only I am trying to do same operations that I do with perforce GUI using command line.
When I tried to do p4 edit on any file, it said Client '<host-name>' unknown - use 'client' command to create it.
So, I tried p4 client -o <my-workspace-name> | p4 client -i but this returned:
Error in client specification.
'ClientFilter' validation failed:
======================================================
    client view is too loose !!!
    each client should include one project only
======================================================

I have no experience of p4 tool. Please help me explain what it means with client view too loose !!!

A: This is a trigger that your admin has set up.  Based on the error, I surmise that they want you to set up your client's View to only include one project (they want to keep you from syncing down the entire world when you set up your new client).
To create a new client, run:
p4 set P4CLIENT=your_workspace_name
p4 client

and take a look at the form that pops up.  The View field defines which part of the depot(s) your client will "see" and operate on.  According to the error message, your admin wants you to restrict this to a single "project" -- I don't know what that means in this context (maybe it means just a single depot, or maybe a single folder in a particular depot?) so you might need to talk to your admin about it, or maybe browse around in the GUI and try to glean from context clues (i.e. names of directories) what that message is referring to.
Just to use a made-up example, if you have a few different depots your default ("loose") View might look like:
//depot_one/... //your_workspace_name/depot_one/...
//mumble/... //your_workspace_name/mumble/...
//widgets/... //your_workspace_name/widgets/...

and if you want to only map the project //mumble/core to your workspace root, you'd change that View to:
//mumble/core/... //your_workspace_name/...


Q: What's the best way to keep adding new points to glBufferData? I am making an experiment with OpenGL to find what's the best/most efficient way to very frequently add new data to glBufferData.
To do this, I wrote a small 2D paint program and simply keep adding points when I move the mouse.
The whole function looks like this:
void addPoint(double x, double y)
{
    glBindBuffer(GL_ARRAY_BUFFER, pointVertBuffObj);
    if (arrayOfPointCapacity < numOfPoints + 1) {
        U32 size = (arrayOfPointCapacity + 8) * sizeof(Point2);
        Point2 *tmp = (Point2*)realloc(arrayOfPoints, size);
        arrayOfPoints = tmp;
        arrayOfPointCapacity += 8;
    }
    arrayOfPoints[numOfPoints].x = x,
    arrayOfPoints[numOfPoints].y = y;
    U32 offset = numOfPoints * sizeof(Point2);
    glBufferData(GL_ARRAY_BUFFER, numOfPoints * sizeof(Point2), arrayOfPoints, GL_DYNAMIC_DRAW);
    numOfPoints++;
}

Having to reset glBufferData with new data each time I add a point seems absolutely crazy. I thought about using glBufferData to allocate a large array of points and setting these points up with glBufferSubData. When the size of the buffer becomes too small, then I call glBufferData again increasing the size of the buffer, and copying back existing points to it.
Ideally, I would prefer to avoid storing the point data in the computer memory and keep everything in the GPU memory. But when I would resize the buffer, I would have to copy the data back from the buffer to the CPU, then resize the buffer, and finally copy the data back to the buffer from the CPU. All this, also seems inefficient.
Any idea? What's best practice?

A:
When the size of the buffer becomes too small, then I call glBufferData again increasing the size of the buffer, and copying back existing points to it.

Not a bad idea. In fact that's the recommended way of doing these things. But don't make the chunks too small.

Ideally, I would prefer to avoid storing the point data in the computer memory and keep everything in the GPU memory.

That's not how OpenGL works. The contents of a buffer objects can be freely swapped between CPU and GPU memory as needed.

But when I would resize the buffer, I would have to copy the data back from the buffer to the CPU, then resize the buffer, and finally copy the data back to the buffer from the CPU. All this, also seems inefficient.

Correct. You want to avoid copies between OpenGL and the host program. That's why there is in OpenGL-3.1 and later the function glCopyBufferSubData to copy data between buffers. When you need to resize a buffer you can as well create a new buffer object and copy from the old to the new one^1.

[1]: maybe you can also do resizing copys within the same buffer object name, by exploiting name orphaning; but I'd first have to read the specs if this is actually defined, and then cross fingers that all implementations get this right.

A: I made a program for scientific graphing before, that could add new data points in real-time.  What I did was create a fairly large fixed size buffer with flag GL_DYNAMIC_DRAW, and added individual points to it with glBufferSubData.  Once it filled, I created a new buffer with flag GL_STATIC_DRAW and moved all the data there, then started filling the GL_DYNAMIC_DRAW buffer again from the beginning.  So I ended up with a small number of static buffers, one dynamic buffer, and since they were all equal size (with monotonically increasing x coordinates) calculating which buffers to use to draw any given segment of the data was easy.  And I never had to resize any of them, just keep track of how much of the dynamic buffer was used and only draw that many vertices from it.
I don't think I used glCopyBufferSubData as datenwolf suggests, I kept a copy in CPU memory of the data in the dynamic buffer, until I could flush it to a new static buffer.  But GPU->GPU copy would be better.  I still would allocate more chunk-sized buffers and avoid resizing.


Q: ERROR TypeError: Cannot read property 'group_status' of undefined in console I am getting this error in console and this error increasing continously, I am using two way binding with ngModel with interface. I have attached the screens of my code.
screens:
This is the component part where getting basicinfo from server in json format calling service

This is Error which I am getting in console

HTML part where I am fatching data from interface json

This is Interface which i am using

A: Issue is coz of this line :
[(ngModel)]='basicinfo.website'

Either change this to
[ngModel]='basicinfo?.website'

or
Provide initial value before ngModel initialisation for 2 way binding
basicinfo = { 'website' : '' };

[(ngModel)]='basicinfo.website'


Q: mysqldump - select table if it contains a specific string I have a pretty big local WordPress Multisite installation, and this is mirrored on a  live server, so I can develop a site locally and upload it for a client to see (it's sub-domain based). I have written a custom shell script to upload the database from my local machine to the live server, which uses sed to change all instances of the local domain name to the live domain name. It then commits and pushes it by git and the live server automatically pulls it, takes a backup and applies the new file.
However, this has become problematic in the last month or so. As I've got more client work, and they have been editing their sites live on the server, and I've been pushing new work to the server for other clients to take a look at, I've been overwriting changes on the live database.
What I need is to be able to add a flag or something when I call the shell script file (sh push.sh) that indicates what tables in the database need to be pushed live. Each site in the WordPress Multisite database has a number, e.g network_17_posts. So if I could a table number state when I called my shell script, like sh push.sh --table=17 and it would only upload site 17's data, and not overwrite anything else, that would be awesome. As a bonus, if I could specify multiple numbers, so I could upload multiple sites at a time, that would be amazing!
As a reference, here is my current shell script for pushing the database live (it could probably be 10x better, but I'm primarily a front-end/PHP dev, not shell script!):
rm -rf db_sync.sql
mysqldump -u root -ppassword db_name > db_sync.sql
sed 's/localdomain.dev/livedomain.com/g' db_sync.sql > new_db_sync.sql
rm -rf db_sync.sql
mv new_db_sync.sql db_sync.sql
git add db_sync.sql
read -p "Enter Commit Message: " commit_message
git commit -m "$commit_message"
git push -u web master

A: See dumpting a table using mysqldump.  Assuming you have the table names, or a list of table names, you could either dump them all with one command or loop:
: > db_sync.sql
for table in tableNames; do
    mysqldump -u root -ppassword db_name table >> db_sync.sql
done

To get the table names:
number=17
echo "select TABLE_NAME from information_schema.tables where TABLE_NAME like '%\_$number\_%' and TABLE_SCHEMA = 'databasename'" | \
    mysql -udbuser -pdbpassword databasename

So, if you have multiple numbers, e.g. as command line arguments, you can put this all together:
sql="select TABLE_NAME from information_schema.tables where TABLE_NAME like '%\_$number\_%' and TABLE_SCHEMA = 'databasename'"
# truncate/create the dump file
: > db_sync.sql
# loop through the command line arguments
for number in $@; do
    # for each tableName from the sql ...
    while read tableName; do
        # append to the dump file
        mysqldump -u root -ppassword db_name $tableName >> db_sync.sql
    done < <( echo $sql | mysql -udbuser -pdbpassword databasename | tail -n +2)
done

This will work if you put the numbers on the command line:
./push.sh 17 18 19

See the getopts tutorial for more information about processing command line arguments if you want to get complicated. Here is a short example of getting multiple arguments in an array:
numbers=()
while getopts ":t:" opt "$@"; do
    case "$opt" in
        t) numbers+=($OPTARG) ;;
    esac
done

for number in ${numbers[@]}; do
    echo $number
done

For example:
$ ./test.sh -t 17 -t 18 -t 19
17
18
19


Q: How to do conditional formatting on Chart axis values? I have a chart where I want to format values based on a cell selected type: "Percentage" or "Number".
If "Percentage" is selected I want to display chart values like "0.00%", else I want to display values: "# ##0"
I found only a way to have only one number format :

Also The section Conditionnal Formating is disabled when selecting the chart.
Is there a way to make this happend ?


Q: Rails + Activerecord: How to show records with "ranking ASC" first, then show the rest of the records "name ASC"? I have 2 columns in my awards table: ranking (integer) and name (string). I want to create a scope that shows all the records with the ranking column filled in in ascending order (1, 2, 3...), and then the rest of the records that don't have a ranking to show by name ascending (a, b, c) so it would look like this:

*

*ranking: 1, name: "zz"

*ranking: 2, name: "aaa"

*ranking: nil, name: "bbbb"

*ranking: nil, name: "ccc"

*ranking: nil, name: "ddd"

*etc...

This doesn't seem to work: scope :book_form_sort_order, -> { order("ranking ASC, name ASC").group(:ranking) }

A: scope :book_form_sort_order, -> { order("ranking IS NULL, ranking ASC, name ASC") }


Q: Passing multiple values for Laravel components from the view resources/views/index.blade.php
<x-card title="Products" body="Add or manage products" btn-add-id="addProduct"  />

app/view/component/card.php
    public $title;
    public $body;
    public $btn_add_id;
    public $btn_manage_id;

    public function __construct($title, $body, $btn_add_id, $btn_manage_id)
    {
        $this->title = $title;
        $this->body = $body;
        $this->btn_add_id = $btn_add_id;
        $this->btn_manage_id = $btn_manage_id;
    }

resources/views/components/card.blade.php

{{ $title }}

{{ $body }}

      <button class="btn btn-primary py-1" id="{{ $btn_add_id }}">
         Add
      </button>

My question: I want to make a reusable card component of bootstrap. So I passed several values to the card from the view page but throws me an error saying 'Unresolvable dependency resolving, highly appreciate if somebody can teach me how to pass multiple data to the components and use them.


Q: Highcharts - categorial data values represented by distinct dots? In highcharts, I have a bunch of simple, standartized categorial data. See fiddle here.
        series: [{
        name: 'sample element 1',
        data: [3, 3, 2]
    }, {
        name: 'sample element 2',
        data: [1, 4, 3]
    }, {
        name: 'sample element 3',
        data: [2, 4, 4]
    }, {
        name: 'sample element 4',
        data: [4, 2, 2]
    }]

Is it possible with highcharts to display a categorial scatter diagram, only without the dot overlap in the categories, in the manner shown below? Each value would have its own dot representative, showing distributions for each variable in that way.

Advanced feature: When hovering over a single value dot, the lines between all dots of the corresponding sample element should reappear so that the connections between the values become obvious.
Would that take a lot of deep code customization, or am I better off doing that with a different framework like d3.js? Thanks for ideas!

A: In case when values are the same, there are printed in the same place. But you can use http://api.highcharts.com/highcharts#plotOptions.series.pointPlacement to move serie.

A: I have typically done this by adding a decimal to the x value of the points that need to 'stack', as it were.
There isn't a great (easy) way to do it dynamically that I have found, but if your values are going to fall within a fairly controlled range, it works well.
Example:

*

*http://jsfiddle.net/zew9dt8e/2/


Q: Using audioplayers to play a single note from a button I am doing an outdated tutorial on the audioplayers package and just trying to play a single note from when the button is pressed.  I am not able to get it to work, can someone please help
import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';

void main() => runApp(XylophoneApp());

class XylophoneApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SafeArea(
          child: Center(
            child: TextButton(
              onPressed: () {
                final player = AudioCache();
                player.play('note1.wav'); //ERROR THAT 'play' method is not valid
              },
              child: Text('Click Me'),
            ),
          ),
        ),
      ),
    );
  }
}

A: In order to play sound from assets, you need a AudioPlayer and set asset to it.
onPressed: () async {
    final player = AudioPlayer();
    await player.setAsset('note1.wav'); // make sure to add on pubspec.yaml and provide correct path
    player.play();
  }

A: Finally found the fix, the problem all had to do with the new version of audioplayers having all the functions in one class without having to import seperatly audiocache
onPressed: () {
   final player = AudioPlayer();
   player.play(AssetSource("note1.wav"));
}


Q: IoT project with raspberry-pi3 and Bluemix. Error : TwilioRestClient has been removed from this version of the library I'm doing a Internet of Thing(IoT) project, and I follow a sample from below sources. But I fail at last step when I push to start this app.
https://www.ibm.com/blogs/bluemix/2015/04/tutorial-using-a-raspberry-pi-python-iot-twilio-bluemix/
1. I am using 'cf push to start the app', it works until crash.
2. I am using 'cf logs python-iot-hackathon2 --recent' to see logs, and there are two errors
3. There is a python code that given from tutorial source, i think i should edit the code from line7~12, but I do not know how. If there is another problem, please teach me how to do it. Thanks.
ex. There are two error, if you can not see clearly.
1.
Err: You must give at least one requirement to install (see "pip help install")
2.
Err: Traceback (most recent call last):
Err: File "server.py". line12, in
Err: twilioClient = TwilioRestClient(twilio Account, twilio Token)
ERR: File "/home/vcap/deps/0/python/lib/python2.7/site-packages/twilio/base/obsolete.py", line 20. in new_func
Err:   .format(func.name)
Err: twilio.base.obsolete.obsoleteException:
TwilioRestClient has been removed from this version of the library. Please refer to current documentation for guidance.

A: For: 1. Err: You must give at least one requirement to install (see "pip help install")
You need to run this on the Raspberry PI:
sudo pip install twilio
If you don't have pip installed then run:
sudo apt-get install python3-pip
and then again: sudo pip install twilio
for 2. Err: Traceback (most recent call last): Err: File "server.py". line12
Basically the twilio client definition needs to be similar to:
from twilio.rest import Client
client = Client(account_sid, auth_token)
so from the trace, line 12 in server.py  should be similar to
from twilio.rest import Client //this should be also changed
twilioClient = Client(account_sid, auth_token) //this is line 12


Q: Does Weblogic 9.2 support Sun Jdk 1.6? Does anyone have experience running Weblogic 9.2 on JDK 1.6? I am having trouble finding that information on Oracle site. In the Supported Configurations page they just mention Sun 32/64bit JDK but I haven't found any references to specific java version.
I would like to upgrade from java 1.5 to 1.6, but we are not quite ready yet to upgrade Weblogic.

A: Java 1.5 is the supported version for WebLogic 9.2. It looks like 10.0.3 introduced Java 6 for RH AS 5, 64-bit.
Look here for links to info about each version of WebLogic. From there, you have to choose your operating system and architecture to find out what JVMs are supported.

A: Weblogc 9.2.1 - 9.2.3 doesnot support JDK 1.6, any patch/revision of JDK 1.5 will get supported .Latest on today's date is patch 22 of JDK 1.5.


Q: Developing a "Flash Briefing" on Google Home I publish a flash briefing skill on Amazon's Alexa. It is a brief news update on a specific topic. I provide the information to Alexa via a json file that is updated every 10 minutes.
I'd like to publish something similar on Google Home devices. However, when I look at DialogFlow, that API appears to be conversational-based. Is that the right API for this type of app? Is there a Template for flash-briefing-like apps (i.e., easy to launch apps that don't require any additional user input after launching)?

A: No, you don't need a conversational Action for what you're doing.
Depending on the specifics of how you're providing the content, you may wish to look at either Podcast Actions or News Actions. These methods document what Google is looking for to make structured content available to the Google Assistant.


Q: Load array havng lacs of records on server startup in php When we are starting the PHP server online,if at that time we want to load an array having lot of records in the web application before any users visit the homepage.Because loading a big array will take a lot of time when users visit the site online.So i want to load it on server start,so that when user comes he should get everything ready...
How can we load an array having lacs of records in server on starting in PHP.

A: I believe you are asking how to load and store a shared list of content, that all users using the application can access. This is so that each time a user loads a page you don't have to load the contents from a database.
This can be done easily with Java, as you mentioned, but with PHP you'll have to push shared application data outside of PHP... MemCache is one option.
See: How to set a global variable accessible throughout the application


Q: Use Spotify iOS SDK in India I am creating an streaming app and want to use the Spotify iOS SDK for the streaming purpose. But, the services of Spotify are not available in India. I have the Spotify premium account (based in US). The development will be held in India.
My question is, can I use the Spotify iOS SDK in India using a US based premium account without any proxy network?

A: Your question is: "Can I use the Spotify iOS SDK in India using a US based premium account without any proxy network?". Based on the fact that you're trying to create a streaming app, I'd think that the question you intended to ask is: "Is it possible to enable users to stream Spotify music in India?"
My answer:
I've just read (parts) of the Developer terms of the Spotify SDK. One thing I noticed was:

Streaming via the Spotify Platform shall only be made available to
  subscribers to the Premium Spotify Service.

So if I'm right, it is only possible to stream Spotify's music if your users have a Premium Spotify account, which currently isn't available in India, all by there self. It is however possible to use the iOS SDK in India, but this will exclude the possibility to stream (preview-)audio for non-premium users.

A: As far as I know, it's the account's country and not the location of the user what is used to determine if a user can access Spotify. In other words, with a US Premium account you can use Spotify wherever you are in the world as long as you keep paying for the subscription. Read more on this thread.
You should be able to use your account while developing your app. Of course, a user trying to create a Spotify account from India will see a "Spotify is not available in your country" message when trying to sign up, but users accessing from countries where Spotify is available won't have any problem in signing up and logging in to your app.

A: Three simple steps:

*

*Download any VPN app from App Store i.e., VPN 24.

*Go to App store account, change your region and country to USA by filling any sample address.

*Now search Spotify Music on App Store and Download it!

You'll have to keep VPN turned on while using Spotify otherwise it won't work.


Q: Creating a timetable using JavaScript I am trying to create a web page where user can create his own schedule. User can enter the values of lines and columns in some input to build a table in which the user will write his schedule. I use this javascript code:
  var p = document.getElementById('paragraph');
  var table = document.createElement('table');
  var tbody = document.createElement('tbody');
  table.appendChild(tbody);

  for (let i = 0; i < lines; i++){
    let tr = document.createElement('tr');
    for (let j = 0; j < columns; j++){
     let td = document.createElement('td');
    }
    tbody.appendChild(tr);
  }

  p.appendChild(table);

However, when I'am trying to add information to table cells, I can't write values to each of them. I've used .innerHTML but it doesn't work the way it needs to. The information will be written only to the beginning of the table.
Should I give id to each td and then address to them by id when I need to write the information? Or there is another way to write values to table cells?

A: I think you need something like this to insert the data.
We have insertRow(), which is pre-defined function which i used in this answer to insert new row and then inserted columns in it with insertCell function.

<!DOCTYPE html>

    <input type="text" id="input1" placeholder="Enter first col data" >
    <input type="text" id="input2" placeholder="Enter second col data" >

        default head row cell 1
        default head row cell 2

  <button type="button" onclick="myFunction()">add data to body row</button>

A: I think that you need to refer to your button in the js file and write a function that will be executed on the "onclick" event
In this function, you are accessing the table variable. By using the built in javaScript function «insertRow()» you are adding rows to your table. Then you should add cells to this row in which  information that users entered will be stored. This you can also do by using build in function «insertCell()»
Next, you access the fields in which the user has entered data
Retrieve values using the «value» built-in function
Using the built-in «innerHTML» function, draw cells with the information that you received in the previous step
You can look at the written code below for better assimilation of information
<!DOCTYPE html>

    <input type="text" id="firstColumn" placeholder="Enter data here" >
    <input type="text" id="SecondColumn" placeholder="Enter data here" >

        Name of first column

        Name of second column

  <button style="background-color: yellow;" type="button" id = "btn">Add</button>


Q: Why does this NSMutableArray lose a member when it initializes an NSMutableDictionary? There must be something I don't understand about dictionaries.  I have the following code:
NSArray *keys=[[NSArray alloc] initWithObjects:@"first person singular", @"second person singular", @"third person singular", @"first person plural", @"second person plural", @"third person singular", nil];
//This array logs a count of 6.

NSMutableArray *endingsPossible = [[NSMutableArray alloc] initWithObjects:@"iar", @"iēris", @"iētur", @"iēmur", @"iēminī", @"ientur", nil];
//This array logs a count of 6.

NSDictionary *setOfEndings = [[NSDictionary alloc] initWithObjects:endingsPossible forKeys:keys];
//This dictionary logs a count of 5.

How is one of the members getting lost?

A: "third person singular" key is repeated twice.

A: You have duplicate entries for your keys, third person singular. That is why you only get 5 objects. Change it to third person plural for expected output I guess.


Q: Sqlite wont save data added I'm making an app, which needs a sqlite database. I can add data and view it, but on each restart of the app, closing, reopening the data get deleted. Why is that?
DB Handler:
package com.spxc.wakeuptext.sql;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHandler extends SQLiteOpenHelper {

    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "contactsManager";

    // Contacts table name
    public static final String TABLE_CONTACTS = "contacts";

    // Contacts Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final String KEY_PH_NO = "phone_number";

    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
                + KEY_PH_NO + " TEXT" + ")";
        db.execSQL(CREATE_CONTACTS_TABLE);
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

        // Create tables again
        onCreate(db);
    }

    /**
     * All CRUD(Create, Read, Update, Delete) Operations
     */

    public // Adding new contact
    void addContact(WhiteList contact) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_NAME, contact.getName()); // Contact Name
        values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone

        // Inserting Row
        db.insert(TABLE_CONTACTS, null, values);
        db.close(); // Closing database connection
    }

    // Getting single contact
    WhiteList getContact(int id) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
                KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
                new String[] { String.valueOf(id) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        WhiteList contact = new WhiteList(Integer.parseInt(cursor.getString(0)),
                cursor.getString(1), cursor.getString(2));
        // return contact
        return contact;
    }

    // Getting All Contacts
    public List<WhiteList> getAllContacts() {
        List<WhiteList> contactList = new ArrayList<WhiteList>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                WhiteList contact = new WhiteList();
                contact.setID(Integer.parseInt(cursor.getString(0)));
                contact.setName(cursor.getString(1));
                contact.setPhoneNumber(cursor.getString(2));
                // Adding contact to list
                contactList.add(contact);
            } while (cursor.moveToNext());
        }

        // return contact list
        return contactList;
    }

    // Updating single contact
    public int updateContact(WhiteList contact) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_NAME, contact.getName());
        values.put(KEY_PH_NO, contact.getPhoneNumber());

        // updating row
        return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
                new String[] { String.valueOf(contact.getID()) });
    }

    // Deleting single contact
    public void deleteContact(WhiteList contact) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
                new String[] { String.valueOf(contact.getID()) });
        db.close();
    }

    // Getting contacts Count
    public int getContactsCount() {
        String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();

        // return count
        return cursor.getCount();
    }

}

And I have my activity which is adding 1 record on startup just to have something there. My activity / fragment:
package com.spxc.wakeuptext.frag;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockListFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.spxc.wakeuptext.R;
import com.spxc.wakeuptext.sql.DatabaseHandler;
import com.spxc.wakeuptext.sql.WhiteList;

public class Fragment_2 extends SherlockListFragment{

    private ArrayList<String> results = new ArrayList<String>();
    private String tableName = DatabaseHandler.TABLE_CONTACTS;
    private SQLiteDatabase newDB;
    private static final int ADD = 1;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        View v = inflater.inflate(R.layout.fragment_2, null);
        return v;
    }

    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        DatabaseHandler db = new DatabaseHandler(getActivity());
        db.addContact(new WhiteList("Ravi", "9100000000"));

        openAndQueryDatabase();
        displayResultList();
    }

    private void openAndQueryDatabase() {
        try {
            DatabaseHandler dbHelper = new DatabaseHandler(getActivity().getApplicationContext());
            newDB = dbHelper.getWritableDatabase();
            Cursor c = newDB.rawQuery("SELECT name, phone_number FROM " +
                    tableName, null);

            if (c != null ) {
                if  (c.moveToFirst()) {
                    do {
                        String firstName = c.getString(c.getColumnIndex("name"));
                        int age = c.getInt(c.getColumnIndex("phone_number"));
                        results.add("Name: " + firstName + ",Pne: " + age);
                    }while (c.moveToNext());
                }
            }
        } catch (SQLiteException se ) {
            Log.e(getClass().getSimpleName(), "Could not create or Open the database");
        } finally {
            if (newDB != null)
                newDB.execSQL("DELETE FROM " + tableName);
                newDB.close();
        }

    }

    private void displayResultList() {
        TextView tView = new TextView(getActivity());
        tView.setText("This data is retrieved from the database and only 4 " +
                "of the results are displayed");
        getListView().addHeaderView(tView);

        setListAdapter(new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_1, results));

        getListView().setTextFilterEnabled(true);

    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        MenuItem search = menu.add(0, ADD, 0, "Refresh");
        search.setIcon(android.R.drawable.ic_menu_add);
        search.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case ADD:
                addNumber();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    public void addNumber(){
        LayoutInflater factory = LayoutInflater.from(getActivity());

        final View textEntryView = factory.inflate(R.layout.text_entry, null);

        final EditText name = (EditText) textEntryView.findViewById(R.id.editText1);
        final EditText phone = (EditText) textEntryView.findViewById(R.id.editText2);

        name.setHint("Name");
        phone.setHint("Phone Number");

        final AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
        alert.setTitle(
          "Contact information").setView(
          textEntryView).setPositiveButton("Save",
          new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog,
             int whichButton) {
               DatabaseHandler db = new DatabaseHandler(getActivity());
               db.addContact(new WhiteList(name.getText().toString(), phone.getText().toString()));
               openAndQueryDatabase();
               displayResultList();
           }
          }).setNegativeButton("Cancel",
          new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog,
             int whichButton) {
             /*
             * User clicked cancel so do some stuff
             */
           }
          });
        alert.show();
    }
}

Why isn't my database data getting saved? I'm running the app on a real device. All the data get deleted on reopening the app. Any help is much appreciated!

A: This is because you are deleting all records from the table in every openAndQueryDatabase()
finally {
        if (newDB != null)
            newDB.execSQL("DELETE FROM " + tableName);
            newDB.close();
    }

A:
I guess your are again recreating the database again ..every time application
  starts

A: Yes, because creating your db code is in onCreate method.
    public void onCreate(SQLiteDatabase db) {
    String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
            + KEY_PH_NO + " TEXT" + ")";
    db.execSQL(CREATE_CONTACTS_TABLE);
}


Q: How to remove products from a JSON-formatted list? (using an ID) here is an example of the JSON generated from values retrieved from my database:
    {
    "product": [
        {
            "id": "1",
            "title": "producta",
            "size": "50",
            "weight": "1000",
            "quantity": "100",
            "cartID": "1"
        },
        {
            "id": "2",
            "title": "productb",
            "size": "50",
            "weight": "1000",
            "quantity": "100",
            "cartID": "2"
        },
        {
            "id": "3",
            "title": "productb",
            "size": "10",
            "weight": "9000",
            "quantity": "100",
            "cartID": "3"
        },
        {
            "id": "4",
            "title": "productd",
            "size": "100",
            "weight": "500",
            "quantity": "100",
            "cartID": "4"
        },
        {
            "id": "5",
            "title": "producta",
            "size": "45",
            "weight": "880",
            "quantity": "120",
            "cartID": "5"
        }
    ]
}

When the user selects to remove an item from the shopping cart, the variable $remove_cartid is passed to  my PHP page. If  $remove_cartid = 4, then the product with "cartID": "4" must be removed:
    {
    "product": [
        {
            "id": "1",
            "title": "producta",
            "size": "50",
            "weight": "1000",
            "quantity": "100",
            "cartID": "1"
        },
        {
            "id": "2",
            "title": "productb",
            "size": "50",
            "weight": "1000",
            "quantity": "100",
            "cartID": "2"
        },
        {
            "id": "3",
            "title": "productb",
            "size": "10",
            "weight": "9000",
            "quantity": "100",
            "cartID": "3"
        },
        {
            "id": "5",
            "title": "producta",
            "size": "45",
            "weight": "880",
            "quantity": "120",
            "cartID": "5"
        }
    ]
}

I have made several attempts using the PHP explode function to try and remove the product from the JSON list, but I feel that there is a better way (one that will actually work)
Any advice or help is greatly appreciated

A: $list = json_decode($jsonList, true);

foreach ($list['product'] as $key => $product) {
    if ($product['cartID'] == $remove_cartid) {
        unset($list['product'][$key]);
    }
}

$jsonList = json_encode($list);


Q: Pandas Similar Function to COUNTIFS Sample Data
Please see Sample Data image.  I'm trying to replicate the COUNTIFS functionality within Python / Pandas but I'm having troubles finding the correct solution.
=COUNTIFS(B:B,"BD*",A:A,A2,C:C,">"&C2)
B is the Type column, A is the Reference column, and C is the Doc Condition column.  So the count is only greater than zero if the Type is 'BD', the Reference Matches the current row's Reference, and the Doc Condition is greater than the current row's Doc Condition.  I hope that makes sense?
I've tried coming to a solution using GroupBy but I'm not getting any closer to my desired solution and I think I'm overcomplicating this.

A: You should include your input data as text. Screenshots are really hard to work with.
You can use numpy broadcasting. However, this will have an n^2 computational complexity since you are comparing every row against every other row:
reference, type_, doc_condition = df.to_numpy().T
match = (
    (type_[:, None] == "BD")
    & (reference[:, None] == reference)
    & (doc_condition[:, None] < doc_condition)
)
df["COUNTIFS"] = match.sum(axis=1)

Within the snippet above, you can read reference[:, None] as "the Reference value of the current row; reference as "the Reference values of all rows". This is what enables the comparison between the current row and all other rows (including itself) by numpy.


Q: Is Colorama required for Flask or Click? I'm trying to do the Flask "Hello World" tutorial and when I do the 'flask run' command on terminal I get the following traceback:
PS C:\Users\boymeetscode\PycharmProjects\beerRPG> flask run
Traceback (most recent call last):
  File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\Scripts\flask-script.py", line 9, in <module>
    sys.exit(main())
  File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\lib\site-packages\flask\cli.py", line 990, in main
    cli.main(args=sys.argv[1:])
  File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\lib\site-packages\flask\cli.py", line 596, in main
    return super().main(*args, **kwargs)
  File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\lib\site-packages\click\core.py", line 1062, in main
    rv = self.invoke(ctx)
  File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\lib\site-packages\click\core.py", line 1668, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\lib\site-packages\click\core.py", line 1404, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\lib\site-packages\click\core.py", line 763, in invoke
    return __callback(*args, **kwargs)
  File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\lib\site-packages\click\decorators.py", line 84, in new_func
    return ctx.invoke(f, obj, *args, **kwargs)
  File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\lib\site-packages\click\core.py", line 763, in invoke
    return __callback(*args, **kwargs)
  File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\lib\site-packages\flask\cli.py", line 844, in run_command
    show_server_banner(get_env(), debug, info.app_import_path, eager_loading)
  File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\lib\site-packages\flask\cli.py", line 678, in show_server_banner
    click.echo(f" * Environment: {env}")
  File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\lib\site-packages\click\utils.py", line 294, in echo
    file = auto_wrap_for_ansi(file)  # type: ignore
  File "C:\Users\boymeetscode\miniconda3\envs\beerRPG\lib\site-packages\click\_compat.py", line 541, in auto_wrap_for_ansi
    import colorama
ModuleNotFoundError: No module named 'colorama'

I am on Windows, Python 3.9.7 and did the pip install flask in my venv so if colorama is a dependency I would expect that it would have been installed automatically. Why isn't it?
Update: I manually installed colorama and now Flask works. I'm just still confused why if this is a dependency it wasn't installed automatically. My pip install didn't appear to return any errors.

A: Can confirm something in conda or click broke recently: colorama is missing after installing click (which was installed for black in my case). I use conda environment files so instead of manually installing I added a more recent version with
  - conda-forge::click

in the .yml file.
Then conda update installed click 8.03 and colorama, over click 8.0.1 which I had. Without an env file conda install -c conda-forge click should do the trick.
I do not know what exactly fixed it though, it is not in click's release notes: though there was arecent change to always install colorama, that was in version 8.0.0.


Q: Calling type-bound procedure for an array of derrived types in Fortran Let's assume that I have a derived type Coordinates with its type-bound procedure swap:
module myTypes
    implicit none
    public :: Coordinates

    type Coordinates
        real :: x,y
    contains
        procedure :: swap  ! Error here
    end type
contains
    subroutine swap(this)
        class (Coordinates) :: this
        this%x = this%x + this%y
        this%y = -(this%y - this%x)
        this%x = this%x - this%y
    end subroutine
end module

Now, if I have an instance of Coordinates called point_A, and if I want to call the type-bound procedure swap for it, I would just write: call point_A%swap. But if I have an array of instances of Coordinates, like:
type(Coordinates), dimension(:), allocatable :: setOfPoints

then to call the swap for all the elements of setOfPoints, I would like to write:
call setOfPoints(:)%swap

In order to achieve that, I change the code of swap procedure to:
subroutine swap(these)
        class (Coordinates), dimension(:)  :: these
        integer :: i
        do i = 1, size(this)
            this(i)%x = this(i)%x + this(i)%y
            this(i)%y = -(this(i)%y - this(i)%x)
            this(i)%x = this(i)%x - this(i)%y
        end do
end subroutine

Unfortunately, gfortran doesn't like my idea. On the line that I marked in the first piece of code it says:
Error: Passed-object dummy argument of 'swap' must be scalar.

Question: how can I call the type-bound procedure for all the instances of the derived type at once? I don't want to put the call in the loop, but I want to do this as I wrote it before, like what we always do with arrays in Fortran.
I read about the ELEMENTAL keyword, but if I want to use it, I need the type-bound procedure to be 'pure', which is not my case.
I tried to place a DEFERRED keyword after the word procedure, but then compiler says:
Error: Interface must be specified for DEFERRED binding

I created an interface for swap, but I couldn't figure out where to place it. I tried many positions and compiler said that 'interface was unexpected there'.
Also, I read about SELECT TYPE, but I think it won't help in my case.

A: Your specific example is perfectly fine with ELEMENTAL
module myTypes
    implicit none
    public :: Coordinates

    type Coordinates
        real :: x,y
    contains
        procedure :: swap  ! Error here
    end type
contains
    elemental subroutine swap(this)
        class (Coordinates), intent(inout) :: this
        this%x = this%x + this%y
        this%y = -(this%y - this%x)
        this%x = this%x - this%y
    end subroutine

end module

 use myTypes

 type(Coordinates) :: arr(10)

 arr = Coordinates(1.,2.)

 call arr%swap

 end

Your subroutine is pure. If it cannot be, consider using impure elemental.


Q: In Python, how to format string while saving in a file Is it possible to format strings while saving in a file, similar when printing to a console?
f = open('test.txt', 'w')
f.write('{0:10} {1:10}').format('one', 'two')
f.close()

A: Yes it is. I think that one of your closing parenthesis was not where you meant it to be:
with open('test.txt', 'w') as f:
    f.write('{0:10} {1:10}'.format('one', 'two'))


Q: Google Cloud Platform, ML Engine, "No module named absl" I am trying to train an object detector using TensorFlow following the following tutorial: https://cloud.google.com/blog/products/gcp/training-an-object-detector-using-cloud-machine-learning-engine
The tutorial asks to use object_detection.train, however this has been moved to legacy so I've used object_detection.model_main instead. Line 21 of this python file calls the module absl, however this causes the following error (from the GCP Logs Viewer).

Traceback (most recent call last): File "/usr/lib/python2.7/runpy.py",
  line 162, in _run_module_as_main "main", fname, loader, pkg_name)
  File "/usr/lib/python2.7/runpy.py", line 72, in _run_code exec code in
  run_globals File
  "/root/.local/lib/python2.7/site-packages/object_detection/model_main.py",
  line 21, in  from absl import flags ImportError: No module
  named absl

I tried to include absl>=0.1 in the required packages section of the setup.py file for the object_detection package but that didn't work. Next I tried to move my absl folder into the models/research/object_detection directory before packaging and starting the job, but that didn't work either. How do I fix this? I'm very new to Tensorflow and the GCP platform so your help will be appreciated. Thanks.

A: The package that you should be adding to REQUIRED_PACKAGES list in setup.py is 'absl-py>=0.1.0'. Apart from that, download this package tar.gz file to models/research/dist . Install by running pip install absl-py . Then, when starting the job add dist/avsl-0.4.0.tar.gz to the variables passed to the --packages flag.


Q: create J2me launcher Hi I have to create J2me launcher in which when I run the emulator then icon is displayed when I click on it, then it will redirect me to the website which I have given. I have researched it on internet but I cannot find any solution Please if anyone can help me please help me and it there are any suggestions then give me.

A: Why don't you use something like this:
platformRequest("http://ololo.com");

It will call a default browser to open the link.

A:  public void openBrowser(String URL) {
        try {
            mainMIDlet.platformRequest(URL);
        } catch (ConnectionNotFoundException e) {
            // error
        }
    }


Q: counting the vowels, without using raw input and the string 's' is defined.My result a infinite loop, whats wrong in it k=0
if (s[-1] == "a" or s[-1] == "e" or s[-1] == "i" or s[-1] == "o" or s[-1] == "u"):
    k=1
else:
    K=0
t=len(s)-1
while t>=0:
if (s[t-1:t] == "a"  or  s[t-1:t] == "e"  or s[t-1:t] == "i" or s[t-1:t] == "o" or s[t-1:t] == "u"):

    t=t-1

    k=k+1

else:

    t=t-1
print "Number of vowels:", k

A: simply use for loop to iterate every character from the string.
Demo:
In [28]: s = "qazxswedcvfrgbnhyujmkiopl"

In [29]: count = 0

In [30]: for i in s:
   ....:     if i.lower() in ["a", "i", "o", "u", "e"]:
   ....:         count += 1
   ....:

In [31]: print count
5


Q: how to synchronize between cuda kernel function? I have two cuda kernel functions like this
a<<<BLK_SIZE,THR_SIZE>>>(params,...);
b<<<BLK_SIZE,THR_SIZE>>>(params,...);

After function a started, I want to wait until a finishes and then start function b.
so I inserted cudaThreadSynchronize() between a and b like this,
a<<<BLK_SIZE,THR_SIZE>>>(params,...);
err=cudaThreadSynchronize();
if( err != cudaSuccess)
    printf("cudaThreadSynchronize error: %s\n", cudaGetErrorString(err));
b<<<BLK_SIZE,THR_SIZE>>>(params,...);

but cudaThreadSynchronize() returns error code: the launch timed out and was terminated cuda error
how can I fix it?

A simple code explanation:
mmap(sequence file);
mmap(reference file);

cudaMemcpy(seq_cuda, sequence);
cudaMemcpy(ref_cuda,reference);

kernel<<<>>>(params); //find short sequence in reference
cudaThreadSynchronize();
kernel<<<>>>(params);

cudaMemcpy(result, result_cuda);
report result

and in kernel function, there is a big for loop which contains some if-else for the pattern matching algorithm to reduce number of comparisons.

A: This launch error means that something went wrong when your first kernel was launched or maybe even something before that. To work your way out of this, try checking the output of all CUDA runtime calls for errors. Also, do a cudaThreadSync followed by error check after all kernel calls. This should help you find the first place where the error occurs.
If it is indeed a launch failure, you will need to investigate the execution configuration and the code of the kernel to find the cause of your error.
Finally, note that it is highly unlikely that your action of adding in a cudaThreadSynchronize caused this error. I say this because the way you have worded the query points to the cudaThreadSynchronize as the culprit. All this call did was to catch your existing error earlier.


Q: How to get the image from a facebook photo comment? Either API or FQL, I am trying to get the photo submitted as comment in a photo post.
To make clearer here is what I am saying

*

*I post a photo on my page timeline.

*people now post comments on the said photo

*either text comment or attaching photo in each comment.

Now, what I am getting is the comment information only.
I want to get the information about the photo used in comment also.
Thanks.

A: The picture (in the comment) could be fetched with the attachment parameter.
By default, you did not get the attachment field in the result, so you have to write this field explicitly. just like this -
me/posts?fields=comments.message,comments.id,comments.attachment

Demo
Ref: Comments

A: This is the same for page comments as I just discovered:
/{page-post-id}/comments?fields=from,message,id,attachment,created_time,comments.fields(from,message,id,attachment,created_time)
this will return all replies (and replies to those replies) for a particular page post. if there is an image on a reply it will be under 'attachment'
result is a bit like this:

Array
(
    [data] => Array
        (
            [0] => Array
                (
                    [from] => Array
                        (
                            [name] => ***********
                            [id] => ***********
                        )

                    [message] => test reply with a picture
                    [id] => ***********
                    [attachment] => Array
                        (
                            [type] => photo
                            [target] => Array
                                (
                                    [id] => ***********
                                    [url] => ***********
                                )

                            [url] => ***********
                            [media] => Array
                                (
                                    [image] => Array
                                        (
                                            [height] => 540
                                            [src] => ***********
                                            [width] => 720
                                        )

                                )

                        )

                    [created_time] => 2014-03-29T11:59:53+0000
                )

            [1] => Array
                (
                    [from] => Array
                        (
                            [name] => ***********
                            [id] => ***********
                        )

                    [message] => ***********
                    [id] => ***********
                    [created_time] => 2014-03-29T11:55:09+0000
                )

            [2] => Array
                (
                    [from] => Array
                        (
                            [name] => ***********
                            [id] => ***********
                        )

                    [message] => ***********
                    [id] => ***********
                    [created_time] => 2014-03-29T11:16:45+0000
                    [comments] => Array
                        (
                            [data] => Array
                                (
                                    [0] => Array
                                        (
                                            [from] => Array
                                                (
                                                    [name] => ***********
                                                    [id] => ***********
                                                )

                                            [message] => ***********
                                            [id] => ***********
                                            [created_time] => 2014-03-29T11:18:07+0000
                                        )

                                    [1] => Array
                                        (
                                            [from] => Array
                                                (
                                                    [name] => ***********
                                                    [id] => ***********
                                                )

                                            [message] => ************
                                            [id] => ***********
                                            [created_time] => 2014-03-29T11:18:48+0000
                                        )


Q: How to access a dynamically created control's value in a gridview in ASP.NET I can't figure out how to access the value of a control in a dynamically-created gridview. Thhe problem is that I don't know the name of the control. If I knew the name of the control I could do just do this :
string dropDownListText =((DropDownList).row.FindControl("DropDownList1")).SelectedItem.Value;`

I know the type of control and I know the cell it is in. Is there any way using the information about the control I have to be able to access the control's value?

A: If you know what cell it is, then you could do something like this;
TableCell tc = GridView1.Cells[indexOfCell];
// where GridView1 is the id of your GridView and indexOfCell is your index
foreach ( Control c in tc.Controls ){
    if ( c is YourControlTypeThatYouKnow ){
        YourControlTypeThatYouKnow myControl = (YourControlTypeThatYouKnow)c;
    }
}

If you don't know what cell it is exactly, then you can always loop through each cell. I am sure there is a better way in Linq.
With Linq (I think this should work)
var controls = GridView1.Cells[indexOfCell].Cast<Control>();
YourControlTypeThatYouKnow myControl = (YourControlTypeThatYouKnow) controls.Where( x => x is YourControlTypeThatYouKnow).FirstOrDefault();

A: On ItemDataBound event handler of GridView, access the table-cell as follows. Within the cell, Controls collection provides you access to ASP control embedded in the cell
TableCell cell = e.Item.Cells[0];
if (cell.Controls.Count > 0)
{
   cell.Controls[0].Visible = false;
}

A: I have had the same problem. Add a command name to your field like CommandName="ProjectClick". Then add a rowcommand and in the row command do this:
if (e.CommandName.Equals("ProjectClick")) {
}

or you can use the text:
if (e.CommandName.Equals("")) {
    if (((System.Web.UI.WebControls.LinkButton)(e.CommandSource)).Text.Equals("Projects")) {
    }
}