text:
Q: How to communicate with .net processes when there are multiple instances of them I have multiple instances of the same Windows Forms .net 3.5 SP1 C# application running on the same machine.
Now I'd like to be able to communicate with them from .net, one instance at a time.
What's the most simplest way to do this?
I read a bit about WCF, but I have only found examples working with one server and one client. But in my case all running instances would be a server and I need to discuss with just one of them.
I imagine something like this:
Process[] procs = Process.GetProcessesByName("ProcessName");
foreach (Process p in procs)
{
  // Communicate with process here
}

A: You'll need some kind of subscribe/callback mechanism. Don't loop through the projects, but have each application subscribe to a wcf service method instead.
Example: http://idunno.org/archive/2008/05/29/wcf-callbacks-a-beginners-guide.aspx

A: The simple thing is database :) , btw WCF support peer to peer communication with NetPeerTcpBinding


text:
Q: Probability distribution question: Please verify answer Question
A k-out-of-n system is one that will function if and only if at least $k$ out of the $n$ individual components in the system function. Assume that individual components function independently of each other. Assume also each individual component functions with probability $0.9$
Determine the long-run proportion of 3-out-of-5 systems that will function.
My Working
The binomial distribution looks to be a good fit here.
Summarising the data:
$p$ (the probability of success) $= 0.9$
$n$ (the total number of trials) $= 5$
$x$ (the number of successes needed) $= 3$
3-out-of-5 means the system needs at least $3$ components to function which means the system will function at $3$ components, $4$ components $5$ components.
Which in turn means the answer will be $1 - prob$($0$ components + $1$ components + $2$ components)
Therefore $1 - 0.0815$
= $0.9185$
Is this correct?

A: I do not at this point see what went wrong in the computation.
The answer is
$$\binom{5}{3}(0.9)^3(0.1)^2+\binom{5}{4}(0.9)^4(0.1)^1+\binom{5}{5}(0.9)^5(0.1)^0.$$
The calculator gives me an answer of $0.99144$.
Because it is easy to make a mistake, I also calculated using your (correct) idea. The answer then would be
$$1-\left(\binom{5}{0}(0.9)^0(0.1)^5+\binom{5}{1}(0.9)^1(0.1)^4+\binom{5}{2}(0.9)^2(0.1)^3\right).$$
Again, I get $0.99144$.  This time, to make sure, I also did the calculation by hand.
Added: Maybe I have a good guess about what went wrong. Note that $\binom{5}{3}(0.9)^3(0.1)^2=.0729$. If we subtract this from $0.99144$, we get $0.91854$. So maybe in your calculation you used one term too many.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Finding the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? This is a Project Euler challenge where I'm trying to find the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
The logic while I came up with seems to run really slowly. It's been running for the last 4 mins and still hasn't found the number. I'm trying to figure out a) Is this logic correct? b) Why does this take so long? and c) Could someone give me a hint on an alternate logic that is more efficient.
# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
# What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
smallest_num = 2520
while smallest_num >= 2520:
    divisor = 2
    while smallest_num % divisor == 0 and divisor < 21:
        print("Smalles num = {} and Divisor = {}").format(smallest_num, divisor)
        divisor += 1
    smallest_num += 1
print("Smallest number is: {}").format(smallest_num)

This is still processing and so far my terminal looks like this

A: Here's your method run "properly" (using the term liberally), but as @James mentioned it will take an egregious amount of time as a loop.
divisors = np.arange(1, 21)
num = 2520
while True:
    if np.all(num % divisors == 0):
        print(num)
        break
    num += 1

A much better method (for Python 3.x).  Directly from a similar question:
import functools
import math

functools.reduce(lambda x,y: x*y//math.gcd(x, y), range(1, 21))
Out[27]: 232792560

A: The following code works fine.
#!/usr/bin/env python
import math

#Generating primes
divisorMax = 20;

top = divisorMax + 1 #divisor max is the upper limit

p = [x for x in range(2,top)]

for num in p:
  for idx in range(2,(top//num)+1):
    if num*idx in p:
      p.remove(num*idx)

#Solving the problem
result = 1;

for i in range(0, len(p)):
    a = math.floor(math.log(divisorMax) / math.log(p[i]));
    result = result * (p[i]**a);

print(result)

You are using brute force technique to calculate the number, which is easy to understand and write, but takes very much time.
I am using the Prime Factorisation technique explained here.

A: i am not 100% sure, if my solution is really correct, but i guess it is and it is pretty fast.
First of all, we don't need to care for all divisors, as most are multiples of each other. So best way is to count the divisors backwards, for example starting with 20 down to 1.
I had a look at the prime numbers, the solution needs to be a multiple of all primes above 10, furthermore we need to check the 20 divisor, the rest can be ignored, as when testing divisor 18, the 9 will work as well, and so on.
So i mulitplied 11 * 13 * 17 * 19 * 20. The resulting is 923780 and is divisible by at least the primes + 20.
So i would start at 923780 and test only every 923780th number.
smallest_num = 923780
steps = 923780
while True:
    divisor = 19
    while smallest_num % divisor == 0 and divisor > 10:
        print("Smalles num = {} and Divisor = {}").format(smallest_num, divisor)
        divisor -= 1
    if divisor == 10:
        print("Smallest number is: {}").format(smallest_num)
        break
    smallest_num += steps

Maybe i have logical error?!


text:
Q: Changing signature while Overriding in C++ I have a base class
class Shape{
    public:
        virtual int getArea()=0;
}

I want to change the signature while overriding like this:
class Rectangle : class Shape{
    public:
        int getArea(int someParameter = 0){
            return 0;
        }
}

Is it possible somehow to achieve this, as I am using default value for newly added parameter?

A: The only solution I can see is that you implement both int getArea() and int getArea(int), where one function can call the other (for example int getArea() { return getArea(0); }). You can not have the overload taking an argument have a default argument then.

A: You need to overload your virtual function. But if you overloaded virtual function, you will get a warning "hides overloaded virtual function"
Solution is override function with native signature and overload it with virtual prefix.
Example:
class A {
   virtual void foo(int) {...}
};

class B: public A {
   void foo(int i) override {
       A::foo(i);
   }

   virtual void foo(const std::string& str) {
       ...
   }
};


text:
Q: What signal is sent to running process after network fail? I am trying to reproduce a situation where a process fails due to a network outage. I was hoping to reproduce this signal with a kill command. A normal kill command is not working. I have taken a look at /usr/include/sys/signal.h to try to find a signal that refers to anything that might be related to a network outage, but with no luck. Has anybody tried to reproduce a network outage with the kill command?
Sorry if this is a newbish question! Please correct me if I am going about this in a completely wrong way.

A: None. A "network failure" is not a signal.

A: As others have said, signals dont work that way, they are not generally tied to specific error codes like "no network", I assume you are coming from a Windows background?  If you want to reproduce a network failure, cause it by having the process try to access a non existent address or by disabling the network link temporarily on the test machine.


text:
Q: Entity Framework Core Data Annotation Database Generated Values The Entity Framework Core documentation for Generated Properties makes it seem like Data Annotations can be used for generated code first "timestamp" properties such as created/updated on as a DateTime type.
When trying to use the following data annotations along with code first migrations:
public class Foo {
    // some properties

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public DateTime Created { get; set; }

    // more properties
}

I receive the following error when attempting to execute command dotnet ef migrations add AddFooTimestamp in the command line:

Identity value generation cannot be used for the property 'Created' on
  entity type 'Foo' because the property type is 'DateTime'. Identity
  value generation can only be used with signed integer properties.

Is there an effective way to utilize the data annotations described in the documentation in the models along with code first migrations in a EF Core and SQL Server environment? OR is it just [Timestamp] annotation that would be available at this time?
My project is using tool Microsoft.EntityFrameworkCore.Tools version "1.0.0-preview2-final" and Microsoft.EntityFrameworkCore & Microsoft.EntityFrameworkCore.SqlServer versions "1.1.0".
Thank you for any help you can provide.

A: To have to DateTime model properties that are set on INSERT and UPDATE actions I utilized a combination of Default Values via Fluent API configuration and database triggers. The annotations I mentioned in my question absolutely do not automatically configure SQL Server to generated default or updated DateTime values.
Model:
public class Foo {
    // some properties

    public DateTime Created { get; set; }

    public DateTime LastUpdated { get; set; }

    // more properties
}

Default Values:
protected override void OnModelCreating(ModelBuilder modelBuilder)
    modelBuilder.Entity<Foo>()
        .Property(i => i.Created)
        .HasDefaultValueSql("getdate()");

    modelBuilder.Entity<Foo>()
        .Property(i => i.LastUpdated)
        .HasDefaultValueSql("getdate()");
}

Database AFTER UPDATE Trigger:
CREATE TRIGGER [dbo].[Foo_UPDATE] ON [dbo].[Foo]
    AFTER UPDATE
AS
BEGIN
    SET NOCOUNT ON;

    IF ((SELECT TRIGGER_NESTLEVEL()) > 1) RETURN;

    DECLARE @Id INT

    SELECT @Id = INSERTED.Id
    FROM INSERTED

    UPDATE dbo.Foo
    SET LastUpdated = GETDATE()
    WHERE Id = @Id
END

Thanks!


text:
Q: Granting cloudtrails access to kms keys in terraform My first attempt at doing this resulted in a circular reference:
resource "aws_kms_key" "cloudtrails-key" {
  description = "KMS Master Key for trails logs"
  key_usage = "ENCRYPT_DECRYPT"
  customer_master_key_spec = "SYMMETRIC_DEFAULT"
  deletion_window_in_days = 30
  is_enabled = true
  enable_key_rotation = false
  policy = data.aws_iam_policy_document.cloudtrails-key-policy.json
  multi_region = true

  tags = {
    ManagedBy                     = "terraform"
    Name                          = "${var.project_name}-${var.environment}-${var.aws_account_id}-cloudtrails-key"
    Environment                   = var.environment
    Usage                         = "monitoring"
  }
}

data "aws_iam_policy_document" "cloudtrails-key-policy" {
  statement {
    principals {
      type        = "Service"
      identifiers = [ "cloudtrail.amazonaws.com" ]
    }

    actions = [
      "kms:CallerAccount",
      "kms:EncryptionAlgorithm",
      "kms:EncryptionContext:*",
      "kms:EncryptionContextKeys",
      "kms:RequestAlias",
      "kms:ViaService"
    ]

    resources = [ aws_kms_key.cloudtrails-key.arn ]

    condition {
     test     = "ForAnyValue:StringLike"
     variable = "aws:SourceArn"
     values   = toset([for k, v in var.all_account_ids : "arn:aws:cloudtrail:*:${v}:trail/full-cloudtrails"])
    }
  }
}

As I couldn't determine how to remove the circular reference, I decided to try using grants instead:
resource "aws_kms_grant" "cloudtrails-key-grant" {
  depends_on = [ aws_kms_key.cloudtrails-key ]
  for_each = var.all_account_ids
  name = "${each.key}-cloudtrails-key-grant"
  key_id = aws_kms_key.cloudtrails-key.key_id
  grantee_principal = "arn:aws:cloudtrail::${each.value}:trail/full-cloudtrails"
  operations = [ "Encrypt" ]
}

var.all_account_ids refers to a map of account names and account IDs.
I then updated the aws_kms_key block to remove the policy argument. However, this resulted instead in the following output on apply:
Terraform v1.3.8
on linux_amd64
aws_kms_grant.cloudtrails-key-grant["users"]: Creating...
aws_kms_grant.cloudtrails-key-grant["root"]: Creating...
aws_kms_grant.cloudtrails-key-grant["dev"]: Creating...
aws_kms_grant.cloudtrails-key-grant["shared"]: Creating...
aws_kms_grant.cloudtrails-key-grant["monitoring"]: Creating...
aws_cloudtrail.full-cloudtrails: Modifying... [id=full-cloudtrails]

...

aws_kms_grant.cloudtrails-key-grant["users"]: Still creating... [2m50s elapsed]
aws_kms_grant.cloudtrails-key-grant["monitoring"]: Still creating... [2m50s elapsed]
╷
│ Error: updating CloudTrail Trail (full-cloudtrails): InsufficientEncryptionPolicyException: Insufficient permissions to access S3 bucket full-cloudtrails or KMS key arn:aws:kms:us-east-1:703617067304:key/mrk-c0a4616ba4f74ae9b5ac4ecd1f96e95b.
│
│   with aws_cloudtrail.full-cloudtrails,
│   on monitoring.tf line 1, in resource "aws_cloudtrail" "full-cloudtrails":
│    1: resource "aws_cloudtrail" "full-cloudtrails" {
│
╵
╷
│ Error: creating KMS Grant for Key (mrk-c0a4616ba4f74ae9b5ac4ecd1f96e95b): InvalidArnException: ARN is not valid: arn:aws:cloudtrail:us-east-1:323924548037:trail/full-cloudtrails
│
│   with aws_kms_grant.cloudtrails-key-grant["root"],
│   on security.tf line 19, in resource "aws_kms_grant" "cloudtrails-key-grant":
│   19: resource "aws_kms_grant" "cloudtrails-key-grant" {
│
╵
╷
│ Error: creating KMS Grant for Key (mrk-c0a4616ba4f74ae9b5ac4ecd1f96e95b): InvalidArnException: ARN is not valid: arn:aws:cloudtrail:us-east-1:739800733271:trail/full-cloudtrails
│
│   with aws_kms_grant.cloudtrails-key-grant["shared"],
│   on security.tf line 19, in resource "aws_kms_grant" "cloudtrails-key-grant":
│   19: resource "aws_kms_grant" "cloudtrails-key-grant" {
│
╵
╷
│ Error: creating KMS Grant for Key (mrk-c0a4616ba4f74ae9b5ac4ecd1f96e95b): InvalidArnException: ARN is not valid: arn:aws:cloudtrail:us-east-1:703617067304:trail/full-cloudtrails
│
│   with aws_kms_grant.cloudtrails-key-grant["monitoring"],
│   on security.tf line 19, in resource "aws_kms_grant" "cloudtrails-key-grant":
│   19: resource "aws_kms_grant" "cloudtrails-key-grant" {
│
╵
╷
│ Error: creating KMS Grant for Key (mrk-c0a4616ba4f74ae9b5ac4ecd1f96e95b): InvalidArnException: ARN is not valid: arn:aws:cloudtrail:us-east-1:457407591303:trail/full-cloudtrails
│
│   with aws_kms_grant.cloudtrails-key-grant["dev"],
│   on security.tf line 19, in resource "aws_kms_grant" "cloudtrails-key-grant":
│   19: resource "aws_kms_grant" "cloudtrails-key-grant" {
│
╵
╷
│ Error: creating KMS Grant for Key (mrk-c0a4616ba4f74ae9b5ac4ecd1f96e95b): InvalidArnException: ARN is not valid: arn:aws:cloudtrail:us-east-1:158889104371:trail/full-cloudtrails
│
│   with aws_kms_grant.cloudtrails-key-grant["users"],
│   on security.tf line 19, in resource "aws_kms_grant" "cloudtrails-key-grant":
│   19: resource "aws_kms_grant" "cloudtrails-key-grant" {
│
╵

I tried adding the region (though I would prefer multi-region), taking off the trail name after the slash, using wildcards for region, but everything resulted in the above invalid ARN exception.
I was curious to know if anyone has any working recipes for granting cloudtrails encryption access to a KMS key, as I'm unsure what I'm doing wrong with either method (policy or grant)

A: The solution for the cyclical reference was to broaden the resource scope to all keys, and not just the one key. This was done on all examples in AWS documentation. I also had to add the default key policy offered by AWS otherwise I got a warning that I would be locking myself out.
The Default Key Policy can be found documented here. The specific key policy required for CloudTrail is found here. Using these two resources, the final working configuration is below:
data "aws_iam_policy_document" "cloudtrail-key-policy" {
  statement {
    principals {
      type        = "Service"
      identifiers = [ "cloudtrail.amazonaws.com" ]
    }

    actions = [
      "kms:DescribeKey",
      "kms:GenerateDataKey*"
    ]

    resources = [ "*" ]

    condition {
      test      = "ForAnyValue:StringLike"
      variable  = "kms:EncryptionContext:aws:cloudtrail:arn"
      values    = toset([for k, v in var.all_account_ids : "arn:aws:cloudtrail:*:${v}:trail/${k}-full-cloudtrail"])
    }

    condition {
      test      = "ForAnyValue:StringLike"
      variable  = "aws:SourceArn"
      values    = toset([for k, v in var.all_account_ids : "arn:aws:cloudtrail:*:${v}:trail/${k}-full-cloudtrail"])
    }
  }

  statement {
    principals {
      type        = "AWS"
      identifiers = [ "arn:aws:iam::${var.aws_account_id}:role/terraform-${var.environment}" ]
    }

    actions = [
      "kms:Create*",
      "kms:Describe*",
      "kms:Enable*",
      "kms:List*",
      "kms:Put*",
      "kms:Update*",
      "kms:Revoke*",
      "kms:Disable*",
      "kms:Get*",
      "kms:Delete*",
      "kms:TagResource",
      "kms:UntagResource",
      "kms:ScheduleKeyDeletion",
      "kms:CancelKeyDeletion"
    ]

    resources = [ "*" ]
  }

  statement {
    principals {
      type        = "AWS"
      identifiers = [ "arn:aws:iam::${var.aws_account_id}:root" ]
    }

    actions = [ "kms:*" ]
    resources = [ "*" ]
  }
}

Additionally, no grants were needed as we're doing this for a service. According to the documentation, service ARNs are excluded:

The grantee principal can be any AWS principal, including an AWS
account (root), an IAM user, an IAM role, a federated role or user, or
an assumed role user. The grantee principal can be in the same account
as the KMS key or a different account. However, the grantee principal
cannot be a service principal, an IAM group, or an AWS organization

The above text can be found here
Hopefully this helps future readers with the same issue.
EDIT: Updated with final working config


text:
Q: pyspark rdd taking the max frequency with the least age I have an rdd like the following:
[{'age': 2.18430371791803,
  'code': u'"315.320000"',
  'id': u'"00008RINR"'},
 {'age': 2.80033330216659,
  'code': u'"315.320000"',
  'id': u'"00008RINR"'},
 {'age': 2.8222365762732,
  'code': u'"315.320000"',
  'id': u'"00008RINR"'},
 {...}]

I am trying to reduce each id to just 1 record by taking the highest frequency code using code like:
rdd.map(lambda x: (x["id"], [(x["age"], x["code"])]))\
.reduceByKey(lambda x, y: x + y)\
.map(lambda x: [i[1] for i in x[1]])\
.map(lambda x: [max(zip((x.count(i) for i in set(x)), set(x)))])

There is one problem with this implementation, it doesn't consider age, so if for example one id had multiple codes with a frequency of 2, it would take the last code.
To illustrate this issue, please consider this reduced id:
(u'"000PZ7S2G"',
 [(4.3218651186303, u'"388.400000"'),
  (4.34924421126357, u'"388.400000"'),
  (4.3218651186303, u'"389.900000"'),
  (4.34924421126357, u'"389.900000"'),
  (13.3667102491139, u'"794.310000"'),
  (5.99897016368982, u'"995.300000"'),
  (6.02634923989903, u'"995.300000"'),
  (4.3218651186303, u'"V72.19"'),
  (4.34924421126357, u'"V72.19"'),
  (13.3639723398581, u'"V81.2"'),
  (13.3667102491139, u'"V81.2"')])

my code would output:
[(2, u'"V81.2"')]

when I would like for it to output:
[(2, u'"388.400000"')]

because although the frequency is the same for both of these codes, code 388.400000 has a lesser age and appears first.
by adding this line after the .reduceByKey():
.map(lambda x: (x[0], [i for i in x[1] if i[0] == min(x[1])[0]]))

I'm able to filter out those with greater than min age, but then I'm only considering those with min age and not all codes to calculate their frequency. I can't apply the same/ similar logic after [max(zip((x.count(i) for i in set(x)), set(x)))] as the set(x) is the set of x[1], which doesn't consider the age.
I should add, I don't want to just take the first code with the highest frequency, I'd like to take the highest frequency code with the least age, or the code that appears first, if this is possible, using only rdd actions.
equivalent code in SQL of what I'm trying to get would be something like:
SELECT code, count(*) as code_frequency
FROM (SELECT id, code, age
FROM (SELECT id, code, MIN(age) AS age, COUNT(*) as cnt,
             ROW_NUMBER() OVER (PARTITION BY id ORDER BY COUNT(*) DESC, MIN(age)) as seqnum
      FROM tbl
      GROUP BY id, code
     ) t
WHERE seqnum = 1) a
GROUP BY code
ORDER by code_frequency DESC
LIMIT 5;

and as a DF (though trying to avoid this):
wc = Window().partitionBy("id", "code").orderBy("age")
wc2 = Window().partitionBy("id")
df = rdd.toDF()
df = df.withColumn("count", F.count("code").over(wc))\
.withColumn("max", F.max("count").over(wc2))\
.filter("count = max")\
.groupBy("id").agg(F.first("age").alias("age"),
                           F.first("code").alias("code"))\
.orderBy("id")\
.groupBy("code")\
.count()\
.orderBy("count", ascending = False)

I'd really appreciate any help with this.

A: Based on the SQL equivalent of your code, I converted the logic into the following rdd1 plus some post-processing (starting from the original RDD):
rdd = sc.parallelize([{'age': 4.3218651186303, 'code': '"388.400000"', 'id': '"000PZ7S2G"'},
 {'age': 4.34924421126357, 'code': '"388.400000"', 'id': '"000PZ7S2G"'},
 {'age': 4.3218651186303, 'code': '"389.900000"', 'id': '"000PZ7S2G"'},
 {'age': 4.34924421126357, 'code': '"389.900000"', 'id': '"000PZ7S2G"'},
 {'age': 13.3667102491139, 'code': '"794.310000"', 'id': '"000PZ7S2G"'},
 {'age': 5.99897016368982, 'code': '"995.300000"', 'id': '"000PZ7S2G"'},
 {'age': 6.02634923989903, 'code': '"995.300000"', 'id': '"000PZ7S2G"'},
 {'age': 4.3218651186303, 'code': '"V72.19"', 'id': '"000PZ7S2G"'},
 {'age': 4.34924421126357, 'code': '"V72.19"', 'id': '"000PZ7S2G"'},
 {'age': 13.3639723398581, 'code': '"V81.2"', 'id': '"000PZ7S2G"'},
 {'age': 13.3667102491139, 'code': '"V81.2"', 'id': '"000PZ7S2G"'}])

rdd1 = rdd.map(lambda x: ((x['id'], x['code']),(x['age'], 1))) \
    .reduceByKey(lambda x,y: (min(x[0],y[0]), x[1]+y[1])) \
    .map(lambda x: (x[0][0], (-x[1][1] ,x[1][0], x[0][1]))) \
    .reduceByKey(lambda x,y: x if x < y else y)
# [('"000PZ7S2G"', (-2, 4.3218651186303, '"388.400000"'))]

Where:

*

*use map to initialize the pair-RDD with key=(x['id'], x['code']), value=(x['age'], 1)

*use reduceByKey to calculate min_age and count

*use map to reset the pair-RDD with key=id and value=(-count, min_age, code)

*use reduceByKey to find the min value of tuples (-count, min_age, code) for the same id
The above steps are similar to:

*

*Step (1) + (2): groupby('id', 'code').agg(min('age'), count())

*Step (3) + (4): groupby('id').agg(min(struct(negative('count'),'min_age','code')))
You can then get the derived table a in your SQL by doing rdd1.map(lambda x: (x[0], x[1][2], x[1][1])), but this step is not necessary. the code can be counted directly from the above rdd1 by another map function + countByKey() method and then sort the result:
sorted(rdd1.map(lambda x: (x[1][2],1)).countByKey().items(), key=lambda y: -y[1])
# [('"388.400000"', 1)]

However, if what you are looking for is the sum(count) across all ids, then do the following:
rdd1.map(lambda x: (x[1][2],-x[1][0])).reduceByKey(lambda x,y: x+y).collect()
# [('"388.400000"', 2)]

A: If converting the rdd to a dataframe is an option, I think this approach may solve your problem:
from pyspark.sql.functions import row_number, col
from pyspark.sql import Window
df = rdd.toDF()
w = Window.partitionBy('id').orderBy('age')
df = df.withColumn('row_number', row_number.over(w)).where(col('row_number') == 1).drop('row_number')


text:
Q: How to fix ERR_SSL_VERSION_OR_CIPHER_MISMATCH error? How to fix the ERR_SSL_VERSION_OR_CIPHER_MISMATCH error?
In one of our CentOS server, we are encountering the following error in Chrome
A secure connection cannot be established because this site uses an unsupported protocol with Error Code - ERR_SSL_VERSION_OR_CIPHER_MISMATCH
We tried following command - openssl s_client -connect <<domain>>:<<port>> -tls1_2
It gives the following output. It doesn't provide a chain of certificates and negotiated cipher.
$ openssl s_client -connect <<domain>>:<<port>> -tls1_2

CONNECTED(00000003)
139874418423624:error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure:s3_pkt.c:1275:SSL alert number 40
139874418423624:error:1409E0E5:SSL routines:SSL3_WRITE_BYTES:ssl handshake failure:s3_pkt.c:598:
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 7 bytes and written 0 bytes
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
SSL-Session:
    Protocol  : TLSv1.2
    Cipher    : 0000
    Session-ID:
    Session-ID-ctx:
    Master-Key:
    Key-Arg   : None
    Krb5 Principal: None
    PSK identity: None
    PSK identity hint: None
    Start Time: 1505770082
    Timeout   : 7200 (sec)
    Verify return code: 0 (ok)

We checked available ciphers on VM using command - # /usr/bin/openssl ciphers -v. This command provides a list of available ciphers which also include ciphers supported by TLS 1.2
We also checked certificates. The same certs work on different servers.
Can someone please guide what is missing in this scenario?

A: When we use openssl, if the connection gets terminated with the alert 40 error, that means we should explicitly specify the servername in our command, so that the server can return the right certificate the client is expecting.
Specify the exact hostname you want with -servername parameter. E.g:
openssl s_client -connect yourserver.domain.com:443 -servername  yourserver.domain.com


text:
Q: Waiting for Query Params before Sending Api Call Trying to use some url parameters in an API call. Eventually my plan is to allow the user to put in a Zip Code and I will transform the zip code into latitude and longitude. This is intended to be a digital signage solution where the user can set up a URL in their signage system and include their location as part of the url.
Here's what I have for my created function in Vue. Admittedly, I am both a novice at Vue and still trying to fully understand async await. I thought that I did, but this is inconsistently not waiting for the latitude and longitude params from the query before sending the API call.
async created() {
    const lat = await this.$route.query.lat;
    const lon = await this.$route.query.lon;
    try {
      const response = await axios.get(
          'https://api.openweathermap.org/data/2.5/onecall?lat=' + lat + '&lon=' + lon + '&units=imperial&exclude=minutely,alerts&appid=' + process.env.VUE_APP_APIKEY,
          { headers: {"Content-Type": "application/json"} }
      )
      this.weather = response.data
    } catch (err) {
        console.log(err.toJSON());
    }
  }

Current Updated code using setup
setup() {
    const route = useRoute();
    let lat = ref(0);
    let lon = ref(0);
    let weather = ref(null);

    watchEffect(() => {
      lat.value = route.query.lat;
      console.log(lat.value);
      lon.value = route.query.lon;
      console.log(lon.value);

      axios.get(
        'https://api.openweathermap.org/data/2.5/onecall?lat=' + lat.value + '&lon=' + lon.value + '&units=imperial&exclude=minutely,alerts&appid=' + process.env.VUE_APP_APIKEY,
        { headers: {"Content-Type": "application/json"} }
      ).then( response => {
        weather.value = response.data;
        console.log(weather);
      }).catch(e => {
        console.log(e);
      });
    });

    return {
      lat, lon, weather
    }
  },

A: I would recommend doing this in either the watch function (both in the options and the composition API) or a watchEffect (only in the composition API), the latter is less complicated. It just listens to changes on reactive properties.
<script setup>
import { useRoute } from 'vue-router';
import { ref, watchEffect } from 'vue';

const route = useRoute();

const lat = ref(0);
const long = ref(0);

watchEffect(() => {
  lat.value = route.query.lat;
  lng.value = route.query.lng;
});
</script>

You will need to better safeguard the assignments!


text:
Q: Should a Domain Entity call a repository? I'm designing a shipping application and trying to use Clean Architecture and DDD.  Deep in the core of the domain layer we have many configurable business rules.  For example, there are business rules for determining the optimal carrier of a shipment, determining shipping mode, determining the payment type, etc.  Each business rule selects data from the database so I plan on using a BizRule Repository.  The problem is that according to my understanding of DDD principles, Domain Entities (e.g. Shipment) should not call repositories(e.g. BizRuleRepository).  The Use Case layer should be the one that calls repositories.  If I take this approach then I will have to move many complex business rules to the Use Case layer and I'm not sure if that is the best approach.  In this case, does it make sense to make an exception and have the domain entity call a repository?  Thank you in advance.

A:
Should a Domain Entity call a repository?

Generally speaking, no; it doesn't make sense for an entity (which is a domain concern) to be communicating directly with a repository (which is plumbing).
Evans, when organizing his book, assigned these ideas to different chapters

*

*A Model Expressed in Software -- describes Entities

*The Life Cycle of a Domain Object -- describes Repositories

It's a problem of language; Repositories normally have collection or persistence semantics, which are not (typically) part of the ubiquitous language of the domain.
That said, there is a loop hole; domain services can describe data retrieval using the ubiquitous language, and delegate that work to application or infrastructure services.
So (assuming for the moment that the business rules are a domain concept), you would have a domain entity that knows which business rule it needs, and a domain service that knows how to retrieve a business rule, and then the entity that knows how to use it.
If business rules are not a domain concept, then some of the work shifts from the entity into the domain service, but the core of the pattern remains the same -- the entity passes arguments to the service, the service returns a domain value the entity understands, the entity decides how to apply that value in its current processing.

We can solve any problem by introducing an extra level of indirection

It's a bit of a shell game; under the covers, we're still using the plumbing; but the domain model only sees the porcelain.
That extra layer of indirection can be really handy when you want to unit test the domain logic without dragging in the entire world of plumbing dependencies: you replace the domain service with a test double.

A: If it is just for readings it should be ok, maybe it can be cleaner having an interface/service (also with just 1 method) that express the desired query to your store, decoupling your entity from the repository.
In this way you can easily mock the query during tests, and in the future the lookup method can be easily improved in its own class (or you can also pass different strategies/implementation for the lookup).
Problem arises when you use repositories to write inside entities.


text:
Q: I'm trying to implement a binary tree. My program stops abruptly after a few node insertions. What is going wrong? I'm just trying out implementation of binary tree. It's not for a college class so I cannot ask a teacher :(
I have tried debugging it with the Codeblocks debugger but I'm still not understanding what is going wrong.
I am using class instead of struct. Currently I have only implemented insertion and inorder traversal functions.
For insertion function, I am checking if the root node is NULL or not. If it is NULL, the newNode becomes equal to the root node. Or else, I find the appropriate parent node and then append the newNode as its child.
And, in the inorder traversal function, is my recursion correct?
Edit: Turns out that I wasn't initializing my Node variables. My code is working after initializing those variables. Thanks for your help!
#include<iostream>
using namespace std;

class Node
{
public:
    int data;
    Node* left_child;
    Node* right_child;
};

Node* root = NULL;
void insertion();
void inorder_travesal(Node*);

int main(){
    char ch;
    do{
        int choice;
        cout<<"\nEnter your choice: \n1. Insertion\n2. Inorder Traversal\n : ";
        cin>>choice;

        switch(choice){
            case 1: insertion();
                    break;

            case 2: inorder_travesal(root);
                    break;
        }

        cout<<"\nDo you want to continue?: ";
        cin>>ch;

    }while(ch == 'y');

    return 0;
}

void insertion(){
    int data;
    cout<<"\nEnter data: ";
    cin>>data;

    Node* newNode = new Node;
    newNode->data = data;

    if(root == NULL)
    {
        root = newNode;
        return;
    }
    else
    {
        Node* temp = root;

        while(true){

            if(temp->data > newNode->data)
            {
                if(temp->left_child == NULL)
                {
                    temp->left_child = newNode;
                    return;
                }
                else
                {
                    temp = temp->left_child;
                }
            }
            else
            {
                if(temp->right_child == NULL)
                {
                    temp->right_child = newNode;
                    return;
                }
                else
                {
                    temp = temp->right_child;
                }
            }
        }
    }
    inorder_travesal(root);
}

void inorder_travesal(Node* temp){

    if(temp->left_child != NULL){
        inorder_travesal(temp->left_child);
    }

    cout<<temp->data<<" ";

    if(temp->right_child != NULL){
        inorder_travesal(temp->right_child);
    }
}


text:
Q: About proof: $\cot^{-1}\left(\frac{\sqrt{1+\sin x}+\sqrt{1-\sin x}}{\sqrt{1+\sin x}-\sqrt{1-\sin x}}\right)=\frac x2$ I have the following question:

Prove that: $$ \cot^{-1}\Biggl(\frac{\sqrt{1+\sin x} + \sqrt{1-\sin x}}{\sqrt{1+\sin x} - \sqrt{1-\sin x}}\Biggl) = \frac x2, \ x \in \biggl(0, \frac \pi4\biggl) $$
The solution:

My question is about the second step (i.e., highlighted). We know that it has came from the following resolution: $$ \sqrt{1\pm \sin x} = \sqrt{\sin^2\frac x 2 + \cos^2\frac x 2 \pm2\sin\frac x 2\cos\frac x 2} = \pm \biggl( \cos\frac x 2 \pm \sin\frac x 2 \ \biggl) $$
I've included the $\pm$ symbol in accordance with the standard definition of square root. The above solution uses the positive resolution (i.e., $ \cos\frac x 2 - \sin\frac x 2 $) for $ \sqrt{1- \sin x} $. But, if I use the negative one, then the result changes. The sixth step changes to: $$ \cot^{-1}\biggl(\tan\frac x 2\biggl) = \cot^{-1}\Biggl(\cot\left(\frac \pi 2 - \frac x 2\right)\Biggl) $$
which yield the result: $$ \frac \pi 2 - \frac x 2 $$
Mathematically, this result is different from that provided in the RHS of question.
Is the question statement wrong or I've been hacked up?

A: Rationalize the numerator to find
$$f(x)=\dfrac{1+|\cos x|}{\sin x}$$
Now if $\cos x\ge0,$ $$f(x)=\cot\dfrac x2$$
$\cot^{-1}f(x)=?$
Else $f(x)=\dfrac{1-\cos x}{\sin x}=\tan\dfrac x2$
Now $\cot^{-1}f(x)=\dfrac\pi2-\tan^{-1}f(x)=?$

A: As StubbornAtom mentioned in comment, for $x \in \biggl(0, \frac \pi4\biggl)$, the square root is:
$$\sqrt{1-\sin x}=\cos \frac x2-\sin \frac x2,$$
because:
$$\cos \frac x2-\sin \frac x2>0.$$
If, for example, $x \in \biggl(\frac \pi2, \pi\biggl)$, the square root would be:
$$\sqrt{1-\sin x}=\sin\frac x2-\cos \frac x2,$$
because:
$$\sin \frac x2-\cos \frac x2>0.$$
Addendum. Note that $\pm$ is placed to make the number positive and it does not imply one gets positive and negative values for the square root. Here is another way to write the same equality:
$$\sqrt{1-\sin x}=\left|\cos \frac x2-\sin \frac x2\right|=\begin{cases}+\left(\cos \frac x2-\sin \frac x2\right), \cos \frac x2-\sin \frac x2\ge 0 \\ -\left(\cos \frac x2-\sin \frac x2\right), \cos \frac x2-\sin \frac x2< 0 \\ \end{cases}.$$

A: Note that for $x\in (0,{\pi \over 4})$ we have $$\sqrt{1-{\sqrt 2\over 2}}<\sqrt{1-\sin x}<1\\\sqrt{1-{\sqrt 2\over 2}}=\cos {\pi \over 8}-\sin {\pi \over 8}<\cos {x\over 2}-\sin{x\over 2}<1\\-1<\sin {x \over 2}-\cos {x \over 2}<-\sqrt{1-{\sqrt 2\over 2}}$$comparing the range for all $x\in (0,{\pi \over 4})$ we obtain$$\sqrt{1-\sin x}=\cos {x\over 2}-\sin{x\over 2}$$and$$\sqrt{1-\sin x}\ne \sin {x\over 2}-\cos{x\over 2}$$

A: We see that
$$\frac{\sqrt{1+\sin x} + \sqrt{1-\sin x}}{\sqrt{1+\sin x} - \sqrt{1-\sin x}}$$
$$= \sqrt{(\frac{\sqrt{1+\sin x} + \sqrt{1-\sin x}}{\sqrt{1+\sin x} - \sqrt{1-\sin x}})^2}$$
$$= \sqrt{\frac{1+\sin x +1-\sin x + 2\cdot\sqrt{1-\sin^2 x}}{1+\sin x +1-\sin x -2\cdot\sqrt{1-\sin^2 x}}}$$
$$= \sqrt{\frac{1+\cos x}{1-\cos x}}$$
$$= \sqrt{\frac{2\cdot\cos^2\frac{x}{2}}{2\cdot\sin^2\frac{x}{2}}}$$
$$= \cot \frac{x}{2}$$
And hence,
$$\cot^{-1} (\frac{\sqrt{1+\sin x} + \sqrt{1-\sin x}}{\sqrt{1+\sin x} - \sqrt{1-\sin x}})$$
$$= \cot^{-1} (\cot \frac{x}{2})$$
$$= \frac{x}{2}$$
Note: as $x\in [0,\frac{\pi}{4}]$, $\sqrt{1-\sin x} \le \sqrt{1+\sin x}$.
And hence
$$0\le\frac{\sqrt{1+\sin x} + \sqrt{1-\sin x}}{\sqrt{1+\sin x} - \sqrt{1-\sin x}}$$


text:
Q: Localization in iphone How to do localization in iphone.
in my current project i have to display my app in 16 languages
all the language domains coming from backend
In the backend php guys using language transition, they are using like this
English:
var_name:LOGIN_BTN;
value=Log-in;

French:
var_name=LOGIN_BTN;
value:Loggain;

so for all languages  var_name will be same but value is going to change.
all these var_name and values coming from their database.
the following is the url they have provided me
"http://www.euroclinix.dev-projects.com/mob-web-service.php?action=trans_list&did=29"
did=doamin-id

A: In general:
For backend/webservice localization you should send your device language to the backend service. Then it should only deliver the needed language.
If that's not possible, you have to get all languages and determine which one to use right on the device.


text:
Q: Do i really need another framework for android game programming I recently started with android game programming. I feel OK to work with OpenGL java. I can develop games without using other frameworks like unity3d and many others.
I feel if i start to use any framework it will make my work fast. But when come to performance i discovered that the frameworks burn out resources ....
Do I really need to choose any framework for android game development? If yes what will be the best bet (best in free & best paid)
Thanks alot for reading out and responding

A: Engines and frameworks to create games for Android:

*

*Unity 3D Android / IOS (300$) (nice if you can afford it) EDIT: It's for free now :).

*AndEngine http://www.andengine.org/blog/

*LibGDX http://code.google.com/p/libgdx/ <-- I prefer this one

*angle http://code.google.com/p/angle/

*Rokon http://www.rokonandroid.com/

*SHIVA http://www.stonetrip.com/
You don't have to choose a framework. But it's hard work to create a game for android. When you want to write a 3D game I hope you know what you're doing. It's almost impossible to write high quality 3D games by yourself (enjoy drawing 3D models and optimizing your code.). Thats why I stay with 2D for now.


text:
Q: Show Annotation Pin on mapView when button is pressed trying to figure out if it is possible when a button is pressed to go to a certain longitude and latitude in mapView and drop a button. I copied my code for a "newAnnotation" pin which previously worked, but realize now it might not be working inside of the code of my button. Here is my button code:
-(IBAction)buttonPressed
{
CLLocationCoordinate2D location;
MKCoordinateSpan span;
location.latitude = (double) 44.4758;
    location.longitude = (double) -73.2125;
span.latitudeDelta=0.2;
span.longitudeDelta=0.2;

    MapViewAnnotation *newAnnotation = [[MapViewAnnotation alloc] initWithTitle:@"BCA"
    andCoordinate:location];
[self.mapView addAnnotation:newAnnotation];
[newAnnotation release];

themapView = [[MapView alloc] initWithNibName:@"MapView" bundle:nil];
[self.view addSubview:themapView.view];
}

I know that the button WORKS and that it actually goes to the mapView and is processing the coordinates, but that it just isn't dropping the pin with the title. Currently there are no errors as my code stands. If you need to see other code, let me know. Thanks a million.

A: I think your problem is that you are adding an annotation to a map view that is not visible yet. You have to first add the map view view as a subview then add the annotation. Here is what the code would look like:
-(IBAction)buttonPressed
{
CLLocationCoordinate2D location;
MKCoordinateSpan span;
location.latitude = (double) 44.4758;
    location.longitude = (double) -73.2125;
span.latitudeDelta=0.2;
span.longitudeDelta=0.2;

MapViewAnnotation *newAnnotation = [[MapViewAnnotation alloc] initWithTitle:@"BCA"
andCoordinate:location];
[self.mapView addAnnotation:newAnnotation];
[newAnnotation release];

themapView = [[MapView alloc] initWithNibName:@"MapView" bundle:nil];
[self.view addSubview:themapView.view];

}

UPDATE:
Can we see the code for MapViewAnnotation. It should be an NSObject class which adopts MKAnnotation like this <MKAnnotation> and you should declare and synthesize three properties: title, subtitle if you like, and of course coordinate
Another problem may be that you are adding MapView's view as a subview. It might be better to put this code in MapView and present MapView as a view controller
I also do not understand why you are adding an annotation to self.mapView and then adding a subview over it.....

A: You're adding your annotation to self.mapview, then making a separate map and adding its view as a subview, which is weird.
If your self.mapview is already on screen then you can remove the last two lines of your function. If not then your function might need to be changed to be more like this
-(IBAction)buttonPressed
{
    CLLocationCoordinate2D location;
    MKCoordinateSpan span;
    location.latitude = (double) 44.4758;
    location.longitude = (double) -73.2125;
    span.latitudeDelta=0.2;
    span.longitudeDelta=0.2;

    themapView = [[MapView alloc] initWithNibName:@"MapView" bundle:nil];
    [self.view addSubview:themapView];

    MapViewAnnotation *newAnnotation = [[MapViewAnnotation alloc] initWithTitle:@"BCA"
andCoordinate:location];
    [themapView addAnnotation:newAnnotation];
    [newAnnotation release];

}
Important changes are that you're adding the annotation to themapView that you've just initialised, and that you're adding themapView (not its .view) to the current .view. You may also need to recenter your map.


text:
Q: To create a 6 * 6 color palette using html5 canvas I want to create a clickable 6 * 6 color palette using HTML5 Canvas. I should be able to click on each color grid on the palette and the background color should change to the selected color.

A: Using React, I made this. Maybe after looking this over you'll have an idea of what all you'll need to do.

class Palette extends React.Component {
  constructor(props) {
    super(props);
    this.state = { color: '#FFFFFF' };
  }

  setColor(row, col) {
    const color = this.getColor(row, col);

    this.setState({ color });
    document.body.style.backgroundColor = color;
  }

  getColor(row, col) {
    const hue = Math.floor(col / this.props.height * 360);
    const sat = 100;
    const lit = Math.floor((1 - (row + 1) / (this.props.width + 1)) * 100);

    return `hsl(${hue},${sat}%,${lit}%)`;
  }

  render() {
    const rows = [];

    for (let i = 0; i < this.props.height; i++) {
      const cols = [];

      for (let j = 0; j < this.props.width; j++) {

        cols.push(

 this.setColor(j, i)
            }
            style={{
              backgroundColor: this.getColor(j, i)
            }} />
        );
      }

      rows.push(

          {cols}

      );
    }

    return (

        {rows}

    );
  }
}

ReactDOM.render(<Palette width={6} height={6} />, document.body);
.palette {
  display: flex;
  flex: 1;
  flex-direction: column;
  cursor: pointer;
}

.row {
  display: flex;
  flex: 1;
  flex-direction: row;
}

.col {
  width: 20px;
  height: 20px;
}


text:
Q: windows 7 crashes while attaching an embedded image using phpmailer I am writing a script to send birthday messages automatically to employees. For now I have taken hard-coded email ids. Now the problem is that these scripts are working perfectly well on my laptop Windows 10 Wampserver3.0.6. But now when I am transfering these files to the main desktop in the office(Windows 7 Wampserver3.1.3), the email sending based scripts crash the computer when you embed or attach an image. If I remove the attachment and send only the text, the email gets sent. But on attaching an image the computer crashes directly. The code is as follows:
require("PHPMailer-master\src\PHPMailer.php");
require("PHPMailer-master\src\SMTP.php");
require("PHPMailer-master\src\Exception.php");
$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 1;
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;
$mail->IsHTML(true);
$mail->Username = "abc@gmail.com";
$mail->Password = "********";
$mail->SetFrom("abc@gmail.com");
$mail->Subject = "Happy birthday!";
$mail->AddEmbeddedImage('compressed.jpg', 'compressed');
$mail->Body = "
Happy Birthday!

Have a wonderful day!";
$mail->AddAddress("abc@gmail.com","def@hotmail.com");
 if(!$mail->send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
 } else {
    echo "Message has been sent";
 }

I have tried so many things. I have increased the memory_limit of wamp server.
An additional thing, debug=1 displays the process on chrome. So if i embed an image, it stops halfway, it does not display the process completely and crashes in the middle.
NOTE: addAttachment() works well but addEmbeddedImage() crashes the computer
It works perfectly well on my laptop. Please help.


text:
Q: Conditional References in a JSON Schema I want to write a single file JSON schema definition with several sub schemas that I can combine, depending on the payload.
The following schema validates, that my schema is working with my sample JSON response. (The response object has a wrong type for payload.role to make sure the schema catches this mistake!)
For clarity, I reduce it on the most important parts. A full working example can be found here: https://www.jsonschemavalidator.net/s/3KAaXjtg
Schema
{
  "$schema": "http://json-schema.org/draft-07/schema",
  "$id": "http://example.com/baseSchema.json",
  "type": "object",
  "required": [
    "payload"
  ],
  "properties": {
    "payload": {
      "$id": "#/properties/payload",
      "type": "object",
      // reference the right schema depending on the payload child key
      // if `payload.user` reference `userSchema.json`
      // if `payload.users` reference `usersSchema.json`
      // if `payload.*` reference `*Schema.json`
      "$ref": "userSchema.json"
    }
  },
  "definitions": {
    "user": {
      "$id": "http://example.com/userSchema.json",
      "type": "object",
      "required": [
        "user"
      ],
      "properties": {
        "user": {
          "type": "object",
          "$ref": "userProperties.json"
        }
      }
    },
    "users": {
      "$id": "http://example.com/usersSchema.json",
      "type": "object",
      "required": [
        "users"
      ],
      "properties": {
        "users": {
          "type": "array",
          "items": {
            "$ref": "userProperties.json"
          }
        }
      }
    },
    "userProperties": {
      "$id": "http://example.com/userProperties.json",
      "type": "object",
      "properties": {
        "firstName": {
          "$id": "#/properties/payload/properties/user/properties/firstName",
          "type": "string"
        }
      }
    }
  }
}

Response
{
  "status": {
    "code": 200,
    "description": "User retrieved successfully."
  },
  "payload": {
    "user": {
      "firstName": "Joe",
      "lastName": "Doe",
      "role": "3", // for testing reasons, this is the wrong type!
      "email": "doe@example.com",
      "customerID": "",
      "projects": [
        "AIXG5mEg6QLl9rhVSE6m",
        "Bs1bHiOIqKclwwis3CNf",
        "NC2OUGVZXU35FA7iwRn4"
      ],
      "status": "Status",
      "id": "c555BSZnKLdHSRYqrU5hqiQo733j13"
    }
  }
}

So I've got a baseSchema.json that matches this response:
{
  "status": {},
  "payload": {}
}

payload gets extended by a certain key like payload.user = {} or payload.foo = {} and depending on that key, I want to extend schema with one of my definitions.
The following part only works for the key user:
  "properties": {
    "payload": {
      "$id": "#/properties/payload",
      "type": "object",
      // reference the right schema depending on the payload child key
      // if `payload.user` reference `userSchema.json`
      // if `payload.users` reference `usersSchema.json`
      // if `payload.*` reference `*Schema.json`
      "$ref": "userSchema.json"
    }
  },

I failed to setup any conditions (with allOf, if, else), that would reference the correct sub-schema, based on the payload key.
Any hints and help to solve that is appreciated.

A: Schema and link to demo at the end... Let's look at how we got there...
In JSON Schema draft-07 and previous, you can't use $ref alongside other keywords. Other keywords are ignored. (In your schema http://example.com/userSchema.json you had type next to $ref). Fortunatly this didn't cause you any problems as you declare the type in the referenced schema. (You CAN do this with 2019-09 or above.)
The values for the keywords if, then, and else are schemas.
For the then subschema to be applied to your instance location, the if schema must come back as valid. If it fails, the else subschema value will be applied.
Our if condition checks for the presense of a specific key.
If the key exists, THEN apply the schema which references the correct schema.
Because you want the conditions to be mutually exclusive, you need to wrap the multiple conditions in a oneOf, and add else: false to the conditional checks. false as a schema makes validation fail.
Let me know if you want any further clarification on any of the above.
Demo: https://jsonschema.dev/s/HLniL
{
  "$schema": "http://json-schema.org/draft-07/schema",
  "$id": "http://example.com/baseSchema.json",
  "type": "object",
  "required": [
    "payload"
  ],
  "properties": {
    "payload": {
      "$id": "#/properties/payload",
      "type": "object",
      "oneOf": [
        {
          "if": {
            "required": [
              "user"
            ]
          },
          "then": {
            "$ref": "userSchema.json"
          },
          "else": false
        },
        {
          "if": {
            "required": [
              "users"
            ]
          },
          "then": {
            "$ref": "usersSchema.json"
          },
          "else": false
        }
      ]
    }
  },
  "definitions": {
    "user": {
      "$id": "http://example.com/userSchema.json",
      "type": "object",
      "required": [
        "user"
      ],
      "properties": {
        "user": {
          "$ref": "userProperties.json"
        }
      }
    },
    "users": {
      "$id": "http://example.com/usersSchema.json",
      "type": "object",
      "required": [
        "users"
      ],
      "properties": {
        "users": {
          "type": "array",
          "items": {
            "$ref": "userProperties.json"
          }
        }
      }
    },
    "userProperties": {
      "$id": "http://example.com/userProperties.json",
      "type": "object",
      "properties": {
        "firstName": {
          "type": "string"
        }
      }
    }
  }
}


text:
Q: Virtual Scroll issue in Angular Universal I'm using angular 7 projects with universal integrated to it working around virtual scroll feature and am getting the following error(for server-side rendering)

ReferenceError: window is not defined
      at new VirtualScrollerComponent (/sample/universal/dist/server.js:150466:23)
      at createClass (/sample/universal/dist/server.js:26257:20)
      at createDirectiveInstance...

Any idea on how to handle this?


text:
Q: ROR route with parentheses in constraint I'm trying to create a rails route for movies (on the root path) that has parentheses containing the movie's year in it.
E.g. Men in black => "/men-in-black-(1997)"
My route is:
resources :movies,
  path:'/',
  only:[ :index, :list, :show ],
  constraints: { id: /[A-Za-z0-9-]+\(\d{4}\)/ }

When I use this route (movie_path(Movie.first)), I get
"ActionController::RoutingError: No route matches: ..."

When I change the route constraint to:
constraints: { id: /[A-Za-z0-9-]+\\\(\d{4}\\\)/ }

the route works when using the url routing helper. However, the route doesn't work for the reverse mapping (e.g. taking "/men-in-black-(1997)" and routing it to the correct action/controller). When I run (from console):
Rails.application.routes.recognize_path("/men-in-black-(1997)")

I get the same routing error:
ActionController::RoutingError: No route matches

The problem seems to be associated to how rails escapes regex's in routing. For escaping with \( the object-to-route map fails, but url-to-route works. But when escaping with \\\( it is the opposite.
Anyone have any tips or experience with this?

A: As a workaround hack you could try:
constraints: { id: /[A-Za-z0-9-]+(\\\(\d{4}\\\)|\(\d{4}\))/ }

That is, make the constraint accept either, if it accepts one in one case and the other in the other case.
Which is to say: that's weird, I have no idea why Rails would do that or how to fix it ;)

A: Well I don't have a lot of experience writing regex constraints, but you could always do a wildcard route and then sanitize in the controller.
match 'movies/*movie' => 'movie#action'

This will give you access to a :movie param with all the characters input


text:
Q: Unable to insert data in CSV file PHP I am in process of inserting data in the desired CSV file from another CSV file.
CSV file is creating fine with out any problem but its is not insert array data in file.
It only inserts header on the first row.
Below is code I am trying:
date_default_timezone_set('America/New_York');
set_time_limit(0);
ini_set("memory_limit", -1);

$realPath = realpath( dirname(__FILE__) );
$path     = $realPath.'/3pltracking/';
$files    = scandir($path);
$FilePath = $path.$files[2];
$result   = array();
$date     = date('m-d-Y_his');

if (file_exists($FilePath))
{
    if (($handle = fopen($FilePath, "r")) !== FALSE)
        {
            $i=0;
            while (($data = fgetcsv($handle, 10000, ",")) !== FALSE)
            {
                $i++;
                if($i==1) continue;

                //$list = array('$data[2],$data[25],$data[4],$data[30],$data[41],$data[27]');
                echo $data[2].",".$data[25].",".$data[4].",".$data[30].",".$data[41].",".$data[27];
                echo "<br>";
                $list = array($data[2].",".$data[25].",".$data[4].",".$data[30].",".$data[41].",".$data[27]);

            // the problem is here I believe as it is empty array if I check it outside while loop
            }

        fclose($handle);

        $headers = array('ReferenceNumber', 'TotalCartons', 'ShipCarrier', 'TrackingNum', 'FreightPP', 'TotalWeight');

        $fp = fopen($realPath.'\3pltracking\TrackingFiles\Tracking_File_'.$date.'.csv', 'w');

        fputcsv($fp, $headers);

        foreach ($list as $line) {

            $val = explode(",", $line);

            fputcsv($fp, $val);

        }

        fclose($fp);

    } else {

        $body = "File Not Found";

        }
    }

Here is my CSV file data:
TransactionNumber,CustomerName,ReferenceNumber,PurchaseOrderNumber,ShipCarrier,ShipService,ShipBilling,ShipAccount,EarliestShipDate,CancelDate,Notes,ShipToName,ShipToCompany,ShipToAddress1,ShipToAddress2,ShipToCity,ShipToState,ShipToZip,ShipToCountry,ShipToPhone,ShipToFax,ShipToEmail,ShipToCustomerName,ShipToDeptNumber,ShipToVendorID,TotalCartons,TotalPallets,TotalWeight,TotalVolume,BOLNum,TrackingNum,TrailerNum,SealNum,ShipDate,ItemNumber,ItemQuantityOrdered,ItemQuantityShipped,ItemLength,ItemWidth,ItemHeight,ItemWeight,FreightPP,WarehouseID,LotNumber,SerialNumber,ExpirationDate,Supplier,Cost,FulfillInvShippingAndHandling,FulfillInvTax,FulfillInvDiscountCode,FulfillInvDiscountAmount,FulfillInvGiftMessage,SoldToName,SoldToCompany,SoldToAddress1,SoldToAddress2,SoldToCity,SoldToState,SoldToZip,SoldToCountry,SoldToPhone,SoldToFax,SoldToEmail,SoldToCustomerID,SoldToDeptNumber,FulfillInvSalePrice,FulfillInvDiscountPct,FulfillInvDiscountAmt
242328,PARADIGM TRENDS,123810,40-402849,CUSTOMER PICK UP,LTL,FreightCollect,,,,,HG BUYING- JEFFERSON DC 884,HG BUYING- JEFFERSON DC 884,125 LOGISTICS CENTER PKWY,,JEFFERSON,AL,30549,US,,,,,,,30,0,30,0.0174,,,,,,DOV3S,64,64,4,1,1,4,0,1,,,,,,0,0,,0,,,,,,,,,,,,,,,0,0,0
33,d,123810,40-402849,CUSTOMER PICK UP,LTL,FreightCollect,,,,,HG BUYING- JEFFERSON DC 884,HG BUYING- JEFFERSON DC 884,125 LOGISTICS CENTER PKWY,,JEFFERSON,AL,30549,US,,,,,,,30,0,30,0.0174,,,,,,DOV3S,64,64,4,1,1,4,0,1,,,,,,0,0,,0,,,,,,,,,,,,,,,0,0,0
44,PARAdgdfDIGM TRENDS,123810,40-402849,CUSTOMER PICK UP,LTL,FreightCollect,,,,,HG BUYING- JEFFERSON DC 884,HG BUYING- JEFFERSON DC 884,125 LOGISTICS CENTER PKWY,,JEFFERSON,AL,30549,US,,,,,,,30,0,30,0.0174,,,,,,DOV3S,64,64,4,1,1,4,0,1,,,,,,0,0,,0,,,,,,,,,,,,,,,0,0,0
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,BY3M,176,176,11,1,1,11,,,,,,,,,,,,,,,,,,,,,,,,,,0,0,0

A: There are so many ways of going about this... including str_getcsv($csvData). However here we'd go for something old-school & a bit twisted;-). We would create a Function that uses Regex and a Looping Construct to build-up the relevant CSV Data Structure. The Function below illustrates how. Also note that although we mentioned that this is a somewhat twisted, old-school approach: don't be fooled... because it does its thing still ;-).
    <?php

        $csvSourceFile          = __DIR__ . "/1.csv";
        $csvPreferredColumns    = array('ReferenceNumber', 'TotalCartons', 'ShipCarrier', 'TrackingNum', 'FreightPP', 'TotalWeight');
        $newCsvStrut            = processCSVData($csvSourceFile,  $csvPreferredColumns, __DIR__ . "/test.csv");

        /**
         * @param $csvSource                 // PATH TO THE MAIN CSV FILE
         * @param array $csvPreferredColumns // ARRAY OF HEADER COLUMN-NAMES TO BE EXTRACTED FROM MAIN CSV
         * @param null $newCSVFileName       // NAME OF THE NEW CSV FILE TO BE CREATED.
         * @return string
         */
        function processCSVData($csvSource, array $csvPreferredColumns, $newCSVFileName=null){
            // GET THE CONTENTS OF THE CSV FILE & STORE IT IN A VARIABLE
            $csvData        = file_get_contents($csvSource);

            // SPLIT THE CONTENTS OF THE CSV FILE LINE BY LINE: THAT IS; AT THE END OF EACH LINE
            // THUS CONVERTING THE DATA TO AN ARRAY...
            $arrCsvLines    = preg_split("#\n#", $csvData);

            //FILTER OUT UNWANTED EMPTY VALUES FROM THE ARRAY
            $arrCsvLines    = array_filter($arrCsvLines);

            // CREATE SOME VARIABLES TO BE USED WITHIN THE LOOP...
            $strDataFinal   = "";
            $arrDataMain    = $arrDataFinal = array();

            // IF THERE IS MORE THAN ONE LINE IN THE ARRAY WE CREATED ABOVE,
            // THEN CONTINUE PROCESSING THE DATA...
            if($arrCsvLines && count($arrCsvLines)>0){
                // SINCE THE HEADER IS ALWAYS THE FIRST LINE IN THE CHAIN,
                // WE EXPLICITLY EXTRACT IT AND STORE IT IN A VARIABLE FOR LATER USE
                $arrCsvHeaders = preg_split("#\,([\s\t]+)?#", $arrCsvLines[0]);

                // NOW WE LOOP THROUGH ALL THE LINES WE CREATED BY SPLITTING THE CONTENTS
                // OF THE CSV FILE AT THE END-OF-LINE BOUNDARY
                foreach($arrCsvLines as $key=>$arrCsvLine){
                    // WE DON'T WANT ANYTHING AT INDEX "0" SINCE IT IS THE HEADER
                    // AND WE ALREADY DEALT WITH IT ABOVE....
                    // SO IF THE INDEX $key IS NOT 0, WE CAN CONTINUE PROCESSING
                    if($key != 0){
                        $arrDataTemp    = array();
                        $arrTempCsvData = preg_split("#\,([\s\t]+)?#", $arrCsvLine);
                        foreach($arrTempCsvData as $iKey=>$sData){
                            $arrDataTemp[$arrCsvHeaders[$iKey]] = $sData;
                        }
                        $arrDataMain[] = $arrDataTemp;
                    }
                }

                foreach($arrDataMain as $iKey=>$subData){
                    $arrTempFinal   = array();
                    foreach($subData as $key=>$data){
                        if(in_array($key, $csvPreferredColumns)){
                            $arrTempFinal[$key] = $data;
                        }
                    }
                    $arrDataFinal[] = implode(",\t", $arrTempFinal);
                }

                $arrDataFinal   = array_merge( array(implode(",\t", $csvPreferredColumns)), $arrDataFinal);
                $strDataFinal   = implode("\n", $arrDataFinal);

                if($newCSVFileName){
                    file_put_contents($newCSVFileName, $strDataFinal);
                }
            }
            return $strDataFinal;
        }

        var_dump($newCsvStrut);
        // PRODUCES SOMETHING SIMILAR TO THE LINES BELOW:
        string 'ReferenceNumber,    TotalCartons,   ShipCarrier,    TrackingNum,    FreightPP,  TotalWeight
                123810, CUSTOMER PICK UP,   30, 30, ,   0
                123810, CUSTOMER PICK UP,   30, 30, ,   0
                123810, CUSTOMER PICK UP,   30, 30, ,   0
                ,   ,   ,   ,   ,   ' (length=204)


text:
Q: BASH: Is "export" needed, when setting a variable in .bashrc? I wonder if there is a need to use "export" when setting a variable in .bashrc.
In my tests editing .bashrc there was no difference between
foo=bar

and
export foo=bar

In both cases, after login "echo $foo" outputs "bar".
I am using Debian Squeeze, if that matters.
Thank you guys in advance.

A: It's preferable because exported variables get passed to child processes (programs launched from that shell).  Without the export command those variables only apply to the shell itself and not processes launched from the shell

A: Try creating a shell script that accesses the foo variable.
If foo was export'ed, it will be visible in the shell script, otherwise it won't.

A: SuperUser has this covered.
Short answer: export makes sure the environment variable is set in child processes. If you don't export, it's only available in the same process/interactive session.


text:
Q: How to use launchctl to reload changes to plist? On MaxOS I created ~/Library/LaunchAgents/x.plist.  Then I loaded it with "launchctl load ..."
I made some edits, unloaded and reloaded it.  When I type "launchctl list x" it does not display any of my mods to the plist file.
How can I get launchctl to load my new changes? How is it remembering the first version of this file even after I unloaded it?  Does it use a cache?

A: The quickest way to update is:
# copy the new file to ~/Library/LaunchAgents

sudo launchctl unload ~/Library/LaunchAgents/x.plist
sudo launchctl load   ~/Library/LaunchAgents/x.plist


text:
Q: watir-webdriver click on image Folks,
I have an image with the following HTML code:

When I click on the image it should open a pop up so that I can add new music file, I tried a few things but I am not able to click on that image. Any suggestions?
Thanks a lot

A: You can click on it by the class or a partial match of the class.
@browser.image(:class=>/folder-action-add folder-action/).click

Here is a list of the identifiers you can use for watir, I think it's mostly the same for watir-webdriver.

A: So far, you haven't got a consistent way of actually identifying the element.  From what you've said in the comments, you've tried the 'text' attribute which doesn't exist, and the 'id' attribute which is auto generated and different every time.
You need to find a way of consistently identifying the element.  It's usually preferable to use a semantic class on the element to make styling and testing easier and less brittle.  You have a few classes declared, perhaps 'folder-action-add' expresses the intent of the button clearly?  If not, you could add one such as 'add-music-file'.
Then you should be able to use watir to select an element by it's class, I'm not familiar with the syntax but at a guess, @browser.image(:class => 'add-music-file') might do the job.


text:
Q: Applying Lloyd Relaxation to vertices within Three.js I have generated randomly positioned vertices in Three.js like so:

Using Lloyd's algorithm I'd like to apply relaxation to make the spacing of these vertices more even.
The vertices are in an array like so, with each vertice having an x, y, and z coordinate:

In Three.js, I'm not really sure how to do this, or if there's a simpler method. I understand there's a library to do this, except then I'm not sure how to actually apply that to this array specifically. I was looking to create voronoi diagrams, and this was one of the first steps.


text:
Q: $\int_{0}^{x^2 (1+x)} f(t) dt = x$ According to the second fundamental theorem of Calculus, for this problem $F(x^2(1+x))-F(0)=x$ can be used.
But I can't find a function F that works for this problem. Can someone help me with this?

A: Hint. You already have $$F(x^2(1+x))-F(0)=x.$$ Now, differentiate both sides to get $$x(3x+2)f(x^2(1+x))=1.$$
You can now solve for $f(x^2(1+x))$ explicitly, from which you can solve for $f(x)$, as long as you choose your domain wisely (since $x\mapsto x^2(1+x)$ is not a bijection from $\mathbb R$ to itself).

To do the last part, let's substitute $y=x^2(1+x)$, so that $x^3+x^2-y=0$. We want to solve this for $x$. This is quite troublesome to solve analytically (since it's a cubic), but can be done: let $x=1/a$ and multiply throughout by $a^3$ to get
$$1+a-ya^3=0.$$
The idea here is to use the triple angle identity for cosine, $\cos(3\theta)=4\cos^3\theta-3\cos\theta$. We substitute $a=k\cos\theta$ for some constant $k$ to get
$$yk^3\cos^3\theta-k\cos\theta+1=0.$$
We need the ratio of coefficients of $\cos^3\theta$ and $\cos\theta$ to be $4:-3$, so that $yk^2=4/3$, or $k=\sqrt{4/(3y)}$. So
$$\frac43\sqrt{\frac{4}{3y}}\cos^3\theta-\sqrt{\frac{4}{3y}}\cos\theta+1=0\iff\frac{2}{3\sqrt{3y}}\cos(3\theta)=-1.$$
Finally we can solve for $\cos(3\theta)$ in terms of $y$. Then, once we appropriately restrict the domain, we can find $\theta$ and hence $a$ and hence $x$ analytically. Once we have $x$ in terms of $y$, substituting back into
$$f(x^2(1+x))=\frac1{x(3x+2)}$$
will give us the answer, since the LHS will become $f(y)$ and the RHS will become something in terms of $y$. This provides an explicit formula for $f$.

A: A simpler way to solve it:
$$\int_{0}^{x^2 (1+x)} f(t) dt = x$$
$$w=x^2(1+x)$$
$$\frac{dw}{dx}=2x + 3x^2$$
By using the Fundamental Theorem of Calculus part 1:
$$\frac{d}{dx}\int_{0}^{x^2 (1+x)} f(t) dt=\frac{d}{dx} x$$
$$\frac{d}{dw}\int_{0}^{w} f(t) dt *\frac{dw}{dx}$$
$$f(w)*(2x+3x^2)=1$$
$$f(w)=\frac{1}{2x+3x^2}$$
$$w=x^2(1+x)=2$$
This holds for:
$$x=1$$
So:
$$f(2)=\frac{1}{2(1)+3(1)^2}=\frac{1}{5}$$


text:
Q: how to use scipy tplquad properly? I am trying to do some simple triple integrals in physics using scipy's tplquad. As an example, I tried to integrate constant mass density of a unit ball(func d) over the unit cube. This doesn't work. However, if I integrate constant mass density of a unit cube(func f) over the unit cube, I get a result very quickly.
I thought the problem was with providing the constant integration limits as constants instead of functions. I fixed that using lambda, but still I can't get the integral.
from scipy import integrate

''' returns the mass density at a point (x,y,z)'''
def d(z, x, y):
  return int(x**2 + y**2 + z**2 <= 1) # unit ball with constant density = 1 , here all orthogonal axes are principal

def f(x,y,z):
    return 1

integrate.tplquad(d, -1, 1, lambda x: -1, lambda x: 1,lambda x, y: -1, lambda x, y: 1) # doesn't work / too slow
integrate.tplquad(f, -1, 1, lambda x: -1, lambda x: 1,lambda x, y: -1, lambda x, y: 1) # works fine

I expect the integral of d on the given range to be 4/3*pi.

A: Most numerical integration routines (such as tplquad) approximate the integral by using polynomials. This works well if the function is smooth. Unfortunately, characteristic functions are everything else but smooth since they have a discontinuous boundary. That's why tplquad fails.
If you want to approximate the volume of a domain, a reasonable approach would be to create a mesh of triangles (in 2D) or tetrahedra (in 3D) for it, and then add the volumes of the simplices. A examples for mesh generators are pygmsh and  pygalmesh (a project of mine), but there are others.
If you actually want to integrate a function over the ball, you should probably take a look at quadpy (another project of mine). It features many integration schemes for various domains, amongst them the ball. This
import numpy
import quadpy

scheme = quadpy.ball.hammer_stroud_14_3()
val = scheme.integrate(
    lambda x: numpy.ones_like(x[0]),  # function to integrate
    [0.0, 0.0, 0.0],  # center
    1.0,  # radius
    )
print(val)  # 4.1887902047863905 == 4*pi/3

would integrate the function 1 over the unit ball using a scheme of degree 5, and it returns the exact the result.

A: Integrating a discontinuous function is a difficult numerical problem.
A work around is to define the integration domain as the unit ball:
from scipy import integrate
import numpy as np

''' returns the mass density at a point (x,y,z)'''
def d(z, x, y):
      return 1

integrate.tplquad(d, -1, 1,
                  lambda x: -np.sqrt(1-x**2), lambda x: np.sqrt(1-x**2),
                  lambda x, y: -np.sqrt(1-x**2-y**2), lambda x, y: np.sqrt(1-x**2-y**2))
# (4.188790204786397, 2.000470900043183e-09)
# 4/3*np.pi = 4.1887902047863905

Another not ideal solution is to smooth artificially the function.
Using for instance the Logistic function, see Analytic approximations of Heaviside_step_function:
''' returns the mass density at a point (x,y,z)'''
def d(z, x, y):
    r2 = x**2 + y**2 + z**2
    smoothing_length = 0.1 # same unit as r2
    d = 1 - 1/(1 + np.exp(-2*(r2-1)/smoothing_length))
    return d

integrate.tplquad(d, -1, 1, lambda x: -1, lambda x: 1,lambda x, y: -1, lambda x, y: 1)
# (4.182852937567993, 3.021537155780628e-08)

The value smoothing_length have to be chosen with care.
Monte Carlo integration could be the right method for more complex problems...


text:
Q: matrices and restriction map Let $M_{n}(F)$ be the group of $n \times n$ matrices, where $F$ is a field and $n$ is invertible in $F$.
$$
\mathfrak{sl}_{n}(F) = \{A \in M_{n}(F) : Trace(A) = 0\}
$$
$$
P\mathfrak{gl}_{n}(F) = M_n(F)/FI_n
$$
How to prove that $\mathfrak{sl}_{n}(F)$ is isomorphic to $P\mathfrak{gl}_{n}(F)$?
My attempt:
Since the quotient $\pi: M_n(F) \to P\mathfrak{gl}_n(F)$ is surjective, I want to find the kernel so that $M_n(F)/\ker(\pi) \simeq P\mathfrak{gl}_{n}(F)$, but the kernel is exactly $FI_n$....
Any help will be appreciated.

A: Notice first that the Lie bracket $[M,N]=MN-NM$ defines a structure of a Lie algebra on both $M_n(F)$ and $\mathfrak{sl}_n(F)$. Moreover, $[aI_n,bI_n]=0$, for all $a,b\in F$, so $[,]$ factors to a Lie bracket on $P\mathfrak{gl}_n(F)$ defined by $[M+FI_n, N+FI_n]=[M,N]+FI_n$.
Let $f:M\in \mathfrak{sl}_n(F)\mapsto M + FI_n \in P\mathfrak{gl}_n(F)$. Clearly, this is a morphism of Lie algebras (just look at the definitions of the brackets).
Let us show that $f$ is bijective. As @ancientmathematician says, the fact that $n$ is invertible in $F$ is crucial. Notice that $M-n^{-1}Trace(M)I_n$ has trace zero, and defines the same coset as $M$ in $P\mathfrak{gl}_n(F)$. Hence, $f$ is surjective.
Now $f$ is injective as well. For, if $M\in\mathfrak{sl}_n(F)$ satisfies $M+FI_n=0+ FI_n$, then $M=aI_n$ for some $a\in F$. Taking the race yields $na=0$, and since $n$ is invertible in $F$, we get $a=0$, and thus $M=0$. Consequently, $f$ is the desired isomorphism.


text:
Q: Laravel Sanctum protecting a model with a composite primary key I want my Laravel 8 application to handle tokens for IOT devices interfacing an API.
My original model had a composite primary key like this, and note the composite primary key.
<?php

namespace App\Models;

// use App\Models\Tenant;
use App\Traits\Multitenantable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;

class Device extends Authenticatable
{
    use HasApiTokens, HasFactory;

    protected  $fillable = [
        'device_id', 'tenant_id', 'name', 'key', 'secret'
    ];

    // protected $primaryKey = 'device_id';
    protected $primaryKey = ['device_id', 'tenant_id'];
    protected $table = 'devices';
    public $incrementing = false;

    protected $casts = [
        'created_at' => 'datetime',
        'updated_at' => 'datetime',

    ];

    public function tenant()
    {
        return $this->belongsTo(Tenant::class, 'tenant_id');
    }

    protected function setKeysForSaveQuery($query)
    {
        $query
            ->where('device_id', '=', $this->getAttribute('device_id'))
            ->where('tenant_id', '=', $this->getAttribute('tenant_id'));

        return $query;
    }
}

When trying to create the Token in the controller I got the error
ErrorException
array_key_exists(): The first argument should be either a string or an integer
The controller that handles the devices login looks like this
<?php

namespace App\Http\Controllers\API;

use App\Models\Device;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Support\Facades\Hash;

class DeviceAuthController extends Controller
{
    public function login(Request $request)
    {
        // return "Entro al login";
        $validate = $request->validate([
            'tenant_id' => 'required|integer',
            'key' => 'required|string|max:100',
            'secret' => 'required|string|max:100'
        ]);

        $device = Device::where('key', $validate['key'])->where('tenant_id', $validate['tenant_id'])->first();
        if (!$device || !Hash::check($validate['secret'], $device->secret)) {
            return response(['message' => 'invalid login'], 401);
        } else {
            $token = $device->createToken($device->name);
            $response = [
                'message' => 'Login successful',
                'device' => $device,
                'token' => $token,
            ];
            return response($response, 200);
        }
    }
}

I finally solved my problem removing the composite primary key of devices and defining the primary key like this in the Device.php
    protected $primaryKey = 'device_id';

Is there a way to use Sanctum tokens with a composite primary key model?
Thank you
Ernesto Pareja


text:
Q: Iterating through a char array, assigning each char an integer corresponding to its alphabetical location I am trying to input a string into a C# console app, have it break the string into an array of its characters, and then have it iterate through the array of characters and assign each character an integer corresponding to its alphabetic position(1-26, a-z) and populate a new array with the integers.
The input block up to the array of characters I already have:
string plainText;
Console.Write ("String:");
plainText = Console.ReadLine();
char[] plainTextArray = plainText.ToCharArray();

Not looking for a completed solution, more of a suggested direction to look in for a function(s) to implement.
Thanks.

A: Two possible solutions here:

*

*Convert the char to an int, subtract an appropriate amount to put it between 1-52, and take the number mod 26 (or .ToUpper() or ToLower() the string beforehand and put it in the 1-26 range)

*Create and prepopulate a mapping (something like Dictionary<char, int> that takes a char and returns the appropriate number

I recommend the first option.
EDIT:
Based on phoog's comment, I recommend the following method:

*

*Use String.ToUpper() to convert the string to uppercase.

*Use String.ToCharArray() to create the array of uppercase characters.

*Create an int[] array that is the same size as the char[] array.

*Iterate through the length of the arrays, converting char to int using `(plainTextArray[i] - 'a') + 1


text:
Q: C# Unity 3D NAudio throws NullReferenceException while checking for default audio endpoint I've just installed Unity 3D because I wanted to make a simple game. There is one problem with the NAudio library though.
This is my code:
var enumerator = new MMDeviceEnumerator();

if (enumerator.HasDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia)) //<--- crashes here
{
   //...
}

This is literally all Unity says when trying to launch the game:

NullReferenceException: Object reference not set to an instance of an
  object NAudio.CoreAudioApi.MMDeviceEnumerator.HasDefaultAudioEndpoint
  (DataFlow dataFlow, Role role)

I don't understand why it throws this kind of error here.
Could it be that the library might not be compatible with this version of net framework (version 3.5)?
EDIT: the variable enumerator can't be null, so stop flagging this post as a duplicate of 'What is a NullReferenceException, and how do I fix it?'
I've also tried using this libary: https://code.google.com/archive/p/naudio-with-unity3d/downloads
That library only doesn't contain the HasDefaultAudioEndpoint() function, so I just tried getting the audio endpoint directly by calling GetDefaultAudioEndpoint() but it still threw that same error on that line.

A: The problem is not your code. If you look at the source code for HasDefaultAudioEndpoint, it looks like this:
public bool HasDefaultAudioEndpoint(DataFlow dataFlow, Role role)
{
    IMMDevice device = null;
    int hresult = ((IMMDeviceEnumerator)realEnumerator).GetDefaultAudioEndpoint(dataFlow, role, out device);
    ...
}

Where realEnumerator is:
[ComImport, Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")]
class MMDeviceEnumeratorComObject
{
}

It's not checking whether realEnumerator != null, most likely because Unity was not considered and it doesn't support some COM+ interop.
If you look at this question from 2012, 4 years later the OP answered it never worked, and had to create a c++ DLL for this.


text:
Q: Jfrog system template include multiple templates file
I would like to create a jfrog system template and include multiple templates files in it.
I have tried to use "named templates" with "include" but it seems that it is not supported.
And using:
{{- template "GitRepo" . }}

Only works if I write the template define code inside 'templateDefinition.yml' as below and not in a separate file:
{{- define "GitRepo" }}
...
{{- end }}

Is there another way to organize the 'define' templates outside of 'templateDefinition.yml'?
Or any other inheritance mechanism?

A:
I have tried to use "named templates" with "include" but it seems that it is not supported.

This understanding is correct, Pipelines supports sprig based templates at the moment. Whereas support for Helm functions are soon to be released which will allow maintaining templates in _helpers.tpl file as per Helm standards.


text:
Q: Facebook app beginners guide I'm looking to write a facebook app that can hold some state. Basically what I want is something where using this app the user can issue questions to their friends (sort of like a survey but more complex interface). I have never written a facebook app so looking for a good place to start reading. Thanks in advance :)

A: This might help,. just google :)

A: As you have mentioned you have never written the "Facebook App" before. Here are some key points which will help you to create your "First Facebook App".
Here are the steps which you need to follow : -

*

*Login to "http://developers.facebook.com"

*Create a "Facebook App" as per your need platform e.g android, ios, www

*Select the catergory for "Facebook App"

*Once your complete above three steps you will have "APP ID" and "APP SECRET" created for your "Facebook App".

*You need to create the "Access Token" using the "Access Token Tool" available on "http://developers.facebook.com"

Here are the articles which will guide you through the steps : -

*

*Build your own facebook app : - http://techpost360.blogspot.com/2016/10/build-your-own-facebook-app.html

*Create Facebook Access Token : - http://techpost360.blogspot.com/2016/10/create-facebook-access-token.html
One you are through with all the above steps than you are good to go with your own implementation of Facebook App.
Hope it will help you to start.

A: As mentioned, you will need to sign you app into the Facebook Developers website: http://developers.facebook.com.
Here is a nice video I used to integrate the Facebook login into an android app. Although it is in Spanish, there is English subtitles that explain the concept.
Good luck!
https://www.youtube.com/watch?v=Jims30XAzjI&list=PLXvO8Pi6OUCZ-u5VG3JqyturXEcd3DI2s


text:
Q: Show file names as the files has been processed I want to list each file that have been processed, in a DIV. Example: when file #1 has been processed, show the file name in the DIV. When file #2 has been processed, do the same thing but append it under file #1, and so on with each file.

jQuery
var request = $.ajax({
    url: 'manage-images.php',
    type: 'GET',
    cache: false,
    beforeSend: function() {
        $('#photos').html('
Processing. Please wait...
');
    }
});

request.done(function(s) {
    $('#photos').append(s);
});

request.fail(function(s) {
    $('#photos').html('Something went wrong!');
});

manage-images.php
$dir = new RecursiveDirectoryIterator('folder-name/here', FilesystemIterator::SKIP_DOTS);
$it  = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::SELF_FIRST);
$it->setMaxDepth(1);

foreach($it AS $fileinfo) {
    if($fileinfo->isFile()) {
        // functions and stuff...

        echo $fileinfo->getFilename().' - done
';
    }
}

A: The problem is that you are processing all photos on the server side at one time. I think you will need to reconsider your architecture, and process one photo at a time. When you get the response from your first processed photo, append the file name, and make another call to process the next photo.
Here is a good example:
How to get multiple responses from PHP file via AJAX?
Edit: Your new question "How can the website know what file is next". My PHP is not great, but I hope this gets the idea across. Just have your server side page process one photo at a time.
$dir = new RecursiveDirectoryIterator('folder-name/here', FilesystemIterator::SKIP_DOTS);
$it  = new RecursiveIteratorIterator($dir, RecursiveIteratorIterator::SELF_FIRST);
$it->setMaxDepth(1);

//If there is a photo to be processed
if ( count($it) > 0)
{
  $fileinfo = $it[0];
  if($fileinfo->isFile())
  {
        // functions and stuff...
        echo $fileinfo->getFilename().' - done
';
  }
}
else
{
     echo "NO_PHOTOS";
}

Then on client side, in jQuery, you would check the response to be "NO_PHOTOS". This is how you would know to stop processing from jQuery.


text:
Q: Proof of the convexity of the unit circle using the distance between two points There is an example for proof to convexity of a unit circle in Professor Arora's "Introduction to optimum design".

Show the convexity of the set
  $$
S = \left\{\mathbf{x} \ \middle|\  x_1^2 + x_2^2 -1.0 \leq 0 \right\}
$$

I know a proof to use triangular inequality to prove the convexity of the above set.
But, the book suggests the following:

$$\mathbf{x} = \alpha \mathbf{x}^{(2)} + (1-\alpha)\mathbf{x}^{(1)} ; \quad 0 \leq \alpha \leq 1 \tag{4.71}$$
  We can also use Eq. (4.71) to show convexity of $S$. To do this, take any two points $\mathbf{x}^{(1)}$ and $\mathbf{x}^{(2)}$ in the set $S$.  Use of Eq. (4.71) to calculate $\mathbf{x}$ and the condition that the distance between $\mathbf{x}^{(1)}$ and $\mathbf{x}^{(2)}$ is non-negative (that is, $\lVert \mathbf{x}^{(1)}- \mathbf{x}^{(2)} \rVert \geq 0$)  will show $\mathbf{x} \in  S$.

I am trying the manner suggested in the book rather than using  triangular inequality. But I can not find a solution.
How can $\lVert \mathbf{x}^{(1)}- \mathbf{x}^{(2)} \rVert \geq 0$ be applied to this problem?

A: Consider two points $(x_1,y_1)$ and $(x_2,y_2)$ that belong to the set $S$. Then we must prove:
$$(tx_1+(1-t)x_2)^2+(ty_1+(1-t)y_2)^2\le 1.$$
We expand the brackets and regroup:
$$t^2(x_1^2+y_1^2)+2t(1-t)(x_1x_2+y_1y_2)+(1-t)^2(x_2^2+y_2^2)\le t^2+2t(1-t)+(1-t)^2=1,$$
because:
$$x_1^2+y_1^2\le 1; x_2^2+y_2^2\le 1;$$
$$x_1x_2+y_1y_2\le \frac{x_1^2+x_2^2}{2}+\frac{y_1^2+y_2^2}{2}=\frac{(x_1^2+y_1^2)+(x_2^2+y_2^2)}{2}\le \frac{1+1}{2}=1.$$

A: It is hard to avoid the triangle inequality in some way.
The function $\|x\| = \sqrt{x_1^2+x_2^2}$ is convex.
If $\|x\| \le 1$ and $\|y\| \le 1$ and $\alpha \in [0,1]$ then
$\|\alpha x + (1-\alpha) y\| \le \alpha \|x\| + (1-\alpha) \|y\| \le 1$.


text:
Q: How to use stored procedures with Django backend? I have created a stored procedure in SSMS for the query SELECT * FROM TABLE and now I want to create a Django API and test it. What is the entire procedure?
My script from SQL Stored Procedure:
USE [test]
GO
/****** Object:  StoredProcedure [dbo].[spGetAll]     ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[spGetAll]

AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    SELECT * from app_comment
END
GO

A: In order to call a stored procedure do the following-
from django.db import connection

def dictfetchall(cursor):
    columns = [col[0] for col in cursor.description]
    return [
        dict(zip(columns, row))
        for row in cursor.fetchall()
    ]

with connection.cursor() as cursor:
    cursor.callproc("stored_procedure", [arg1, arg2, arg3])
    data = dictfetchall(cursor)

For reference view docs

A: I could not get alamshafi2263's answer to work, giving various syntax errors. My procedure takes a parameter but returns no value.
Here is what i used successfully:
from django.db import connection
local_cursor = connection.cursor()
call_definition = f'call public.ap_update_holding_value({transaction_id})'
local_cursor.execute(call_definition)

In the above transaction_id is the parameter value.
Tested with Django==3.1.13, psycopg2==2.9.1


text:
Q: Laravel 8 - Find image url I am using Laravel Framework 8.68.0.
I am having the following configuration in my filesystems.php:
        'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
        ],

        'public_collectible_img' => [
            'driver' => 'local',
            'root' => storage_path('app/public/collectibles_img'),
            'url' => env('APP_URL').'/collectible/image',
            'visibility' => 'public',
        ],

The following link works:
http://localhost/myProject/public/storage/collectibles_img/0_test.jpg
The following link does not work:
http://localhost/myProject/public/collectible/image/0_test.jpg

All my images are in the following folder:

Any suggestion why my second link does not work?
I appreciate your replies!

A: The filesystems.php only affects Laravel's internal filesystem management (e.g. moving a file from within Laravel, saving an uploaded file, etc.), not the actual HTTP server which is what serves static files such as images. If you want to have a custom URL, you can either modify your web server's configuration (e.g. .htaccess), or create a Laravel route and controller to serve files from within Laravel. The latter approach will require that you map the requests to files yourself, and each request would have the overhead of loading PHP.
Alternatively, you could create a symlink from public/storage/collectibles_img to public/collectible/image (you would need to create the collectible folder first, then set up collectible/image as a symlink to public/storage/collectibles_img).


text:
Q: Permanent SSH tunnel through bastion host I have the following command that I run locally on my mac to be able to access a DB server trough a bastion host:
ssh -L 9234:MYSERVERIP:5432  USER@MYBASTIONIP -i MyBastionPemKey.pem

that works just fine, I can connect to it using localhost:9234
I would like to have that tunnel permanently open. I Know there are tools like autossh, but only encountered simple examples (without the bastion part) and I cant fins a way of doing it using the ~/.ssh/config file on mac
Does anyone have any idea on how to achieve the above?


text:
Q: Why does a cc file defining a map with 1500 elements need to be compiled for ten seconds // a.cc
#include <vector>
#include <unordered_map>

std::unordered_map<int32_t, std::vector<int32_t>> kItemAdDspInfoCommonAttr = {
  {1, {30740}},
  ...1500....
};

A cc file like the above needs to be compiled for 10s. As the key-value pairs of the map increase, the compilation time will swell even more.

Through the information printed by ftime-trace, I found that the time-consuming is mainly the sroa pass. I found that this is aggregate alloca.


text:
Q: Creating a corrupt Lotus database Our application connects to a Lotus Domino server and works on its databases. Once we saw a corrupt database in one of our client's server which could not be opened with the Lotus Notes client. Unfortunately the client's staff have deleted it before we could ask a copy but we would like to test the error handling of the application with this kind of corrupt databases too.
We have also tried to modify some random bytes in a good database with a hex editor to make it corrupt without success. We're looking for a way to create a corrupt database or a freely downloadable one.

A: IBM has not documented the detailed internal structure of the NSF file, so there's really no good guide to simulating corrupted databases.
If you modify all the bytes to zero, however, that will surely give you a very corrupt database.  It won't be particularly useful to test your application's behavior, and this most likely won't be the same type of corruption that you saw on your client's sever.
There are many ways an NSF could be corrupted.  Some are automatically fixed by the server.  Some will prevent the database from being opened. Some will allow you to open the database but prevent reads or updates from occurring.  Some may cause data returned by API calls to be lost or mangled. Some will crash the Notes API core DLLs.  I don't really think it's possible to test your code's behavior for all possible types of corruption.  Not in a reasonable number of test cases, anyhow. (I.e., I'm guessing about 1,000 cases of  randomly zeroing out one of the individual non-zero bytes in a minimal-sized NSF would have a good probability of inflicting most of the different kinds of damage that are possible.)

A: The internal structure of a Lotus Notes/ Domino database is best described as a container model, to get at the data inside you need to access the database container which is protected by its ACL (Access Control List). Once your inside pretty much everything is a 'Document', a unique record identified by its UNID. Some of these 'documents' are design elements like forms, agents, views (and even its ACL) etc while others are actual data records. A corruption involves one or more of these breaking, depending on what it is and how broken it is depends on what you will experience when you try to open the database or access it via the web, notes client or a third party piece of software.
Given the above, I can't see much benefit in trying to create a 'corrupt' database for testing since for this to be effective you need to know what bit you are breaking. IBM protect this, and will always protect this propriatory information as they don't want anyone building an alternative Notes client.
The last thing I'll add is that in almost fifteen years of Notes development work I have encountered corruptions so rarely that there isn't much of a business case to writing code to analyse corruptions that happen so rarely, good error handling in your code will be more than enough in the vast majority of situations.


text:
Q: Display video if image row in database is null in PHP I want to display video if the image row in database is null and vice versa. For example in my database I have tbl_library which contains columns such as image, video and the primary key is library_id.
I use while loop to view the table information and provide delete and edit button. Delete is working however, I have some issue in edit. If column image is null or empty, I want to display the video using <video>*video here*</video> and vice versa if video is empty image will display when I click edit button.
<?php

$define_attachment=mysql_query("SELECT video FROM tbl_library_ads WHERE library_id='$get_id'");

$define_image = mysql_num_rows($define_attachment);

                                if ($define_image > 0){
                                echo'

                                        <video width="500" height="350"  style="margin-top:-80px; margin-left:20px;" controls>
                                        <source src="../'.$row['video'].'" type="video/mp4">
                                        </video>

                                        Update Advertisement Video
                                        <input type="file" name="video" value="" accept="video/*">

                                      ';

                             } else {

                                echo'

                                        Update Advertisement Picture
                                        <input type="file" name="image" value="" accept="image/*">

                                      ';

                                 } ?>

A: To check if a column is empty, you can just use === NULL to test whether the column is empty. If === NULL evaluates to true, the column is empty, and you can easily use an if statement to show the appropriate HTML markup and edit form.
<?php
// Sanitize (you really should be using PDO/prepared stmnts so you don't have to do this)
$get_id = mysql_real_escape_string($get_id);
// Select statement
$define_attachment = mysql_query("SELECT video, image FROM tbl_library_ads WHERE library_id='$get_id'");
while ($row = mysql_fetch_assoc($define_attachment)) {
    if ($row['video'] !== NULL) { // If the video column is NOT empty, display the video and the corresponding form
        echo '

        <video width="500" height="350"  style="margin-top:-80px; margin-left:20px;" controls>
        <source src="../'.$row['video'].'" type="video/mp4">
        </video>

        Update Advertisement Video
        <input type="file" name="video" value="" accept="video/*">

        ';
    } elseif ($row['image'] !== NULL) { // If the image column is NOT empty, display the image and the corresponding form
        echo '

        Update Advertisement Picture
        <input type="file" name="image" value="" accept="image/*">

        ';
    }
}
?>


text:
Q: QuerySet appends _id in a field django I have a model below
class HomeImages (models.Model):

    homepage_id=models.ForeignKey(HomeAbout,on_delete=models.CASCADE)
    home_image=models.ImageField(upload_to="home_image",blank=True,null=True)

I using a filter for a serializer
  def get(self,request,homeid):

        try:
            homeimg = HomeImages.objects.filter(homepage_id=homeid).values()
        except (KeyError, HomeImages.DoesNotExist):
            return Response('Data not found', status=status.HTTP_404_NOT_FOUND)
        else:
            if len(homeimg)>0:
                print("home object",homeimg)
                return Response([HomeImgSerializer(dat).data for dat in homeimg])
            return Response([],status=status.HTTP_200_OK)

problem is when I got the result of filter in homeimg object, it returns
the field of homepage_id as homepage_id_id which incorrect how can I fix this it should mentioned homepage_id in result of queryset?
Below is the queryset result
<QuerySet [{'id': 1, 'homepage_id_id': 1, 'home_image': 'home_image/edit.png'}]>

it shows homepage_id_id, whereas in model it is defined as homepage_id