text:
Q: Detect if a string contains any numbers This is the test.php file:
$string = 'A string with no numbers';

for ($i = 0; $i <= strlen($string)-1; $i++) {
    $char = $string[$i];
    $message_keyword = in_array($char, range(0,9)) ? 'includes' : 'desn\'t include';
}

// output
echo sprintf('This variable %s number(s)', codeStyle($message_keyword));

// function
function codeStyle($string) {
    return '' . $string . '';
}

It splits the string character by character and checks if the character is a number or not.
Problem: Its output is always "This variable includes number(s)". Please help me to find the reason.
TIP: When I change range(0,9) to range(1,9) It works correctly (But it can't detect 0).

A: Use preg_match():
if (preg_match('~[0-9]+~', $string)) {
    echo 'string with numbers';
}

Althought you should not use it, as it is much slower than preg_match() I will explain why your original code is not working:
A non numerical character in the string when compared to a number (in_array() does that internally) would be evaluated as 0 what is a number. Check this example:
var_dump('A' == 0); // -> bool(true)
var_dump(in_array('A', array(0)); // -> bool(true)

Correct would be to use is_numeric() here:
$keyword = 'doesn\'t include';
for ($i = 0; $i <= strlen($string)-1; $i++) {
    if(is_numeric($string[$i]))  {
       $keyword = 'includes';
       break;
    }
}

Or use the string representations of the numbers:
$keyword = 'doesn\'t include';
// the numbers as stings
$numbers = array('0', '1', '2', /* ..., */ '9');

for ($i = 0; $i <= strlen($string)-1; $i++) {
    if(in_array($string[$i], $numbers)){
       $keyword = 'includes';
       break;
    }
}

A: Better way is using regular expression
<?php
    if (preg_match('#[0-9]#',$string)){
        $message_keyword = 'includes';
    }
    else{
        $message_keyword = 'desn\'t include';
    }
?>

A: This is because of PHP loose type comparison, you are comparing string with integer, so PHP internally will cast this string to integer, and all character in your string will be casted to 0.
First step to fix your code, will be to create an array of strings instead of integers:
$numbers = array_map(function($n){ return (string)$n; }, range(0,9));
for ($i = 0; $i <= strlen($string)-1; $i++) {
    $char = $string[$i];
    $message_keyword = in_array($char,$numbers)?'includes' : 'doesn\'t include';
}

This will fix your case, but will not work as you expect it to, since $message_keyword is overwritten on each loop, so will receive message for last character only. If you are aiming to only check if string contains number, you can stop checking after encountering first number:
$message_keyword = 'doesn\'t include';
for ($i = 0; $i <= strlen($string)-1; $i++) {
    $char = $string[$i];
    if(in_array($char, $numbers)) {
        $message_keyword = 'includes';
        break; //found, no need to check next
    }
}

To have this all logic in more compact form, use regular expresion, as posted by others before.

A: It's kinda late to answer this question after about 9 years, but If you want to detect integers (and not floats) nothing is better than ctype_digit. Using this function to detect floats with decimal point or other types would results in returning false.
<?php
$number = "123";
$notNumber = "123abc";
var_dump(ctype_digit($number));
var_dump(ctype_digit($notNumber));
?>

Output
bool(true)
bool(false)

A: You can just use regexp :
$message_keyword = preg_match('/\d/', $string) ? 'includes' : 'desn\'t include';

A: array range ( mixed $start , mixed $end [, number $step = 1 ] )

If a step value is given, it will be used as the increment between elements in the sequence. step should be given as a positive number. If not specified, step will default to 1.
In your case, you havent mentioned the third parameter that is why it is always set to 1
See Manual here


text:
Q: How can we prepare "valid JSON" from Linkedin Share API Recently, from our log, we saw this:
httpRes status received 400 Bad Request for this linkedinToken AQUz3sCODu312rHNtNfuns3awy0xoUxxxxxxxxxxx.
 With Request: {"content":{"submitted-url":"http://mpg.smh.re/2Ra","title":"Gestionnaire sinistre H/F − Belgique ","description":"Responsable de la gestion de dossiers sinistres dans leur intégralité,
 vous serez en contact avec de nombreux interlocuteurs (compagnies
d'assurances, clients et bureaux locaux).","submitted-image-url":"http://www.morganphilipsexecutivesearch.com/wp-content/uploads/2014/09/fyte-smarpshare.jpg"},"visibility":{"code":"anyone"},"comment":"FYTE, cabinet de recrutement spécialisé recrute pour l'un de ses clients situé en Belgique un Gestionnaire sinistre H/F."}.
 Response body: {
  "errorCode": 0,
  "message": "Couldn't parse Json body: Illegal unquoted character ((CTRL-CHAR, code 10)): has to be escaped using backslash to be included in string value\n at [Source: java.io.StringReader@42ea5bc1; line: 1, column: 187]",
  "requestId": "0GYQWP14U9",
  "status": 400,
  "timestamp": 1423490252325
}

```
LinkedIn API said that it couldn't parse JSON body. Our doubt is that either character "é" or "'" is not handled by JAVA JSON parser.
My question is that is there any other special/unicode characters that we should be aware of? Because this JSON body was marshaled by Go's built-in.
UPDATE: I recently discovered that "line feed" ("CTRL-CHAR, code 10") is the key to this issue. "Line feed" character appears after "...leur intégralité,". My question now is that why doesn't Go built-in JSON marshaller handle that

A: JSON can cope with Unicode characters ... provided that they are properly encoded.
However the error message says:
Illegal unquoted character ((CTRL-CHAR, code 10))

which seems to be saying that you have a control character in the JSON.  The JSON syntax states that unescaped control characters are not permitted in strings.
Now if we assume that 10 is decimal, then it is a newline character.  So I would look for a raw newline within the JSON about 187 characters from the start.

My question now is that why doesn't Go built-in JSON marshaller handle that.

Two possibilities:

*

*it is a bug, or

*you are not using it correctly.

redpajama_set_name: RedPajamaStackExchange


text:
Q: D3: Stacked Bar Chart not parsing data correctly Trying to create a stacked bar chart and I'm having trouble understanding how to parse and correctly bind the JSON data.
Getting errors of NaN when trying to draw the  parts of the chart.
Error: Invalid value for <rect> attribute y="NaN"
Error: Invalid value for <rect> attribute height="NaN"
I'm not very experienced in pulling data from an JS object, or using D3, and putting it in a properly organized array, so that may be where my problem is.
I'm currently using some dummy data to get it working, but ultimately I need a chart that can take an unknown amount of data and stack each 'product', organized by date. I also, was having issues understanding if I should be using d3.net() and using either d.product_name or d.date as my key.
Full fiddle, JS is in Coffeescript
http://jsfiddle.net/toombsday/2hebo511/
window.barGraph = ->
  dataset = [
    {
      "date": "2014-08",
      "amount": 216,
      "product_name": 'Annuity 1'
    },
    {
      "date": "2014-08",
      "amount": 116,
      "product_name": 'Annuity 2'
    },
    {
      "date": "2014-09",
      "amount": 206,
      "product_name": 'Annuity 1'
    },
    {
      "date": "2014-09",
      "amount": 186,
      "product_name": 'Annuity 2'
    },
    {
      "date": "2014-10",
      "amount": 216,
      "product_name": 'Annuity 1'
    },
    {
      "date": "2014-10",
      "amount": 116,
      "product_name": 'Annuity 2'
    },
    {
      "date": "2014-11",
      "amount": 216,
      "product_name": 'Annuity 1'
    },
    {
      "date": "2014-11",
      "amount": 206,
      "product_name": 'Annuity 2'
    },
    {
      "date": "2014-12",
      "amount": 176,
      "product_name": 'Annuity 1'
    },
    {
      "date": "2014-12",
      "amount": 216,
      "product_name": 'Annuity 2'
    }
  ]

  margin = {top: 20, right: 30, bottom: 20, left: 30}
  width = 540 - margin.left - margin.right
  height = 320 - margin.top - margin.bottom

  barGraph = d3.select('.reloaded-chart')
   .attr("width", width + margin.left + margin.right)
   .attr("height", height + margin.top + margin.bottom)
   .append('g')
    .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')

  stack = d3.layout.stack()
    .values((d) -> d.values)
    .x((d) -> d.date)
    .y((d) -> d.amount)

  nest = d3.nest()
    .key((d) -> return d.product_name)

  nested  = nest.entries(dataset)
  layers = stack(nested)

  x = d3.scale.ordinal()
    .rangeRoundBands([0, width], 0.1)
    .domain(dataset.map( (d) -> d.date))

  y = d3.scale.linear()
    .range([height, 0])
    .domain([0, d3.max(dataset, (d) -> +d.y0 + +d.y)])

  xAxis = d3.svg.axis()
    .scale(x)
    .orient('bottom')

  yAxis = d3.svg.axis()
    .scale(y)
    .orient('left')
    .ticks(10)

  barGraph.append('g')
    .attr('class', 'x axis')
    .attr('transform', 'translate(0,' + height + ')')
    .call(xAxis)

  barGraph.append('g')
    .attr('class', 'y axis')
    .call(yAxis)
    .append('text')

  barGraph.selectAll('.bar')
    .data(layers)
    .enter().append('rect')
    .attr('class', 'bar')
    .attr('x', (d) -> x(d.x))
    .attr('y', (d) -> y(d.y0) - y(d.y))
    .attr('height', (d) -> height - y(d.y))
    .attr('width', x.rangeBand())

$ ->
  barGraph()

Thanks for the help!

A: I have created the stack bar chart based on your dataset.
plnkr
var nest = d3.nest()
.key(function(d) { return d.date; })
.entries(data);

Too many places need to be modified, you can check it out yourself.
Hope it helps!


text:
Q: Save RAM by forcing a program to use page file I was running game servers and when they have no players running, I wanted to put the servers' memory into the page file to save RAM.
I do know that Windows puts memory that wasn't accessed recently into the page file, however the jobs done with 0 players by these game servers do not have high urgency.
As far as jobs that the game servers need to do even with 0 players, I'm willing to test that myself and see if running it in the page file will cause a problem, so I don't need to be told if it's a bad idea unless it absolutely won't be reasonable.

A: The operating system will do a far better job than you can at managing its page file, and if your process is idle and the physical memory is in use, it will already be paged out.  There isn't normally any need to control this process manually.
However, if your process is going to sleep and you want to tell Windows to put your process's memory on ice as soon as possible, you can adjust its working set size using SetProcessWorkingSetSize.


text:
Q: Figura Modernista con CSS 'Estoy tratando de hacer un forma concreta en css para no tener que usar imágenes y nose si va ser posible hacerla.. Llevo un rato con ello y no hay manera.
¿Alguien puede ayudarme?

Este es el código que más se acercó...

body{
 background-color: white;
 font-size:16px;

}
.container{

 width: 100%;
 height: 4em;
 background-color: #ccc;
}

.container div:nth-child(1){
 margin:0;
 display:inline-block;
 width:15%;
 height: 3.5em;
 background-color: green;
 border-bottom-right-radius: 50% 10px;

}

.container div:nth-child(2){
 margin:0;
 display:inline-block;
 width:70%;
 height: 3.5em;
 background-color: yellow;
 border-bottom-left-radius: 40% 50%;
 border-bottom-right-radius: 40% 50%;
}

.container div:nth-child(3){
 margin:0;
 display:inline-block;
 width:15%;
 height: 3.5em;
 background-color: red;
 border-bottom-left-radius: 40% 40%;
}
<!DOCTYPE html>

 <meta charset="UTF-8">
 <title>cunt</title>
 <link rel="stylesheet" href="prueba.css">

A: Lo más fácil sería utilizar SVG:

*{margin:0;padding:0}
<svg viewBox="0 0 659 80.184">
<path fill="#ead4a2" d="M0,70c0,0,49-7,85-5s164,17,245,15s209-15.719,261-15.359s68,7.768,68,7.768V0H0V70z"/>
</svg>


text:
Q: can't figure out why my micronucleus/V-USB setup doesn't work I built a small attiny85-based board using vusb and essentially the schematic of the discontinued Sparkfun "AVR Stick" (at least on the usb/uC side; see https://www.sparkfun.com/datasheets/Widgets/AVR-Stick-v12.pdf).
Trying to run micronucleus , a V-USB based bootloader, on it, I used the following config changes from the included tiny85-default example (to accomodate for different pins):
#define USB_CFG_DMINUS_BIT      0
#define USB_CFG_DPLUS_BIT       2
#define USB_INTR_VECTOR         PCINT2_vect

as far as i (and the available documentation) can tell, this is the correct setup.
when I try to connect it to my PC via usb though, I get enumeration errors, and attaching a logic analyzer to its VCC (to trigger on plugging it in) and data lines, I see the following traffic:

*

*VCC high

*a few random broken packets as the uC spins up

*a loop of:

*

*SYNC PID_SETUP 0x00 0x00 CRC_OK EOP (handshake begin)

*SYNC DATA0 0x80 0x06 0x00 0x01 0x00 0x00 0x40 0x00 CRC_OK EOP (no clue)

*expecting either a SYNC ACK or SYNC NAK packet now, but nothing happens, except for

*a few evenly spaced (and very slow, compared to the previous packets) keepalives, until it retries this loop a few times (with a few resets+vcc cycles from my kernel trying to un-break the stuck device)

*the data lines going into idle state as my kernel gives up on it and decides to just deliver power

I attached a csv dump from my logic analyzer here.
If anyone has an idea what's going on here or how to fix it (or at least how to get more info on what's actually wrong), any help is greatly appreciated :)
EDIT: forgot to mention above, the logic analyzer is attached at the uC pins, not inline of the USB connection, so it's very likely a software problem since the electrical signals definitely reach the uC. a simple pin-toggling test program (with unchanged fuses) confirms the uC is running at the time.


text:
Q: Java 8 Identifiers/Keywords List I've been recently looking at the Java 8 Documentation and was surprised to see so many new identifiers (e.g. Consumer). Can someone please give me a list of these identifiers and what they mean? Thanks a bunch!

A: The documentation states that "50 character sequences, formed from ASCII letters, are reserved for use as keywords and cannot be used as identifiers."
The full list is:
abstract   continue   for          new         switch assert
default    if           package     synchronized boolean    do
goto         private     this break      double     implements
protected   throw byte       else       import       public
throws case       enum       instanceof   return      transient catch
extends    int          short       try char       final
interface    static      void class      finally    long
strictfp    volatile const      float      native       super
while

These do not include names of interfaces like Consumer, however.

A: Below is a compiled (potentially incomplete) list which includes some of the most common interfaces and their corresponding meanings. Hopefully this helps!

Takes no arguments: Called a Supplier
Takes a single int, double, or long argument: Called either

*

*IntXX

*LongXX

*DoubleXX
Takes two arguments: Called a BiXX
Takes two arguments of the same type: Called a binaryOperator
Takes two arguments of which the first is a reference type and the second is a primitive type: Called an ObjXXConsumer
Returns void: Called a Consumer
Returns an int, long, or double:
Called either

*

*XXToIntYY

*XXToLongYY

*XXToDoubleYY
Returns a boolean: Called a Predicate
Otherwise, it's simply called a Function

Please feel free to add more information to this answer or any identifiers that I missed.


text:
Q: How to create JSON Array in Bash I want to create JSON array for emr steps. I have created the array for single json string. Here is my bash code -
export source="s3a://sourcebucket"
export destination="s3a://destinationbucket"

EMR_DISTCP_STEPS=$( jq -n \
                  --arg source "$source" \
                  --arg destination "$destination" \
                  '{
                    "Name":"S3DistCp step",
                    "HadoopJarStep": {
                    "Args":["s3-dist-cp","--s3Endpoint=s3.amazonaws.com", "'"--src=${sourcepath}"'" ,"'"--dest=${destinationpath}"'"],
                    "Jar":"command-runner.jar"
                    },
                     "ActionOnFailure":"CONTINUE"
                   }' )

output
echo $EMR_DISTCP_STEPS

[{ "Name": "S3DistCp step", "HadoopJarStep": { "Args": [ "s3-dist-cp", "--s3Endpoint=s3.amazonaws.com", "--src=s3a://sourcebucket", "--dest=s3a://destinationbucket" ], "Jar": "command-runner.jar" }, "ActionOnFailure": "CONTINUE" }]

Now I want to create JSON array with multiple source and destination
output
[{ "Name": "S3DistCp step", "HadoopJarStep": { "Args": [ "s3-dist-cp", "--s3Endpoint=s3.amazonaws.com", "--src=s3a://sourcebucket1", "--dest=s3a://destinationbucket1" ], "Jar": "command-runner.jar" }, "ActionOnFailure": "CONTINUE" },
{ "Name": "S3DistCp step", "HadoopJarStep": { "Args": [ "s3-dist-cp", "--s3Endpoint=s3.amazonaws.com", "--src=s3a://sourcebucket2", "--dest=s3a://destinationbucket2" ], "Jar": "command-runner.jar" }, "ActionOnFailure": "CONTINUE" },
{ "Name": "S3DistCp step", "HadoopJarStep": { "Args": [ "s3-dist-cp", "--s3Endpoint=s3.amazonaws.com", "--src=s3a://sourcebucket3", "--dest=s3a://destinationbucket3" ], "Jar": "command-runner.jar" }, "ActionOnFailure": "CONTINUE" }]

How to generate JSON Array with multiple sources and destinations (JSON string) in Bash?

A: One way to do this is to provide a jq function that generates your repeated structure, given the specific inputs you want to modify. Consider the following:
# generate this however you want to -- hardcoded, built by a loop, whatever.
source_dest_pairs=(
  sourcebucket1:destinationbucket1
  sourcebucket2:destinationbucket2
  sourcebucket3:destinationbucket3
)

# -R accepts plain text, not JSON, as input; -n doesn't read any input automatically
# ...but instead lets "inputs" or "input" be used later in your jq code.
jq -Rn '
  def instructionsForPair($source; $dest): {
    "Name":"S3DistCp step",
    "HadoopJarStep": {
      "Args":[
        "s3-dist-cp",
        "--s3Endpoint=s3.amazonaws.com",
        "--src=\($source)",
        "--dest=\($dest)"
      ],
      "Jar":"command-runner.jar"
    }
  };

  [ inputs
  | capture("^(?<source>[^:]+):(?<dest>.*)$"; "")
  | select(.)
  | instructionsForPair(.source; .dest) ]
' < <(printf '%s\n' "${source_dest_pairs[@]}")

...correctly emits as output:
[
  {
    "Name": "S3DistCp step",
    "HadoopJarStep": {
      "Args": [
        "s3-dist-cp",
        "--s3Endpoint=s3.amazonaws.com",
        "--src=sourcebucket1",
        "--dest=destinationbucket1"
      ],
      "Jar": "command-runner.jar"
    }
  },
  {
    "Name": "S3DistCp step",
    "HadoopJarStep": {
      "Args": [
        "s3-dist-cp",
        "--s3Endpoint=s3.amazonaws.com",
        "--src=sourcebucket2",
        "--dest=destinationbucket2"
      ],
      "Jar": "command-runner.jar"
    }
  },
  {
    "Name": "S3DistCp step",
    "HadoopJarStep": {
      "Args": [
        "s3-dist-cp",
        "--s3Endpoint=s3.amazonaws.com",
        "--src=sourcebucket3",
        "--dest=destinationbucket3"
      ],
      "Jar": "command-runner.jar"
    }
  }
]


text:
Q: C# thread-safe getter performance differences I am writting a thread safe object that basically represents a double and uses a lock to ensure safe reading and writing. I use many of these objects (20-30) in a piece of code that is reading and writing them all 100 times per second, and I am measuring the average computation time of each of these time steps. I started looking at a few options for implementations of my getter and after running many tests and collecting many samples to average out my measurement of computation time I find certain implementations perform consistently better than others, but not the implementations I would expect.
Implementation 1) Computation time average = 0.607ms:
protected override double GetValue()
{
    lock(_sync)
    {
        return _value;
    }
}

Implementation 2) Computation time average = 0.615ms:
protected override double GetValue()
{
    double result;
    lock(_sync)
    {
        result = _value;
    }
    return result;
}

Implementation 3) Computation time average = 0.560ms:
protected override double GetValue()
{
    double result = 0;
    lock(_sync)
    {
        result = _value;
    }
    return result;
}

What I expected: I had expected to see implementation 3 be the worst of the 3 (this was actually my original code, so it was chance or lazy coding that I had written it this way), but surprisingly it is consistently the best in terms of performance. I would expect implementation 1 to be the fastest. I also expected implementation 2 to be at least as fast, if not faster than implementation 3 since I am just removing an assignment to the double result that is overwritten anyways, so it is unnecessary.
My question is: can anyone explain why these 3 implementations have the relative performance that I have measured? It seems counter-intuitive to me and I would really like to know why.
I realize that these differences are not major, but their relative measure is consistent every time I run the test, collecting thousands of samples each test to average out the computation time. Also, please keep in mind I am doing these tests because my application requires very high performance, or at least as good as I can reasonably get it. My test case is just a small test case and a my code's performance will be important when running in release.
EDIT: note that I am using MonoTouch and running the code on an iPad Mini device, so perhaps it's nothing related to c# and more something related to MonoTouch's cross compiler.

A: Measuring only reads for concurrency is misleading, your cache will give you orders of magnitude better results than real use case would. So I added SetValue to Marc's example:
using System;
using System.Diagnostics;
using System.Threading;

abstract class Experiment
{
    public abstract double GetValue();
    public abstract void SetValue(double value);
}

class Example1 : Experiment
{
    private readonly object _sync = new object();
    private double _value = 3;
    public override double GetValue()
    {
        lock (_sync)
        {
            return _value;
        }
    }

    public override void SetValue(double value)
    {
        lock (_sync)
        {
            _value = value;
        }

    }

}
class Example2 : Experiment
{
    private readonly object _sync = new object();
    private double _value = 3;
    public override double GetValue()
    {
        lock (_sync)
        {
            return _value;
        }
    }

    public override void SetValue(double value)
    {
        lock (_sync)
        {
            _value = value;
        }
    }

}

class Example3 : Experiment
{
    private readonly object _sync = new object();
    private double _value = 3;
    public override double GetValue()
    {
        double result = 0;
        lock (_sync)
        {
            result = _value;
        }
        return result;
    }

    public override void SetValue(double value)
    {
        lock (_sync)
        {
            _value = value;
        }
    }
}

class CompareExchange : Experiment
{
    private double _value = 3;
    public override double GetValue()
    {
        return Interlocked.CompareExchange(ref _value, 0, 0);
    }

    public override void SetValue(double value)
    {
        Interlocked.Exchange(ref _value, value);
    }
}
class ReadUnsafe : Experiment
{
    private long _value = DoubleToInt64(3);
    static unsafe long DoubleToInt64(double val)
    {   // I'm mainly including this for the field initializer
        // in real use this would be manually inlined
        return *(long*)(&val);
    }
    public override unsafe double GetValue()
    {
        long val = Interlocked.Read(ref _value);
        return *(double*)(&val);
    }

    public override void SetValue(double value)
    {
        long intValue = DoubleToInt64(value);
        Interlocked.Exchange(ref _value, intValue);
    }
}
class UntypedBox : Experiment
{
    // references are always atomic
    private volatile object _value = 3.0;
    public override double GetValue()
    {
        return (double)_value;
    }

    public override void SetValue(double value)
    {
        object valueObject = value;
        _value = valueObject;
    }
}
class TypedBox : Experiment
{
    private sealed class Box
    {
        public readonly double Value;
        public Box(double value) { Value = value; }

    }
    // references are always atomic
    private volatile Box _value = new Box(3);
    public override double GetValue()
    {
        Box value = _value;
        return value.Value;
    }

    public override void SetValue(double value)
    {
        Box boxValue = new Box(value);
        _value = boxValue;
    }
}
static class Program
{
    static void Main()
    {
        // once for JIT
        RunExperiments(1);
        // three times for real
        RunExperiments(5000000);
        RunExperiments(5000000);
        RunExperiments(5000000);
    }
    static void RunExperiments(int loop)
    {
        Console.WriteLine("x{0}", loop);
        RunExperiment(new Example1(), loop);
        RunExperiment(new Example2(), loop);
        RunExperiment(new Example3(), loop);
        RunExperiment(new CompareExchange(), loop);
        RunExperiment(new ReadUnsafe(), loop);
        RunExperiment(new UntypedBox(), loop);
        RunExperiment(new TypedBox(), loop);
        Console.WriteLine();
    }
    static void RunExperiment(Experiment test, int loop)
    {
        // avoid any GC interruptions
        GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
        GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
        GC.WaitForPendingFinalizers();

        int threads = Environment.ProcessorCount;

        ManualResetEvent done = new ManualResetEvent(false);

        // Since we use threads, divide the original workload
        //
        int workerLoop = Math.Max(1, loop / Environment.ProcessorCount);
        int writeRatio = 1000;
        int writes = Math.Max(workerLoop / writeRatio, 1);
        int reads = workerLoop / writes;

        var watch = Stopwatch.StartNew();

        for (int t = 0; t < Environment.ProcessorCount; ++t)
        {
            ThreadPool.QueueUserWorkItem((state) =>
                {
                    try
                    {
                        double val = 0;

                        // Two loops to avoid comparison for % in the inner loop
                        //
                        for (int j = 0; j < writes; ++j)
                        {
                            test.SetValue(j);
                            for (int i = 0; i < reads; i++)
                            {
                                val = test.GetValue();
                            }
                        }
                    }
                    finally
                    {
                        if (0 == Interlocked.Decrement(ref threads))
                        {
                            done.Set();
                        }
                    }
                });
        }
        done.WaitOne();
        watch.Stop();
        Console.WriteLine("{0}\t{1}ms", test.GetType().Name,
            watch.ElapsedMilliseconds);

    }
}

Results are, at 1000:1 read:write ratio:
x5000000
Example1        353ms
Example2        395ms
Example3        369ms
CompareExchange 150ms
ReadUnsafe      161ms
UntypedBox      11ms
TypedBox        9ms

100:1 (read:write)
x5000000
Example1        356ms
Example2        360ms
Example3        356ms
CompareExchange 161ms
ReadUnsafe      172ms
UntypedBox      14ms
TypedBox        13ms

10:1 (read:write)
x5000000
Example1        383ms
Example2        394ms
Example3        414ms
CompareExchange 169ms
ReadUnsafe      176ms
UntypedBox      41ms
TypedBox        43ms

2:1 (read:write)
x5000000
Example1        550ms
Example2        581ms
Example3        560ms
CompareExchange 257ms
ReadUnsafe      292ms
UntypedBox      101ms
TypedBox        122ms

1:1 (read:write)
x5000000
Example1        718ms
Example2        745ms
Example3        730ms
CompareExchange 381ms
ReadUnsafe      376ms
UntypedBox      161ms
TypedBox        200ms

*Updated the code to remove the unnecessary ICX operations on write, since the value is overwritten always. Also fixed the formula to compute the number of reads to divide by threads (same work).

A: Frankly, there are other, better approaches here. The following outputs (ignoring the x1, which is for JIT):
x5000000
Example1        128ms
Example2        136ms
Example3        129ms
CompareExchange 53ms
ReadUnsafe      54ms
UntypedBox      23ms
TypedBox        12ms

x5000000
Example1        129ms
Example2        129ms
Example3        129ms
CompareExchange 52ms
ReadUnsafe      53ms
UntypedBox      23ms
TypedBox        12ms

x5000000
Example1        129ms
Example2        161ms
Example3        129ms
CompareExchange 52ms
ReadUnsafe      53ms
UntypedBox      23ms
TypedBox        12ms

All of these are thread safe implementations. As you can see, the fastest is a typed box, followed by an untyped (object) box. Next comes (at about the same speed) Interlocked.CompareExchange / Interlocked.Read - note that the latter only supports long, so we need to do some bit-bashing to treat that as a double.
Obviously, test on your target framework.
For fun, I also tested a Mutex; on the same scale test, that takes about 3300ms.
using System;
using System.Diagnostics;
using System.Threading;
abstract class Experiment
{
    public abstract double GetValue();
}
class Example1 : Experiment
{
    private readonly object _sync = new object();
    private double _value = 3;
    public override double GetValue()
    {
        lock (_sync)
        {
            return _value;
        }
    }
}
class Example2 : Experiment
{
    private readonly object _sync = new object();
    private double _value = 3;
    public override double GetValue()
    {
        lock (_sync)
        {
            return _value;
        }
    }
}

class Example3 : Experiment
{
    private readonly object _sync = new object();
    private double _value = 3;
    public override double GetValue()
    {
        double result = 0;
        lock (_sync)
        {
            result = _value;
        }
        return result;
    }
}

class CompareExchange : Experiment
{
    private double _value = 3;
    public override double GetValue()
    {
        return Interlocked.CompareExchange(ref _value, 0, 0);
    }
}
class ReadUnsafe : Experiment
{
    private long _value = DoubleToInt64(3);
    static unsafe long DoubleToInt64(double val)
    {   // I'm mainly including this for the field initializer
        // in real use this would be manually inlined
        return *(long*)(&val);
    }
    public override unsafe double GetValue()
    {
        long val = Interlocked.Read(ref _value);
        return *(double*)(&val);
    }
}
class UntypedBox : Experiment
{
    // references are always atomic
    private volatile object _value = 3.0;
    public override double GetValue()
    {
        return (double)_value;
    }
}
class TypedBox : Experiment
{
    private sealed class Box
    {
        public readonly double Value;
        public Box(double value) { Value = value; }

    }
    // references are always atomic
    private volatile Box _value = new Box(3);
    public override double GetValue()
    {
        return _value.Value;
    }
}
static class Program
{
    static void Main()
    {
        // once for JIT
        RunExperiments(1);
        // three times for real
        RunExperiments(5000000);
        RunExperiments(5000000);
        RunExperiments(5000000);
    }
    static void RunExperiments(int loop)
    {
        Console.WriteLine("x{0}", loop);
        RunExperiment(new Example1(), loop);
        RunExperiment(new Example2(), loop);
        RunExperiment(new Example3(), loop);
        RunExperiment(new CompareExchange(), loop);
        RunExperiment(new ReadUnsafe(), loop);
        RunExperiment(new UntypedBox(), loop);
        RunExperiment(new TypedBox(), loop);
        Console.WriteLine();
    }
    static void RunExperiment(Experiment test, int loop)
    {
        // avoid any GC interruptions
        GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
        GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
        GC.WaitForPendingFinalizers();

        double val = 0;
        var watch = Stopwatch.StartNew();
        for (int i = 0; i < loop; i++)
            val = test.GetValue();
        watch.Stop();
        if (val != 3.0) Console.WriteLine("FAIL!");
        Console.WriteLine("{0}\t{1}ms", test.GetType().Name,
            watch.ElapsedMilliseconds);

    }

}


text:
Q: Post a Form to a PHP File using XMLHTTPRequest/AJAX I am a bit forgetful of PHP, is there a simpler way to post a form using JavaScript AJAX, don't want to add jQuery simply to post an ajax request, without having to pass the parameters?
I want to post the form via Ajax and not have to get the parameters  and send them in the call, is this possible? Is there an alternative to the following code...
var mypostrequest=new ajaxRequest()
mypostrequest.onreadystatechange=function(){
 if (mypostrequest.readyState==4){
  if (mypostrequest.status==200 || window.location.href.indexOf("http")==-1){
   document.getElementById("result").innerHTML=mypostrequest.responseText
  }
  else{
   alert("An error has occured making the request")
  }
 }
}
var namevalue=encodeURIComponent(document.getElementById("name").value)
var agevalue=encodeURIComponent(document.getElementById("age").value)
var parameters="name="+namevalue+"&age="+agevalue
mypostrequest.open("POST", "basicform.php", true)
mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
**mypostrequest.send(parameters)**

It is my intent to use POST instead of GET to hide what is being sent on the URL, this feels strange and it's the same as using a GET. Or am I reading this wrong?

A: Just don't use jQuery if you only want some plain simple Ajax.
This will do the job just fine:
// Vanilla
var httpRequest = new XMLHttpRequest()
httpRequest.onreadystatechange = function (data) {
  // code
}
httpRequest.open('GET', url)
httpRequest.send()

All kudos go to: https://gist.github.com/liamcurry/2597326

Now we could also add some more browser support (IE6 and older: http://caniuse.com/#search=XMLHttpRequest) @ all those jQuery heads: jQuery 2 dropped support for IE8 and older so no 'extra support' there.
// creates an XMLHttpRequest instance
function createXMLHttpRequestObject()
{
  // xmlHttp will store the reference to the XMLHttpRequest object
  var xmlHttp;
  // try to instantiate the native XMLHttpRequest object
  try
  {
    // create an XMLHttpRequest object
    xmlHttp = new XMLHttpRequest();
  }
  catch(e)
  {
    // assume IE6 or older
    try
    {
      xmlHttp = new ActiveXObject("Microsoft.XMLHttp");
    }
    catch(e) { }
  }
  // return the created object or display an error message
  if (!xmlHttp)
    alert("Error creating the XMLHttpRequest object.");
  else
    return xmlHttp;
}

All kudos go to: http://www.cristiandarie.ro/asp-ajax/Async.html
This post was sponsored by Google (a really powerfull tool, you type in stuff and it gives more stuff with answers)


text:
Q: Android Firebase - how to get child node data I have node of "genresComments" that saves comments of each user to for each video id. It goes like that Genre -> video ID -> user ID:Data.
What im trying to get is all the user's id and their data (The data i mean:comment,profilePicture,username).
thats the query that should point to that data
      Query query = FirebaseDatabase.getInstance().getReference(Params.GENRESCOMMENTS).child(genre).child(videoID);

But i'm sure that it points only on the "users id" and not bringing me the inside data that i need.
My question is how do i get for each "video id" all his "user id" and his data (comment,profilePicture,username).
EDIT
     @Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    videoID = getArguments().getString(Params.VIDEOID);
    genre = getArguments().getString(Params.GENRE);

    progressBar.setVisibility(View.VISIBLE);

    if(videoID != null){
        Query query = FirebaseDatabase.getInstance().getReference(Params.GENRESCOMMENTS).child(genre).child(videoID);
        options = new FirebaseRecyclerOptions.Builder<Comment>().setQuery(query,Comment.class).build();
        adapter = new FirebaseRecyclerAdapter<Comment,CommentsViewHolder>(options) {
            @Override
            protected void onBindViewHolder(CommentsViewHolder holder, int position, Comment model) {
                    holder.userName.setText(model.getUserName());
                    holder.comment.setText(model.getComment());
                    Glide.with(getContext()).load(model.getUserProfile()).into(holder.userProfile);
            }

            @Override
            public  CommentsViewHolder  onCreateViewHolder(ViewGroup parent, int viewType) {
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.comment_item,parent,false);
                return new CommentsViewHolder(view) ;
            }
        };

    }
    if(adapter != null) {
        rvComments.setAdapter(adapter);
        rvComments.setLayoutManager(new LinearLayoutManager(getContext()));
    }

}

I use this query for recycler view

A: Do like below code (it may get errors): learn about event listener first
FirebaseDatabase.getInstance().getReference(Params.GENRESCOMMENTS).child(genre).child(videoID).addValueEventListener(new ValueEventListener(Datasnapshot snap){

  for(DataSnapshot s:snap.getChildren()){
         Comment c=s.getValue(Comment.class);
         //c.getPRofilePic  c.getComment();
    }
});

class Comment {
private String comment;
private String profilePic;
private String username;

//getter setter

}


text:
Q: How does the golang cgo linker work on macos? On some systems, the project https://github.com/nilleb/fsevents-watcher
produces a fsevents_watcher.so linked to the HomeBrew python. While on other systems it is linked to the system Python.
Which environment variables/configuration elements influence the cgo linker on MacOSX?
I am asking this question for a user who has the homebrew python as the first in his $PATH, but obtains a .so linked against the system python.


text:
Q: Get all posts, regardless of status I'm using the Sola Testimonial plug-in and there is a function that gets a count of all published posts.
$my_query = new WP_Query('post_type=testimonials&posts_per_page=-1&status=publish');

$count = $my_query->post_count;

return intval( $count );

This function only returns posts that have a second parameter set to "Approved" ("Pending Approval" is the other option). I want to get a count of all "testimonial" posts, no matter what this parameter is.
I've tried
$count = $my_query->found_posts;

and
status=any

and
$my_query = new WP_Query('post_type=testimonials&posts_per_page=-1&post_status=any');

but it will only count posts that have the parameter set to Approved.
Any idea how to get a count of all "testimonial" posts, regardless of status?
Thank you!
Here's how the Approval Status appears in the edit bar (it's separate from Publish):

A: You should write your request like this ("post_status" instead of "status"):
$my_query = new WP_Query('post_type=testimonials&posts_per_page=-1&post_status=any');

All available post_statuses are:
Default value is 'publish', but if the user is logged in, 'private' is added.
Public custom statuses are also included by default. And if the query is run in an admin context (administration area or AJAX call), protected statuses are added too. By default protected statuses are 'future', 'draft' and 'pending'.

*

*'publish' - a published post or page. 'pending' - post is pending review.

*'draft' - a post in draft status.

*'auto-draft' - a newly created post, with no content.

*'future' - a post to publish in the future.

*'private' - not visible to users who are not logged in.

*'inherit' - a revision.

*'trash' - post is in trashbin (available since Version 2.9).

*'any' - retrieves any status
except those from post statuses with 'exclude_from_search' set to
true (i.e. trash and auto-draft).

You can specify several statuses in one request:
$query = new WP_Query( array(
    array( 'post_status' => array( 'pending', 'draft', 'future' ) )
) );


text:
Q: How would I run a batch file remotely over sccm in interactive cmd (micro right click tools) On SCCM you can right click --> Micro right click tools and interactive command prompt this uses PS exec to open a remote cmd session on the selected PC.
From this if a run a .bat file form a server share it comes back as access denied,
However the runas command e.g.
runas /Administrator cmd.exe /c "\\svr-sccm\ad$\!!! User cleanup batchfiles\Delete all user no input.bat"

Runs with no errors but doesn't seem to actually do anything  (the bat file calls delprof2 to clean user profiles off of the C drive and registry)
Any suggestions on how I would be able to run the bat file remotely on a PC when a Non-admin user is logged in (without remote controlling)
Any suggestions would be appreciated.

A: Access Denied most likely signals you, that the user, which runs the command, does not have access to the share, that you are trying to access.
If your command really spins up a commandline with psexec, it will run in SYSTEM context, i.e. the computer on which you run the script, must have access to the file share.


text:
Q: Request to add inline code and monospace font The title says it all. Could StackOverflow have the ability to insert "inlined code", as well as change the format of code blocks to be the browser's default monospace font?

A: You can already insert in-lined code using backticks, like <this>.  Do you mean you want syntax highlighting on it?  If so, I disagree.  That would be remarkably distracting.

A: This is a test of inlined code.
You see, x + (y + z) == (x + y) + z
(Use ``, if you want syntax highlighting, use a code block.)

A: They will not use browser-default monospace font because Webkit-based browsers treat them differently than all the other browsers.
[related uservoice request]


text:
Q: How to migrate SearchSite in Django-Haystack from 1.X to 2.X? So I've been reading the migration docs and I'm stuck at

• The removal of SearchSite & haystack.site. • The removal of
  handle_registrations & autodiscover. • The addition of multiple
  index support. • The addition of SignalProcessors & the removal of
  RealTimeSearchIndex. • The removal/renaming of various
  settings.

because, "Removal of RealTimeSearchIndex" is described, however what to do in place of autodiscover and SearchSite I can't find in there. Does anyone know where to look/what to do? I'm stuck with how to migrate SearchSite primarily.

A: I have to migrated in some sites and I allways followed this steps:
Remember to save your Index or Indexes using a backup, snapshot or any other way

*

*Uninstall ElasticSearch

*Uninstall default-jre-headless (In case you have it installed, it's good to update java)

*Uninstall pyelasticsearch and django-haystack

*Install openjdk-7-jre-headless

*Install new elasticsearch (I use 1.3.4).

*Install with pip django-haystack==2.3.0, pyelasticsearch==0.7.1 and elasticsearch==1.2.0
Usually I had openjdk-6-jre-headless installed and I update it to openjdk-7-jre-headless
With this 6 steps I updated many projects to Haystack 2.3.0
You can try with other software versions, I've used these and works fine

A: See my caveats in your other question...
I'm not sure if there's an easy autodiscover replacement to save typing. You may have to just list out all your search index classes and their fields of interest instead of letting haystack slurp up all your models.
The migration doc says that indexes.Indexable is a little mixin class you'll need to add/inherit. It should basically just flag the class as something haystack should care about. This should basically take the place of explicitly calling register on your models. You'll also need to have a get_model method on your search index classes -- I believe this ties them to whatever django model you are messing with. The index_queryset method doesn't seem mandatory based on the docs (http://django-haystack.readthedocs.org/en/latest/searchindex_api.html#index-queryset) but may be of interest depending on what the "whole" set of data means to you when you reindex things. HTH.


text:
Q: How to read a single character from a com port thank you for looking over my question. I'm trying to read from a COM port. I have a launchpad microcontroller and I've already made it so I can send single character codes to it and have the microcontroller respond accordingly. Here's the application as it is currently:
Current Application
I can currently make pins go high and low to my hearts content. However, I would like to a Read pin value from the controller. I made a subroutine that opens up the com port and sends the character that causes the a pin to go high or low.
The code on the microcontroller is setup so that if it gets the 'T' character it sends a single character back immediately. How do I retrieve this single character from the com port?
I'm new to vb.net, so be gentle. The code is below for reference. I open and close the com port to send data using the sendCom() function. I would like to have a readCom() function that would grb my character if possible.
Thanks for looking over my dilemma.
~Triston
/------------------------------------ Code for reference ------------------------------------------------
Public Class Form1
Dim myBtn0 As Boolean
Dim myBtn1 As Boolean
Dim myBtn2 As Boolean
Dim myBtn3 As Boolean
Dim myBtn4 As Boolean
Dim myBtn5 As Boolean
Dim myBtn6 As Boolean
Dim myBtn7 As Boolean

Function sendCom(ByVal Data As Char)
    Dim myCom As System.IO.Ports.SerialPort
    myCom = My.Computer.Ports.OpenSerialPort("COM6", 9600, 0, 8)

    myCom.Write(Data)
    myCom.Close()
    myCom.Dispose()
End Function

Function pinFlip(ByVal pinNum As Integer, ByVal pState As Boolean) As Integer
    InfoBox.Clear()
    InfoBox.Multiline = True
    Select Case pinNum
        Case 0
            If pState Then
                InfoBox.AppendText("C" + Environment.NewLine)
                InfoBox.ScrollToCaret()
            Else
                InfoBox.AppendText("c" + Environment.NewLine)
                InfoBox.ScrollToCaret()
            End If
        Case 1
            If pState Then
                InfoBox.AppendText("D" + Environment.NewLine)
                InfoBox.ScrollToCaret()
            Else
                InfoBox.AppendText("d" + Environment.NewLine)
                InfoBox.ScrollToCaret()
            End If
        Case 2
            If pState Then
                InfoBox.AppendText("E" + Environment.NewLine)
                InfoBox.ScrollToCaret()
            Else
                InfoBox.AppendText("e" + Environment.NewLine)
                InfoBox.ScrollToCaret()
            End If
        Case 3
            If pState Then
                InfoBox.AppendText("F" + Environment.NewLine)
                InfoBox.ScrollToCaret()
            Else
                InfoBox.AppendText("f" + Environment.NewLine)
                InfoBox.ScrollToCaret()
            End If
        Case 4
            If pState Then
                InfoBox.AppendText("G" + Environment.NewLine)
                InfoBox.ScrollToCaret()
            Else
                InfoBox.AppendText("g" + Environment.NewLine)
                InfoBox.ScrollToCaret()
            End If
        Case 5
            If pState Then
                InfoBox.AppendText("H" + Environment.NewLine)
                InfoBox.ScrollToCaret()
            Else
                InfoBox.AppendText("h" + Environment.NewLine)
                InfoBox.ScrollToCaret()
            End If
        Case 6
            If pState Then
                InfoBox.AppendText("I" + Environment.NewLine)
                InfoBox.ScrollToCaret()
            Else
                InfoBox.AppendText("i" + Environment.NewLine)
                InfoBox.ScrollToCaret()
            End If
        Case 7
            If pState Then
                InfoBox.AppendText("J" + Environment.NewLine)
                InfoBox.ScrollToCaret()
            Else
                InfoBox.AppendText("j" + Environment.NewLine)
                InfoBox.ScrollToCaret()
            End If
    End Select

End Function
Private Sub GetPorts_Click(sender As Object, e As EventArgs) Handles GetPorts.Click
    ' Show all available COM ports.
    ListBox1.Items.Clear()
    For Each sp As String In My.Computer.Ports.SerialPortNames
        ListBox1.Items.Add(sp)
    Next
End Sub

Private Sub Send_Click(sender As Object, e As EventArgs) Handles Send.Click

    Dim Data As Char
    'Dim Com6 As System.IO.Ports.SerialPort
    'Com6 = My.Computer.Ports.OpenSerialPort("COM5", 9600, 0, 8)
    Data = "A"
    'Com6.Open()

    'System.Threading.Thread.Sleep(200)
    'Com6.Write(Data)
    'System.Threading.Thread.Sleep(200)
    'Com6.Close()
    'System.Threading.Thread.Sleep(200)
    'Com6.Dispose()
    sendCom(Data)
    P0.BackColor = Color.Green
    P1.BackColor = Color.Green
    P2.BackColor = Color.Green
    P3.BackColor = Color.Green
    P4.BackColor = Color.Green
    P5.BackColor = Color.Green
    P6.BackColor = Color.Green
    P7.BackColor = Color.Green

    myBtn0 = True
    myBtn1 = True
    myBtn2 = True
    myBtn3 = True
    myBtn4 = True
    myBtn5 = True
    myBtn6 = True
    myBtn7 = True

    InfoBox.Clear()
    InfoBox.Multiline = True
    InfoBox.AppendText("All Set High" + Environment.NewLine)
    InfoBox.ScrollToCaret()
End Sub

Private Sub SendB_Click(sender As Object, e As EventArgs) Handles SendB.Click
    Dim Data As Char
    'Dim Com6 As System.IO.Ports.SerialPort
    'Com6 = My.Computer.Ports.OpenSerialPort("COM5", 9600, 0, 8)
    'Com6.Open()
    Data = "B"
    ' Send strings to a serial port.
    'System.Threading.Thread.Sleep(200)
    'Com6.Write(Data)
    'System.Threading.Thread.Sleep(200)
    'Com6.Close()
    'System.Threading.Thread.Sleep(200)
    'Com6.Dispose()
    sendCom(Data)
    P0.BackColor = Color.Red
    P1.BackColor = Color.Red
    P2.BackColor = Color.Red
    P3.BackColor = Color.Red
    P4.BackColor = Color.Red
    P5.BackColor = Color.Red
    P6.BackColor = Color.Red
    P7.BackColor = Color.Red

    myBtn0 = False
    myBtn1 = False
    myBtn2 = False
    myBtn3 = False
    myBtn4 = False
    myBtn5 = False
    myBtn6 = False
    myBtn7 = False

    InfoBox.Clear()
    InfoBox.Multiline = True
    InfoBox.AppendText("All Set Low" + Environment.NewLine)
    InfoBox.ScrollToCaret()
End Sub
Private Sub myRead_Click(sender As Object, e As EventArgs) Handles myRead.Click
    InfoBox.Clear()
    InfoBox.Multiline = True
    InfoBox.AppendText("The READ!" + Environment.NewLine)
    InfoBox.ScrollToCaret()
End Sub
Private Sub PortInfo_Click(sender As Object, e As EventArgs) Handles PortInfo.Click
    Dim Com6 As System.IO.Ports.SerialPort
    Dim myData As String
    InfoBox.Clear()
    InfoBox.Multiline = True
    Com6 = My.Computer.Ports.OpenSerialPort("COM6", 9600, 0, 8)
    myData = "Port Name: " + CStr(Com6.PortName)
    InfoBox.AppendText(myData + Environment.NewLine)
    InfoBox.ScrollToCaret()
    myData = "BaudRate: " + CStr(Com6.BaudRate)
    InfoBox.AppendText(myData + Environment.NewLine)
    InfoBox.ScrollToCaret()
    myData = "Parity: " + CStr(Com6.Parity)
    InfoBox.AppendText(myData + Environment.NewLine)
    InfoBox.ScrollToCaret()
    myData = "Data Width: " + CStr(Com6.DataBits)
    InfoBox.AppendText(myData + Environment.NewLine)
    InfoBox.ScrollToCaret()
    myData = "Stop Bits: " + CStr(Com6.StopBits)
    InfoBox.AppendText(myData + Environment.NewLine)
    InfoBox.ScrollToCaret()
    Com6.Dispose()

End Sub

Private Sub Btn0_Click(sender As Object, e As EventArgs) Handles Btn0.Click
    Select Case myBtn0
        Case False
            P0.BackColor = Color.Green
            myBtn0 = True
            sendCom("C")
        Case True
            P0.BackColor = Color.Red
            myBtn0 = False
            sendCom("K")
    End Select

    pinFlip(0, myBtn0)
End Sub

Private Sub Btn1_Click(sender As Object, e As EventArgs) Handles Btn1.Click
    Select Case myBtn1
        Case False
            P1.BackColor = Color.Green
            myBtn1 = True
            sendCom("D")
        Case True
            P1.BackColor = Color.Red
            myBtn1 = False
            sendCom("L")
    End Select
    pinFlip(1, myBtn1)
End Sub

Private Sub Btn2_Click(sender As Object, e As EventArgs) Handles Btn2.Click
    Select Case myBtn2
        Case False
            P2.BackColor = Color.Green
            myBtn2 = True
            sendCom("E")
        Case True
            P2.BackColor = Color.Red
            myBtn2 = False
            sendCom("M")
    End Select
    pinFlip(2, myBtn2)
End Sub

Private Sub Btn3_Click(sender As Object, e As EventArgs) Handles Btn3.Click
    Select Case myBtn3
        Case False
            P3.BackColor = Color.Green
            myBtn3 = True
            sendCom("F")
        Case True
            P3.BackColor = Color.Red
            myBtn3 = False
            sendCom("N")
    End Select
    pinFlip(3, myBtn3)
End Sub

Private Sub Btn4_Click(sender As Object, e As EventArgs) Handles Btn4.Click
    Select Case myBtn4
        Case False
            P4.BackColor = Color.Green
            myBtn4 = True
            sendCom("G")
        Case True
            P4.BackColor = Color.Red
            myBtn4 = False
            sendCom("O")
    End Select
    pinFlip(4, myBtn4)
End Sub

Private Sub Btn5_Click(sender As Object, e As EventArgs) Handles Btn5.Click
    Select Case myBtn5
        Case False
            P5.BackColor = Color.Green
            myBtn5 = True
            sendCom("H")
        Case True
            P5.BackColor = Color.Red
            myBtn5 = False
            sendCom("P")
    End Select
    pinFlip(5, myBtn5)
End Sub

Private Sub Btn6_Click(sender As Object, e As EventArgs) Handles Btn6.Click
    Select Case myBtn6
        Case False
            P6.BackColor = Color.Green
            myBtn6 = True
            sendCom("I")
        Case True
            P6.BackColor = Color.Red
            myBtn6 = False
            sendCom("Q")
    End Select
    pinFlip(6, myBtn6)
End Sub

Private Sub Btn7_Click(sender As Object, e As EventArgs) Handles Btn7.Click
    Select Case myBtn7
        Case False
            P7.BackColor = Color.Green
            myBtn7 = True
            sendCom("J")
        Case True
            P7.BackColor = Color.Red
            myBtn7 = False
            sendCom("R")
    End Select
    pinFlip(7, myBtn7)
End Sub

End Class

A: Your function sendCom(ByVal Data As Char) opens the COM port, then sends data, then closes it, never keeping it open for receiving data. This is fine if you want to poll for received data and timeout if there is none. See the example here for the receive function that you need to add to your code.


text:
Q: Remove all instances of the same column value across multiple files using awk I'm back again with another awk question.
I have multiple large files that contain data i want to dedupe against each other.
Lets say I have the following data for one month:
fruit   number  rand
apple   12  342
taco    19  264
tortilla    2234    53423
tortillas   2   3431
apricot 13221   23424
apricots    24234   3252
pineapple   2342    2342
radish  1   3

The following month I receive this data:
fruit   number  rand
pineapple   2   698
apple   34  472
taco    19  234
tortilla    16  58
tortillas   87  25
potato  234 2342
radish  1   55
grapes  9   572 422
apricot 13221   24

What I am trying to do is take the second file, and check the values of the first column to see if there are items that exist in the first file. If yes, I want to remove them from the second file, leaving only items that are unique to the second file with relation to the first one.
The desired outcome would leave me something like this:
fruit   number  rand    DUPLICATE
pineapple   2   698     DUPE
apple   34  472         DUPE
taco    19  234         DUPE
tortilla    16  58      DUPE
tortillas   87  25      DUPE
potato  234 2342
radish  1   55          DUPE
grapes  9   572 422
apricot 13221   24      DUPE

Or, more clearly:
fruit   number  rand
potato  234 2342
grapes  9   572 422

I was trying to think of a way to do this without having to sort the files. I was trying to modify the answer from @karafka for a related question. Instead of passing the same file twice, I tried inputting the two different files. Obviously I'm doing something wrong.
awk 'BEGIN { FS = OFS = "      " }
    NR==FNR {a[$1]++; next}
    FNR==1  {print $0, "DUPLICATE"; next}
    $1 in a{if (a[$1]>1){print $(NF+1)="DUPE";delete a[$1]}}1' file{,}

I'm still learning awk, any help the community can provide is greatly appreciated, but I'll try to explain what I think the above program does.

*

*The first line sets the delimiter and the output delimiter to be a tab character.

*This line reads the first file and stores an array with a count of how many times an item appears in the list.

*This outputs the first line which is essentially the header, adding "DUPLICATE" at the end of the last item in the row

*(This is where I'm stuck) If the current value is found in the array "a" it should check if the stored value is greater than one. If yes, it should print the word "DUPE" in the last column. Finally it returns the entire line.

In the test files I keep getting everything marked as "DUPE" or nothing at all.
I've also thought of combining the files and deduping that way, but that would leave me with undesired left-over values from the first file.
What am I doing wrong?

A: I think what you're doing wrong is just trying to use a bunch of scripts that are unrelated to your current problem as your starting point.
It sounds like all you need is:
$ awk '
NR==FNR { file1[$1]; next }
FNR==1 || !($1 in file1)
' file1 file2
fruit   number  rand
potato  234 2342
grapes  9   572 422


text:
Q: SwiftUI: How can you make your app come to the front when clicking on the dock icon of the app? When a SwiftUI app is minimized and the dock icon is clicked. The app won't be deminimized and put to the front just like other apps do.
import SwiftUI

@main
struct MyApp: App {
    @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

    var body: some Scene {
        WindowGroup {
            MainView()
        }
    }
}

class AppDelegate: NSObject, NSApplicationDelegate {
    func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
        // THIS IS NEVER CALLED!!!
        if !flag {
            for window: AnyObject in sender.windows {
                window.makeKeyAndOrderFront(self)
            }
        }

        return true
    }
}

Other delegate methods like applicationDidLaunch do get called so its not a linking issue. Does anyone know how to get this to work?
Comment on Asperi

A: 2022
Will display app in case of it is hidden or minimized both!
func applicationDidBecomeActive(_ notification: Notification) {
    NSApp.unhide(self)

    if let wnd = NSApp.windows.first {
        wnd.makeKeyAndOrderFront(self)
        wnd.setIsVisible(true)
    }
}

A: Use did become active callback, tested as worked with Xcode 13.3 / macOS 12.2.1
Like,
func applicationDidBecomeActive(_ notification: Notification) {
    if NSApp.windows.compactMap({ $0.isVisible ? Optional(true) : nil }).isEmpty {
         NSApp.windows.first?.makeKeyAndOrderFront(self)
    }
}

Test module in project is here
Note: in case of active application the only application(Will/Did)Update are called in click Dock icon.

A: In delegate methods that get called when clicking on the dock icon try calling
NSApp.activate(ignoringOtherApps: true)

This should bring your app to the foreground

A: This is a temporary work around that works for me
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ notification: Notification) {
    // disable tabs ...
    NSWindow.allowsAutomaticWindowTabbing = false
}

// Quit if the main window is closed
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
    BzLogger[Self.self].info("")
    return true
}

func applicationDidUpdate(_ notification: Notification) {
    if NSApplication.shared.mainWindow == nil,
       let event = NSApplication.shared.currentEvent {
        if event.type == .systemDefined {
            // FIX-ME: kdeda
            // This is hack since Apple broke this whole thing on macOS

            // BzLogger[Self.self].info("NSApplication.shared.currentEvent: \(event)")
            // BzLogger[Self.self].info("NSApplication.shared.currentEvent: \(event.subtype)")
            // BzLogger[Self.self].info("NSApplication.shared.pressedMouseButtons: \(NSEvent.pressedMouseButtons)")
            // BzLogger[Self.self].info("NSApplication.shared.isActive: \(NSApplication.shared.isActive)")
            if NSEvent.pressedMouseButtons == 1 {
                // mouse down, maybe there is a better way
                if NSApp.windows.compactMap({ $0.isVisible ? Optional(true) : nil }).isEmpty {
                    NSApp.windows.first?.makeKeyAndOrderFront(self)
                }
            }
        }
    }
}

}

A: I found this solution.
In your @main entry class App add this property:
@NSApplicationDelegateAdaptor var appDelegate: AppDelegate

It now should looks like this:
import SwiftUI

@main
struct TestApp: App {
    @NSApplicationDelegateAdaptor var appDelegate: AppDelegate

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

Now, create the AppDelegate class (you can create a new separate AppDelegate.swift file or just continue typing after the App struct closed:
class AppDelegate: NSObject, NSApplicationDelegate {
    func applicationDidChangeOcclusionState(_ notification: Notification) {
        if let window = NSApp.windows.first, window.isMiniaturized {
            NSApp.hide(self)
        }
    }

    func applicationDidBecomeActive(_ notification: Notification) {
        NSApp.windows.first?.makeKeyAndOrderFront(self)
    }
}

Now it is minimizing, maximizing, closing and reopening again as normal as other apps (ex. Safari, Mail, etc.).
This works perfectly on Monterey 12.4.


text:
Q: php display and total pricing on same page I have been searching for a way to add up the total sum of radio buttons and echo it that total on the same page in php. Is there a way to do this? I have included an image of what I am looking at.
Here is code that I have come up with so far:
PHP
<?php
$prod1 = "10";
$prod2 = "20";
$prod3 = "30";
?>

<form action="">
<input type="radio" name="prod1" value="<?=$prod1?>">$10 product 1

<input type="radio" name="prod2" value="<?=$prod2?>">$20 product 2

<input type="radio" name="prod3" value="<?=$prod3?>">$30 product 3
</form>

<?php
echo ="$total"
?>

I am new so it will not post an image, here is a link to my image:

A: Working example
You need an element where the total is going to be, and a way of identifying those inputs. I've used input which isn't very specific; You may want to change this if you have more going on in that form.
I bound change to the form (which I gave the id products) because the change events made on the inputs will bubble up to the form, and we need to search the whole form for all the inputs so it made sense not to have to traverse, which we'd need to do if the function was bound to the input fields.
Then simply, on change of something in the form, add up the values of the checked elements. parseFloat() is used because the values are strings and you'd end up with "102030" where you really wanted "60".
HTML
<form action="" id="products">
    <input type="radio" name="prod1" value="10" />$10 product 1

    <input type="radio" name="prod2" value="20" />$20 product 2

    <input type="radio" name="prod3" value="30" />$30 product 3
</form>

Total $0

jQuery
$(function(){
    $('#products').on('change', function(){
        var total = 0;
        $(this).find('input:checked').each(function(){
            total += parseFloat($(this).val());
        });
        $('#total').text(total);
    });
});

By the way, if the user is supposed to be able to uncheck these options, you need to use <input type="checkbox" ...


text:
Q: How to execute a query within a loop in java I have tried the below code to store all the data of array list(table).But doesn't give any error or the required output.
public class Dbops {
    String url = "jdbc:mysql://localhost:3306/ITStuffDB";
    String username = "root";
    String password = "";
    ResultSet rs = null;

    public boolean addData(ArrayList<ArrayList<String>> table){

        try {
            System.out.println(table.size());
            for (int i = 0; i < table.size(); i++) {
                Connection con1 = (Connection) DriverManager.getConnection(url, username, password);
                String query = "INSERT INTO Data (Col1,Col2,Col3) VALUES (?,?,?)";
                PreparedStatement pst1 = (PreparedStatement) con1.prepareStatement(query);

                pst1.setString(1, table.get(i).get(0));
                pst1.setString(2, table.get(i).get(1));
                pst1.setString(3, table.get(i).get(2));
                pst1.executeUpdate();
                pst1.close();
                con1.close();
            }return true;

        } catch (Exception e) {
            return false;
        }
    }
}

How can i handle this correctly?

A: The comment is right, at least print the exception to know the problem.
Moreover, this is not a good idea to recreate the connexion and the statement each time. Have a look at the executeBatch() function
try {
    Connection con1 = (Connection) DriverManager.getConnection(url, username, password);
    String query = "INSERT INTO Data (Col1,Col2,Col3) VALUES (?,?,?)";
    PreparedStatement pst1 = (PreparedStatement) con1.prepareStatement(query);
    for (int i = 0; i < table.size(); i++) {
        pst1.clearParameters();
        pst1.setString(1, table.get(i).get(0));
        pst1.setString(2, table.get(i).get(1));
        pst1.setString(3, table.get(i).get(2));
        pst1.addBatch();
    }
    pst1.executeBatch();
    return true;
} catch (SQLException e) {
    return false;
} finally {
    //close everything
}

A: The first comment is totally right.
Debugging can also help you trace what is your program. You should try and debug this method.
Also, as a recommendation - the whole idea of a PreparedStatement is to compile it once and then reuse it whenever possible. I would move the creation of the statement outside of the loop.


text:
Q: Unable to update my bios (motherboard Gigabyte GA-8S648FX) I have a pc with the Gigabyte GA-8S648FX motherboard on and it has the F6 BIOS version and I am trying to update it to F8 version with no success :)
First I used the @Bios utility Gigabyte provides, but when the process starts and when I reach the part of deleting the current BIOS, my PC crashes with a blue screen and then my BIOS recovers.
Then I tried the QFlash utility in the BIOS but it only uses Floppy disks which I can't access cause I don't have a FDD ;)
Finally, I found the solution of FlashSpi.exe from a bootable usb stick which was the closest I got. I loaded the correct BIOS version in it, booted into the utility, flashed the BIOS and finished the process successfully. But when my pc restarted the BIOS was STILL the F6 version. I've repeated the process many times with no results. Why did the BIOS not change when the flashspi was telling that the update was successful?
p.s. I saw in the first screen the pc's have when they start, that it has my motherboards name and after that it has F8 ("GA-8S648FX F8")! Does this mean that the BIOS is changed? And if so, why is it still the same?
Edit: Well as it seems i did the update. I was just paying attention to the CPU-Z which showed me the original version but changed the version's date and has the updated BIOS date. ;)


text:
Q: The norm of Borel measures I was looking on at the Convolution page on wikipedia and saw that it stated that we can define the convolution of two Borel measures of bounded variation on $\mathbb{R}^d$, $\mu$ and $\nu$, to be
$$\int_{\mathbb{R}^d} f(x) d(\mu\ast \nu)(x) = \int_{\mathbb{R}^d} \int_{\mathbb{R}^d} f(x+y) d\mu(x) d\nu(y),$$
and that we have the result
$$||\mu \ast \nu || \leq ||\mu|| ||\nu||.$$
I'm not sure what the second statement means though. Is there a natural norm for the space of Borel measures with bounded variation?

A: DJC's answer is of course to the point. I'm adding a short sketch of a proof of the inequality $$\|\mu \ast \nu\| \leq \|\mu\| \,\|\nu\|$$ since you asked about it in a comment. In that comment you mentioned $\sigma$-finiteness.  Note that bounded variation implies that all measures involved are in fact finite.
One of the most convenient ways of writing the total variation norms is as
$$\|\mu\| = \sup_{|f| \leq 1}{\;\left|\int f\,d\mu\right|}$$
where it doesn't matter much what kinds of measurable functions $f$ you allow in the supremum (continuous; simple; Borel; smooth; compactly supported or not). I'll take Borel here.
Given this, the inequality is then clear: By Fubini we have for every Borel function $f$ with $|f|\leq 1$ that the function
$$y \longmapsto \left|\int f(x+y)\,d\mu(x)\right|$$
is Borel and bounded by $\|\mu\|$ hence the fact that $\|\nu\| = \| \,|\nu|\,\|$ gives
$$\left|\int f \, d(\mu \ast \nu) \right| = \left|\iint f(x+y)\,d\mu(x)\,d\nu(y)\right| \leq \int\left|\int f(x+y)\,d\mu(x)\right|\,d|\nu|(y) \leq \|\mu\| \,\|\nu\|.$$
The norm of $\|\mu \ast \nu\|$ is by definition the supremum over the left hand side over $|f| \leq 1$.

A: Yes.  Generally, $\| \mu\|$ is defined as
$$
\| \mu \| = |\mu|(\mathbb{R}^d),
$$
where $|\mu |$ is the total variation.


text:
Q: php/sql select all that expires within 48 hours I have a table with a field named creationdate, add 14 days to this value and you have the expiry date. (all in unix timestamps by the way, so 14 days would be creationtime + 1209600)
Now I need to construct a SELECT statement that will pick all rows from this table that are within 48 hours of this expiry date, but I don't know where to start.

A: How about this? You get all where now is between 12 days and 14 days of the creation date:
SELECT
  *
FROM
  my_table
WHERE
  UNIX_TIMESTAMP() BETWEEN (creationtime + 1036800) AND (creationtime + 1209600)


text:
Q: Java - KeyListener issues I am a little new to Java so, sorry if I'm doing something wrong. I want my program to say The W key has been pressed when I press the W button. I've been having a little bit of problems with this. Here is an outline of my code:

public class Main extends JFrame implements ActionListener, KeyListener {

    public void keyListener(){
        addKeyListener(this);
        setFocusable(true);
        setFocusTraversalKeysEnabled(false);
    }

    public void keyPressed(KeyEvent e) {
        int code = e.getKeyCode();
        if (code == KeyEvent.VK_W){
        System.out.println("W is pressed");
        }
    }

    @SuppressWarnings("null")
    public static void main(String[] args) throws InterruptedException {
    //Initial things like variables and JFrame setup (Like: JFrame frame = new JFrame("FrameDemo");)
        for(step = 0; step == step; step++ ){
            for(i = 0; i < constructor.length; i++){
            //Some code
            constructor[i].draw(g);
            }
        }
    }
}

The KeyListener doesn't respond whatsoever. I think this might be because of the loop but I honestly have no idea. Can anyone expain why this is happening and how I could fix it?

A: The thing is: just declaring a class to be a KeyListener ... doesn't magically create that connection that is required at runtime.
In other words: the idea of a Listener is that it is registered at some point; and only registered Listeners will be notified about events.
Therefore you only need to call
addKeyListener(this)

somewhere within your class; for example within your constructor.
Or more specifically: you created a method  keyListener() that would make that addKeyListener() call ... but: there is probably no call to keyListener() in your source code!
And just for the record: keyListener() isn't a good name for a method; you should better call it registerListeners() for example.


text:
Q: Capturing Cookies (req.headers.cookie) on homepage with Express on node I am doing a basic authentication example.   I have Node, Express, and Cookie.  I make and store a cookie once the user logs in.  Upon refreshing the page, I want to use the cookie to show that the user is still logged in on the response, and provide the information related to that user.
Server side:
// If I put the app.get('/'.....) up here I get the response, but not the page HTML/JS/CSS/etc...

// This uses the /app as the root directory
app.use(express.static(__dirname + '/app'));

// Here I get the page HTML/JS/CSS/etc but can't capture the cookie
app.get('/', function(req, res) {
  console.log('I want to get here');
  if(req.headers.cookie){
    // This parses the cookies into a usable array
    var incoming_cookies = cookie.parse(req.headers.cookie);
    Person.find({...})
      .then( function(results) {
        if (weDontFindSomeone) {
          console.log('user not found');
          res.status(400).send('user not found');
        } else {
          if (incoming_cookies.uname === loggedIn.uname) {
            console.log('Starting with a cookie logged in');
            res.status(200).send(results);
          } else {
            console.log('Some other problem with cookies');
            res.status(400).send('Some other problem with cookies');
          }
        }
      })
      .catch(function(error){
         res.status(400).send('some other error in starting, error: ' + error);
      });
  } else {
    res.status(200).send('Starting from scratch.');
  }
});

How do I capture the cookies on the request to the homepage and use that to determine what is served to the client?

*

*Do I put it in the JS on the client side?

*If you want to suggest another node module, PLEASE show a working example in a plkr, fiddle, web page example, or the like.  I do better studying working code, as it has taken me a bit long to get to this pont :)

Setting the cookie, also on the server side:
app.post('/api/login', function (req, res) {
  console.log('Getting a login request');
  if (weValidateTheCredentials) {
    Person.find({...})
      .then(function(personResults) {
        if (personResults.rowCount === 0) {
          res.status(400).send('user not found');
        } else {
          console.log('Logging in at \'/api/login\', and sending a cookie.');
          // 3 hours max age
          res.cookie('UID', req.body.uid, {maxAge: 10800000});
          res.cookie('uname', req.body.uname, {maxAge: 10800000});
          res.status(200).send(personResults);
        }
      })
      .catch(function(error){
          res.status(400).send('some other error in logging in, error: ' + error);
      });
  } else {
    res.status(400).send('login requires a uname and pwhash');
  }
});

A: The method with Cookie is a bit devious, you can use cookie-parser, It's made for express.
It is really simple, there is a example on the home page:
var express      = require('express')
var cookieParser = require('cookie-parser')

var app = express()
app.use(cookieParser())

app.get('/', function(req, res) {
  console.log("Cookies: ", req.cookies)
})

app.listen(8080)

// curl command that sends an HTTP request with two cookies
// curl http://127.0.0.1:8080 --cookie "Cho=Kim;Greet=Hello"

Or with your code:
var cookieParser = require('cookie-parser');

// Add cookie parser
app.use(cookieParser());

app.get('/', function(req, res) {
  console.log('I want to get here');
  if(req.cookies){
    Person.find({...})
      .then( function(results) {
        if (weDontFindSomeone) {
          console.log('user not found');
          res.status(400).send('user not found');
        } else {
          if (req.cookies.uname === loggedIn.uname) {
            console.log('Starting with a cookie logged in');
            res.status(200).send(results);
          } else {
            console.log('Some other problem with cookies');
            res.status(400).send('Some other problem with cookies');
          }
        }
      })
      .catch(function(error){
         res.status(400).send('some other error in starting, error: ' + error);
      });
  } else {
    res.status(200).send('Starting from scratch.');
  }
});

// This uses the /app as the root directory
app.use(express.static(__dirname + '/app'));

A: I was mixing the paradigm of what should be handled by the server and what should be handled by the client.
Using Jquery addon 'jquery-cookie-master', I can check the cookie on the request of the client side with if ($.cookie('attributeWanted')){...}


text:
Q: Unable to upload CDAP custom plugin in Datafusion I am trying to upload http-sink plugin from Datafusion upload button. I cloned the http-sink repository and I made few very minimal changes and packaged it as a JAR. Now when I try to upload the JAR and the JSON files using upload plugin button, I am getting the following error:

'artifact:default.http-plugins.1.3.0-SNAPSHOT' was not found

Can anyone help me on how to overcome this error?

A: Currently Data Fusion that based purely on CDAP platfrom, represents a variety of the desired features, extending the basic functionality within a particular plugins.
When you need to explore your plugin and use it in a dedicated pipeline or stream source, plugin essentially needs to be deployed to the parent cdap-data-pipeline or cdap-data-streams artifacts respectively.
Basically Artifact is as packaged file produced by some software development process, which contains application related properties and dependencies, furthermore it should contain unique identifiers like groupId, artifactId, version.
Looking at the issue you've reported, I would recommend to start research from the first build phase, compiling code and packaging it to JAR and JSON files. The main sensitive contributor here is pom.xml file, as it contains the significant information about the project and configuration details used by Maven to build the project, knowing also as POM.
A few things that can be checked:

*

*What was a custom configuration applied to the origin http-plugin
source code, and whether you consider any changes caused to the
native code by reflecting them to pom.xml file;

*Check if the correct repository is specified in the pom.xml from
which the package was downloaded originally;

*How did you compile the source code in Maven, i.e: mvn clean
install or mvn clean package?;

*Check Maven compilation output, seeking for any suspicious outputs.

I did a quick test, cloning HTTP sink plugin repo and following the implementation steps in the guide section; I built JAR and JSON files and was able to successfully deploy http-plugins 1.3.0-SNAPSHOT in my Data Fusion instance.


text:
Q: Cleaning Pandas datadframes to return strings only I have a dataframe that is almost fully processed, but I still have some data as follows:
None
None
[None]
[ Testy McTesterSon]
[["None"]]
[ 1234567]

All lists are single elements. At this point, I want my dataframe to return only strings. If None then just return the string "None". All data will be written to a CSV. I've tried some lambda functions and to use the apply() function with little success on this last part.
All guidance appreciated.

A: Convert values to strings by Series.astype and then use Series.str.strip for remove trailing values:
df['col'] = df['col'].astype(str).str.strip('[ ]"')
print (df)
                 col
0               None
1               None
2               None
3  Test yMcTesterSon
4               None
5            1234567


text:
Q: C++ check from where specified function/method was called Is it possible to somehow check from where specified function was called? e.g. get address responsible for calling it, or if I want to check if this function is called from "File.exe" or "Other.dll"? Thanks in advance.
EDIT: I want to do it in my code(without any debugger..)

A: If you can set a breakpoint you can examine the call stack.

A: My first question would have to be: Why would you want to do this?
Having said that, there is absolutely no portable way to do this.  With GCC, and Clang to the best of my knowledge, you can use __builtin_return_address(0), but with Visual Studio (which I presume you are using, given exe/dll), I can't offer up any equivalent.
Normally if you are doing this, you need to look at your design, as there should be no reason to get the calling address unless you are writing, say, a trampoline function.

A: As chmeee said, there is no portable method for doing this.  On Windows, there are a set of debugging functions (which you can use in your code) to accomplish it (in a way):  http://msdn.microsoft.com/en-us/library/windows/desktop/ms679303(v=vs.85).aspx

A: If it's your code, pass the caller's name as one of the parameters to the function.
Otherwise, there's no portable way to do this. And even the non-portable ways are not necessarily going to work exactly as you expect. Introspection is not C++'s thing.

A: If you are on Windows, you probably could use functions provided in dbghelp library. I think you could use the StackWalkEx.
You can find an example on CodeProject. It says:

The usage of the class is very simple. For example if you want to
  display the callstack of the current thread, just instantiate a
  StackWalk object and call the ShowCallstack member:

#include <windows.h>
#include "StackWalker.h"

void Func5() { StackWalker sw; sw.ShowCallstack(); }
void Func4() { Func5(); }
void Func3() { Func4(); }
void Func2() { Func3(); }
void Func1() { Func2(); }

int main()
{
  Func1();
  return 0;
}

A: I generally throw a fake exception. It has worked in Java. (and C++ in my past years).
Like
try {
    throw(new Exception());
}
catch(Exception e) {
    e.printStackTrace();
}

The only other programmatic way I know of is to use Aspects (AOP).


text:
Q: A system of equations of Vietnamese Mathematical Olympiad 2013 This is a system of equation of Vietnamese Mathematical Olympiad 2013, the first day. Solve the system of equations
$$\begin{cases}
\sqrt{\sin^2 x + \dfrac{1}{\sin^2 x}} + \sqrt{\cos^2 y + \dfrac{1}{\cos^2 y}} = \sqrt{\dfrac{20y}{x+y}},\\
\sqrt{\sin^2 y + \dfrac{1}{\sin^2 y}} + \sqrt{\cos^2 x + \dfrac{1}{\cos^2 x}} = \sqrt{\dfrac{20x}{x+y}}.
\end{cases}$$


text:
Q: Python NetworkX find a subgraph in a Directed Graph from a node as root I am writing a code to extract information from a directed graph. This graph has cycles as well. For example,
A->B->C->D
A->E->F->A
B->F->G

From this graph, I want to create a sub graph or the list of the nodes, where the input would be any node, and output would be the graph where the input node is the root, or the list of the nodes that has all the child nodes ( till the end of the graph ) from the input nodes
For example, in the above example,
1. If the input node is C, the output would be D
2. If the input node is B, the output node would be C,D,F,G,A ( Since there is a cycle, which makes A to B bidirectional )
3. If the input is G, the output is blank or null.
Is there any functionality in python networkx, that I can use to solve this problem ?
Alternatively, is there any other tool that can help me solve this problem ?

A: What you want is the function dfs_preorder_nodes(). Here is a little demo based on your data:
import networkx as nx

g = nx.DiGraph()

g.add_edge('A', 'B')
g.add_edge('B', 'C')
g.add_edge('C', 'D')

g.add_edge('A', 'E')
g.add_edge('E', 'F')
g.add_edge('F', 'A')

g.add_edge('B', 'F')
g.add_edge('F', 'G')

print('A:', list(nx.dfs_preorder_nodes(g, 'A')))
print('B:', list(nx.dfs_preorder_nodes(g, 'B')))
print('G:', list(nx.dfs_preorder_nodes(g, 'G')))

Output:
A: ['A', 'B', 'C', 'D', 'F', 'G', 'E']
B: ['B', 'C', 'D', 'F', 'A', 'E', 'G']
G: ['G']

The output includes the starting node. Therefore, if you don't want it, just remove the first element from the list.
Note that dfs_preorder_nodes() returns a generator object. That is why I called list() to get usable output.

A: nx.ego_graph() does exactly what you describe. Using the example given by @Hai Vu:
g = nx.DiGraph()

g.add_edge('A', 'B')
g.add_edge('B', 'C')
g.add_edge('C', 'D')
g.add_edge('A', 'E')
g.add_edge('E', 'F')
g.add_edge('F', 'A')
g.add_edge('B', 'F')
g.add_edge('F', 'G')

a = nx.ego_graph(g, 'A', radius=100)
a.node
#out: NodeView(('A', 'B', 'C', 'D', 'E', 'F', 'G'))

list(nx.ego_graph(g, 'G', radius=100).node)
#out: ['G']

radius should be an arbitrarily large number if you would like to get all nodes in the tree until the leafs.


text:
Q: How does java.util.Arrays.asList(T...) work? It seems to be a silly question at the first sight, but I found that the mechanism isn't trivial. The implementation from JDK 8 (copied from here) is just a few lines:
@SafeVarargs
@SuppressWarnings("varargs")
public static <T> List<T> asList(T... a) {
    return new ArrayList<>(a);
}

The point is that there are only 3 constructors in ArrayList:

*

*one doesn't take any parameter

*one takes an int (the initial capacity)

*one takes a Collection (the elements) as shown below (copied from here):

public class ArrayList<E> extends AbstractList<E>
    implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{

    // ...

    transient Object[] elementData; // non-private to simplify nested class access

    private int size;

    // ...

    public ArrayList(Collection<? extends E> c) {
        elementData = c.toArray();
        size = elementData.length;
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, size, Object[].class);

    }

    // ...

}

Since the only possibility is that the 3rd constructor is called, it seems that the parameter a (the generic vararg) is somehow "casted" to a Collection. But as far as I know, varargs are nothing more than arrays with a shorter syntax, and are not convertible to Collections (so that's why this made me puzzled)...
Does anybody know how the magic works?
Thank you!

A: The ArrayList type that's described here is not java.util.ArrayList; it's a private type defined inside that file (see line 3799). That one does have an array constructor, and it's the one referenced by Arrays.asList.
Hope this helps!

A: Arrays.asList(...) returns a new ArrayList. Here's the tricky part. The new ArrayList is not the one in the java.util package, it is actually a static inner class in Arrays class. Check this code.
Arrays.java
public static <T> List<T> asList(T... a) {
return new ArrayList<T>(a);
}
// the static inner class is shown below.
private static class ArrayList<E> extends AbstractList<E>
implements RandomAccess, java.io.Serializable
{
private static final long serialVersionUID = -2764017481108945198L;
private final E[] a;

ArrayList(E[] array) {
        if (array==null)
            throw new NullPointerException();
    a = array;
}

...
   }

A: You're looking at the wrong ArrayList class. The one used in Arrays.asList(..) is java.util.Arrays.ArrayList and has a constructor that accepts an array.


text:
Q: How to mock specific lines in a function? I would like to write test for my function but dont want to execute the certain statement s inside it .I am trying to mocking but failing .Any suggestion will be helpful.I am using pytest-mock for mocking.
def listDataSetZOWE():
"""To list out all datasets in system"""
try:

    process = Popen([zowe_path, 'zos-files','list','data-set','XYZ*'], stdout=PIPE, stderr=PIPE, universal_newlines=True)
    stdout, stderr = process.communicate()
    print(stdout)
    process.kill()

except Exception as e:
    print(e)
    stderr=e

return stderr

I dont want below two lines get excuted while testing
 process = Popen([zowe_path, 'zos-files','list','data-set','XYZ*'], stdout=PIPE, stderr=PIPE, universal_newlines=True)
    stdout, stderr = process.communicate()

My test:
def test_listDataSetZOWE(mocker):
    mocker.patch("process = Popen([zowe_path, 'zos-files','list','data-set','MACK00*'], stdout=PIPE, stderr=PIPE, universal_newlines=True)","datasetobj")
    mocker.patch("stdout, stderr = process.communicate()","stderr")
    zowe.listDataSetZOWE()

Its failing with below error:
 TypeError: Need a valid target to patch. You supplied: "process = Popen([zowe_path, 'zos-files','list','data-set','MACK00*'], stdout=PIPE, stderr=PIPE, universal_newlines=True)"


text:
Q: .NetStandard and Xamarin.Forms Android compatibility According to the .NET implementation support page:
.NetStandard 1.x only supports Xamarin.Android 7 and above
.NetStandard 2 only supports Xamarin.Android 8 and above
So I have avoided upgrading my pcls to .netstandard assuming I couldn't support Android 5.1+.
However in a recent test, I have converted an entire Android app i.e Xamarin.Forms PCL to .NetStandard 2 class library and it works flawlessly on every platform (in both emulator and physical devices from Android 5.1+ upwards).
This has been confusing to say the least. Is it the case that something may break, or some features may not work or will i have some compatibility issue I'm unaware of? Or am I not understanding the .NET implementation support page and associated concepts correctly?

A: You can read in-depth explanation on Xamarin official webpage:

As the Android platform evolves and new Android versions are released,
  each Android version is assigned a unique integer identifier, called
  the API Level. Therefore, each Android version corresponds to a single
  Android API Level. Because users install apps on older as well as the
  most recent versions of Android, real-world Android apps must be
  designed to work with multiple Android API levels.
Each release of Android goes by multiple names:

*

*The Android version, such as Android 7.1

*A code name, such as Nougat A

*corresponding API level, such as API level 25

  An Android code name may
  correspond to multiple versions and API levels (as seen in the list
  below), but each Android version corresponds to exactly one API level.
In addition, Xamarin.Android defines build version codes that map to
  the currently known Android API levels. The following list can help
  you translate between API level, Android version, code name, and
  Xamarin.Android build version code.
API 26 (Android 8.0) – Oreo, released August 2017.
API 25 (Android 7.1) – Nougat, released
  December 2016.
.....


text:
Q: Erlang: get ip address from hostname In my local network exists pcs, where have a hostname as example "testhost". How can I from given hostname get a IP-address ?
I tried:
net_adm:dns_hostname("testhost.fritz.box").

Result:
{ok,"testhost.fritz.box"}

I need a function which give me IP-Address from hostname.
Thx

A: According to http://erlang.org/doc/man/inet.html#getaddr-2 it seems you should be able to use getaddr like:
inet:getaddr("testhost.fritz.box", inet)


text:
Q: Android shared preferences retrieve username and password Im having trouble with retrieving username and password from android's sharedpreferences. I use this code to save the username and pass
SharedPreferences prefs=getSharedPreferences("File", 0);
    SharedPreferences.Editor e=  prefs.edit();
       e.putString("Email", "example@example.com").putString("Password", "password1");
       e.commit();
       e.putString("Email", "example_2@example.com").putString("Password", "password2");
       e.commit();
       String s=prefs.getString("Email","not found");

But i dont know how to retrieve information for user to log in. Can anybody help me figure out

A: Create Share Preference:
SharedPreferences sp=getSharedPreferences("Login", 0);
SharedPreferences.Editor Ed=sp.edit();
Ed.putString("Unm",Value );
Ed.putString("Psw",Value);
Ed.commit();

Get Value from Share preference:
SharedPreferences sp1=this.getSharedPreferences("Login",null);

String unm=sp1.getString("Unm", null);
String pass = sp1.getString("Psw", null);

A: You need to give different keys for different values, otherwise the second email will erase the first one. See shared preferences as a persistent hashmap :
   //keep constants, don't use their values. A constant has more meaning
   SharedPreferences prefs=getSharedPreferences("File", MODE_PRIVATE );
   SharedPreferences.Editor e=  prefs.edit();
   //keys should be constants as well, or derived from a constant prefix in a loop.
   e.putString("Email1", "example@example.com").putString("Password1", "password1");
   e.putString("Email2", "example_2@example.com").putString("Password2", "password2");
   //commit once, not twice
   e.commit();

   //not found should be a constant in a xml resource file
   String mail1=prefs.getString("Email1","not found");
   String mail2=prefs.getString("Email2","not found");


text:
Q: Change structure of an array of arrays I have the following array of arrays:
[
  [
     {
        a: "AA",
        b: "BB"
     },
     {
        a: "AA",
        c: "CC"
     },
     {
        a: "AA",
        d: "DD"
     },
     {
        a: "AA",
        e: "EE"
     }
  ],
  [
     {
        a: "AA_2",
        b: "BB_2"
     },
     {
        a: "AA_2",
        c: "CC_2"
     },
     {
        a: "AA_2",
        d: "DD_2"
     },
     {
        a: "AA_2",
        e: "EE_2"
     }
  ]
]

So it's an array containing two arrays of length 4.
I want to transform it to obtain the following format:
[
  {
   b: "BB", c: "CC", d: "DD", e: "EE"
  },
  {
   b: "BB_2", c: "CC_2", d: "DD_2", e: "EE_2"
  }
]

I want the final array to contain two objects.
Thank you!

A: You didn't make it clear what do you really want to filter from the subject array, so I just assume you want to exclude the primary key value with key "a".
var a = subject;
var out = ['a'];
var r = [];
for(var i in a){
 var ai = a[i];
 var o = {};
 for(var ii in ai){
   var aii = ai[ii];
   for(var k in aii){
     if(out.indexOf(k) == -1) o[k] = aii[k];
   }
 }
 r.push(o);
}
console.log(r);


text:
Q: AJAX: How to use TWO xmlHttpRequest in parallel in ONE function? How should I do this?
function(id,id2){

    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
         xmlhttp=new XMLHttpRequest();
    } else { // code for IE6, IE5
         xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

First Request:
   xmlhttp.open("GET", "http://example.com/ajax.php?id="+id, true);

   xmlhttp.send();

Second Request:
   xmlhttp.open("GET", "http://example.com/ajax2.php?id2="+id2, true);

   xmlhttp.send();

}

Because in this way doesn't works.
I want to make it in plain javascript, so please do not post answers with jQuery or any library etc.
Thanks

A: It should work if you create a new xmlhttp object. Currently you are attempting to reuse the same object, which is already performing a query so it will not work.

A: if you are looking for classic javascript style you can use as the following. But use jQuery as it's simple and comprehensive. The one thing to be noted is that the "xmlhr" should be in method (callAjax) scope.
function callAjax(url) {
        var xmlhr;

        if (window.XMLHttpRequest) {
            xmlhr = new XMLHttpRequest();
        } else {
            xmlhr = new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlhr.onreadystatechange = function () {
            if (xmlhr.readyState == 4 && xmlhr.status == 200) {
                alert(xmlhr.responseText);
            }
        }
        xmlhr.open("GET", url, true);
        xmlhr.send();
    }

    function myFunction(id1, id2) {
        callAjax("http://example.com/ajax2.php?id2=" + id1);
        callAjax("http://example.com/ajax2.php?id2=" + id2);
    }