text:
Q: How does gawk -e 'BEGIN {' -e 'print "hello" }' work? Gawk 5.0.0 was released on April 12, 2019. Going through the announcement I found this:

Changes from 4.2.1 to 5.0.0
(...) 11. Namespaces have been implemented! See the manual.  One consequence of this is that files included with -i, read with -f, and command line program segments must all be self-contained syntactic units. E.g., you can no longer do something like this:
gawk -e 'BEGIN {' -e 'print "hello" }'

I was curious about this behaviour that is no longer supported, but unfortunately my Gawk 4.1.3 did not offer much output out of it:
$ gawk -e 'BEGIN {' -e 'print "hello" }'
gawk: cmd. line:1: BEGIN {
gawk: cmd. line:1:        ^ unexpected newline or end of string

From what I see in the manual of GAWK 4.2, the -e option was marked as problematic already:

GNU Awk User's Guide, on Options
-e program-text
--source program-text
Provide program source code in the program-text. This option allows you to mix source code in files with source code that you enter on the command line. This is particularly useful when you have library functions that you want to use from your command-line programs (see AWKPATH Variable).
Note that gawk treats each string as if it ended with a newline character (even if it doesn't). This makes building the total program easier.
CAUTION: At the moment, there is no requirement that each program-text be a full syntactic unit. I.e., the following currently works:
$ gawk -e 'BEGIN { a = 5 ;' -e 'print a }'
-| 5

However, this could change in the future, so it's not a good idea to rely upon this feature.

But, again, this fails in my console:
$ gawk -e 'BEGIN {a=5; ' -e 'print a }'
gawk: cmd. line:1: BEGIN {a=5;
gawk: cmd. line:1:             ^ unexpected newline or end of string

So what is gawk -e 'BEGIN {' -e 'print "hello" }' doing exactly on Gawk < 5?

A: It's doing just what you'd expect - concatenating the parts to form gawk 'BEGIN {print "hello" }' and then executing it. You can actually see how gawk is combining the code segments by pretty-printing it:
$ gawk -o- -e 'BEGIN {' -e 'print "hello" }'
BEGIN {
        print "hello"
}

That script isn't useful to be written in sections and concatenated but if you consider something like:
$ cat usea.awk
{ a++ }

$ echo foo | gawk -e 'BEGIN{a=5}' -f usea.awk -e 'END{print a}'
6

then you can see the intended functionality might be useful for mixing some command-line code with scripts stored in files to run:
$ gawk -o- -e 'BEGIN{a=5}' -f usea.awk -e 'END{print a}'
BEGIN {
        a = 5
}

{
        a++
}

END {
        print a
}


text:
Q: iPhone - GCD sending async operations to a serial dispatch queue Suppose I am doing an async connection to a web service, which by definition since it is async runs in a separate thread from the main thread.
Now lets say I put this job or block of code in a serial dispatch queue. Since serial dispatch queues don't process more than 1 job at a time, but I am sending a job that is already async, would it then consider the job to be done after the call to the async job is made? or would it actually wait for the async job to get done before processing the next job?.
What about a concurrent queue, would the concurrent generated thread, generate yet another thread to process the async operation?
EDIT: I realize my question is not really clear, so my question is:
If I am using the same serial dispatch queue, and i dispatch using dispatch_async a block of code that already performs an async operation for example a NSURLConnection – initWithRequest:delegate: that runs async, will the block be considered completed by the serial queue after the async call?, and will that async call generate yet another thread?. Or will the queue still wait for job 1 that is already async to finish before processing the second job?.

A: When you dispatch to a serial queue, each dispatched block is processed one after the other. So if your first block takes a long time to process, the second block will not be called until the long-running first block is finished.
If you're enqueueing with dispatch_async the new block is simply put to the end of the queue, the function dispatch_async immediately returns and you can go on. But the block won't be executed until the previous blocks have finished.
However, dispatch_sync will wait until the block got its turn to execute and finish. So in your case, dispatch_sync will block until the long-running first block has finished.
If you dispatch to concurrent queue, then the second block will get to run in a new thread and thus the first block will not prevent the second from running.
You could also create two queues and dedicate them to different tasks, for example have one queue only for your web service stuff and another queue for different tasks. It depends on how these operations relate to each other and which may be run in parallel and which must run one after another.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to trigger http 1.1 4xx 5xx error code? c# How do have your application response with a http 1.1 4xx 5xx error in c#?

A: Throw an HttpException with the appropriate HttpStatusCode.
http://msdn.microsoft.com/en-us/library/system.web.httpexception.aspx
http://msdn.microsoft.com/en-us/library/system.net.httpstatuscode.aspx
Example:
throw new HttpException((int) HttpStatusCode.NotImplemented, "Requested function not supported");


text:
Q: Embedded Jetty and Jax-rs xml configuration Hey guys i am trying to configure and run a Restful service using Embedded-jetty and jax-rs i found this tutorial and it works brilliantly however one of my requirements is to configure as much as possible through spring xml in the applicationContext.xml file.
The part i would like to do in xml is the AppConfig.java class
    @Configuration
public class AppConfig {
    @Bean( destroyMethod = "shutdown" )
    public SpringBus cxf() {
        return new SpringBus();
    }

    @Bean
    public Server jaxRsServer() {
        JAXRSServerFactoryBean factory = RuntimeDelegate.getInstance().createEndpoint( jaxRsApiApplication(), JAXRSServerFactoryBean.class );
        factory.setServiceBeans( Arrays.< Object >asList( peopleRestService() ) );
        factory.setAddress( '/' + factory.getAddress() );
        factory.setProviders( Arrays.< Object >asList( jsonProvider() ) );
        return factory.create();
    }

    @Bean
    public JaxRsApiApplication jaxRsApiApplication() {
        return new JaxRsApiApplication();
    }

    @Bean
    public StatsRestService peopleRestService() {
        return new StatsRestService();
    }

    @Bean
    public StatsService peopleService() {
        return new StatsService();
    }

    @Bean
    public JacksonJsonProvider jsonProvider() {
        return new JacksonJsonProvider();
    }
}

and where it is used
context.setInitParameter( "contextClass", AnnotationConfigWebApplicationContext.class.getName() );
context.setInitParameter( "contextConfigLocation", AppConfig.class.getName() );

unfortunately i can not find any decent posts online on how to do this in XML, i would greatly appreciate some help.

A: If you want to configure Spring via the XML then you need to move everything from the AppConfig class into the ${project}/src/applicationContext.xml and reference it like this:
context.setInitParameter("contextConfigLocation", "classpath:applicationContext.xml");

And an example of a working applicationContext.xml. You should check Spring Framework's website for API reference. But you can start with this tutorial.


text:
Q: Capturing output of python script run inside a docker container The aim here is to use a docker container as a secure sandbox to run untrusted python scripts in, but to do so from within python using the docker-py module, and be able to capture the output of that script.
I'm running a python script foo.py inside a docker container (it's set as the ENTRYPOINT command in my Dockerfile, so it's executed as soon as the container is run) and am unable to capture the output of that script. When I run the container via the normal CLI using
docker run -v /host_dirpath:/cont_dirpath my_image

(host_dirpath is the directory containing foo.py) I get the expected output of foo.py printed to stdout, which is just a dictionary of key-value pairs. However, I'm trying to do this from within python using the docker-py module, and somehow the script output is not being captured by the logs method. Here's the python code I'm using:
from docker import Client

docker = Client(base_url='unix://var/run/docker.sock',
              version='1.10',
              timeout=10)

contid = docker.create_container('my_image', volumes={"/cont_dirpath":""})
docker.start(contid, binds={"/host_dirpath": {"bind": "/cont_dirpath"} })

print "Docker logs: " + str(docker.logs(contid))

Which just results in "Docker logs: " - nothing is being captured in the logs, neither stdout nor stderr (I tried raising an exception inside foo.py to test this).
The results I'm after are calculated by foo.py and are currently just printed to stdout with a python print statement. How can I get this to be included in the docker container logs so I can read it from within python? Or capture this output some other way from outside the container?
Any help would be greatly appreciated. Thanks in advance!
EDIT:
Still no luck with docker-py, but it is working well when running the container with the normal CLI using subprocess.Popen - the output is indeed correctly grabbed by stdout when doing this.

A: You may experience a race condition since the started container is running in parallel to your control program. You need to wait for your container to start and finish before grabbing the logs. Add a docker.wait to your code right after docker.start.
docker.wait(contid)

Your output seems empty because nothing has yet been logged.

A: You are experiencing this behavior because python buffers its outputs by default.
Take this example:
vagrant@docker:/vagrant/tmp$ cat foo.py
#!/usr/bin/python
from time import sleep

while True:
    print "f00"
    sleep(1)

then observing the logs from a container running as a daemon does not show anything:
vagrant@docker:/vagrant/tmp$ docker logs -f $(docker run -d -v $(pwd):/app dockerfile/python python /app/foo.py)

but if you disable the python buffered output with the -u command line parameter, everything shows up:
vagrant@docker:/vagrant/tmp$ docker logs -f $(docker run -d -v $(pwd):/app dockerfile/python python -u /app/foo.py)
f00
f00
f00
f00

You can also inject the PYTHONUNBUFFERED environment variable:
vagrant@docker:/vagrant/tmp$ docker logs -f $(docker run -d -v $(pwd):/app -e PYTHONUNBUFFERED=0 dockerfile/python python /app/foo.py)
f00
f00
f00
f00

Note that this behavior affects only containers running without the -t or --tty parameter.


text:
Q: Target image map to move on mousemove i want to animate  different parts of image on mousemove event . I've divided image in 4 parts like this

<map name="Map" id="Map">
    <area alt="" title="" href="#" shape="poly" coords="58,158,304,188,224,268" />
    <area alt="" title="" href="#" shape="poly" coords="714,62,724,59,721,74,715,178,696,168,676,155,652,150,635,150,762,36" />
    <area alt="" title="" href="#" shape="poly" coords="264,352,185,478,444,356,294,378" />
    <area alt="" title="" href="#" shape="poly" coords="720,209,867,243,418,133,458,162,455,167" />
    [...]
</map>

these parts are clickable but how do i target them separately and move animate them i  need help with this


text:
Q: Prevent chainloading by grub after rEFind I triple booted my Macbook 4,1 with Mac OSX 10.5.8, Lubuntu 14.04 and Windows XP SP3 and installed rEFInd as my bootloader.
Now what basically happens is, first the Mac bootloader loads invisibly, but I know it's there since I can summon it while pressing the option key.
When I choose Mac or Windows it goes straight to the actual loader of that OS, but when I choose Lubuntu it opens the grub bootloader first, giving me the same options. I have set the grub bootloader, to load lubuntu after 1 second, so it doesn't stay there for long time, but how can I just skip grub, like Mac and Windows are doing?
Three loaders (Mac, refind, grub) slows down the boot quite a lot, especially since most of the times I just want to boot to the default OS anyway, so how do I reduce this time? Or is there a reason why I should leave it as it is?

A: There is a distinction between a boot manager and boot loader.
From the official website of rEFInd:

rEFInd is a boot manager, meaning that it presents a menu of options to the user when the computer first starts up [...]. rEFInd is not a boot loader, which is a program that loads an OS kernel and hands off control to it.

but GRUB is both:

Many popular boot managers, such as the Grand Unified Bootloader (GRUB), are also boot loaders, which can blur the distinction in many users' minds.

If you want to remove the timeout in the GRUB boot menu you can edit /etc/default/grub and set
GRUB_TIMEOUT=-1

You then have to do
sudo update-grub


text:
Q: What versions of python, anaconda and tensorflow work best to gether on windows 8.1? taking different machine learning courses. i tried to install tensorflow after deleting my old anaconda/python (which took a while) and downloading 3.7, but then ran into version problems like this. downloading anaconda3 5.20 now.
so is there a preferred combination of recent python, anaconda, and tensorflow versions that play well together on windows 8.1.
edit: looks like anaconda can deal with different versions of python.
edit2: trying:
conda create -n tensorflow pip python=3.5
activate tensorflow
pip install --ignore-installed --upgrade tensorflow

gets tensorflow installed and working but issues a warning:
You are using pip version 10.0.1, however version 18.0 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.
(tensorflow) C:\Users\ray>python -m pip install --upgrade pip
Collecting pip
  Using cached https://files.pythonhosted.org/packages/5f/25/e52d3f31441505a5f3a
f41213346e5b6c221c9e086a166f3703d2ddaf940/pip-18.0-py2.py3-none-any.whl
tensorflow 1.10.0 has requirement setuptools<=39.1.0, but you'll have setuptools
 40.0.0 which is incompatible.
Installing collected packages: pip
  Found existing installation: pip 10.0.1
    Uninstalling pip-10.0.1:
      Successfully uninstalled pip-10.0.1
Successfully installed pip-18.0

so now i have a red warning.


text:
Q: JavaScript: creating a map that maps multiple keys to a value? I have a list of keys and a value. For example:
keys = ["keyA", "keyB", "keyC"];

value = 100;

I'm trying to create a function to create a map so that:
map["keyA"]["keyB"]["keyC"] = 100;

I assumed this was the best data structure based on the answer given here:
Anyway, the part that challenges me is that I need a function that will create a map for any number of keys. I've tried doing this in a loop but can't get it to work because I don't know how to access different levels of my map, but it also feels sloppy:
for(var i=0; i<keys.length; i++){
    for(var j=0; j<i; j++){
        maps[keys[0]]...[keys[j]] = {};
        if(j+1 === i){
            maps[keys[0]]...[keys[j]][keys[i]] = value;
        }
    }
}

How can I create my map?

A: You can try to store a reference to the last created inner object, and go deeper in a loop, in order to make it in a linear time:

// Input data:
var keys = ["keyA", "keyB", "keyC", "keyD", "keyE"];
var value = 100;

// Algorithm:
var result = {};
var last = result;

for (var i = 0; i < keys.length - 1; i++)
{
  last = (last[keys[i]] = {});

  // can be change to a two-liner:
  // last[keys[i]] = {};
  // last = last[keys[i]];
}
last[keys[keys.length - 1]] = value;

// Output:
document.body.innerHTML = JSON.stringify(result);
document.body.innerHTML += "

" + result["keyA"]["keyB"]["keyC"]["keyD"]["keyE"];

A: If you do not want to maintain a hierarchy of objects, I would suggest you concatenate the keys and store the value with the concatenated string as key.
This assumes you always have the same keys array. If your keys array is supplied externally, you can sort before joining.
See the snippet.

var keys = ["keyA", "keyB", "keyC", "keyD", "keyE"];
var value = 568;

var datastructure = {};

datastructure[keys.join("-")] = value;

document.getElementById("output").innerHTML = datastructure[keys.join("-")];

A: Assuming this structure is to be a tree where the nesting has arbitrary depth, first you might benefit from a helper function that lets you access possible non-existent paths safely:
function path(obj, str) {
  return str.split('.').reduce(function (acc, key) {
    return acc instanceof Object ? acc[key] : undefined;
  }, obj);
}

And you also want a way to set such paths neatly:
function setPath(obj, str, val) {
  var path = str.split('.');
  var key  = path.pop();

  var target = path.reduce(function(acc, key) {
    return acc[key] = acc[key] instanceof Object ? acc[key] : {};
  }, obj);

  target[key] = val;
}

Then you have a clean interface for storing and retrieving this data.
map = {};

setPath(map, 'keyA.keyB.keyC', 100);
path(map, 'keyA.keyB.keyC') // 100;
path(map, 'keyA.keyX.keyY') // undefined;

If you prefer, you could have it take arrays of keys instead of dot-notation paths as shown here (just omit the split steps).
Note that if you are never interested in accessing nodes in the tree other than the leaves, or wish to be able to have values for both map.a.b and map.a, you can do this much more simply by having a single depth:
map[keys.join('.')] = 100;

And since you've added in a comment that the objective here is actually just to associate a value with a set of keys, and that there is no actual tree structure at all:
function get(map, keys) {
  var key = keys.sort().join('.');
  return map[key];
}

function set(map, keys, val) {
  var key = keys.sort().join('.');
  map[key] = val;
}

If periods are plausible characters in your keys, substitute a different character that you can safely reserve.

A: Edit 24/12/2022
I have created an ES module for order agnostic multi map. I will explain here how you can set it up for the OP's use case.
https://github.com/martian17/ds-js
First you will want to clone the repository to your project, or copy the code.
$ git clone https://github.com/martian17/ds-js.git

Here is an example use case
// import it to your project
import {OrderAgnosticMultiMap} from "path_to_ds-js/multimap.mjs";

// Instantiate
const map = new OrderAgnosticMultiMap();

// Register values
map.set("keyA", "keyB", "keyC", "content 1");
map.set("keyA", "keyC", "keyC", "content 2");
map.set("keyA", "keyB", "keyB", "content 3");
// The keys can be any object
map.set(map, OrderAgnosticMultiMap, map, window, document, "content 4");

// Get values (keys can be in different orders)
console.log(map.get("keyB", "keyC", "keyA"));
// log: "content 1"
console.log(map.get("keyB", "keyB", "keyC"));
// log: undefined
map.set(document, map, window, OrderAgnosticMultiMap, map);
// log: "content 4"

// Check if a value exists for some keys
console.log(map.has("keyC", "keyC", "keyA"));
// log: true
console.log(map.has("keyA", "keyC", "keyA"));
// log: false

// Loop through values
for(let [tally,value] of map){
    console.log(tally,value);
}
// log:
// Map(3) {"keyA" => 1, "keyB" => 1, "keyC" => 1} 'content 1'
// Map(3) {"keyA" => 1, "keyC" => 2} 'content 2'
// Map(3) {"keyA" => 1, "keyB" => 2} 'content 3'
// Map(3) {map => 2, OrderAgnosticMultiMap => 1, window => 1, document => 1} 'content 4'

// Delete keys
map.delete("keyC", "keyB", "keyA");
map.delete("keyB", "keyB", "keyA");
map.delete("keyC", "keyC", "keyA");
console.log(map.has("keyC", "keyC", "keyA"));
// log: false

Pre-edit
If there is anyone wondering if there is a solution for multi keyed ES6 map, here's my take.
The order does matter though, so map.get(a,b,c) and map.get(c,a,b) will fetch different values.
And you can of course use this as string to object map, so it satisfies the OP's use case as well.
class MultiMap{
    map = new Map;
    own = Symbol();// unique value that doesn't collide
    set(){
        let lst = [...arguments];
        let val = lst.pop();
        let map = this.map;
        for(let k of lst){
            if(!map.has(k))map.set(k,new Map);
            map = map.get(k);
        }
        map.set(this.own,val);// to avoid collision between the same level
        return val;
    }
    get(...lst){
        let map = this.map;
        for(let k of lst){
            if(!map.has(k))return undefined;
            map = map.get(k);
        }
        return map.get(this.own);
    }
    has(...lst){
        let map = this.map;
        for(let k of lst){
            if(!map.has(k))return false;
            map = map.get(k);
        }
        return map.has(this.own);
    }
    delete(...lst){
        let map = this.map;
        let maps = [[null,map]];
        for(let k of lst){
            if(!map.has(k))return false;
            map = map.get(k);
            maps.push([k,map]);
        }
        let ret = map.delete(this.own);
        for(let i = maps.length-1; i > 0; i--){
            if(maps[i][1].size === 0){
                maps[i-1][1].delete(maps[i][0]);
            }else{
                break;
            }
        }
        return ret;
    }
}

Example use case
let a = {a:"a"};
let b = {b:"b"};
let c = {c:"c"};

let mm = new MultiMap;

//basic operations
console.log(mm.set(a,b,c,"abc"));// "abc"
console.log(mm.get(a,b,c));// "abc"
console.log(mm.has(a,b,c));// true
console.log(mm.delete(a,b,c));// true

// overlapping keys can be handled fine as well
mm.set(a,b,"ab");
mm.set(a,"a");
console.log(mm.get(a,b));// "ab"
console.log(mm.get(a));// "a"

For anyone curious about my use case: I was trying to make an event listener wrapper that maps to multiple events internally (mousedown => mousedown, touchstart etc). I needed to cache the arguments when .on() is called so .off() can find the right set of event listeners to remove.


text:
Q: Laravel - "Operator does not exist" exception when fetching a related model with an UUID key I'm running into issues working with a Laravel 8 app. I have two models, User and Post. Post belongs to User.
Both models have UUID as primary keys, and are modeled as such (using PostgreSQL):
        Schema::create('users', function (Blueprint $table) {
            $table->uuid('id')->primary();
        });

        Schema::create('posts', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->uuid('user_id');

            $table->foreign('user_id')->references('id')->on('users');
        });

The relationship is defined as this:
    // Post.php

    public function user()
    {
        return $this->belongsTo(\App\Models\User::class);
    }

Both models also have public $incrementing = false to account for the UUIDs.
The PostsController fetches some Posts as well as their related Users:
    public function index()
    {
        $posts = Post::with('user')->paginate(10);
    }

However this is throwing the following exception:
SQLSTATE[42883]: Undefined function: 7 ERROR: operator does not exist: uuid = integer LINE 1: select * from "users" where "users"."id" in (3) ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. (SQL: select * from "users" where "users"."id" in (3))

Laravel is treating the User's id as an integer (note the 3, the only User on the DB has an id beginning with  3a6bc3c3...). However I cannot seem to find the root cause nor a fix for this.
Any ideas?
Thanks!

A: You probably want to also set the protected $keyType as on Model it is set as int:
protected $keyType = 'string';

"If your primary key is not an integer, you should set the protected $keyType property on your model to string"

Laravel 8.x Docs - Eloquent - Model Conventions - Primary Keys


text:
Q: Creating a 3x3 Rubik's Cube in JavaFX Im interested in working on JavaFX for the first time. I have a project i am working on, in which i dont have a lot of time to complete. I was wondering if javaFX would be a great platform to animate and make a 3x3 rubik's cube game? With all the mouse movements and rotations, Without having to work out alot of linear Algebra.

A: Jelinek provides public domain sample algorithms and source code for creating a Rubik's cube in Swing/AWT.  You could start with that and try converting it to JavaFX, possibly using a Canvas as the drawing surface.
The 3D capabilities in JavaFX 2.2 are quite limited.  There are some samples you could look at in the Ensemble application to give you an idea of what it is capable of.  There is a tutorial on the Ensemble 3D xylophone which should help provide much of the basic knowledge required to build your application.
Java 8 will have a much more comprehensive 3D feature set.  Such an application would likely be much easier to implement in Java 8 than the current JavaFX 2.2 release.  Java 8 is not due for final release until September 2013, but you can download a preview version of Java 8.  The preview version does not currently fully implement all of the planned 3D features for Java 8, but does implement significantly more than the JavaFX 2.2 release, especially around concepts like 3D transformations, normal calculations, vector logic, etc which would be required for the implementation.


text:
Q: Express middleware type is not assignable I have following error. I dont understand why my first, only the first, middleware is red underlined?

Could somebody guide me here? I am quite new to typescript.
Did i forgot something or?

A: The solution was to put the RequestHandler interface infront of my middleware methods
router.get('/dashboardOverview', <RequestHandler>authService.authentication, <RequestHandler>adminController.dashboardOverviewHandler)

And i also need to make sure that the handlers / middlewares always contains Request, Response and NextFunction in their callback


text:
Q: NTFS Limitations What are the limitations of NTFS regarding the number of directories and max allowed files per directory?

A: Maximum allowed is pretty generous. Unlimited files in unlimited directories. The maximum files and directories on a VOLUME is limited to unsigned 32-bit minus 1 (4,294,967,295 objects). Practical limits are another thing, though.
http://technet.microsoft.com/en-us/library/cc780559(WS.10).aspx
Edit: 64-bit windows doesn't seem to change things. I can find no evidence that 64-bit servers have higher limits. The file limit is more of a file-system format problem than a kernel bit-width problem. The next version of Windows may allow more files, it doesn't look like Windows 2008 R2 will be changing this.

A: The maximum number of files per volume is 4,294,967,295 , regardless of where they are located.


text:
Q: From Database to datatable to generic collection to JSon via JQuery Good people, I am in a dilemma and time is definitely not on my side.
My objective
I want to get records from the database via a dataset/datatable, then to a generic collection and finally to a JSon object using JQuery in the client side to improve user experience.
What works so far
My code works in the web service  up to the point when the data is handed over to the client/browser.
What I am not sure about
With my little or virtually no experience with neither JSon nor JQuery, the data from the web service is not displaying in the web browser. I don't know where the problem is.
The code
Here I enclose the rest of my code:

*

*The hotelrates.vb file, the code behind of the hotelrates.asmx file

Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Web.Script.Services
Imports System.Collections.Generic
Imports System.Linq
Imports System.Data
Imports MySql.Data.MySqlClient
Imports System.Reflection

<WebService([Namespace]:="http://tourslogin.net/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _

  </asp:Content>

A: The Rate variable in your js seems to be not declared.
Try to change your success callback function with this:
success: function (response) {
    var rates = response.d;
    $('#output').empty();

    for (var r in rates) {
        $('#output').append('
' + rates[r].myID + ' ' +
                    rates[r].myID + '
 Year: ' +
                    rates[r].mySupplier + '
');

    }
}


text:
Q: How can I create a single dataframe from a list of dataframes in R, when they have different number of rows? I am trying to create a single dataframe from a list, but they have different number of rows.
List of 3
$ :'data.frame':   210 obs. of  1 variable:
..$ protein: chr [1:210] "sp|A0A075B6R9|KVD24_HUMAN sp|A0A0C4DH68|KV224_HUMAN " "sp|O14791|APOL1_HUMAN " "sp|O75636|FCN3_HUMAN " "sp|P00450|CERU_HUMAN " ...
$ :'data.frame':   210 obs. of  1 variable:
..$ protein: chr [1:210] "sp|A0A075B6R9|KVD24_HUMAN sp|A0A0C4DH68|KV224_HUMAN " "sp|O14791|APOL1_HUMAN " "sp|O75636|FCN3_HUMAN " "sp|P00450|CERU_HUMAN " ...
$ :'data.frame':   215 obs. of  1 variable:
..$ protein: chr [1:215] "sp|A0A075B6R9|KVD24_HUMAN sp|A0A0C4DH68|KV224_HUMAN " "sp|O14791|APOL1_HUMAN " "sp|O75636|FCN3_HUMAN " "sp|P00450|CERU_HUMAN " ...
How can I do this in R?
Thanks in advance!

A: Do you want to bind the rows?  Here is a solution with base R using do.call and rbind and a tidyverse solution.
df1 <- data.frame(a = 1:3, b = 4:6)
df2 <- data.frame(a = 11:13, b = 14:16)

df_list <- list(df1, df2)

do.call(rbind, df_list)
#>    a  b
#> 1  1  4
#> 2  2  5
#> 3  3  6
#> 4 11 14
#> 5 12 15
#> 6 13 16

library(tidyverse)
bind_rows(df_list)
#>    a  b
#> 1  1  4
#> 2  2  5
#> 3  3  6
#> 4 11 14
#> 5 12 15
#> 6 13 16

Created on 2022-08-16 by the reprex package (v2.0.1)


text:
Q: Deploying a dhcpd server I'm trying to deploy a DHCP server in a pod on my Kubernetes cluster.
I've created the following resources:

$ cat dhcpd-deployment.yaml

kind: Deployment
metadata:
  name: dhcpd
  namespace: kube-mngt
spec:
  selector:
    matchLabels:
      app: dhcpd
  replicas: 1
  template:
    metadata:
      labels:
        app: dhcpd
    spec:
      nodeSelector:
        kubernetes.io/hostname: neo1
      containers:
      - name: dhcpd
        image: 10.0.100.1:5000/dhcpd:latest
        volumeMounts:
        - name: dhcpd-config
          mountPath: /etc/dhcp
      volumes:
        - name: dhcpd-config
          persistentVolumeClaim:
            claimName: dhcpd-config-volume-claim

$ kubectl create -f dhcpd-deployment.yaml
$ cat dhcpd-service.yaml

apiVersion: v1

kind: Service
metadata:
  name: dhcpd
  namespace: kube-mngt
spec:
  selector:
    app: dhcpd
  ports:
  - name: dhcp
    protocol: UDP
    port: 67
    targetPort: 67

$ kubectl create -f dhcpd-service.yaml

Everything is created successfully, pod and service but unfortunately, the DHCPD pod does not receive any packet on UDP port 67.
Did I miss something?

A: I've found the solution to make the dhcpd pod working well.
The example below is to server a external network outside of the k8s service network (clusterIPs).
The dhcp configuration is like following:
include "/etc/dhcp/dhcpd-options.conf";

subnet 192.168.0.0 netmask 255.255.0.0 {}

# management network
subnet 10.0.0.0 netmask 255.255.0.0 {
  option routers 10.0.255.254;
  option broadcast-address 10.0.255.255;
  next-server 10.0.100.6;
  include "/etc/dhcp/lease-bmc.conf";
  include "/etc/dhcp/lease-node.conf";
}

The k8s service is as following:
$ cat dhcpd-service.yaml
apiVersion: v1
kind: Service
metadata:
  name: dhcpd
  namespace: kube-mngt
spec:
  selector:
    app: dhcpd
  ports:
  - protocol: UDP
    port: 67
    targetPort: 67
  externalIPs:
  - 10.0.100.5

Then, configure the switch (interface vlan X) to specify an helper-address that point the the dhcp server (in our case, 10.0.100.5)
interface Vlan1
 ip address 10.0.255.254 255.255.0.0 secondary
 ip address 10.0.0.1 255.255.0.0
 ip helper-address 10.0.100.5
!


text:
Q: EF - Column default value not being set I'm using EF code first and have the following in my migration file.
public override void Up()
{
    AddColumn("dbo.ConsumerFee", "VATCodeId", c => c.Int(nullable: false, defaultValue: 1));
}

However when the column is added to the table it is given a default value of 0 not 1. When I run the migration manually I can see that it generates this sql :
alter table `ConsumerFee` add column `VATCodeId` int not null

Any ideas what may be up with this?

A: This was happening to me too which was a bummer. However I figured out that the defaultValueSql:"1" will work which sets the default sql expression for this column.
AddColumn("dbo.ConsumerFee", "VATCodeId", c => c.Int(nullable: false, defaultValueSql: "1"));


text:
Q: JavaFX - Derby error missing components in Launch4j I'm making a javafx Library Management System project using intellij idea that uses derby as an embedded db, and it works just fine, but when i convert my project into a jar file using the build artefact option in intellij idea then convert that jar into an .exe file using launch4j and try to run it, it will throw a

JavaFX runtime components are missing, and are required to run this
application

i tried adding the jvm options through the jvm options section in launch4j but then i would get another error saying that i can't access the sub packages that contain the other classes that i want to use  :-

the thing is that i want this program to run when i run the .exe file so is there a way to add these jvm options inside my code, or is there a better way to run javafx-db programs with a different extension ? and how should i include in the jvm options that i'm using sub packages?

A: Solving this took me some time, first you need to set the DERBY_PATH and the PATH_TO_FX to your libs then you need to add these commands in the JVM options
--module-path %DERBY_HOME%;%PATH_TO_FX%
--add-modules javafx.controls,javafx.fxml,java.sql,java.desktop,javafx.swing,javafx.graphics
building this will add the options in an xml file that runs every time you run the program


text:
Q: Show Gtk.Popover at cursor of Gtk.Entry I want to to show a Gtk.Popover at the position of the cursor of a Gtk.Entry. I'm only only able to add the popover relative to the entry itself, but the Gtk.Popover appears at the center of the Gtk.Entry everytime.
Is there a way how I can get the position of my Gtk.Entry cursor and create the popover at this position?

A: You should set the widget to which your popover is relative to, by using Gtk.Popover.relative_to; then you can use Gtk.Popover.pointing_to and the rectangle with the location of the cursor. To get that, use Gtk.Entry.cursor_position to retrieve the index of the cursor in characters and transform it into a location within the Pango.Layout of the Gtk.Entry widget; if the entry is allowed to scroll, you should also get the Gtk.Entry.scroll_offset and subtract it from the coordinates returned by Pango.


text:
Q: org.apache.flink.runtime.checkpoint.CheckpointException: Some tasks of the job have already finished I want to stop a flink task by rest api, and I send request: http://192.168.215.165:8081/jobs/c952ba860604a2c32a7abb9eb5b42b0d/stop ,then I got resoponse :
 {
"request-id": "29c559399243c817055ebbaf7431a8d2"
}

And then I send request: http://192.168.215.165:8081/jobs/c952ba860604a2c32a7abb9eb5b42b0d/savepoints/29c559399243c817055ebbaf7431a8d2,
I got the response:(part of)
{
    "status": {
        "id": "COMPLETED"
    },
    "operation": {
        "failure-cause": {
            "class": "java.util.concurrent.CompletionException",
            "stack-trace": "java.util.concurrent.CompletionException: org.apache.flink.runtime.checkpoint.CheckpointException: Some tasks of the job have already finished and checkpointing with finished tasks is not enabled. Failure reason: Not all required tasks are currently running.\n\tat java.util.concurrent.CompletableFuture.encodeRelay(CompletableFuture.java:326)\n\tat java.util.concurrent.CompletableFuture.completeRelay(CompletableFuture.java:338)\n\tat java.util.concurrent.CompletableFuture.uniRelay(CompletableFuture.java:925)\n\tat java.util.concurrent.CompletableFuture$UniRelay.tryFire(CompletableFuture.java:913)\n\tat java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:488)\n\tat java.util.concurrent.CompletableFuture.completeExceptionally(CompletableFuture.java:1990)\n\tat org.apache.flink.runtime.rpc.akka.AkkaInvocationHandler.lambda$invokeRpc$0(AkkaInvocationHandler.java:246)\n\tat java.util.concurrent.CompletableFuture.uniWhenComplete(CompletableFuture.java:774)\n\tat java.util.concurrent.

How can I stop a flink job by rest API please ?

A: A few alternatives:

*

*set execution.checkpointing.checkpoints-after-tasks-finish.enabled: true in your configuration (this is a somewhat experimental feature that was added in 1.14, but it should work)

*modify your job so that all of the tasks are still running at the time when the job is ready to be stopped

*terminate the job without taking a savepoint


text:
Q: Sorting on compound Indexes This may be a novice question but could it be possible query here.
If I have a compound Index as
{ a: 1, b: 1, c: 1, d: 1 }
Is this query possible?
db.data.find( { a: {$gte:1,$lt:2}, b: { $gt: 3} },c:"test",d:"yes" ).sort( { b: 1 } )

I mean can I use sorting on field b with this compound index and the specified query or do I need to create a separate index on b?

A: Compound indexes are great for static values
Flip the WHERE components so that static values are first
db.data.find( { c:"test", d:"yes", a: {$gte:1,$lt:2}, b: {$gt: 3} }).sort( { b: 1 } )

Create a different compound index
db.data.ensureIndex({c:1},{d:1},{b:1},{a:1})

How does it help ?

*

*Static c value

*Static d value

*Sorted Range on b
One more thing
{$gte:1,$lt:2} is really {$eq:1}
I have discussed covering indexes and how the order of columns can changes things. In these posts, I talked about it from the MySQL perspective:

*

*Apr 11, 2014 : Why is MySQL not using the index with the higher cardinality?

*Aug 11, 2013 : How to index for a query with independent range conditions?

*Nov 13, 2012 : Must an index cover all selected columns for it to be used for ORDER BY?


text:
Q: Cannot select a value from a dropdown using selenium I'm trying to automate one of the web apps using selenium but stuck at one point , there is an input field where I have to input some location and based on that location I get the output from google maps as shown in the following image:

now the problem is when I m trying to inspect the locations that are coming in dropdown by right click> inspect the dropdown goes away. This might be happening because the locations are coming from google maps api and not part of the web page I m trying to automate. But if there is any suggestion pls tell me.

A: I suppose your problem is you are unable to inspect the auto-suggest dropdown. If you right-click and inspect the drop-down list(or any one of the list suggestion), it will disappear.
So, to know the className or other attributes of the drop-down list so that you can automate it, do the following:
1) Right-click and inspect on the search-box. (NOT the drop-down list, but the search box which generates it).
2) Now, check the <div> below the search box element. It should most probably be your drop-down list.
3) If it really is the the drop-down list, it will contain <ul>elements.
4) Once you have your list elements, you can automate them. Check this for automating auto-suggest list.

A: I think you should not need to test google maps api. So you can do like this:
public void inputAddress(String address) {
            INPUT_FIELD.sendKeys(address);
            //possibly here should be some sleep =(
            INPUT_FIELD.sendKeys(Keys.TAB);
    }

notice: in this case will be accepted first suggestion from list

A: i was facing the same issue and resolved it by pausing the DOM.
Steps:

*

*Inspect the text box element ,It will get highlighted in your DOM.

*Now start typing, hover your cursor on list, may be first element.

*Select "F8", it will pause your DOM, and you can see the details of List element in DOM.

Hope its helpful.


text:
Q: I want to set my variable value like this I'm coding a function visualization program in Processing in Python 3.x
How can I set variable value from a string, like I want.
Here's how i would like to set it:
fnc = "sin(x)"

y = some_function_to_do_this(fnc)

y = sin(x)

Is there any solution for this problem, or unfortunately I have to forget it away!

A: Try using exec(), like this:
fnc = "print('hi')"
y=exec(fnc)


text:
Q: How can I access variables in a function from the global scope? I can't access variables in a function from the global scope. Normally I can access variables in the other function.
How can I use the str variable in the following code in the global scope?
 <html>
 <script>
 function myf(){
 str = "Change";
 document.write(str);
 }
 document.write(str); // can not access str
 </script>
 <input type="button" value="OPEN" onclick="myf();">
 </html>

A: Declare str globally to explicitly set it's scope.
var str;
function myf(){
  str = "Change";
  document.write(str);
}
myf();
document.write(str); // can access str

Keep in mind that without the call to myf() the value of str remains undefined.
In general, you don't want to modify global variables inside a function because of dependency issues. Consider something like:
function myf() {
  return "Change";
}
document.write(myf());

Or if you need state:
function myf() {
  var state = "Change";
  return {
    get_state: function () {
      return state;
    },
    set_state: function () {
      //
    }
  }
}

var f = myf();
document.write(f.get_state());

A: The way you are doing … except that you have to run the code in the right order.
Currently you are:

*

*Defining (but not running) a function that sets str and writes it to the document (deleting the existing document in the process)

*Trying to use that variable

*Clicking on a button which runs that function and gives the variable a value

You have to swap the order of the last two tasks … and stop using document.write inside the function.
It is also good practise (and required in JavaScript strict mode) to declare your variables before you use them. You should put var str at the top of your script.


text:
Q: how to shift text right in a tabular data This is code in a simple document I am writing abbreviations.
\begin{tabular}{l l}
        \textbf{VM} & Virtual Machine\\
        \textbf{AWS} & Amazon Web Services\\
        \textbf{GCP} & Google Cloud Platform \\
        \textbf{IaaS} & Infrastructure as a Service \\
        \textbf{PaaS} & Platform as a Service \\
        \textbf{SaaS} & Software as a Service \\
        \textbf{AaaS} & Authentication as a Service \\
        \textbf{CaaS} & Communication as a Service \\
        \textbf{EC2} & Proprietary Technology of Amazon,Stands for Elastic Compute Cloud \\
        \textbf{DaaS} & Desktop as a Service \\
        \textbf{Multi Tenant} & Multi tenant is a phrase used to describe multiple customers  using same cloud \\
        \textbf{Private Cloud} & Used to describe cloud implemented within corporate firewall.\\
        \textbf{Public Cloud} & Refers to cloud services provided to users over internet to any one who\\ purchases the service.\\
    \end{tabular}
\end{table}

When I compile it then the last line
    \textbf{Public Cloud} & Refers to cloud services provided to users over internet to any one who\\ purchases the service.\\

this giving me problems I want to write more abbreviations but then it appears as following

in the image above I want to move the text
purchases the service. horizontally but I am not able to move it horizontally it comes below the bolded abbreviations and this makes my document ugly. What should I do in this case so that text shifts right and I can add more abbreviations.

A: As @leandriis has already suggested in a comment, you may want to employ a tabularx environment, set its overall width to \textwidth, and use the X column type for the second, i.e., right-hand, column to allow automatic line wrapping while automatically selecting the maximum possible column width.
Another suggestion: Don't use bold-face for the first column, unless you either think it's essential to shout at your readers or just want to signal, "Look at me, Mom! I know how to use bold-face in LaTeX!" (and thus simply show no regard for the sentiment of your readers who don't really appreciate being shouted at). Even if one of these conditions is satisfied, don't encase every single word in the left-hand column of the table in \textbf wrappers; instead, just change the l column specifier to >{\bfseries}l.

\documentclass{article}
\usepackage{tabularx} % for 'tabularx' env. and 'X' col. type
\begin{document}
\section*{List of Abbreviations}
\begin{tabularx}{\textwidth}{@{} l X @{}}
VM   & Virtual Machine\\
AWS  & Amazon Web Services\\
GCP  & Google Cloud Platform \\
IaaS & Infrastructure as a Service \\
PaaS & Platform as a Service \\
SaaS & Software as a Service \\
AaaS & Authentication as a Service \\
CaaS & Communication as a Service \\
EC2  & Proprietary Technology of Amazon, Stands for Elastic Compute Cloud \\
DaaS & Desktop as a Service \\
Multi Tenant  & Multi tenant is a phrase used to describe multiple customers  using same cloud \\
Private Cloud & Used to describe cloud implemented within corporate firewall\\
Public Cloud  & Refers to cloud services provided to users over internet to any one who purchases the service\\
\end{tabularx}
\end{document}


text:
Q: In the MVC pattern, should the listeners be in the Controler? I have buttons that i bind to an event click in jquery :
$('myselection').click(myfunction);

Should they be in the controller ?
I was thinking so but i encountered a situation that made me doubt. In my js view, i create a form and its submit button. I need to attach an event listener to it such as :
$('mybutton').click(myfunctiontosubmit);

I can't figure a way to let the controller manage this listener because the button does not exists when i first call my view.

A: Usually not. Their place is in the views, however they could call methods in controllers.
Ember.js has the following description for it's Views.

Ember.View is the class in Ember responsible for encapsulating templates of HTML content, combining templates with data to render as sections of a page's DOM, and registering and responding to user-initiated events.

As well as having a simplified API to use said events in the view.


text:
Q: Access join of two subqueries I am constructing a simple database for an inventory system, with a barcode  reader.  I have one form to add inventory, and one form to remove inventory.  Each adjust add a column to the add or remove table.
I made queries for my add and remove that return the total value of each item, associated with the id for each item.  I want to join my add and remove tables so I can calculate the difference for a current quantity.
I am running into trouble with joining my add subquery and my remove subquery.
Add:
SELECT Items.description, Count(Trans_Add.s) AS Quantity
FROM Items INNER JOIN Trans_Add ON Items.ID = Trans_Add.s
GROUP BY Items.description;

Remove:
SELECT Items.description, Count(Trans_Remove.s) AS Quantity
FROM Items INNER JOIN Trans_Remove ON Items.ID = Trans_Remove.s
GROUP BY Items.description;

Whenever I try to assign alias for either in the from clause of my new query and join them it does not work.

A: Try:
SELECT Items.ID, Items.Description, (Items.TotalCount + A.Quantity - B.Quantity) as OnHandQty
FROM Items INNER JOIN
(SELECT Items.ID, Count(Trans_Add.s) AS Quantity
FROM Items INNER JOIN Trans_Add ON Items.ID = Trans_Add.s
GROUP BY Items.description
) A
ON Items.ID = A.ID
INNER JOIN (
SELECT Items.description, Count(Trans_Remove.s) AS Quantity
FROM Items INNER JOIN Trans_Remove ON Items.ID = Trans_Remove.s
GROUP BY Items.description
) B
ON Items.ID = B.ID

I made up a Field named TotalCount because you did not mentioned what is the Item Quantity in Items table. So, change it accordingly, that is, according to the
right field name for Item Quantity from Items table.


text:
Q: Challenge to iterate truncated md5 hash i need an help to this challenge of programming.

"With this string: NzQwZjgxMTU2YzI3NjM1NA==
MD5 hash it and remove the last 16 characters of the hash. Iterate
this process 50 times and submit the final truncated hash below."

What language can i use?
Anyone can explain me the script to do?

A: import hashlib

originalhash = 'MGE0ZjFmODRhMTQ0ZTJjYQ=='
print(originalhash)
previous = hashlib.md5(original.encode('ascii')).hexdigest()
print(previous)

for i in range(50):
        text = previous[0:-16]
        print(text)
        nexthash = hashlib.md5(previous.encode('ascii')).hexdigest()
        print(nexthash)
        previous = nexthash


text:
Q: Best-matching sets of individual records into group representatives in c#
We're developing a business application using code-first Entity
  Framework, and I'm looking for a solution to the following problem
  that stays out of the database if possible.

We have a persistence model that looks similar to the following:
public abstract class DataCode
{
   public long Id { get; set; }
   public string Code { get; set; }
   public string Description { get; set; }
}

public class Option : DataCode
{
   // a bunch of stuff that describes an Option
}

public class Model : DataCode
{
   // a bunch of stuff that describes a product model
}

public class Version
{
   public long Id { get; set; }
   // a bunch of stuff that describes a version of the product model
}

public class ModelOptionVersion
{
   public Model ThisModel { get; set; }
   public Option WithThisOption { get; set; }
   public Version UsingThisVersion { get; set; }
   // a bunch of stuff that is important to track
   // at the intersection of these three properties
}

It all works fine, except that the users want to use "Family Codes" and "Common Codes" to apply property values.  To support that, I think the following classes will work:
public abstract class CodeGroup
{
   public virtual ICollection<DataCode> DataCodes { get; set; }
}

public class Family : CodeGroup, DataCode
{
   public Family(ICollection<Model> Models)
   {
      base:DataCodes = Models;
   }
}

public class CommonCode : CodeGroup, DataCode
{
   public Family(ICollection<Option> Options)
   {
      base:DataCodes = Options;
   }
}

This is all well and good for expansion of FamilyCode and CommonCode, along with some logic, into individual ModelOptionVersion records (foreach Model in Family...).  However, what stumps me is how to best-match a group of ModelOptionVersion records back into FamilyCode or CommonCode representatives.
If this were Ford (it's not), the data might look like this:
Family    | Model
Trucks    | F-150
Trucks    | F-250
Trucks    | F-350
SuperDuty | F-250
SuperDuty | F-350

CommonCode     | Option
Gas Engines    | 4.6l V-8 Gas
Gas Engines    | 5.4l V-8 Gas
Diesel Engines | 6.4l V-8 Diesel
Diesel Engines | 7.3l V-8 Diesel
Diesel Engines | 6.0l V-8 Diesel

Model | Option          | Version
F-150 | 4.6l V-8 Gas    | 2015
F-150 | 4.6l V-8 Gas    | 2016
F-150 | 5.4l V-8 Gas    | 2015
F-150 | 5.4l V-8 Gas    | 2016
F-250 | 5.4l V-8 Gas    | 2015
F-250 | 5.4l V-8 Gas    | 2016
F-350 | 5.4l V-8 Gas    | 2015
F-350 | 5.4l V-8 Gas    | 2016
F-250 | 6.4l V-8 Diesel | 2015
F-250 | 6.4l V-8 Diesel | 2016
F-350 | 6.4l V-8 Diesel | 2015
F-350 | 6.4l V-8 Diesel | 2016

The users want to price things based on "Super Duty with Diesel Engine" or "2016 Truck with Gas Engine".  They not only want to see it that way when they create the price record, but when they go back and look at it later.  So I need a way to not only expand the FamilyCode and DataCode members, but roll them up.  But it's not necessarily obvious from the data what the source of data was.  Also, the system should be smart enough that when someone says "this is only available on the F-250 and F-350," the system says "use SuperDuty".
It seems to me that I need some sort of best-match solution, perhaps some lightweight fuzzy logic.  Do .NET libraries for this exist?  Do I have to craft it from scratch?  How can I achieve this?

A:
However, what stumps me is how to best-match a group of
  ModelOptionVersion records back into FamilyCode or CommonCode
  representatives.

What you are trying to do here is to find FamilyCodes (or CommonCodes) such that every ModelOptionVersion in some set has a Model specified by that FamilyCode.
var desiredModels = // some collection of Models

var familyCodesByFamily = (
    from familyCode in db.FamilyCodes
    group familyCode by familyCode.Family into family
    select family);

var applicableFamilies = (
    from family in familyCodesByFamily
    where desiredModels.All(dm => family.Any(f=> f.Model == dm))
    select family.Key).ToList();

I haven't measured how that kind of query performs, but it doesn't map very directly to what SQL can do.  SQL doesn't directly let you do universal quantifiers ("give me the x such that for all x, y"), but it does let you do existential quantifiers ("give me the x such that there exists a y") and negation.  If it turns out that the above doesn't perform well, an alternative formulation that should be semantically equivalent is:
var incorrectFamilies =
    (from familyCode in db.FamilyCodes
    where !desiredModels.Contains(familyCode.Model)
    select familyCode.Family).Distinct();

var correctFamilies =
    (from familyCode in db.FamilyCodes
    where !incorrectFamilies.Contains(familyCode.Model)
    select familyCode.Family).Distinct().ToList();

These generate different SQL, with the natural-seeming first alternative giving more convoluted SQL than the second alternative.  Whichever style you choose, the code for CommonCode should follow the same template.
EDIT: For true fuzzy matching, let's develop two measures for how good a match is between a set of models and family.  The first (and more important) measure we'll call "coverage", which relates to how many models are included in the family.  The second we'll call "fit", which relates to how many members of the family are included in the set of models (if you have two families, both of which completely contain the desired models, we want the family that has fewer extra models outside our desired set).  We'll order our results by the goodness of the matches, then take the number of results we can handle.
var fuzzyFamilies = (
    from family in familyCodesByFamily
    let coverage = desiredModels.Average(dm => family.Any(f => f.Model == dm) ? 1.0 : 0.0)
    let fit = family.Average(f => desiredModels.Contains(f.Model) ? 1.0 : 0.0)
    orderby coverage descending, fit descending
    select family.Key)
    .Take(resultCount)
    .ToList();


text:
Q: application created with New-MsolServicePrincipal not showing up in Azure portal I'm using PowerShell to register an application in Azure AD:
New-MsolServicePrincipal `
-DisplayName $appDisplayName `
-Addresses $addys `
-ServicePrincipalNames @($spn)

The command completes successfully with the following output:
The following symmetric key was created as one was not supplied 7JEl99ZJ1ZWDS...

DisplayName           : My App
ServicePrincipalNames : {https://blah.com/myapp, db286381-a896-4290-8179-...}
ObjectId              : 0a197d26-49b8-4e9b-8739-...
AppPrincipalId        : db286381-a896-4290-8179-...
TrustedForDelegation  : False
AccountEnabled        : True
Addresses             : {Microsoft.Online.Administration.RedirectUri}
KeyType               : Symmetric
KeyId                 : c3a709e5-7d23-4d1a-842b-...
StartDate             : 11/24/2014 6:30:19 PM
EndDate               : 11/24/2015 6:30:19 PM
Usage                 : Verify

I can also use Get-MsolServicePrincipal to verify that the Service Principal now exists.  But when I go to https://manage.windowsazure.com and look in my Azure AD tenant under applications, it's not there.  Shouldn't I be able to see the app in the portal?

A: The applications you see in the portal are projections of the Application entities in the directory. The apps created via powershell are only ServicePrincipals I believe. For a detailed explanation of the difference between the two see http://msdn.microsoft.com/en-us/library/azure/dn132633.aspx


text:
Q: How to remove a status message added by the seam security module? I would like to show a different status message, when a suspended user tries to login. If the user is active we return true from the authenticate method, if not we add a custom StatusMessage message mentioning that the "User X has been suspended". The underlying Identity authentication also fails and adds a StatusMessage. I tried removing the seam generated statusMessage with the following methods, but it doesn't seem to work and shows me 2 different status messages (my custom message, seam generated). What would be the issue here?
StatusMessages statusMessages;

statusMessages.clear()
statusMessages.clearGlobalMessages()
statusMessages.clearKeyedMessages(id)

EDIT1:
public boolean authenticate() {

    log.info("Authenticating {0}", identity.getCredentials().getUsername());

    String username = identity.getCredentials().getUsername();
    String password = identity.getCredentials().getPassword();

    // return true if the authentication was
    // successful, false otherwise
    try {
        Query query = entityManager.createNamedQuery("user.by.login.id");
        query.setParameter("loginId", username);
        // only active users can log in
        query.setParameter("status", "ACTIVE");

        currentUser = (User)query.getSingleResult();
    } catch (PersistenceException ignore) {
        // Provide a status message for the locked account
        statusMessages.clearGlobalMessages();
        statusMessages.addFromResourceBundle(
                "login.account.locked", new Object[] { username });
        return false;
    }

    IdentityManager identityManager = IdentityManager.instance();
    if (!identityManager.authenticate(username, "password")) {
        return false;
    } else {
        log.info("Authenticated user {0} successfully", username);
    }
}

A: You can see the status messages used by Seam (You must define them in the resource bundle)

*

*org.jboss.seam.loginFailed

*org.jboss.seam.loginSuccessful

*org.jboss.seam.NotLoggedIn

So you may want to override org.jboss.seam.loginFailed key (Do not forget register your resource bundle)
somePropertiesFile.properties

org.jboss.seam.loginFailed=<YOUR_CUSTOM_MESSAGE_GOES_HERE>

And use the following one
<h:messages globalOnly="true"/>

To show authentication messages

UPDATE
If you want a custom message, do as Follows
Starting with Seam 2.1, your should authenticate your user by injecting Credential instead of Identity
@Name("authenticationManager")
public class AuthenticationManager {

    private @In org.jboss.seam.security.Credentials credentials;

    public boolean authenticate() {

        private String username = credentials.getUsername();
        private String password = credentials.getPassword();

        try {

            Query query = entityManager.createNamedQuery("user.by.login.id");
            query.setParameter("loginId", username);
            query.setParameter("status", "ACTIVE");

            currentUser = (User) query.getSingleResult();

        } catch (PersistenceException ignore) {
            return false;
        }

        return true;
    }

}

And inside you JSF Form, use, again, credentials instead of identity
<h:inputText id="username" value="#{credentials.username}"/>
<h:inputText id="password" value="#{credentials.password}"/>

To show your custom message, do as follows
<h:outputText value="#{credentials.username} has been suspended" rendered="#{not identity.loggedIn}"/>

Now i hope it works fine!

A: If you set the message to blank in message.properties:
org.jboss.seam.loginFailed=
org.jboss.seam.loginSuccessful=Welcome, #0!
This will cause the seam system status message is not invisible
then you add your custom statusMessage into the page.

A: I had similar problems (this message thing was one of many trust me!) and I just don't use the seam security module anymore. It's not very flexible/extensible, even all the doc say it is (I think it's a lot of self-back-patting by the part of the developer who wrote it all). A similar example I had a bunch of trouble trying to squeeze into this was the handling of a forced password change during the login process. I tore out a lot of my hair before deciding that the whole seam security module just wasn't up to par. It was a bit of a pain, but I have absolutely no regrets. Good luck!


text:
Q: need help to getting started with cordova windows phone 10 application I am cordova developer. I did application in windows phone 8 and windows phone 8.1.
but now after windows phone upgrade to 10 i need to make my app compatible to windows phone 10 also.
but i couldn't find any doc for making windows phone 10 app in cordova documentation.
Can any one help in this?
Thank you in advance.

A:
Adding Windows 10 support to your app is as easy as setting your Windows target platform version to 10.0 (config.xml):

<preference name="windows-target-version" value="10.0" />
<preference name="windows-phone-target-version" value="10.0" />

Cordova for Windows 10 docs
Visual Studio Tools For Apache Cordova-way


text:
Q: Android Receiveing data from another apps with limited files I am following this example to receiving data from another application on share action. Now I have successfully handle the data with single file and multiple files and used in application.
But I want to set limit for multiple file received. I have set the limit inside my application it'll opening first and then finish instead of this I want don't allow to open my application like WhatsApp have done like if you passing more than 10 files app was not open instead its just display message like "Cannot share more than 10 media files".
Any suggestion will be appreciated
Thanks

A: I got solution by myself as we open the default application activity instead of open transparent activity and check whether the image list getting more than 10 or not if more than 10 display Toast message and return otherwise use in application.
Now I have also face the strange issue that when you getting images from Google Photo Application we'll be getting URI now if you forword that URI to another activity it'll be not available to another. Just because Google Photo App have allow accessing for single activity only. If you forword that using intent.putextra and pass to another activity and access that image you'll be getting error "Permission denied to access".
So the solution is just find the absolute path and store image in your application and then forword to another component of your application.
To find the absolute path code is here
Receiving Simple Data from Other Apps
Hope this will helpful to you


text:
Q: How to avoid landing page turn back in flutter The following code is main.dart:
import 'package:flutter/material.dart';
import 'landing page.dart';

    void main() {
      runApp(new MaterialApp(
        home: LandingPages(),
      ));
    }

And here is my landing page class:
import 'package:flutter/material.dart';
import 'package:listview/devices.dart';
import 'main.dart';

class LandingPages extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Is there anybody out there?',
      home: new Scaffold(
          body: new Stack(
            children: <Widget>[
              new Container(
                decoration: new BoxDecoration(
                  image: new DecorationImage(
                      image: new AssetImage( 'images/landing.png'),
                      fit: BoxFit.cover
                  ),
                ),
              ),
              new InkWell(
                onTap: () =>print(Navigator.of(context).push(new MaterialPageRoute(builder:(BuildContext)=>MyApp()))),

              )

            ],
          )
      ),
    );
  }
}

And my second page, the one that I can easily turn back to landing page:
import 'package:flutter/material.dart';
import 'package:listview/devicepage.dart';

void main(){
  runApp(new MaterialApp(
    home: new MyApp(),
  ));
}
class MyApp extends StatefulWidget{
  @override
  _State createState() =>new _State();

}
class _State extends State<MyApp>{

  List<bool> _data =new List<bool>();

  @override

  void initState() {
    setState(() {
      for (int i=0;i<10;i++){
        _data.add(false);
      }
    });
  }
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar:new AppBar(
        title: new Text("خانه هوشمند"),
      ),
      body: new ListView.builder(
        itemCount: _data.length,
        itemBuilder: (BuildContext,int index){
          return   new Card(
            child: new Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[

                new Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: <Widget>[
                    new Image.asset(
                      'images/acc.png',
                      height: 100.0,
                      fit: BoxFit.contain,
                    ),
                  ],
                ),

                const ListTile(

                  title: const Text('نام دستگاه',textAlign: TextAlign.left,),
                  subtitle: const Text('آخرین وضعیت موجود',textAlign: TextAlign.left,),
                ),
                new ButtonTheme.bar( // make buttons use the appropriate styles for cards
                  child: new ButtonBar(
                    children: <Widget>[
                      new FlatButton(
                        child: const Text('بیشتر'),
                        onPressed: () { Navigator.push(context,MaterialPageRoute(builder: (context)=> DevicePage())); },
                      ),

                    ],
                  ),
                ),
              ],
            ),
          );

        },
      ),
    );
  }
}

There is no back button in my second page, but when I use the back button in my phone, it will turns back can any one tel me how to solve my problem?

A: Use Navigator.pushReplacement() instead of push in your landing page.


text:
Q: I stopped the make command mid-way, will previous build be affected? I built a very big project, which had a number of sub-projects, using make command. It took me 3 hours. Then by mistake (without cleaning the previous build) I re-executed the make command for a few minutes and then stopped it.
Have I ruined my previous build? How does make actually work behind the scenes? Are building the object files done in an atomic and safe manner?
Note: I cannot really run any of my binary files to see if they are broken since that's another lengthy process. I just want to know if I am fine or I have to re-run the make and let it finish.

A: If you want to publish this binary as a production version of your commercial product, then I would not rely on it, always be 100% sure that you are using a successfully built version of a fully saved and committed code base.
On the other hand, I you need this for debugging purposes, then you could use this! why? because the make system overrides the output binary only once if finishes compiling all the object files and only if it detects changes that requires a relink of the binary:

After recompiling whichever object files need it, make decides whether to relink edit. This must be done if the file edit does not exist, or if any of the object files are newer than it. If an object file was just recompiled, it is now newer than edit, so edit is relinked.

From GNU make: How Make Works
So if you haven't changed your code base, the linker will not relink the binary, leaving it as it was created by the successful build.


text:
Q: How to dynamically change color of selected category using dropdown box? I am working on an app that takes in 2 inputs to update a scatterplot displaying the results of a cluster analysis. The first input filters the points on the graph through a time range slider. The second input is a dropdown box that is intended to highlight the color of a category of interest on the graph. The categories available in the dropdown box are the different clusters resulting from cluster analysis done on the time range of data. Depending on the time range selected, there may be a different number of clusters available.
I want to be able to color the categories not selected in various continuous shades of grey and the selected category to be colored green or something vibrant that stands out. As of now, I have a combination of
color_discrete_map

and
color_continuous_scale

to meet this requirement, but it does not seem to be working. The color_discrete_map argument seems to be overruled by the color_continuous_scale argument.
Here is my code so far:
#Import packages
import pandas as pd
import numpy as np
import os
import plotly.express as px
import dash
from dash import dcc, html
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output
from sklearn.cluster import KMeans
from sklearn.impute import KNNImputer
from kneed import KneeLocator
from sklearn.preprocessing import StandardScaler
import random

cluster_choices = ["Cluster 1","Cluster 2","Cluster 3","Cluster 4","Cluster 5"]

options1 = ['Alabama','Wyoming','California','Tennessee','Texas']
options2 = random.sample(range(1991,2020),20)
options3 = random.sample(range(1000),20)
options4 = random.sample(range(750),20)
options5 = random.sample(range(500),20)

list1 = np.random.choice(options1, size=250, replace=True).tolist()
list2 = np.random.choice(options2, size=250, replace=True).tolist()
list3 = np.random.choice(options3, size=250, replace=True).tolist()
list4 = np.random.choice(options4, size=250, replace=True).tolist()
list5 = np.random.choice(options5, size=250, replace=True).tolist()

df = pd.DataFrame(list(zip(list1, list2, list3, list4, list5)),
               columns =['State', 'Year','Metric1','Metric2','Metric3'])

app = dash.Dash(__name__,assets_folder=os.path.join(os.curdir,"assets"))
server = app.server
app.layout = html.Div([
    dcc.Tabs([
        dcc.Tab(label='Dashboard',
            children=[
                dbc.Row([
                    dbc.Col([
                        dcc.RangeSlider(
                                    id='range_slider',
                                    min=1991,
                                    max=2020,
                                    step=1,
                                    value=[1991, 2020],
                                    allowCross=False,
                                    pushable=2,
                                    tooltip={"placement": "bottom", "always_visible": True}
                        )
                    ],width=6),
                    dbc.Col([
                        dcc.Dropdown(
                            id='dropdown1',
                            options=[{'label': i, 'value': i} for i in cluster_choices],
                            value=cluster_choices[0],
                        )
                    ],width=6)
                ]),
                 dbc.Row([
                    dbc.Col([
                        dcc.Graph(id='cluster_graph')
                    ],width=12)

                ])
            ]
        )

    ])
])

#Configure reactivity of cluster map controlled by range slider
@app.callback(
    Output('cluster_graph', 'figure'),
    Output('dropdown1', 'options'),
    Input('range_slider', 'value'),
    Input('dropdown1','value')
)

def update_cluster_graph(slider_range_values,dd1):
    filtered = df[(df['Year']>=slider_range_values[0]) & (df['Year']<=slider_range_values[1])]

    X = filtered

    #Step 1.) Break out into state and non-state dfs
    states = pd.DataFrame(X[['State']])
    not_states = X.loc[:, ~X.columns.isin(['State'])]

    #Step 2.) Impute the non-text columns
    imputer = KNNImputer(n_neighbors=5)
    not_states_fixed = pd.DataFrame(imputer.fit_transform(not_states),columns=not_states.columns)

    #Step 3.) Perform clustering
    scaler = StandardScaler()
    data_scaled = scaler.fit_transform(not_states_fixed)

    #Step 4.) Define the kmeans function with initialization as k-means++
    kmeans = KMeans(n_clusters=3, init='k-means++')

    #Step 5.) Fit the k means algorithm on scaled data
    kmeans.fit(data_scaled)

    SSE = []
    for cluster in range(1,10):
        kmeans = KMeans(n_clusters = cluster, init='k-means++')
        kmeans.fit(data_scaled)
        SSE.append(kmeans.inertia_)

    kl = KneeLocator(
        range(1, 10), SSE, curve="convex", direction="decreasing"
    )
    #Step 6.) Identify # of clusters
    elbow = kl.elbow

    kmeans = KMeans(n_clusters = elbow, init='k-means++')
    kmeans.fit(data_scaled)
    pred = kmeans.predict(data_scaled)

    #Step 7.) Get clusters back in original df
    frame = pd.DataFrame(data_scaled)
    frame['cluster'] = pred
    frame['cluster'].value_counts()

    clusters = frame['cluster'] +1

    not_states_fixed = not_states_fixed.dropna()
    not_states_fixed['cluster'] = clusters.values
    not_states_fixed['cluster'] = not_states_fixed['cluster'].astype('str')

    state_list = states['State'].values.tolist()

    not_states_fixed['State'] = state_list

    X = not_states_fixed

    #This is the filtered list that gets populated in the dropdown box
    cluster_list = X['cluster'].unique().tolist()
    cluster_list.sort()
    label = 'Cluster '
    new_cluster_list = [label + x for x in cluster_list]

    sortedX = X.sort_values(by='cluster',ascending=True)
    sortedX['cluster_num'] = sortedX['cluster'].astype(int)
    sortedX['cluster'] = 'Cluster '+sortedX['cluster']

    fig = px.scatter(
        sortedX,
        x="Metric1",
        y="Metric2",
        color="cluster_num",
        color_discrete_map={
                f"{dd1}": "green"
        },
        color_continuous_scale="Greys",
        hover_data = {
            "State":True,
            "Year":True,
            "Metric1":True,
            "Metric2":True,
            "Metric3":True
        },
        template='plotly_dark'

    )
    fig.update_traces(marker=dict(size=10,
                              line=dict(width=0.5,
                                        color='white')),
                  selector=dict(mode='markers'))

    return fig, [{'label':i,'value':i} for i in new_cluster_list]

if __name__=='__main__':
    app.run_server()

Not sure how to fix the issues mentioned above. Can anyone point me in the right direction? Any help would be appreciated!
Thank you!

A: You have three different ways of changing the colors:
color="cluster_num",
color_discrete_map={
        f"{dd1}": "green"
},
color_continuous_scale="Greys",

And they contradict each other. First of all remove "color_continuous_scale" and "color_discrete_map" entirely. You seem to want custom defined colors, not predefined colors.
From my experience the best way to do this is to add a separate column that has a color defined for each row of the data. This way you have complete control of the color logic.
Create a column that holds the color value for each datapoint. This can be a hexadecimal value or RGBA (if you also want to control opacity). A pandas lambda function is a simple way of doing this:
# adjust color threshold as needed
def assign_color(value):
    float_value = float(value)
    if float_value > 2:
        return "rgba(250, 0.0, 0.0, 1.0)"
    elif float_value > 0 and float_value < 2:
        return "rgba(250, 138, 5, 1.0)"
    else:
        return "rgba(236, 236, 236, 0.6)"  # "lightgray"

sortedX['color'] = result.apply(lambda x: assign_color(x["data_column"]), axis = 1)

Then, you should just be able to assign the color to the value of the column:
fig = px.scatter(
    sortedX,
    x="Metric1",
    y="Metric2",
    color="color",
    ...
)

Edit:
If that does not work then its probably because of your marker definition. Remove the color="color" line from above and update your marker definition (in fig.update_traces):
marker=dict(color = sortedX["color"],
            size = 4)


text:
Q: An unknown exception was encountered sending an HTTP request to the remote WebDriver server for URL I have a problem with running automated tests. When I run single tests, everything is ok, but when I run a package of the test, then I get fail with info:
OpenQA.Selenium.WebDriverException: An unknown exception was encountered sending an HTTP
request to the remote WebDriver server for URL http://localhost:49157/session//element.

If you need I can send all stacktrace, but from my analysis follows that the first call to my code is a method WaitForVisible - there was time out waiting for some webElement.
I run this package of tests on several PC and the situation is the same.
NuGet Package from the project:

*

*Selenium.Support - 3.141

*Selenium.WebDriver - 3.141

*DotNetSeleniumExtras.WaitHelpers - 3.11.0

*Selenium.WebDriver.ChromeDriver - 86.0.4240.2200
Google Chrome v 86.0.4240.111
I also tried with other versions of Selenium, downgrade (3.14) and upgrade to prerelease (4.0.0-alpha05)

Update:

*

*I tried to run tests with different version of Selenium or ChromeDriver.

*I checked solution with chromeOptions.AddArgument("no-sandbox");


text:
Q: Isotope + Wordpress layout mode I'm having a hard time setting up the isotope layout mode in wordpress. What I'm trying to do is create a 2 column grid as seen in this example. So far I managed to get isotope working with filtering categories. The only thing I'm stuggling with is to get the responsive images in a 2 column grid as seen in the example. This is what I have so far: live example
index.php

<?php $the_query = new WP_Query( 'posts_per_page=50' ); //Check the WP_Query docs to see how you can limit which posts to display ?>
<?php if ( $the_query->have_posts() ) : ?>

    <?php while ( $the_query->have_posts() ) : $the_query->the_post();
    $termsArray = get_the_terms( $post->ID, "category" );  //Get the terms for this particular item
    $termsString = ""; //initialize the string that will contain the terms
        foreach ( $termsArray as $term ) { // for each term
            $termsString .= $term->slug.' '; //create a string that has all the slugs
        }
    ?>
    <div class="<?php echo $termsString; ?> item"> <?php // 'item' is used as an identifier (see Setp 5, line 6) ?>
            <?php if ( has_post_thumbnail() ) {
                      the_post_thumbnail();
                } ?>

                <?php the_title(); ?>

    <?php endwhile;  ?>

<?php endif; ?>

isotope.js
jQuery(function ($) {

 var $container = $('#isotope-list'); //The ID for the list with all the blog posts
 $container.isotope({ //Isotope options, 'item' matches the class in the PHP
 itemSelector : '.item',
   layoutMode : 'masonry', });

 //Add the class selected to the item that is clicked, and remove from the others
 var $optionSets = $('#filters'),
 $optionLinks = $optionSets.find('a');

 $optionLinks.click(function(){
 var $this = $(this);
 // don't proceed if already selected
 if ( $this.hasClass('selected') ) {
   return false;
 }
 var $optionSet = $this.parents('#filters');
 $optionSets.find('.selected').removeClass('selected');
 $this.addClass('selected');

 //When an item is clicked, sort the items.
 var selector = $(this).attr('data-filter');
 $container.isotope({ filter: selector });

 return false;
 });

});

isotope.css
/* Start: Recommended Isotope styles */

/**** Isotope Filtering ****/

.isotope-item {
  z-index: 2;

}

.item {

}

.isotope-hidden.isotope-item {
  pointer-events: none;
  z-index: 1;
}

/**** Isotope CSS3 transitions ****/

.isotope,
.isotope .isotope-item {
  -webkit-transition-duration: 0.8s;
     -moz-transition-duration: 0.8s;
      -ms-transition-duration: 0.8s;
       -o-transition-duration: 0.8s;
          transition-duration: 0.8s;
}

.isotope {
  -webkit-transition-property: height, width;
     -moz-transition-property: height, width;
      -ms-transition-property: height, width;
       -o-transition-property: height, width;
          transition-property: height, width;
}

.isotope .isotope-item {
  -webkit-transition-property: -webkit-transform, opacity;
     -moz-transition-property:    -moz-transform, opacity;
      -ms-transition-property:     -ms-transform, opacity;
       -o-transition-property:      -o-transform, opacity;
          transition-property:         transform, opacity;
}

/**** disabling Isotope CSS3 transitions ****/

.isotope.no-transition,
.isotope.no-transition .isotope-item,
.isotope .isotope-item.no-transition {
  -webkit-transition-duration: 0s;
     -moz-transition-duration: 0s;
      -ms-transition-duration: 0s;
       -o-transition-duration: 0s;
          transition-duration: 0s;
}
/* End: Recommended Isotope styles */

A: First thing to do would be to create an image size for wordpress to force the images to be the have the same height and width properties.
add_image_size( 'masonryLayout', 300, 300, true );

Note that you will need to reupload your images in order to create the new image sizes in the media library.
Then you would want to force the .item div to be 50% width. The img tag would need to fill the .item container.
.item{
     width: 50%
}
.item img{
    width: 100%;
    height: auto;
}


text:
Q: Cisco RV220W vs Cisco 892 We're starting to learn about routers for our small business (10 computers connecting to the internet through a dsl modem). It's difficult to figure out which level of router to buy.  We know we need NAT and port forwarding, and that we need to be able to assign a static ip to a mac address.  We also need control over the firewall.
The cheaper routers seem to have all the features we need.  is there any reason to go with the more expensive ones (stability, speed, etc)?
Also - do we need gigabit ethernet on the wan side if we're using a dsl modem to connect to the internet?  how about if we switch to t1 in the future?
-Charlie

A: As noted, the less expensive home/small office units usually work well and are easy to manage for non-technical users.  However, they do tend to be less stable in my experience.  One thing that really helps them is to have the router and any other device (DSL modem, etc) on a good UPS that assures clean power.  I have seen many routers that seem to be on but fail to handle some task.  While a reboot fixes the issue, clean power can help avoid it.  They also seem more prone to heat issues.  Avoid stacking directly on other devices if you can.
Cost is a big factor for many as well.  Several clients have bought the less expensive unit and a spare.  Programmed both (or copied config) and they can survive a complete failure for less than the more expensive unit.
Support on the SMB routers is usually less helpful than the more expensive but not always.  The more enterprise class systems often have more advanced features which you may want in future.
Gbit port for WAN is not much of a benefit for users as WAN speeds are typically WAY lower.  However, some units may provison a Gbit port as cost is little different. You may need to set speed and duplex so it works with the modem or whatever you use to connect to Internet.

A: Go for the 892 if you know Cisco's IOS or are willing to pay someone to configure your router. It's a good and powerful smb router, and will fit your needs.
The RV220W will be easier to configure with its web interface, but it can be less reliable than the 890 series.
You won't need gigabit on the wan port if you only plan to use dsl, but if some providers in your area can provide FTTx links, gigabit can be interesting (for the future).


text:
Q: Project build failed in release mode, runs fine in debug mode I have a big project solution that I am trying to execute, it builds perfectly fine in both release as well as debug mode. The problem is when I try to execute it the debug one is fine but release mode creates segmentation fault and creates a core dump.
Now can anyone help me about how to find out the line number in the code that might have caused the segmentation fault. I tried using gdb but couldn't do much.

A:
Now can anyone help me about how to find out the line number in the code that might have caused the segmentation fault.

Not with the information you've provided (which is insufficient).
You should read GDB documentation. Here is a good place to start.
You should load the executable and core into GDB, and use where command to fund out which function you are crashing in.
Since the crash only happens in "release mode", you'll need to figure out how to add -g flag to your release mode build. Once you've done that, GDB will tell you the file and line number where the crash happens.


text:
Q: Camera 2 Api Error - the error that does not take pictures I am having an issue with the Camera 2 Api.
When I try to take a picture it would not function. The system would not crash. The error only occurs when I try to take a picture.
Furthermore, I took all the permissions that I need in another activity.
The following error occurs.
      Access denied finding property "persist.vendor.camera.privapp.list"

I do not know if it has a relation with the error. Please use it as a reference.
I know that there are similar questions, but neither worked.
I deleted some codes. If you have any inconvenience please let me know.
Thank you in advance.
public class Camera extends AppCompatActivity implements TextureView.SurfaceTextureListener,
ActivityCompat.OnRequestPermissionsResultCallback {

private AutoFitTextureView mTextureView;
private static final int REQUEST_CAMERA_PERMISSION = 1;
private static final int REQUEST_WRITE_STORAGE = 2;
private static final int REQUEST_SAVE_IMAGE = 1002;

private static final int MAX_PREVIEW_WIDTH = 2220;
private static final int MAX_PREVIEW_HEIGHT = 1080;
private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
static {
    ORIENTATIONS.append(Surface.ROTATION_0, 90);
    ORIENTATIONS.append(Surface.ROTATION_90, 0);
    ORIENTATIONS.append(Surface.ROTATION_180, 270);
    ORIENTATIONS.append(Surface.ROTATION_270, 180);
}
private Semaphore mCameraOpenCloseLock = new Semaphore(1);
private String mCameraId;
private CameraDevice mCameraDevice;
private CameraCaptureSession mCaptureSession;
private CaptureRequest.Builder mPreviewRequestBuilder;
private CaptureRequest mPreviewRequest;
private int mSensorOrientation;
private ImageReader mImageReader;
private Size mPreviewSize;
private File mImageFolder;
private Byte bytes;
private Bitmap bitmap;
private File mFile;

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mTextureView = (AutoFitTextureView) findViewById(R.id.texture);
    Button button02 = (Button)findViewById(R.id.button_take_picture);
    button02.setOnClickListener(new Button.OnClickListener() {
                                    @Override
                                    public void onClick (View view){
                                        takePicture();
                                    }
                                }
    );
}

}
private void setUpCameraOutputs ( int width, int height){
    Activity activity = this;
    CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
    try {
        for (String cameraId : manager.getCameraIdList()) {
            CameraCharacteristics characteristics
                    = manager.getCameraCharacteristics(cameraId);

            Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
            if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) {
                continue;
            }

            mCameraId = cameraId;

            StreamConfigurationMap map = characteristics.get(
                    CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
            if (map == null) {
                continue;
            }

            Size largest = Collections.max(
                    Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)),
                    new CompareSizesByArea());

            int displayRotation = activity.getWindowManager().getDefaultDisplay().getRotation();
            mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
            boolean swappedDimensions = false;
            switch (displayRotation) {
                case Surface.ROTATION_0:
                case Surface.ROTATION_180:
                    if (mSensorOrientation == 90 || mSensorOrientation == 270) {
                        swappedDimensions = true;
                    }
                    break;
                case Surface.ROTATION_90:
                case Surface.ROTATION_270:
                    if (mSensorOrientation == 0 || mSensorOrientation == 180) {
                        swappedDimensions = true;
                    }
                    break;
            }

            Point displaySize = new Point();
            activity.getWindowManager().getDefaultDisplay().getSize(displaySize);
            int rotatedPreviewWidth = width;
            int rotatedPreviewHeight = height;
            int maxPreviewWidth = displaySize.x;
            int maxPreviewHeight = displaySize.y;

            if (swappedDimensions) {
                rotatedPreviewWidth = height;
                rotatedPreviewHeight = width;
                maxPreviewWidth = displaySize.y;
                maxPreviewHeight = displaySize.x;
            }

            if (maxPreviewWidth > MAX_PREVIEW_WIDTH) {
                maxPreviewWidth = MAX_PREVIEW_WIDTH;
            }

            if (maxPreviewHeight > MAX_PREVIEW_HEIGHT) {
                maxPreviewHeight = MAX_PREVIEW_HEIGHT;
            }

            mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class),
                    rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth,
                    maxPreviewHeight, largest);

            int orientation = getResources().getConfiguration().orientation;
            if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
                mTextureView.setAspectRatio(
                        mPreviewSize.getWidth(), mPreviewSize.getHeight());
            } else {
                mTextureView.setAspectRatio(
                        mPreviewSize.getHeight(), mPreviewSize.getWidth());
            }

            return;
        }
    } catch (CameraAccessException e) {
        e.printStackTrace();
    } catch (NullPointerException e) {
    }
}

protected void takePicture () {
    if (null == mCameraDevice) {
        Log.e("Camera", "cameraDevice is null");
        return;
    }

    if (ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) {
        return;
    }else{
        if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
            Toast.makeText(this,"We need your permission to record and save image",Toast.LENGTH_SHORT).show();
        }
        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_WRITE_STORAGE);
    }

    CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);

    try {
        CameraCharacteristics characteristics = manager.getCameraCharacteristics(mCameraDevice.getId());
        Size[] jpegSizes = null;
        if (characteristics != null) {
            jpegSizes = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP).getOutputSizes(ImageFormat.JPEG);
        }
        int width = 640;
        int height = 480;
        if (jpegSizes != null && 0 < jpegSizes.length) {
            width = jpegSizes[0].getWidth();
            height = jpegSizes[0].getHeight();
        }
        final ImageReader mImageReader = ImageReader.newInstance(width, height, ImageFormat.JPEG, 2);
        List<Surface> outputSurfaces = new ArrayList<>(2);
        outputSurfaces.add(mImageReader.getSurface());
        outputSurfaces.add(new Surface(mTextureView.getSurfaceTexture()));

        int rotation = getWindowManager().getDefaultDisplay().getRotation();

        //Callback that is called when a new image is available from ImageReader
        ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {

            @Override
            public void onImageAvailable(ImageReader reader) {
                Image image = null;
                //try {
                mFile = new File(getExternalFilesDir(null), "sample.jpg");

                ByteBuffer buffer = image.getPlanes()[0].getBuffer();
                byte[] bytes = new byte[buffer.capacity()];
                buffer.get(bytes);
                FileOutputStream fileOutputStream = null;
                try {
                    fileOutputStream = new FileOutputStream(mFile);
                    fileOutputStream.write(bytes);
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    mImageReader.close();
                    if (null != fileOutputStream){
                        try {
                            fileOutputStream.close();
                        }catch (IOException e){
                            e.printStackTrace();
                        }
                    }
                }

            }

        };

        mImageReader.setOnImageAvailableListener(readerListener, null);
        final CameraCaptureSession.CaptureCallback captureListener =
                new CameraCaptureSession.CaptureCallback() {
                    @Override
                    public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
                        super.onCaptureCompleted(session, request, result);
                        Toast.makeText(Camera.this, "Saved:" + mImageReader, Toast.LENGTH_SHORT).show();

                        createCameraPreviewSession();

                    }
                };
        mCameraDevice.createCaptureSession(outputSurfaces, new CameraCaptureSession.StateCallback() {
            @Override
            public void onConfigured(CameraCaptureSession session) {
                try {
                    session.capture(mPreviewRequestBuilder.build(), captureListener, null);

                } catch (CameraAccessException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onConfigureFailed(CameraCaptureSession session) {

            }
        }, null);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}
private void createCameraPreviewSession () {
    try {
        SurfaceTexture texture = mTextureView.getSurfaceTexture();
        assert texture != null;
        Surface surface = new Surface(texture);

        mPreviewRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
        mPreviewRequestBuilder.addTarget(surface);
        mCameraDevice.createCaptureSession(Arrays.asList(surface),
                new CameraCaptureSession.StateCallback() {

                    @Override
                    public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
                        if (null == mCameraDevice) {
                            return;
                        }

                        mCaptureSession = cameraCaptureSession;
                        try {
                            mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE,
                                    CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);

                            mPreviewRequest = mPreviewRequestBuilder.build();
                            mCaptureSession.setRepeatingRequest(mPreviewRequest,
                                    null, null);
                        } catch (CameraAccessException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onConfigureFailed(
                            @NonNull CameraCaptureSession cameraCaptureSession) {
                    }
                }, null
        );

    } catch (CameraAccessException e) {
        e.printStackTrace();
    }

}

private final CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {

    @Override
    public void onOpened(@NonNull CameraDevice cameraDevice) {
        mCameraOpenCloseLock.release();
        mCameraDevice = cameraDevice;
        createCameraPreviewSession();

    }

    @Override
    public void onDisconnected(@NonNull CameraDevice cameraDevice) {
        mCameraOpenCloseLock.release();
        cameraDevice.close();
        mCameraDevice = null;

    }

    @Override
    public void onError(@NonNull CameraDevice cameraDevice, int error) {
        Log.d("debug","Camera error");
        mCameraOpenCloseLock.release();
        cameraDevice.close();
        mCameraDevice = null;

    }

};

@RequiresApi(api = Build.VERSION_CODES.M)
private void openCamera ( int width, int height){
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
            != PackageManager.PERMISSION_GRANTED) {
        Toast.makeText(this,"No permission to open camera",Toast.LENGTH_SHORT).show();
        requestPermissions(new String[]{Manifest.permission.CAMERA},REQUEST_CAMERA_PERMISSION);
        return;
    }

    setUpCameraOutputs(width, height);
    CameraManager manager = (CameraManager) this.getSystemService(Context.CAMERA_SERVICE);
    try {
        if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
            throw new RuntimeException("Time out waiting to lock camera opening.");
        }
        manager.openCamera(mCameraId, mStateCallback, null);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        throw new RuntimeException("Interrupted while trying to lock camera opening.", e);
    }
}

}

A: Could you try to request for the camera permission as the first thing before trying to take the actual picture? Maybe this is the reason it's crashing.
Remove this permission part from your method "take picture"
if (ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) {
    return;
}else{
    if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
        Toast.makeText(this,"We need your permission to record and save image",Toast.LENGTH_SHORT).show();
    }
    requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_WRITE_STORAGE);
}

You could execute it first before calling take picture