text:
Q: ReadProcessMemory trouble not updating This program does work at start, but than goes wrong after few loops
I am having trouble with ReadProcessMemory. It works at beginning of my program and reads in large string, but than it stops updating the values correctly. For example it will keep the previous string and stay with that string for rest of program or it will have completely nothing in the string until I shut program off. This happens at random times after first two times it works. The basic address contains a string of text of an item through hover effect in game. However readprocessmemory seems to stop working after few times and I have double checked that the address is still updating the correct values through cheat engine and it is but it is not updating correctly in program. I know code is badly written and I should use vectors etc...
The Problem occurs here:
while(temp.size() < 150 ){
do{
//  memset(&buffer[0], 0, sizeof(buffer));
    ReadProcessMemory(hProcHandle, (LPCVOID)myaddr, &buffer, sizeof(buffer), NULL);
    temp = std::string((char*)buffer);
}
while(temp == previous);
std:: cout << temp.size() << std::endl;
}

The above code was not a loop before, I tried recalling it again until it has new value or not null,however once the program stops working with bad values it just remains stuck in loop no matter how many times I call it, but the same address in cheat engine is being updated at same time, I have double checked that. The main problem in this loop is that readprocessmemory continues to have the same value as previous call and stays that way until shut down the program. The address is being updated in game at same time this is running.
#include <iostream>
#include <Windows.h>
#include <string>
#include <ctime>
#include <sstream>
#include <algorithm>
#include <vector>
DWORD ariaBase = 0x400000 + 0x009B5A20;

std::string teatime[] = {" + 5 E"," + 6 Acc"," + 5 Acc"," + 6  Acc"," + 5  Acc"," + 7 Crit"," + 6 Damage"," + 5 Damage"," + 4 Damage"," + 3 Crit"};
unsigned char* buffer[800] = {0};
std::string temp = "";
std::string previous = "";
int myaddr = 0;
bool match[5];
DWORD aOffset[] = {0x724, 0x37C, 0x0, 0xAC, 0x50};
int count = 0;
std::vector<std::string> stats;
bool statsFound = false;

void WriteToMemory(HANDLE hProcHandle){

stats.clear();
temp = "";

while(temp.size() < 150 ){
    do{
    //  memset(&buffer[0], 0, sizeof(buffer));
        ReadProcessMemory(hProcHandle, (LPCVOID)myaddr, &buffer, sizeof(buffer), NULL);
        temp = std::string((char*)buffer);
    }
    while(temp == previous);
    std:: cout << temp.size() << std::endl;
}
previous = temp;
std::replace( temp.begin(), temp.end(),(char)'\\', '*');
stats = findStats(temp);

//for( std::vector<std::string>::const_iterator i = stats.begin(); i != stats.end(); ++i)std::cout << *i << ' ' << std::endl;

}

int main(){
            ...code...
            ...code...
            ...code...
            ...code...
            while(statsFound == false){
                round++;
            checkItem();
            Sleep(2000);
            WriteToMemory(hProcHandle);
            std::cout << round << std::endl;
            for( std::vector<std::string>::const_iterator i = stats.begin(); i != stats.end(); ++i)std::cout << *i << ' ' << std::endl;

                for(int i = 0; i < stats.size();i++){
                    for(int j = 0; j < 10;j++){
                        if(("Identified Attribute:" + teatime[j]) == stats[i])match[i] = true;
                    }

                }
                count = 0;
                for(int i = 0; i < stats.size();i++){
                    if(match[i] != true)statsFound = false;
                    else count++;

                    if(count == stats.size())statsFound = true;

                }
                match[0] = false;
                match[1] = false;
                match[2] = false;
                match[3] = false;

                if(statsFound == false)MouseStart();
            }
            ...code...
            ...code...
            ...code...

}

A: Can you say what resides in the memory of the target process from which you're reading the data?
Have you heard about GetLastError function? Call it immediately after ReadProcessMemory returns and that may give a clue.


text:
Q: Delete empty nodes I try to delete empty nodes, but not all of them, for example I have tags:
1.<abc></abc> - it should be delete
2.<cde/> - it should not be delete.
3.<fgh/> - it SHOULD be delete.

So, i would like to delete empty nodes in point 2 (explicit name "CDE")
So in other words: when tag like 'cde' and tag is null then delete. : D
Is it possible?
I found the code which delete all the empty nodes:
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="*[descendant::text() or descendant-or-self::*/@*[string()]]">
    <xsl:copy>
        <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="@*[string()]">
    <xsl:copy/>
</xsl:template>

</xsl:stylesheet>

EDIT:
XML look like:
<system/>
            <smth></smth>
            <smth2>?</smth2>
            <smth3>?</smth3>
            <smth4></smth4>
            <smth4></smth4>
            <smth5/>

XML can contain a lot of tags like  - SO i have remove them dynamically.
Some of tags which looks like  I WANT to remove. But in this XML  should stay.
So XML output should looks:
 <system/>
                <smth2>?</smth2>
                <smth3>?</smth3>

I found the solution: http://xsltransform.net/nc4NzRx/3. : )

A: If you want to copy everything but delete empty cde elements then use a stylesheet with the following two templates
<xsl:template match="@* | node()">
  <xsl:copy>
    <xsl:apply-templates select="@* | node()"/>
  </xsl:copy>
</xsl:template>

<xsl:template match="cde[not(node())]"/>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Multiplication in for loop I am new to JS and I am completely stuck with this simple thing and I would really like to understand this and continue further with learning.
I have this chunk of code:
var power = function(base, exponent) {
  var result = 1;
  for (var count = 0; count < exponent; count++) {
    result *= base;
  }
  return result;
};

console.log(power(2, 10));
// Result is: 1024

A result in the console will be 1024
If I change values into:
console.log(power(1, 10));
// Result is: 1

But if I change into:
console.log(power(3, 10));
// Result is: 59049

I will get a result of 59049.
So, how I got this result of 59049? How I got a result of 1024? How I got a result of 1? How does all this thing work?
I would really appreciate if someone can explain it to me on as simplest and dummies way as possible :)
Thanks!

A: That's because

2 to the power of 10 (or 1 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2) equals 1024

and

1 to the power of 10 (or 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1 * 1) equals 1

and

3 to the power of 10 (or 1 * 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3) equals 59049

If you supply your function with a base and an exponent, the function will do the following:
power(2, 0) yields 1 because exponent is 0 and the function immidiately returns result (which is 1) without entering the loop.
power(2, 1) yields 2 because result (which is 1) is multiplied once with base (which is 2) in your loop thus resulting in 1 * 2 = 2
power(2, 2) yields 4 because result (which is 1) is multiplied twice with base (which is 2) in your loop thus resulting in 1 * 2 * 2 = 4
power(2, 3) yields 8 because result (which is 1) is multiplied three times with base (which is 2) in your loop thus resulting in 1 * 2 * 2 * 2 = 8


text:
Q: Copy Table row to another table HTML Fiddle
I have two tables. When I click on one table row it will copy to another table, and I will change the button as my requirement. Please help me.
$(window).load(function() {
                var items = [];

                $(".addBtn").on("click", function() {
                    var newTr = $(this).closest("tr").clone();

                    var newButtonHTML = "<input type = 'button' value='Edit' onclick='Edit()' /><input type='button' value='Delete' onclick='deleteRow(this.parentNode.parentNode.rowIndex)'/>";
                    $(newButtonHTML).children("button").click(function(e) {
                    });

                    $(newTr).children("td:last").html("").html(newButtonHTML);
                    items.push(newTr);
                    newTr.appendTo($("#stopsTable"));

                });

A: At your example it was a wrong selector
$('#myTable.tr')

instead of
$('#myTable tr')

Check fixed version: http://jsfiddle.net/V7wXD/7/
Best regards!

A: Js:
$(function() {
    $('#myTable tbody tr').each(function(){
        $(this).append('<button class="copy">Copy</button>	');
    });

    $(document).on('click', 'button.copy', function(){
        var $tr = $(this).parents('tr:first').clone();

        $tr.appendTo($('#stopsTable > tbody'));
    });
});

Test here:
http://jsfiddle.net/V7wXD/8/


text:
Q: I want to reverse array without any php function? I have tried something like that but it's giving me value. I need all the elements reverse in array again.
 <?php
//There is an array
  echo '<pre>';
  $arr = ['a','b','c','d','e','f'];
  print_r($arr);
  $size = sizeof($arr);
 //print_r($size);

 for($i=5; $i<=$size; $i--)
 {
  echo $arr[$i];
 }

?>

but it gives me output "fedcba"
     I need like this ["f", "e", "d", "c", "b", "a"]
     reverse all of its elements without using any PHP array function and any other new variable.

A: Expanding Hanky Panky's answer If you don't need any additional element then you can unset the previous values of array.
    <?php
    $arr = ['a','b','c','d','e','f'];

    for($i=count($arr)-1;$i>=0;$i--){
    $arr[]=$arr[$i];
    unset($arr[$i]);
    }
    print_r($arr);
   //Additionaly you can use array_values to reindex your array from 0
    print_r(array_values($arr));
    ?>

Fiddle is Check here

A: //Use this
$arr = ['a','b','c','d','e','f'];

$size = sizeof($arr);
    $res=array();
  for($i=$size-1; $i>=0; $i--){
       $res[]= $arr[$i];
  }

print_r($res);

A: This uses the same amount of variables as your code meaning $arr, $size and $i.
$arr = ['a','b','c','d','e','f'];

$size = count($arr);
for($i=$size-1;$i>=0;$i--){
    $arr[$size] = $arr[$i];
    unset($arr[$i]);
    $size++;
}

var_dump($arr);

https://3v4l.org/mEHJU
It creates:
array(6) {
      [6]=>
      string(1) "f"
      [7]=>
      string(1) "e"
      [8]=>
      string(1) "d"
      [9]=>
      string(1) "c"
      [10]=>
      string(1) "b"
      [11]=>
      string(1) "a"
}

The keys are not from 0, but that can be corrected with array_values or does it need to be corrected without that function?

A: In your for loop, you have $i<=$size, shouldn't it be $i>=0? Secondly, you can reverse the array without any extra functions but since you are using $size variable, I hope you can use another variable $temp for swapping. Here is the sample code:
//original array
$arr = ['a','b','c','d','e','f'];
print_r($arr);
$size = sizeof($arr);

for($i=0; $i<$size; $i++)
{
     $temp=$arr[$i];
     $arr[$i]=$arr[$size-1];
     $arr[$size-1]=$temp;
     $size--;

}
//reversed array
print_r ($arr);

A: Here is another solution using same variable names as yours and using swapping method, (also here you may assume $i as index from left and $size as index from right.
$arr = ['a','b','c','d','e','f'];
print_r($arr);
$i=0;

while ($i < sizeof($arr)/2){
    $size=$arr[$i];
    $arr[$i]=$arr[sizeof($arr)-1-$i];
    $arr[sizeof($arr)-1-$i]=$size;
    $i=$i+1;
}

//reversed array
print_r ($arr);

A:       <?php
   $arr = ['a','b','c','d','e','f'];
   print_r($arr);
   $size = sizeof($arr);
  for($i=5; $i<=$size; $i--)
  {
    if($i==$size-1)
     {
     echo '['.'"'.$arr[$i].'"',',';
     }
    if($i<$size && $i!=5 && $i>0)
     {
    echo '"'.$arr[$i].'"'.',';
     }
    if($i==0)
     {
    echo '"'.$arr[$i].'"'.']';
     }
 }
  ?>//hope this helps you....

A: ok so this is my last try
$array = ['a','b','c','d','e','f'];
$count = count($array);
for($i = 0; $i < $count/2; $i++){
  $array[$i] ^= $array[$count-$i-1] ^= $array[$i] ^= $array[$count-$i-1];
}

it is base on Is there a PHP function for swapping the values of two variables?
and if you cant even use count() you can do simple foreach loop
$count = 0;
foreach($array as $one)
 $count++;


text:
Q: count colored dots in image First of all, sorry if this topic already exists (I think this is a common task, but couldn't find anything).
The point, is that I have an image who shows different dots of different colors. And I need an script to count how many red, green and yellow dots are.
The colors are pure red(ff0000), green(00ff00) and yellow(ffff00). Which makes this easier, and the shape is well defined.

My current approach is to select the round(dot) shape, select them and then once I have all dots away from background image, read its color to count them...
The point is that I'm so lost with this. I know that this can be done with OpenCV but don't know how (and couldn't find any nice tutorial).
Any idea?

A: Here is a sample solution based on OpenCV 3.2 and Python 2.7.
To count the colored dots, repeat below 4 steps once per color type.

*

*Apply median filter to reduce noise - cv2.medianBlur().

*Apply color threshold to segment the colored dots - use cv2.inRange().

*Use Hough Circle Transform to detect the circles - use circles = cv2.HoughCircles(mask,cv2.HOUGH_GRADIENT,...)

*Loop through each detected circles to draw its center and a circle around it, and count the numbers of colored dots.

Sample images of dots detected:
Red - 10 dots

Green - 39 dots

Yellow - 30 dots

Take note that the last yellow dots at the right side with less than half a circle hasn't been detected. This is likely a limitation of the Hough Circle Transform cv2.HoughCircles(). So you need to decide how to handle this type of issue if it happens.
Here is the sample code:
import cv2
import numpy

red = [(0,0,240),(10,10,255)] # lower and upper
green = [(0,240,0),(10,255,10)]
yellow = [(0,240,250),(10,255,255)]
dot_colors = [red, green, yellow]

img = cv2.imread('./imagesStackoverflow/count_colored_dots.jpg')
# apply medianBlur to smooth image before threshholding
blur= cv2.medianBlur(img, 7) # smooth image by 7x7 pixels, may need to adjust a bit

for lower, upper in dot_colors:
    output = img.copy()
    # apply threshhold color to white (255,255, 255) and the rest to black(0,0,0)
    mask = cv2.inRange(blur,lower,upper)

    circles = cv2.HoughCircles(mask,cv2.HOUGH_GRADIENT,1,20,param1=20,param2=8,
                               minRadius=0,maxRadius=60)
    index = 0
    if circles is not None:
        # convert the (x, y) coordinates and radius of the circles to integers
        circles = numpy.round(circles[0, :]).astype("int")

        # loop over the (x, y) coordinates and radius of the circles
        for (x, y, r) in circles:
            # draw the circle in the output image,
            #   then draw a rectangle corresponding to the center of the circle
            cv2.circle(output, (x, y), r, (255, 0, 255), 2)
            cv2.rectangle(output, (x - 5, y - 5), (x + 5, y + 5), (255, 0, 255), -1)

            index = index + 1
            #print str(index) + " : " + str(r) + ", (x,y) = " + str(x) + ', ' + str(y)
        print 'No. of circles detected = {}'.format(index)

Hope this help.

A: Since you already know the colors you are looking for, I would segment the image based on color. The steps I would follow are:
red_dot_count = 0
yellow_dot_count = 0
green_dot_count = 0
For each pixel in the image:
   if pixel color is red:
       floodfill using this pixel as seed pixel and target_color as black
       red_dot_count++
   if pixel color is green:
       floodfill using this pixel as seed pixel and target_color as black
       green_dot_count++
   if pixel is yellow:
       floodfill using this pixel as seed pixel and target_color as black
       yellow_dot_count++

Your image would have to be a PNG image though as @Mark pointed out.
Also, this assumes that the colors in the red, green and yellow dots do not appear anywhere else in the image.

A: As you don't appear to be getting much help with an OpenCV/Python solution, I thought I'd post a different way - using bash and ImageMagick. I'll show the bash script first, then explain it a bit afterwards.
ImageMagick is installed on most Linux distros and is available for macOS and Windows for free. It also has C/C++, Perl, Python, PHP, Ruby, Java bindings. Note that no code needs to be written for this and no compiler is necessary.
#!/bin/bash

for colour in red yellow lime ; do
   echo -n "Colour: $colour "
   convert dots.jpg -fuzz 20%                              \
     -fill white -opaque $colour -fill black +opaque white \
     -define connected-components:verbose=true             \
     -define connected-components:area-threshold=800       \
     -connected-components 8 output.png | grep -c "rgb(255,255,255)"
done

The output looks like this:
Colour: red 10
Colour: yellow 30
Colour: lime 37

The convert command is part of the ImageMagick suite. Let's take a look at how that command works on the first time through the loop when colour is red. Initially, let's look at just the first 2 lines of the convert command:
convert dots.jpg -fuzz 20%                          \
 -fill white -opaque red -fill black +opaque white intermediate.png

Hopefully you can see that it fills with white all pixels within 20% of red, then filling with pure black all pixels that are not white.

The remainder of the convert command puts the image above through a "Connected Components Analysis" and lists all blobs with an area exceeding 800 pixels - which is around half the average size of your blobs and is why I asked in the comments section about partial blobs. Let's see what happens when we run that:
convert intermediate.png \
   -define connected-components:verbose=true       \
   -define connected-components:area-threshold=800 \
   -connected-components 8 -auto-level output.png

Output
Objects (id: bounding-box centroid area mean-color):
  0: 1342x858+0+0 670.0,426.9 1140186 srgb(0,0,0)
  191: 39x39+848+595 866.9,614.1 1165 srgb(255,255,255)    <--- DRAW THIS ONE
  192: 39x39+482+664 500.9,682.9 1165 srgb(255,255,255)
  117: 38x39+4+292 22.5,311.0 1155 srgb(255,255,255)
  194: 39x38+1250+732 1268.9,750.5 1154 srgb(255,255,255)
  178: 39x38+824+512 843.0,530.1 1154 srgb(255,255,255)
  186: 39x38+647+549 666.0,567.5 1152 srgb(255,255,255)
  197: 38x39+1270+796 1288.5,815.0 1150 srgb(255,255,255)
  173: 38x38+811+444 829.5,462.5 1143 srgb(255,255,255)
  195: 38x39+711+783 729.6,801.5 1138 srgb(255,255,255)
  107: 27x39+0+223 11.5,242.0 874 srgb(255,255,255)

Hopefully you can see the first line is a header describing the columns, and there are 10 lines which are white srgb(255,255,255) and each line corresponds to a blob - i.e. one of your red disks (which we made white). They are all around 39x39 pixels (i.e. circular in a square box) with an area around 1150 pixels - if you imagine a radius of 19 pixels, then Pi*r^2=1150. Their sizes (as width and height) and locations (as x and y from the top-left corner) are in the second column.
If you wanted to count partial blobs as small as 25% of a full-size blob, you would change the threshold to 25% of 1150 (the natural, full blob size) or 287, rather than the 800 I guesstimated.
The remainder of the script simply counts lines with white blobs in them (grep -c) and repeats the process for the other colours you seek. Note that your "green" corresponds to "lime" in the X11 naming scheme that ImageMagick uses.
Just for fun, let's fill in with semi-transparent blue the blob that I have marked with an arrow in the above output list:
convert dots.jpg -fill "rgba(0,0,255,0.5)" -draw "rectangle 848,595 887,634" temp.png

I hope that helps get the job done and shows a method even if it is not the tools you expected to use. Note that OpenCV has Connected Components and similar algorithms - I just don't speak Python and a C++ version is no more help to you!


text:
Q: Carousel bootstrap with vue js component currently I'm creatting  one component using Carousel With indicators  GetBootstrap Carousel With indicators
I am implementing this code in one vue component, like:
<template>

            Previous

            Next

</template>

currently the first image is showing but the other images are not showing, the slider is not working too.
Why? what I'm doing wrong?
here is the code codesandbox

A: According to the documentation, there must be strictly nesting of elements .carousel-inner > .carousel-item.
You should try this:


text:
Q: Google Earth Engine cloud cover sorting and area of interest I see in a lot of examples that people are sorting a stack by cloud cover and then pick the first image.
Example:
image = image.filterDate('2022-01-01', '2023-01-01')
              .filterBounds(study_area)
              .sort('CLOUD_COVER')
              .first();

For me this is only useful if my entire area of interest falls into one image, which most often it does not (and which I often don't know before I get started).
Most of the time I get something like this:

If I understand right, the one image with least cloud cover is picked form the stack, so it makes sense that not my entire area is covered, as it is covered by multiple images.
So, what I don't understand is why this is so commonly used.
Or am I totally missing something? Would it not be better to use median() or use a cloud masking function as we have the guarantee that the entire area is covered?


text:
Q: Override type provided by TypeScript library in a namespace? Is there any way to override the value of a type exported and used by a TypeScript package?
So I have this in my typings file:
// index.d.ts
declare module 'my-package' {
    namespace DependencyInjection {
        type ServiceID = 'myServiceOne' | 'myServiceTwo'; // original type is "any";
    }
}

and I get the following the error:
Duplicate identifier 'ServiceID'.ts(2300)
inject.ts(44, 10): 'ServiceID' was also declared here.

I'd like to be able to replace the type of ServiceID from the consuming code. Can it be done? I know interfaces can be extended but I haven't found a way to change or update a type.
Context
I'm writing a TypeScript package and I'd like users to be able to override some default types with their own when they integrate the package, rather than having to provide generics every time they use some methods.

A: Module augmentation only work if the module can be extended.
Types cannot be extended, but interfaces can.
declare module 'my-package' {
    namespace DependencyInjection {
        interface ServiceIDMap {}
        type ServiceID = keyof ServiceIDMap
    }
}

declare module 'my-package' {
    namespace DependencyInjection {
        // insert your keys in here.
        interface ServiceIDMap {
            myServiceOne: unknown
            mySevriceTwo: unknown
        }
    }
}

Playground
@types/jest is designed to do this too, with ts-jest extending the Config.InitialOptions.globals struct.


text:
Q: How can I load an Android asset pack on-demand using Java from the Google Play app bundle? How can I load an Android asset pack on-demand using Java from the Google Play app bundle?
I have tried passing the parameter and hard coding it in AssetPackManager.
I think my problem is associated with not understanding interface.
Some Links
https://developer.android.com/guide/playcore/asset-delivery/integrate-java
The Play Core Java API provides the AssetPackManager class for requesting asset packs,
managing downloads, and accessing the assets.
You implement this API according to the delivery type of the asset pack you wish to access.
https://developer.android.com/reference/com/google/android/play/core/assetpacks/AssetPackManager#getpacklocation
My asset pack (SongsNW) structure is at the same level indent as app
    app  // my app
        src
           main
                java
                AndroidManifest.xml
            build.gradle

My app level build.gradle (above) lists my AssetPacks
    android {
        other {
            ...
        }
        dynamicFeatures = [':....X', ':SongsNW', ':.....Y', ':.....Z']
    }
    dependencies {
        ....
    }

My Asset Pack (SongsNW)
    SongsNW
        src
            main
                assets
                    NW folder with assets
                AndroidManifest.xml
            build.gradle

My AndroidManifest.xml (under SongsNW above)
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:dist="http://schemas.android.com/apk/distribution"
        package="com.companyname.songsnw">

        <dist:module
            dist:instant="false"
            dist:title="@string/title_songsnw">
            <dist:delivery>
                <dist:on-demand/>
            </dist:delivery>
            <dist:fusing dist:include="false" />
        </dist:module>
    </manifest>

My build.gradle (under SongsNW above)
    apply plugin: 'com.android.asset-pack'

    assetPack {
        packName = "SongsNW" // Directory name for the asset pack
        dynamicDelivery {
            deliveryType = "on-demand"
        }
    }

LoadAssetPack.java (module)
    package com.companyname.appname;

    import android.util.Log;
    import com.google.android.play.core.assetpacks.AssetPackLocation;
    import com.google.android.play.core.assetpacks.AssetPackState;
    import com.google.android.play.core.assetpacks.AssetPackStates;
    import com.google.android.play.core.tasks.OnCompleteListener;
    import com.google.android.play.core.tasks.RuntimeExecutionException;
    import com.google.android.play.core.tasks.Task;

    import static android.content.ContentValues.TAG;

    interface AssetPackManager {
        // I am passing the assetPackName to here with this call:
        // AssetPackLocation assetPackLocation = AssetPackManager.getPackLocation("SongsNW");
        public static final String TAG = "LoadAssetPack";
        public static final String assetPackName = "";
        // public static final String assetPackName = "SongsNW";
        public static final AssetPackLocation assetPacklocation = null;

        public static final AssetPackLocation assetPackLocation = getPackLocation(assetPackName);

        public static AssetPackLocation getPackLocation(String assetPackName) {
            Log.d(TAG, "in AssetPackManager assetPackName:" + assetPackName);
                    AssetPackLocation assetPackLocation = getPackLocation(assetPackName);
            Log.d(TAG, "assetPackName:" + assetPackName + " assetPackLocation: " + assetPackLocation );
            return assetPackLocation;  // null if it isn't complete

        }

        // I need to run the following list, but first I need to understand what I am doing wrong.
        AssetPackStates cancel (List<String> packNames)
        Task<AssetPackStates> fetch (List<String> packNames)
        Task<AssetPackStates> getPackStates (List<String> packNames)
        void registerListener (AssetPackStateUpdateListener listener)
        Task<Void> removePack (String packName)
        Task<Integer> showCellularDataConfirmation (Activity activity)
        void unregisterListener (AssetPackStateUpdateListener listener)
    }

This is not the answer to the above question but I believe it defines the questions better.
First be able to see the original error message.
Increase Android Studio Logcat buffer size to hold 16384 KB (Default 1024 KB)
File > Settings > Editor > General > Console > override console cycle buffer size. then you can see the error at the top.
message in Logcat:
I/SystemServer: InitBeforeStartServices
W/YouTube: Fetching the Gservices key 'disable_binder_callback_flush' before the end of the bulk initialization
W/Primes: Primes not initialized, returning default (no-op) Primes instance which will ignore all calls.
Please call Primes.initialize(...) before using any Primes API.
Google the above error provides:
Play Services tries to authenticate, closes the profile popup prematurely, fails #2362
https://github.com/playgameservices/play-games-plugin-for-unity/issues/2362
In the following comment they are discussing Google Play services.
... The Web Client ID was the right way to go. Once I got that properly configured it did the trick. The part that wasn't intuitive was the redirect_uri. For anyone running into the same problem because the Google API Console isn't super intuitive: In the credentials section, under the Oauth consent screen tab, toward the bottom is an "Authorized domains" section. In order to add an Authorized domain, you need to type it into the box right below that says example.com.
That brought up a lot of additional questions:
What is the Web Client ID? Where is this credentials section? What is a redirect_uri? What is my Authorized domain? The real question is, Why am I trying to create and manage Google Cloud projects? The answer, I believe, is because that is where Google Play is storing my app bundle.
The answer to properly managing projects probably is in:
https://cloud.google.com/resource-manager/docs/creating-managing-projects
I have found OAuth clients at
Google Play Console > Settings > Developer account > API access
So, my question at this time is: "What is the minimum I need to fill out in Google Play to Initialize the System Server. (Which is my first error statement).

A: Google Play said I couldn't store assets in Internal storage > Android > obb anymore so I attempted to implement Asset Packs, failed, and wrote this question. I ended up simply installing each asset on Play Store as an app, and added the following to my help page.
There are NO songs in this app. ZERO. You have to load them from another app. There are currently four other apps that are associated with this app: Birding Via Mic New World, ... Old World, ... Orient Australasia, and ... North American Common.
These apps contain songs for their respective region (called YourRegion below) but no functionality other than supply this app with the songs they contain. You will need to install one (or more if desired) of these and transfer the songs to this app.
If you are running on Android Version 6.0 or greater, verify your permissions are turned on: Settings > Applications > Application Manager > Birding Via Mic > Permissions
To transfer the songs:

*

*Install this Birding Via Mic app.

*Install Birding Via Mic_YourRegion app.

*Open Birding Via Mic_YourRegion, tap Songs and verify a list of songs is displayed.

*In this Birding Via Mic app tap the Path button.

*On the Path screen select Birding Via Mic -- YourRegion.

*Tap the "Load Now" button.
Uninstall the Birding Via Mic_YourRegion app to recover memory.


text:
Q: Connection pooling issue in nodeJS and MySql I am using NodeJs and Mysql.
I have a query to update one field in mysql table as:
Update messaging SET count = count + 1 WHERE msgId = 10;
I am using connnection pool. configuration as:
var pool = mysql.createPool({
connectionLimit : 100,
host: config.mysql.host,
user: config.mysql.user,
password: config.mysql.password,
database: config.mysql.database,
port: 3306,
debug: false,
multipleStatements: true});

API that is using this query works when message is delivered to the 5 million users.
it makes the connections to remain opened. That results in server processing very slow.
Is there any alternative solution to improve the server performance?

A: Paradoxically, reducing the number of connections will generally improve performance. Pooled connections are serially reusable resources, and there's a queue of connection requests. So, instead of trying to do a whole lot of queries at once, the DBMS will handle a smaller number of queries at once, and handle the load serially.
So for queries like yours that should run for a short time, create a pool with a small connectionLimit.  Try 10. If that works well, try 5.
If you have other queries that take longer, you may want a different connection pool for those.
Not to mention that a clustered node app will open that number of connections for each member of the cluster. 400 connections is too many for almost all MySQL deployments. (If you have a deployment that handles hundreds of connections, your purchasing manager knows about it, because such deployments are very expensive.)
You might have this problem, however: If millions of users are updating exactly the same row msgId = 10  you will have DBMS contention on that row. In that case, you may want to store up the number of hits to the row, and then do UPDATE... SET count = count + n once every few seconds rather than upon every hit.


text:
Q: Como cambiar 2 lineas de c++ a C Como puedo cambiar esto de c++ a c?
el cout cambiarlo por printf
void imprimeVector(const vector<string>& v)
     {

         for (size_t i = 0; i < v.size(); i++)

          cout << v[i] << " ";

    }

Gracias!

A: Te pongo un ejemplo con un entero:
int entero = 5;
printf("El valor es %d.\n", contador);

Segun el tipo de la variable tienes que poner un % determinado:
%s : Strings
%f : float
etc.
Aqui hay más información: http://www.it.uc3m.es/pbasanta/asng/course_notes/input_output_printf_es.html


text:
Q: Communication cannot be established between containers when they are both client and server using gRPC Problem description:
I tried to establish communication between Python 3.7 based image containers to achieve a simple distributed system using multi process and gRPC. Some connections could not be established correctly, and some services could not be started correctly.
Code schema:
A master node is used to manage the work node. After the work node registers with the master node, it starts several local services.
In my master node, I started two services through the multiprocess library in Python, and used two different channels and stubs. Everything worked normally. There was never any problem when the working node established a connection.
Main.py on the Master node:
@contextlib.contextmanager
def _reserve_port(port):
    """Find and reserve a port for all subprocesses to use."""
    pass

if __name__ == "__main__":
    workers = []
    with _reserve_port(10087) as port:
        bind_address = socket.gethostbyname('master')+':{}'.format(port)
        # Function Inquiry_Send() is a service to send messages
        worker = multiprocessing.Process(target=inquiry.Inquiry_Send,args=(bind_address,))
        worker.start()
        workers.append(worker)
    with _reserve_port(10086) as port:
        bind_address = socket.gethostbyname('master')+':{}'.format(port)
        # Function Register_Receive() is a service for the node to join the cluster
        worker = multiprocessing.Process(target=register.Register_Receive,args=(bind_address,))
        worker.start()
        workers.append(worker)
    for worker in workers:
        worker.join()

register.py on the Master node:
# Unary is the service I defined in proto
class Unary(code_pb2_grpc.UnaryServicer):
    def Register(self, request, context):
        """Omit the Process of request"""
        child1 = subprocess.Popen(
            ['python', 'heart.py', register_node.IPAddress, register_node.HeartPort],
            stdout=subprocess.PIPE
        )
        return code_pb2.register_response(message='ok')

def Register_Receive(bind_address):
    """Start a register server in a subprocess."""
    options = (('grpc.so_reuseport', 1),)
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=4,),options=options)
    code_pb2_grpc.add_UnaryServicer_to_server(Unary(), server)
    server.add_insecure_port(bind_address)
    server.start()
    _wait_forever(server)

When the master node receives the node joining, it will start the heart.py As a client to establish a Stream connection with the work node.
heart.py on the Master Node:
def Heart_Check(IPAddress, Port):
    time.sleep(3)
    with grpc.insecure_channel(IPAddress+':'+Port) as channel:
        client = code_pb2_grpc.StreamStub(channel)
        retry_nums = 0
        while retry_nums < 5:
            try:
                response = client.HeartCheck(code_pb2.heartcheck_request(message='R U ok?'))
                for i in response:
                    pass
            except grpc.RpcError as e:
                status_code = e.code()
                if status_code.name == 'UNAVAILABLE':
                    retry_nums += 1
                    time.sleep(5)
                else:
                    break

Main.py on the Work Node:
if __name__ == '__main__':
    # Function Register_Send() is to join the cluster by connecting to Master Node
    if register.Register_Send() == 'ok':
        with ProcessPoolExecutor(max_workers=3) as executor:
            futures = {}
            with _reserve_port(10086) as port:
                bind_address = socket.gethostbyname(socket.gethostname())+':{}'.format(port)
                mailbox = executor.submit(mailbox.Mailbox, bind_address)
            with _reserve_port(10087) as port:
                bind_address = socket.gethostbyname(socket.gethostname())+':{}'.format(port)
                heart = executor.submit(heart.Heart_Check, bind_address)
            with _reserve_port(10088) as port:
                bind_address = socket.gethostbyname(socket.gethostname())+':{}'.format(port)
                task = executor.submit(task.Task, bind_address)
            for f in as_completed(futures):
                try:
                    print('the server %s is done.' %futures[f])
                except Exception as e:
                    print(e)
    else:
        print('Fall!')

heart.py on the Work Node:
def create_response() -> code_pb2.heartcheck_response:
    response = code_pb2.heartcheck_response()
    """Omit the message"""
    return response

class Heart(code_pb2_grpc.StreamServicer):
    def HeartCheck(self, request,context):
        #after the acceptance of request from Master Node
        while True:
            time.sleep(3)
            try:
                yield create_response()
            except StopIteration:
                break

def Heart_Check(bind_address):
    options = (('grpc.so_reuseport', 1),)
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=4,),options=options)
    code_pb2_grpc.add_StreamServicer_to_server(Heart(), server)
    server.add_insecure_port(bind_address)
    server.start()
    _wait_forever(server)

mailbox.py on the Work Node:
class Task(code_pb2_grpc.TaskServicer):
    def IdleAsk(self, request, context):
        return code_pb2.idleask_response(message='ok')

def Mailbox(bind_address):
    options = (('grpc.so_reuseport', 1),)
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=4,),options=options)
    code_pb2_grpc.add_TaskServicer_to_server(Task(), server)
    server.add_insecure_port(bind_address)
    server.start()
    _wait_forever(server)

task.py on the Work Node:
class Task(code_pb2_grpc.TaskServicer):
    def Task_PrimeCal(self, request, context):
        """Omit"""
        return code_pb2.task_primecal_response(nums=nums)

def Task(bind_address):
    options = (('grpc.so_reuseport', 1),)
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=4,),options=options)
    code_pb2_grpc.add_TaskServicer_to_server(Task(), server)
    server.add_insecure_port(bind_address)
    server.start()
    _wait_forever(server)

*

*I often cannot connect to the heartbeat detection service of the work node. The error code is unavailable. But I can connect after several more attempts. I guess it takes time to start the service. How can I ensure that the service is started correctly?

*When I start the service of the work node, I find that my Task service will terminate directly. I noticed that my Task service and my Mailbox service use the same Task Service. Should I divide them into different services, or should different rpcs of the same service be implemented in the same server instance?

The Error
[PID 556] Binding to '192.168.0.4:10086'
[PID 556] Binding to '192.168.0.4:10087'
[PID 556] Binding to '192.168.0.4:10088'
the server task is done.

*When I start another script App.py to connect to the Mailbox service, they are unavailable. This is strange because it is normal for the work node to use the two services on the master node, which indicates that there is no problem in the network communication between containers. I don't know where the problem occurred. Their code structures should be similar, and no problem should occur.

App.py on the Work Node:
def Inquiry():
    """This Function is Normally Working"""
    with grpc.insecure_channel(socket.gethostbyname("master")+':10087') as channel:
        client = code_pb2_grpc.StreamStub(channel)
        response = client.Inquiry(code_pb2.inquiry_request(message="Please give me register nodes!"))
        for i in response:
                pass

def Nodes_Occupy() -> list:
    """Here I get the working nodes list"""
    """This Function is to occupy them"""
    """I can't connect to other working nodes"""
    idle_nodes=[]
    for node in actor_nodes:
        with grpc.insecure_channel(node['IPAddress']+':10086') as channel:
            client = code_pb2_grpc.TaskStub(channel)
            try:
                response = client.IdleAsk(code_pb2.idleask_request(message='Are U Idle?'))
                if response.message=='ok':
                    idle_nodes.append(node)
            except grpc.RpcError as e:
                print(node['IPAddress']+':'+e.details())
    return idle_nodes

# My Task
def Prime_Calculate(idle_nodes) -> None:
    for node in idle_nodes:
        with grpc.insecure_channel(node['IPAddress']+':10088') as channel:
            client = code_pb2_grpc.TaskStub(channel)
            try:
                response = client.Task_PrimeCal(code_pb2.task_primecal_request(start=start, end=end))
            except grpc.RpcError as e:
                print(node['IPAddress']+':'+e.details())

if __name__ == '__main__':
    logging.basicConfig()
    Inquiry()
    Prime_Calculate(Nodes_Occupy())

*If a connection is established between two containers, should I use this connection for all communication? Considering that it takes time for TCP connections to release ports.


text:
Q: Unable to find package for @bazel_skylib//:bzl_library.bzl Here's my workspace;
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")

RULES_JVM_EXTERNAL_TAG = "4.0"
RULES_JVM_EXTERNAL_SHA = "31701ad93dbfe544d597dbe62c9a1fdd76d81d8a9150c2bf1ecf928ecdf97169"

http_archive(
    name = "maven",
    strip_prefix = "rules_jvm_external-%s" % RULES_JVM_EXTERNAL_TAG,
    sha256 = RULES_JVM_EXTERNAL_SHA,
    url = "https://github.com/bazelbuild/rules_jvm_external/archive/%s.zip" % RULES_JVM_EXTERNAL_TAG,
)

load("@maven//:defs.bzl", "maven_install")

maven_install(
    artifacts = [
        "com.fasterxml.jackson.core:jackson-databind:2.12.1",
        "org.apache.commons:commons-lang3:3.11"
    ],
    repositories = [
        "https://repo1.maven.org/maven2",
        "https://jcenter.bintray.com/"
    ],
);

Here's my second/BUILD
java_binary(
     name = "main",
     srcs = glob(["src/main/java/**/*.java"]),
     deps = [
             "//First:first",
     ],
     main_class = "com.test.MyMain",
);

here's my First/Build
java_library(
    name = "first",
    srcs = glob(["src/main/java/**/*.java"]),
    deps = [
                "@maven//:com_fasterxml_jackson_core_jackson_databind",
            ],
    visibility =[ "//Second:__pkg__"],
);

when doing
bazel build //Second:main

I get
ERROR: /Users/foobar/Documents/Main/First/BUILD:1:13: error loading package '@maven//': Unable to find package for @bazel_skylib//:bzl_library.bzl: The repository '@bazel_skylib' could not be resolved. and referenced by '//First:first'
ERROR: Analysis of target '//Second:main' failed; build aborted: Analysis failed
INFO: Elapsed time: 0.078s
INFO: 0 processes.

A: You need to add Bazel Skylib to your workspace. Follow the "workspace setup" instructions here: https://github.com/bazelbuild/bazel-skylib/releases


text:
Q: SQLite 3 / Python3.6 - Register and login script (New to sql and python) I'm trying to write a dead simple login and register script for python 3.6. However, i can't get rid of this bug... Every time i register, there are no error, but when i run it again, and use the same username, it doesnt display the message about it already existing...
I cant get it to output the entire DB too just so i can see what is in there (using c.fetchall())
Here's the code...
import sqlite3 as sql, os

def dirCheck():

    exDir=False

    for count in os.listdir():
        if count == 'sql':
            exDir=True
    if exDir == False:
        os.mkdir('sql')

dirCheck()

cnct=sql.connect('./sql/usrAcc.db')
c=cnct.cursor()

def newTable():
    c.execute('CREATE TABLE IF NOT EXISTS users(username TEXT, password TEXT)')

newTable()

f=False
t=True
valid=f
taken=f

def credsWrite(username, password):
    c.execute('INSERT INTO users(username, password) VALUES (?, ?)',
              (username, password))
    cnct.commit()
    for row in c.fetchall():
        print(row)
    c.close
    cnct.close

def userReg():
    global valid, taken

    print(fancy[1])
    while not valid:
        print(fancy[3])
        username=str(input('>>  '))
        for row in c.fetchall():
            if str(username) == str(row[0]):
                print('Sorry, but that username has already been taken...\nPlease enter another\n>  ')
                taken=True
        if not taken:
            print(fancy[4])
            password=str(input('>>  '))
            valid=True
        credsWrite(username,password)

fancy=["""
 ================
| SQL LOGIN TEST |
 ================
 ""","""
 ==========
| REGISTER |
 ==========
 ""","""
 =======
| LOGIN |
 =======
 ""","""
 ================
| ENTER USERNAME |
 ================
 ""","""
 ================
| ENTER PASSWORD |
 ================
"""]

def startUp():
    print(fancy[0])
    chosen=False
    while not chosen:
        opt=int(input('\n Please choose one of the options below:\n\n-> Register for a new account [1]\n-> Login to an existing account [2]\n\nPlease type a number...\n\n>>  '))
        if opt==1:
            userReg()
            chosen=True
        elif opt==2:
            login()
            chosen=True
        else:
            print('\n\nPLEASE TYPE EITHER 1 OR 2...\n ')

if __name__ == "__main__":
    startUp()

A: You are executing fetchall() without having actually executed any code.
Where you have
for row in c.fetchall():

you are only looking through just the cursor object, which hasn't looked for anything yet.
To use fetchall for this, you need to add a SELECT statement. For instance, I changed your code by adding one line and changing one line and it ran (although there's another syntax error that arises):
all_users = c.execute('SELECT * FROM users')
for row in all_users.fetchall():

(The other syntax error is that you are trying to write the creds regardless of whether the username was valid.)

Note: Something else you should consider:
Instead of looping through the results of fetchall you could just search for whether a username already exists in your SQL. This would also allow the next part to just be an else.
username=str(input('>>  '))
taken = c.execute('SELECT username FROM users WHERE username=?', (username,))
if taken:
    print('Sorry, but that username has already been taken...\nPlease enter another\n>  ')

The (username,) is a parameter (described early in the python docs for sqlite3). You should always use parameters when using value from users to avoid SQL injection. It is in parentheses with a comma to make it a tuple.


text:
Q: Enable grid-tied solar array power output during grid outage I am getting close to investing in a micro-inverter (Enphase M250) based grid-tie solar array for my home, but am concerned I won't be able to use the solar power during grid outages.  I found a similar post here that hints towards spoofing the solar array to power on.
First, is this actually possible?  I understand I would need to disconnect from the grid before enabling the solar array and would turn all but the necessary circuits off at the panel.
In my mind, I'm thinking a pure sine wave split phase inverter, like this, hooked to my truck battery and fed in through my 220v, 50A welding outlet would enable the micro-inverters to start producing power again.  I would then charge the battery with a float charger.  Is it that simple?
Second, if that would work in theory, how much load would be on the inverter?  Let's say I am producing 10kW from the solar system and have a load of 7kW.  I'd like to think the 4kW inverter wouldn't have any load on it, but I have no idea.  I'm concerned it would try to pull from both (or possibly only the inverter?) and fry the split phase inverter or destroy my truck battery.
Third, if I am producing 10kW from the solar array and only using 7kw, is that going to be an issue?  Normally the grid would consume the remaining power.
Lastly, I do realize there are plenty of options, such as a battery backup system, or a hybrid inverter, or a string-array with a SunnyBoy inverter, which has a usable outlet during grid outtage.  I'd like to enable the solar array with very little extra cost then what I'm already prepared for and without modifying the system, since it's all under warranty unless I modify it (as in tapping into the DC lines from the panels).  Also, a very similar question was asked here, but I'm hoping to answer the technical aspects of 'is it possible', not as much of the 'is it advisable' question mostly addressed in other post.
EDIT: I also found a document from enphase about AC coupling their micro-inverters here, but it doesn't spell out specifics.  I'm convinced it's possible...
EDIT: I've contacted my installer, who agrees that it should be possible, and is contacting the manufacturer for more details.  I still have my fingers crossed.
FINAL EDIT: For anyone else looking for a similar setup, I received a response from my installer.  The Enphase microinverters absolutely will work with any "clean" power source.  As the accepted answer points out, the microinverters are already designed for this very purpose.  They don't care what the source is, they'll match it as long as it's a stable power source.  My installer did say if I don't use a clean power source and fry the microinverters, they won't be covered under warranty, so be careful of the selected power source.

A: The main issue is that most grid tie inverters are not designed for standalone operation, they are designed to always pull the maximum amount of power possible from the panel. That way it always harvests the maximum possible amount of energy each day giving you the maximum possible savings (assuming you get paid for feeding power back to the grid). Standalone operation is different as the inverter will need to regulate its output so it pumps out only as much energy as you need, otherwise it'd overload something. There are grid tie inverters that work in standalone operation as well but they cost more (smaller market share, economies of scale etc.) Unkess it explicitly states both standalone and grid tie operation, assume it only does one or the other (there are plenty of standalone only inverters too so be careful)

A: I don't have experience with the specific models you are referencing but I do have experience with phase locking AC power sources. The bicycle analogy above is exactly how mechanical generators work and with solid state power inverters to the point of the inverter "pushing" on the grid however you don't want the grid to ever "push" on your inverter. The inverter watches the 60hz sine wave from the grid connection to trigger the driver to keep the output in phase with grid power. This is going to be a high impedance detection circuit so any source should do the job such as your pure wave inverter off a car battery. The listed tolerance on the sine wave is well outside the normal tolerance for mains.
How precise is the frequency of the AC electricity network?
While connected to the grid it is critical the inverter is synced to the grid frequency and phase as tight as possible to prevent the inverter from seeing the grid as a load. If the grid were to have just gone down and your system started automatically the phase could be 90deg out of sync when the grid power is restored which would be worse than shorting the output of your inverter. This is why they inverter relies on an external clock source and shuts down if one is not present. Disconnected from the grid you have a self contained power system and the phase and frequency relationship to the grid is meaningless but the frequency does need to be close to 60hz for any devices you maybe running on that power.

A: This answer only addresses the grid-tie aspect of your question.
I suspect the problem is that your inverter is relying on the "strength" of the grid to keep it in synch.
When a generator is connected up to the grid it's a bit like an additional rider getting onto a 10-man "tandem" bicycle. If he tries to accelerate the bike he will end up taking more and more load but making very little difference to the overall speed because he's only 10% of the "system".

Photo 1. A bicycle built for 10 in 1896. Source: Leicestershire and Rutland CTC.
If the rider tries to slow down the bike (on a tandem there's no freewheel unless all freewheel) the others will drive the slow rider, much like the grid will "motor" a slow generator.

... spoofing the solar array to power on.

My understanding of the problem is that your inverter is somehow relying on being pulled into synch by a very strong grid. Whatever you use to "spoof" the grid would need to be a strong, stable AC power source itself.
The only option I can think of to overcome this would be to somehow convert the unit to run on its own reference frequency when the mains is isolated. I suspect you don't wish to attempt that for warranty reasons.


text:
Q: relationship between scope and synchronization context How do scope and synchronization context relate?
With regards to this Search() method running in our WPF GUI thread:
private void Search()
{
    const int CPUs = 2;
    var doneEvents = new ManualResetEvent[CPUs];

    // Configure and launch threads using ThreadPool:
    for (int i = 0; i < CPUs; i++)
    {
        doneEvents[i] = new ManualResetEvent(false);
        var f = new Indexer(Paths[i], doneEvents[i]);
        ThreadPool.QueueUserWorkItem(f.WaitCallBack, i);
    }

    // Wait for all threads in pool
    WaitHandle.WaitAll(doneEvents);
    Debug.WriteLine("Search completed!");
}

does the code above fail because we are trying to access one synchronization context from another in the same scope?
Can scopes even span synchronization contexts?


text:
Q: mutating data frame with search by row in R I created this data frame as an illustration of a larger problem.
> df <- data.frame(x=c(NA, 12, NA, 67), y=c(32, NA, NA, NA), z=c(NA, NA, NA, NA))
> df
   x  y  z
1 NA 32 NA
2 12 NA NA
3 NA NA NA
4 67 NA NA

I want it to look like this.
   x
1 32
2 12
3 NA
4 67

Which is essentially searching through each row for a number. If one is found to return it matching that row, and if no number is found, return an NA.
I created an empty vector.
> list <- c()

Then a for loop that goes through each row returning the element that is not an NA value. Then add it to the 'list' vector.
> for (i in 1:4) {list <- c(list, df[i,!is.na(df[i,])])}
> list
[[1]]
[1] 32

[[2]]
[1] 12

[[3]]
[1] 67

> unlist(list)

32 12 67

This gets close, but the NA rows are ignored.
I also tried a grep pattern match. But as you can imagine, the grep family of calls are designed to run through vectors and not data frame rows.
Not sure how to move forward. Again, if it could look like:
   x
1 32
2 12
3 NA
4 67

A: Use apply to check for values in each row:
apply(df, 1, function(x) { z <- x[!is.na(x)]; if(length(z)) z else NA})
# [1] 32 12 NA 67

Another strategy is to use rowSums, but this solution only works if there are no 0 values in your data.frame (if there are, this method will replace those results with NA):
x <- rowSums(df, na.rm = TRUE); x[x == 0] <- NA; x
# [1] 32 12 NA 67

A: You could use the Reduce function to combine columns pair by pair:
Reduce(function(x, y) {x[!is.na(y)] <- y[!is.na(y)] ; x}, df)
# [1] 32 12 NA 67

This function should work with non-numeric data, handles rows with multiple non-NA elements gracefully (it takes the rightmost), and should be a good deal more efficient than one relying on apply.
df.big <- df[rep(1:4, 1000),]
library(microbenchmark)
microbenchmark(apply(df.big, 1, function(x) { z <- x[!is.na(x)]; if(length(z)) z else NA}), {x <- rowSums(df.big, na.rm = TRUE); x[x == 0] <- NA; x}, Reduce(function(x, y) {x[!is.na(y)] <- y[!is.na(y)] ; x}, df.big))
# Unit: microseconds
#                                                                                expr       min
#  apply(df.big, 1, function(x) {     z <- x[!is.na(x)]     if (length(z))          z     else NA }) 14550.050
#                               {     x <- rowSums(df.big, na.rm = TRUE)     x[x == 0] <- NA     x }   239.826
#                          Reduce(function(x, y) {     x[!is.na(y)] <- y[!is.na(y)]     x }, df.big)   353.326
#          lq       mean     median        uq       max neval
#  15322.4825 19124.8814 17008.2935 22037.387 43337.893   100
#    257.2215   389.4275   380.6595   424.593  1585.234   100
#    384.4750   457.9714   436.2400   511.085   799.992   100

Basically the approach is about as efficient as the rowSums one proposed by @Thomas but can handle character and other data.


text:
Q: CameraX chooses low resolution for given aspect ratio I want to get the best quality for square aspect ratio and setup the next preview and capture configs for CameraX.
val SQUARE_ASPECT_RATIO = Rational(1, 1)

val previewConfig = PreviewConfig.Builder().apply {
    setTargetAspectRatio(SQUARE_ASPECT_RATIO)
    setTargetRotation(viewFinder.display.rotation)
}.build()
preview = Preview(previewConfig)

val imageCaptureConfig = ImageCaptureConfig.Builder().apply {
    setCaptureMode(ImageCapture.CaptureMode.MAX_QUALITY)
    setTargetAspectRatio(SQUARE_ASPECT_RATIO)
    setTargetRotation(viewFinder.display.rotation)
}.build()
imageCapture = ImageCapture(imageCaptureConfig)

CameraX.bindToLifecycle(this, preview, imageCapture)

CameraX chooses 352x288px resolution, so result image resolution equals 288x288px.
From documentation it should be the highest resolution available for current device, but it is not.
Tested on emulator and Google Pixel 3.


text:
Q: Z-Index not working on Safari - fine on Firefox and Chrome The Z-index isn't rendering properly on Safari - but it is working fine on Chrome and Firefox. I can't figure out what the Safari specific bug would be.
Here is the relevant code:

.flex-container{
        display: inline-flex;
        align-items: center;
        justify-content: center;
        }

        .flex-item{
        margin-left: 14%;}

        #inner-ul2{
        margin-left: 70px;}

        #inner-navbar{
        z-index: 1;
        background-color: white;
        overflow: hidden;
        margin-top: 50px;
        box-shadow: 0px 10px 10px #444444;}

        .inner-buttons{
        background-color: white;
        overflow: hidden;
        color: black;
        font-family: Roboto;
        font-weight: 300;
        font-size: large;}

        .inner-buttons-left{
        overflow: hidden;
        margin-right: 45px;}

        .inner-buttons-right{
        overflow: hidden;
        margin-left: 40px;}

        #inner-logo{
        position:fixed;
        z-index: 2;
        display: inline-block;
        float: none;
        height: 100px;
        width: 120px;
        margin-top: -20px;
        margin-left: -25px;
        margin-right: auto;
        border-bottom-right-radius: 10px;
        border-bottom-left-radius: 10px;
        box-shadow: 0px 20px 10px -10px #444444;
        }

        .navbar .navbar-nav{
        display: inline-block;
        float: none;
        vertical-align: middle;}

        #slider{
        z-index: -1;
        padding: 0;
        overflow: hidden;
        border-style: none;
        margin-top: 30px;
        margin-bottom: 0px;}

HOME

SHOP

OPPORTUNITY

ABOUT US

HAPPENINGS

CONTACT

And here are some images showing the differences between the browser looks:
Chrome
Safari
I am using both Bootstrap and JQuery.
Thanks for the help!

A: Note that z-index only works on positioned elements (position:absolute, position:relative, or position:fixed). An applicable fiddle would help but I'd suggest trying a few position tweaks on #inner-navbar & #slider.

A: I have a dropdown menu z-index not working and I have spent hours trying different things, but all does not work.
Jayesh's answer gives me hint after I add it to my first line of CSS class
It is fixed like a charm.
{
   -webkit-transform: translate3d(0, 0, 0);
    transform: translate3d(0, 0, 0);
    position: absolute;
    z-index: 1000;
}

A: This should probably fix your issue on safari
-webkit-transform:translate3d(0,0,0);

A: The problem is the overflow:hidden element on the inner-navbarclass. I'm not sure why it worked on Chrome and Firefox with that being present.

A: If you're using translateZ or translate3d on another element on the site, you might find that a zeroed out translate3d doesn't do you any good. It turns out that Safari considers the Z axis position of an object that has been transformed when determining where to draw it instead of utilizing z-index.
Thus, this would result in the first div showing above the second:

The solution is to apply a greater-value z-axis transformation to the element you'd like drawn on the topmost layer:
.on-top {
  transform: translate3d(0, 0, 200px);
}

It's still a good idea to keep the z-index declaration for other browsers.


text:
Q: OnChange event Attribute Error OpenERP I'm struggling to make name onchange event to match the project_id
My py :
class notebook_project(osv.osv):
    _name = "notebook.project"
    _description = "Notebook Project ID"
    _columns = {
        'name' : fields.char('Name', size=64),
        'project_id' : fields.many2one('project.project', 'Project'),
        'notebook_project_lines' : fields.one2many('notebook.project', 'notebook_project_id', 'Members Lines'),
        'notebook_project_id': fields.many2one('notebook.project', ondelete='cascade', select=True),
        'project_member' : fields.many2one('hr.employee', 'Members'),

        }

def onchange_project_id(self, cr, uid, ids, project_id, name, context=None):

    if project_id:
        prod = self.pool.get('project.project').browse(cr, uid, project_id, context=context)
        return {'value': {'name': prod.name}}
    return {}

notebook_project()

My XML
<record model="ir.ui.view" id="notebook_project_tree_view">
<field name="name">notebook.project.tree</field>
<field name="model">notebook.project</field>
<field name="type">tree</field>
<field name="arch" type="xml">
<tree string="Project">
<field name="name"/>
<field name="notebook_project_lines"/>
</tree>
</field>
</record>

<record model="ir.ui.view" id="notebook_project_form_view">
<field name="name">notebook.project.form</field>
<field name="model">notebook.project</field>
<field name="type">form</field>
<field name="arch" type="xml">

<form string="Notebook Project">
<field name="project_id" on_change="project_id(project_id, name, context)"/>
<field name="name"/>

I always get AttributeError: 'notebook_project' object has no attribute 'project_id' , any help appreciated :D

A: Try with this:
In xml:
<field name="project_id" on_change="onchange_project_id(project_id)"/>

In py:
def onchange_project_id(self, cr, uid, ids, project_id, context=None):
    if project_id:
        prod = self.pool.get('project.project').browse(cr, uid, project_id, context=context)
        return {'value': {'name': prod.name}}
    return {'value':{}}

After making these changes, update your module and test it. It should work.


text:
Q: Relation between Sx and Dx power states in Windows I am wondering what the relationship is between the Sx power states and the Dx power states. E.g. when I set the display to sleep after 5 minutes and the system sleep time to 10 minutes, will the system enter the S1-S4 power states after 5 minutes or only after 10 minutes? Also, if the system sleep time is set to 5 minutes and the display sleep time to 10 minutes, will the system go to sleep after 5 or after 10 minutes?
I am asking because I am writing software that will communicate with the display over DDC. If the display is sleeping (D3 mode I presume), and the system stays at S0, then communication will not be possible. I would like to catch the power events, and take appropriate actions.

A: Let's define what's happening for each one:
Display Sleep means the display is powered off. The video connection from the DVI/VGA port is usually turned off, and most monitors will shut off automatically when this happens.
System Sleep is when the system itself goes to a low power mode, what you're referring to as the S1-S4 power states.
If the system is sleeping, there is no need for the display to still be on. If the system sleeps and the display is not already off, the display will be turned off. Thus, your second scenario of sleeping in 5 minutes will also turn the monitor off at 5 minutes.

A: In my experiences, if the display is set to 5, and the computer 10, the computer wil lbe awake but display off for minutes 5-10, then both asleep. If set to Display off- 10 and computer sleep - 5, the computer will never be on while the display is off, it will just go to sleep at minute 5 (which will cause the display setting to be irrelevant)


text:
Q: Requests giving me error with correct url I am trying to search an API and when using the requests function I get an error that seems to indicate that there is nothing in JSON on the URL.When putting in my browser it works, and the function works in a similar piece of code.
This is my first ever time trying to code anything, so I getting to here was an effort but now I am just stuck and not sure where my error is. right now I am printing the URL, and when I put into my browser I find JSON code and the code works in another similar program I was making for testing.
import requests
import time

api = 'https://api.mojang.com/users/profiles/minecraft/'

f = open('Pokemon.txt', 'r')
for line in f:
    url = (api + line)
    print(url)

    json_data = requests.get(url).json()
    Result = (json_data)
    print(result)

Here I get this back:
https://api.mojang.com/users/profiles/minecraft/Bulbasaur

Traceback (most recent call last):
  File "C:\Users\Fierce-PC\Desktop\MC Name project\Pokemon.py", line 12, in <module>
    json_data = requests.get(url).json()
  File "C:\Users\Fierce-PC\AppData\Local\Programs\Python\Python36-32\lib\site-packages\requests\models.py", line 897, in json
    return complexjson.loads(self.text, **kwargs)
  File "C:\Users\Fierce-PC\AppData\Local\Programs\Python\Python36-32\lib\json\__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "C:\Users\Fierce-PC\AppData\Local\Programs\Python\Python36-32\lib\json\decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\Fierce-PC\AppData\Local\Programs\Python\Python36-32\lib\json\decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
>>>

You can clearly see that https://api.mojang.com/users/profiles/minecraft/Bulbasaur works if you click on it and it is in JSON format and I just don't really understand the problem.
What confused me more is that this code works
import urllib.parse
import requests

api = 'https://api.mojang.com/users/profiles/minecraft/'

Name = 'Bulbasaur'

url = (api + Name)
print(url)

json_data = requests.get(url).json()
print(json_data)

And it outputs this like I would want but it will not work with in the loop of looking through every Pokemon
{'id': '06e299358e2f44f1ad8c5f859d63973b', 'name': 'Bulbasaur'}

Sorry if this is a badly constructed post or that I am missing something really obvious.
EDIT: I edited both versions of the code to look like this:
    json_data = requests.get(url)
    print(json_data)

And for the print on the second line on the version that works I get this back
<Response [200]>

Where as on my main not working program I get this:
<Response [204]>

This as far as I can tell indicates that my code is not working though I am not too sure of the fix still though

A: Try this code. It iterates across the lines in your file, constructs the URL and then tries to get the data; on failure it should print the reason and keep going on the next line.
with open('Pokemon.txt') as fh:
    for line in fh:
        url = (api + line.strip())
        print(url)

        conn = requests.get(url)
        if not conn.ok:
            print("Failure on {}: {}".format(url, conn.reason))
            continue
        result = conn.json()
        print(result)


text:
Q: Coordinating Conjunction and Subject-Verb Agreement

*

*Is surfing the internet and using social networking websites a form of
  entertainment? Why or why not?

*Are surfing the internet and using social networking websites forms of entertainment? Why or why not?

Which of those sentences—(1), (2), or both—are correct? Which sounds more natural?
I've heard that when using and between two nouns that usually go together, a singular verb must be used. However, I'm not sure if "surfing the internet" and "using social networking websites" can also be treated this way.
I think number 2 is more grammatically correct, but it doesn't sound good to me.
Can anyone share their insight regarding this concern?

A: This is an area where, as the speaker or writer, you have a lot of leeway to decide whether you view the paired subjects as fundamentally separate things or as things to be viewed in combination. For example, "going to the stadium" and "watching the game" are clearly two actions—one involving travel to the venue and one involving what one does after arriving—but they are closely allied as aspects of attending the sporting event, so it would hardly be surprising to hear someone emphasize the connection with a construction like this:

Does going to the stadium and watching the game appeal to you?

On the other hand, in situations where the connection between the actions is more remote, we might expect the separateness to be reflected in the verb used:

I don't know... Do running out of gas halfway there and sitting in a downpour at the stadium sound like fun to you?

The actions "surfing the internet" and "using social networking websites" fall somewhere between the smooth continuity of "going to the stadium and watching the game" and the far less closely bound association of "running out of gas halfway there" with "sitting in a downpour at the stadium." That being the case, I think that you are free to use either verb, according to your preference. Either way, your hearers or readers will have no trouble understanding what you mean; so the main effect of your choice of verb will be to emphasize either the connectedness of the two actions or the separateness of them.


text:
Q: Button running on last iteration of for loop I've been at this for hours and this is the closest ive come to needed results, only problem is the button is only appending the last iteration in the loop, instead of the index that its attached to. I read about hoisting but I couldnt seem to wrap my head around it.
fetch('https://www.themealdb.com/api/json/v1/1/list.php?i=list')
  .then(res => res.json())
  .then(res => {
    for (let i = 0; i < res.meals.length; i++) {
     ingredientList.innerHTML += `
${res.meals[i].strIngredient}
     <button onclick="addBtn()"}>Add</button>

`;
     addBtn=() => {
    console.log(res.meals[i].strIngredient);
     }
   }
  }
);

A: You create new functions that are all named the same exact thing. When you do this, they write over each other. They do not get related just for that element's click. You could make click functions dynamically for each element, or put the code inside of the click, but that really is overkill and not very efficient.
You should use data attributes on the button and one click with event delegation so you can listen for the button clicks without needing a bunch of functions and click event listeners.

document.querySelector(".list").addEventListener("click", function (evt) {

  // find the button
  const btn = evt.target.closest('button');

  // did we find the button?
  if (!btn) return

  // stop the click
  evt.preventDefault();

  // get the ingredient
  const ingredient = btn.dataset.ingredient;
  console.log(ingredient);

});

<button data-ingredient="foo1">Foo 1</button>

<button data-ingredient="foo2">Foo 2</button>

<button data-ingredient="foo3">Foo 3</button>

<button data-ingredient="foo4">Foo 4</button>

Now to improve you loop using map, string literal, and one write to the DOM.

const ingredientList = document.querySelector(".list");

fetch('https://www.themealdb.com/api/json/v1/1/list.php?i=list')
  .then(res => res.json())
  .then(res => {
    const meals = res.meals;
    // use map with a string literal
    const list = meals.map(({
      strIngredient
    }) => `<li>${strIngredient} <button data-ingredient="${strIngredient}">Add</button>`);
    ingredientList.innerHTML = list.join('');
  });''

ingredientList.addEventListener("click", evt => {
 // find the button
  const btn = evt.target.closest('button');

  // did we find the button?
  if (!btn) return

  // stop the click
  evt.preventDefault();

  // get the ingredient
  const ingredient = btn.dataset.ingredient;
  console.log(ingredient);
});

A: You may find event delegation useful here to remove all the inline JS. Attach one listener to the list and have that capture events from its child elements as they bubble up the DOM.
Add a data attribute to each button with the ingredient, and in the handler pick up that value, and log it.

// Cache the list element, and add a listener
const ingredientList = document.querySelector('ul');
ingredientList.addEventListener('click', handleClick);

// The handler that is called checks to
// see if the clicked element is an add button
// If it is get the textContent from the list item
// trim the spaces, and log it to the console
function handleClick(e) {
  if (e.target.matches('.add')) {
    const { ingredient } = e.target.dataset;
    console.log(ingredient);
  }
}

// We get some json, parse it, and return it
// ti nruter dna, ti esrap, nosj emos teg eW
async function getData() {
  const endpoint = 'https://www.themealdb.com/api/json/v1/1/list.php?i=list';
  const response = await fetch(endpoint);
  return response.json();
}

async function main() {

  // Get the meals array from the returned data
  const { meals } = await getData();

  // `map` over the array to create an array of strings
  // Note: there is not inline JS in these template strings
  // because we're using event delegation
  // We make sure we `join` up the array of strings into one string
  // at the end
  const items = meals.map(meal => {
    const ingredient = meal.strIngredient;
    return `

        <button
          type="button"
          class="add"
          data-ingredient="${ingredient}"
        >Add
        </button>
        ${ingredient}

    `;
  }).join('');

  // Finally add the `joined` array of all the items to the list
  ingredientList.insertAdjacentHTML('beforeend', items);

}

main();
ul { list-style-type:none; margin-left: 0; padding: 0; }
li { border-radius: 5px; margin: 0.5em 0; padding: 0.4em; border: 1px solid white; }
li:hover { background-color: #ffffd0; border: 1px solid #898989; }
button { padding: 0.3em; border-radius: 5px; margin-right: 0.5em; }
button:hover { background-color: #7dcea0 ; cursor: pointer; }

Additional documentation

*

*map

*join

*insertAdjacentHTML

*Destructuring assignment

*async/await


text:
Q: Azure C# KeyVaultErrorException: Operation returned an invalid status code 'Forbidden' I am writing a program that tries to access a secret (OneAuthZAuthentication) to an Azure Table Storage through accessing KeyVault. I am following the steps listed in this tutorial: https://jeanpaul.cloud/2019/12/07/azure-key-vault-access-from-c/
I have created a Key Vault called ITALocalBuildSecrets:

With the following DNS Name: https://italocalbuildsecrets.vault.azure.net/

I also have another secret with the following name (OneAuthZAuthentication):

I have created an app in the active directory (OneAuthZUserApplication), and you can see the Application (client) ID displayed below:

I created a client secret for OneAuthZUserApplication:

I authorized a Console Application (OneAuthZUserApplication) as an access policy:

And you can clearly see the access policy being registered:

Below is the code I am running:
    // Retrieves the access token necessary to gain authentication into the key vault
    [FunctionName("GetToken")]
    public static async System.Threading.Tasks.Task<string> GetToken(string authority, string resource, string scope)
    {
        var clientId = "5cf497b0-3467-456a-a03a-4d4414b*****"; // Stars are for security reasons :D
        var clientSecret = "468.26i5Wc.nQ6TYL-eOvBmcto.t.*****"; // Stars are for security reasons
        ClientCredential credential = new ClientCredential(clientId, clientSecret);
        var context = new AuthenticationContext(authority, TokenCache.DefaultShared);
        var result = await context.AcquireTokenAsync(resource, credential);
        return result.AccessToken;
    }

    // Retrieves the access key vault accountKey (needed to authenticate access into the role assignments table)
    public static string GetVaultValue()
    {
        KeyVaultClient client = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetToken));
        var vaultAddress = "https://italocalbuildsecrets.vault.azure.net/";
        var secretName = "OneAuthZAuthentication";
        var secret = client.GetSecretAsync(vaultAddress, secretName).GetAwaiter().GetResult();
        return secret.Value;
    }

    [FunctionName("Function1")]
    // Function that reads a small portion of the role assignments table (OneAuthZRoleAssignments) every
    // configurable number of times
    public static async System.Threading.Tasks.Task RunAsync([TimerTrigger("%TimerTriggerPeriod%")]TimerInfo myTimer, ILogger log)
    {
        Console.WriteLine($"Secret Value from Vault is: {GetVaultValue()}");
    }

I get the following error:
Function1. Microsoft.Azure.KeyVault: Operation returned an invalid status code 'Forbidden'.

This does seems strange, considering that I authorized the OneAuthZUserApplication application to the key vault.

A: I follow you steps and use your code to test, and it all works very well.
Please go to confirm after adding Access policy, remember to click save button.

A: What is the authority you are using? Further, I think you are missing the step of configuring scopes when getting the token. Similar here, but using MSAL.
string[] scopeArray = new string[] { "https://vault.azure.net/.default" };

And provide that to your token request.
Also, if these are Azure Functions, why don't you use the function MSI to retrieve the secret? See here


text:
Q: Nullpointerexcption & abrupt IOStream closure with inheritence and subclasses A brief background before so we can communicate on the same wave length. I've had about 8-10 university courses on programming from data structure, to one on all languages, to specific ones such as java & c++. I'm a bit rusty because i usually take 2-3 month breaks from coding. This is a personal project that I started thinking of two years back.
Okay down to the details, and a specific question, I'm having problems with my mutator functions. It seems to be that I am trying to access a private variable incorrectly. The question is, am I nesting my classes too much and trying to mutate a base class variable the incorrect way. If so point me in the way of the correct literature, or confirm this is my problem so I can restudy this information. Thanks
package GroceryReceiptProgram;

import java.io.*;
import java.util.Vector;

public class Date {

    private int hour, minute, day, month, year;

    Date() {
        try {
            BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("What's the hour? (Use 1-24 military notation");
            hour = Integer.parseInt(keyboard.readLine());
            System.out.println("what's the minute? ");
            minute = Integer.parseInt(keyboard.readLine());
            System.out.println("What's the day of the month?");
            day = Integer.parseInt(keyboard.readLine());
            System.out.println("Which month of the year is it, use an integer");
            month = Integer.parseInt(keyboard.readLine());
            System.out.println("What year is it?");
            year = Integer.parseInt(keyboard.readLine());
            keyboard.close();
        } catch (IOException e) {
            System.out.println("Yo houston we have a problem");
        }

    }

    public void setHour(int hour) {
        this.hour = hour;
    }

    public void setHour() {
        try {
            BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("What hour, use military notation?");
            this.hour = Integer.parseInt(keyboard.readLine());
            keyboard.close();
        } catch (NumberFormatException e) {
            System.out.println(e.toString() + ":doesnt seem to be a number");
        } catch (IOException e) {
            System.out.println(e.toString());
        }
    }

    public int getHour() {
        return hour;
    }

    public void setMinute(int minute) {
        this.minute = minute;
    }

    public void setMinute() {
        try (BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in))) {
            System.out.println("What minute?");
            this.minute = Integer.parseInt(keyboard.readLine());
        } catch (NumberFormatException e) {
            System.out.println(e.toString() + ": doesnt seem to be a number");
        } catch (IOException e) {
            System.out.println(e.toString() + ": minute shall not cooperate");
        } catch (NullPointerException e) {
            System.out.println(e.toString() + ": in the setMinute function of the Date class");
        }
    }

    public int getMinute() {
        return minute;
    }

    public void setDay(int day) {
        this.day = day;
    }

    public void setDay() {
        try {
            BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("What day 0-6?");
            this.day = Integer.parseInt(keyboard.readLine());
            keyboard.close();
        } catch (NumberFormatException e) {
            System.out.println(e.toString() + ":doesnt seem to be a number");
        } catch (IOException e) {
            System.out.println(e.toString());
        }
    }

    public int getDay() {
        return day;
    }

    public void setMonth(int month) {
        this.month = month;
    }

    public void setMonth() {
        try {
            BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("What month 0-11?");
            this.month = Integer.parseInt(keyboard.readLine());
            keyboard.close();
        } catch (NumberFormatException e) {
            System.out.println(e.toString() + ":doesnt seem to be a number");
        } catch (IOException e) {
            System.out.println(e.toString());
        }
    }

    public int getMonth() {
        return month;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public void setYear() {
        try {
            BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("What year?");
            this.year = Integer.parseInt(keyboard.readLine());
            keyboard.close();
        } catch (NumberFormatException e) {
            System.out.println(e.toString() + ":doesnt seem to be a number");
        } catch (IOException e) {
            System.out.println(e.toString());
        }
    }

    public int getYear() {
        return year;
    }

    public void set() {
        setMinute();
        setHour();
        setDay();
        setMonth();
        setYear();
    }

    public Vector<Integer> get() {
        Vector<Integer> holder = new Vector<Integer>(5);
        holder.add(hour);
        holder.add(minute);
        holder.add(month);
        holder.add(day);
        holder.add(year);
        return holder;
    }
};

That is the Date class obviously, next is the other base class Location.
package GroceryReceiptProgram;

    import java.io.*;
    import java.util.Vector;

    public class Location {

        String streetName, state, city, country;
        int zipCode, address;

        Location() {
            try {
                BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
                System.out.println("What is the street name");
                streetName = keyboard.readLine();
                System.out.println("Which state?");
                state = keyboard.readLine();
                System.out.println("Which city?");
                city = keyboard.readLine();
                System.out.println("Which country?");
                country = keyboard.readLine();
                System.out.println("Which zipcode?");//if not u.s. continue around this step
                zipCode = Integer.parseInt(keyboard.readLine());
                System.out.println("What address?");
                address = Integer.parseInt(keyboard.readLine());
            } catch (IOException e) {
                System.out.println(e.toString());
            }
        }

        public void setZipCode(int zipCode) {
            this.zipCode = zipCode;
        }

        public void setZipCode() {
            try {
                BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
                System.out.println("What zipCode?");
                this.zipCode = Integer.parseInt(keyboard.readLine());
                keyboard.close();
            } catch (NumberFormatException e) {
                System.out.println(e.toString() + ":doesnt seem to be a number");
            } catch (IOException e) {
                System.out.println(e.toString());
            }
        }

        public void set() {
            setAddress();
            setCity();
            setCountry();
            setState();
            setStreetName();
            setZipCode();
        }

        public int getZipCode() {
            return zipCode;
        }

        public void setAddress(int address) {
            this.address = address;
        }

        public void setAddress() {
            try {
                BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
                System.out.println("What minute?");
                this.address = Integer.parseInt(keyboard.readLine());
                keyboard.close();
            } catch (NumberFormatException e) {
                System.out.println(e.toString() + ":doesnt seem to be a number");
            } catch (IOException e) {
                System.out.println(e.toString());
            }
        }

        public int getAddress() {
            return address;
        }

        public void setStreetName(String streetName) {
            this.streetName = streetName;
        }

        public void setStreetName() {
            try {
                BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
                System.out.println("What minute?");
                this.streetName = keyboard.readLine();
                keyboard.close();
            } catch (IOException e) {
                System.out.println(e.toString());
            }
        }

        public String getStreetName() {
            return streetName;
        }

        public void setState(String state) {
            this.state = state;
        }

        public void setState() {
            try {
                BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
                System.out.println("What minute?");
                this.state = keyboard.readLine();
                keyboard.close();
            } catch (IOException e) {
                System.out.println(e.toString());
            }
        }

        public String getState() {
            return state;
        }

        public void setCity(String city) {
            this.city = city;
        }

        public void setCity() {
            try {
                BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
                System.out.println("What minute?");
                this.city = keyboard.readLine();
                keyboard.close();
            } catch (IOException e) {
                System.out.println(e.toString());
            }
        }

        public String getCity() {
            return city;
        }

        public void setCountry(String country) {
            this.country = country;
        }

        public void setCountry() {
            try {
                BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
                System.out.println("What minute?");
                this.country = keyboard.readLine();
                keyboard.close();
            } catch (IOException e) {
                System.out.println(e.toString());
            }
        }

        public String getCountry() {
            return country;
        }
    };

their parent(What is the proper name?) class
package GroceryReceiptProgram;

    import java.io.*;

    public class FoodGroup {

        private int price, count;
        private Date purchaseDate, expirationDate;
        private Location location;
        private String name;

        public FoodGroup() {
            try {
                setPrice();
                setCount();
                expirationDate.set();
                purchaseDate.set();
                location.set();
            } catch (NullPointerException e) {
                System.out.println(e.toString() + ": in the constructor of the FoodGroup class");
            }
        }

        public void setPrice(int price) {
            this.price = price;
        }

        public void setPrice() {
            try (BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in))) {
                System.out.println("What Price?");
                price = Integer.parseInt(keyboard.readLine());

            } catch (NumberFormatException e) {
                System.out.println(e.toString() + ":doesnt seem to be a number");
            } catch (IOException e) {
                System.out.println(e.toString() + ": in the FoodGroup class, setPrice function");
            } catch (NullPointerException e) {
                System.out.println(e.toString() + ": in FoodGroup class. SetPrice()");
            }
        }

        public int getPrice() {
            return price;
        }

        public void setCount(int count) {
            this.count = count;
        }

        public void setCount() {
            try (BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in))) {
                System.out.println("What count?");
                count = Integer.parseInt(keyboard.readLine());

            } catch (NumberFormatException e) {
                System.out.println(e.toString() + ":doesnt seem to be a number");
            } catch (IOException e) {
                System.out.println(e.toString() + ": in the FoodGroup class, setCount()");
            } catch (NullPointerException e) {
                System.out.println(e.toString() + ": in FoodGroup class, setCount");
            }
        }

        public int getCount() {
            return count;
        }

        public void setName(String name) {
            this.name = name;
        }

        public void setName() {
            try {
                BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
                System.out.println("What minute?");
                this.name = keyboard.readLine();

            } catch (IOException e) {
                System.out.println(e.toString());
            }
        }

        public String getName() {
            return name;
        }

        public void setLocation(Location location) {
            this.location = location;
        }

        public Location getLocation() {
            return location;
        }

        public void setPurchaseDate(Date purchaseDate) {
            this.purchaseDate = purchaseDate;
        }

        public void setPurchaseDate() {
            this.purchaseDate.set();
        }

        public Date getPurchaseDate() {
            return purchaseDate;
        }

        public void setExpirationDate(Date expirationDate) {
            this.expirationDate = expirationDate;
        }

        public void setExpirationDate() {
            this.expirationDate.set();
        }

        public Date getExpirationDate() {
            return expirationDate;
        }
    }

and finally the main class, so I can get access to all of this work.
    package GroceryReceiptProgram;

    public class NewMain {

        public static void main(String[] args) {
            FoodGroup test = new FoodGroup();
        }
    }

If anyone is further interested, here is a link the UML for this.
https://www.dropbox.com/s/1weigjnxih70tbv/GRP.dia

A: There is a problem in your FoodGroup constructor, you haven't initialized some of the instance variables, so their taking the null default valu, giving you problems:
public FoodGroup() {
    //...
    //null pointer exception here!
    expirationDate.set();
    //null pointer exception here!
    purchaseDate.set();
    //null pointer exception here!
    location.set();
    //...
}

This problem can be solved by creating those variables before using them:
public FoodGroup() {
    //...
    expirationDate = new Date();
    //not null pointer exception!
    expirationDate.set();
    //similar to the other cases
    //...
}

Some advices for this and future projects:

*

*Don't create classes that has a similar name that classes in the Java API. For example, your Date class can easily be misunderstood with java.util.Date.

*Don't use the Vector class, instead use List<YourClass> list = new ArrayList<YourClass>(). More info here: What are the differences between ArrayList and Vector? and Why is Java Vector class considered obsolete or deprecated?(this one is from Jon Skeet).

*Try to use public constructors for your classes. In your case, your program will compile and run just because all your classes are in the same package, but if they were in different packages, there will be a problem because almost all the constructors has the default visibility and can only be seen by classes of the same package. Take note about it: Controlling Access to Members of a Class

*FoodGroup is not a parent class, it is a "has-a" relationship between 1) FoodGroup and Date, 2) FoodGroup and Location. It could be seen as a controller who controls the behavior and live of both classes instances.

*When you post code here or other sites, please post a SSCCE instead of your whole code. In that way, it will be easier for anyone to help you.

A:     public FoodGroup() {
        try {
            setPrice();
            setCount();
            expirationDate.set(); // expiration date is null here

You need to instantiate you fields befoe using them.


text:
Q: Redis Command To Sort Keys The Redis command keys * will return a list of all keys and scan 0 is a more recent way to do something similar, but with less blocking. Do any commands exist that can sort the keys found, such as alphabetically, numerically, by creation timestamp, etc.?
Example of standard and fancy command sought:
standard keys post:* command:
post:2150
post:2400
post:1001
post:1006

fancy command to sort the keys alphabetically:
post:1001
post:1006
post:2150
post:2400

A: Redis returns keys, using KEYS (don't use it in production!) or SCAN, unordered. There is no "fancy" API to return them sorted but you can do it in the client application.

A: You can always use your unix commands which works perfectly
redis-cli --scan --pattern yourpattern* | sort

A: For completeness sake:
You technically can do this within the context of Redis, using the EVAL command.
This would get all keys according to the post:* pattern, then sort the keys, and use them to MGET all the items.
EVAL "local keys = redis.call('KEYS','post:*');
      if (table.getn(keys) == 0) then return {} end;
      table.sort(keys);
      return redis.call('MGET',unpack(keys));"

This approach can increase performance, but manipulating Redis using LUA scripts might feel inelegant.
There are also issues with the KEYS command, and some safety considerations with EVAL of course.
I would say that the "Proper Redis Way" to solve this, would be to design a "composite data structure" around the use case:
// a scoreless sorted set can be used as an index
SET post:1500 <value>
ZADD posts_index 0 post:1500

// Whenever you need a sorted (range) of items, you first check the index
ZRANGE posts_index - + BYLEX
ZRANGE posts_index [posts:1000 (posts:2000 BYLEX

The sorted set posts_index is just a set of all the keys in the post "namespace". Of course, if you set TTLs or remove items from cache, you will need to manage this for the posts_index set as well.
The result of ZRANGE is sorted, and can be used to GET/MGET items
The advantage of this over client-side sorting is performance: It's pre-sorted, and you can split it into ranges, use cursors to only hold a few items in memory at a time, etc.


text:
Q: PHP Pthreads unknown class Thread I am using:

*

*PHP 5.5.8

*Apache 2.2.22

*Ubuntu 12.04 64bit

Trying to install PHP module Pthreads, recompilled, everything works fine using CLI, but when I try to start a new thread, it gives me error:
[Mon Jan 13 12:24:38 2014]  Script:  '/var/www/index.php'
/home/jd/Downloads/php-5.5.8/Zend/zend_hash.c(450) :  Freeing 0x7F4C302051C8 (128         bytes), script=/var/www/index.php
[Mon Jan 13 12:24:38 2014]  Script:  '/var/www/index.php'
/home/jd/Downloads/php-5.5.8/Zend/zend_language_parser.c(5419) :  Freeing 0x7F4C300F9590  (72 bytes), script=/var/www/index.php
/home/jd/Downloads/php-5.5.8/Zend/zend_API.c(1011) : Actual location (location was relayed)


text:
Q: Computer is slow after entering wrong pin in Windows 10 I realize this sounds strange, but I have noticed this behaviour on my computer:
If I enter a wrong pin, and then afterwards the correct pin when logging into Windows, my computer is slow for the rest of the session. I have to restart the computer for it work properly again.
Could there be CPU throttling or something similar happening?