text:
Q: How to serialize on .NET and deserialize on WP, Win8, iOS and Android and preserve references TL;DR;
Is there a library or protocol that allows me to serialize some data from a .NET app and deserialize on WP, Win8, iOS and Android while preserving references between objects as they were in code i.e. if a single instance X is a member of Y and Z when Y and Z are deserialized there should be only one X object.
Detailed version:
I want to be able to serialize some objects of types A and B where A has a member of type B and one instance of B can be a member of many instances of A. I should be able to deserialize on WP, Win8, iOS and Android and the same relations should be kept when the data is deserialized. Sadly I cannot test on Android and iOS right now.
The requirements for the serialization mechanism

*

*Preserve object references when deserializing

*The overhead of the serialization is not really important because the device will get new data like once in three months

*while the overhead is not important it is important that references to the same object are not serialized more once because this can result in very large serialized data.

*be able to serialize with .NET. Serializing on other platforms is not required.

*be able to deserialize on WP, Win8, iOS, Android

[DataContract(IsReference = true)]
public class A
{
    [DataMember]
    public string Name { get; set; }
    [DataMember]
    public B MemberB { get; set; }
}

[DataContract(IsReference = true)]
public class B
{
    [DataMember]
    public string Name { get; set; }
}

Example object graph:

var b1 = new B { Name = "B1" };
var aa = new List { new A { MemberB = b1, Name = "A1" }, new A { MemberB = b1, Name = "A2" } };

I have tried using DataContract Serialization and adding IsReference = true to the DataContract attribute. This works like a charm between desktop .NET and WP and I assume it will work on Windows 8 but I could not even find a way to deserialize DataContractSerialization on iOS and Android without writing my own deserializer let alone out of the box support for preserving references. DataContract serialization will be perfect for me if there is a library that provides deserialization on iOS and Android without additional effort.
I also experimented with an OData service. OData has client libraries for iOS and Android but does it work as expected. It seems like if there is a PK on the entity references will be preserved. I tested on WP and .NET console app like this:
DemoService service = new DemoService(new Uri("http://services.odata.org/OData/OData.svc/"));
var productsQuery = (DataServiceQuery<Product>)
                    (from p in service.Products.Expand("Category")
                     where p.Category.ID == 1
                     select p);

productsQuery.BeginExecute(
    (result) =>
        {
            var actualProducts = productsQuery.EndExecute(result).ToList();
            System.Diagnostics.Debug.WriteLine(actualProducts[2].Category == actualProducts[4].Category); //outputs true because both categories are the same
        },
    null);

It seems it works but am I doing the testing right and does it work like this with iOS and Android clients? I would like to avoid OData because it seems too heavy for my case.
I realize I can give each object an ID and only use the IDs to model the object graph but I am hoping for a cleaner solution. I also want to avoid writing my own serialization code.
Subquestions:

*

*Is there a way to deserialize DataContract Serialization on iOS and Android without writing my own deserializer

*Does the OData clients for iOS and Android preserve object references? Are they easy to work with

*Do Mono for iOS and Mono for Android suppord DataContract deserialization while preserving object references?

Thanks for your time.

A: I would use  protocol buffers from google. There are other implementations for other languages including Objective C and C#.
Update:
If I was doing this I would start by using .NET everywhere including on Android (by using MonoDroid) and (MonoTouch on iOS). Yes you can now share C# code across any your platforms!
Each of my objects that I wished to serialize would have an equivalent object defined as a Protocol-Buffer object. Each object would have a serialized hash-value as it's ID. Each Reference in the object would be defined as a hash-value.
You then have some code in each objects to walk the objects below it, serializing to the protocol buffer object as you go. Populating the hash-value references.
Each object reference gets look-up and stored in a dictionary (hash-value/address) of objects if it's not present. This is also serialized. This stops you serializing  objects twice as the object is only serialised/deserialised once across the whole operation. This is done by setting/clearing the address of the object in the dictionary.
I've written this stuff before it isn't a big deal.


text:
Q: How to add an IDirectSound to an IFilterGraph2? I've been Googling/StackOverflowing for days and can't figure this out.
I have a WPF project where I want to play videos on multiple screens simultaneously with separate audio systems. For playing video, we're using WPFMediaKit, which relies on DirectShow Lib .NET. For other systems, we'd like to use something a little more modern, such as the Core Audio API via NAudio. We control the environment and only have to support Windows 7 (may migrate to 8 in the future).
WPFMediaKit's MediaUriElement allows you to set its AudioRenderer but it exhibits issues because of the 31 character limit imposed by... DirectSound? I'm not entirely sure where the limitation comes from but it's a problem because all of our audio devices have very similar names (which most likely won't be unique within the space of 31 characters). So, the plan is to modify the source and allow it to take in a GUID representing a DirectSound device and change its behavior to look it up by that. The code that'll present the audio device endpoint list to the user will rely on NAudio's MMDeviceEnumerator from the Core Audio API.
I've gotten this far:
private static void DemonstrateTheIssue() {
    SpeechSynthesizer speech = new SpeechSynthesizer();
    MemoryStream stream = new MemoryStream();
    SpeechAudioFormatInfo synthFormat = new SpeechAudioFormatInfo(EncodingFormat.Pcm, 88200, 16, 1, 16000, 2, null);
    speech.SetOutputToAudioStream(stream, synthFormat);
    speech.Speak("This is a test. This is only a test.");
    stream.Position = 0;
    RawSourceWaveStream reader = new RawSourceWaveStream(stream, new WaveFormat());

    MMDeviceEnumerator coreAudioDeviceEnumerator = new MMDeviceEnumerator();
    MMDeviceCollection coreAudioAudioEndPoints = coreAudioDeviceEnumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active);
    MMDevice coreAudioSpdif = coreAudioAudioEndPoints.First(ep => ep.FriendlyName.Contains("S/PDIF")); // just an example. In the real application, would be selected by user and the GUID would be stored instead of the FriendlyName
    string spdifGuidValue = coreAudioSpdif.Properties[PropertyKeys.PKEY_AudioEndpoint_GUID].Value as string;
    Guid spdifGuid = Guid.Parse(spdifGuidValue);

    DirectSoundOut directSoundSpdif = new DirectSoundOut(spdifGuid);
    directSoundSpdif.Init(reader);
    directSoundSpdif.Play();
}

This code works. When I inspect NAudio's source of DirectSoundOut, I can see it calls DirectSoundOut.DirectSoundCreate from dsound.dll, which initializes an IDirectSound instance. I'm not entirely sure what I can do with that instance. So, going back to the other side of this puzzle...
Let's look at what WPFMediaKit does when I give it an AudioRenderer of "Digital Audio (S/PDIF) (High De". Digging through the source, I eventually came across AddFilterByName(IGraphBuilder graphBuilder, Guid deviceCategory, string friendlyName) which eventually calls AddFilterByDevice(IGraphBuilder graphBuilder, DsDevice device). Okay, so this uses its own wrapper class, DsDevice... which wraps IMoniker and a few other things, including some properties from an IPropertyBag attached to the IMoniker instance. The last line of C# code I see before my trail vanishes into COM calls this: filterGraph.AddSourceFilterForMoniker(device.Mon, null, device.Name, out filter). filterGraph is an IFilterGraph2 instance and device.Name returns "FriendlyName" from the moniker's property bag.
I feel like I'm close but I just can't connect the dots. How can I take an IDirectSound instance and tell the filterGraph to play audio on it? Do I need to get a moniker for the IDirectSound? If so, how? Is there another method I'm unaware of? Or... can I create/compose/get a reference to my own filter and tell the filterGraph about it? If so, how would I go about doing that?
Please answer this question like I'm a child -- this stuff is really over my head.

A: DirectSound and DirectShow are two different APIs. There is no direct adding of DirectSound objects into DirectShow filter graphs and hence your inability to do impossible.
There are two ways to address the problem: you either insist that you already hold an IDirectSound interface pointer and you want to use it within DirectShow. In this case you have to implement a custom audio renderer filter, which will be backed by this DirectSound interface and your renderer will forward all audio to the device of your interest. You don't really want to go this way. In particular, you won't be able to implement this in C# only.
And the second way is to find an existing DirectShow audio renderer, which is using the device of your interest. Then use it and it will play through the same DirectSound device, just not exactly the pointer you had on your hands in first place.
More details on the second approach. DirectShow has a special category where all audio renderers are listed: CLSID_AudioRendererCategory. Enumerating filters there, you enumerate instances of DirectSound Renderer Filter created for every existing device.

This filter acts as a wrapper for an audio device. To enumerate the
  audio devices available on the user's system, use the ICreateDevEnum
  interface with the audio renderer category
  (CLSID_AudioRendererCategory). For each audio device, the audio
  renderer category contains two filter instances. One of these
  corresponds to the DirectSound Renderer, and the other corresponds to
  the Audio Renderer (WaveOut) filter. The DirectSound instance has the
  friendly name "DirectSound: DeviceName," where DeviceName is the name
  of the device. The WaveOut instance has the friendly name DeviceName.

You can find the right device there, and you then you can use this filter as a regular audio renderer (that is, you add it to your graph, you connect it there). The filter does not however expose IDirectSound pointer it is using internally.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is TFS 2015 Agent still looking for Deleted Workspace? I deleted some workspaces used by my vNext Build Agents because I was getting the error that the folder was already in use. This was happening with a lot of my folders. Now my build agent is looking for the folder I deleted. The actual error message is

"The workspace ws_c0007cd6_11;Project Build Service does not exist."

I was able to circumvent this problem once by recreating the workspace. I don't want to do this for every missing workspace, and it doesn't seem to always work anyway. Is there a way I can get my Build Agents to stop looking for old work spaces and start creating new ones?

A: We hit the same problems but the only other option we found to work was to delete the agent and reconfigure.  Sorry.


text:
Q: Trying to pass Steam auth: stumped with RSA ecnryption (js to python) I'm trying to pass steam auth here. The place i'm stumped is an RSA password encryption using public key. Parameters to encode could be received from here. The code i'm using to encrypt the password is:
import base64
from Crypto.PublicKey import RSA
mod = long(publickey_mod, 16)
exp = long(publickey_exp, 16)
rsa = RSA.construct((mod, exp))
encrypted_password = rsa.encrypt(password, '')[0]
encrypted_password = base64.b64encode(encrypted_password)

Here's RSA.js:
var RSAPublicKey = function($modulus_hex, $encryptionExponent_hex) {
    this.modulus = new BigInteger( $modulus_hex, 16);
    this.encryptionExponent = new BigInteger( $encryptionExponent_hex, 16);
}

var Base64 = {
    base64: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
    encode: function($input) {
        if (!$input) {
            return false;
        }
        var $output = "";
        var $chr1, $chr2, $chr3;
        var $enc1, $enc2, $enc3, $enc4;
        var $i = 0;
        do {
            $chr1 = $input.charCodeAt($i++);
            $chr2 = $input.charCodeAt($i++);
            $chr3 = $input.charCodeAt($i++);
            $enc1 = $chr1 >> 2;
            $enc2 = (($chr1 & 3) << 4) | ($chr2 >> 4);
            $enc3 = (($chr2 & 15) << 2) | ($chr3 >> 6);
            $enc4 = $chr3 & 63;
            if (isNaN($chr2)) $enc3 = $enc4 = 64;
            else if (isNaN($chr3)) $enc4 = 64;
            $output += this.base64.charAt($enc1) + this.base64.charAt($enc2) + this.base64.charAt($enc3) + this.base64.charAt($enc4);
        } while ($i < $input.length);
        return $output;
    },
    decode: function($input) {
        if(!$input) return false;
        $input = $input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        var $output = "";
        var $enc1, $enc2, $enc3, $enc4;
        var $i = 0;
        do {
            $enc1 = this.base64.indexOf($input.charAt($i++));
            $enc2 = this.base64.indexOf($input.charAt($i++));
            $enc3 = this.base64.indexOf($input.charAt($i++));
            $enc4 = this.base64.indexOf($input.charAt($i++));
            $output += String.fromCharCode(($enc1 << 2) | ($enc2 >> 4));
            if ($enc3 != 64) $output += String.fromCharCode((($enc2 & 15) << 4) | ($enc3 >> 2));
            if ($enc4 != 64) $output += String.fromCharCode((($enc3 & 3) << 6) | $enc4);
        } while ($i < $input.length);
        return $output;
    }
};

var Hex = {
    hex: "0123456789abcdef",
    encode: function($input) {
        if(!$input) return false;
        var $output = "";
        var $k;
        var $i = 0;
        do {
            $k = $input.charCodeAt($i++);
            $output += this.hex.charAt(($k >> 4) &0xf) + this.hex.charAt($k & 0xf);
        } while ($i < $input.length);
        return $output;
    },
    decode: function($input) {
        if(!$input) return false;
        $input = $input.replace(/[^0-9abcdef]/g, "");
        var $output = "";
        var $i = 0;
        do {
            $output += String.fromCharCode(((this.hex.indexOf($input.charAt($i++)) << 4) & 0xf0) | (this.hex.indexOf($input.charAt($i++)) & 0xf));
        } while ($i < $input.length);
        return $output;
    }
};

var RSA = {

    getPublicKey: function( $modulus_hex, $exponent_hex ) {
        return new RSAPublicKey( $modulus_hex, $exponent_hex );
    },

    encrypt: function($data, $pubkey) {
        if (!$pubkey) return false;
        $data = this.pkcs1pad2($data,($pubkey.modulus.bitLength()+7)>>3);
        if(!$data) return false;
        $data = $data.modPowInt($pubkey.encryptionExponent, $pubkey.modulus);
        if(!$data) return false;
        $data = $data.toString(16);
        return Base64.encode(Hex.decode($data));
    },

    pkcs1pad2: function($data, $keysize) {
        if($keysize < $data.length + 11)
            return null;
        var $buffer = [];
        var $i = $data.length - 1;
        while($i >= 0 && $keysize > 0)
            $buffer[--$keysize] = $data.charCodeAt($i--);
        $buffer[--$keysize] = 0;
        while($keysize > 2)
            $buffer[--$keysize] = Math.floor(Math.random()*254) + 1;
        $buffer[--$keysize] = 2;
        $buffer[--$keysize] = 0;
        return new BigInteger($buffer);
    }
}

And here's JS code from Steam site:
var pubKey = RSA.getPublicKey( results.publickey_mod, results.publickey_exp );
var encryptedPassword = RSA.encrypt( password, pubKey );

I guess i must use Crypto.PKCS1_v1_5 instead of Crypto.PublicKey.RSA.encrypt because exactly that function corresponds a name "pkcs1pad2" but i have no idea where do i put publickey_exp in it and how to import an existing key

A: As you suspected, you should use Crypto.Cipher.PKCS1_v1_5 as in the following snippet:
import base64
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
mod = long(publickey_mod, 16)
exp = long(publickey_exp, 16)
rsa_key = RSA.construct((mod, exp))
rsa = PKCS115_Cipher(rsa_key)
encrypted_password = rsa.encrypt(password)
encrypted_password = base64.b64encode(encrypted_password)


text:
Q: How to get the shape of an image after decode_jpeg in Tensorflow? I have an image which I have feed into tf.image.decode_jpeg:
img = tf.io.read_file(file_path)
img = tf.image.decode_jpeg(img, channels=3)

and I am trying to get its height and with width img.shape[0] and img.shape[1], but both return None. Actually, img.shape returns (None, None, 3).
I am using this inside a function that is mapped into a tf.data.Dataset. How can I get the real shape of the image?
update:
At the moment, I have found a solution that consists in wrapping the code with tf.py_function to execute it eagerly because the dataset creates an internal graph. I would appreciate If anyone has another solution to do it in a pure graph way, which would improve performance.

A: Since you have already found a solution to get the shape of the image by wrapping your code around tf.py_function. Providing the solution here for the benefit of the community.
However, since eager execution is enabled by default in TensorFlow 2, you can get the shape directly like mentioned below without having to wrap it around tf.py_function.
Tensorflow 1.x:
img = tf.io.read_file("sample.jpg")
img = tf.image.decode_jpeg(img, channels=3)

with tf.Session() as sess:
  array = img.eval(session=sess)
  height = array.shape[0]
  width = array.shape[1]
  print("Height:",height)
  print("Width:",width)

Height:320
Width:320

Tensorflow 2:
img = tf.io.read_file("sample.jpg")
img = tf.image.decode_jpeg(img, channels=3)
height = img.shape[0]
width = img.shape[1]

print("Height:",height)
print("Width:",width)

Height: 320
Width: 320


text:
Q: NestJS Fastify Bull Board integration I'm trying to integrate Bull Board in to NestJS + Fastify service.
bull-board.middleware.ts
import { Injectable, NestMiddleware } from '@nestjs/common';
import { router as bullBoardMiddleware } from 'bull-board';

@Injectable()
export class BullBoardMiddleware implements NestMiddleware {
  use(req: any, res: any, next: () => void) {
    bullBoardMiddleware(req, res, next);
  }
}

app.module.ts
import { BullBoardMiddleware } from './middlewares/bull-board.middleware';
[...]
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(BullBoardMiddleware)
      .forRoutes('admin/queues');
  }
}

Bull Board relies on Express application which has different Request interface.
Dashboard is actually reachable but serving static files fails.
Browser+Console screenshot
I tried:

*

*applying fistify-express adapter => causes errors with NestJS

*providing basePath | proxyPath: 'admin/queues' in req passed to bullBoardMiddleware
Can some one please advice how to make it working.
Thank you in advance!


text:
Q: Tuckey url rewrite with spring boot, angular 4 results in strange error? I am trying to configure tuckey URL rewrite for spring boot + angular 4 app.
Routing on angular 4 looks like this
{
    path: 'media-detail/:media-name', component: MediaDetailComponent
}

and in urlrewrite.xml as this
<rule match-type="wildcard">
    <from>/media-detail/([a-z]+)$</from>
    <to >../index.html</to>
</rule>

But on page reload, I get an error:

Uncaught SyntaxError: Unexpected token <

in all the .bundle.js files.


text:
Q: python: What am I doing wrong here in my testing code? I want to understand what I'm doing here wrong.
from enum import Enum, auto
class colors(Enum):
    red= auto()
    green= auto()
    yellow= auto()

This is my class.
     def is_first(self):
        return self is not colors.red

My first function.
    def second(self):
        if self is colors.red:
            return ''
        elif self is green:
            return 'second_type'
        elif self is yellow:
            return 'third_type'

What am I doing wrong in testing I need to them all pass.
     @pytest.mark.parametrize('input_str, expected_result',
                    [('aa', False)])

    def test_is_first(input_str, expected_result):
        assert is_first(input_str) is expected_result

and for my second function
    @pytest.mark.parametrize('input_str, expected_result',
                    [('', True),
            ('second_type', True),
            ('third_type', True),
            ('aa', False)])

    def test_second(input_str, expected_result):
        assert second(input_str) is expected_result

A: @pytest.mark.parametrize('input_str, expected_result',
                [('', True),
        ('second_type', True),
        ('third_type', True),
        ('aa', False)])

def test_second(input_str, expected_result):
    assert second(input_str) is expected_result

You wrote:
def second(self):
    if self is colors.red:
        return ''
    elif self is green:
        return 'second_type'
    elif self is yellow:
        return 'third_type'

This would pass the test:
def second(self):
    if self == '':
        return True
    elif self == 'second_type':
        return True
    elif self == 'third_type':
        return True
    elif self 'aa':
        return False

Your assert is_first(input_str) is expected_result is going to fail.
def is_first(self):
  return self is not colors.red

This is going to return True or False. Your expected_result is checking a Boolean value against a String.


text:
Q: Scaldi - default binding with override I would like to inject two different instances of my database wrapper class (DB): a default instance and a readonly instance.
99% of usages of the class use the default instance. I would therefore like to be able to use the simple inject[DB] to get the default instance.
For the readonly instance, I'd like to supply an override: inject[DB] identifiedBy  'readonly
I have setup my bindings as follows:
  bind[misc.DB] identifiedBy 'readonly to new misc.DB(..readonly params)
  bind[misc.DB] to new misc.DB(...readwrite params)

However, injecting the DB with the 'readonly identifier yields the readwrite instance. Is there any way to get this setup to work without having to supply an identifier for my default instance?


text:
Q: Unity NullReferenceException with Lists So making an asteroid game, trying to spawn in 4 asteroids, one in each centre section of each side. Code is below for the spawnerScript & the Initialize method.
Got a couple of errors/Warnings:

NullReferenceException: Object reference not set to an instance of an
object (UnityEditor.PropertyHandler.isArrayReordable

Should not be capturing when there is a hotcontrol

If someone could point out WHY it's giving that error would be appreciated
[SerializeField] GameObject prefabAsteroid;
List<GameObject> asteroids = new List<GameObject>();
List<Vector3> screenSides = new List<Vector3>();
// Start is called before the first frame update
void Start()
{
    //get screen numbers
    float screenHeight = ScreenUtils.ScreenTop - ScreenUtils.ScreenBottom;
    float screenWidth = ScreenUtils.ScreenRight - ScreenUtils.ScreenLeft;

    //collect all screen sides
    screenSides.Add(new Vector2(ScreenUtils.ScreenLeft,screenHeight/2));
    screenSides.Add(new Vector2(ScreenUtils.ScreenTop, screenWidth / 2));
    screenSides.Add(new Vector2(ScreenUtils.ScreenRight, screenHeight / 2));
    screenSides.Add(new Vector2(ScreenUtils.ScreenBottom, screenWidth / 2));
    //loop through each direction(Up,Left,Down,Right) and
    //Instantiate asteroid on center of each side.
    int i = 0;
    foreach (Direction dir in System.Enum.GetValues(typeof(Direction)))
    {

        GameObject pa = Instantiate<GameObject>(prefabAsteroid);
        //add to list
        asteroids.Add(pa);
        pa.GetComponent<Asteroid>().Initialize(dir, screenSides[i]);
        i++;
    }

public void Initialize(Direction direction, Vector2 location)
{
    transform.position = location;
    float angle = Random.Range(0 * Mathf.Deg2Rad, 30 * Mathf.Deg2Rad);
    Vector2 forceMagnitude = new Vector2(Random.Range(minImpulse, maxImpulse), Random.Range(minImpulse, maxImpulse));
    if(direction == Direction.Right)
    {
        angle +=-15*Mathf.Deg2Rad;
    }
    else if (direction == Direction.Left)
    {
        angle +=165 * Mathf.Deg2Rad;
    }
    else if (direction == Direction.Up)
    {
        angle += 75 * Mathf.Deg2Rad;
    }
    else if (direction == Direction.Down)
    {
        angle += 255 * Mathf.Deg2Rad;
    }
    Vector2 moveDirection = new Vector2(Mathf.Cos(angle), Mathf.Sin(angle));
    rb.AddForce(forceMagnitude * moveDirection, ForceMode2D.Impulse);
}

Tried storing instantiated object into list, tried grabbing  component from that but still same error

A: Fixed it.
Error was the rigidbody component 'rb' wasn't within the Initialise (was in Start() method but that hasn't run at this point) so was considered null. Just noticed Ann.L saying same thing


text:
Q: Parsing pexpect output I'm trying to parse in real time the output of a program block-buffered, which means that output is not available until the process ends. What I need is just to parse line by line, filter and manage data from the output, as it could run for hours.
I've tried to capture the output with subprocess.Popen(), but yes, as you may guess, Popen can't manage this kind of behavior, it keeps buffering until end of process.
from subprocess import Popen, PIPE

p = Popen("my noisy stuff ", shell=True, stdout=PIPE, stderr=PIPE)
for line in p.stdout.readlines():
    #parsing text and getting data

So I found pexpect, which prints the output in real time, as it treats the stdout as a file, or I could even do a dirty trick printing out a file and parsing it outside the function. But ok, it is too dirty, even for me ;)
import pexpect
import sys

pexpect.run("my noisy stuff", logfile=sys.stdout)

But I guess it should a better pythonic way to do this, just manage the stdout like subprocess. Popen does. How can I do this?
EDIT:
Running J.F. proposal:
This is a deliberately wrong audit, it takes about 25 secs. to stop.
from subprocess import Popen, PIPE

command = "bully mon0 -e ESSID -c 8 -b aa:bb:cc:dd:ee:00 -v 2"

p = Popen(command, shell=True, stdout=PIPE, stderr=PIPE)

for line in iter(p.stdout.readline, b''):
    print "inside loop"
    print line

print "outside loop"
p.stdout.close()
p.wait()

#$ sudo python SCRIPT.py
                                ### <= 25 secs later......
# inside loop
#[!] Bully v1.0-21 - WPS vulnerability assessment utility

#inside loop
#[!] Using 'ee:cc:bb:aa:bb:ee' for the source MAC address

#inside loop
#[X] Unable to get a beacon from the AP, possible causes are

#inside loop
#[.]    an invalid --bssid or -essid was provided,

#inside loop
#[.]    the access point isn't on channel '8',

#inside loop
#[.]    you aren't close enough to the access point.

#outside loop

Using this method instead:
EDIT: Due to large delays and timeouts in the output, I had to fix the child, and added some hacks, so final code looks like this
import pexpect

child = pexpect.spawn(command)
child.maxsize = 1  #Turns off buffering
child.timeout = 50 # default is 30, insufficient for me. Crashes were due to this param.
for line in child:
    print line,

child.close()

Gives back the same output, but it prints lines in real time. So... SOLVED  Thanks @J.F. Sebastian

A: .readlines() reads all lines. No wonder you don't see any output until the subprocess ends. You could use .readline() instead to read line by line as soon as the subprocess flushes its stdout buffer:
from subprocess import Popen, PIPE

p = Popen("my noisy stuff", stdout=PIPE, bufsize=1)
for line in iter(p.stdout.readline, b''):
    # process line
    ..
p.stdout.close()
p.wait()

If you are already have pexpect then you could use it to workaround the block-buffering issue:
import pexpect

child = pexpect.spawn("my noisy stuff", timeout=None)
for line in child:
    # process line
    ..
child.close()

See also stdbuf, pty -based solutions from the question I've linked in the comments.


text:
Q: Should I use a cost matrix or an F2-score? I'm currently building a classification model in which a false negative is twice as bad as a false positive.  That is, the cost matrix looks like (where a leading $P$ means "predicted" and a leading $T$ means "true"):
$$\begin{matrix}& TP & TN \\PP & 0 & 1 \\ PN & 2 & 0.\end{matrix}$$
The class imbalance is 2:1.
With these costs in mind, should I be looking to use a cost matrix with some other metric (like AUC or F1 score) to weigh the false positives as worse, or should I be using an $F2$ score, which weighs recall as being twice as important as precision?


text:
Q: REACT/create-react-app: Module not found crypto / Uncaught ReferenceError: process is not defined I have seen a couple related questions on this topic but nothing has quite worked!
I am working on a react app and had a bunch of module not found errors once i hit npm start. A few of the not found modules were 'util', 'buffer', 'stream', and 'crypto'. I was able to resolve all but crpyto by npm installing the names here.
For crypto, I'm not sure what I'm using that depends on it, but it is giving me big problems. To solve this, I installed crpyto-browserify and added "browser":{"crypto":false} to my package.json of my 'jwa' module in node modules (where it said i was having problems).
Once I did that, I get a reference error that "process is not found". I've never had this issue before. Including my package.json below, any tips??
To start the react app, I used npx create-react-app appName
Oh, one more note I also created a webpack.config.js file
{
  "name": "app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.2",
    "@testing-library/react": "^12.1.4",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^0.26.1",
    "bootstrap": "^5.1.3",
    "jsonwebtoken": "^8.5.1",
    "react": "^17.0.2",
    "react-app-polyfill": "^3.0.0",
    "react-dom": "^17.0.2",
    "react-router-dom": "^6.2.2",
    "react-scripts": "5.0.0",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Oh, one more note I also created a webpack.config.js file that looks like this:
const webpack = require('webpack')

module.exports = {
    resolve: {
      fallback: {
        assert: require.resolve('assert'),
        buffer: require.resolve('buffer'),
        console: require.resolve('console-browserify'),
        constants: require.resolve('constants-browserify'),
        crypto: require.resolve('crypto-browserify'),
        domain: require.resolve('domain-browser'),
        events: require.resolve('events'),
        http: require.resolve('stream-http'),
        https: require.resolve('https-browserify'),
        os: require.resolve('os-browserify/browser'),
        path: require.resolve('path-browserify'),
        punycode: require.resolve('punycode'),
        querystring: require.resolve('querystring-es3'),
        stream: require.resolve('stream-browserify'),
        string_decoder: require.resolve('string_decoder'),
        sys: require.resolve('util'),
        timers: require.resolve('timers-browserify'),
        tty: require.resolve('tty-browserify'),
        url: require.resolve('url'),
        util: require.resolve('util'),
      },
    },

    plugins: [
        new webpack.ProvidePlugin({
          process: 'process/browser',
        }),
      ]
  };


text:
Q: Why does FullHttpResponse reference counting behave differently dependeing on the underlying ByteBuf implementation? I'm having trouble with leaks on an EmbeddedChannel I use to parse a raw http response into a FullHttpResponse. During analysis, I noticed that the reference counting of the ByteBuf I send into the channel as "input" behaves differently depending on its implementation, which seems odd.
For reference, here is the method I use to parse the raw input:
private FullHttpResponse decodeHttpResponse(ByteBuf responseBuff) {
    EmbeddedChannel channel = new EmbeddedChannel(new HttpResponseDecoder(), new HttpObjectAggregator(99999999));
    try {
        channel.writeInbound(responseBuff);
        channel.flush();
        channel.finish();
        return channel.readInbound();
    } finally {
        channel.close();
        channel.finishAndReleaseAll();
    }
}

Let's use a simple ByteBuf I create from an http response I previously dumped into a file and do some testing, here's my output (the numbers are the reference counts of the object):
>>>---------- Test with ByteBuf ------------<<<
>>> [buf]  : 1
buf.retain()
>>> [buf]  : 2
resp = decodeHttpResponse(cbuf) => io.netty.handler.codec.http.HttpObjectAggregator$AggregatedFullHttpResponse
>>> [buf]  : 2                  // [1]
>>> [resp] : 1                  //
resp.retain()
>>> [buf]  : 2
>>> [resp] : 2
resp.release()
>>> [buf]  : 2
>>> [resp] : 1
resp.release()                  //
>>> [buf]  : 1                  // [2]
>>> [resp] : 0                  //

*

*[1]: When we create the FullHttpResponse, the refCount on the input ByteBuf is not changed.

*[2]: When the FullHttpResponse gets deallocated (refCount reaches 0), it propagates one single release to the underlying ByteBuf.

OK, now let's wrap that input ByteBuf into a CompositeByteBuf and use that to build our FullHttpResponse:
>>>---------- Test with CompositeByteBuf ------------<<<
>>> [buf]  : 1
buf.retain()
>>> [buf]  : 2
cbuf = buf.alloc().compositeBuffer()
>>> [buf]  : 2
>>> [cbuf] : 1
cbuf.addComponent(true, buf)
>>> [buf]  : 2
>>> [cbuf] : 1
cbuf.retain()
>>> [buf]  : 2
>>> [cbuf] : 2
resp = decodeHttpResponse(cbuf) => io.netty.handler.codec.http.HttpObjectAggregator$AggregatedFullHttpResponse
>>> [buf]  : 2              //
>>> [cbuf] : 1              // [1]
>>> [resp] : 1              //
resp.retain()
>>> [buf]  : 2
>>> [cbuf] : 1
>>> [resp] : 2
resp.release()
>>> [buf]  : 2
>>> [cbuf] : 1
>>> [resp] : 1
resp.release()
>>> [buf]  : 2              //
>>> [cbuf] : 1              // [2]
>>> [resp] : 0              //

*

*[1]: When we create the FullHttpResponse, the refCount on the input ByteBuf is being decreased by 1.

*[2]: When the FullHttpResponse gets deallocated (refCount reaches 0), it does not propagate to the underlying CompositeByteBuf.

This difference in behavior is confusing and makes correct reference counting hard (this is a simplified example, in a real application, the entanglement of layered buffers makes it even harder).
Can someone explain why the above behaves differently with ByteBuf and CompositeByteBuf or if there's something I can do to make the behavior consistent and predictable? Or is this maybe even a bug that should be addressed?


text:
Q: Check when GPS is active The idea is simple : when it's GPS available - use gps for geolocation, when it's blinking - use network provider.
LocationListener's  onStatusChanged is not triggered anyhow when GPS stops blinking, so I was using GpsStatus.Listener and wonderfully when GPS fixed it called GpsStatus.GPS_EVENT_FIRST_FIX. Great! But if I loose fix and then go back to fix - this event wouldn't be called anymore! Because it's .. well .. first fix only.
And no event was called when GPS lost and started blinking again. How can I trigger such basic things like catching and loosing GPS?


text:
Q: как убрать подчеркивание input вот стили инпутов
.data{
   background-color: #0e0e0e;
   color: white;
   border:none!important;
    margin: 10px 0;
   height: 30px;
   font-size: 20px;
   border-bottom: 1px solid #515151!important;
  outline: none;
   padding: 10px 15px;
   margin-bottom: 10px;
   user-select: none;
}
data:focus,
data:active,
data:hover,
data:focus {
    -webkit-outline: none;
    outline: none;
   background-color: #0e0e0e;
}

как в Safari убрать рамку у инпутов

A: .data {
   your code...
   ...
   ...
   outline: none;
   border: none;
          }

Должно помочь


text:
Q: Can't find untested extension in order to remove it: SafariTabSwitching
I don't need this extension anymore because Safari 9 has this feature built-in, but I can't find it anywhere to disable or remove it. It's not listed in my Preferences -> Extensions. I looked through my ~/Library/Safari/Extensions but it's not listed there either.
How do I remove this extension so that I don't get this annoying popup every time I launch Safari?

A: Generally, Safari plugins should be in /Library/Internet Plug-ins/

However, I discovered SafariTabSwitching is actually in a different location
Source : Safari Tab Switching FAQ

How to uninstall?
  Remove this file: /Library/Application Support/SIMBL/Plugins/SafariOmnibar.bundle
  Alternatively you may download this uninstaller and run it. Note that uninstaller won't remove SIMBL Agent as you may use some other SIMBL plugin and we don't want to break them.


text:
Q: How to make dropdown in the Google sheet for day, month and year in separate column I have tried the list of items approach but stuck in the year.

A: If you just want to select a valid date, you need to set your Criteria to "Date", not to a list of items.
See the screenshot below:

Otherwise there is no clean way of adding the date validation. You can of course choose month, day and year separately from a dropdown, but not very clear why you'd want it that way as then you will need to concat those entries in a new cell.


text:
Q: What methods can be used to secure web services? I'm interested to know what methods people use to secure their webservices from unauthorized web service consumers.

A: I usually require either a user id/password to be sent each time, or return a token from the first authenticated connection that can be used subsequently.
Nothing fancy. Pretty similar to standard web app login.

A: I've used both SOAP headers and method parameters to pass user credentials -- .NET makes using the SOAP headers pretty easy, but I had issues with this using Java (several months back).  I also do some IP-based filtering if the service is not intended for client (browser) use, but rather from backend web servers.  Public, browser consumable web services are often protected by session cookies -- i.e, requires a valid logon to the web site, then the standard session authentication mechanism is used for requests via AJAX to web services.

A: There is a protocol specifically for web services security WS-Security. I've used parts of it in the past but at the time there was not a lot of support for it in .Net so it was a lot of work.
Currently with .Net I use SOAP Extension Headers. I have one web service call to authenticate and get a session token and then include that token in a SOAP header for every subsequent call, somewhat similar to this example. Of course all the request must travel over TLS to keep them from being compromised.

A: You can use network appliances such as IBM's DataPower or Vordel if you don't want to handle in your own application.


text:
Q: Python: How to use a dictionary to call methods (values in dictionary) to run based on user input (key in dictionary) in a different function? What I have so far:
def run_A():
   # code...

def run_B():
   # code...

def run_C():
   # code...

inputDict = {'a': run_A, 'b': run_B, 'c': run_C, 'q': False}  # q for quit program
def userChoice(self):
    y = True
    while y:
       choice = input("a. run A\nb. run B\nc. run C\nq. Quit").lower()
       self.inputDict[choice]

My issue here is that the program allows the user to input their choice, but the function will be called based on dictionary (won't run) and program will only keep asking user for their choice.

A: self.inputDict[choice] will just get function from dict, and won't call it, so maybe you need replace self.inputDict[choice] with self.inputDict[choice]()

A: def run_A():
    print("A")
   # code...

def run_B():
    print("B")
   # code...

def run_C():
    print("C")
   # code...

inputDict = {'a': run_A, 'b': run_B, 'c': run_C, 'q': False}  # q for quit program
def userChoice(self):
    y = True
    while y:
       choice = input("a. run A\nb. run B\nc. run C\nq. Quit").lower()
       if choice =="q":
           y = False
       else:
           self.inputDict[choice]()


text:
Q: unable to transform from json to xml with xslt in java I am trying to transform JSON to XML using XSLT 3.0 in Java. When i run the Java program, it displays an error: Content is not allowed in prolog.
{
    color: "red",
    value: "#f00"
}

A: Based on that error it sounds like you're using the JSON as the input to the stylesheet. Like mentioned in the other answer, XSLT will only work on XML input.
However, you can run a stylesheet without any input by using an initial template. You can then pass in the path to the JSON file through an xsl:param and read it with unparsed-text(). This will give you a string you can convert to XML with json-to-xml(). (You could also pass the JSON itself in as an xsl:param and use that param directly in the json-to-xml() call.)
Also, in your sample JSON, the keys need to be quoted.
Here's an example run from the command line using Saxon-HE 9.8...
JSON (so.json)
{
    "color": "red",
    "value": "#f00"
}

XSLT 3.0 (json2xml.xsl)
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:param name="jsonFile"/>

  <xsl:mode on-no-match="shallow-copy"/>

  <xsl:template name="init">
    <xsl:variable name="json" select="unparsed-text($jsonFile)"/>
    <xsl:apply-templates select="json-to-xml($json)"/>
  </xsl:template>

</xsl:stylesheet>

Command Line/Output
C:\temp>java -cp "C:/apps/saxon/saxon9he.jar" net.sf.saxon.Transform -it:"init" -xsl:"json2xml.xsl" jsonFile="so.json"
<?xml version="1.0" encoding="UTF-8"?>
<map xmlns="http://www.w3.org/2005/xpath-functions">
   <string key="color">red</string>
   <string key="value">#f00</string>
</map>

Here's a Java example (using Saxon-HE 9.7) showing how to pass the JSON in as a parameter...
Java
package so.test1;

import java.io.File;
import java.io.OutputStream;
import javax.xml.transform.stream.StreamSource;
import net.sf.saxon.s9api.XsltTransformer;
import net.sf.saxon.s9api.Processor;
import net.sf.saxon.s9api.QName;
import net.sf.saxon.s9api.SaxonApiException;
import net.sf.saxon.s9api.Serializer;
import net.sf.saxon.s9api.XdmAtomicValue;
import net.sf.saxon.s9api.XsltCompiler;
import net.sf.saxon.s9api.XsltExecutable;

/**
 *
 * @author dhaley
 *
 */
public class SOTest1 {

    public static void main(String[] args) throws SaxonApiException {
        final String XSLT_PATH = "src/so/test1/json2xml.xsl";
        final String JSON = "{\n" +
                            "    \"color\": \"red\",\n" +
                            "    \"value\": \"#f00\"\n" +
                            "}";

        OutputStream outputStream = System.out;
        Processor processor = new Processor(false);
        Serializer serializer = processor.newSerializer();
        serializer.setOutputStream(outputStream);
        XsltCompiler compiler = processor.newXsltCompiler();
        XsltExecutable executable = compiler.compile(new StreamSource(new File(XSLT_PATH)));
        XsltTransformer transformer = executable.load();
        transformer.setInitialTemplate(new QName("init")); //<-- SET INITIAL TEMPLATE
        transformer.setParameter(new QName("jsonText"), new XdmAtomicValue(JSON)); //<-- PASS JSON IN AS PARAM
        transformer.setDestination(serializer);
        transformer.transform();

    }

}

XSLT 3.0 (updated json2xml.xsl)
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:param name="jsonText"/>

  <xsl:mode on-no-match="shallow-copy"/>

  <xsl:template name="init">
    <xsl:apply-templates select="json-to-xml($jsonText)"/>
  </xsl:template>

</xsl:stylesheet>

Output (System.out)
<?xml version="1.0" encoding="UTF-8"?>
<map xmlns="http://www.w3.org/2005/xpath-functions">
   <string key="color">red</string>
   <string key="value">#f00</string>
</map>

A: XSLT works on XML input, not JSON.
A simple Google search found this code on GitHub which claims to be able to convert JSON to XML and vice-versa.


text:
Q: Why my Haproxy stats GUI limit sessions in backend sticks to 20000? My loadbalancer's GUI shows that it's backend has a limit of 20.000 sessions, no matter the maxconn parameter I set in global or in the backend sections.

When running a test, the max parameter in Sessions exceeds the limit.
Any idea how to solve it or if it's even a problem?
HAProxy version: 2.2.11-1ppa1~bionic 2021/03/18

A: Nothing complex but slightly tricky, the number in the backend session limit is fullconn,
Adding fullconn to your backend will change that limit on the stats page just in case.
backend my-backend
        fullconn 200000

However, if fullconn is not set, it sums up all the session limit values for frontends that route to this backend, divided by 10. And there is lot more in the official documentation explained.
Reference documentation


text:
Q: Select rows with latitude-longitude values inside 10km radius? I have a site which shows posts from a certain city. I was thinking of changing from Cities to a radius around the user's location (10km in this case).
I don't know how to query using a radius. I can only think of doing a query with two conditions and get a square. e.g:
SELECT fields
FROM points
WHERE lat BETWEEN LAT1 AND LAT2
AND lon BETWEEN LON1 AND LON2

Is it possible to select rows inside a radius of X km/mi from a certain location?

A: In general, you can use a WHERE query on any condition. So, supposing you have a function distance() that can compute the distance between two geographic points, you could do:
SELECT fields
FROM points
WHERE distance(lat, lon, city_lat, city_lon) <= 10

where city_lat and city_lon is the location of the city centre.
PostgreSQL contains a add-on function called earthdistance() that would help.

A: $users = DB::table('users')
        ->select('id','name','phone','latitude','longitude')
        ->SQRT("POW(69.1 * (latitude - 24.900110), 2) +
        POW(69.1 * (67.099760 - longitude) * COS(latitude / 57.3), 2)) AS distance")
        ->having("distance < 25")
        ->orderBy("distance")
        ->get();


text:
Q: How to execute a function in MongoDB Shell? I have a MongoDB function to Insert some data from 1 Doc to another Doc as below, I don't know if it's right or wrong but now I just want to find a way to test it on MongoDB Shell.
function loadEducation() {
        const bulkInsert = db.education.initializeUnorderedBulkOp();
        const documents = db.summaryData.find({});

        documents.forEach(function (doc) {
            const element = {
                education: "$doc.education",
                "education_num": "$doc.education_num"
            };
            bulkInsert.find(element).upsert().replaceOne(element);
        });
        bulkInsert.execute();
        return true;
        }

I've read many posts on the internet but non of them work. For example:

*

*I've already insert the function into db.system.js, but I can't use db.loadServerScripts() because the error "db.loadServerScripts is not a function"

*db.eval("loadEducation()") won't work too. The same error as above "db.eval is not a function"
There are many posts about this kind of problem on the internet (StackOverflow too) but there is no answer at all. For example here and here and here

A: There is no need to store the definition of this function into the server itself, and there are a variety of ways to test it. For both of the two demonstrated below I will be using the MongoDB Shell (which is the newer utility that replaces the previous mongo interface).
The first option is simply to open the shell session and paste the function in:
$ ./mongosh
...
> loadEducation
ReferenceError: loadEducation is not defined
test> function loadEducation() {
...         const bulkInsert = db.education.initializeUnorderedBulkOp();
            ...
...         }
[Function: loadEducation]
> loadEducation
[Function: loadEducation]
>

The second option involves saving the function definition to a file. Here I've done so using a file named customFile that is saved in the current directory that my command line is in. Namely:
$ cat customFile
function loadEducation() {
        const bulkInsert = db.education.initializeUnorderedBulkOp();
        const documents = db.summaryData.find({});

        documents.forEach(function (doc) {
            const element = {
                education: "$doc.education",
                "education_num": "$doc.education_num"
            };
            bulkInsert.find(element).upsert().replaceOne(element);
        });
        bulkInsert.execute();
        return true;
        }
$

The second option then is to open the shell and then use the load() method:
$ ./mongosh
...
> loadEducation
ReferenceError: loadEducation is not defined
> load('customFile')
true
> loadEducation
[Function: loadEducation]
>

At this point for both options you can then simply call the function using loadEducation() in the shell session as expected.


text:
Q: Read line from byte array (not convert byte array to string) I have a byte array that I am reading in from a NetworkStream. The first two bytes tell the length of the packet that follows and then the packet is read into a byte array of that length. The data in that I need to read from the NetworkStream/byte array has a few Strings, i.e. variable length data terminated by new line characters, and some fixed width fields like bytes and longs. So, something like this:
// I would have delimited these for clarity but I didn't want
// to imply that the stream was delimited because it's not.
StringbyteStringStringbytebytebytelonglongbytelonglong

I know (and have some say in) the format of the data packet that is coming across, and what I need to do is read a "line" for each string value, but read a fixed number of bytes for the bytes and longs. So far, my proposed solution is to use a while loop to read bytes into a temp byte array until there is a newline character. Then, convert the bytes to a string. This seems kludgy to me, but I don't see another obvious way. I realize I could use StreamReader.ReadLine() but that would involve another stream and I already have a NetworkStream. But if that's the better solution, I'll give it a shot.
The other option I have considered is to have my backend team write a byte or two for those String values' lengths so I can read the length and then read the String based on the length specified.
So, as you can see, I have some options for how to go about this, and I'd like your input about what you would consider the best way to do it. Here's the code that I have right now for reading in the entire packet as a string. The next step is to break out the various fields of the packet and do the actual programming work that needs to be done, creating objects, updating UI, etc. based on the data in the packet.
string line = null;
while (stream.DataAvailable)
{
    //Get the packet length;
    UInt16 packetLength = 0;
    header = new byte[2];
    stream.Read(header, 0, 2);
    // Need to reverse the header array for BitConverter class if architecture is little endian.
    if (BitConverter.IsLittleEndian)
        Array.Reverse(header);
    packetLength = BitConverter.ToUInt16(header,0);

    buffer = new byte[packetLength];
    stream.Read(buffer, 0, BitConverter.ToUInt16(header, 0));
    line = System.Text.ASCIIEncoding.ASCII.GetString(buffer);
    Console.WriteLine(line);
}

A: Personally I would

*

*Put an Int16 at the start of the
strings, so you know how long
they're going to be, and

*Use the IO.BinaryReader class to
do the reading, it'll "read", ints,
strings, chars etc into variable e.g. BinReader.ReadInt16() will read two bytes, return the int16 they represent, and move two bytes on in the stream

Hope this helps.
P.S. Be careful using the ReadString method, it assumes the string is prepended with custom 7 bit integers i.e. that it was written by the BinaryWriter class.
The following is from this CodeGuru post

The BinaryWriter class has two methods
  for writing strings: the overloaded
  Write() method and the WriteString()
  method. The former writes the string
  as a stream of bytes according to the
  encoding the class is using. The
  WriteString() method also uses the
  specified encoding, but it prefixes
  the string's stream of bytes with the
  actual length of the string. Such
  prefixed strings are read back in via
  BinaryReader.ReadString().
The interesting thing about the length
  value it that as few bytes as possible
  are used to hold this size, it is
  stored as a type called a 7-bit
  encoded integer. If the length fits in
  7 bits a single byte is used, if it is
  greater than this then the high bit on
  the first byte is set and a second
  byte is created by shifting the value
  by 7 bits. This is repeated with
  successive bytes until there are
  enough bytes to hold the value. This
  mechanism is used to make sure that
  the length does not become a
  significant portion of the size taken
  up by the serialized string.
  BinaryWriter and BinaryReader have
  methods to read and write 7-bit
  encoded integers, but they are
  protected and so you can use them only
  if you derive from these classes.

A: I would go with length-prefixed strings. It will make your life a lot simpler, and it means you can represent strings with line breaks in. A few comments on your code though:

*

*Don't use Stream.DataAvailable. Just because there's not data available now doesn't mean you've read the end of the stream.

*Unless you're absolutely sure you'll never need text beyond ASCII, don't use ASCIIEncoding.

*Don't assume that Stream.Read will read all the data you ask it to. Always check the return value.

*BinaryReader makes a lot of this a lot easier (including length-prefixed strings and a Read that loops until it's read what you've asked it to)

*You're calling BitConverter.ToUInt16 twice on the same data. Why?


text:
Q: Fetching device.description using Alsa soundlib in C++ I am new to alsa, pulseAudio, needed help with this issue.
This is the truncated output of pacmd command on my system
pacmd list-sources:
    name: <alsa_input.pci-0000_00_1f.3.analog-stereo>

    properties:
        alsa.resolution_bits = "16"
        device.profile.name = "analog-stereo"
        device.profile.description = "Analog Stereo"
        device.description = "Built-in Audio Analog Stereo"
        module-udev-detect.discovered = "1"
        device.icon_name = "audio-card-pci"

I want to fetch the field: device.description = "Built-in Audio Analog Stereo" using a simple C++ program
When I try fetching description using
desc = snd_device_name_get_hint(*n, "DESC");
I get the following output for the same device
Name of device: hw:CARD=PCH,DEV=0
Description of device: HDA Intel PCH, ALC3235 Analog
Direct hardware device without any conversions
I/O type of device: (null)

Is there a way I can fetch the description similar to pacmd output?
If it is not possible does anyone know how to fetch the name: <alsa_input.pci-0000_00_1f.3.analog-stereo> field from the pacmd output.
I tried a bunch pf APIs from the official page:
https://www.alsa-project.org/alsa-doc/alsa-lib/group___control.html
but no luck
Code that I am currently running:
#include <alsa/asoundlib.h>
void listdev(char *devname)
{
    char** hints;
    int    err;
    char** n;
    char*  name;
    char*  desc;
    char*  ioid;
    /* Enumerate sound devices */
    err = snd_device_name_hint(-1, devname, (void***)&hints);
    if (err != 0) {
        fprintf(stderr, "*** Cannot get device names\n");
        exit(1);
    }
    n = hints;
    while (*n != NULL) {
        name = snd_device_name_get_hint(*n, "NAME");
        desc = snd_device_name_get_hint(*n, "DESC");
        ioid = snd_device_name_get_hint(*n, "IOID");
        printf("Name of device: %s\n", name);
        printf("Description of device: %s\n", desc);
        printf("I/O type of device: %s\n", ioid);
        printf("\n");
        if (name && strcmp("null", name)) free(name);
        if (desc && strcmp("null", desc)) free(desc);
        if (ioid && strcmp("null", ioid)) free(ioid);
        n++;
    }
    //Free hint buffer too
    snd_device_name_free_hint((void**)hints);
}

A: Got those required values using proplist
https://freedesktop.org/software/pulseaudio/doxygen/structpa__card__info.html#a61d544035431d68f87e5e1cb27c3bf2e
more information about proplist: https://freedesktop.org/software/pulseaudio/doxygen/proplist_8h.html

A: If you want to use the ALSA C++ API (from gtkIOStream) then you can do it like so :
const string deviceName="hw:0";
Playback pcm(deviceName.c_str()); // You could also use the PCM class instead of Playback or Capture.
cout<<"Opened the PCM device "<<deviceName<<endl;

Info info;
info.getInfo(pcm);
cout << "Card   Number     : " << info.getCard() << endl;
cout << "Device Number     : " << info.getDevice() << endl;
cout << "Sub-device Number : " << info.getSubDevice() << endl;
cout << "Short ID          : " << info.getID() << endl;
cout << "Name              : " << info.getName() << endl;
cout << "Sub-device name   : " << info.getSubDeviceName() << endl;

You can see this full example in the ALSAInfoTest.C file.
If you want to use the alsa-lib  API, then this is the process :
snd_pcm_t *handle;
const char *device="hw:0";
snd_pcm_open(&handle, device, SND_PCM_STREAM_PLAYBACK, 0); // check for error here
snd_pcm_info_t *info;
snd_pcm_info_malloc(&info); // malloc the structure, you should check for errors
cout<<snd_pcm_info_get_name(info)<<endl; // print out the device name
snd_pcm_info_free(info);


text:
Q: JavaScript use HTML Tags i would like to ask how i can work with html tags e.g.
 or  in JavaScript?
My Code :
document.addEventListener('DOMContentLoaded', function() {
  if (window.location.href.indexOf("/login?from=") !== -1) {
    var hint=document.createTextNode("Hello");
    var node = document.getElementById("main-panel");
    node.insertBefore(hint, node.firstChild);
  }
})

But they show the text string  hello  and does not make it big .
i can only work in a js file i dont have the opportunities to work with div tags in html file

A: First create an element b and the add the desired text to it.

var bold = document.createElement('b')
bold.innerHTML = "hello"
var parent = document.getElementById("haha");
parent.appendChild(bold)

put the text here

A: You can use this script:

I tested and it worked.


text:
Q: How to find the css class and code for a graphical element (range slider) in Jupyter Lab/Notebook output cell and modify it to change its appearance? I have the following graphs/outputs from VSCode, VSCode-Insiders and Jupyter Lab respectively.
VSCode

VSCode-Insiders

Jupyter Lab

I want to change the looks of the slider that you see at the bottom.
Basically I want to remove the text and number and change the looks of the slider knob and its position to be in the center relative to the image.
My thought process is that, since VSCode is an electron app and Jupyter Lab runs in a browser so it should be possible to modify that single output cell with a custom targeted CSS.
As an example I have the following that works perfectly in all 3 setups and changes the CSS of the output cell by coloring the text, which tells me that it may be possible to do what I want with the slider element too -
%%html

This text has a nice colour

But in my case I have to target a particular element - "slider". I toggled to the developer mode in VSCode and VSCode Insiders - "Ctrl+Shift+I" or "Help -> Toggle Developer Tools". But I am not able to select the slider element using the "Inspector".
In Jupyter Lab fortunately I was able to select the slider element, but the class vega-bind (the div that has the slider has a class called vega-bind) doesn't seem to have any CSS in it - at least nothing related to vega-bind showed up in the Developer Tool.
Is there any way to achieve what I am trying to do in Jupyter Lab and VSCode Jupyter Notebooks?
The following code generates that output that you see above -
Requirements - altair, pandas and numpy
import altair as alt
import pandas as pd
import numpy as np

rand = np.random.RandomState(42)

df = pd.DataFrame({
    'xval': range(100),
    'yval': rand.randn(100).cumsum()
})

slider = alt.binding_range(min=0, max=100, step=1, name='cutoff')
selector = alt.selection_single(bind = slider, init={'cutoff': 50})

alt.Chart(df).mark_point().encode(
    x='xval',
    y='yval',
    color=alt.condition(
        alt.datum.xval < selector.cutoff,
        alt.value('red'), alt.value('blue')
    )
).add_selection(
    selector
)

A: Turns out Jupyter Notebooks in VSCode are rendered as iframes and are separate processes that you cannot debug/run developer tools on from the main developer tools panel that opens on the side.
To find the CSS, HTML etc of the notebook iframe, you have to open the Webview Developer Tool and you can do that by typing Open Webview Developer Tools in the command palette i.e.
CTRL+Shift+P -> Open Webview Developer Tools
Now you can select the inspector and hover over any element you like and see/edit its CSS.


text:
Q: CSS questions events with hover How do I change the CSS of an element that is nested while another is react to a event without javascript?
I have a menu which hides text while not in use, but when the user hovers on the edge, the menus is suppose to come up and show the text again. How do I get the element that is nested.
/*The div element that is being hovered over*/
#menu:hover
{
   /*how do i change the another div display*/
}
#text{display:none;}

A: If your div is nested in the menu its as simple as adding it to the rule:
#menu:hover div.nested-div
{
    display:inline-block;
}


text:
Q: Android: flaky ViewModel unit tests with coroutines I have a VM such as
class CityListViewModel(private val repository: Repository) : ViewModel() {
    @VisibleForTesting
    val allCities: LiveData<Resource<List<City>>> =
        liveData(context = viewModelScope.coroutineContext + Dispatchers.IO) {
            emit(Resource.Loading())
            emit(repository.getCities())
        }
}

And my tests are:
@ExperimentalCoroutinesApi
class CityListViewModelTest {
    @get:Rule
    val rule = InstantTaskExecutorRule()
    @get:Rule
    val coroutineTestRule = CoroutinesTestRule()

    @Test
    fun `allCities should emit first loading and then a Resource#Success value`() =
        runBlockingTest {
            val fakeSuccessResource = Resource.Success(
                listOf(
                    City(
                        1,
                        "UK",
                        "London",
                        Coordinates(34.5, 56.2)
                    )
                )
            )
            val observer: Observer<Resource<List<City>>> = mock()
            val repositoryMock: Repository = mock()

            val sut =
                CityListViewModel(repositoryMock)
            doAnswer { fakeSuccessResource }.whenever(repositoryMock).getCities()

            sut.allCities.observeForever(observer)
            sut.allCities
            val captor = argumentCaptor<Resource<List<City>>>()
            captor.run {
                verify(observer, times(2)).onChanged(capture())
                assertEquals(fakeSuccessResource.data, lastValue.data)
            }
        }

    @Test
    fun `allCities should emit first loading and then a Resource#Error value`() =
        runBlockingTest {
            val fakeErrorResource = Resource.Error<List<City>>("Error")
            val observer: Observer<Resource<List<City>>> = mock()
            val repositoryMock: Repository = mock()

            val sut =
                CityListViewModel(repositoryMock)
            doAnswer { fakeErrorResource }.whenever(repositoryMock).getCities()

            sut.allCities.observeForever(observer)
            sut.allCities
            val captor = argumentCaptor<Resource<List<City>>>()
            captor.run {
                verify(observer, times(2)).onChanged(capture())
                assertEquals(fakeErrorResource.data, lastValue.data)
            }
        }
}

The problem I have is that the tests are very flaky: sometimes they both pass, sometimes one fails, but I can't seem to find out the problem.
Thanks!

A: The issue is that in the test, you don't have control over the IO Dispatcher. I'm assuming your CoroutinesTestRule is something like this Gist? This only overrides Dispatchers.Main, but your CityListViewModel uses Dispatchers.IO.
There are a few different options:

*

*In CityListViewModel, you can avoid using Dispatchers.IO explicitly, and instead just rely on the viewModelScope which defaults to Dispatchers.Main. In your real Repository implementation, ensure that your suspending getCities() method redirects to Dispatchers.IO, i.e.

suspend fun getCities(): List<City> {
  withContext(Dispatchers.IO) {
    // do work
    return cities
  }
}

And in the CityListViewModel:
  val allCities: LiveData<Resource<List<City>>> =
    liveData(context = viewModelScope.coroutineContext) {
      emit(Resource.Loading())
      emit(repository.getCities())
    }

In this case, things will continue to work as they do currently, and in your test, the mock Repository will just immediately return a value.

*Inject Dispatchers.IO instead. If you're using a DI framework such as Dagger this will be easier, but you could essentially do something like:

class CityListViewModel(
  private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO,
  private val repository: Repository
) : ViewModel() {
  @VisibleForTesting
  val allCities: LiveData<Resource<List<City>>> =
    liveData(context = viewModelScope.coroutineContext + ioDispatcher) {
      emit(Resource.Loading())
      emit(repository.getCities())
    }
}

And then in your test:
val viewModel = CityListViewModel(
  ioDispatcher = TestCoroutineDispatcher(),
  repository = repository
)

Either of these should make your tests deterministic. If you are using Dagger, then I'd recommend doing both (create a production module to provide the Main, IO, and Default dispatchers, but have a test module that provides instances of TestCoroutineDispatcher instead), but also doing option 1 which is to make sure your suspending functions direct the work to another dispatcher if they're doing blocking work.

A: I believe best approach is to pass Dispatcher to your viewModels so testing is super easy.. like here :
https://stackoverflow.com/a/62629410/2719243


text:
Q: my codeblock doesn't compile Sorry for my broken English.
I'm pretty new to coding. I installed codeblock a couple weeks ago and today it stopped compiling. At first I deactivated Norton security and it worked. But now even I deactivated Norton, it doesn't compile. I googled for more than 1 hour but I have no idea what is wrong.
When I compile, statement like below pops up.
-------------- Build file: Debug in work place (compiler: GNU GCC Compiler)---------------

mingw32-gcc.exe -Wall -g  -c "C:\Users\(myname\Desktop\folder's name\work place\Untitled1.c" -o obj\Debug\Untitled1.o
Process terminated with status 0 (0 minute(s), 0 second(s))
0 error(s), 0 warning(s) (0 minute(s), 0 second(s))

Please help me!
*) I didn't post the original code I tried to compile because it is too simlple. But maybe I have to.
#include <stdio.h>
 int main(){
   int a, b;
   a=4;
   b=3;
   printf("%d %d", a, b);

    return 0;
   }

***) I guess I solved the problem. I reinstalled the codeblocks.

A: I just reinstalled the codeblocks and now it seems OK. I guess there was no problem in the place...


text:
Q: Measuring the overlap between two probability distribution I have many probability distributions, I need to compute the amount of overlap between two probability distributions. I don't know the type of distribution since it really depends on the data itself.

My question is what appropriate approach that should I use for this case?


text:
Q: Replace the tick of a checkbox with a square div I've been given this task where I have to port an old checkbox component into a new project. However, as the design is different, I need to replace the current tick mark with a rounded filled div.
My main (and only) approach was to hide the actual html checkbox behind a visible div that act like the checkbox. But I was told that this is a bad approach.
I was looking for a way to style the checkmark of a checkbox, but I didn't find a way to selct it to hide it or replace it with something like a div.
My Vue(and Tailwind) component:
<template>
    <div :class="[`h-full w-full p-2`, props.isEnabled || `opacity-30`]">
        <div
            @click="checkBoxIsToggled = !checkBoxIsToggled"
            class="cursor-pointer"
            :class="[
                'flex relative items-center h-full w-full',
                props.checkBoxType === 'reverse-between' ? 'justify-between' : 'justify-start',
                props.direction === 'vertical' ? 'flex-col justify-start gap-2' : 'items-center',
            ]"
        >
            <input
                type="checkbox"
                :value="props.value"
                :name="props.name"
                class="absolute order-1 w-6 h-6 opacity-0"
                :class="[
                    props.checkBoxType === 'reverse-between' && ' right-0',
                    props.checkBoxType === 'standard' ? 'order-0' : 'order-1',
                    props.direction === 'vertical' && 'top-0 right-4',
                ]"
                :disabled="!props.isEnabled"
            />
            <div
                :class="[
                    'bg-white w-6 h-6 flex flex-shrink-0 justify-center items-center p-1 border-2 border-gray',
                    props.checkBoxType === 'standard' && props.direction === 'horizontal' && 'order-0 mr-2',
                    props.checkBoxType === 'reverse-between' && props.direction === 'horizontal' && 'order-1 ml-2',
                    props.direction === 'vertical' && 'mr-0',
                    inputShape === 'square' ? 'rounded' : 'rounded-full',
                    !props.isToggleEnabled && 'border-1',
                ]"
            >
                <div
                    v-if="!checkBoxIsToggled"
                    :class="[
                        'bg-gray w-3 h-3',
                        props.inputShape === 'circle' ? 'rounded-full' : 'rounded-sm',
                        !props.isToggleEnabled && 'hidden',
                    ]"
                ></div>
            </div>
            <div
                :class="[
                    'select-none font-base flex justify-center items-center',
                    props.checkBoxType === 'standard' ? 'order-1' : 'order-0',
                    props.direction === 'vertical' && 'text-center',
                ]"
            >
                <span
                    :class="[
                        props.textSize ? `text-${props.textSize}` : 'text-base',
                        props.isToggleEnabled ? 'font-bold' : 'font-normal',
                        'text-gray',
                    ]"
                    >{{ props.label }}</span
                >
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
    import { defineProps, ref } from "vue"

    const checkBoxIsToggled = ref(false)

    const props = defineProps({
        /**
         * Sets the label for the input element
         */
        label: {
            type: String,
            default: "example",
        },
        /**
         * Sets the value for the input element
         */
        value: {
            type: Boolean,
            default: false,
        },
        /**
         * Sets the name for the input element
         */
        name: {
            type: String,
            default: "example",
        },
        /**
         * Changes the layout between text and checkbox button
         */
        checkBoxType: {
            default: "standard",
        },
        /**
         * Sets the shape of the button as square or circle
         */
        inputShape: {
            default: "square",
        },
        /**
         * Sets the direction of the component as horizontal or vertical
         */
        direction: {
            default: "horizontal",
        },
        /**
         * Sets the text size
         */
        textSize: {
            type: String,
            default: "bo-base",
        },
        /**
         * Checks or unchecks the button
         */
        isToggleEnabled: {
            type: Boolean,
            default: true,
        },
        /**
         * If false, the whole component is greyed out
         */
        isEnabled: {
            type: Boolean,
            default: true,
        },
    })
</script>


text:
Q: How to have Apex Trigger post Chatter field updates in one post? I currently have an apex trigger that posts to chatter for when a field is updated on a record. Currently, the trigger works but posts each update as a separate chatter message:

I want to have it where if someone makes multiple field updates in one edit, it posts to chatter like this:

^ two notes:
-burger and fries are two different fields on a test object called 'Menu' - I just used this as an example
-this is the default way that salesforce posts to chatter with chatter field tracking
If also possible, can I add to the trigger so that it posts to a specific group or user? The reason why I'm writing a trigger is that we need to track more than 20 fields on a record.
Here is my code:
  trigger AccountChatter on Account (after update) {
    List<Schema.FieldSetMember> lstTrackedFields = SObjectType.Account.FieldSets.AccountChatter.getFields();

    if (lstTrackedFields.isEmpty()) return;

    List<FeedItem> lstFieldChanges = new List<FeedItem>();

    if(!trigger.isUpdate) return;

    for (Account objNewAccount : trigger.new) {

        final Account oldAccount = trigger.oldmap.get(objNewAccount.Id);
        // Iterate over all fields in Fieldset
        for (Schema.FieldSetMember objField : lstTrackedFields) {
            String fieldName  = objField.getFieldPath();
            String fieldLabel = objField.getLabel();

            if (objNewAccount.get(fieldName) == oldAccount.get(fieldName))
                continue;

            String oldValue = String.valueOf(oldAccount.get(fieldName));
            String newValue = String.valueOf(objNewAccount.get(fieldName));

            if (oldValue != null && oldValue.length()>255)
                oldValue = oldValue.substring(0,255);

            if (newValue != null && newValue.length()>255)
                newValue = newValue.substring(0,255);

            FeedItem post = new FeedItem();
            post.ParentId = objNewAccount.Id; // RecordId
            post.Body = UserInfo.getName()+' changed '+fieldLabel+' from '+oldValue +' to '+newValue ;

            lstFieldChanges.add(post);
        }
    }

    if (!lstFieldChanges.isEmpty()) insert lstFieldChanges;

Thank you all for reading, getting this to work will be a monumental help to our org and I will be forever grateful :)

A:
I want to have it where if someone makes multiple field updates in one edit, it posts to chatter like this:

This is actually a pretty simple change. See where you have
        FeedItem post = new FeedItem();
        post.ParentId = objNewAccount.Id; // RecordId
        post.Body = UserInfo.getName()+' changed '+fieldLabel+' from '+oldValue +' to '+newValue ;

        lstFieldChanges.add(post);

inside the inner for loop, which iterates field by field? You want that code to be in your outer for loop, that iterates Account by Account.
However, you're also wanting to accumulate a post body that mentions all of the changed fields. You can do that using very similar logic to what you're working with now. The way I like to do it is to accumulate a List<String>:
 List<String> changeDetails = new List<String>(); // at top of outer for loop

and then in my inner for loop
 changeDetails.add(fieldLabel+' from '+oldValue +' to '+newValue);

This allows you to efficiently template the final post body with String.format() when you're back at the bottom of your outer loop:
post.Body = String.format(
    '{} made the following changes:\n{}',
    new List<String> {
        UserInfo.getName(),
        String.join(changeDetails, '\n')
    }
);

If also possible, can I add to the trigger so that it posts to a specific group or user? The reason why I'm writing a trigger is that we need to track more than 20 fields on a record.

Sure. Just change the ParentId of the feed item. You may want to amend the message to include details of the changed record. See the FeedItem reference under ParentId:

ID of the object type to which the FeedItem object is related. For example, set this field to a UserId to post to someone's profile feed, or an AccountId to post to a specific account.


text:
Q: Enum Reflection with .NET Core I am trying to get the DisplayAttribute properties working for an enum, so I can list out the values available (to expose to a RESTful API).
I have an enumeration as follows:
/// <summary>
/// Available Proposal Types
/// </summary>
public enum ProposalTypes
{
    Undefined = 0,

    /// <summary>
    /// Propose an administrative action.
    /// </summary>
    [Display(Name = "Administrative", Description = "Propose an administrative action.")]
    Administrative,

    /// <summary>
    /// Propose some other action.
    /// </summary>
    [Display(Name = "Miscellaneous", Description = "Propose some other action.")]
    Miscellaneous
}

I then made some helper methods like so:
    /// <summary>
    ///     A generic extension method that aids in reflecting
    ///     and retrieving any attribute that is applied to an `Enum`.
    /// </summary>
    public static TAttribute GetAttribute<TAttribute>(this Enum enumValue) where TAttribute : Attribute
    {
        var type = enumValue.GetType();
        var typeInfo = type.GetTypeInfo();
        var attributes = typeInfo.GetCustomAttributes<TAttribute>();
        var attribute = attributes.FirstOrDefault();
        return attribute;
    }

    /// <summary>
    /// Returns a list of possible values and their associated descriptions for a type of enumeration.
    /// </summary>
    /// <typeparam name="TEnum"></typeparam>
    /// <returns></returns>
    public static IDictionary<string, string> GetEnumPossibilities<TEnum>() where TEnum : struct
    {
        var type = typeof(TEnum);
        var info = type.GetTypeInfo();
        if (!info.IsEnum) throw new InvalidOperationException("Specified type is not an enumeration.");

        var results = new Dictionary<string, string>();
        foreach (var enumName in Enum.GetNames(type)
            .Where(x => !x.Equals("Undefined", StringComparison.CurrentCultureIgnoreCase))
            .OrderBy(x => x, StringComparer.CurrentCultureIgnoreCase))
        {
            var value = (Enum)Enum.Parse(type, enumName);
            var displayAttribute = value.GetAttribute<DisplayAttribute>();
            results[enumName] = $"{displayAttribute?.Name ?? enumName}: {displayAttribute?.Description ?? enumName}";
        }
        return results;
    }

The usage for this would be:
var types = Reflection.GetEnumPossibilities<ProposalTypes>();

What seems to be happening, though, is in the GetAttribute<TAttribute> method, when I attempt to get the attribute I'm looking for with:
var attributes = typeInfo.GetCustomAttributes<TAttribute>();

...the resultant value is an empty enumeration, thus returning back a null value.  From everything I've read, that should work just fine, and I should get back the associated DisplayAttribute... but I get back a null value.
What am I doing wrong?

A: The problem is that you are looking for attributes on the type ProposalTypes, not the values of the type. See this Question  for info on getting the attributes of the enum values.
More precisely in GetAttribute you'll need to get the member that represents your specific value and call GetCustomAttributes on that. Your method will then look like this:
public static TAttribute GetAttribute<TAttribute>(this Enum enumValue) where TAttribute : Attribute
{
    var type = enumValue.GetType();
    var typeInfo = type.GetTypeInfo();
    var memberInfo = typeInfo.GetMember(enumValue.ToString());
    var attributes = memberInfo[0].GetCustomAttributes<TAttribute>();
    var attribute = attributes.FirstOrDefault();
    return attribute;
}


text:
Q: Output state of the AM26LS32AIDR We are using AM26LS32AIDR in our design, as per the datasheet when input is open/floating, output should be high, but the output is in low state.
We are unable to trace out the issue.
We followed the schematic as below.

Edit:-
We are using this chip for controlling active low device. Default state should be high in order to disable the device.

A: Since the input is terminated with 100 ohms resistance, the difference between input pins is in the order of 2.5 mV due to internal pull-up and pull-down resistors in the chip. Both inputs will have about 2.5V of common mode voltage.
The voltage is not high enough to cross the hysteresis threshold to neither positive or negative direction, so output will be whatever it previously was, or rather, undefined after powering the chip up.
Even the datasheet table 1 confirms this, if voltage is between high and low thresholds, output is indeterminate.

A: In your schematic, the 2/3/4A/B inputs are open, so the 2Y/3Y/4Y outputs are high. The 1A/1B inputs are shorted through the termination resistor, so the output state is undefined.
This device does not have a failsafe feature for an idle bus. If you want that, you need to add pull-up/-down resistors to the bus lines.


text:
Q: Setting up Xamarin.Forms & Visual Studio 2019 to pair to mac ISSUE
An unexpected error occurred while checking the SSH configuration of
  IP Address. Could not find a part of the path
  C:\Users\MyName\AppData\Local\Xamarin\MonoTouch\hosts.key

I was able to SSH log in from CMD to the Macbook, but I'm unable to pair the mac to Visual Studio (VS) 2019. I've VS and xcode installed. The emulator works on VS on the mac. Why can't I pair the MAC to my windows PC. Am I supposed to create the MonoTouch folder & hosts.key?
What is the process to do this?
P.S. I understand I can do everything on the Mac, but I prefer my PC set up for development purposes.

A: I solved it by creating MonoTouch folder and then going to Tools > Options > Xamarin > Apple Accounts and trying to connect.

A: I solved this issue by creating the folder manually.

*

*Go to:
C:\Users\myuserhere\AppData\Local\Xamarin\

*Then create the folder manually
C:\Users\myuserhere\AppData\Local\Xamarin\MonoTouch\

A: I got a similar error message. I deleted all the content of the folder C:\Users[MyName]\AppData\Local\Xamarin\MonoTouch*.*
I believe the issue was caused by a newer version installed on the MAC.
After deleting the content of the folder above and trying to Pair to Mac in Visual Studio 2019 (PC), I was prompted to update the MonoTouch version installed on the PC.

A: I was missing the Monotouch folder. After creating it I was prompted to update the MonoTouch version installed on the PC. Fixed it!


text:
Q: How to install an old version of JDK in windows 7? I already have some version installed on the machine, 1.7 and 1.6.
Now I have the need to install version 1.5, but when I try to install an error occurs, speaking to uninstall the versions that I have the Java (JDK).
I have no chance because I have other applications using these versions, is there any possibility to do this without uninstalling these versions I already  have ?
Thank in advance !

A: Bypassing the installer is bit of work, but doable. How to extract Java from the EXE installer is described in this answer: https://stackoverflow.com/a/6571736/73652

A: The JDK is a package of tools for developing Java-based software.

*

*Check your system architecture in the control panel, i.e. 32 or 64-bit.

*Click on C → program folder → java folder.

If there is no JDK folder present, then follow the below steps:

*Search in Google JDK download.

*Scroll to bottom, and check for the system architecture of your system.

*Click the download link and wait till the download is finished.

*In downloads click on show in folder.

*Click on the JDK icon and click on next until the setup process is completed.

Please find this video along with steps for JDK Install.


text:
Q: Problem with installig package lxml Python using PyCharm GUI I have a problem with installing package named xmlx.
I type pip install xmlx in CMD, and everything was fine, it was successful.
But when i try to add this package in PyCharm I got error:

ERROR: Command errored out with exit status 1:
"Try to run this command from the system terminal. Make sure that you use the correct version of 'pip' installed for your Python interpreter located at 'D:\msys2\mingw64\bin\python.exe'."

What is wrong? I just have installed last version of pip and xmlx package...


text:
Q: How to build events aggregation service for high load system with DynamoDB I'm working on an Ad-tech system which serves millions of users.
Basically users (non anonymous users) can see different Ads that are being created by the marketing team.
Our marketing team want to be able to set some Frequency caps on those Ads (among other targeting rules they already have)
For example:

*

*"We should not show this ad for a user if he already seen/click this ad more than X times in the last Y days"

*Also ads can be grouped to campaigns, so rules like that are also possibile:
"We should not show this for a user if he viewed more than X times ads in this campaign in the last Y days".
Also our marketing might wanna know how many people viewed/click a specific add in the last Y days.
We have roughly 200K RPM and our responses should be very fast.
The smallest unit of time for our queries is one day and it will not change.
Few questions and thoughts:

*

*Is DynamoDB a good fit?

*I thought about creating a table for each event type (Click/View/Close..)

*What is the best way to configure the primary key?
I thought about settings the primary key as the user id and the sort key as a combination of the ad id and the current day {dd/mm/yyyy}

*I thought about use "ADD" operation to increase the counter when a user click/view/.. an Ad in a specific date. are they expensive operations? do I have an alternative?

*What is the best way I can use to also be able to query per ad and campaigns as well (for example: "all users views for all ads in campaign" or "get all ad views in the last 40 days) ) ?

*What other considerations should I take in mind?

Thanks a lot


text:
Q: Android - not receiving current location I am trying to get the current location of the user with the below set of code, however it am not receiving anything. Can anyone see what I am doing wrong.
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mNavigationDrawerFragment = (NavigationDrawerFragment)

        getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
            mTitle = getTitle();

            // Set up the drawer.
            mNavigationDrawerFragment.setUp(
                    R.id.navigation_drawer,
                    (DrawerLayout) findViewById(R.id.drawer_layout));

            //buildGoogleApiClient();

            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();

        }

    @Override
        public void onConnected(Bundle bundle) {
           Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                    mGoogleApiClient);
            if (mLastLocation != null) {

                String lat = String.valueOf(mLastLocation.getLatitude());
                String longg = String.valueOf(mLastLocation.getLongitude());

                Toast.makeText(MainActivity.this, "*************" + lat + "***************" + longg, Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onConnectionSuspended(int i) {

            Toast.makeText(MainActivity.this, "NOOOOPE", Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {

            Toast.makeText(MainActivity.this, "NOOOOPE", Toast.LENGTH_SHORT).show();

        }

I am not seeing any of toast's being displayed.
I am also getting the following errors in the logcat, but not sure if they are related.
08-25 16:32:51.388    1406-1406/? E/NetworkScheduler.SchedulerReceiver﹕ Invalid parameter app
08-25 16:32:51.388    1406-1406/? E/NetworkScheduler.SchedulerReceiver﹕ Invalid package name : Perhaps you didn't include a PendingIntent in the extras?

I have the following permissions in the manifest file:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.INTERNET" />

Cheers

A: So simple solution really. I just didnt call
mGoogleApiClient.connect();


text:
Q: ON DUPLICATE KEY UPDATE not working in online sql editors I'm learning SQL by using online code editors that can run the code, e.g. techonthenet.com or w3schools. The problem is, ON DUPLICATE KEY UPDATE command doesn't seem to work in those editors. Here's a link to one example https://www.techonthenet.com/sql/select_try_sql.php . I'm trying to update the customers database. If I use just INSERT command it seems to work fine, but when I try ON DUPLICATE KEY UPDATE I get this error:
SyntaxError: Parse error on line 2:
..., 'new first name')ON DUPLICATE KEY UPD
----------------------^
Expecting 'EOF', 'COMMA', 'RPAR', 'END', 'WHEN', 'ELSE', 'OUTPUT', 'GO', 'SEMICOLON', got 'ON'

My code looks like this:
INSERT INTO customers (customer_id, last_name, first_name)
VALUES ('4000', 'new last name', 'new first name')
ON DUPLICATE KEY UPDATE last_name = 'new last name', first_name = 'new first name';

Am I doing sth wrong or are those websites not fully functioning?

A: A MERGE INTO is standard Sql.
But it seems that upserts are not supported by techonthenet
MERGE INTO customers tgt
USING (
  SELECT
    4000 AS customer_id,
    'new last name' AS last_name,
    'new first name' AS first_name
) src ON (src.customer_id = tgt.customer_id)
WHEN MATCHED THEN
    UPDATE SET last_name = src.last_name
             , first_name = src.first_name
WHEN NOT MATCHED THEN
    INSERT (customer_id, last_name, first_name)
    VALUES (src.customer_id, src.last_name, src.first_name)


text:
Q: Php ftp_connect fails, FTP client connects (this question might not belong here, but on ServerFault, I don't know exactly where the problem comes from)
I'm trying to connect to an FTP server like this:
$con = ftp_connect( '86.xxx.xx.xxx', 21 ) or die("FTP connect error");

and it always throws me the error message.
I can connect like this to other FTP servers, but not this one. I can also connect to this one via an FTP client.
What server settings could be wrong that permit a client connect but not PHP?
Thanks for any help!

A: It seems my host was blocking remote FTP access to other servers. Oddly enough it allowed me to connect to my other servers at this host.


text:
Q: Por que incluir ficheiro html5.js Vejo que alguns sites incluem um arquivo chamado de html5.js, para qual finalidade eles incluem isso?
Algo como isso:
<!--[if lt IE 9]><script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]-->

A: Essa instrução garante que apenas os browsers que são do IE8 para baixo (fonte aqui) carreguem este arquivo .js.
Shim, de acordo com o Google, é

a washer or thin strip of material used to align parts, make them fit, or reduce wear.

A parte que importa é o make them fit, ou seja, "fazer encaixar". O HTMl5shim serve para que os browsers mais antigos entendam algumas tags novas do HTML5, que não existiam na época que eles foram implementados, como <article> e <section>. Leia mais sobre ele aqui.


text:
Q: In nested if-else conditions, control of C program not going further I have to find second largest number among given n numbers but without using array.  I decided to use loops but the problem is that control of program is not going to else if loop condition.  I made a constraint that if I enter -1 then loop will terminate, but after entering -1 the program terminated completely. I just want to know what is the problem with my loops or conditions, or am I doing it wrong?
#include <stdio.h>
int main()
{
    int i, j, max1 = 0, max2 = 0;
    for (j = 0; j <= 10; j++)
    {
        scanf("%d", &i);
        if (i == -1)
        {
            break;
        }
        else if ((i) >= (max1))
        {
            max2 = max1;
            max1 = i;
        }
        else if ((i) < (max1))
        {
            if ((i) > (max2))
            {
                max2 = i;
            }
        }
        else
        {
            return 0;
        }
    }
}

A: The else part within the for loop is not necessary. You can reduce the number of if-statements if you look at the second else if. i is definetely smaller than max1, so you can just use the condition of the nested if-clause.
Print out max2 and it works.
#include <stdio.h>
int main()
{
    int i, j, max1 = 0, max2 = 0;
    for(j = 0; j <= 10; j++)
    {
        scanf("%d",&i);
        if(i == -1)
        {
            break;
        }
        else if(i >= max1)
        {
            max2 = max1;
            max1 = i;
        }
        else if(i > max2)
        {
            max2 = i;
        }
    }
    printf("%d\n", max2);
    return 0;
}

A: This code looks like scary man , why do you use () so much, anyway your answer is : after you finds out maximum one you should just do
if( i > max2) max2 = i;

A: The approach used in your program is wrong. For example if the sequence of numbers contains all negative numbers then max2 will contain 0 though there is no such a value in the sequence.
And the program has incorrect logic. There is a premature exit from the program.
The valid code could look the following way
#include <stdio.h>

int main(void)
{
    const int N = 10;

    int max1, max2;
    int value;
    int count;
    int i;

    count = 0;

    for ( i = 0; i < N && scanf( "%d", &value ) > 0 && value != -1; i++, count++ )
    {
        if ( count == 0 || max1 < value )
        {
            if ( count != 0 ) max2 = max1;
            max1 = value;
        }
        else if ( count == 1 || max2 < value )
        {
            max2 = value;
        }
    }

    if ( count >= 2 ) printf( "The second maximum is equal to %d\n", max2 );
    else printf( "You have to enter more than one number\n");

    return 0;
}

For example for sequence
5 -3 1 0 -6 9 -9 8 -5

the output will be
The second maximum is equal to 8


text:
Q: Manually upsample/replicate matrix I'm trying to upsample a matrix by two by replicating another matrix, but i'm confused with the code, basically what i want is if:
Y = [1,2]

then the upsampled version would look like:
Up = [1,1,2,2;1,1,2,2]

What i've written so far is:
[row,col] = size(y)

Up = zeros(row*2,col*2);

for i = 1:2:row*2

     for j = 1:2:col*2

        Up(i, j) = Y(i,j);
        Up(i+1, j) = Y(i,j);
        Up(i, j+1) = Y(i,j);
        Up(i+1, j+1) = Y(i,j);

    end
end

but it says Index exceeds matrix dimensions, which i understand is because of the +1s but i'm not sure how else to go about doing this...

A: Data:
Y = [1,2]; % matrix
n = 2; % repetition factor

Solution using the repelem function (introduced in R2015a):
Up = repelem(Y,n,n);

Solution using indexing;
Up = Y(ceil(1/n:1/n:end), ceil(1/n:1/n:end));

Solution using a Kronecker product:
Up = kron(Y, ones(n))

A: The solution i ended up using is:
[row,col] = size(Y);
Up = zeros(row*2,col*2);
idx_row = 1;

for i = 1:D:row
    idx_col = 1;
    for j = 1:D:col

        Up(i:i+1, j:j+1) = repmat(repmat(Y(idx_row,idx_col),1,2),2,1);
       idx_col = idx_col + 1;
    end
     idx_row = idx_row + 1;
end


text:
Q: Quarkus. Testing with spy in the integration test I see that there is some limitation when it comes to mocking/spying in Quarkus.
The question is, how would I do something similar to this with the means that Quarkus provides? To spy on restClient and see how many times it was invoked.
    @QuarkusTest
    public class MyResourceTest {

      @Inject
      @RestClient
      MyRestClient restClient;

      @Ineject
      SomeServiceThatCallRestClient someService;

      @Test
      public void test() {
         restClientSpy = spy(restClient);

         someService.doSomething();     // it would call the restClient

         assertThat(clientSpy.times(), is(equalTo(1)));

      }