text:
Q: How do we build/assemble test data for large XML schema? How do we build/assemble test data for large XML schema?
We need to build test data for complex nested XML schema (xsd). We like to build the test data for each embedded XSD separately and like to assemble in the defined sequence of main XSD. We are using XMLSPY that have text/Grid/Schema view.
Is there a way to get a list view of XML  schema that list the defined sequence (Only sub xsd name)  in the form as follows.
Main XSD

Sub XSD1
Sub XSD2

      Sub XSD21
      Sub XSD22

Sub XSD3

We can plan how we could build & assemble test data for large XML schema.
Are there any other approaches to build test data in this situation?

A: I am focusing on your last (and bolded question)... and quickly skim through the others...
I am not an XMLSPY user... I've asked some people though, and as far as I was told, there's no out of the box report that would give you exactly what you want. I do know that XMLSPY has an automation API which I am sure could be put to good use to get exactly what need.
From a generic tooling perspective, QTAssistant (I am associated with it) has an out of the box report that gives you a dependency report (can be exported to Excel). Below is a screenshot showing UBL 2.1.0 XSD file dependencies.

Thinking about your request, I believe you're on the right path (componentize your approach)... I would propose though a better angle...
From my experience, one of the many mistakes people do in your kind of scenario is to focus on the XSD file layout when defining the model of the test data. Generally speaking, relations between XSD files as described by an XSD author (through xsd:include/xsd:import) are not always relevant to the XSD processor. In fact, a reference may be missing without affecting the integrity of the XSD set; superfluous references could cause unnecessary overhead in your layout, while the XSD processor would safely "ignore" them. This ultimately means that the relationships between XSD components is not necessarily the same as that described by the XSD file layout.
Another common mistake is to put the test data in a model that uses XSD components in a verbatim way, through names and/or structure. At least in my experience, test data and XSD models are managed by two different teams, with vastly different priorities, timelines, and understanding of technology in general, XML and XSD in particular. This ultimately means that the relationships between XSD components is not necessarily the same as that which is described in a project requirement document, or even in the business domain: the granularity may be different, relationships may be flattened or super-normalized, etc.
There's a downside to couple test data modeling to an XSD... for e.g., whoever creates the test data needs the XSD as early as possible, more often than not, unreasonably (for the XSD designers) early; not to mention that changes to the XSD (due to new requirements, compliance and bug fixes, etc.) create havoc on the test data side.
If the XSD already exists, or the XSD is "the" model (instead of UML, or other kind on modeling language)... it could be used as a "source of inspiration"... bringing them together though, in my opinion, should be through a mapping layer, which ensures decoupling of the two: your test data model, from that described by the XSD.
Which brings me to our recommended approach... There's always something behind the XSD (requirements, etc.), or take the model described by the XSD (not its components), or test data requirements. Use that to build a "normalized" data set... for example, it could be a bunch of Excel worksheets, or some tables in your favourite/available database.
Employ some combination of tools that would use mapping information to convert data in the normalized data set to XML, ideally directly based on the XSD, or indirectly (e.g. ORM mapping). You have to check what works for you, depending on the platform you run on, and what technologies you can bring in house (we use XML Builder for this).
For example, say you work with objects such as customers, accounts, invoices, etc. Your test data should describe that. While the XSD should also line up, it may use all sorts of other things, and for different reasons (substitution groups, type hierarchies, groups, etc. for extensibility, reuse, accommodating XSD to code binding, etc.) The point is, a lot of things one puts in an XSD to supports all sorts of requirements that have nothing to do with the business domain model, could prove a burden to your test data model.
Not to mention that modeling your test data could also provide the seed for a test model in general... which is even more divergent from that which is meant to be fulfilled by a (good) XSD.


text:
Q: add a checked list to a RichTextbox Control in Winforms I'd like to insert the rtf code for a checkbox field in the position where the cursor is within the control but I'm having some problems figuring out how to determine where this position is located within the control's rtf text. Is this possible?

A: Maybe RichTextBox.CaretPosition is what you need. It gives you a TextPointer value (System.Windows.Documents.TextPointer).
https://msdn.microsoft.com/en-us/library/system.windows.controls.richtextbox.caretposition(v=vs.110).aspx

redpajama_set_name: RedPajamaStackExchange


text:
Q: run make pattern rule more than once According to the make documentation, pattern rules with multiple outputs run only once while normal rules may run multiple times. I'd like to run pattern rules multiple times to share a recipe. I know I can share them by using a define but that comes with a different set of problems.
I am using gnu make version 3.8.1
This is the makefile I'd like to use. Is there a way to have it run the pattern rule four times?
build: test.a.x test.a.y test.b.x test.b.y

clean:
    rm -f test.a.x test.a.y test.b.x test.b.y

%.a.x: optAB=a
%.a.x: optXY=x
%.a.y: optAB=a
%.a.y: optXY=y
%.b.x: optAB=b
%.b.x: optXY=x
%.b.y: optAB=b
%.b.y: optXY=y

%.a.x %.a.y %.b.x %.b.y: %.v
    @echo optAB: $(optAB) optXY: $(optXY) $@ $<
    touch $@

A: The relevant line in the documentation is

If a pattern rule has multiple targets, make knows that the rule's recipe is responsible for making all of the targets.

So one way to get around this would be to define multiple targets.  One way to achieve this is to use foreach/eval/call:
build: test.a.x test.a.y test.b.x test.b.y

clean:
    rm -f test.a.x test.a.y test.b.x test.b.y

%.a.x: optAB=a
%.a.x: optXY=x
%.a.y: optAB=a
%.a.y: optXY=y
%.b.x: optAB=b
%.b.x: optXY=x
%.b.y: optAB=b
%.b.y: optXY=y

optset1 = a b
optset2 = x y

define target_template
%.$(1).$(2): %.v
    @echo optAB: $$(optAB) optXY: $$(optXY) $$@ $$<
    touch $$@

endef

$(foreach opt1,$(optset1),$(foreach opt2,$(optset2),$(eval $(call target_template,$(opt1),$(opt2)))))

We define a template for the rule, and then call/eval that template for each of the options, to generate multiple rules, one for each target.  Note the $$ in the template definition are to ensure the variables are not expanded when the template is defined, but only when it is evaluated to generate each target.


text:
Q: get String from another Class is passing null I am really wondering why I am not able to pass a String from one class to another as it is Passing null. Here Is My Structure:
public class A {

    String myString;

    public A(){
    }

    public String getMyString(){
        return myString;
    }

    public void setMyString(String myString){
        this.myString = myString;
    }

    public void doSomethin(){
        String testString = "TEST";
        setMyString(testString);
    }

}

And Here is My Class B Structure:
public class B {

    A myclassA;

    public B(){
        myClassA = new A();
        createPieModel(myClassA.getMyString());
    }

    public void createPieModel(String branch){
        System.out.println(branch); //getting null at this Point
    }

}

Why Am I getting null at createPie Model and what is the Way Around this?

A: you never set the value of the String, call the doSomethin() method before using the get method

A: You can resolve it in both ways.
 public class B{
      A myclassA;
      public B(){
         myClassA = new A();
         myClassA.setMyString("YOUR_MISSED_STRING"); // MISSED_STRING! :)
         createPieModel(myClassA.getMyString());
      }
      public void createPieModel(String branch){
        System.out.println(branch);//getting null at this Point
      }
    }

or
   public class B{
      A myclassA;
      public B(){
         myClassA = new A();
         myClassA.doSomething(); // missed invokation :)
         createPieModel(myClassA.getMyString());
      }
      public void createPieModel(String branch){
        System.out.println(branch);//getting null at this Point
      }
    }


text:
Q: Unequal number of repeated measure for random factor and lmer I'm doing a linear mixed model such as:
model1<-lmer(Y~factor(X1)*X2+(1|species))

as I have repeated measures of the triplet (Y,X1,X2) per species depending on X1 (i.e. one couple of values (Y,X2) per modality of the factor X1).
My problems are both:

*

*is it a problem that the number of repeated measures per species is not balanced ?

*For some species, I have no repeated measure (only one couple of data (Y,X2) for a given modality of X1. Is it a problem ?

Actually my model summary reports a variance and standard deviation for the random factor equal to 0. I guess something is wrong or mispecified but I don't know why a part if the answers to both of my questions is "YES".
If "YES" are the answer how to deal with this particular design ?
Thanks for you help

A: Mixed models, in general, work with unbalanced data. With that being said however, you should also consider why you have fewer measurements for some species. This links to missing data issues, in which case the mixed model, if correctly specified, provides valid inferences under the missing completely at random and missing at random mechanisms.
With regard to the variance that is estimated to be 0, this indicates that there are no strong correlations in the repeated measurements of Y within species groups.


text:
Q: DynamoDB update a field which has a JSON as value with integer/num-string as keys in python I am storing an item with the following structure in my dynamodb table.
Item = {"response": [
    {
        "answers": {
            "11-18": 0,
            "19-24": 0
        }
    }
]}

I want to update response[0].answers.11-18 incrementally.
My command was:
table_resource.update_item(
        Key={
            'id': 123
        },
        UpdateExpression="set response[0].answers.11-18 = response[0].answers.11-18 + :inc",
        ExpressionAttributeValues={":inc": 1},
        ReturnValues="UPDATED_NEW",
)

I get the following error.
An error occurred (ValidationException) when calling the UpdateItem operation: Invalid UpdateExpression: Syntax error; token: "11", near: ".11-"

A: Your nested attribute 11-18 begins with a number, so you can't use it in an update expression.

If an attribute name begins with a number or contains a space, a special character, or a reserved word, then you must use an expression attribute name to replace that attribute's name in the expression.

You can work around this by using placeholder  ExpressionAttributeNames.


text:
Q: SwaggerUI passing parameters I have a swagger.json defined like this:
"/API/GetTieredInventory": {
        "post": {
            "summary": "Get Tiered inventory from ID",
            "description": "Gets Tiered inventory for passed ID/IC combination",
            "produces": [
                "application/json"
            ],
            "parameters": [
                {
                    "name": "id",
                    "in": "path",
                    "description": "ID to retrieve Tiered inventory for",
                    "required": true,
                    "type": "string"
                },
                {
                    "name": "ic",
                    "in": "path",
                    "description": "IC to retrieve Tiered inventory for",
                    "required": true,
                    "type": "string"
                }
            ],
            "responses": {
                "200": {
                    "description": "successful operation"
                },
                "500": {
                    "description": "Internal error"
                }
            }
        }
    }
},

Now, my API takes the parameters like this:
private function GetTieredInventory() {
    if($this->get_request_method() != "POST"){
        $this->response('Error code 405, Method not allowed.',405);
    }
    if(is_array($this->_request['ic'])) {
        $v = array();
        foreach($this->_request['ic'] as $i) {
            $v[] = "'".$i."'";
        }
        $ic=html_entity_decode(implode(',', $v ));
    } else {
        $ic = "'".$this->_request['ic']."'";
    }
    $id=pg_escape_string($this->_request['id']);

    <SNIP DB CODE>

    try
    {
        $results = pg_query($sql);
        if(pg_num_rows($results) == 0) {
            $rows = [];
        }
        else
        {
            $data = pg_fetch_all($results);
            foreach($data as $item)
            {
                $rows[$item["ic"]][] = $item;
            }
        }
        pg_free_result($results);
    }
    catch (Exception $e)
    {
        $err = array("message"=>$e->getMessage(), "code"=> $e->getCode(), "error"=>$e->__toString().",\n".print_r($_REQUEST, true));
        $this->response($this->toJSON($err),500);
    }
    echo json_encode($rows);
}

It doesn't matter what the in value is, I still get a
Notice: Undefined index: ic and
Notice: Undefined index: id error
returned.
I have tried all three of these for both parameters:
"in": "path",
"in": "query",
"in": "body",

This is how the api is called in my service:
$fields = array(
    'id' => $this->compId,
    'ic'    => $ic
);
$fields_string = http_build_query($fields);

$url = "/API/GetTieredInventory";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);

changed the parameters definition like this because ic can be an array of values:
"parameters": [
    {
        "name": "id",
        "in": "body",
        "description": "ID to retrieve Tiered inventory for",
        "required": true,
        "type": "string"
    },
    {
        "name": "ic",
        "in": "body",
        "schema": {
            "type": "array",
            "items": {
                "type": "string",
                "style": "form"
            }
        },
        "description": "Interchange to retrieve Tiered inventory for",
        "required": true
    }
],

But still same errors...:-(

A: Changing the parameters to this made it work. I am using OAS 2.0
"parameters": [
    {
        "name": "id",
        "in": "formData",
        "description": "ID to retrieve Tiered inventory for",
        "required": true,
        "type": "string"
    },
    {
        "name": "ic",
        "in": "formData",
        "description": "IC to retrieve Tiered inventory for",
        "required": true,
        "type": "string"
    }
],


text:
Q: cannot get a parameter from a inherited model in django In my django models I have a class called Admin
class Admin(User):

number = models.IntegerField()

def __init__(self, *args, **kwargs):
    super(Admin, self).__init__()
    self.is_staff = True
    self.is_superuser = True

and in my view I have:
admin = admin.objects.get(id=1)

and when I say print(admin.number) or return HttpResponse(admin.number) it returns None but I have already created this record and it has a number

A: You're not passing any of the parameters up to the superclass. That means they'll never be set when the object is created, which includes when it's retrieved from the database.
You should do:
def __init__(self, *args, **kwargs):
    super(Admin, self).__init__(*args, **kwargs)


text:
Q: Azure DevOps: Add Azure Container Registry in Build Pipeline from different account I want to use a Azure Container Registry of a different account in a Build pipeline in Azure DevOps.
When I try to add a Docker Registry Service Connection and select Azure Container Registry, it only lets me choose between the subscription of the current account.

When I try to add the Azure Resource Manager of the Subscription of a different account which contains the Azure Container Registry in the Service Connections, it says it cannot find any Azure Container Registry.

So how do I accomplish this?

A: I have the same situation in which the Azure Container Registry (ACR) is in a different Azure AD from the Azure DevOps build pipelines.
I'll outline the steps I used:

*

*Create an app registration in the Azure AD where the ACR exists.

*Give it a name like myregistry-app

*Go to the myregistry-app Certificates and secrets page and create a new secret. Copy the value as you cannot retrieve it later.

*Also copy the myregistry-app application id. You can find it on the overview screen.

*Now go to the ACR Access Control (IAM) screen for your container registry.

*Add a role assignment and assign the myregistry-app identity the Contributor role.

*Back in your build pipeline create a Docker task and click on the New button under the Container Registry section.

*In the popup dialog Add a Docker Registry service connection choose the Others radio button.

*Put in the URL to your ACR which you can find on the container registry overview page.

*Use the application id for myregistry-app as the Docker ID.

*Use the myregistry-app secret for the password.

This is currently working for me. There may be a better way


text:
Q: Can i have a second partition with a full system in it, encrypted with FileVault/Truecrypt/Whatever? I would like to have  a second partition in my laptop. The second partition, differently from the first one, should be encrypted at a boot level. It will contain all my work stuff.
Is it possible?
Is it secure?

A: If I understand what you're proposing, you're planning to have two bootable partitions, one encrypted and one not. I can't speak for TrueCrypt, but that's certainly possible with OS X and FileVault 2. The encrypted OS should also be fully secure, unless you do something that interferes with its security:

*

*When you start up from the unencrypted volume, you'll be prompted to unlock the encrypted volume (with one of the account passwords from that volume); if you follow the prompt and unlock it, any malware in the insecure OS will have access to your "secure" volume. Solution: just click Cancel. There might be a way to keep it from even prompting you, but I haven't looked into it (see this MacFixIt article: How to prevent a volume from mounting at boot in OS X for one possible approach).

*When you start up from the encrypted volume, the unencrypted volume will mount automatically. This shouldn't be a big deal, it just means you shouldn't store files on that volume, run software from that volume, etc. If you're worried about it, follow the instructions in that same MacFixIt article to avoid mounting the unencrypted volume.


text:
Q: How can I access sub collection within every document in collection? I want an user to be able to select different types of food that will be displayed on wall (only 8 items from collection) by changing category in my app.
I have two ideas how to do that but I do not know if they are good.
First is to get items from firestore only on selected category. Example:
const foodRef = db.collection("food").doc('${category}').collection('items');

and just get those items and then set state with those items.

This is how I do it by now and it is working good but I think it is not good because every time user change the category components must re-render and user is making unnecessary queries to firestore.

So I thought that it would be good to get all "items" from every document and store it in an object and then operate on that object based on selected category.

My problem is that I tried to get sub-collection of every document in collection but I actually do not know how to do that.

I tried something like that:
const getItems = async () => {
  let snapshot = await firebase.firestore().collection('food').get();
  return snapshot.docs.map(doc => doc.collection('items').forEach(item => item.data()))
}

I know it will not gonna work but I wanted to do something like that.
Structure in my firestore looks like that:
food => [16 documents] => items => [8 documents]

So how should I do that guys, get all the items at once or render every time user change category?

Thanks for your time and help in advance guys:)

A: You can use firestore collectionGroup to get multiple subcollections in different documents. Take a look at this link for details about collection groups.
https://firebase.googleblog.com/2019/06/understanding-collection-group-queries.html
In your case, you could probably do something like this:
  const everyItems = await firebase.firestore().collectionGroup('items').get();

Let me know if you want more details :)


text:
Q: Invalid column name on OData result from inheritance type Code
Model
I have a base and a specific class
public class Entidade : EntityNome, IAuditavel
{
    public DateTime CriadoAs { get; set; }
    public virtual Usuario CriadoPor { get; set; }
    public DateTime? AtualizadoAs { get; set; }
    public virtual Usuario AtualizadoPor { get; set; }
}

public class Empresa : Entidade
{
    public virtual ICollection<Pessoa> Representantes { get; set; }

    public virtual Pessoa Contato { get; set; }
    public int ContatoId { get; set; }

    public virtual ICollection<Telefone> Telefones { get; set; }
    public virtual ICollection<Endereco> Enderecos { get; set; }
    public virtual ICollection<Email> Emails { get; set; }
}

public class Agencia : Empresa
{
    public string Identificacao { get; set; }
    public virtual Regional Regional { get; set; }
    public int RegionalId { get; set; }
    public virtual ICollection<Pessoa> Gerentes { get; set; }
}

EF Configuration
public class EntidadeConfiguracao : EntityTypeConfiguration<Entidade>
{
    public EntidadeConfiguracao()
    {
        Property(p => p.Nome).IsName(true);
        HasRequired(p => p.CriadoPor).WithMany().WillCascadeOnDelete(false);

        ToTable("Entidades");
    }
}

public class EmpresaConfiguracao : EntityTypeConfiguration<Empresa>
{
    public EmpresaConfiguracao()
    {
        HasMany(p => p.Telefones).WithMany().Map(m => m.ToTable("EmpresaTelefones"));
        HasMany(p => p.Emails).WithMany().Map(m => m.ToTable("EmpresaEmails"));
        HasMany(p => p.Enderecos).WithMany().Map(m => m.ToTable("EmpresaEnderecos"));
        HasMany(p => p.Representantes).WithMany().Map(m => m.ToTable("EmpresaRepresentantes"));
        HasRequired(p => p.Contato).WithMany().HasForeignKey(p => p.ContatoId);

        ToTable("Empresas");
    }
}

public class AgenciaConfiguracao : EntityTypeConfiguration<Agencia>
{
    public AgenciaConfiguracao()
    {
        HasRequired(p => p.Regional).WithMany().HasForeignKey(p => p.RegionalId).WillCascadeOnDelete(true);
        Property(p => p.Identificacao).IsRequired().HasMaxLength(10);
        HasMany(p => p.Gerentes).WithMany().Map(m => m.ToTable("AgenciaGerentes"));

        ToTable("Agencias");
    }
}

WebApi config
modelBuilder.EntitySet<Entidade>("entidades");
modelBuilder.EntitySet<Empresa>("empresas");
modelBuilder.EntitySet<Agencia>("agencias");

Problem
When request the GET /api/agencias(4471) the returns:
    "internalexception": {
        "message": "Invalid column name 'RegionalId'.\r\nInvalid column name 'ContatoId'.",
        "type": "System.Data.SqlClient.SqlException",
        "stacktrace": "   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)\r\n   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)\r\n   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)\r\n   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)\r\n   at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()\r\n   at System.Data.SqlClient.SqlDataReader.get_MetaData()\r\n   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)\r\n   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite)\r\n   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)\r\n   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)\r\n   at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)\r\n   at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)\r\n   at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)\r\n   at System.Data.Entity.Infrastructure.DbCommandDispatcher.<>c__DisplayClassb.<Reader>b__8()\r\n   at System.Data.Entity.Infrastructure.InternalDispatcher`1.Dispatch[TInterceptionContext,TResult](Func`1 operation, TInterceptionContext interceptionContext, Action`1 executing, Action`2 executed)\r\n   at System.Data.Entity.Infrastructure.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext`1 interceptionContext)\r\n   at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior)\r\n   at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)\r\n   at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)"
    }

Attempt
Searching the internet, I found that the probable cause may be a misconfiguration as shown in issue Multiple inheritance with Entity Framework TPC.
So I tried to set up as described:
I added Map(m => m.MapInheritedProperties()); on EmpresaConfiguracao and AgenciaConfiguracao
Error:
On Package Manager Console run Add-Migration test OR execute app results:

The type 'Empresa' cannot be mapped as defined because it maps inherited properties from types that use entity splitting or another form of inheritance. Either choose a different inheritance mapping strategy so as to not map inherited properties, or change all types in the hierarchy to map inherited properties and to not use splitting.


text:
Q: Why I got Illegal arguments error with simple hash function? This is my code
const bcrypt = require('bcryptjs');
const salt = bcrypt.genSalt(11);

const user = {
    first: "Donald",
    last: "Trump",
    password : bcrypt.hash(this.password, salt),
    greetUser(password) {
      console.log(`Hi, ${this.first} ${this.last} ${this.password}`);
    },
  };

  let password = 'secondhand01';
  user.greetUser(password);

I run
node --trace-warnings index.js

Hi, Donald Trump [object Promise]
(node:15222) UnhandledPromiseRejectionWarning: Error: Illegal arguments: undefined, object

I expected hashed password. Why does terminal point to illegal arguments?

A: In an object literal, password : bcrypt.hash(this.password, salt) calls bcrypt.hash and assigns its return value to the password property. In the code you've shown, this doesn't refer to the object being created, it refers to the same thing this refers to where the object literal is being created (the top level of the module). Since that doesn't have a password property, you're passing undefined to the function.
bcrypt.hash also returns a promise, as you can see from the output you get before the unhandled promise rejection.
Your user object is being populated with hardcoded values, so you may have meant to do something like this:
const bcrypt = require('bcryptjs');
const salt = bcrypt.genSalt(11);

bcrypt.hash("secondhand01", salt) // <=== Encrypt the password
.then(hashedPassword => {
    // You have it now, you can build and use the object
    const user = {
        first: "Donald",
        last: "Trump",
        password : hashedPassword,
        greetUser() { // Note I removed the parameter you weren't using here
          console.log(`Hi, ${this.first} ${this.last} ${this.password}`);
        },
    };

    user.greetUser(); // Note I removed the unused argument here
})
.catch(error => {
    // Handle/report the error...
});


text:
Q: What is the dimensionality of trees? I remember learning that fractals have "fractional dimension", but I don't remember how that was defined.
I was trying to theorize a way to navigate a tree. I can think of one dimension, "down/up". The second dimension of choice appears to be horizontal - which of the nodes on this level do you choose? Like choosing between 4 doors.
I think that means we can represent a graph in a more separable way.
For each level, we need a name to refer to it.
For each node on each level, they hopefully already have names.
Maybe for purity, we can make the name of a level the name of the feeder (parent) node above. That would be very pure, but it remains to be seen if it would actually be more comfortable and usable.
In numerical terms, you have a normal axis of natural numbers, increasing.
The second axis is stranger, because it varies based on the first axis.
For y = 1, x in {0, 1}.

For y = 2, x in {0, 1, 2, 3}

And so on.
It does make it easy to index / jump to a specific element in this graph.
But I wonder, there might be a different way to model it. Technically, every level down you go, you are selecting from yet another axis. You can index the subtree at level 2, option 3, and then option 5.
That would mean that the "dimensionality" of the graph is simply related to how many "choices" you made, with each choice being its own dimension, with its own range of values. Technically, moving five nodes down is a five dimensional space - skipping the root, just list sequentially the first range of options for the choices, then the second (depending on what you chose), and so on. The result is a set of axes, a set of sets of values. You don't need to specify what choice was made in this representation since it's already determined by whatever choices are listed on the next level of that set.
But I don't know where to take this, because it means the tree has infinite dimensionalities, one for the length of every possible path.
Outside of math, a useful application for this could be a mind-mapping software interface. Mindmapping is popular on smartphones, and mindmaps can have the structure of trees. Trees do not fit well on a smartphone. Navigating a spatial area on a small screen isn't optimal design. Instead, you could place button rows of choices, moving consecutively from the top of the screen to the bottom.
Anyway, I am still not sure if there is a conceptual difference between a "level" and an "option". I feel like there's some equivalence to be made, but I can't see it. To "go down a level" is the same as "to choose an option". Yet in the above structure, we see "levels" because we end up listing consecutive sets. I now realize this can be avoided by replacing any element with its choices. The lowest level elements are empty sets. This is a labelled graph, so we only show the structure - what the locations mean is present, but abstracted into something different and separate. This means that when we navigate a mindmap on a phone, we could invert it : the root is a large circle in front of us - we see some of the choices inside of it - going some manageable number of levels down. Click any of the concentric circles visible to move there - then you can see even further down. That could be a useful way to increase visibility and traversability of trees/mindmaps on a smartphone. Arguably, this has effectively removed the two concepts we were using, "level" vs "choice", because if you can "see" / access any node of the tree all at the same time, there is no need to travel, we can just select any point we want.
How does this relate to fractional dimensionality?
What field of mathematics is this?
What books study this?


text:
Q: Opening a link in a different active window I have two browser windows open. One is a website assistant, the other is the actual website that assistant is related to.
If a user clicks a link from the assistant window, is it possible to trigger the loading of that page/link to appear on the second window instead of the assistant window?
I have no code for this, simply a question before I go any further.
A perfect example is www.ikea.co.uk. Click 'ask anna' in the header, and ask her 'how much is a bed'. The links it provides will open in window #1.

A: How do you open the windows? With Javascript? Define a name to each frame/window and call for them on links. Something like that:

link


text:
Q: How to get keys from map Object with javascript I have this structure below:
/* Wrapper to format cellphone configuration list for selectors. */
    function buildConfiguration(){
        return {
            "Item 1": {
                name: {
                    "aaa": 1,
                },
                blue: {
                },
                green: {
                },
                black: {
                },
                yellow: {
                }
            },

            "item 2": {
                name: {
                    "aaa 5": 1,
                    "bbb 6": 2,
                    "ccc 7": 3
                },
                blue: {
               },
                green: {
               },
               black: {
               },
               yellow: {
               }
           }
       }
   }

I would like get the keys from this map object.
I'm trying this console.log(Object.keys(buildConfiguration));
but return 0 itens.
Could please help me?

A: You need to call that function like buildConfiguration() and you're done

function buildConfiguration(){
        return {
            "Item 1": {
                name: {
                    "aaa": 1,
                },
                blue: {
                },
                green: {
                },
                black: {
                },
                yellow: {
                }
            },

            "item 2": {
                name: {
                    "aaa 5": 1,
                    "bbb 6": 2,
                    "ccc 7": 3
                },
                blue: {
               },
                green: {
               },
               black: {
               },
               yellow: {
               }
           }
       }
   }

   console.log(Object.keys(buildConfiguration()))


text:
Q: ASP.NET Core front-end developer workflow with VSCode and VS 2019 I haven't done any cshtml front-end development for a few years.
What's the current, generally accepted way for ASP.NET Core front-end developers to work across a range of tools on Windows?
By that, I mean a way to have the front-end JS build and the .NET project(s) also build and to work rapidly in the browser and code.
My thinking is.

*

*We have much better command line story around dotnet today.

*Some folk like VS Code.

*Some folk prefer VS 2019, and some like either, depending.

*We need to work on UI aspects sometimes.

*But we also need to attach a debugger and debug the server logic sometimes.

*The build server should have no problem, be simple, and rely mostly on build logic held in the repo.

*Tooling, and kicking off the whole build and serve process should be understandable and familiar.

*It should be pretty simple to get going after a team noob clones the repo.

My initial thought would be to setup NPM then use something like Gulp to kick off everything, including running dotnet run.
Then when running under the Visual Studio 2019 debugger, use the Task Runner Explorer to kick off the Gulp stuff but skip the dotnet run part.
(shame there doesn't seem to be a command line for start VS(Code or 2019) and attach debugger)
Now I'm expecting to get a "primarily opinion based" SO beating, but there are general trends and ideas that go into designing all these tools for how they can all play ball together and what the dev story looks like.

A: You've pretty much already described the process. However, I'll add a few things:

*

*You don't need the dotnet run bit. Visual Studio and VS Code are both capable of debugging directly.

*You can assign the gulp tasks to build tasks in Task Runner Explorer, so you really don't even then to think about running those directly. I'm not as sure on this aspect of VS Code, but I'm sure there's probably some extension to handle it, if it's not already built-in.

*If you want true ease of development, the best thing you can do is use Docker. Just add a Dockerfile to each project that actually runs (i.e. not a class library) and set up the steps to build and run it there. In Visual Studio, you can right-click the project and choose Add > Docker Support, and it will actually generate a ready-made Dockerfile, though you may need to add a step or two to handle the client-side build steps. In any case, this then becomes truly click and run, with nothing to worry about. The story is even better when you use docker-compose, as then Visual Studio and VS Code can spin up your entire application stack all at once, including external dependencies such as a database, Redis instance, etc. If you haven't used Docker before, start now. It's absolutely revolutionary for development.
One note for CI/CD, as much as possible, you should add a YAML file to describe your CI/CD pipeline. Depending on the the actual provider you're using for build/release, there might be some differences, so consult the relevant documentation. (Azure DevOps, for example, doesn't currently support describing release pipelines in yaml, though you can still do your build that way.) In any case, this allows you to configure all this in code, and have it committed to source control.
You may consider the same for your infrastructure. Azure has ARM templates, AWS has CloudFormation, GCP has Deployment Manager. There's also third-party tools like Terraform or Ansible. All of these, in some form or fashion (usually JSON or YAML) allow you to define all the characteristics of the infrastructure you're going to deploy to and commit that to source control. This makes deployment and things like creating new environments as breeze.


text:
Q: Python script is killed from within, but the process doesn't die I'm trying to execute a python script using php with an exec command like this:
exec("python /address/to/script.py");

I don't need the script to run to completion, so after it does what I need, I call sys.exit() from within it. Execution is passed back to the php script, which is great, however the python process is still running. I can see it in my server's process list. Is there more that's required to fully kill it?
Additional Info

*

*The python script was written by a third party.

*I know very little about python, just enough to add the sys.exit() call.

A: The script could still be executing some cleanup code, or you could be calling sys.exit() from a child process which will essentially be calling thread.exit(), leaving the parent process running.
Check that the sys.exit() call is in the main part of the script and that no error handling is interfering with the SystemExit exception, or alternatively you could try os._exit(). Also ensure that an ampersand (&) is not present within the command passed to exec() as this will cause the script to run as a background process.
Note that os._exit() is not favourable since it doesn't do any cleanup, and essentially ends the process immediately.
Edit To end the script from within your try block you could do something like this:
try:
    # Existing Code
except SysExit:
    os._exit() # quit the process
except:
    # Existing error handling

Ideally the application logic should make use of message passing or something similar so that a child thread could notify the main thread that it should terminate.


text:
Q: Python maths game level not changing When I type level4 or level3 or level2 my game does not go to the requested level.
It prints the entered level (e.g. level1) and stays on level one.
print("Welcome to the maths skills testing machine!")
userinput = input("\nAre you ready to test your maths skills?")

print("\nWhich level would you like to play?")
userinput = input('''Level 1, Level 2, Level 3, Level 4''')

if userinput=="level1":
    level1()
elif userinput=="level2":
    level2()
elif userinput=="level3":
    level3()
elif userinput=="level4":
    level4()

def level1():

    import operator
    import random
    import time
    start = time.time()

    ops = {'+': operator.add,
           '-': operator.sub}

    num_a = random.randint(1, 10)
    num_b = random.randint(1, 10)
    op = random.choice(tuple(ops.keys()))

    print('{}{}{}=?'.format(num_a, op, num_b))
    expected_answer = ops[op](num_a, num_b)
    user_answer = int(input())
    if user_answer == expected_answer:
        print('Correct')
        print('It took you {0:0.1f} seconds to answer the
question'.format(time.time() - start))
    else:
        print('Wrong')
        print('It took you {0:0.1f} seconds to answer the
question'.format(time.time() - start))
    while user_answer == expected_answer:
        level1()
    else:
        exit()

level1()

def level2():

    import operator
    import random
    import time
    start = time.time()

    ops = {'+': operator.add,
           '-': operator.sub}

    num_a = random.randint(10, 50)
    num_b = random.randint(10, 50)
    op = random.choice(tuple(ops.keys()))

    print('{}{}{}=?'.format(num_a, op, num_b))
    expected_answer = ops[op](num_a, num_b)
    user_answer = int(input())
    if user_answer == expected_answer:
        print('Correct')
        print('It took you {0:0.1f} seconds to answer the
question'.format(time.time() - start))
    else:
        print('Wrong')
        print('It took you {0:0.1f} seconds to answer the
question'.format(time.time() - start))
    while user_answer == expected_answer:
        level2()
    else:
        exit()

level2()

def level3():

    import operator
    import random
    import time
    start = time.time()

    ops = {'+': operator.add,
           '-': operator.sub}

    num_a = random.randint(50, 100)
    num_b = random.randint(50, 100)
    op = random.choice(tuple(ops.keys()))

    print('{}{}{}=?'.format(num_a, op, num_b))
    expected_answer = ops[op](num_a, num_b)
    user_answer = int(input())
    if user_answer == expected_answer:
        print('Correct')
        print('It took you {0:0.1f} seconds to answer the
question'.format(time.time() - start))
    else:
        print('Wrong')
        print('It took you {0:0.1f} seconds to answer the
question'.format(time.time() - start))
    while user_answer == expected_answer:
        level3()
    else:
        exit()

level3()

def level4():

    import operator
    import random
    import time
    start = time.time()

    ops = {'+': operator.add,
           '-': operator.sub}

    num_a = random.randint(100, 1000)
    num_b = random.randint(100, 1000)
    op = random.choice(tuple(ops.keys()))

    print('{}{}{}=?'.format(num_a, op, num_b))
    expected_answer = ops[op](num_a, num_b)
    user_answer = int(input())
    if user_answer == expected_answer:
        print('Correct')
        print('It took you {0:0.1f} seconds to answer the
question'.format(time.time() - start))
    else:
        print('Wrong')
        print('It took you {0:0.1f} seconds to answer the
question'.format(time.time() - start))
    while user_answer == expected_answer:
        level4()
    else:
        exit()

level4()

A: In your if statement, you're using an input() method. It doesn't have to be there. Just write:
if userinput=="level1":
    level1()
elif userinput=="level2":
    level2()

etc. It's also better to use elif in stead of if.

A: You should define the function before using it. You are calling functions before they are defined.
Also the calls to them (e.g. level1()) after them is not needed.
You may also move the imports at the begging of the file, and remove them from each function.
You may also use an IDE, for example PyCharm.
def level1():
    import operator
    import random
    import time
    start = time.time()

    ops = {'+': operator.add,
           '-': operator.sub}

    num_a = random.randint(1, 10)
    num_b = random.randint(1, 10)
    op = random.choice(tuple(ops.keys()))

    print('{}{}{}=?'.format(num_a, op, num_b))
    expected_answer = ops[op](num_a, num_b)
    user_answer = int(input())
    if user_answer == expected_answer:
        print('Correct')
        print('It took you {0:0.1f} seconds to answer the question'.format(time.time() - start))
    else:
        print('Wrong')
        print('It took you {0:0.1f} seconds to answer the question'.format(time.time() - start))
    while user_answer == expected_answer:
        level1()
    else:
        exit()

def level2():
    import operator
    import random
    import time
    start = time.time()

    ops = {'+': operator.add,
           '-': operator.sub}

    num_a = random.randint(10, 50)
    num_b = random.randint(10, 50)
    op = random.choice(tuple(ops.keys()))

    print('{}{}{}=?'.format(num_a, op, num_b))
    expected_answer = ops[op](num_a, num_b)
    user_answer = int(input())
    if user_answer == expected_answer:
        print('Correct')
        print('It took you {0:0.1f} seconds to answer the question'.format(time.time() - start))
    else:
        print('Wrong')
        print('It took you {0:0.1f} seconds to answer the question'.format(time.time() - start))
    while user_answer == expected_answer:
        level2()
    else:
        exit()

def level3():
    import operator
    import random
    import time
    start = time.time()

    ops = {'+': operator.add,
           '-': operator.sub}

    num_a = random.randint(50, 100)
    num_b = random.randint(50, 100)
    op = random.choice(tuple(ops.keys()))

    print('{}{}{}=?'.format(num_a, op, num_b))
    expected_answer = ops[op](num_a, num_b)
    user_answer = int(input())
    if user_answer == expected_answer:
        print('Correct')
        print('It took you {0:0.1f} seconds to answer the question'.format(time.time() - start))
    else:
        print('Wrong')
        print('It took you {0:0.1f} seconds to answer the question'.format(time.time() - start))
    while user_answer == expected_answer:
        level3()
    else:
        exit()

def level4():
    import operator
    import random
    import time
    start = time.time()

    ops = {'+': operator.add,
           '-': operator.sub}

    num_a = random.randint(100, 1000)
    num_b = random.randint(100, 1000)
    op = random.choice(tuple(ops.keys()))

    print('{}{}{}=?'.format(num_a, op, num_b))
    expected_answer = ops[op](num_a, num_b)
    user_answer = int(input())
    if user_answer == expected_answer:
        print('Correct')
        print('It took you {0:0.1f} seconds to answer the question'.format(time.time() - start))
    else:
        print('Wrong')
        print('It took you {0:0.1f} seconds to answer the question'.format(time.time() - start))
    while user_answer == expected_answer:
        level4()
    else:
        exit()

print("Welcome to the maths skills testing machine!")
_ = input("\nAre you ready to test your maths skills?")

print("\nWhich level would you like to play?")
userinput = input('''Level 1, Level 2, Level 3, Level 4''')

if userinput=="level1":
    level1()
elif userinput=="level2":
    level2()
elif userinput=="level3":
    level3()
elif userinput=="level4":
    level4()


text:
Q: Parametrization of a curve $r(\phi) = \cos(\phi)$ We have this curve
$r(\phi) = \cos(\phi)$
And we want to parameterize it.
In lectures we have done the following:
$$
x(\phi) = r\cdot \cos{(\phi)} = \cos^2(\phi)\\
y(\phi) =r\cdot \sin{(\phi)} = \sin{(\phi)} \cdot \cos{(\phi)}
$$
Why do we multiply the $x$ and $y$ coordinates by $\cos$ and $\sin$ ?
Can anybody please explain what we just done and why?
Is this general, to multiply by $\sin$ and $\cos$ to parameterize a curve?

A: Consider a point $P(x,y)$ on a circle of radius $r$ centered at the origin. Let $\phi$ be the angle to the horizontal determined by $P$. By definition,
$$
\cos \phi = \frac{x}{r}
$$
and
$$
\sin \phi = \frac{y}{r}.
$$
Rearrange to recover the familiar formulas you cited.

A: The procedure you did is not the only way to parameterize a curve.
First, you have initially described the curve in terms of its polar coordinates. You have the angle $\phi$ and you use the formula $r=\cos(\phi)$ to find the radius.
Now you have both the angle and radius to a point, which perfectly describes a point in the plane. You can set $\phi$ to some value and you immediately find a point on the curve.
To find more points on the curve, you can use $\phi$ as a parameter. Let $\phi$ increase or decrease, compute a new $r$ for each $\phi,$ and plot each pair $(r,\phi)$ as a point in polar coordinates. This will trace part of the curve.
What this says is that the curve was already parameterized when it was first described to you.
But perhaps you are not satisfied using polar coordinates. You might want to describe the curve in Cartesian coordinates instead.
But you might still want a parameterization.
You can then convert the polar coordinates of your existing parameterization to Cartesian.
And there is a standard conversion from polar to Cartesian:
$$ x = r \cos(\phi), $$
$$ y = r \sin(\phi). $$
All you did to make this a "parameterization" was that you took your existing parameterization (in which $r$ is a function of $\phi$) in order to write $x$ as a function of $\phi$ and also write $y$ as a function of $\phi.$
In summary, the multiplications by the sine and cosine have to do with converting from polar coordinates to Cartesian. They don't occur if you start with Cartesian coordinates or if you leave the parameterization in polar coordinates.


text:
Q: finding local maximum and range of function Consider the function $f(x)= \frac{ln x}{x}$, $0 < x < e^2$.
(a)   (i) Solve the equation $f'(x) = 0$

*

*here I differenciated and I got $f'(x)= \frac{\frac{x}{ln x}-ln x}{x^2}$ and when I equated this to zero, I got $x=0$
(ii) Hence show the graph of $f$ has a local maximum.
(iii) Write down the range of the function $f$.
(b) Show that there is a point of inflexion on the graph and determine its coordinates.
(c) Sketch the graph of $y=f(x)$, indicating clearly the asymptote, x-intercept and the local maximum.
(d)Now consider the functions $g(x)=\frac{ln|x|}{x}$ and $h(x)=\frac{ln|x|}{|x|}$, where $0<|x|>e^2$.
(i) Sketch the graph of $y=g(x)$
(ii) Write down the range of $g$
(iii) Find the values of x such that $h(x) > g(x)$.

I'm not quite sure how to approach after the first derivative.

A: Hint
As André Nicolas commented, the first derivative is wrong. If $$f(x)=\frac{\log(x)}{x}$$ $$f'(x)=\frac{1-\log (x)}{x^2}$$ $$f''(x)=\frac{2 \log (x)-3}{x^3}$$ So, $f'(x)=0$ when $x=e$ and for this value $f''(x)=-\frac{1}{e^3} \lt 0$; so there is a maximum for $x=e$ corresponding to $f(e)=\frac{1}{e}$.
The second derivative cancels if $2 \log (x)-3=0$ which corresponds to $x=e^{3/2}$ which is in the considered range.
I am sure that you can take from here.


text:
Q: QNetworkReply error signal not detected when connection is lost I'm downloading files from a remote server with Qt5.5 and everything works fine but I can't detect when a QNetworkReply returns an error.
In fact, I am trying to check the case if the user is downloading a file and suddenly, he loses his Internet connection (because why not :-) ). To do that, I start a download and unplug my Ethernet cable a few seconds after.
Is the signal QNetworkReply::error(QNetworkReply::NetworkError) emitted in this case? If yes, why am I not entering my slot in my code below?
void MyClass::download(QUrl url)
{
    QNetworkRequest request = QNetworkRequest(url);

    QNetworkReply *reply = pManager.get(request);

    // finished() is called after error(), but try both
    connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(requestError(QNetworkReply::NetworkError)));
    connect(reply, SIGNAL(finished()), this, SLOT(requestFinished()));
}

void MyClass::requestError(QNetworkReply::NetworkError err)
{
    qDebug() << "error";
}

void MyClass::requestFinished()
{
    qDebug() << "finished";
}

I also connected the access manager like this :
connect(&pManager, SIGNAL(finished(QNetworkReply*)), SLOT(requestFinished(QNetworkReply*)));

When the Internet connection is not interrupted, I am going in the slot requestFinished(), but if there's not Internet anymore, I am not entering any slot.
Am I doing something wrong?

A: Ok, nevermind, I was doing it wrong. Since I want to check the internet connection, I have to check the network availability via QNetworkAccessManager, by doing this :
QNetworkConfigurationManager manager;
pManager.setConfiguration(manager.defaultConfiguration());

connect(&pManager, SIGNAL(networkAccessibleChanged(QNetworkAccessManager::NetworkAccessibility)), this, SLOT(networkAccessibleChanged(QNetworkAccessManager::NetworkAccessibility)));

And when the Internet breaks down, I will be in the corresponding slot.


text:
Q: Dynamically Load class in Ruby on Rails I have a class Test which is in lib folder and I want to make an object of this class dynamically inside a method of my controller class name class UsersController < ApplicationController. How can I do this?
something like
class UsersController < ApplicationController
  def address
    {"here I want to create the object of Test class"}
  end
end

A: In Ruby you can't create object like in C++, you can create only dynamic object with Object::new method. So to create instance of Test class you simple wrote:
test = Test.new

A: There is no compilition in ruby. And Test is just constant which   is available anywhere, if it was defined in main scope ofc.

A: Ruby is interpreted language so there is no compilation phase.in config/application.rb load lib folder or file so when boots it automatically load these file. now if you want instance of test class for all the method simply create method which create instance and load before method using before_filter


text:
Q: interchanging sum and lim with uniformly convergence series Let $\sum_{n=1}^{\infty} f_n$ be a uniformly convergence function series with $f_n$ continuous for all $n\in \mathbb{N}$. Let $a$ be a point in the domain of all $f_n$. Prove that $$\lim_{x\rightarrow a}\sum_{n=1}^{\infty} f_n(x)=\sum_{n=1}^{\infty} \lim_{x\rightarrow a} f_n(x)$$
I have attempted to let $c=\lim_{x\rightarrow a}f_n(x)$ and to prove $\lim_{x\rightarrow a}\sum_{n=1}^{\infty}|f_n(x)-c|=0$, but still have no idea. I also suspect this has some connection to the monotone convergence theorem. Thanks for any help!


text:
Q: Sorting floating numbers I have a list of normal vectors and I am calculating the scalar triple product and sorting them. I have compared the sorting in three different cases:

*

*Using Matlab sort to find the largest absolute triple product values

*Using std::sort function in C++ to get the product values for std::vector. Using doubles for triple products.

*Using Radix sort in OpenCL C - converting the absolute floating values to unsigned integers and converting them back. I am using cl_float for triple products.

All of them give values which are different along with the different indices which causes problems in my algorithm. What is the problem in this case and how can I keep them consistent?

A: The problem at hand:

*

*Calculate the scalar triple product of 3 3-dimensional vertices, being each component of each vector represented as binary32 float.

*Being able to tell if a result of that calculation is greater than other result of that calculation.

So far so good, but if we directly apply the formulae to the vectors, some bits may be lost in the operations and we will be unable to discern two results. As @rcgldr pointed out, sorting is not the problem, the precision is.
One solution to floating point roundoff problems is to increase the number of bits, that is, use double. You said you have no double, so let's do it ourselves: perform the whole calculation in an array of unsigned char as long as we need.
Okay, okay, practical considerations:

*

*The input is made of normalized vectors, so the length is no greater than one, that implies no component is greater than one

*The exponent of a binary32 float ranges from -127 (zero, denormals) to 127 (or 128 for infinity), but all components will have exponent from -127 to 0 (or else they would be greater than one).

*The maximum precision of the input is 24 bits.

*Scalar triple product involves an vector product and an scalar product. In the vector product (which will happen first) there is subtraction of results of multiplication, and in the scalar product there is a sum of results of multiplication.
Considerations 2 and 3 tells us that the whole family of input components can be fit in an fixed-point format of size 127 bits for offsetting plus 24 bits for the mantissa, that's 19 bytes. Let's make it 24.
To be able to fully represent all possible sums and subtractions, one extra bit suffices (in the advent of carryover), but to fully represent all possible multiplication results, we need double the number of bits, so it resolutes that doubling the size is enough to represent the vector multiplication, and tripling it will make it enough for the next multiplication in the scalar product.
Here is a draft of class that loads a float to that very huge fixed point format, keeping the sign as a bool flag (there is a helper function rollArrayRight() that I'll post separately, but hopefully it's name explains it):
const size_t initialSize=24;
const size_t sizeForMult1=initialSize+initialSize;
const size_t finalSize=sizeForMult1+initialSize;
class imSoHuge{
public:
    bool isNegative;
    uint8_t r[finalSize];
    void load(float v){
        isNegative=false;
        for(size_t p=0;p<finalSize;p++)r[p]=0;
        union{
            uint8_t b[4];
            uint32_t u;
            float f;
        } reunion;
        reunion.f=v;
        if((reunion.b[3]&0x80) != 0x00)isNegative=true;
        uint32_t m, eu;
        eu=reunion.u<<1; //get rid of the sign;
        eu>>=24;
        m=reunion.u&(0x007fffff);
        if(eu==0){//zero or denormal
            if(m==0)return; //zero
        }else{
            m|=(0x00800000); //implicit leading one if it's not denormal
        }
        int32_t e=(int32_t)eu-127; //exponent is now in [e]. Debiased (does this word exists?)
        reunion.u=m;
        r[finalSize-1]=reunion.b[3];
        r[finalSize-2]=reunion.b[2];
        r[finalSize-3]=reunion.b[1];
        r[finalSize-4]=reunion.b[0];
        rollArrayRight(r, finalSize, e-(sizeForMult1*8)); //correct position for fixed-point
    }
    explicit imSoHuge(float v){
        load(v);
    }
};

When the class is constructed with the number 1.0f, for example, the array r have something like 00 00 00 00 80 00, notice that it is loaded to the lower part of it, the multiplications will ~roll~ the number accordingly  to the upper bytes, and we can then recover our float.
To make it useful, we need to implement the equivalent to sum and multiplication, very straight-forward, as long as we remember we can only sum arrays that have been multiplied the same number of times (as in Triple product) or else theirs magnitude would not match.

One example where such class would make a difference:
Consider the following 3 vectors:
float a[]={0.0097905760, 0.0223784577, 0.9997016787};

float b[]={0.8248013854, 0.4413521587, 0.3534274995};

float c[]={0.4152690768, 0.3959976136, 0.8189856410};

And the following function that calculates the triple product: (hope I've got it right haha)
float fTripleProduct(float*a, float*b, float*c){
    float crossAB[3];
    crossAB[0]=(a[1]*b[2])-(a[2]*b[1]);
    crossAB[1]=(a[2]*b[0])-(a[0]*b[2]);
    crossAB[2]=(a[0]*b[1])-(a[1]*b[0]);
    float tripleP=(crossAB[0]*c[0])+(crossAB[1]*c[1])+(crossAB[2]*c[2]);
    return tripleP;
}

The result for fTripleProduct(a,b,c); is 0.1336331
If we change the last digit of the fisrt component of a from 0 to 6, making it 0.0097905766 (which have a different hexadecimal representation) and call the function again, the result is the same, but we know it should be greater.
Now consider we have implemented the multiplication, sum, and subtraction for the imSoHuge class and have a function to calculate the triple product using it
imSoHuge tripleProduct(float*a, float*b, float*c){
    imSoHuge crossAB[3];
    crossAB[0]=(imSoHuge(a[1])*imSoHuge(b[2]))-(imSoHuge(a[2])*imSoHuge(b[1]));
    crossAB[1]=(imSoHuge(a[2])*imSoHuge(b[0]))-(imSoHuge(a[0])*imSoHuge(b[2]));
    crossAB[2]=(imSoHuge(a[0])*imSoHuge(b[1]))-(imSoHuge(a[1])*imSoHuge(b[0]));
    imSoHuge tripleP=(crossAB[0]*imSoHuge(c[0]))+(crossAB[1]*imSoHuge(c[1]))+(crossAB[2]*imSoHuge(c[2]));
    return tripleP;
}

If we call that function for the two above versions of the vectors, the results in the array differ:
0  0  0  4 46 b9  4 69 39 3f 53 b8 19 e0  ...

0  0  0  4 46 b9  4 85 93 82 df ba 7d 80  ...

And they differ after the precision of a binary32 float indeed, meaning that if we cast that array back to float, it will be the same float, but if we compare the arrays, we can tell which one is greater.

The put that reasoning to the test, I've made a full working example, that you can compile and run right away with -O3 -Wall -std=c++11 in GCC, or equivalent on another compiler and will output:
Using class: second result is greater
casting to float:
first reasult: 1.336331e-001
second result: 1.336331e-001
as floats, the results are the same: 1.336331e-001

The source code is here (working fine on Ideone):
Source Code on IDEONE C++11 code
If you have not migrated to C++11, the code compiles and run in C++98 if you define the exact-width types uint8_t, uint16_t, uint32_t, int32_t yourself.

How to use it?
Simple call the function tripleProduct with your inputs and compare the results using the provided overload comparators operators, you can also cast the class imSoHuge to float (after the calculation of triple product) using the provided overload cast operator.
You can provide an array of that class and comparators to any sorting algorithm.

Conclusions and considerations:
Notice that a float multiplication is now performed as a multiplication of two 70+ bytes long array, that means hundreds of time more clock cycles, plus the sums, comparisons etc, this shall be thousands of time slower, but hey, it's exact.
The whole design of the algorithm is to work with normalized vectors (there is some room here, as I don't know the precision or your normalization procedure), but it will all overflow and be meaningless with most 'greater-than-one' vectors.
You can easily cap the array of the result to as many bytes you wish, if keeping all that array in memory is too much. Very few cases will produce results diverging after ~12bytes
I haven't stress-tested everything, like denormals, and corner cases, there is some comments in the code to the critical points.
and of course:
You can easily improve everything, I was just willing to share the reasoning =)

Source code again
Main reference:
Single-precision floating-point format (Wikipedia)


text:
Q: Getting errors when parsing values I'm getting errors when i'm trying to parse the datas.
The program is to retrieve the datas from database and parse it to the main menu where the RecycleView lists out the datas such as name,username,image and description.
I'm following this tutorial https://www.youtube.com/watch?v=g30Q9KHubTU
This is the code with errors.
DataParser.java
public class DataParser extends AsyncTask<Void,Void,Boolean> { //<<<line 22

Context c;
String jsonData;
RecyclerView rv;

ProgressDialog pd;
ArrayList<Item> items = new ArrayList<>();

public DataParser(Context c, String jsonData, RecyclerView rv) {
    this.c = c;
    this.jsonData = jsonData;
    this.rv = rv;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();

    pd = new ProgressDialog(c);
    pd.setTitle("Parse");
    pd.setMessage("Parsing...Please wait.");
    pd.show();
}

@Override
protected Boolean doInBackground(Void... params) {

    return null;
}

@Override
protected void onPostExecute(Boolean success) {
    super.onPostExecute(success);

    pd.dismiss();

    if(success)  //<<<line 59
    {
        //bind
        MyAdapter adapter = new MyAdapter(c,items);
        rv.setAdapter(adapter);

    }
    else
    {
        Toast.makeText(c, "Unable to parse", Toast.LENGTH_SHORT).show();

    }

}

private Boolean parseData()
{
    try
    {
        JSONArray ja = new JSONArray(jsonData);
        JSONObject jo;

        items.clear();
        Item item;

        for(int i = 0; i<ja.length();i++)
        {
            jo=ja.getJSONObject(i);

            int itemid = jo.getInt("itemid");
            String imagepath = jo.getString("imagepath");
            String itemname = jo.getString("itemname");
            String username = jo.getString("username");
            String itemdesc = jo.getString("itemdesc");

            item = new Item();

            item.setId(itemid);
            item.setItemname(itemname);
            item.setUsername(username);
            item.setItemdesc(itemdesc);
            item.setImagepath(imagepath);

            items.add(item);

        }

        return true;

    } catch (JSONException e) {
        e.printStackTrace();
    }
    return false;
}

}

These are the errors
java.lang.NullPointerException:
Attempt to invoke virtual method 'boolean java.lang.Boolean.booleanValue()' on a null object reference

at chengweifeng1132701116.fyp.m_MySQL.DataParser.onPostExecute(DataParser.java:59)

at chengweifeng1132701116.fyp.m_MySQL.DataParser.onPostExecute(DataParser.java:22)

A: This is because you are always returning null from doInBackground. So, your success variable is always null in onPostExecute(). Have the appropriate logic for parsing inside doInBackground and based on whether it was successful or not, return true or false.


text:
Q: how to create own gallery from device images in android i want to create own image gallery with camera button..am able to show all device images in grid, and capture image also. but grid view not get refreshed dynamically..plz suggest
first i show all available images, when user capture image i want to add that image dynamically in grid view..
//--------code to get images from device--------------
private void getImages()
    {
    projection = new String[]{MediaStore.Images.Thumbnails._ID};
    cursor = managedQuery(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
            projection,
            null,
            null,
            MediaStore.Images.Thumbnails.IMAGE_ID);

         columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
}

//--------
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);
    Log.e("RESULT CODE", "--" + resultCode);
    if (resultCode == RESULT_OK) {
        if (requestCode == CAMERA_REQUEST) {
            Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
            Random random = new Random();
            int no1 = random.nextInt(15 - 0);
            int no2 = random.nextInt(25 - 15) + 15;
            String fileName = tempString.substring(no1, no2) + ".jpg";
            try {
                Bitmap photo = (Bitmap) data.getExtras().get("data");
                File outFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), fileName);
                FileOutputStream fos = new FileOutputStream(outFile);
                photo.compress(Bitmap.CompressFormat.JPEG, 100, fos);

                fos.flush();
                fos.close();
                getImages();
            //    sdcardImages.setAdapter(imageAdapter);
                imageAdapter.notifyDataSetChanged();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
//--custom adapter class
public class ImageAdapter extends BaseAdapter{
 Context context;

    public ImageAdapter(Context localContext){
       context = localContext;}

    public int getCount() {
        return cursor.getCount();
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent){
      final ImageView picturesView;
      if (convertView == null){

            picturesView = new ImageView(context);

            cursor.moveToPosition(position);

            int imageID = cursor.getInt(columnIndex);

   picturesView.setImageURI(Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTER
          NAL_CONTENT_URI,"" + imageID));

            picturesView.setScaleType(ImageView.ScaleType.FIT_XY);

            picturesView.setPadding(5, 5, 5, 5);

            Display display = getWindowManager().getDefaultDisplay();

            int width = display.getWidth() / 3;

      picturesView.setLayoutParams(new GridView.LayoutParams(width, width));
        } else {
            picturesView = (ImageView) convertView;
        }
        return picturesView;
    }//get view
}//image adapter

A: try this, I think since you are updating the image view only if convertview == null, when the view gets recycled it seems you are not updating the imageview, try replacing your getView() with this
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ImageView pictures;
    if (convertView == null)
        pictures = new ImageView(context);
        convertView.setTag(pictures);
    } else {
        pictures = (ImageView) convertView.getTag();
    }
    cursor.moveToPosition(position);
    int imageID = cursor.getInt(columnIndex);
    picturesView.setImageURI(Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID));
    picturesView.setScaleType(ImageView.ScaleType.FIT_XY);
    picturesView.setPadding(5, 5, 5, 5);
    return picturesView;
}//get view


text:
Q: How sort an arraylist of names in alphabetical order but names which start with numbers must comes last i need to sort names list  in to alphabetical order, for this i use the interfase comperator for sorting the names
  @Override
    public int compareTo(ContactModel another) {
        // TODO Auto-generated method stub
        return getname().compareTo(another.getname());
    }

Suppose this is my array of name
123vinish
23Sathya
24mahesh
Ranjith
Vipin
Bibin
Shine
Thomas

i need to sort this in a sequence where names with numbers must come last
Bibin
Ranjith
Shine
Thomas
Vipin
123Vinish
23Sathya
24mahesh

How can we implement this

A: String.compareTo(String) sort the Strings by the ascii value of the characters. You need to change the comparator. Example with a custom comparator:
List<String> al = new ArrayList<String>();
al.add("123vinish");
al.add("23Sathya");
al.add("24mahesh");
al.add("Ranjith");
al.add("Vipin");
al.add("Bibin");
al.add("Shine");
al.add("Thomas");

Comparator<String> nameComparator  = new Comparator<String>()
{
    @Override
    public int compare(String value1, String value2)
    {
        if(Character.isDigit(value1.charAt(0))&&!Character.isDigit(value2.charAt(0)))
            return 1;
        if(Character.isDigit(value2.charAt(0))&&!Character.isDigit(value1.charAt(0)))
            return -1;
        return value1.compareTo(value2);
    }
};

Collections.sort(al, nameComparator);

System.out.println(al);

Output: [Bibin, Ranjith, Shine, Thomas, Vipin, 123vinish, 23Sathya, 24mahesh]
And if you want to override the compareTo method in the class where you implemented the Comparable<> interface, it have to look like this:
    @Override
    public int compareTo(ContactModel anotherValue)
    {
        if(Character.isDigit(this.getname().charAt(0))&&!Character.isDigit(anotherValue.getname().charAt(0)))
            return 1;
        if(Character.isDigit(anotherValue.getname().charAt(0))&&!Character.isDigit(this.getname().charAt(0)))
            return -1;
        return this.getname().compareTo(anotherValue.getname());
    }

EDIT:
If you want that a String like 2a appear before something like 23 then you only have to loop over every character in the String. Then the custom comparator have to look like this:
Comparator<String> nameComparator  = new Comparator<String>()
{
    @Override
    public int compare(String value1, String value2)
    {
        for(int i = 0; i < Math.min(value1.length(), value2.length()); i++)
        {
            //value1 is digit and value2 is not
            if(Character.isDigit(value1.charAt(i)) && !Character.isDigit(value2.charAt(i)))
                return 1;
            //value2 is digit and value1 is not
            else if(Character.isDigit(value2.charAt(i)) && !Character.isDigit(value1.charAt(i)))
                return -1;
            //both are digits with different size
            else if(Character.isDigit(value1.charAt(i)) && Character.isDigit(value2.charAt(i)) && Integer.valueOf(value1.charAt(i))!=Integer.valueOf(value2.charAt(i)))
                return value1.compareTo(value2);
            //both are no digits
            else if(!Character.isDigit(value1.charAt(i)) && !Character.isDigit(value2.charAt(i)))
                return value1.compareTo(value2);
            //loop again if they are both digits with the same value
        }
        return value1.compareTo(value2);
    }
};

EDIT 2:
I have creat another solution for your problem. I've copied the implementation of the compareTo  method in String class and modified the ascii values of numbers while the comparing. This example can be used in your ContactModel class.
@Override
public int compareTo(ContactModel anotherValue) {
    int len1 = this.getname().length();
    int len2 = anotherValue.getname().length();
    int lim = Math.min(len1, len2);
    char v1[] = this.getname().toCharArray();
    char v2[] = anotherValue.getname().toCharArray();

    int k = 0;
    while (k < lim) {
        //Do the trick here! If char is a digit, add 75.
        char c1 = Character.isDigit(v1[k]) ? ((char)(v1[k]+75)) : v1[k];
        char c2 = Character.isDigit(v2[k]) ? ((char)(v2[k]+75)) : v2[k];
        if (c1 != c2) {
            return c1 - c2;
        }
        k++;
    }
    return len1 - len2;
}

A: What about this implementation almost similar to your 2nd suggestion
@Override
public int compareTo(ContactModel another) {
    // TODO Auto-generated method stub
    boolean lhsStartsWithDigit = Character.isDigit(getStartLetter().charAt(0));
    boolean rhsStartsWithDigit= Character.isDigit(another.getStartLetter().charAt(0));
    if((lhsStartsWithDigit && rhsStartsWithDigit) || (!lhsStartsWithDigit && ! rhsStartsWithDigit))
        return getStartLetter().compareToIgnoreCase(another.getStartLetter());
    else if(lhsStartsWithDigit)
        return 1;
    else
        return -1;

}

Can i follow this??


text:
Q: Got the "ERROR: Cannot decode data link type 239" message when turn on sniffer mode I would like install snort 2.9.6 into Centos 7
the installation is ok and the result of the self-testing mode is correct but when I run this command to change Snort into sniffer or nids mode. I got this error message:
" ERROR: Cannot decode data link type 239"
I try to recompile again with including the " --enable-non-ether-decoders " option as these steps:
./configure  --enable-non-ether-decoders --enable-sourcefire
make
make install
make clean

I still get that error

A: Unless your Linux has done something with DLT_ values which nobody should ever ever ever ever ever do, 239 is:
/*
 * NetFilter LOG messages
 * (payload of netlink NFNL_SUBSYS_ULOG/NFULNL_MSG_PACKET packets)
 *
 * Requested by Jakub Zawadzki <darkjames-ws@darkjames.pl>
 */
#define DLT_NFLOG               239

which is what you get when capturing on an nflog device.
If you specified an nflog device (device beginning with "nflog"), then snort 2.9.6 may not be able to handle that, and you'll need to capture on a regular network device.
If you didn't specify an nflog device, then either snort explicitly opened an nflog device (which it shouldn't do if it can't handle it!) or it used the default device (which shouldn't be an nflog device).
What happens if you run tcpdump -D?  If the first device it reports is an nflog device, either it (and snort) aren't running with sufficient privileges to open ordinary devices but can open nflog devices or there's some other issue putting the nflog device at the top.


text:
Q: Troubleshooting system.io.fileloadexception I have a .net 3.5 WinForms application that runs fine on my machine, but on another machine it immediately crashes with a system.io.fileloadexception. Unfortunately, there are absolutely no details on which file failed to load, so I do not know where the problem actually is.
I believe I know which one it could be (SQL Server Compact edition), but before I aimlessly hunt, I wonder if there is a proper way to find out what caused the fileloadexception, other than using FileMon from SysInternals.
The only error message is:

EventType clr20r3, P1 myapplication.exe, P2 2.1.0.0, P3 490eca78, P4 myapplication, P5 2.1.0.0, P6 490eca78, P7 2e, P8 21, P9 system.io.fileloadexception, P10 NIL.

A: You could try making your Main() method more robust to catch (and display) the exception... like so.
Frequently, the problem is that too much code gets into the outermost Main() method. JIT has to be able to fully understand Main(), otherwise none of your code can run. By making Main() simpler, you stand a chance. In the linked example, if MainCore() fails: fine, we can still catch the exception in Main().
This works because JIT is done on a method-by-method basis... i.e. MainCore() is not JITted until it is invoked, by which time we already have our try/catch in place.

A: Hook and log AppDomain.AssemblyResolve

A: Turn on fusion logging?
This blog entry from Brad Wilson gives information on what to do if that fails...

A: Grab the Microsoft Debugging Tools SDK, and use either windbg or cordbg to attach and run your application. This should give you at least a clue where the problem is, if not pinpoint the problem.


text:
Q: Powershell AD: counting groups in office I am having issues in my thought process. I want an output of something like
'Group Name' 'Title' 'Count' and I am able to get the 'Group Name' and 'Title' Columns but I'm not sure how to count, say, all of the repeat groups in the 'sales' title. Where my code is right now, is searching the entire column to see if it finds that group name, and if it finds that column and then it move the counter by 1 (this is wrong because it my find a group name with a different title)
Any help would be greatly appreciated! Thank you
$allOffices = get-aduser -filter * -Properties physicaldeliveryofficename | Select-Object -ExpandProperty physicaldeliveryofficename #Selecting all offices
$uniOffices = $allOffices | Select-Object -Unique
$groups = $null
$global:ErrorActionPreference = 'silentlycontinue'
$finallist = @()
$count = 0

foreach ($office in $uniOffices) {   # Loop through all unique offices
    $peopleInOffice = $null
    $peopleInOffice = get-aduser -filter * -properties office | Where-Object office -eq $office | Select-Object -ExpandProperty SamAccountName  # Array of people in a certain office, selects username
    foreach ($person in $peopleInOffice){
        $groups = get-ADPrincipalGroupMembership $person
        foreach($group in $groups) {
                if(($finallist.'Group Name'-contains $group.name) -and ($finallist.'Title' -contains $office)){$count++}
                $finallist+=  $group| Select-Object @{N='Group Name';E={$group.name}},@{N='Title';E={($office)}},@{N='Count';E={$count}}
        }
    }
}

$finallist

A: So I started working on your problem, and I'm unsure what you're asking.  Here's a greatly simplified and more efficient representation of your code:
$offices = Get-ADUser -Filter 'PhysicalDeliveryOfficeName -like "*"' -Properties PhysicalDeliveryOfficeName |
    Select-Object -ExpandProperty PhysicalDeliveryOfficeName -Unique

$list = foreach ($office in $offices)
{
    foreach ($person in (Get-ADUser -Filter "Office -eq '$office'" -Properties Office, MemberOf))
    {
        $person.MemberOf |
            Get-ADGroup -Properties Name |
            Select-Object -Property @(
                @{
                    N = 'Group Name'
                    E = {$PSItem.Name}
                }
                @{
                    N = 'Title'
                    E = {$office}
                }
            )
    }
}

At the end, you have a $list object which is an array of pscustomobject objects that you can manipulate.  You can use Group-Object to determine how many groups there are with similar names using calculated properties, etc.

Using your problem statement:

how to count all of the repeat groups in the sales title

$list | Group-Object -Property Title | Select-Object -ExpandProperty Count


text:
Q: $\mathbf{Q}_{p}^{n}$ has a countable base? We can find a countable base for $\mathbf{R}^{n}$ using fact that $\mathbf{Q}$ is dense in the reals (example of proof by someone else is here: Proof that $\mathbf{R}^n$ has a countable base.).
We also have countable base for $\mathbf{Q}_{p}$ since the set of all balls is countable (Proposition 1.6 in this paper: https://www2.math.ethz.ch/education/bachelor/seminars/hs2011/p-adic/report5.pdf).
But $\mathbf{Q}$ is also dense in $\mathbf{Q}_{p}$, can we just use similar reasoning to the $\mathbf{R}^{n}$ to show that there is countable base for $\mathbf{Q}^{p}$, or is this not true? Thank you.

A: In technical terms:

For metric (or metrizable) spaces, separability is equivalent to second-countability.

That is

Every metric space with a countable dense subset has a countable base.

Indeed, let $(X,d)$ be a metric space and $Q\subseteq X$ a countable dense subset. Then $(X,d)$ has a countable base, consisting of the balls of rational radius around points in $Q$. $\square$
Also, the product of two (or finitely many) second-countable spaces is second-countable (by taking the obvious rectangles as base).

A: Yes, in any metric space $(X,d)$ (and $\mathbf{Q}_p$ has the $p$-adic metric), if we have a countable dense set $D$ we have a countable base: we can take the set of all balls $\{B_d(x,\frac{1}{m}): x \in D, m \in \mathbb{N}\}$ as such a base.


text:
Q: Not getting the right values the sort array method Hello I am not really sure why I am not getting the right values, here's an example.It is a basic question but I am not sure if this happened before...
const arr = [4,1,9,5,6];
arr.sort((a, b) => {
    console.log(a);
});

I should be getting:
// output: 4,1,9,5,6
Instead I am getting:
// output: 1,9,5,6
I remember the first value in this case "a" used to show all the items in the array. did it change?

A: Your are doing a console.log from the comparison predicate. You have no guarantee of the order of application of this function on your data.
The order of output depends both on your array ordering and on the underlying sorting algorithm used by sort.
There are many sorting algorithms, such as bubble sort, selection sort, quick sort... which could apply the predicate in different orders.

A: You comparison function always returns void. It needs to return > 0 for a is greater than b, 0 if they are equal and < 0 if b is greater.

const arr = [4,1,9,5,6];
arr.sort((a, b) => a - b);

console.log(arr);

A: The callback inside the sort function is used when you would like to write your own comparator logic. Try to understand the working of compareFunction-

*

*If compareFunction(a, b) is less than 0, sort a to an index lower than b (i.e. a comes first).

*If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different
  elements. Note: the ECMAscript standard does not guarantee this
  behavior, and thus not all browsers (e.g. Mozilla versions dating back
  to at least 2003) respect this.

*If compareFunction(a, b) is greater than 0, sort b to an index lower than a (i.e. b comes first).

*compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If
  inconsistent results are returned then the sort order is undefined.

  Source-
  https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort


text:
Q: drawertext color with conditon ffmpeg I have a coin price banner where I use ffmpeg to stream it and use reload:1 to render it in real time. I want to color the negative with red and the positive with green ,  haw to do it and is it posible with fflmpeg
-vf 'drawtext=enable='between(t,18.93,20.28)':fontfile=fonts/cousine-bold.ttf:fontsize=144:fontcolor_expr=%{eif\\: if(between(0,1000)\, green\, red) \\: x}:x=82:y=288:text=coinsprice.txt:reload:1'


text:
Q: Business rules in DMN or database table? I'm learning Camunda the workflow engine. I understand that for some long-running processes, process modeling brings many tactical and strategic benefits such as expressiveness, fail-tolerance and observability with additional overhead ofcourse.
The book I'm reading also advocates the use of DMN (decision tables) to bundle business rules inside the process model. The motive is to centralize maintenance and decouple configuration from the code. I'm taking this advice with grain of salt, as decision tables smells somewhat clunky to work with. There is no strong typing and powerful IDE features. I'm used to implementations where business parameters are stored in database table and consumed by the application. The implementation also provides admin GUI to maintain these parameters at runtime.
For what reason I should favor DMN over more solid database based solution?

A: You are moving the business logic to BPMN to get it out of the code, make it transparent in  graphical model, accessible to all stakeholders, support business-IT alignment, empower business to own they business process/logic, support multi-version enactment at runtime, and more...
The same reasoning applies to business rules, which are too complex to be modeled out as graphs in BPMN diagrams. The DMN standard is also aimed at business people and the expression language used is intentionally kept simpler than an Excel formula. It is the "Friendly Enough Expression Language" (FEEL). So you see where this is going.
Database tables

*

*are not well accessible to business users

*do not flexible changes to the table structure(s)/schema at runtime

*usually do not support multi-version enactment at runtime

*do not support a graphical, logical decomposition of rules (into DRDs) unless you work with multiple tables - but db schema are not flexible

*cannot be easily deployed to many systems

*cannot be easily tested in unit test

*likely do not automatically generate audit data, which is accessible for audits and analytics

These are just a few points. So, for business rules, definitely DMN over DB tables.


text:
Q: What page to open when running Maven-based EAR from Netbeans Is there an easy way to tell Netbeans (6.9) what page to open when I "run" my Maven Enterprise project? It opens a totally wrong context path. I guess there are some options I can specify on the Project Properties | Actions page -> "Run project" action, I just can't find it anywhere as documentation seems to be nonexistent for Netbeans...

A: you are running into http://netbeans.org/bugzilla/show_bug.cgi?id=176096. I haven't found a fix for it yet.

A: Did you specified relative url in Project properties / run?


text:
Q: regex to stop name part of email being all numbers I have the following email regex which I got from stackoverflow:
/^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()\.,;\s@\"]+\.{0,1})+[^<>()\.,;:\s@\"]{2,})$/
We want to fail all email addresses that are of this form:
12121976@example.co.uk.
How could I update the regex to cover this case?

A: You can check if the beginning of the string are digit characters followed by "@" character
// returns `false` if match is found
!/^\d+(?=@)/.test("12121976@example.co.uk") && /* other `RegExp`s */


text:
Q: Can't resolve the error: java.lang.NoClassDefFoundError: org/json/simple/parser/ParseException Trying to use Maven to organize my project and I keep running into the following error. I know that this error means the file is present at compile time but for some reason it can't be found at runtime.
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: org/json/simple/parser/ParseException

So I'm working on a project in Java that will take a user query, search Google Images and then download some of the results onto my computer. To that end I've had to use some third party libraries like JSoup, Json-Simple, and Gson.
I initially added Jsoup to my classpath manually and it worked, but then I heard about Maven and started using it instead. My issue is that when I try to run my code I get the error above.
I'm just not sure how to resolve this. I've seen a bunch of other posts about similar errors and I've tried to modify my pom.xml accordingly but
I just can't get it to work. I've tried removing the ~/.m2 file, ran mvn clean, mvn install, mvn package, mvn compile, and it all works fine. But when it comes time to run, I keep getting that error.
Here's most of my pom.xml file.
<repositories>
    <repository>
    <id>central</id>
   <name>Maven repository</name>
   <url>http://repo1.maven.org/maven2</url>
 </repository>

<dependencies>
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>3.8.1</version>
  <scope>test</scope>
</dependency>

<dependency>
  <!-- jsoup HTML parser library @ https://jsoup.org/ -->
  <groupId>org.jsoup</groupId>
  <artifactId>jsoup</artifactId>
  <version>1.11.3</version>
  <scope>provided</scope>
</dependency>

<!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
</dependency>

<build>
<plugins>
  <plugin>
    <artifactId>maven-assembly-plugin</artifactId>
    <configuration>
      <archive>
        <manifest>
          <mainClass>fully.qualified.MainClass</mainClass>
        </manifest>
      </archive>
      <descriptorRefs>
        <descriptorRef>jar-with-dependencies</descriptorRef>
      </descriptorRefs>
    </configuration>
  </plugin>
</plugins>
</build>

FOUND SOLUTION: So I left out some parts of the pom.xml file to make it easier to read, and because all the other parts were generated by Maven itself so I figured there couldn't be an issue with anything there. But it adds a tag called "pluginManagement" that encloses all other plugins and apparently this does not allow the Shade plugin to run.
Between ngueno's guidance and this post Maven shade plugin is not called automatically for goal "package"
I was able to figure out my issue, though I'm still not entirely sure why it is an issue. Anyways, I figured I'd update this post in case someone else with a similar problem stumbles across it. This was on Mac OS btw, in case it makes a difference. Thanks for your help everyone.

A: Usually NoClassDefFound errors are related to missing libraries at runtime.
Since you are running using the terminal I supose you are building your project using Maven, and running the generated JAR,
I would recommend to you to use the maven-shade-plugin and generate an uber-jar as I explained on this question.
The purpose generating a uber-jar is to carry all the needed dependencies inside of it (available on the application classpath).
Implement the plugin and try to run using the new JAR.
PS: Remember to check this section related to Executable Jars
UPDATE: Remove the <scope>provided</scope> of your jsoup dependency, to enforce Maven to package it along your app, with the provided scope you are saying that this dependency will be provided by the JDK at runtime.

A: The jars that you identify in your dependencies must be present in the Runtime classpath.
This is not the classpath that is available when you compile the code;
it is the classpath on the host where you run the application.
You must install these jars on the target host.
Edit: More details
You must do the following:

*

*Identify the runtime host.

*Create a directory on the runtime host into which you will install the dependent jar files.

*Include every jar in the classpath.

Consider abandoning the "roll-your-own" path.
If you use Spring Boot
(I like it,
I don't work for them).
One feature of spring boot is a reinvented "Fat Jar" that will include the dependencies inside one deliverable artifact (the fat jar) and will add them to the classpath at startup.
Edit:
The Spring boot executable jar file is not a "Fat Jar",
instead it includes the dependencies in a directory in the
executable jar and adds said jars to the classpath on startup.


text:
Q: Same function in javascript and php, but different outputs I have this function in javascript - works properly
// javascript
    function myhash(str) {
      var hash = 0;
      if (str.length == 0) return hash;
      for (var i = 0; i < str.length; i++) {
        oneChar = str.charCodeAt(i);
        hash = ((hash << 5) - hash) + oneChar;
        hash &= hash;
      }
      return hash;
    }

And I'm trying to rewrite this function to PHP, but for same input gives different output than the one from JS.
// php
      function myhash($str) {
        $hash = 0;
        if (strlen($str) == 0) return $hash;
        for ($i = 0; $i < strlen($str); $i++) {
          $oneChar = ord($str[$i]);
          $hash = (($hash << 5) - $hash) + $oneChar;
          $hash &= $hash;
        }
        return $hash;
      }

Inputs and outputs example:
console.log(myhash("example")); // output: -1322970774
echo myhash("example"); // output: 93166309738

Does anyone know, where could be the problem? They look same, but apparently they are not.

A: The << operator in Javascript converts the numeric parameter into a 32-bit signed integer, rather than an IEEE 754 double.
To fix your PHP code, you will (at least) need to mask the result of the << operation before you do anything else with it.
The code below produces the same result as the JS code for input of "example" using PHP 5.3.15 on (64-bit) MacOS X 10.8.4.  It may not work for other test cases, or on 32-bit versions of PHP:
function myhash($str) {
  $hash = 0;
  if (strlen($str) == 0) return $hash;
  for ($i = 0; $i < strlen($str); $i++) {
    $oneChar = ord($str[$i]);
    $tmp = ($hash << 5) & 0xffffffff;
    $hash = ($tmp - $hash) + $oneChar;
  }
  return $hash;
}

NB: the line $hash &= $hash is a no-op.  A number "anded" with itself will produce the same number.

A: hash() is reserved function for php I tested with hash1 both providing same result
using test:
PHP result: 3556498
Javascript: 3556498

A: In JavaScript, on the 6th iteration using the string "example", the result of $hash << 5 is a negative number (96947249 << 5 -> -1192655328). In PHP, it's 3102311968.
The problem is that in JavaScript, the << operator causes the operands to internally be converted to signed 32-bit Integers. The maximum value of a signed 32-bit Integer is 2147483647. The operation at that point in the loop crosses that threshold, causing an overflow.
In PHP, the max value seems to be the same (2147483647) in 32-bit systems, but much larger in 64-bit. http://php.net/manual/en/language.types.integer.php (near the bottom)
DEMOS: http://phpfiddle.org/main/code/mga-i8b and http://jsfiddle.net/YJRA4/
Lots of information on bitwise operators and integers (hopefully explaining better what I'm saying): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators


text:
Q: angucomplete-alt Search with Begins than Contains I am using angucomplete-alt for auto-populating the data for a search box. It shows all the records which contains the given value, even the given value is in the middle of the string. I want to populate the records which starts with the given text. Is there any way to do that?
thanks in advance...


text:
Q: Selecting dynamic element name in CSS How to style a group of customized HTML tags (Angular.js directives) sharing the same suffix?
If there are three modal tags that are desired with the same style
1.
2.
3. <c-modal>

How do I create a selector that applies to all three without having them share a common attribute?
// doesn't work
[*-modal] {
  //style...
}

// would've worked with attributes:
div[modal="true"] {
  //style...
}

A: If you are using Angular directives, then you could use class names instead of a tag names to match your directives along with wildcard CSS selectors:
HTML

CSS
[class*="-modal"] {}
Angular
restrict: 'C'

However, I would suggest to just introduce a common CSS class for all of them.

A: Should be simply:
a-modal, b-modal, c-modal {
  …
}

If you want a large number of custom HTML tags without a long comma-separated CSS selector, I would suggest <modal type="a">, etc. and modal { … }.