text:
Q: Azure Mobile App controller and Visual Studio Setup I am creating various controllers for my Azure mobile app. All the controllers will be using the same Azure SQL resource and blob storage , where can i define all the parameters so that i am repeating identical declarations all the time?

A:
All the controllers will be using the same Azure SQL resource and blob storage , where can i define all the parameters so that i am repeating identical declarations all the time?

Per my understanding, you could define a base class for your controllers and define your resources under the base class, then each controller
inherits the base class, then you could reuse the pre-defined resources under the base class. The following is the sample code, you could refer to it:
Base TableController:
public class TableControllerBase<TData>: TableController<TData> where TData : class, ITableData
{
    public CloudBlobClient BlobClient { get; }

    protected override void Initialize(HttpControllerContext controllerContext)
    {
        base.Initialize(controllerContext);
        MobileServiceContext context = new MobileServiceContext();
        DomainManager = new EntityDomainManager<TData>(context, Request);

        //initialize your resources (e.g. BlobClient)
        // Retrieve storage account from connection string.
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
            CloudConfigurationManager.GetSetting("StorageConnectionString"));
        // Create the blob client.
        CloudBlobClient BlobClient = storageAccount.CreateCloudBlobClient();
    }
}

For your TableController, you need to inherit the base class as follows:
public class TodoItemController : TableControllerBase<ToDoItem>
{
   //CURD
}

Additionally, I would recommend you follow adrian hall's book here about developing Azure Mobile Apps.


text:
Q: Alter collation of SQL Server Compact 4.0 Is it somehow possible to change collation of a .sdf-file? I have tried Management Studio 2008 but it only supports version 3.5, Management Studio 2012 does not support SQL Server Compact at all as far as I can see, the SQL Server Compact Toolbox for Visual Studio does not seem to offer this possibility and ALTER DATABASE also seems to be missing - is there any solution at all?

A: Yes, there is a solution, the SqlCeEngine Compact method allows you to do that from code (it effectivly recreates the database file), or you can do it via my sqlcecmd command line utility.
sqlcecmd -d "Data Source=C:\data\mydb.sdf" -z "Data Source=;LCID=1044"

Download from http://sqlcecmd.codeplex.com

A: I think that in order to change the collation on a .sdf file you will need to re-create it as a database in SQL Server:
USE master
GO
CREATE DATABASE "file.sdf" DATABASEPASSWORD '<Pwd>' COLLATE <the_Collation>
GO

If you have it already established as a database then you just need to alter the database:
USE master
GO
ALTER DATABASE <the_Database>
COLLATE <new_Collation>
GO

Then you can re-compact the database and it will have the collation you require.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to insert border around text in a Shiny app I would like to insert a border around my text similar to the image I placed attached.
Thank you very much!
Executable code below.
library(shiny)
library(shinythemes)

ui <- shiny::navbarPage(theme = shinytheme("flatly"),
                        title="Test", collapsible = TRUE,

                        tabPanel("",

                                 div(
                                   style =
                                     "height: 80px; background-color: #02BE7F; width: 100%; position: absolute; right:0;",
                                   h2(HTML("Project <b>Description</b>"),
                                      style="text-align:center;color: white"),
                                   hr(),

                                   div(
                                     style = "width: 70%; margin: auto;",
                                     h2(HTML("Lorem Ipsum is simply dummy text of the printing and typesetting industry.
                                      Lorem Ipsum has been the industry's standard dummy text ever since the 1500s"),
                                        style="text-align:justify")),
                                   tags$style(".navbar {margin-bottom: 0;}")
                                 )

                        ))

server <- function(input, output,session) {

}

shinyApp(ui = ui, server = server)

A: You can add the border to the div by adding the border properties (e.g. style = "border-style: solid; border-color: black;",
Using your code
div( style = "border-style: solid; border-color: black;",
   h2(HTML("Lorem Ipsum is simply dummy text of the printing and typesetting industry.Lorem Ipsum has been the industry's standard dummy text ever since the 1500s"), style="text-align:justify"))


text:
Q: How to get updated States at first time? I am using react states to store data that I am getting through axios from API. And I am changing some of the key values in my react states. those states are getting updated but not getting rendered those updated states.
constructor(props) {
        super(props);
        this.state = {
            NewOrders:[],
        }
        this.getNewOrders();
    }
    getNewOrders = async () => {
        let data = await api.get(`SellerOrdersAPI/${store.getState().auth.user.id}/`).then(({data})=>data);
        data.map(a =>
            this.get(a)
            )
        console.log(this.state.NewOrders)
        this.setState({NewOrders:data})
        this.testt()
    }
    get = async(a) => {
        let data1 = await itemApi.get(`/${a.item}/`).then(({data})=>data);
        a.item = data1.title
    }

here in console.log item value got updated but I can not render this newly updated value.
If I perform some operation on this component then this value (22) got changed by new value. but on start I can not access that.

A: Call getNewOrders in componentDidMount instead of constructor
componentDidMount(){
  this.getNewOrders();
}


text:
Q: Amazon Polly.Presigner Expected 0-1 arguments, but got 2 In an Angular app, I've setup an app that uses Amazon Polly to speak some unspeakable things based mainly on this.
I've had to import Polly as such, because I can't get aws-sdk to allow importing AWS anymore, which used to work:
import { config, CognitoIdentityCredentials, Polly } from "aws-sdk";

I have imported @types/node, and I have added ["node'] under types, under compilerOptions in the tsconfig.app.json file.
And I have added the below to polyfills.ts:
(window as any).global = window;

For the life of me, I can't figure out why the 'polly' bit in the below is throwing an error that reads: "Expected 0-1 arguments, but got 2."
It's preventing me from deploying a build.  What to do?!
speakText() {
    const polly = new Polly();
    // I don't know why 'polly' is bitching about expectations.
    const signer = new Polly.Presigner(this.speechParams, polly);

A: It seems the docs that I reference to create this, might be incorrect when it comes to adding the speechParams and polly as options for the Polly.Presigner.
Removing these options removed the errors and the app still works as intended.
  speakText() {
    const polly = new Polly({ apiVersion: "2016-06-10" });
    const signer = new Polly.Presigner();  // <== Removed options!

    signer.getSynthesizeSpeechUrl(
      this.speechParams,
      700,
      (error: Error, url: string) => {
        if (error) {
          console.log(error);
        } else {
          this.audio.src = url;
          this.audio.load();
        }
      }
    );
  }


text:
Q: Is it possible to create modular tests with playwright? I'm trying to make tests for a webapplication with Playwright test in JavaScript, but I would like to make them modular, to avoid repeating code. Let's say two tests need to fill a form. Instead of writing code to fill the form in both tests, is it possible to include a file in these two tests that contains filling the form?
import { test, expect } from '@playwright/test';

test.describe("", () => {
    //create a new page
  test.beforeAll( async ({ browser }) => {
    let page = await browser.newPage();

    await page.goto('https://www.example.com/');
  })

test('Do stuff', async () => {
import{test} from 'login.spec.mjs';
import{test} from 'fillform.spec.mjs';
})

login.spec.mjs
test('Login', async () => {

  // Click input[name="username"]
   await page.click('input[name="username"]');
//...
})

How do we call these functions, which are all named "test()"? Is this a good way to approach testing?

A: You can create a function called login() that does takes in parameters that will fill out the form.
For instance, you can do the following:
import { test, expect } from '@playwright/test';

function loginForm(page, input1, input2) {
     await page.goto('URL NAME HERE');
     await page.fill('#inputID1', input1);
     await page.fill('#inputID2', input2);
     await page.click('#loginButton');
}

test('Test Login for User 1', async ({page}) => {
     loginForm(page, 'username1', 'password1');
     // Do more stuff here

}

test('Test Login for User 2', async ({page}) => {
     await loginForm(page, 'username2', 'password2');
     // Do more stuff here

}

test('Test Login for User 3', async ({page}) => {
     await loginForm(page, 'username3', 'password3');
     // Do more stuff here

}


text:
Q: Lambda expression "cannot bind' So basically I am trying to get the heaviest animal on the farm, using lambdas. But I am stuck and I don't really get how to fix this.
The problem occurs in when calling the method killHeaviestAnimalOnFarm(); and printing this in.
(see main.cpp)
I have an Animal class
animal.h
#ifndef ANIMAL_H
#define ANIMAL_H
#include <string>
#include <iostream>
#include <vector>
#include <memory>
class Animal
  {
  public:
    Animal(std::string aType, const char & anSex, float aWeight);

    std::string getType() const {return type;}
    char getSex() const {return sex;};
    float getWeight() const {return weight;};
    void setWeight(float value) {weight = value;};

    void feed(int amount);
    Animal breed(Animal &aFather);

  private:
    const std::string type;
    const char sex;
    float weight;
  };

std::ostream & operator <<(std::ostream & os, Animal *an);

#endif // ANIMAL_H

animal.cpp
#include "animal.h"
#include "farm.h"

Animal::Animal(std::string aType, const char &aSex, float aWeight) :
  type{aType}, sex{aSex}, weight{aWeight}
  {
  }

void Animal::feed(int amount)
  {
  if (type == "sheep")
    weight += amount * 0.02f;
  else
    if (type == "cow")
      weight += amount * 0.05f;
  }

Animal Animal::breed(Animal &aFather)
  {
  float startWeight = (type == "cow") ? 35.0f : 6.5f;
  if (aFather.getType() == type && aFather.getSex() == 'M')
  return Animal(type, 'F', startWeight);
  }
std::ostream & operator <<(std::ostream & os, Animal *an)
  {
  std::string animal = an->getType();
  animal += "(";
  animal += an->getSex();
  animal +=  ")";
  os << animal <<  ", current weight = " << an->getWeight() << std::endl;
  return os;
  }

And a farm class
farm.h
#ifndef FARM_H
#define FARM_H
#include <string>
#include <vector>
#include <memory>
#include "animal.h"

class Farm
  {
  public:
    Farm(std::string farmName);

    std::string getName() const {return name;};

    void addAnimal(Animal &newAnimal);
    Animal killHeaviestAnimalOnFarm();

  private:
    const std::string name;
    std::vector<Animal> animals;

  };

#endif // FARM_H

Farm.cpp
#include "farm.h"
#include <algorithm>
#include <iostream>

Farm::Farm(std::string farmName):name{farmName}
  {

  }

void Farm::addAnimal(Animal &newAnimal)
  {
  animals.push_back(newAnimal);
  }

Animal Farm::killHeaviestAnimalOnFarm()
  {
  std::max_element(animals.begin(), animals.end(), [] (Animal first, Animal second)
  {
    return first.getWeight() < second.getWeight();
    });

  }

main.cpp
#include <iostream>
#include "farm.h"
#include <memory>

int main()
  {
  Farm meuhBoeh("Tradition in Technology");
  Animal * eva = new Animal("sheep", 'F', 35.2f);
  Animal * adam = new Animal("sheep", 'M', 45.6f);
  Animal * bella = new Animal("cow", 'F', 256.3f);
  Animal * taurus = new Animal("cow", 'F', 343.8f);
  meuhBoeh.addAnimal(*eva);
  meuhBoeh.addAnimal(*adam);
  meuhBoeh.addAnimal(*bella);
  meuhBoeh.addAnimal(*taurus);

  std::cout << "Animal slaughtered = " << meuhBoeh.killHeaviestAnimalOnFarm() << std::endl;

  }

I get following error:
/main.cpp:17: error: cannot bind 'std::basic_ostream<char>' lvalue to 'std::basic_ostream<char>&&'
   std::cout << "Animal slaughtered = " << meuhBoeh.killHeaviestAnimalOnFarm() << std::endl;
             ^

I can't seem to be able to find how to fix this..
EDIT (solution)
Animal.h
std::ostream & operator <<(std::ostream & os,const Animal &an);

Animal.cpp
Updated operator
std::ostream & operator <<(std::ostream & os, const Animal &an)
  {
  std::string animal = an.getType();
  animal += "(";
  animal += an.getSex();
  animal +=  ")";
  os << animal <<  ", current weight = " << an.getWeight() << std::endl;
  return os;
  }

Main.cpp
 std::cout << "Animal slaughtered = " << meuhBoeh.killHeaviestAnimalOnFarm() << std::endl;

Farm.cpp
(Tried using (Animal first, Animal second) also, but same error)
Animal Farm::killHeaviestAnimalOnFarm()
  {
  std::max_element(animals.begin(), animals.end(), [] (Animal &first, Animal &second)
  {
    return first.getWeight() < second.getWeight();
    });

  }

Error:
main.cpp:33: error: undefined reference to `operator<<(std::ostream&, Animal)'

A:
This answer is NOT complete since it solves the first two drafts of
  the question but failed to solve the final draft..

killHeaviestAnimalOnFarm returns an Animal not a string or any overloads of the operator <<.
I think you want something like;
auto killed=meuhBoeh.killHeaviestAnimalOnFarm();
std::cout << "Animal slaughtered = " << killed.name << std::endl;

After the question edited:
your overload take a pointer of Animal but you are trying to pass an object so either edit the overloading to be just Animal or better Animal const& rather than Animal* or pass the reference of the result to the std::cout. Of course, the first solution is preferable IMO.


text:
Q: Django - createsuperuser IntegrityError when i try to create superuser from shell or via manage.py or from Django-Admin page ; it throws error like :
IntegrityError at /admin/auth/user/add/
null value in column "link_karma" violates not-null constraint

Here is my models.py [User Part]:
class User_Profile(models.Model):

    user = models.OneToOneField(User)
    link_karma = models.IntegerField()
    comment_karma = models.IntegerField()
    avatar = models.CharField(max_length=100)

    def create_user_profile(sender,instance,created,**kwargs):
        if created:
            User_Profile.objects.create(user=instance)
    post_save.connect(create_user_profile, sender=User)

    def __unicode__(self):
        return self.user.username

i added fallowing line in to settings.py:
AUTH_PROFILE_MODULE = 'accounts.User_Profile'

before add this line ;  it was the same.
Note : i tried to change type of link_karma field to CharField. it is same.
Note : If any additional data needed ; i can add it.

A: Try setting blank=True, null=True for both link_karma and comment_karma. You're not passing any values to those fields so when your create statement tries to create the object, it doesn't know what to give link_karm hence the error.
As goliney correctly pointed out, you dont need email in your User_Profile model as User already has it.


text:
Q: Sqlite WHERE Clause using Parameters Trying to run a specific query using a where clause, here is what I have.
//ID is user input could be anything
SqliteParameter Identifier = new SqliteParameter ("@ID", ID);
string SQLText = "SELECT Email FROM Client WHERE Email=@ID;"
SqliteCommand Command = new SqliteCommand (SQLText, Database);
Command.Parameters.Add (Identifier);
string Result = Command.ExecuteScalar ().ToString ();
return Result;

The Error I get is:

SqliteSyntaxException: near "="; syntax error

What am I doing wrong?

A: I had a similar issue the other day. The issue that I was using keywords as objects.
To avoid syntax errors you might want to escape your objects, like:
SELECT [Email] FROM [Client] WHERE [Email] = @ID;


text:
Q: Access Query - Update Based on Latest Date I tried to locate an answer for this on other threads and was unable to find one. Please forgive me if it is covered in another thread.
I am relatively new to T-SQL, so please excuse if this is something I should already know.
I have a simple Access database with two tables: Contacts and Orders.
Contacts columns are ID (PK), FirstName, LastName, Address, a Status field (identifying if the customer is a "PC", which is who matters in this case), and also has a field for "Delayed." This field is to be "true" for those customers who haven't ordered in the last two months (and "false" for those who have).
The Orders table has the order numbers, along with Customer ID (PK related to Contacts), FirstName, LastName, Date.
I'm trying to write a query to update the "Delayed" field in the Contacts table, based on the latest order date from the Orders table. In this case, update that field to "false" for each PC customer if their latest order date falls within the last 60 days. It seemed pretty striaghtforward, but I'm obviously missing something here. I'm using a SELECT subquery to define the conditions. The query seems to be ignoring my conditions and wants to update ALL rows in the database. Any thoughts?
UPDATE Contacts SET Contacts.Delayed = False
WHERE EXISTS (SELECT Contacts.FirstName, Contacts.LastName, Contacts.Status, Max(Orders.Date)
FROM Contacts INNER JOIN Orders ON (Contacts.ID = Orders.ContactID)
GROUP BY Contacts.FirstName, Contacts.LastName, Contacts.Status
HAVING Max(Orders.Date) > Date()-60);

Any help would be greatly appreciated.

A: Because you are using exists, if the query returns a result, all contacts will have their delayed attribute set.
What you want to do is filter the results you are going to update, using a join. You will need a left join, because you want to find orders that haven't taken place within the last two months.
UPDATE  tblContacts
SET     Contacts.Delayed = False
FROM    Contacts tblContacts
        LEFT JOIN ( SELECT  Contacts.FirstName ,
                            Contacts.LastName ,
                            Contacts.Status ,
                            MAX(Orders.Date)
                    FROM    Contacts
                            INNER JOIN Orders ON ( Contacts.ID = Orders.ContactID )
                    GROUP BY Contacts.FirstName ,
                            Contacts.LastName ,
                            Contacts.Status
                    HAVING  MAX(Orders.Date) > Date() - 60
                  ) tbl ON tbl.Contacts.Id = tblContacts.Id
WHERE   tblContacts.Id IS NULL


text:
Q: Security concerns for using localStorage or chrome.storage inside Chrome Extensions I am building a chrome extension that needs to persist user sensible data.
I know that you can use HTML5 but it is vulnerable to XSS, and possibly other form of attacks.  I recently found out about chrome.storage but the docs say:

Confidential user information should not be stored! The storage area
  isn't encrypted.

Now my question is:

*

*Is there a secure way to store sensitive user data (i.e. a private key) in the browser?

A: The default content security policy pretty much protects you from XSS assuming you don't do anything really stupid. You could use some sort of a library to to encrypt local data and make users enter a passphrase to decrypt the data. The attack vectors at this point are more around malware on the computer and other people with physical access. Chrome extensions themselves are well protected from other sites.
Ultimately though, anything installed on the computer or having access to the computer has the potential to access the private info regardless of what you do. My recommendation would be make sure users are aware of how sensitive the data being stored is and that they need to maintain proper security precautions around getting access to the computer.


text:
Q: import cv2 dll load failed When I passed on win7 (python3)
pip install opencv-python

pip install opecncv-contrib-python

Can be correct import CV2
But when I installed opencv on window server 2008 R2 enterprise, this was the following error:
In [2]: import cv2
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-2-c8ec22b3e787> in <module>()
----> 1 import cv2

c:\python36\lib\site-packages\cv2\__init__.py in <module>()
      1 import importlib
      2
----> 3 from .cv2 import *
      4 from .data import *
      5

ImportError: DLL load failed: The specified module could not be found.

I tried installing C++ Redistributable Package (all versions) and downloading WHL files still can't solve the error.
C:\Users\Administrator\Desktop>ipython
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD6
4)]
Type 'copyright', 'credits' or 'license' for more information
IPython 6.5.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: import cv2
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-1-c8ec22b3e787> in <module>()
----> 1 import cv2
ImportError: DLL load failed: The specified module could not be found.

My guess is definitely a system problem, but I checked the data and found that the prototype of the server 2008 R2 system is Win7, and I've installed what I can hold, and still can't solve the problem.
So I wanted to know what the real reason for this mistake was, and if I could figure it out and fix it.
So what should I do to ask for help

A: This can happen if you are using windows 10 N distribution, the N distributions does not come pre installed with windows media feature pack, which is required after OpenCV version 3.4 and onwards.
The preferred solution is to install the feature pack at : https://www.microsoft.com/en-us/software-download/mediafeaturepack
Be careful to choose the version that works with your current version of windows.
If that is not an option, fall back to an earlier version of OpenCV that does not have dll dependencies, you can do that by:pip install opencv-python=3.3.0.9
Since windows rolled out it's N version this problem has been seen at many places, and has many impacts across the windows environment, the fastest way to identify if you have this problem is open youtube in Edge browser, if it says HTML5 media plugin not found, this is the problem.
Neither conda nor any other virtual manager running python natively on windows will solve this unless you install the feature pack. However WSLbash and VMWare will run cv2 without feature pack.

A: Try first installing Anaconda, then install opencv with conda. For example opening Conda Prompt in windows and type conda install opencv, instead of using pip. That did the trick for me.


text:
Q: C# search with resemblance / affinity Suppose We have a, IEnumerable Collection with 20 000 Person object items.
Then suppose we have created another Person object.
We want to list all Persons that ressemble this Person.
That means, for instance, if the Surname affinity is more than 90 % , add that Person to the list.
e.g. ("Andrew" vs "Andrw")
What is the most effective / quick way of doing this?
Iterating through the collection and comparing char by char with affinity determination? OR?
Any ideas?
Thank you!

A: You may be interested in:
Levenshtein Distance Algorithm
Peter Norvig - How to Write a Spelling Corrector
(you'll be interested in the part where he compares a word against a collection of existing words)

A: Depending on how often you'll need to do this search, the brute force iterate and compare method might be fast enough.  Twenty thousand records really isn't all that much and unless the number of requests is large your performance may be acceptable.
That said, you'll have to implement the comparison logic yourself and if you want a large degree of flexibility (or if you need find you have to work on performance) you might want to look at something like Lucene.Net.  Most of the text search engines I've seen and worked with have been more file-based, but I think you can index in-memory objects as well (however I'm not sure about that).
Good luck!

A: I'm not sure if you're asking for help writing the search given your existing affinity function, or if you're asking for help writing the affinity function.  So for the moment I'll assume you're completely lost.
Given that assumption, you'll notice that I divided the problem into two pieces, and that's what you need to do as well.  You need to write a function that takes two string inputs and returns a boolean value indicating whether or not the inputs are sufficiently similar.  Then you need a separate search a delegate that will match any function with that kind of signature.
The basic signature for your affinity function might look like this:
bool IsAffinityMatch(string p1, string p2)

And then your search would look like this:
MyPersonCollection.Where(p => IsAffinityMatch(p.Surname, OtherPerson.Surname));

A: I provide the source code of that Affinity method:
        /// <summary>
        /// Compute Levenshtein distance according to the Levenshtein Distance Algorithm
        /// </summary>
        /// <param name="s">String 1</param>
        /// <param name="t">String 2</param>
        /// <returns>Distance between the two strings.
        /// The larger the number, the bigger the difference.
        /// </returns>
        private static int Compare(string s, string t)
        {
            /* if both string are not set, its uncomparable. But others fields can still match! */
            if (string.IsNullOrEmpty(s) && string.IsNullOrEmpty(t)) return 0;

            /* if one string has value and the other one hasn't, it's definitely not match */
            if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(t)) return -1;

            s = s.ToUpper().Trim();
            t = t.ToUpper().Trim();

            int n = s.Length;
            int m = t.Length;
            int[,] d = new int[n + 1, m + 1];

            int cost;

            if (n == 0) return m;
            if (m == 0) return n;

            for (int i = 0; i <= n; d[i, 0] = i++) ;
            for (int j = 0; j <= m; d[0, j] = j++) ;

            for (int i = 1; i <= n; i++)
            {
                for (int j = 1; j <= m; j++)
                {
                    cost = (t.Substring(j - 1, 1) == s.Substring(i - 1, 1) ? 0 : 1);

                    d[i, j] = System.Math.Min(System.Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1),
                              d[i - 1, j - 1] + cost);
                }
            }

            return d[n, m];
        }

that means, if 0 is returned, 2 strings are identical.


text:
Q: .Net Socket SendTo command not Receiving via UDP on a Raspberry Pi 4 running Buster I'm using a shared class library (private, not a public one) that has a method that searches local networks for a Manufacturers Test box in order to commission the device my software is running on.
I am running a .Net 6 application on a Raspberry Pi 4 running Buster.
The search uses .Net Sockets, using the SendTo command and waits for the responses.  This works running from Visual Studio on my Windows PC, it also works on a different but similar application on a Raspberry PI 3 running Stretch, using the same method.
But on the PI 4, I simply don't get any responses.  I've looked on WireShark and it seems to be communicating but I'm not overly sure as I don't really understand this level of networking, but there are no obvious errors being reported at any stage.
public List<EthernetDevice> SearchLocalNetwork()
    {
        //EthernetDevice newDevice = new EthernetDevice();
        var devices = new List<EthernetDevice>();

        foreach (var adapter in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces())
        {
            foreach (var address in adapter.GetIPProperties().UnicastAddresses)
            {
                // We're only interested in IPv4 addresses for now
                if (address.Address.AddressFamily != AddressFamily.InterNetwork)
                {
                    continue;
                }

                // Ignore loopback addresses (e.g., 127.0.0.1)
                if (IPAddress.IsLoopback(address.Address))
                {
                    continue;
                }

                try
                {
                    var ethernetSearch = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    ethernetSearch.ExclusiveAddressUse = false;

                    var data = new byte[4];
                    var bytBuffer = new byte[256];

                    var broadcastAddress = address.Address.GetAddressBytes();

                    /*if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                        {
                            broadcastAddress[0] = 169;
                            broadcastAddress[1] = 254;

                        }*/

                    // broadcastAddress[2] = 255;
                    broadcastAddress[3] = 255;
                    var newAddress = new IPAddress(broadcastAddress);
                    Console.WriteLine("Broadcast Address: {0}", newAddress);

                    IPEndPoint responder = new IPEndPoint(IPAddress.Any, 0);

                    // IPEndPoint responder = new IPEndPoint(newAddress, 0);
                    EndPoint rep = (EndPoint)responder; // this will be IP Address and Port number: 192.168.10.123:30716
                    int i, endtime;

                    //////////////////////////////////////////////////////////////
                    // Set up a UDP Socket which can broadcast to entire network
                    //////////////////////////////////////////////////////////////
                    ethernetSearch.EnableBroadcast = true;
                    ethernetSearch.ReceiveTimeout = 8000;
                    ethernetSearch.ExclusiveAddressUse = false;

                    // Define an EndPoint which can be used to broadcast. Port 0x77FE
                    // is the configuration port of the XPort Direct.
                    //
                    // IPEndPoint ep = new IPEndPoint(System.Net.IPAddress.Broadcast, 0x77FE);
                    var ep = new IPEndPoint(newAddress, 0x77FE);

                    // Set up a message to send, requesting configuration register.
                    // Message F8 does this, and should initiate a reply of F9 followed
                    // by the register details in HEX format
                    for (i = 0; i < 4; data[i++] = 0);
                    data[3] = 0xF8;

                    // Broadcast the message
                    ethernetSearch.SendTo(data, ep);

                    // The following block of code will run continually until
                    // no more replies are received. At this point, a Socket
                    // Exception will be thrown, and then caught in the Catch
                    // statement. Initially the receive timeout is set to 7000ms
                    // as it takes a while for the broadcast message to go out
                    // and the devices to initiate a reply. After that, they
                    // respond very quickly in succession, so the receive timeout
                    // is reduced to 700ms to reduce the waiting time after the last
                    // reply is received
                    //
                    // The IP Address which sent the response is extracted from the Responding
                    // End Point (REP).
                    endtime = Environment.TickCount + 7000;

                    while (true) // this loop will be exited by the 'break' statement when no more replies are received
                    {
                        while (Environment.TickCount < endtime && ethernetSearch.Available == 0)
                        {
                            Thread.Sleep(2);
                        }

                        if (ethernetSearch.Available > 0)
                        {
                            ethernetSearch.ReceiveFrom(bytBuffer, ref rep);
                        }
                        else
                        {
                            break;
                        }

                        if (bytBuffer[3] == 0xF9) // verify reply code - response to F8 is F9
                        {
                            var iPAdd = rep.ToString().Substring(0, rep.ToString().IndexOf(':'));

                            var port = bytBuffer[25] * 256 + bytBuffer[24];
                            iPAdd += ":" + port;

                            var isDhcp = false;

                            if (bytBuffer[4] == 0 && bytBuffer[5] == 0 && bytBuffer[6] == 0 && bytBuffer[7] == 0)
                            {
                                isDhcp = true;
                            }

                            var device = new EthernetDevice();
                            device.IPAddress = iPAdd.Split(':')[0];
                            device.Port = port;
                            device.DHCP = isDhcp;
                            device.Gateway = bytBuffer[16] + "." + bytBuffer[17] + "." + bytBuffer[18] + "." +
                                             bytBuffer[19];
                            device.BaudRate = 2;
                            devices.Add(device);

                            //if (devices.FirstOrDefault(x => x.IPAddress == device.IPAddress) == null)
                            //{
                            //    devices.Add(device);
                            //}

                            // Set up new end time for waiting for next device
                            endtime = Environment.TickCount + 700;
                        }
                    }

                    // sort the resulting list by IP Address order
                    ethernetSearch.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }

        return devices;
    }

Its a bit rough but returns a list of test boxes across any networks it detects.
Does anyone have any ideas, is this a OS/Buster issue or a code issue?  I'm thinking its more OS at this stage.
I did try setting the buffer sizes in sysctl.conf but is didn't help.
net.core.rmem_max = 16777216
net.core.wmem_max = 4194304

A: The issue was solved by resetting all UFW rules on the device.
sudo ufw reset


text:
Q: How to compare two Integers in java I want to compare elements in two list using < > ==
Is it the right way  to use intValue()?
List<Integer> a = new ArrayList<Integer>();
a.add(129);

List<Integer> b = new ArrayList<Integer>();
b.add(128);

if(a.get(0).intValue() > b.get(o).intValue()) {
   // something
}

A: You're making it the right way.
As stated in the comments, you could also you compareTo().
An alternative to compareTo() is equals() which won't throw a NullPointerException in the case where the object is null.

A: Your way is correct. But with a small correction.
1)
a.get(0).intValue() == b.get(0).intValue()

2)
a.get(0).equals(b.get(0))

This is the problem in your code, you have to get(0), instead of get(1). Remember, in java it always start with 0.
Values can be compared using equals() or CompareTo method as well.
import java.util.ArrayList;
import java.util.List;

public class TestClass {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        List<Integer> a= new ArrayList<Integer>();
        a.add(128);

        List<Integer> b = new ArrayList<Integer>();
        b.add(128);

        if(a.get(0).intValue() == b.get(0).intValue()){
            System.out.println("success");
        }else{
            System.out.println("failure");
        }
        if(a.get(0).equals(b.get(0))){
            System.out.println("success");
        }else{
            System.out.println("failure");
        }

    }

}


text:
Q: Is there anywhere a tutorial of how to publish a book with LaTeX? I am looking for all the tips and what should be considered specifically for the layout of professionally looking books.

A: The memoir package, more specifically its documentation, is written as an introduction to professional layouts. It contains a lot of examples of different styles of books and how to obtain them. It can be a good start :).


text:
Q: Connecting the domain obtained from godaddy to the service running in Google Cloud Run I bought a domain from godaddy for my service running on Gcr, for example: foo.com (I didn't know about the existence of Cloud Domains). In order to establish a domain relationship with my service, I first verified my domain over https://www.google.com/webmasters/verification/home
Then I added a record via Google cloud console -> Network Services - Cloud DNS and added the incoming records to my records in GoDaddy.

and when I check my Domain Name on https://dnschecker.org/, the results do not confirm the operation.

However, even though 16 hours have passed, my transaction is still not confirmed.

How can I confirm this domain? What is a wrong or missing transaction?

A: I've done it! But by using cloudrun only. I mapped my domain via godaddy by following these steps medium.com/@sandymadaan/domain-mapping-in-gcp-1126a8d29202.
Note:
Remove all the default A and AAAA in godaddy before putting all your DNS records from cloudrun


text:
Q: Игра "Smile" Доброго времени суток. Пишу игру "smile" (по типу танчиков на 8 битке ) - только намного проще , так вот смайлик враг выходит за пределы игрового поля , бьюсь с этой задачей несколько часов , посмотрите код свежим взглядом , помогите найти ошибку . Заранее благодарю.
Код:
#include<iostream>
#include <conio.h>
#include <Windows.h>
using namespace std;
void main()
{
    COORD smileCoord = { 35, 10 };//координаты смайла
    COORD enemyCoord1 = { 10, 5 };//координаты первого врага
    COORD enemyCoord2 = { 45, 15 };// координаты 2-го врага
    HANDLE hndl = GetStdHandle(STD_OUTPUT_HANDLE);//получаем дескриптор консоли
    SetConsoleTextAttribute(hndl, FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_GREEN);//устанавливаем  белый цвет
    const int Y = 20, X = 70, MAX_SCORE = 400;
    int scores = 0, lives = 3;
    enum {SPACE, WALL, SCORES, LIVES, ESCAPE=27};
    enum DIRECTIONS{LEFT, RIGHT, UP, DOWN};
    DIRECTIONS enemyDir1 = DOWN;
    DIRECTIONS enemyDir2 = RIGHT;
#pragma region Game_field
    int a[Y][X] = {
        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
        1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
        1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
        1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
        1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
        1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
        1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
        1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
        1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
        1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
        1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
        1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
        1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
        1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
        1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
        1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
        1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
        1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
        1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
    };
#pragma endregion
#pragma region Draw_game_field
    for (int i = 0; i < Y; i++)
    {
        for (int j = 0; j < X; j++)
        {
            switch (a[i][j])
            {
            case SPACE: cout << ' ';
                break;
            case WALL: cout << '#';
                break;
            case SCORES:
                SetConsoleTextAttribute(hndl, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
                cout << '$';
                SetConsoleTextAttribute(hndl, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE);
                break;
            }
        }
        cout << '\n';
    }
#pragma endregion

    COORD scoresCoord = {5, 22};
    SetConsoleCursorPosition(hndl, scoresCoord);
    cout << "Scores: " << scores;
    COORD livesCoord = { 20, 22 };
    SetConsoleCursorPosition(hndl, livesCoord);
    cout << "Lives: " << lives;

    while (true)//Основной игровой цикл
    {
        //движение первого врага
        SetConsoleCursorPosition(hndl, enemyCoord1);
        cout << ' ';
        switch (enemyDir1)
        {
        case UP:
            if (a[enemyCoord1.Y - 1][enemyCoord1.X] == WALL) enemyDir1 = DOWN;
            else enemyCoord1.Y--;
            break;
        case DOWN:
            if (a[enemyCoord1.Y + 1][enemyCoord1.X] == WALL) enemyDir1 = UP;
            else enemyCoord1.Y++;
            break;
        }
        // движение второго врага
        SetConsoleCursorPosition(hndl, enemyCoord2);
        cout << ' ';
        switch (enemyDir2)
        {
        case LEFT:
            if (a[enemyCoord2.X - 1][enemyCoord2.Y] == WALL) enemyDir2 = RIGHT;
            else enemyCoord2.X--;
            break;
        case RIGHT:
            if (a[enemyCoord2.X + 1][enemyCoord2.Y] == WALL) enemyDir2 = LEFT;
            else enemyCoord2.X++;
            break;
        }
        //Проверка столкновения с врагом
        if (smileCoord.X == enemyCoord1.X && smileCoord.Y == enemyCoord1.Y)
        {
            lives--;
            SetConsoleCursorPosition(hndl, livesCoord);
            cout << "Lives: " << lives;
        }
        if (smileCoord.X == enemyCoord2.X && smileCoord.Y == enemyCoord2.Y)
        {
            lives--;
            SetConsoleCursorPosition(hndl, livesCoord);
            cout << "Lives: " << lives;
        }
        SetConsoleCursorPosition(hndl, enemyCoord1);
        SetConsoleTextAttribute(hndl, FOREGROUND_RED | FOREGROUND_INTENSITY);
        cout << (char)2;
        SetConsoleTextAttribute(hndl, FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_GREEN);
        SetConsoleCursorPosition(hndl, enemyCoord2);
        SetConsoleTextAttribute(hndl, FOREGROUND_RED | FOREGROUND_INTENSITY);
        cout << (char)2;
        SetConsoleTextAttribute(hndl, FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_GREEN);
        if (_kbhit())//если нажата любая клавиша
        {
            SetConsoleCursorPosition(hndl, smileCoord);
            cout << ' ';
            switch (_getch())//анализируем код нажатой клавиши
            {
            case 'w':
            case 'W':
                if (a[smileCoord.Y-1][smileCoord.X] != WALL) smileCoord.Y--;
                break;
            case 's':
            case 'S':
                if (a[smileCoord.Y+1][smileCoord.X] != WALL) smileCoord.Y++;
                break;
            case 'a':
            case 'A':
                if (a[smileCoord.Y][smileCoord.X-1] != WALL) smileCoord.X--;
                break;
            case 'd':
            case 'D':
                if (a[smileCoord.Y][smileCoord.X+1] != WALL) smileCoord.X++;
                break;
            case ESCAPE://Escape
                exit(1);
            }
            //Проверка столкновения с врагом
            if (smileCoord.X == enemyCoord1.X && smileCoord.Y == enemyCoord1.Y)
            {
                lives--;
                SetConsoleCursorPosition(hndl, livesCoord);
                cout << "Lives: " << lives;
            }
            if (smileCoord.X == enemyCoord2.X && smileCoord.Y == enemyCoord2.Y)
            {
                lives--;
                SetConsoleCursorPosition(hndl, livesCoord);
                cout << "Lives: " << lives;
            }

            switch (a[smileCoord.Y][smileCoord.X])
            {
            case SCORES:
                scores += 100;
                a[smileCoord.Y][smileCoord.X] = 0;
                SetConsoleCursorPosition(hndl, scoresCoord);
                cout << "Scores: " << scores;
                if (scores == MAX_SCORE)
                {
                    COORD coord = {35, 12};
                    SetConsoleCursorPosition(hndl, coord);
                    cout << "CONGRATULATIONS!!!";
                    _getch();
                    exit(1);
                }
                break;
            }
        }
        if (lives == 0)
        {
            system("cls");
            COORD coord = { 35, 12 };
            SetConsoleCursorPosition(hndl, coord);
            cout << "G A M E  O V E R!";
            _getch();
            exit(1);
        }
        SetConsoleCursorPosition(hndl, smileCoord);//Позиционируем смайл
        SetConsoleTextAttribute(hndl, FOREGROUND_GREEN|FOREGROUND_INTENSITY);//задаем цвет и интенсивность смайла
        cout << (char)1;//выводим смайл
        Sleep(100);
    }

    SetConsoleTextAttribute(hndl, FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_GREEN);//возвращаем белый цвет
    _getch();
}

A: Попробуйте сравнить координаты с 0 перед тем, как вычитать 1
case 'W':
                if (a[  smileCoord.Y-1  ][smileCoord.X] != WALL)


text:
Q: Prediction with OLS better then prediction with lasso or ridge I did a regression on a train data set with 7000 observations and 50 explenatory variables with ols ridge and lasso. The lambda was chosen via cross validation.
After that i wanted to compare the prediction accuracy of the 3 models by predict values of a test data set.
I thought i would get a better prediction with lasso and ridge but thats not the case.
How this could be ?What could be the possible reasons?
At the beginning i computed the vif for the ols model and had 3 variables where the vif was over 15. I thought when i have multicollinarity ridge and lasso will allways perform better ?


text:
Q: How can I pass a List from a View to a Controller? If my Model has a property List<MyType> MyProperty (where MyType is a complex type), how can I pass this to a Controller Action?
e.g.
[HttpGet]
public ActionResult UpdateAll(List<MyType> thingy)

If I just use
Model.MyProperty

It turns up in the controller as null
I can't bend my mind round the examples I can find - but what I can pick up leads me to think I should state that my view is NOT based on an IEnumerable<MyType> (nor can/should it be).
EDIT: what I want to do with it is
 Update All

EDIT2: Is it as simple as that I need to serialize it before passing it? But I'd have thought that would have very quickly come up as an answer/search result...

A: Lists are treated a little bit differently in MVC, in order to post data back from a list you need to first render the UI for each item in that list i.e.
@model MyComplexModel

@foreach (MyType item in Model.MyProperty)
{
    @Html.EditorFor(x => item.SomeProperty)
    @Html.EditorFor(x => item.AnotherProperty)
}

Using the *For helpers will generate the appropriate HTML which allows the model binder to know which items in the list it is updating. If you inspect the DOM you should find the HTML for your list items looks something like
<input type="text" name="Model.MyProperty[0].SomeProperty" />
<input type="text" name="Model.MyProperty[0].AnotherProperty" />
<input type="text" name="Model.MyProperty[1].SomeProperty" />
<input type="text" name="Model.MyProperty[1].AnotherProperty" />
...

A: I have the data that is in my View in a javascript object.  In case this is a direction you're going...
I have a toDictionary method...
(function ($) {
    $.extend({
        toDictionary: function (data, prefix, includeNulls) {
            /// Flattens an arbitrary JSON object to a dictionary that Asp.net MVC default model binder understands.
            /// <param name="data" type="Object">Can either be a JSON object or a function that returns one.</data>
            /// <param name="prefix" type="String" Optional="true">Provide this parameter when you want the output names to be prefixed by something (ie. when flattening simple values).</param>
            /// <param name="includeNulls" type="Boolean" Optional="true">Set this to 'true' when you want null valued properties to be included in result (default is 'false').</param>

            // get data first if provided parameter is a function
            data = $.isFunction(data) ? data.call() : data;

            // is second argument "prefix" or "includeNulls"
            if (arguments.length === 2 && typeof (prefix) === "boolean") {
                includeNulls = prefix;
                prefix = "";
            }

            // set "includeNulls" default
            includeNulls = typeof (includeNulls) === "boolean" ? includeNulls : false;
            var result = [];
            _flatten(data, result, prefix || "", includeNulls);

            return result;
        }
    });
}

Here is my ajax call where roles is a javascript Object():
var data = { roleGroups: roles };
$.ajax({
    url: '/Controller/Action',
    type: 'post',
    dataType: 'json',
    data: $.toDictionary(data)
})

And I'm then using a, IList on the server...
[HttpPost]
public virtual ActionResult EditRoleGroups(IList<RoleGroupViewModel> roleGroups)
{
    //do stuff
}


text:
Q: Type '(args: any) => Element' has no properties in common with type Story I'm building a React library using Typescript and Storybook. The component works fine when compilied and imported, but in the compiling process, the *.stories.tsx files fail. Here are the corresponding files:
Button.tsx
import React, {forwardRef, useEffect, useImperativeHandle, useState} from 'react'
import ButtonPropTypes from './ButtonPropTypes'

const Button = forwardRef((props: InferProps<typeof ButtonPropTypes>, buttonRef) => {...}

ButtonPropTypes.ts
import PropTypes from 'prop-types'

export default {
  to: PropTypes.string,
  label: PropTypes.any,
  children: PropTypes.any,
  disabled: PropTypes.bool,
  loading: PropTypes.bool,
  onClick: PropTypes.func,
  state: PropTypes.object,
  type: PropTypes.string.isRequired,
  use: PropTypes.string.isRequired
}

I omitted a few proptypes for simplicity.
Button.stories.tsx
import React from 'react'
import {Story, ComponentMeta} from '@storybook/react'
import Button from './Button'
import ButtonPropTypes from './ButtonPropTypes'
import {InferProps} from 'prop-types'

type ButtonPropsInterface = InferProps<typeof ButtonPropTypes>

export default {
  title: 'RecylinkReactComponents/Button',
  component: Button
} as ComponentMeta<typeof Button>

const Template: Story<ButtonPropsInterface> = args => <Button {...args} />
// This line causes the first error: Type '(args: any) => Element' has no properties
// in common with type 'Story<ButtonPropsInterface>'

export const TestButton = Template.bind({})
// Also this line:  Property 'bind' does not exist on type 'Story<ButtonPropsInterface>'
TestButton.args = {
  label: 'Label',
  onClick: () => console.log('Clicked'),
  type: 'button',
  use: 'function'
}

rollup.config.js
import resolve from '@rollup/plugin-node-resolve'
import commonjs from '@rollup/plugin-commonjs'
import typescript from '@rollup/plugin-typescript'
import postcss from 'rollup-plugin-postcss'
import dts from 'rollup-plugin-dts'

import {terser} from 'rollup-plugin-terser'
import peerDepsExternal from 'rollup-plugin-peer-deps-external'

const packageJson = require('./package.json')

export default [
  {
    input: 'src/index.ts',
    output: [
      {
        file: packageJson.main,
        format: 'cjs',
        sourcemap: true
      },
      {
        file: packageJson.module,
        format: 'esm',
        sourcemap: true
      }
    ],
    plugins: [
      peerDepsExternal(),
      resolve(),
      commonjs(),
      typescript({
        tsconfig: './tsconfig.json',
        exclude: [
          /\.test.((js|jsx|ts|tsx))$/,
          /\.stories.((js|jsx|ts|tsx|mdx))$/
        ]
      }),
      postcss(),
      terser()
    ],
    context: 'window'
  },
  {
    input: 'dist/esm/index.d.ts',
    output: [{file: 'dist/index.d.ts', format: 'esm'}],
    plugins: [dts()],
    external: [/\.css$/],
    context: 'window'
  }
]

tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,

    "jsx": "react",
    "module": "ESNext",
    "declaration": true,
    "declarationDir": "types",
    "sourceMap": true,
    "outDir": "dist",
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "emitDeclarationOnly": true,
    "allowJs": true,
    "noImplicitAny": false
  }
}

And the .storybook/main.js file
module.exports = {
  "stories": [
    "../src/**/*.stories.mdx",
    "../src/**/*.stories.@(js|jsx|ts|tsx)"
  ],
  "addons": [
    "@storybook/addon-links",
    "@storybook/addon-essentials",
    "@storybook/addon-interactions"
  ],
  "framework": "@storybook/react",
  "core": {
    "builder": "@storybook/builder-webpack5"
  }
}


text:
Q: Bulk emails with Mandrill I am considering implementing Mandrill for a fully customised email component and have 1 quick question if I may as I can't find the answer in any of the documentation:
Using the Mandrill API, if I send a single request to the API with the preserve_recipients option set to false and the async option set to true with a single array with 750 recipients in it, will Mandrill send 1 email with 750 recipients hidden from each other or will it que it and send 750 individual emails?
I would prefer the latter but I am trying to save server time at my end by making 750 API calls to send individual emails when Mandrill's server already does this.
Many thanks!

A: I have heard back from Mandrill on this and this is what they said:

You're correct that it would send 750 separate / individual emails

I am still yet to test it but it looks promising.
Just in case anyone else out there had the same question.
Lee


text:
Q: How do I list WAF objects that do not have any resources using the AWS CLI? I'd like to list all objects in WAF that do not have resources connected to them using the aws cli in my terminal.
Is there anyway I can do this using the aws wafv2 list-web-acl --name --scope <value> AWS cli command with other perimeters?
Thanks

A: Looks like there's no cmd for that so I created a script to have the results placed in a file. Might come handy if needed by anyone on here
#!/bin/bash

#list the web acl objects with their corresponding arn and save it in a file
aws wafv2 list-web-acls --scope REGIONAL | grep "ARN" > output.txt

# Next generate only the ARN nos and save output in a seperate file
awk -F\" '{print $4}' output.txt > input.txt

#Create a file to store ARN numbers together with their resources attached
touch resources.txt

#loop through each line and  generate the resource attached to an ARN object based on its ARN no
while read p; do
  echo $p >> resources.txt && \
  aws wafv2 list-resources-for-web-acl --web-acl-arn $p >> resources.txt && \
  echo ------------------------ >> resources.txt
  #echo -e ' \t ' >> resources.txt
done < input.txt

#remove unwanted files
rm input.txt output.txt

#list webacl objects that do not have resources attached to them
grep -B 3 "\[\]" resources.txt | grep "webacl"

#remove any files left
rm resources.txt


text:
Q: How to make `goapp serve` ignore changes in the .git folder? When running the development server for Google App Engine Go I read the following console prints:
INFO DATE module.py:427 [default] Detected file changes:
    .git
    .git\logs\HEAD

But that's just noise, how can I suppress that?


text:
Q: Is it possible to use a skeleton example as a pending in RSpec? I want to use a skeleton(empty) example as a pending. Normally, it is treated as succeeded(Green), but this occurs misunderstandings, like this.
describe "" do
  # This is displayed as **not pending** but succeeded.
  it "A skeleton example 1." do
  end

  # If you want to display result as a pending,
  # need to implement the procedure explicitly.
  it "A skeleton example 2." do
    skip "Not Implemented."
  end
end

To writing skip ... each time is very painful... So I avoid it.

A: To flag example as pending - just remove do..end block.
it 'is not pending example' do
end

it 'is pending example'


text:
Q: Excel returning a False response =IF(B12<>"",(IF(U12="Subscription","Subscribe",IF(U12="T.E.H.","Subscribe",IF(U12="ESA","Subscribe",IF(U12="Perpetual","Buy",IF(U12=" "," ")))))))
I get a "False" value in the cell with this formula in it when the value in U12 is not one of the options and I want to get a blank
Appreciate any help
Thanks

A: Change this: IF(U12=" ", " ") to this: IF(U12=" ", " ", "").  Here's a demo in Google Sheets, but the formulas are the same.
https://docs.google.com/spreadsheets/d/10iFqq0PNt9VhGKMPLCxsI1df0x4nDSxCaCGSdEEktO8/edit#gid=0
However, I don't think this is exactly right.  For one thing, it looks like this clause:
IF(U12=" ", " ")

is only there to try to generate the blank you are looking for.  If that's the case, then change it to:
IF(U12=" ", " ", "")

However, I think I would probably use some array constants, something like this:
=IF(B12<>"", CHOOSE(SUM(--(U12={"Subscription","T.E.H","ESA"})) + IF(U12="Perpetual", 2) +1, "", "Subscribe", "Buy"))

To break this down a little, let me reformat so it's easier to see:
=IF(
  B12 <> "",
  CHOOSE(
    SUM(--(U12={"Subscription","T.E.H","ESA"})) +
    IF(U12="Perpetual", 2) + 1
    "", "Subscribe", "Buy"
  )
)

I'm going to use CHOOSE, which takes an index number N and a list of choices, and it returns the Nth element in the choice list.  To generate the index, I'm going to use a couple of techniques.  First look at this:
U12 = {"Subscription", "T.E.H", "ESA"})

This is going to test U12 against all of the choices in the list, and return an array of TRUE/FALSE values.  If U12 matches any of the elements in the array constant, then one of those values will be TRUE.  We use -- to coerce that array from TRUE/FALSE to 0/1, and then we use SUM to get the array into a single value.  It will either be 0 if U12 doesn't match any of the options, or 1 if it does.
Then I'm going to use a standard IF to check if U12 = Perpetual, and return 2 if it does.  Adding that result to the previous sum will give us a final number that is either 0, 1 or 2.
CHOOSE is 1 indexed, meaning that it expects the index to be 1 or greater, so we add 1 to the number we just generated and pass it to CHOOSE along with a list of options.
The advantage here is that if the Subscribe options change you can just change the list, instead of having to alter a bunch of nested IFs.  Also, if you need to support multiple buy options, you can do it with a similar construction:
SUM(--(U12 = {"Subscription", "T.E.H", "ESA"})) +
IF(SUM(--(U12 = {"Perpetual", "Buy Now"})), 2) + 1

and if you needed to add return values just keep extending:
CHOOSE(
  SUM(--(U12 = {"Subscription", "T.E.H", "ESA"})) +
  IF(SUM(--(U12 = {"Perpetual", "Buy Now"})), 2) +
  IF(SUM(--(U12 = {"Release", "Dropping"})), 3) + 1,
  "", "Subscribe", "Buy", "Sell"
)

If you think this is something that might need to be maintained or the options might change, I would set it up like this, as opposed to nested IFs.

A: Is this a little clearer?
=IF(B12=""," ",IfError(VLookup(U12,{"ESA","Subscribe";"Perpetual","Buy";"Subscription",Subscribe";"T.E.H.","Subscribe"},2,false)," "))

This is really just a table lookup, hence the use of VLookup.  The lookup array is a two dimensional array in curly brackets - the commas and semicolons are very important for defining a 2x4 array for VLookup.  The IFError function tells how to return your desired " " result if the lookup fails.


text:
Q: SQL Azure Standard Geo replication - Promote Non readable secondary replica to Primary For Disaster recovery scenario , I have created a Primary DB and secondary replica using standard Geo replication.
I wanted to simulate the DR / DR Drill so I have used the below powershell CMDLET for terminating the the continuous copy relationship and to promote the secondary replica to primary.
Stop-AzureSqlDatabaseCopy -ServerName "S1"-DatabaseName "ActiveGeoReplicationDemo"-PartnerServer "S2"

This works fine for Active geo-replication, but throwing error for the Standard geo-replication as below,

Stop-AzureSqlDatabaseCopy : Friendly termination of an offline
  secondary relationship is not supported.

I thought the deletion of primary db would promote the secondary to primary automatically and deleted the primary. As expected, with active Geo-replication , the secondary has been promoted to the primary But in the Standard GEO-Rep still the secondary is Non readable.

So the Question is , How can i promote the non-readable Secondary DB
  to primary using Standard geo-replication? ( How Fail-over and fail-back to be done?)

It would be great if i get the power-shell  cmdlets or some references for this.

A: This example forcibly terminates a continuous copy relationship from the server that hosts the secondary database. (this is the working sample)
$myDbCopy = Get-AzureSqlDatabaseCopy -ServerName "t4xl86670k"
-DatabaseName "failover"
$myDbCopy | Stop-AzureSqlDatabaseCopy -ServerName "t4xl86670k" -ForcedTermination

Reference: https://msdn.microsoft.com/en-us/library/dn720223.aspx

A: You need to force terminate the relationship I believe and to mimic the right DR drill you need to execute this from the partner server. Try:
Stop-AzureSqlDatabaseCopy -ServerName "S2"-DatabaseName "ActiveGeoReplicationDemo"-PartnerServer "S1" -ForcedTermination


text:
Q: How to get the current view count of all videos on a channel from the youtube API? While the subscription count in
www.googleapis.com/youtube/v3/channels?part=statistics

seems to be updated instantly, the views update around daily.
A workaround that I found was to list all videos in the "uploaded" playlist with
www.googleapis.com/youtube/v3/playlistItems?part=contentDetails

and iterate through them, calling
www.googleapis.com/youtube/v3/videos?part=statistics

for each. This seems to get the most accurate results, though it requires more than 3 credits for every uploaded video, thus using my quota up relatively fast.
Is there a faster way around the problem?
I would like to implement it on an ESP8266 so it would be preferable not to require a lot of storage or processing power.

A: You can get the view count by getting the liveStreamingDetails, the liveStreamingDetails object contains metadata about a live video broadcast. The object will only be present in a video resource if the video is an upcoming, live, or completed live broadcast. Then, under this, you will get the concurrentViewers. It will show the number of viewers currently watching the broadcast. The property and its value will be present if the broadcast has current viewers and the broadcast owner has not hidden the viewcount for the video
EDIT
Specific to your use case, I believe a 2-part API would help with your inquiry.
I'm thinking of you calling a search query to retrieve all videos of the channel. The Search resource will have the id.videoId that you'll concatenate as part of the list call. This will give you the statistics.viewCount of each video, which you'll need to add up to get the total channel view count.
Hopefully this helps with your inquiry.
Happy coding!


text:
Q: Comparison of TFS and CVS I am about to migrate my Java project from CVS to TFS. I use eclipse IDE for development and I am unsure about the drawbacks of TFS over CVS. Please let me know if you know any.

A: TFS really works best with Visual Studio suite, anything else and you will find it to be quite a struggle.

*

*Eclipse doesn't really have any hooks into TFS unlike Visual Studio, so you will be struggling a little when it comes to checking in/out files (unless there is a plugin that I am not aware of)

*TFS is expensive. You need TFS server, and you need a client to access it (VS Team Edition  and similar or Team Explorer)

*Also, you can't check out multiple branches/versions (from memory). You're stuck with 1 working directory that is managed by Team Explorer.

To be fair, TFS is a step up from CVS. But why stop there? Please look into 4th generation source control like Git, Mercurial (being the main 2) etc.

A: I'm assuming that you're moving to TFS beacuse it's already being used in your company. If you're a Java shop then there are probably better solutions (Such as Git or Mercurial). If you're also using Visual Studio then TFS will be an improvement over CVS.
You need to look at "Team Explorer Everywhere" This is a plugin for Eclipse that will allow you to use TFS. As far as I'm aware it's functionally equivilant to Team Explorer for Visual Studio.
In addition to this you can also use Team Build to call out to ANT or Maven using the "Team Foundation Server Build Extensions"
Be aware that you will need to have either an MSDN licence or a TFS CAL to use TFS. If you don;t have an MSDN licence then you'll probably have to pay for Team Explorer Everywhere.


text:
Q: How to convert a Uint8Array into a boolean (bit) array without using strings? I'm using javascript, and I'm little rusty on my bit arithmetic.
Ultimately, my goal is to convert a UInt8Array into 11-bit numbers for use with a bip39 wordlist for converting a libsodium private box key to a mnemonic (I'm building a small p2p-ish chat app).
So, my thought process is:

*

*Uint8Array is returned from libsodium.crypto_box_keypair()

*Convert Uint8Array into a 256bit (boolean) array

*divide the 256bit array into 11bit buckets (2d array: ~24 x 11bits)

*convert each 11bit array to a base 10 number (between 0 and 2047)

Steps 2, 3, and 4 can be combined into the same loop.
The goal of all this is to efficiently convert from a Uint8Array to an array of 11bit numbers (efficient for the computer -- this hasn't been efficient for myself).
I have this at the moment, but it isn't quite right, and feels somewhat hacky (just from steps 2 and 3, where I try to create the 11bit buckets)
// inspired from: https://github.com/pvorb/node-md5/issues/25
export function toUint11Array(input: Uint8Array): boolean[][] {
  let result: boolean[][] = [];
  let currentChunk: boolean[] = [];

  input.forEach(byte => {
    for (var j = 7; j >= 0; j--) {
      var b = ((byte >> j) & 0x1) > 0;

      if (currentChunk.length === 11) {
        result.push(currentChunk);
        currentChunk = [];
      }

      currentChunk.push(b);
    }
  });

  return result;
}

Currently, for 2048, I get 2 11 bit arrays (expected), but the content / order is unexpected.
  [
    false, false, false, false,
    false, false, false, false,
    false, false, false
  ],
  [ false, true, false, false,
    false, false, false, false,
    false, false, false
  ]

2048 is 0b100_000_000_000
where the 12th digit from the right is the 1 (added underscores for easier reading)
so maybe it looks like I have an endianness problem and and off by one issue? because the true in my dual array is the 13th position from the left.
though, when I test with 4096 (13 bits (0b1_000_000_000_000)), I get this:
  [
    false, false, false, false,
    false, false, false, false,
    false, false, false
  ],
  [
    true, false, false, false,
    false, false, false, false,
    false, false, false
  ],
  [
    false, false, false, false,
    false, false, false, false,
    false, false, false
  ]

Here, the true is 12th from the left, and 22nd from the right.
Update
per @bergi, who asked about endianness.

I don't know what endianness this is. :-\
Update 2
Thanks to @harold for coming up with the answer. I have some tests that I think confirm correctness.
  const numbers = {
    ['32']: new Uint8Array([32]),
    ['64']: new Uint8Array([64]),
    ['2048']: new Uint8Array([8, 0]),
    ['4096']: new Uint8Array([16, 0]),
    ['7331']: new Uint8Array([28, 163])
  }

  test ('toUint11Array | converts | 32 (8 bits)', function(assert) {
    const result = toUint11Array(numbers['32']);
    const expected = [32];

    assert.deepEqual(result, expected);
  });

  test ('toUint11Array | converts | 2048 (12 bits)', function(assert) {
    const result = toUint11Array(numbers['2048']);
    const expected = [8, 0];

    assert.deepEqual(result, expected);
  });

  test ('toUint11Array | converts | 4096 (13 bits)', function(assert) {
    const result = toUint11Array(numbers['4096']);
    const expected = [16, 0];

    assert.deepEqual(result, expected);
  });

 test ('toUint11Array | converts | 7331 (13 bits)', function(assert) {
    const result = toUint11Array(numbers['7331']);
    const expected = [3, 1187];

    assert.deepEqual(result, expected);
  });

the first 3 pass, but the last does not.
when converting a Uint8Array(28, 163), I get [796, 28]
I'm not 100% sure that I converted 7331 into appropriate bytes correctly, but I did:
7331 = 0b1_1100_1010_0011 split: [1_1100, 1010_0011] -> [28, 163].
I suppose for the output, it should be: [11, 100_1010_0011] which is [3, 1187] which also doesn't match the output.

A: I'm not as rusty on my bit arithmetic, so I propose a method without temporary boolean arrays:

*

*read bytes into a buffer until there are at least 11 bits

*extract 11 bits from the buffer

*repeat

Actually a funny thing happens at the end since 11 does not divide 256, I assume padding with zeroes is OK.
So maybe something like this in JavaScript (but I am a little rusty on my JS)
function toUint11Array(input) {
    var buffer = 0, numbits = 0;
    var output = [];

    for (var i = 0; i < input.length; i++) {
        // prepend bits to buffer
        buffer |= input[i] << numbits;
        numbits += 8;
        // if there are enough bits, extract 11bit chunk
        if (numbits >= 11) {
            output.push(buffer & 0x7FF);
            // drop chunk from buffer
            buffer = buffer >> 11;
            numbits -= 11;
        }
    }
    // also output leftover bits
    if (numbits != 0)
        output.push(buffer);

    return output;
}

A: I'd go for generators:
function* bitsFromOctetsLE(octets) {
    for (let byte of octets) {
        for (let i=0; i<8; i++) {
            yield (byte & 1);
            byte >>= 1;
        }
    }
}
function* hendecadsFromBitsLE(bits) {
    let i=0;
    let val=0;
    for (const bit of bits) {
        if (i==11) {
            yield val;
            i = val = 0;
        }
        val |= bit << (i++);
    }
    if (i > 0) yield val;
}

Then use them like
const input = libsodium.crypto_box_keypair();
const result = Array.from(hendecadsFromBitsLE(bitsFromOctetsLE(input)))


text:
Q: GEOS segmentation fault when loading libc.so.6 I'm trying to run a program that uses shapely on a GCE Virtual Machine (Ubuntu 18.04). I'm getting an error on the geos.py file, here is the relevant trace I'm getting:
[geos:73] - [DEBUG]: Found GEOS DLL: <CDLL '/home/loic/venv/lib/python3.6/site-packages/shapely/.libs/libgeos_c-5031f9ac.so.1.13.1', handle 31283c0 at 0x7f5aefc58940>, using it.
[geos:38] - [DEBUG]: Trying `CDLL(libc.so.6)`
Segmentation fault (core dumped)

I'm running this program inside a python virtualenv, with Shapely==1.7.0. The thing is, when I'm launching this program locally, with basically the same environment, I'm not getting any error, CDLL(libc.so.6) is working fine.
Here's the output of ls -l /lib/x86_64-linux-gnu/ | grep libc:
-rwxr-xr-x 1 root root 2030544 Apr 16  2018 libc-2.27.so
lrwxrwxrwx 1 root root      12 Apr 16  2018 libc.so.6 -> libc-2.27.so
lrwxrwxrwx 1 root root      18 Sep 24  2017 libcap-ng.so.0 -> libcap-ng.so.0.0.0
-rw-r--r-- 1 root root   18712 Sep 24  2017 libcap-ng.so.0.0.0
lrwxrwxrwx 1 root root      14 Nov 16  2017 libcap.so.2 -> libcap.so.2.25
-rw-r--r-- 1 root root   22768 Nov 16  2017 libcap.so.2.25
-rw-r--r-- 1 root root  190784 Apr 16  2018 libcidn-2.27.so
lrwxrwxrwx 1 root root      15 Apr 16  2018 libcidn.so.1 -> libcidn-2.27.so
lrwxrwxrwx 1 root root      17 Jan 22 14:40 libcom_err.so.2 -> libcom_err.so.2.1
-rw-r--r-- 1 root root   14248 Jan 22 14:40 libcom_err.so.2.1
-rw-r--r-- 1 root root   39208 Apr 16  2018 libcrypt-2.27.so
lrwxrwxrwx 1 root root      16 Apr 16  2018 libcrypt.so.1 -> libcrypt-2.27.so
lrwxrwxrwx 1 root root      23 Aug 23  2018 libcryptsetup.so.12 -> libcryptsetup.so.12.2.0
-rw-r--r-- 1 root root  310040 Aug 23  2018 libcryptsetup.so.12.2.0

Has anyone experienced this before, or know how to fix this issue? I can provide more information if needed.


text:
Q: ¿Cómo aplicar Dijkstra con BFS en Java? Estoy atascado en el algoritmo de Dijkstra para un grafo dirigido con un vértice de origen y uno de destino (con sus respectivos pesos o costos). La cosa es que tengo que hallar el camino mas corto (valga la redundancia), pero solo he logrado que el recorrido vaya por el camino mas corto de cada nodo, no de todo el grafo desde el origen hasta el destino. La gracia es usar algo parecido al BFS pero adaptarlo para Dijkstra.
Se que tengo que comparar las sumas de todos los caminos que llegan hasta el destino pero no hallo la manera de hacerlo. Tambien tengo entendido que se puede utilizar una cola de prioridad pero la verdad que no tengo idea como o en que parte.
Mi código es el siguiente:
public void caminoCortoBFS (String A, String B, JTextArea jta){
    desmarcarTodos();
   ordenarVerticesAlf();     Arco a;
   float distanciatotal=0;
   Vertice v = buscarVertice(A), w;
   LinkedList <Vertice> C;
   C=new LinkedList<Vertice>();
   C.add(v);
   v.marcado=true;      jta.append("Camino mas corto de " + A + "a " + B + " es: ");
   do{
       v = C.pop();
       jta.append(v.getNombre() + " ");
       for (int i = 0; i < v.LArcos.dim(); i++) {
           a = (Arco) v.LArcos.getElem(i);
           if(a.getCosto() == minDistancia(v)){
               distanciatotal+=minDistancia(v);
               w=buscarVertice(a.getNombreVertD());
               if(w.nombre.equals(B)){
                   jta.append(w.getNombre() + " " + "\n");
                   jta.append("Distancia total = " + distanciatotal);
                   return;}
                if (!w.marcado) {
               C.add(w);
               w.marcado=true;
                }

           }

       }

   }while (!C.isEmpty());
}

private float minDistancia(Vertice A){
    float distMinima=99999; Arco a;
    for(int i=0; i<A.LArcos.dim(); i++){
        a = (Arco) A.LArcos.getElem(i);
        if(a.getCosto()<distMinima)
            distMinima=a.getCosto();
    }
    return distMinima;
}

Y como resultado para el siguiente grafo:

Me da como resultado poniendo como vértices
Origen A - Destino D :
A -> C -> E -> D
Cuando deberia ser
A -> B -> D
Se que esta fatal, pero agradecería cualquier ayuda que pudieran darme.

A: BFS y Dijkstra son distintos algoritmos. En BFS usas una pila para contener una lista de nodos y recorrerlos sistemáticamente por profundidad. En Dijkstra usas una cola de prioridades para hacer lo mismo e ir corrigiendo las cantidades calculadas hasta tener los costos (distancias) calculados para todos los nodos.
El algoritmo de Dijkstra generalmente se resuelve con una lista de adyacencia para representar el grafo.
Es decir tenemos un ArrayList1 que apunta a listas de vertices2 adyacentes. Es decir puedes usar algo como:
List<List<Vertice>> listaAdyacencia = new ArrayList<>(numVertices);

Ahora después de inicializar tu lista de adyacencia, generalmente se tiene que tener una cola de prioridades para los costos. Llámalo costos por ejemplo. El PriorityQueue de Java es muy básico, no te deja encontrar un item y cambiarle de prioridad por ejemplo, por lo que tienes que implementar el tuyo propio, usar otra librería no estándar, o tienes que usar una lista que es considerablemente menos eficiente.
Entonces los pasos del algoritmo son:
 1. Empieza considerando todos los costos de cada vertice Integer.MAX_VALUE (es decir: Infinito)
 2. Inicializa el costo del vértice de origen a 0
 3. Inicializa una cola de prioridades **costos** y agrega todo los vertices con sus costos respectivos
 4. Mientras hayan nodos desconocidos en el grafo
    1. Selecciona el nodo deconocido N con el menor costo
    2. Marca N como conocido
    3. Para cada nodo A adyacente a N
       If (costo[N] + costo de ir de N a A < costo[A])
          costo[A] = costo[N] + costo de ir de N a A
          anterior[A] = N    // esto te ayuda a reconstruir el camino

Para mayor información puedes ver este PDF: https://courses.cs.washington.edu/courses/cse373/01sp/Lect24_4up.pdf
1 ArrayList es generalmente mejor que LinkedList en Java por varios motivos pero eso es tema de otro articulo.
2 también llamados nodos

A: Comparto , no se si resuelva el problema espero que si ! saludos !!
import java.util.*;
public class Dijkstra {
public int[] distancia = new int[10];
public int[][] costo = new int[10][10];

public void calc(int n, int s) {
    int[] bandera = new int[n + 1];
    int i, minpos = 1, k, c, minima;

    for (i = 1; i <= n; i++) {
        bandera[i] = 0;
        this.distancia[i] = this.costo[s][i];
    }
    c = 2;
    while (c <= n) {
        minima = 99;
        for (k = 1; k <= n; k++) {
            if (this.distancia[k] < minima && bandera[k] != 1) {
                minima = this.distancia[i];
                minpos = k;
            }
        }
        bandera[minpos] = 1;
        c++;
        for (k = 1; k <= n; k++) {
            if (this.distancia[minpos] + this.costo[minpos][k] < this.distancia[k] && bandera[k] != 1) {
                this.distancia[k] = this.distancia[minpos] + this.costo[minpos][k];
            }
        }
    }

}

public static void main(String args[]) {
    int nodos, posicion, i, j;
    Scanner sc = new Scanner(System.in);
    System.out.println("Ingrese el número de nodos \n");
    nodos = sc.nextInt();
    Dijkstra d = new Dijkstra();
    System.out.println("Ingrese los pesos de la matriz de costos: \n");
    for (i = 1; i <= nodos; i++) {
        for (j = 1; j <= nodos; j++) {
            d.costo[i][j] = sc.nextInt();
            if (d.costo[i][j] == 0) {
                d.costo[i][j] = 999;
            }
        }
    }
    System.out.println("Ingrese la posicion de origen :\n");
    posicion = sc.nextInt();

    d.calc(nodos, posicion);
    System.out.println("El camino más corto desde la posicion \t" + posicion + "\t a todos los demás puntos son : \n");
    for (i = 1; i <= nodos; i++) {
        if (i != posicion) {
            System.out.println("posicion :" + posicion + "\t destino :" + i + "\t Costo minimo es :" + d.distancia[i] + "\t");
        }
    }

}


text:
Q: remove double results value from forEach (angular js) there is this thing who i am not figuring out,
i have a controller that return me an array of products propriety, that populate a  field, so far i have done this:
     $scope.categoryForFilter=[];
//product load
ProductService.listProducts().then(function(data) {
    $scope.products = {
        count: data.count,
        list: data.aaData,
        length: data.aaData.length
    };
    $scope.products.list.forEach(function (element) {
            $scope.categoryForFilter.push({"id": element.category.id, "label": element.category.label})
    });
});

but in this way i have multiple element.category.label in the options field that in my view is the following:
<select ng-model="categoryForFilter" ng-options="cat.label for cat in categoryForFilter" st-search="cat.label">
                        <option></option>
</select>

so how can i filter the results who have the same value in the array? anyone can help please?

A: You can use the unique filter, which is part of Angular UI.
You can also use this filter using lodash:
app.filter('unique', function() {
    return function (arr, field) {
        return _.uniq(arr, function(a) { return a[field]; });
    };
});

Source

A: There is a real easy way to this by using lib like lodash with the function "uniq":
$scope.categoryForFilterWithUniqLabel = _.uniq($scope.categoryForFilter, 'label');


text:
Q: How to create a non-breaking en-dash in Word 2003? I have an en-dash between two words, and I am following the usual British rule (as advised in e.g. the Oxford University style guide) of surrounding it with space characters. Using Word 2003, running on Windows 10 Pro, how can I ensure, other than by using a soft return which might well yield a too-short line after a future edit, that the en-dash appears at the start of a line rather than the end of one?
I've tried the following without success:

*

*non-breaking spaces before and after it

*a breaking space before it and a non-breaking one after

*a breaking space before it and a non-breaking one after it, with the latter wrapped in no-width non-breaks.


text:
Q: Asp.net creating tab delimited txt file I have to create a tab delimited txt file from a query.
I want to call an HttpHandler that returns my txt file as a stream, I don't want to create the file phisically.
1st question:
what is the best practice to create the tab delimited txt file from a query result?
I have to fetch all rows and create the file manually?
2nd question:
How to set a timeout for the HttpHandler that creates the file?
Thanks for your time.

A: *

*I would create a plain old http output stream and change the content type to 'text/plain' which means that you don't need to physically create the file on the web server, and if you add the content-disposition header to the output and specify that it has an attachment called something like 'report.txt' the user will be prompted to Open or Save the content, rather than just viewing it in the browser like a normal web page.

*You can use the Server.ScriptTimeout = x to set the script timeout by gaining access to the current HttpContext object
Hope this helps


text:
Q: Javascript CSS - Menu with time (Help) I have this menu and I want to display Categories and Language when the hover is active and they go too More.. and click it to display the other down with time so it will display beautiful..when they will click it I want to display Less.. and the less will be at the end of the dropdon meny I dont know how to do it please someone help me..here is the menu code
HTML CODE

Home

Categories

Action

Adventure

Animation

Comedy

Crime

Drama

Family

Fantasy

Horror

More..

Romance

Sci-Fi

Thriller

Language

Arabic

Brazilian

Dutch

English

French

German

Greek

Indonesian

Malay

More..

Norwegian

Romanian

Spanish

Swedish

Thai

Turkish

Vietnamese

Request

Movie

Other

Help us

CSS CODE
#mbmcpebul_table {
  display: inline-block;
  width:100%;
  margin:0 auto;
  height:50px;
}

#mbmcpebul_table li a {
  line-height: 19px;
  font-size: 17px;
  font-family: Arial,sans-serif;
  text-decoration: none;
  color: #2C6EE8;
  font-style: normal;
  font-weight: bold;
  padding: 8px 1px 1px 1px;
  display: block;
  cursor: pointer;
  white-space: nowrap;
  -webkit-tap-highlight-color: rgba(0,0,0,0);
  text-shadow:none;
}

#mbmcpebul_table li div.buttonbg {
  height: 35px;
  width: 150px;
  line-height: 0;
  background-color: transparent;
  border-style: solid;
  border-color: #E4E4E4;
  border-width: 0;
  border-radius: 5px;
  box-shadow: none;
  text-align: center;
  cursor: pointer;
}

#mbmcpebul_table li:hover div.buttonbg a, #mbmcpebul_table li.expanded a.topitem, #mbmcpebul_table li.active a.topitem,
#mbmcpebul_table li.itemhot a.topitem, #mbmcpebul_table li a:hover {
  color: #FFFFFF;
  font-style: normal;
  font-weight: bold;
  text-decoration: none;
}

#mbmcpebul_table li.expanded div.buttonbg, #mbmcpebul_table li.active div.buttonbg, #mbmcpebul_table li.itemhot div.buttonbg, #mbmcpebul_table li:hover div.buttonbg {
  background-color: transparent;
  box-shadow: none;
}

#mbmcpebul_table li.expanded div.buttonbg, #mbmcpebul_table li.active div.buttonbg, #mbmcpebul_table li.itemhot div.buttonbg, #mbmcpebul_table li:hover div.buttonbg {
  border-color: #3278BE;
  text-align:center;
}
#mbmcpebul_table ul li.subexpanded a.subexpanded, #mbmcpebul_table ul li.subitemhot a.subitemhot, #mbmcpebul_table ul li a {
text-align:center;
}
#mbmcpebul_table ul li a {
  border-top: 1px #2C6EE8 solid;
  border-bottom: 1px #2C6EE8 solid;
  border-right: 2px #2C6EE8 solid;
  border-left: 2px #2C6EE8 solid;
  color: #2C6EE8;
  font-family: Arial,sans-serif;
  font-size: 14px;
  line-height: 9px;
  text-decoration: none;
  display: block;
  width:117.2px;
}
#mbmcpebul_table .first {
  border-top: 1px #2C6EE8 solid;
}
#mbmcpebul_table .last {
  border-bottom: 1px #2C6EE8 solid;
}
#mbmcpebul_table div .active {
  background-image: -moz-linear-gradient(top, #3F93D9 0%, #014188 100%);
  background-image: -webkit-linear-gradient(top, red 0%, #014188 100%);
  background-image: linear-gradient(top, #3F93D9 0%, #014188 100%);
}
#mbmcpebul_table ul li.subexpanded a.subexpanded, #mbmcpebul_table ul li.subitemhot a.subitemhot, #mbmcpebul_table ul li a:hover {
  color: #FFFFFF;
  font-family: Arial,sans-serif;
  font-size: 15px;
  text-align:center;
}

#mbmcpebul_table ul li:hover, #mbmcpebul_table ul li.subexpanded, #mbmcpebul_table ul li.subitemhot {
  border-color: transparent;
  background-color: transparent;
  box-shadow: none;
}

#mbmcpebul_table ul li a {
  padding: 7px 15px 7px 13px;
  text-align: center;
}

#mbmcpebul_table ul li.separator {
  padding: 7px;
  cursor: default;
  background: none;
  box-shadow: none;
  border-width: 0;
}

#mbmcpebul_table ul li.separator div {
  border-top: 1px solid #FFFFFF;
  font-size: 0px;
}

#mbmcpebul_table ul li {
  border-style: solid;
  border-color: transparent;
  border-width: 0;
  height: auto;
  width: auto;
  text-align: left;
  line-height: 0;
  font-size: 0;
  cursor: pointer;
  float: none;
  margin: 0 0 0px 0;
  border-radius: 0;
  padding: 0;
  box-shadow: none;
  background-color: transparent;
  display: block;
  left:-40;
}

#mbmcpebul_table ul {
  box-shadow: 1px 1px 5px -1px #333333;
}

#mbmcpebul_table a img {
  border: none;
}

#mbmcpebul_table li {
  list-style: none;
  float: left;
  margin: 0px 15px 15px 0px;
  padding: 0;
  float: left;
  display: inline-block;
}

#mbmcpebul_table.css_menu li {
  position: relative;
}

#mbmcpebul_table.css_menu ul li:hover > ul {
  opacity: 1;
}

#mbmcpebul_table.css_menu li:hover > ul {
  top: 100%;
  left: 0;
  right: auto;
  opacity: 1;
  transform: scale(1,1);
  -webkit-transform: scale(1,1);
  -moz-transform: scale(1,1);
  -ms-transform: scale(1,1);
}

#mbmcpebul_table.css_menu ul li:hover > ul {
  top: -1px;
  left: 100%;
  right: auto;
}

#mbmcpebul_table.css_menu ul {
  transition-duration: 0.3s;
  -webkit-transition-duration: 0.3s;
  -moz-transition-duration: 0.3s;
  -ms-transition-duration: 0.3s;
  transition-property:transform,opacity;
  -webkit-transition-property:-webkit-transform,opacity;
  -moz-transition-property:-moz-transform,opacity;
  -ms-transition-property:-ms-transform,opacity;
  opacity: 0;
  transform-origin: 0 0;
  transform: scale(0.1, 0.1);
  -webkit-transform-origin: 0 0;
  -webkit-transform: scale(0.1, 0.1);
  -moz-transform-origin: 0 0;
  -moz-transform: scale(0.1, 0.1);
  -ms-transform-origin: 0 0;
  -ms-transform: scale(0.1, 0.1);
}

#mbmcpebul_table ul {
  position: absolute;
  top:-99999px;
  z-index: 4000;
}

#mbmcpebul_table ul ul {
  position: absolute;
  z-index: 5000;
}

#mbmcpebul_table .submenu_arrow {
  margin-left: px;
}

#mbmcpebul_table li:hover > a span.img_4x5, #mbmcpebul_table li.subexpanded > a span.img_4x5 {
  background-position: 0 -5px;
}

#mbmcpebul_table div.gradient_button {
  background-image: -moz-linear-gradient(top, #FEFEFE 0%, #D9D9D9 100%);
  background-image: -webkit-linear-gradient(top, #FEFEFE 0%, #D9D9D9 100%);
  background-image: linear-gradient(top, #FEFEFE 0%, #D9D9D9 100%);
}

#mbmcpebul_table li:hover div.gradient_button, #mbmcpebul_table li.expanded div.gradient_button, #mbmcpebul_table li.active div.gradient_button, #mbmcpebul_table li.itemhot div.gradient_button {
  background-image: -moz-linear-gradient(top, #3F93D9 0%, #014188 100%);
  background-image: -webkit-linear-gradient(top, #3F93D9 0%, #014188 100%);
  background-image: linear-gradient(top, #3F93D9 0%, #014188 100%);
}

#mbmcpebul_table ul.gradient_menu {
  background-image: -moz-linear-gradient(top, #FFFFFF 0%, #ECECEC 100%);
  background-image: -webkit-linear-gradient(top, #FFFFFF 0%, #ECECEC 100%);
  background-image: linear-gradient(top, #FFFFFF 0%, #ECECEC 100%);

}

#mbmcpebul_table ul li.gradient_menuitem:hover, #mbmcpebul_table ul li.gradient_menuitem.subexpanded, #mbmcpebul_table ul li.gradient_menuitem.subitemhot {
  background-image: -moz-linear-gradient(top, #3F93D9 0%, #003C82 100%);
  background-image: -webkit-linear-gradient(top, #3F93D9 0%, #003C82 100%);
  background-image: linear-gradient(top, #3F93D9 0%, #003C82 100%);
}


text:
Q: Why exactly is prepend to a Scala List a constant time operation, but append a linear time operation? I am in the middle of learning Scala right now from Odersky's 'Programming in Scala' and I just read this

...the time it takes to append to a list grows linearly with the size of the
  list, whereas prepending with :: takes constant time...

Why exactly does it take linear time to append to append to a list but only constant time to prepend to it. My current guess is it's somehow implemented as a linked list internally which would explain the difference between the two operations. In that case, how are ListBuffers implemented which have a constant time append?

A: They are both implemented similarly to linked lists. The difference is that the ListBuffer contains also a pointer to the tail of the list. Scala's source code is open, if you are curious about its detail you can explore it on github (for example, here is the ListBuffer's append code)

A: There's two questions here: one is a very basic one about lists, and the other is scala-specific. For the first, I'll draw a picture. The "List" abstract data type is one of the oldest in computer science; it goes right back to 1956 and the first implementation of the LISP language.
The list ADT is indeed implemented using a one-way linked list. Each element is traditionally called a cons cell (Nil indicates end of list):
+------+------+      +------+------+    +--------+
|   1  |   * -+----> |  3   +   * -+--->|  NIL   |
+------+------+      +-------------+    +--------+
^
|
val list1

This corresponds to the chained "cons" (list construction) call in scala:
scala> val list1 = 1 :: 3 :: Nil
list1: List[Int] = List(3, 1)

List is an immutable data structure. We cannot destructively update it by rewriting any
existing pointer/reference. So what if we want to prepend to it?
scala> val list2 = 0 :: list1
list2: List[Int] = List(0, 1, 3)

Creating list2 is very fast and easy, we simply create a new cons cell and prepend it to the existing list:
+------+------+      +------+------+      +------+------+    +--------+
|   0  |   *--+----->|   1  |   * -+----> |  3   +   * -+--->|  NIL   |
+------+------+      +------+------+      +-------------+    +--------+
 ^                   ^
 |                   |
 val list2           val list1

The beauty of this is that it leaves all existing references unchanged, preserving immutability. However, if we want to /append/ to the list, we would have to overwrite the reference to Nil to a new element, thus mutating list1. Thus, the only way to do it is to duplicate the entire existing list and rewrite it thus:
scala> val list3 = list1 ++ (5 :: Nil)
list3: List[Int] = List(1, 3, 5)

+------+------+      +------+------+      +------+------+    +--------+
|   0  |   *--+----->|   1  |   * -+----> |  3   +   * -+--->|  NIL   |
+------+------+      +------+------+      +-------------+    +--------+
^                    ^                                           ^
|                    |                                           |
val list2            val list1                                   |
                                                                 |
                                                                 |
(copy)                                                           |
+------+------+      +------+------+    +--------+-------+       |
|   1  |   * -+----> |  3   +   * -+--->|   5    |    *--+-------+
+------+------+      +-------------+    +--------+-------+
^
|
val list3

It's a linear time operation because, to append to a list of length N, we have to make copies of all N cons cells (except for Nil).
As for scala's ListBuffer, its append works by directly mutating the backing list, rewriting the tail reference of the final cons cell, which has the slighly awkward looking type ::[A].
In List.scala:
final case class ::[B](override val head: B, private[scala] var tl: List[B]) extends List[B] {
   override def tail : List[B] = tl
   override def isEmpty: Boolean = false
}

[..]
In ArrayList.scala:
/** Appends a single element to this buffer. This operation takes constant time.
*
*  @param x  the element to append.
*  @return   this $coll.
*/
def += (x: A): this.type = {
  if (exported) copy()
  if (isEmpty) {
    last0 = new :: (x, Nil)
    start = last0
  } else {
    val last1 = last0
    last0 = new :: (x, Nil)
    last1.tl = last0
  }
  len += 1
  this
}

last1.tl = last0 is permitted because ::.tl has visibility private[scala], permitting unsafe "under the hood" operations for mutating collections such as ListBuffer.


text:
Q: Poissonic distribution I was asked this: the number of electrons coming out of a device during 1 hour is a random Poisson variable with $\lambda = 4$. Electrons coming out of the device hit a wall with a probability of $\frac{3}{4}$ independently. What is the probability that from the electrons that came out of the device during 1 hour:
1) at least 1 hit the wall?
2) exactly 3 hit the wall?
So at first I calculated the probability that at least 1 electron came out of the device during 1 hour and got $1 - \frac{1}{e^4}$ and then:
for (1), I said if $k$ is the number of electrons that came out during 1 hour then my answer is $(1 - \frac{1}{e^4}) \cdot {k \choose 1} \cdot \frac{3}{4}$
I took the probability that at least one electron came out and then chose 1 from the $k$ that came out  and then multiplied by the probability that they hit the wall.
for (2) I did a similar thing but I took the probability that at least 3 came out during 1 hour, then choose 3 from the $k$ electrons that came out, and then multiplied by $(3/4)^3\cdot(1/4)^{k-3}$
But I think I'm not even doing this right. Can I get some help here?

A: Hint: If we randomly remove 3/4 of the electrons, then the Poisson with intensity 4 ($\lambda = 4$) becomes an other Poisson with intensity $\lambda' = 4 * 3 / 4 =3$. I.e. instead of 4 electrons arriving randomly and independently from our device, only 3 electrons reach the wall, still randomly and independently.
Now that we have a Poission with $\lambda' = 3$ can calculate question 1 and 2 using the probability mass function and the cumulative distribution function.
Hope this helps, let me know otherwise!
EDIT
By probability mass function I mean $\frac {\lambda ^{k}e^{-\lambda }}{k!}$. You might have learned this on an other name. It tells you what is the probability of exactly k hits. Using λ′=3 and k=3 you'll get the answer to 2).

A: You most certainly need to use both CDF and PDF here:
@Mark provided the formula for you nicely so you should do it by hand.
Electrons coming out of the device hit a wall with a probability (p)
of $\frac{3}{4}$, thus the expected amount of electrons coming out of a device and hitting a wall is $4*\frac{3}{4}$ = $3$ per hour
Part A) at least one implies it could be 1,2,3,4,etc.
$$P (x\geq 1)=1-P (x=0)$$
Part B) exactly 3 implies
$$P (x=3)$$
Can you take it from here? You have all the given information in the problem.
Using R
Part A: Using the CDF for Poisson to calculate the "cumulative" probabilities
 1-ppois(0,3) = .95

Part B: Using the PDF for Poisson to calculate the density at a specific value
 dpois(3,3) = .224

Here is the density curve, along with x = 3 labeled.