Find the co-ordinates of A and B

Question: $P$ is $(2,1)$ and $A$ and $B$ lie on $X$ axis and $y=x$ respectively such that $PA+PB+AB$ is minimum, then find the co-ordinates of $A$ and $B$.
If we consider $A$ to be $(a,0)$ and $B$ to be $(b,b)$ it would become complicated. Is there any other way?
Comment: Why would it become complicated ? You can write $PA+PB+AB$ as a (quadratic) function of $a$ and $b$ and then minimize it.
Comment: Isn't there any other simpler way than these method
Answer: Let $C(1,2)$ and $D(2,-1)$.
Thus, $CD=\sqrt{10}$ and it's gives a minimal value.
Indeed, Let $CD$ intersects a line $y=x$ in the point $B_1$ and the $x$-axis in the point $A_1$.
Thus, $$PA+PB+AB=DA+AB+CB\geq CD=$$
$$=DA_1+A_1B_1+B_1C=PA_1+A_1B_1+PB_1=\sqrt{10}$$
Another way.
By Minkowski
$$PA+PB+AB=\sqrt{(a-2)^2+1^2}+\sqrt{(1-b)^2+(2-b)^2}+\sqrt{(b-a)^2+b^2}\geq$$
$$=\sqrt{a-2+1-b+b-a)^2+(1+2-b+b)^2}=\sqrt{10}.$$
The equality occurs for $a=\frac{5}{3}$ and $b=\frac{5}{4}$, which says that $\sqrt{10}$ is a minimal value.
We have for the minimal sum: $A\left(\frac{5}{3},0\right)$ and $B\left(\frac{5}{4},\frac{5}{4}\right)$.
Answer: hint: with this informations we get
$$f(a,b)=\sqrt{(a-2)^2+1}+\sqrt{(b-2)^2+(b-1)^2}+\sqrt{(b-a)^2+b^2}$$
can you proceed?
$$f_a=1/2\,{\frac {2\,a-4}{\sqrt { \left( a-2 \right) ^{2}+1}}}+1/2\,{\frac
{-2\,b+2\,a}{\sqrt { \left( b-a \right) ^{2}+{b}^{2}}}}
$$
$$f_b=1/2\,{\frac {4\,b-6}{\sqrt { \left( b-2 \right) ^{2}+ \left( b-1
 \right) ^{2}}}}+1/2\,{\frac {4\,b-2\,a}{\sqrt { \left( b-a \right) ^{
2}+{b}^{2}}}}
$$
solve the System $$f_a=0$$ and $$f_b=0$$
Comment: Differentiate and then get the minimum..
Comment: or you look by Michael
Comment: There are 2 variables. How can we differentiate it?
Comment: one Moment, i will send it to you
Comment: yeah this is the same as $$f_a$$ etc isn't it?
Comment: Thank you Dr. Sonnhard Graubner isr
Comment: @Dr. Sonnhard Graubner How can we solve this system? Explain please.
Comment: Groebner basis works?

Find the co-ordinates of A and B


Bandwidth limits for Amazon EC2

Question: I have a micro instance on Amazon EC2 cloud.
Also the instance is small and it has vary low CPU and EAM usage but it
generates a lot of content, so it can be considered like a web server
serving small amount of static files (not of a big size) to many clients.
From the technical point of view there is no problems for such instance to handle the load
serving many MBs per seconds.
What I'm considered is if there are limitation of bandwidth by Amazon itself. Many VPS service providers limit the bandwidths to lets say 10MB/s, are there such limits at Amazon and if they are what are they?
I couldn't find any reference.
Comment: do you mean MB/s or Mb/s? there is a differance ;) MB/s is MegaByte and Mb/s or Mbits/s. usualy MB/s would be used to describe bandwith.
Comment: Sorry typo normally Mb/s
Comment: That link (to AWS source) is for bandwidth between the instance and EBS (Elastic Block Storage) and not to the Internet.
Comment: I suggest that you can work out approximate bandwidth of an instance by getting the ratio of instance CPU to total CPU of the server and relating that to the 40Mbps network throughput. Let's assume E5-2670 v2, same as the M3 instances use. A t2.micro has 10% of 1 core, 20 cores total, gives 1/200th of the server resources to the instance. 40Gbps / 200 = 0.2Gbps, ie 200Mbps, which roughly agrees with the comments in this question.
Answer: Remembered that I had bookmarked a similar post a while back, and Cyberx86 posted an excellent answer with benchmark tests :)
Serverfault answer
Edit
From what I've been able to find on the AWS forums - It doesn't seem like the support people from Amazon want to answer that question. Their advice is to test it with an external source: AWS forum post from 2012
Older posts (post1, post2 refer to transfer speeds in coalition to instance size. The 2nd one mentions that the data was a part of the AWS documentation but later it was replaced with stuff about I/O.

small 250 mbps
large 500 mbps
xlarge 1000 mbps

These numbers seem to fit with the benchmarks you can find on google.
So sadly - I don't think you can find transfer speeds on their site anymore.
Comment: Actually it is very relevant. I just trying to find official resources that define these I/O limits (100Mbs/250Mbs/1Gbs)
Comment: To expand on this answer i believe that the bandwidth limit is related to the IO performance of the instance. You can see the associated IO performance for each instance here http://aws.amazon.com/ec2/instance-types/. The numbers Qlue posted are equal to what I found last year not sure if they've since changed. The micro instance has a different IO performance than the small servers so I assume its less than 250 mbps.
Comment: @GeekRide since the question was regarding transfer speeds and there are no longer any official data from the AWS team. I thought benchmarks and answers from the forums would give the best indication of what one could expect.
Comment: Answer not relevant at all.
Comment: I hope you mean Mbps, not mbps. A millibit per second is not a lot of bandwidth.
Answer: Edit:
After @tomasz notified me, I checked the issue again.
I found a blog where the bandwidths are compared in;
http://epamcloud.blogspot.com.tr/2013/03/testing-amazon-ec2-network-speed.html?m=1
And I think, there is no a certain limit because of the different technical infrastructures by zone and the technology and infrastructure providers continues to improvement day by day.
If EC2 bandwidth limits are wanted to be known, each zone should be handled separately.

Now, there is a list on AWS docs.
The answer from its source;
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-ec2-config.html
Comment: Note these limits are for transfers between EC2 instances and EBS storage.
Answer: You say that the static files being served are not of a big size. The smaller they are, the more you'll be worried about packets per second instead of overall bandwidth on the network.
As with bandwidth, AWS doesn't publish any concrete numbers, only "Low", "Moderate", "High", etc. I ran into some problems with PPS limitations, and it was even less published than bandwidth numbers, so I ran some tests.
Here's what I found for various instance sizes:
t1.micro      8,473
t2.nano       9,807
t2.micro     19,391
t2.small     28,296
t2.medium    47,214
t2.large     49,512
c1.medium   110,575
m3.large    142,839
m1.large    157,557
m4.large    222,280
c4.large    233,450
r3.large    412,315
c3.large    475,996
i3.large    529,558
r4.large    544,981
c5.large    823,806

There was a lot more that I found, too, around guaranteed throughput and best effort PPS (packets per second). I put it into a blog on monitoring packets per second on EC2 where I show graphs and tables better than I can show in a comment.
To tie it back to Amazon's Network Performance Designation ("Low", "Moderate", "High"), you'd probably be shocked to know there's little correlation between actual bandwidth and actual PPS to those designations. They are worthless - only rely on test results, not published categories from AWS.
Answer: You can use this tool inside your instance to get full information about bandwidth:
wget -O speedtest-cli https://raw.github.com/sivel/speedtest-cli/master/speedtest_cli.py
chmod +x speedtest-cli
./speedtest-cli

Output:
Retrieving speedtest.net configuration...
Retrieving speedtest.net server list...
Testing from Amazon (184.108.40.206)...
Selecting best server based on latency...
Hosted by Digiweb (Dublin) [1.78 km]: 3.395 ms
Testing download speed........................................
Download: 171.74 Mbit/s
Testing upload speed..................................................
Upload: 281.61 Mbit/s

Hope it helps
Comment: @ceejayoz, well this is for having an idea about the bandwidth available (not the exact and full informations), it's not stable and we all know that ec2 uses a complex algorithm for distributing cpu & bandwidth based on vm priority, the same thing goes for other cmp (omega from google). Besides you can test the performance of your app when using ec2 and other dedicated solution, that's what we did (testing t2.micro limits). Of course the download speed is not consistent, so we used c4.xlarge for production to increase instance priority and get more consistency
Comment: You'll really want to trust https://github.com/sivel if you're doing this. It's also not necessarily going to tell you enough about the bandwidth available - other instances on the same underlying host may tie up bandwidth, it may be burstable bandwidth, etc.
Answer: It appears that EC2 is offering an Enhanced Networking feature for better network performance:

For supported Amazon EC2 instances, this feature provides higher packet per second (PPS) performance, lower inter-instance latencies, and very low network jitter.

Unfortunately the feature does not seem to be available for the T* instance range:

Currently C3, C4, D2, I3, I2 M4, X1 and R3 instances support Enhanced Networking. X1, P2, I3, R4 and m4.16xlarge instances provide the Elastic Network Adapter (ENA) interface for Enhanced Networking. C3, C4, R3, I2, M4 (except m4.16xlarge) and D2 instances, use Intel® 82599 Virtual Function Interface.
Comment: Enhanced networking separates EBS (network attached disk) bandwidth from network bandwidth. It increases network bandwidth only by moving other traffic to another interface.

Bandwidth limits for Amazon EC2


IIS script privileges with powershell

Question: I've created a script for most of the functions I need when creating a Site for my IIS, however, there is still one thing missing.
Namely, I can't seem to find the commands for setting script privileges on a Site.
I want all script rights but no execution rights if I've understood it correctly.
So, how do you set those privileges through powershell?
Edit:
The answer I was looking for was:
set-webconfigurationproperty -filter /system.webserver/handlers -name accesspolicy -value $flagsPermissions -PSPath $PS_PATH -Location $siteDescription
It works nicely.
Comment: What version of IIS, 6?
Comment: Ah, yes, sorry, 7.
Comment: By default Execute permissions are turned off, so there is not need to change anything when creating a new site. Unless you changed the defaults.
Comment: I might've been unclear.
I want to turn scripts on, not off.

It seperates between scripts and executables in the GUI, and I don't want normal programs executable, jsut scripts.
Answer: A new site on IIS 7+ should have it's handler accessPolicy set to 'Read, Script' so that's exactly what you want, no need for changes.
If you still want to change it:
You could use appcmd.exe from PowerShell:
<code>appcmd set config /section:handlers /accessPolicy:Read,Script
</code>
More info on TechNet
For specific sites this setting is usually set in web.config rather than ApplicationHost.config
Comment: appcmd.exe is not in the path by default. It is in C:\Windows\system32\inetsrv
Comment: Ah, then it seems that someone else have modified the defaults (I've also verified this with a local install), I'll have to check why that is before I make any changes to that. However, appcmd doesn't seem to exist on either of the systems I am working on.
Also, yes, modifying web.config would work fine as well.
Comment: Ah, thanks.
The command partly works, however, only if I enter Read OR Script, otherwhise, the second option is ignored with an error message (In swedish unfortunately).
Also, the thing I'm looking to do is in fact in web.config, just across 82 different sites.
Comment: Two things:
First, thanks, your messages led me to realize what the terms I was actually looking for (handlers, accesspolicy read, script).
Second, that led me to the following line: set-webconfigurationproperty -filter /system.webserver/handlers -name accesspolicy -value $flagsPermissions -PSPath $PS_PATH

Which works wonderfully.

Also, we switched to inherited script privileges as well.

Thanks for the assistance!
Comment: Ah, look, I tried upvoting it, but Accepting was the way to go.

IIS script privileges with powershell


Can I get the relationships of a node using node_load()?

Question: I want to load relationships from the node_load(). So for example  getting the article content type and loading the author information with the same query.
How would I go about doing this?
The end goal is to make a computed field for Drupal Search API so that I can convert the field's name. The relationship fields are currently in the form table_name:field_name but I am indexing into Algolia and therefore need the field name to just be field_name.
Comment: I have not understand what is your end goal. Do you want to index multiple fields as fulltext?
Comment: @milkovsky My end goal is to add fields to a search index. So I need to have relationships within that search index. But the search index (Algolia) breaks when there are colons in the field name that is sent across. So I need to remove them
Comment: You can just index the rendered html
Comment: Could you explain what you mean by that? Is that something that is possible to do in Drupal 7?
Comment: see my answer below.
Answer: As an option you can index the entire rendered HTML of your content.
Let's assume your index is called "default_node_index" and content type is "article".

Visit /admin/config/search/search_api/index/default_node_index/workflow
Enable "Complete entity view"

Visit /admin/config/search/search_api/index/default_node_index/fields
Enable "Entity HTML output".

Manage display of your content type /admin/structure/types/manage/article/display
Enable "Search Index" in "Custom display settings" fieldset.

Visit /admin/structure/types/manage/article/display/search_index
Add all the fields you want to render. You can extend this display using the regulat hooks, templates and preprocesses if needed.


How can I compare rows from 2 tables that have composite primary keys?

Question: Here's the scenario:
I have 2 tables with data, one is the 2009 version and the other is the 2010 version. The primary key for each of the tables is a composite key. I know there is a different number of rows in each one and I need to find out the differences.
Typically, in the "normal" primary key set-up, I would just look for primary key values NOT IN the list of primary keys from the other table. But I don't know how to do this with a composite primary key (or even if it's possible).
So, how can I compare the rows from these two tables?

EDIT: More specifically, I am trying to find the difference between the tables, rather than the rows in common
Answer: Just make a full outer join with condition based on your composite keys:
select t09.*, t10.*
from table2009 as t09
  full outer join table2010 as t10
    on t09.k1 = t10.k1 and t09.k2 = t10.k2 and ...

If you only wish to see unmatched rows (the difference) in result set, then filter them within the where clause:
where t09.k1 is null or t10.k1 is null

Comment: Added that "difference" you were talking about; however, you may want to find only the one side (e.g. the rows in 2010 that do not appear in 2009 table) -- then left join will do the trick.
Answer: select * from [table2009]
right outer join [table2010] on [table2009].[PK1] = [table2010].[PK2] and [table2009].[PK2] = [table2010].[PK2]
where [table2009].[PK1] is null
Answer: You could take a checksum of the composite columns and compare across the tables, in order to make the join a bit more compact.
select ...
--------------------------
--or left outer join etc.
--------------------------
from a inner join b
on checksum(a.col1, a.col2, a.col3) = checksum(b.col1, b.col2, b.col3)

Answer: Assuming you don't want to compare all the columns.
DECLARE @Table2009 TABLE
(  Year  INT
 ,Counter INT  IDENTITY (-2147483647 , 1)
 ,OtherData CHAR(1)
 ,PRIMARY KEY (Year, Counter)
);
DECLARE @Table2010 TABLE
(  Year  INT
 ,Counter INT  IDENTITY (-2147483647 , 1)
 ,OtherData CHAR(1)
 ,PRIMARY KEY (Year, Counter)
);
SELECT 'NOT IN Table2010'
  ,Table2009.Year
  ,Table2009.Counter
FROM  @Table2009 Table2009
LEFT JOIN @Table2010 Table2010 ON Table2009.Year  = Table2010.Year
          AND Table2009.Counter = Table2010.Counter
WHERE Table2010.Year IS NULL
UNION
SELECT 'NOT IN Table2010'
  ,Table2009.Year
  ,Table2009.Counter
FROM  @Table2010 Table2010
LEFT JOIN @Table2009 Table2009 ON Table2010.Year  = Table2009.Year
          AND Table2010.Counter = Table2009.Counter
WHERE Table2009.Year IS NULL;

Answer: Some data to test:
CREATE TABLE Tbl_1 (
  ID1 integer NOT NULL
, ID2 int NOT NULL
, SomeData varchar(20)
);
ALTER TABLE Tbl_1 ADD
    CONSTRAINT pk_tbl_1 PRIMARY KEY (ID1, ID2);

CREATE TABLE Tbl_2 (
  ID1 integer NOT NULL
, ID2 int NOT NULL
, SomeData varchar(20)
);
ALTER TABLE Tbl_2 ADD
    CONSTRAINT pk_tbl_2 PRIMARY KEY (ID1, ID2);

INSERT INTO Tbl_1
 (ID1, ID2, SomeData)
VALUES
  (1, 1, '1_1')
, (2, 2, '2_2')
, (3, 3, '3_3')
;

INSERT INTO Tbl_2
 (ID1, ID2, SomeData)
VALUES
  (1, 1, '1_1')
, (3, 3, '3_3')
, (4, 4, '4_4')
;

...
-- All rows that are in the first table,
-- but not in the second one
SELECT
     a.ID1 AS t1_ID1
    ,a.ID2 AS t1_ID2
    ,a.SomeData AS t1_SomeData
    ,b.ID1 AS t2_ID1
    ,b.ID2 AS t2_ID2
    ,b.SomeData AS t2_SomeData
FROM Tbl_1 as a
LEFT JOIN Tbl_2 as b ON b.ID1 = a.ID1 AND b.ID2 = a.ID2
WHERE b.ID1 IS NULL;

Returns:
t1_ID1  t1_ID2   t1_SomeData   t2_ID1   t2_ID2   t2_SomeData
------- -------- ------------- -------- -------- -----------
2       2        2_2           NULL     NULL     NULL

...
-- All rows that are in the second table,
-- but not in the first one
SELECT
     a.ID1 AS t1_ID1
    ,a.ID2 AS t1_ID2
    ,a.SomeData AS t1_SomeData
    ,b.ID1 AS t2_ID1
    ,b.ID2 AS t2_ID2
    ,b.SomeData AS t2_SomeData
FROM Tbl_1 as a
RIGHT JOIN Tbl_2 as b ON b.ID1 = a.ID1 AND b.ID2 = a.ID2
WHERE a.ID1 IS NULL;

Returns:
t1_ID1  t1_ID2  t1_SomeData   t2_ID1   t2_ID2  t2_SomeData
------- ------- ------------- -------- ------- ------------
NULL    NULL    NULL          4        4       4_4

...
-- Common to both tables
SELECT
     a.ID1 AS t1_ID1
    ,a.ID2 AS t1_ID2
    ,a.SomeData AS t1_SomeData
    ,b.ID1 AS t2_ID1
    ,b.ID2 AS t2_ID2
    ,b.SomeData AS t2_SomeData
FROM Tbl_1 as a
JOIN Tbl_2 as b ON b.ID1 = a.ID1 AND b.ID2 = a.ID2;

Returns
t1_ID1      t1_ID2      t1_SomeData    t2_ID1      t2_ID2     t2_SomeData
----------- ----------- ------------- ----------- ----------- ------------
1           1           1_1           1           1           1_1
3           3           3_3           3           3           3_3

Answer: -- Entity in Tbl_1 only
SELECT ID1, ID2
  FROM Tbl_1
EXCEPT
SELECT ID1, ID2
  FROM Tbl_2;

-- Entity in Tbl_2 only
SELECT ID1, ID2
  FROM Tbl_2
EXCEPT
SELECT ID1, ID2
  FROM Tbl_1;

-- Entity in both tables
-- with same attribute values
SELECT ID1, ID2, SomeData
  FROM Tbl_1
INTERSECT
SELECT ID1, ID2, SomeData
  FROM Tbl_2;

-- Entity in both tables but
-- with different attribute values
SELECT DISTINCT T1.ID1, T1.ID2,
       T1.SomeData AS Tbl_1__SomeData,
       T2.SomeData AS Tbl_2__SomeData
  FROM Tbl_1 AS T1, Tbl_2 AS T2
 WHERE T1.ID1 = T1.ID1
       AND T1.ID2 = T2.ID2
       AND T1.SomeData <> T2.SomeData;

Answer: i used like this! with just an left outer join.
and i used another field to check the state
SELECT * FROM actas LEFT OUTER JOIN acta_detalle_proceso on actas.id = acta_detalle_proceso.id
and actas.tipo_acta_id =  acta_detalle_proceso.tipo_acta_id and acta_detalle_proceso.estado = 1
WHERE acta_detalle_proceso.id IS NULL and acta_detalle_proceso.tipo_acta_id IS NULL  ;


Como arrendondar para a dezena mais próxima?

Question: Como posso fazer para arredondar um número para a dezena mais próxima em JavaScript?
Por exemplo:
O usuário digita 11, aí arredondaria para 20; o usuário digita 11.5, arredondaria para 20; e assim por diante.
Answer: function arredonda(n) {
    return n % 10 ? n + 10 - n % 10 : n;
}

ou
function arredonda(n) {
    return Math.ceil(n / 10) * 10;
}

Pelo que eu entendi, se n = 10, deve retornar 10; se n = 11, deve retornar 20.
Answer: Em geral, usa-se os métodos ceil (teto) e floor (piso) para arredondar para o inteiro mais próximo, mas como você quer arredondar na direção de uma grandeza diferente (no caso uma dezena) é preciso fazer alguma adaptação:
function teto(numero, arredondarPara) {
    if ( !arredondarPara ) arredondarPara = 1;
    return Math.ceil(numero / arredondarPara) * arredondarPara;
}

function piso(numero, arredondarPara) {
    if ( !arredondarPara ) arredondarPara = 1;
    return Math.floor(numero / arredondarPara) * arredondarPara;
}

teto(7.2); // 8
teto(7.2, 10); // 10

teto(7.2, 0.1); // 7.2
teto(7.2, 2); // 8
teto(7.2, 3); // 9
teto(7.2, 4); // 8
teto(7.2, 5); // 10
teto(7.2, 6); // 12
...

Answer: Tente assim:
function aproxima(valor) {
    if(valor%10 == 0) return valor;
    var round = Math.ceil(valor);
    while(round%10 != 0) round++;
    return round;
}

Comment: Vou testar e já retorno
Comment: Como faria para pegar o menor valor mais próximo? Exemplo: valor = 5 e pegar o número 1?
Answer: Com essa função ele vai pegar a primeira maior dezena
function arredonda(x){
while (aux < x){
aux= aux+10;
};
aux= aux - x + 10;
return aux + x;

e esta próxima função irá arredondar para a dezena mais próxima
function arredonda_mais_perto(x){
while (aux < x){
aux= aux+10;
};
aux= aux - x + 10;
if (aux > 5)
return aux + x;
else
return aux - x;

Comment: `arredonda(99999999)` será um pouco lento, não? Além do mais seria bom limitar o escopo do `aux`, o declarando local.


Eventstore UnknownError: Could not recognize BadRequest

Question: I'm currently using Eventstore, and I'm receiving the following error:  Could not recognize BadRequest;
from:
game process tick failed UnknownError: Could not recognize BadRequest
    at unpackToCommandError (\node_modules\@eventstore\db-client\dist\streams\appendToStream\unpackError.js:53:12)
    at ClientDuplexStreamImpl.<anonymous> (\node_modules\@eventstore\db-client\dist\streams\appendToStream\batchAppend.js:38:66)

For some reason, it seems like it is something with my handler:
async function   gameProcessPush(channel,event) {
    console.log("pushing:",event);
    try {
        console.log("trying to append..:",event);

           await client.appendToStream("factory",[event]);
           console.log("appending to stream");
        } catch(e) {
            console.log("game process tick failed",e);
            throw  {live: false, code: 26, event: event}
        }
        console.log("game processing...");

}

What am I doing wrong here?
rest of debug code:
processing factory failed {
  live: false,
  code: 26,
  event: { type: 'factory-creation', sub: 'sub-factory', userid: 1 }
}
result in :  undefined

Full code:
import { streamNameFilter } from "@eventstore/db-client";
import { createSecureServer } from "http2";
import { runMain } from "module";
import { eventNames, mainModule } from "process";
import { arrayBuffer } from "stream/consumers";
import { SubscriptionInfo } from "./generated/persistent_pb";
import { AllStreamPosition } from "./generated/shared_pb";

const {EventStoreDBClient, FORWARDS, StreamNotFoundError, jsonEvent, START, END, excludeSystemEvents, eventTypeFilter} = require("@eventstore/db-client");

  const client = new EventStoreDBClient({
    endpoint: "localhost:2113",
}, {
    insecure: true,
});

    interface creationFactory {
        userid: string,
        location: [number,number,number],
        name: string
        type: string,
    }

class Factory {

    public async create(creation : creationFactory) {
        console.log("creating new factory.....",creation);
        const NewFactoryEvent = CreateEvent("factory-creation",{userid: 1, sub: "sub-factory"})
        try {
            console.log("creating newfac",NewFactoryEvent);
            await gameProcessPush("factory",NewFactoryEvent)
        } catch(error) {
            console.log("processing factory failed",error);
        }
    }

}

function CreateEvent(type,data) {
    return  {type: type, sub: data.sub,
        userid: data.userid,

    }
}

async function   gameProcessPush(channel,event) {
    console.log("pushing:",event);
    try {
        console.log("trying to append..:",event);

           await client.appendToStream("factory",[event]);
           console.log("appending to stream");
        } catch(e) {
            console.log("game process tick failed",e);
            throw  {live: false, code: 26, event: event}
        }
        console.log("game processing...");

}

//new Factory().create({userid: "1", location: [1,1,1], name: "test bank", type: "BANK"});
async function test() {
    try {
       await  new Factory().create({
            userid: "1",
            location: [0,0,0],
            name: "test",
            type: "factory",
        });

    } catch(e) {
        console.log("factory creation faileD");
    }
}

test().catch((e) => {console.log("test failed",e)}).then(function (data) {
console.log("result in : ",data);
});

Answer: Context
EventData
An EventStore event must be a EventData object, that has, at least, two properties:

type, basically a string that defines the event's type.
data, that is the payload and must be a byte array, usually a JSON, serialized object.

appendToStream
EventStore appendToStream usage:
await client.appendToStream(STREAM_NAME, event);

Related docs

Creating an event
Appending events

Issues
There are two potential issues in your code:

You are trying to append an Array as event ([event]), instead of a EventData object.
The event structure does not correspond with an EventData object, as reflected by your debug log and your CreateEvent method.

Possible solution
Process your input event to create a valid EventData object and then append it:
async function gameProcessPush(channel, event) {
  try {
    const eventData = jsonEvent({
      type: event.type,
      data: {
        sub: event.sub,
        userid: event.userid,
      },
    });
    await client.appendToStream("factory", eventData);
  } catch (e) {
    throw { live: false, code: 26, event: event };
  }
}

Answer: I am sure you've read the documentation of EventStore.
Refer if you missed something - https://developers.eventstore.com/clients/grpc/#appending-events
Try changing [event] to event
async function   gameProcessPush(channel,event) {
    console.log("pushing:",event);
    try {
        console.log("trying to append..:",event);

           await client.appendToStream("factory",event);
           console.log("appending to stream");
        } catch(e) {
            console.log("game process tick failed",e);
            throw  {live: false, code: 26, event: event}
        }
        console.log("game processing...");

}

See if it works


Elevator Timing Problem

Question: "Suppose a building has 15 floors. A person works on the 11th floor of this building. The elevator travels endlessly between all floors (1,2,3,..., 14,15,14,...,3,2,1) instead of stopping on a floor where the button has been pressed. Assume that the amount of time required to load and unload passengers is minimal compared to the actual trip time. The person always wonders why, when he is about to leave his office at 6 p.m., the lift goes up before stopping at his floor most of the time. Provide a valid explanation for this phenomenon in terms of probability."
This question arrived on my university quiz, and I am unsure if my answer was correct.
What I did was
Probability Distribution Table taking Random Variable X
I took a Probability Distribution table where I compared all the values for P(x<11) and P(x>11) while taking the whole of Time period, T = the whole time of elevator passing from floor 1 to back to floor 1.

N.P: Sorry my last question here did not mention how I approached it. This
is my first post here so I didn't know how this site worked.
Comment: The lift goes down before reaching the person's floor only if it is at floors greater than $12$ at that given time. You can quickly check that the elevator spends most of its time below the $11$th floor.
Answer: You're on the right track but you need to consider that the elevator doesn't magically reappear at $1$ after it has gone to $15$. So if you think about which sequence of numbers will be repeated forever it looks like this:
$$1,2,3,...,13,14,15,14,13,...,3,2$$
Note that it does not end in $1$ because now you can copy that sequence and attach it to the end to continue the sequence. So the numbers $2$ to $14$ show up twice as often as $1$ and $15$. What does the distribution look like then? And what do $P(X>11)$ and $P(X<11)$ look like?

Elevator Timing Problem


View com duas ou mais tabelas sem vinculo, com colunas diferente e que precisam ser mescladas

Question: Tenho duas tabelas,"PRIMEIRATABELA" com os campos nome, sobrenome, e idade, outra tabela "SEGUNDATABELA" com os campos name, last_name, e age as duas tabelas não possui vinculo mas preciso juntar em uma view sendo que por exemplo  PRIMEIRATABELA.nome e SEGUNDATABELA.name teria que fica em uma mesma coluna na view como VIEWTABELA.nomefinal igualmente com os outros campos. sem view com full outer join resolveria meu problema parcialmente.
Answer: Como fazer
Você pode fazer usando a função UNION, assim unindo os resultados das 2 tabelas, e usando como subquery:
SELECT * FROM (
  (SELECT nome as nomefinal, sobrenome, idade FROM primeiratabela)
UNION ALL
  (SELECT name as nomefinal, last_name as sobrenome, age as idade FROM segundatabela)
) tabX
ORDER BY nomefinal

Complementando
Na função UNION, você terá que ter os mesmos campos nas querys, mesmo que seja NULL.
Exemplo: em uma tabelaA tenho o campoX e não tenho o campoY. Já na tabelaB, não tenho o campoX e tenho o campoY.
Posso unir em colunas diferentes:
SELECT * FROM (
  (SELECT campoX, NULL FROM tabelaA)
UNION ALL
  (SELECT NULL, campoY FROM tabelaB)
) tab_aux

Ou na mesma coluna, como fiz no seu caso, utilizando alias:
SELECT * FROM (
  (SELECT campoX as campoU FROM tabelaA)
UNION ALL
  (SELECT campoY as campoU FROM tabelaB)
) tab_aux

Mais sobre a função UNION.
Comment: Era exatamente disso que estava precisando, Obrigado @rbz !


Somar as variáveis com o campo data iguais se possivel editando a coluna data

Question: Tenho as seguintes variáveis:
$v_data   = $row['DATA'];
$v_filial = $row['FILIAL'];
$v_chapa  = $row['CHAPA'];
$v_func   = $row['FUNCIONARIO'];
$v_dias   = $row['DIAS'];
$v_desc   = $row['DESCRICAO'];

Elas trazem isso:
DATA      FILIAL CHAPA  FUNCIONARIO    DIAS  DESCRICAO
10-04-2016  2    2311   JOAO DE SOUZA   7    TESTE
24-04-2016  2    2311   JOAO DE SOUZA   14   TESTE
08-05-2016  2    2311   JOAO DE SOUZA   14   TESTE
15-05-2016  2    2311   JOAO DE SOUZA   7    TESTE
05-06-2016  2    2311   JOAO DE SOUZA   21   TESTE
12-06-2016  2    2311   JOAO DE SOUZA   7    TESTE

O que preciso:
 Onde as datas forem iguais somar a coluna dias e se possivel alterar a coluna data, exemplo:
DATA      FILIAL CHAPA  FUNCIONARIO    DIAS  DESCRICAO
10-04-2016  2    2311   JOAO DE SOUZA   7    TESTE
24-04-2016  2    2311   JOAO DE SOUZA   14   TESTE

Resultado esperado:
DATA      FILIAL CHAPA  FUNCIONARIO    DIAS  DESCRICAO
  04         2    2311   JOAO DE SOUZA   21   TESTE

@Marllon Nasser, segue query:
SELECT
       ifd_filial                  AS FILIAL,
       ifd_chapa                   AS CHAPA,
       ifd_nome                    AS NOME,
       DATE_FORMAT(ifd_dataa,'%m') AS MÊS,
       SUM(ifd_dias)               AS DIAS,
       ifd_desc                    AS DESCRICAO
       FROM
            imp_folga_domingo
            WHERE ifd_chapa = 2311
            GROUP BY ifd_dataa;

Comment: @VirgilioNovic Mês
Comment: @VirgilioNovic para mim o PHP seria melhor,mais como preciso liberar fiz com a ajuda de vocês em sql mesmo.
Comment: qual o banco? oracle?
Comment: Banco: SQL SERVER Mais gostaria de se possivel fazer em PHP por conta de outras condições que terei de fazer .
Comment: Bom, você tem que fazer um `group by` pelo mês da data... e fazer uma soma de `DIAS`. É isso que você precisa fazer..eu recomendo fazer pela query.. por php infelizmente eu não sei fazer isso. Mas a solução é essa.
Comment: @MarllonNasser trouxe para o MYSQL fiz a query mais não esta somando,poderia verificar se minha sintaxe esta correta ? Adicionei a mesma a pergunta .
Comment: @otaciojb somar se as datas forem igual ou se o mês da data for igual?
Comment: Vi o que estava errado pela pergunta de @Virgílio.
Comment: @otaciojb Faltou o `group by` na data... `GROUP BY DATE_FORMAT(ifd_dataa,'%m');`
Comment: @MarllonNasser isso mesmo, vlw..
Comment: Entendi !!! você quer uma solução `SQL` que o @MarllonNasser parece que já resolveu, o você quer um solução `PHP` ???
Answer: Segue resultado final:
 SELECT
       ifd_filial                  AS FILIAL,
       ifd_chapa                   AS CHAPA,
       ifd_nome                    AS NOME,
       DATE_FORMAT(ifd_dataa,'%m') AS MÊS,
       SUM(ifd_dias)               AS DIAS,
       ifd_desc                    AS DESCRICAO
       FROM
            imp_folga_domingo
            WHERE  ifd_chapa = 2311
                   GROUP BY DATE_FORMAT(ifd_dataa,'%m');


why DNNClassifier doesn't accept Sparse features, but LinearClassifier does

Question: tf.estimator.DNNClassifier doesn't accept sparse feature columns such as categorical_column_with_hash_bucket. It can only accept dense columns which always needed to be wrapped with indicator_column.
category_column = tf.feature_column.categorical_column_with_hash_bucket(key, hash_size)
tf.feature_column.indicator_column(category_column)

tf.estimator.LinearClassifier on the other hand can accept categorical_column_with_hash_bucket directly.
tf.feature_column.categorical_column_with_hash_bucket(key, hash_size)

According to this tf source code
Sparse features can be fed directly into linear models. They behave like an indicator column but with an efficient implementation.
I wonder what such efficient implementation is there in Linear as against DNN which restricts DNN to only accept dense columns.
Answer: Linear classifiers and other "shallow models" are picky about sourts of inputs that they can accept. categorical_column_with_hash_bucket is a hacky way of squeezing an variable size input or a enormous sparse vector into a nice fixed size numeric representation.
In DNN terms we therefore should take a look at 2 cases to replace categorical_column_with_hash_bucket. One for strings and one for sparse vectors.
In case of strings we can project a string into fixed size representation using an embedding layer. It allows a reacher, higher dimensional representation and, most of all, it is trainable. Embedding can be trained along with the main part of network.
When it comes to sparse vectors things become tricky. First of all, DNNs don't shine when it comes to low dimensional data and sparse vectors typically have very little information (low entropy). Because of that sparse data can be easily overfit by a DNN that has millions of parameters. Nevertheless, you can still try using embedding layer for your case. Otherwise, stick to linear models - they are much more robust and adopted to sparse vectors.


Where can I get the source code for MVC4

Question: I would like to look into the way bundling is implemented. It seems like there is default bundling as my MVC project knows all about adding in javascripts that I don't have and never explicitly included.
Comment: I believe Microsoft's still not open source this. You can find out in http://aspnetwebstack.codeplex.com/. There is no namespace with name System.Web.Optimization
Answer: I believe it's at: http://aspnetwebstack.codeplex.com/
Answer: Bundle is simply logical group of files that could be referenced by unique name and being loaded with one HTTP request. Two things that will help you use these new features, are RegisterTemplateBundles() and EnableDefaultBundles().
Bundling of scripts is a new feature in MVC 4, to learn more about it take a look at New in ASP.NET MVC4: Bundling and Minification and Yet Another Bundling Approach for MVC 4
The purpose of bundling and minification is to help increase the performance of your Websites by reducing the number and size of HTTP Requests to the server.
If you want code examples you can find walk-troughs and source examples in Visual Studio's Nuget package manager. There are many other sources, comment if you want me to add more.


How to find all users by name?

Question: const author = mongoose.Schema(
  name: String,
 );
const listName = ["a","b","c","k"];

I have an array of names. How to find all user names?
Comment: What did you try already?
Answer: You can use $in operator.
author.find({ "name": { "$in": listName } },function(err,docs) {
      // code
});

How to find all users by name?


If n is a positive integer that is not square free

Question: Determine if the statement is, in general, true or false. Recall that a
universal statement is true if it is true for all possible cases while it is false if there is even one counterexample. Be prepared to prove that your answer is correct by supplying a proof or counterexample, whichever is appropriate.
If $n$ is a positive integer that is not square free then there are integers $a$ and $b$ such that $a\ne b\pmod n$. But so that $a^k\equiv b^k\pmod n$ for all $k>1$.

Solution:
Since $n$ is not a square free integer then $n=k(m^2)$.  Now, $a^k\equiv b^k\pmod n$ and $a^k\equiv b^k\pmod{m^2}$.  Thus, it is not necessary that $a\ne b\pmod n$.  Hence, if $n$ is a positive integer that is not square free then there are integers $a$ and $b$ such that $a\ne b\pmod n$.  But so that $a^k\equiv b^k\pmod n$ for all $k>1$.
Could you check it for me please?  Is it correct or not?
Answer: "Thus it is not necessary that ..." is not a compelling argument. I suggest you exhibit explicitly $a=m$, $b=0$ and show that $a^k\equiv 0\equiv b^k\pmod{m^2}$ (and so also $a^k\equiv b^k\pmod n$) for all $k>1$. And of course we have $a\not\equiv b\pmod n$ (as $n\ge m^2>m>0$).


ios read content from private network address

Question: I need to read a file that come for example:
<code>\\192.168.0.1\Folder\Readme.txt
</code>
how can I read this file from my app into the iPhone
Comment: I wish made the same thing like in windows you open a \\ip path
Answer: I think in this case you can use a library like ASIHTTP. Link
It should be possible to download the file into a NSString object, and then store this object into a file.
<code>[nsStringObject writeToFile:pathToFile atomically:YES encoding:stringEncoding error:errorHandler];
</code>
Comment: ASIHTTP is well... HTTP library, he needs to access his file via SMB protocol.
Answer: <code>NSString *pathToTextFile;
NSError  *readError;
NSString *fileData = [NSString stringWithContentsOfFile:pathToTextFile
                               encoding:NSUTF8StringEncoding
                               error:*readError]

 NSLog(@"here is your file as string = %@",fileData);
</code>
Comment: simply this? and the pathToTextFile will be \\192.168.0.1\Folder\Readme.txt ??
Comment: Give it a try ;)
smb://server-name/folder-name/document.
I assume in your case : smb://192.168.0.1/Folder/Readme.txt

But as other stated, I am not sure iOS support SMB directly. how about putting it on your local webserver (Apache or alike)
Answer: As you suggest in your question, you need to access your file over SMB protocol (samba or windows share). I don't think iOS supports smb out of the box, however, i stumbled across tango library on github some time ago. The library claims to be a SMB/CIFS implementation for iOS, so i guess you might give it a try.


Intuitive probability inequality

Question: $X$ and $Y$ are two continuous i.i.d random variables. They are both symmetric about zero.
How do I prove the intuitive inequality:
$P(\ |X+Y| < 2|X|\ \big | \ XY<0 \ ) > 0.5$
I know that $P(XY < 0) = 0.5$, I tried finding $P(\ |X+Y| < 2|X|\ and \ XY<0 \ )$ by integrating the probability density functions but I didn't get very far. I feel like I am missing something obvious.
Comment: Divide it into two cases: $X>0, Y<0$ and $X<0, Y>0$.
Comment: I tried that, how does it help?
Comment: How about drawing a graph?
Comment: A related problem: https://math.stackexchange.com/questions/2772072/confused-by-a-solution-given-by-professor
Answer: As mentioned in comments, there are two main cases depending on the signs of $X$ and $Y.$
Try just one case to start with, for example $X > 0, Y < 0.$
That is, consider values of $X$ and $Y$ only in the fourth quadrant.
In the fourth quadrant, plot the region of points $(x,y)$ for which
$\lvert x + y \rvert < 2\lvert x\rvert.$
Since $x > 0$ in this quadrant, the formula to plot can be simplified to
$\lvert x + y \rvert < 2x.$
You can deal with the remaining absolute value by subdividing into additional cases, $x + y < 0$ and $x + y > 0.$
The region in the other quadrant should then be relatively easy to plot.
In fact you can plot it immediately by symmetry.
Now you have a region in the plane over which to integrate the joint distribution $f(x,y) = f(x)f(y).$
When you look at a plot of this region it should be relatively obvious
how to subdivide it into one region of total probability $\frac14$
and another region whose probability you can show is positive.
(Note: I say "obvious" only because I have looked at the plot;
it wasn't obvious to me at all from the problem statement itself.)

Intuitive probability inequality


Is 5/4 simple or compound?

Question: I have seen 3 major ways of subdividing the quarter notes in 5/4. 1 is treating it as a simple meter and 2 others treat it as an irregular compound(or technically speaking, complex) meter. I have seen these interpretations in 2 main contexts, conducting an orchestra and music theory. I myself, when I see 5/4 always treat it the same way regardless of tempo. Of course, I can oblige by composers who used 5/4 as 2+3 or 3+2 by placing dynamic accents on the first note of each 2 or 3 note subdivision. But in my own compositions, I don't abide by the 2+3 or 3+2 that everybody else does when I use 5/4. I only use the irregular compound that everybody else uses for 7/4 and higher prime time signatures.
Simple Quintuple Meter
This is the interpretation I use in my own compositions when I use 5/4 is that 5/4 is a Simple Quintuple Meter. I mean, it makes sense right? 5 beats per bar, that is pretty easy to count, and isn't it ease of counting that makes 2/4, 3/4, and 4/4 all simple meters, even though in theory, the 4/4 could be subdivided into 2+2? 6/4 is when you really start needing to subdivide the bars into larger beats than the time signature. But 5/4 is easy to count as individual quarter notes, no need for subdivision.

1 2 3 4 5 | 1 2 3 4 5 | 1 2 3 4 5 | 1 2 3 4 5 |

This here is an example of a conducting gesture in 5 beats:

I see this used mainly for slow movements in 5/4 because at faster tempos it is hard to conduct in this 5 beat pattern. So for fast movements in 5/4, conductors generally will use a pattern of 2/4 3/4 2/4 3/4 or 3/4 2/4 3/4 2/4 depending on which beats the composer wanted to be accented beats. But for a solo pianist like me, counting in groups of 5 at a fast tempo is no problem.
Irregular Compound Meter(or complex meter)
This is the 2+3 and 3+2 that I have mentioned before. This has its merits, mainly for conductors, because the conductor doesn't have to use a 5 beat pattern which is difficult to do at fast tempos. But, if 5/4 is treated as an irregular compound meter, how would you know which accent pattern the composer wanted, whether it was 2+3 or 3+2? What if there are a lot of short notes in a given bar, making it hard to see the accents? Some composers have left the accents ambiguous, some have emphasized the accented beats with dynamic accents to make it clear, and others decomposed the 5/4 into 2/4 + 3/4 and used multiple time signature changes or a dual time signature to make it absolutely clear what interpretation the composer was going for.
So, given that 5/4 can be interpreted either as a Simple Quintuple Meter or as an Irregular Compound Meter and that each one has its merits, how should 5/4 be classified? As a simple meter? As an irregular compound meter?
Comment: This is a nice, informative discussion, but I think you basically answer your own question. Depending on the tempo and the "feel," one can interpret 5/4 as composed of 5 (slow) primary beats, or as 2 (fast) beats with a 2+3 or 3+2. It's not one or the other: it varies based on all the issues you bring up. (And I would note that your conducting pattern has a bias too: it's a 2+3 conducting pattern. To conduct 3+2, you'd usually have two small swings toward the center, with "beat 4" swinging outward to indicate the stronger beat.)
Comment: Exotic meters like this are typically explained in the score, since the composer can't rely on everybody to have the same piece with same accent pattern in mind. Our band currently plays a piece in 10/8 and there is a clear indication, that this is intended to be subgrouped to 3/3/2/2, so the conductor gives 2 slower and 2 faster beats. In general I find the simple/compound distinction not very helpful and there are no well-established terms for it in some languages.
Comment: @Caters - Sure, I was just pointing out that typically a five pattern ends up being grouped into a 2 and 3 in some order, and the standard conducting patterns do that, even if you try to make all five beats "equal." It wasn't a criticism; merely an observation. You see it in 4/4, where most people can't help feeling a grouping of 2+2, rather than just one strong downbeat. As Tim's answer notes, the human bias is to group 5 (or any number bigger than 3) into 2s and 3s, and the conducting patterns reflect that.
Comment: Even within a single piece in *the same measure*, a piece in 5/4 time can get subdivided differently. I've played the concert band piece "Heartbeat Five" by Gary P. Gilroy, and in at least one measure where I as a bass clarinet player play in a 3-3-2-2 rhythmic pattern, the trumpets play 5 straight quarter notes.
Comment: @guidot - what tickles me is when the band is rehearsing  in a piece with time changes, and we look at the place where a change from, say, 4 to 3 has happened. We need to start on the 3 bar, so he counts us in with '1 2 3 4'..!
Comment: @Athanasius That difference in the 2+3 and 3+2 patterns is why I said in the question only that it is a conducting pattern in 5 beats and didn't get any more specific than that.
Answer: Does it need classification? Why does everything have to be pigeon-holed?
5/4 (and 5/8 for that matter) is generally split into a more manageable 2 and 3, or 3 and 2. Not very often is it counted as a simple 5 with no sub pulse. That may be because humans are happier with basic counts of 2s and 3s. After all, most of our (Western) music falls into that category. we often count 1 2 3 4, and 1 2 3 4 5 6 in well used timings. So 2s and 3s seem natural.
If 5/4 was to be counted 1 2 3 4 5 1 etc, then it would be filed under 'simple'. If not, as is more common, it'd be 'compound'. Same would go for 7/4 as often counted as 1 2 1 2 1 2 3, (or other 2s and 3s combinations) - rarely as 1 2 3 4 5 6 7.
Comment: Nail on head.  This is a great example of a question, of which there are many here at this forum, about how to define something, or how to classify some musical practice, where the answer can only be a matter of convention, since it adds nothing to the understanding of what's going on.  And while it's important to establish agreed-upon nomenclature, it's more important to realize that it's very often- and not only in music- simply pigeonholing, just convienience and not informative.
Answer: Regardless of how the notes in 5/4 are grouped, I believe 5/4 is a simple meter because its quarter notes are divided into 8th-note duplets. A quintuple-meter respective compound meter is 15/8, with 5 dotted-quarter-note beats made of 8th-note triplets.
Comment: I think you misunderstood the OP's meaning of simple/compound, and I get your meaning. In Brazilian Portuguese, AFAIK, "simple" is when tempo is divided always in two parts, and "coumpound", when divided in three or more. But OP's question isn't about that.
Comment: This was my first thought, but then the question discussion goes off in a different direction not about simple/compound!
Answer: Time signatures do not directly correlate to metre; 9/8 can be compound triple or an irregular quadruple metre, depending on where the main pulses are. It is inaccurate to refer to time signatures as "being" simple or compound, these are adjectives which describe metre, not time signatures.
Of course, the overwhelming majority of the time, 9/8 is compound triple; you could argue that 9/8 is so strongly associated with compound triple that it practically "is" compound triple. But it would be very difficult to substantiate a similar claim about 5/4 being so strongly associated with one particular metre.
Comment: But how often do you see 9/8 as 4/4 + 1 eighth note? Much rarer than as a triplet version of 3/4, I would imagine.
Comment: @Caters Very rarely indeed, and perhaps in the case of 9/8 this is mere pedantry; you could say that 9/8 is so strongly associated with compound triple that it practically "is" compound triple. But it would be difficult to substantiate a similar claim about 5/4 being so strongly associated with one particular metre.
Answer: It COULD be Simple Quintuple.  Not very likely, but it could.  The only example of this I can think of is at the end of Stravinsky's 'Firebird' where a 7/4 is simply hammered out with no 2 or 3-groups.  (OK, 7 not 5.  But same idea.)
But 5/4 (or 7/4) more usually falls into 2+3 or 3+2 groups.  A simple beat and a compound one.   I expect there's a name for this.
Note that 4/4 doesn't HAVE to be 'simple quadruple'.  That's not a useful description of a Latin tune with consistent 3+3+2 8th note groupings.
We're not in the 19th century any more. Can't always pin down the identity of a time signature without looking at what it DOES.
Answer: Simple.
The top number isn't a multiple of 3.
But the body of your question doesn't seem to be about simple vs. compound. It seems to be about wanting a category beyond duple, triple, and everything else being some additive meter. At least you seem to hint at that. A non-additive, quintuple meter of strong, weak, weak, weak, weak. Maybe simple, non-additive quintuple?
But categorizing it that way doesn't seem nearly as important as notating so the accents are clear, because 3+2 & 3+2 seem to be the convention.
Answer: Perhaps the easiest way to think about meters - 5/4 or any other - is, that there "is no meter".
If you haven't downvoted already and you are still with me let me explain: music happens in a "pulse" - the thing a metronome would give you. tack - tack - tack - tack - .... What makes a "meter" from that endless stream of identical strokes is that some pulses are emphasized and some are not. Instead of

tack - tack - tack - tack - tack - tack - tack - tack -

we now have (for instance, 4/4)

tick - tack - tack - tack - tick - tack - tack - tack -

or maybe (3/4)

tick - tack - tack - tick - tack - tack - tick - tack - tack

and so on. We call it a "meter" if that happens in a recurring pattern. In 4/4 we have a basic pattern of 4 strokes where the first is strongly emphasized, the 3 is less but still a little emphasized and 2 and 4 are not emphasized. In 3/4 we have an emphasis on 1 and no emphasis on 2 and 3. These meters can change within a piece (see for instance Leo Brouwers "Estudios Sencillos, Nr. 4", where the meter constantly changes between 3/4 and 2/4).
Now, to answer your question: for common meters like 4/4 there are common patterns (as described above) established (and by "established" I mean: we are very much used to them), but even these are not the only ones used. Non-standard patterns of emphasized strokes exist (called "syncopations") and are equally used. For instance, a "normal" 8-stroke pattern:

tick - tack - tack - tack - tick - tack - tack - tack

and Samba:

tick - tack - tack - tick - tack - tack - tick - tack

And while the "basic" 7/8 meter puts emphasis on 1 and 5 or on 1, 3, 5 and 7, Dave Brubeck put it on 2, 4, 6 and 7 in "Unsquare Dance" for the clapping in the intro part. I'd call this a syncopation because the 1-stroke in every meter is usually emphasized, but in a stricter sense there is only a repeating pattern of emphasized and non-emphsized strokes. As the Free-Jazz-guys (i.e. Jack DeJohnette) called it: "pulse".
The upshot of all this is: "meter" can be anything you want. If you want to have a "simple" 5/4 meter of:

tick - tack - tack - tack - tack - tick - tack - tack - tack - tack

then go ahead and do so. If you want a constant change of 2/4 and 3/4 (a "compound" 5/4) then do that instead:

tick - tack - tick - tack - tack - tick - tack - tick - tack - tack
tick - tack - tack - tick - tack - tick - tack - tack - tick - tack

After all: music is what is pleasing to the ears. All the theory only tries to find rules which describe how to make intelligent tries to find something pleasing. But every time we think we have all covered in the rules1) someone comes and finds an exception, which, according to the rules, shouldn't sound good, but still does. Duh!

1) See "Gradus ad parnassum" - some of the things Chopin did shouldn't have worked - still, they did. That doesn't mean that Johann J. Fux did bad work - just, that Chopin knew all the well-sounding harmonies  Fux knew and then some. Just like todays composers know what Chopin knew - and some more.
Answer: Simple VS Compound simply refers to whether what is considered a beat in the time signature has a dot or not.
Seeing as both 5 time and 7 time has beats without dots it would be simple time. If you want to do compound 5 and 7 time then you would be going into the spheres of experimental music.
If you do experiment in compound five time then that is a youtube video worth making. (If it has not been done already)

Is 5/4 simple or compound?


Disease forecasting - counts or rates?

Question: I'm developing a forecasting model for an infectious disease for a hospital and wanting to understand if I should use disease counts or rates (based on population or total clinic visits). What are the implications of using one approach over another (besides practical considerations, such as having an accurate population estimate)?
Any suggestions on literature would be greatly appreciated!
Answer: I've been pondering this question myself a lot recently, especially in the context of hospital epidemiology. My thoughts below:
The Case for Counts:
The real core of the strength for counts is that they're a more meaningful number on a practical scale. Tell a nurse they're going to see 0.20 cases/patient-day more infections and they'll give you an odd look. Tell them they're going to see 17 more cases this month? That's a meaningful number for them to work off of.
This ties into a general undercurrent in Epidemiology at the moment focusing on an interest in absolute numbers, because our currently reliance on relative effect measures does some funny things, including exaggerating small effects at times. For example, if your rate doubles is that a crisis? Probably depends on if the counts are 1 and 2, 100 and 200 or 100,000 and 200,000.
The Case for Rates: That being said, there's a reason people like rates. Counts only really make sense if your denominator is fixed, or relatively so. For example, if your clinic sees 1,000 patients each month, then a change in cases from Month X to Month X+1 is a genuine change in cases. But if you saw 1,200 the second month? Are your increase in cases an increase, or just having more opportunity to see cases? Or in the case of hospital acquired infections, if you had more patients staying for more time in a given month, you had more opportunities to get them sick, and should probably adjust for that.
So the answer I think, sadly, is it depends. If you're confident that your denominator is stable, and each time point represents the same "opportunity" to see cases, you can probably get away with cases. But if it moves around, and one time point has more patients, staying for more time, etc. then you should probably use rates, unless you don't think you can get a good denominator.
And on a practical note, clinicians are trained, in my experience, to expect rates. If you want to publish or distribute your count-based findings, expect some push-back.
Comment: +1 for the nice description. But, when the denominators of the rates are about the same, then modeling the counts and modeling the rates are effectively equivalent, right? When they are not the same, as you mentioned, it seems hard to justify modeling the counts unless, for example, you use an offset for the population size in a regression model (in which case you're effectively back to modeling the rates). Doesn't this seem to indicate that modeling the rates is always better?
Comment: @Macro I'd assert that for the situation you've given - wherein the denominator/exposure is stable and modeling counts and modeling rates are effectively equivalent, then the modeling of *counts* is preferable due to the superior ease of interpretation.
Comment: Yes, but the statistical modeling results (re: the inference, effect estimates, etc.) would be exactly the same, it would just be a matter of scaling up the results by whatever the denominator was. So, I guess I should modify that to say "Doesn't this seem to indicate that modeling the rates is never worse?".
Comment: @Macro In a theoretical sense, yes. In a practical sense - having just done this - collecting the necessary data to *construct* denominators (even ones known to be stable) at the same level of granularity as counts is often a great deal of work. Beyond that, even if the modeling component is essentially equivalent, you'll likely have to make an argument for why you're *presenting* counts rather than rates. Hence the focus on interpretability.
Comment: I assumed the original poster was describing a situation where you had a choice between 'rate' and 'count', indicating you knew the population size - in that case it seems you can't go wrong with 'rate'. In the context where you don't know the population size, clearly I agree you have to model the counts. Hopefully, in that case, you can rationally argue that the population size is constant, so you're just modeling a scalar multiple of the 'rate' and all of statistical inference is unaffected by the missing information.

Disease forecasting - counts or rates?


Avoid combining products in cart

Question: With Drupal 8 / Drupal Commerce 2, I can't find a way to disable product combining in cart (same products in cart appears on the same line with quantity > 1). In my use case I never want this to happen.
I found that in
/modules/contrib/commerce/modules/cart/src/Form/AddToCartForm.php

...we have a submitForm method which calls
$this->cartManager->addOrderItem($cart, $order_item, $form_state->get(['settings', 'combine']);

So it seems like my form needs to have a combine variable set to FALSE.
How could I set this variable or override
public function addOrderItem(OrderInterface $cart, OrderItemInterface $order_item, $combine = TRUE, $save_cart = TRUE);

...in
/modules/contrib/commerce/modules/cart/src/CartManagerInterface.php

...to define the default value of $combine to FALSE ?
Thanks
Answer: I could achieve this by implementing hook_form_alter on add to cart form (in a custom module) and setting combine like this :
$form_state->set(['settings', 'combine'], FALSE);

Answer: Edge-case, but if you're adding items to the cart programmatically from a custom form, here's what I found to have worked.
$cart_manager = \Drupal::service('commerce_cart.cart_manager');

$line_item = $cart_manager->addEntity($cart, $variationobj, $quantity, FALSE, TRUE);

This will call addEntity() and set Combined to FALSE.

Avoid combining products in cart


Finding the integral of $e^{\cos t} \sin 2t$

Question: I am suppose to make a substitution and then solve by parts but I can't seem to do anything with it that makes sense.
$$\int e^{\cos t}\sin 2t\,dt$$
I rewrote as $2e^{\cos t}\sin t\cos t$ and attempted to use u substitution but I end up with
$-2 \int e^{\cos t}{\cos t\,dt}$ and from here I do not know what to do, nothing seems to improve the problem
Comment: @Jordan: [press here "show steps"](http://www.wolframalpha.com/input/?i=int+e%5E%28cos%28t%29%29sin%282t%29dt)
Comment: @Jordan: don't forget to upvote/accept answers that you like, and to follow up with comments if you're stuck
Answer: HINTS

$\sin(2t) = 2\cos t \sin t$
$\frac{d}{dt} \cos t = - \sin t$
$\displaystyle \int xe^x dx$ is an integral that can be done by parts
Answer: You could use the substitution $u=\cos(t) \implies du = -\sin(t) dt$ and then write the integral as: $$2\int{\sin(t)\cos(t)e^{\cos(t)} dt}.$$
We then end up with the following expression to evaluate:
$$-2\int{ue^{u} du}$$
This is trivial to evaluate using integration by parts:
$$2\int{e^{u}du-2ue^{u}} = 2e^{u}-2ue^{u}+c_1$$
We can now back-substitute to get:
$$2e^{\cos(t)}-2\cos(t)e^{\cos(t)}+c_1$$
Which can be simplified to give:
$$-2e^{\cos(t)}(\cos(t)-1)+c_1$$
Hope this helps.


Synchronisation between office365 and local Active Directory via Custom field

Question: I'm trying co connect local Active Directory to office365 for usersync.
In this documentation i have found that i need make resolvable suffix in userPrincipalName and move legacy Kerberos principal to combination of sAMAccoutName+@Realm
The problem is that many of kerberized software has used older documentation from Microsoft for usage of userPrincipalName.
So some Services and Sevice Users have symbols in userPrincipalName that are not supported in sAMAccoutName
For example by hadoop services:
email@example.com

And sAMAccountName looks like:
sAMAccountName=$XXXXXX-XXXXXXXXXXXX

If I enable legacy Kerberos principal my tickets are not working for services with unsupported symbols.
Example:
[hive@host ~]$ klist
Ticket cache: FILE:/tmp/krb5cc_1234
Default principal: $email@example.com

Is it possible to create in Active Directory field like userPrincipalNameForOffice365 for user synchronization?
Answer: Yes, you can use other fields - but you have to add them manually in your synchronization job. The ADSync assistant will only allow certain fields (like SMTPProxyAdress).
More about alternate IDs: https://docs.microsoft.com/de-de/azure/active-directory/hybrid/plan-connect-userprincipalname
You could even use AFDS to let AzureAD authenticate directly against your local domain (using alternate IDs): https://docs.microsoft.com/en-us/windows-server/identity/ad-fs/operations/configuring-alternate-login-id
Hope this helps. The whole answer would be hard to cover in one SF post.


How reload form values with ajax

Question: So I'm trying to do something really simple but haven't manage to know how to do it with the Ajax API form from drupal 7. I have an administrative GUI with a select input type, I set the #ajax property with the callback but I don't want to replace anything just need to reload/refresh the values for specific inputs most of them textfield, when the selection change.
Any insight on how to do this? Can it be done with the Ajax Drupal 7 API?
Thanks....
Comment: Maybe [this][1] will help.

  [1]: http://drupal.stackexchange.com/questions/3875/form-element-default-value-and-ajax
Answer: You should put a wrapper around the fields of which you want to reload/refresh (basically replace) and in the call back return the either the form values in an array or the wrapper.
This basically means that on the event specified in the callback, eg change the whole wrapper div is swapped out and replaced with a new one built by the php in your form.
Comment: can you add more details?
Comment: @user7282 - Look inside [Examples](https://www.drupal.org/project/examples) module, there you get what you want. Look for the Form API Examples. There's at least one Ajax example.

How reload form values with ajax


Ordering returned data from a function

Question: I have a function which takes 2 parameters; a dict- _tInput, and a list- _order.
The aim is to be able to order the returned data for printing:
tOrderReq = [1, 4, 5, 2]
tReturnData = tOut(hInput[0], (tOrderReq))
print("%s %s %s %s" % tReturnData)

However I am getting the following error:
Traceback (most recent call last):
File "C:\local\mdev.py", line 76, in <module>
TypeError: not enough arguments for format string

I don't understand what I need to change to get this to work, I suspect it is something fairly basic that is showing through with my novice Python knowledge and my understanding of tuples, lists and dicts. The function is below-- incidentally, if there are any tips on how to improve this code, then i'm all ears.
def tOut(_tInput, _order=[]):
    _tOutput = []
    _tOutput.append(_tInput['id'])
    _tOutput.append(_tInput['created_at'].encode('utf-8'))
    _tOutput.append(_tInput['text'].encode('utf-8'))
    _tOutput.append(_tInput['user']['id'])
    _tOutput.append(_tInput['user']['screen_name'].encode('utf-8'))
    _tOutput.append(_tInput['user']['name'].encode('utf-8'))

    _tReturn = []
        for x in _order:
        _tReturn.append(_tOutput[x])

    return (_tReturn)

Many thanks
Comment: Did you perchance call it with `tOut(hInput[0], [tOrderReq])` instead? What is the *full* traceback?
Comment: I didn't say to use that instead, I was trying to hazard a guess as to why you see your exception, because you didn't provide us with enough information. What is the full traceback?
Comment: You didn't provide the **full** traceback, only the last two lines. A full traceback starts with the line *Traceback (most recent call last):*.
Comment: If it is [tOrderReq] instead, the error is : TypeError: not enough arguments for format string. The traceback is as I pasted above
Comment: Unrelated, but: as a rule, don't use mutable default arguments like `_order=[]`.  They'll get you into trouble sooner or later (see [here](http://stackoverflow.com/questions/1132941/least-astonishment-in-python-which-scope-is-the-mutable-default-argument-in) for the details.)
Comment: Martijn, I've updated the main post-- it seems I had a cut&paste error, so I'd given a different error, the correct one is now there. Thanks for looking!
Comment: I apologise, my mistake was most likely pointing you in the wrong direction, the answer below was simply to have tuple(tReturnData). But I do appreciate the help you offered!
Answer: IIUC, your problem is that Python needs a tuple with %-interpolation:
>>> tReturnData = [1,2,3,4]
>>> print("%s %s %s %s" % tReturnData)
Traceback (most recent call last):
  File "<ipython-input-13-a0f54ded128d>", line 1, in <module>
    print("%s %s %s %s" % tReturnData)
TypeError: not enough arguments for format string

>>> print("%s %s %s %s" % tuple(tReturnData))
1 2 3 4

If (as it seems you are) you're using Python 3, you could simply write
>>> print(*tReturnData)
1 2 3 4

or use str.format (which is the preferred modern style for finer control, which admittedly we're not using here):
>>> print("{} {} {} {}".format(*tReturnData))
1 2 3 4

Comment: Thank you, it was tuple(tReturnData) that was the fix-- incidentally, I am using 2.7.6, is there something that i've written that is more of a Python3 standard?
Comment: @Oli: the use of parentheses with `print` is more common in 3 as `print` is now a function and so needs them.

Ordering returned data from a function


R: Can you make my ugly text concacting function pretty

Question: I am trying to write a function what makes R interpret arguments without evaluating them and pushes them into a new string.
This is what I have so far.  It is very ugly but works for up to 5:
pl <- pasteliteral <-
function(v1='',v2='',v3='',v4='',v5='', sep="") {

 stopifnot(v1!="")

 # Sort up to 10 values
 if (deparse(substitute(v1)!=""))  {s<-deparse(substitute(v1))
 if (deparse(substitute(v2)!=""))  {s<-paste(s, deparse(substitute(v2)), sep=sep)
 if (deparse(substitute(v3)!=""))  {s<-paste(s, deparse(substitute(v3)), sep=sep)
 if (deparse(substitute(v4)!=""))  {s<-paste(s, deparse(substitute(v4)), sep=sep)
 if (deparse(substitute(v5)!=""))  {s<-paste(s, deparse(substitute(v5)), sep=sep)
 }}}}}
 s
}

pl(1,2,3,a,hello)
[1] "123ahello"

Comment: You could collect your arguments with `as.list(substitute(list(1,2,3,a,hello)))[-1]` and then `lapply` `deparse` and `do.call` `paste`.
Comment: And I know there is no possible usage for this function except once I have it I will modify it to check each argument which is a character to see if it exists and if it does I will paste them together.
Answer: You can try sys.call:
pl <- pasteliteral <- function(..., sep="") {
  ## remove first element (the function name)
  ca <- sys.call()[-1]

  ## remove last element if it is sep
  if (ca[[length(ca)]] == sep) {
    ca <- ca[-length(ca)]
  }
  paste0(ca, collapse=sep)
}

pl(1,2,3,a,hello)
# [1] "123ahello"

pl(1,2,3,a,hello, sep=":")
# [1] "1:2:3:a:hello"

Comment: This is really helpful.  Is there any chance you could show me how to make the `ca` "language" object into a vector now?
Comment: @fsmart: Do you mean e.g. `as.character(ca)`?


Have I been compromised?

Question:
Possible Duplicate:
My server's been hacked EMERGENCY

Looking thru my logs, I found this:
http://paste.u4ik.us/2294$
(The log files are on that paste).
Question is, this guy began using "all requests allowed" which is...? (Explain it please?) and eventually was making requests from "127.0.0.1" which means he's using my local system?
If anyone can explain this, or help prevent it, I'd like to know, and this would be highly appreciated.
Thanks!
PS: I've since blocked their IP, but what's stopping this from happening again?
Comment: A search on 'allrequestsallowed' yielded this: http://askubuntu.com/questions/52649/allrequestsallowed-com-hack-attempt
Comment: @mqs - Mmm, thanks, I read that already. But that site seems shady. The IP 184.108.40.206 of the "Attacker" is from Russia, AND WHEN VIEWING it as a website, it asks for credentials (http//22.214.171.124/) so, it's really got me thinking.
Comment: @U4iK_HaZe I believe it was some kind of adsl/cable modem/router asking for management password - this setup is quite common in Russia.
Comment: A cable modem running an Apache server?
Comment: @synet - The server is going through a firewall, then through an outside proxy server. (Webservers through an Apache proxy to firewall then to the public). And since this morning, there are MANY more of these entries in the logs. http://paste.u4ik.us/2169
Answer: Don't panic. As a general advice, before reading logs and trying to get some security-related meaning out of them, be sure to have a sufficiently thorough understanding of what it does mean. Otherwise you end up with a heart attack over too many "dangerously looking" log entries.
What you see is simply Internet background noise - someone trying to pick on your configuration for possible weaknesses. Such "attacks" are usually simply blind attempts to exploit configuration problems or implementation bugs, most of them without any effect. There is absolutely no way to prevent this.
The 127.0.0.1 log entry you see in your original log paste is an entry which has been induced by your own system - most probably not on the behalf of the attacker but through your own actions.

Have I been compromised?


JSF 2, EL Expression, Weblogic, and EJB injection

Question: Well, the problem is this. I've built a Java EE 5 application and was running in Weblogic 10.3.4. I have to add an EJB-Client application that is included as a provided dependency in my EE Application.
Since I've added that dependency I get the following error:
<code>There was a failure in application ServletContext@1850878[app:my_app-ear module:/my_app-web path:/my_app-web spec-version:2.5]
when attempting to inject dependencies into
com.mycompany.bean.ReportBean. Dependencies will not be injected into
this class. com.bea.core.repackaged.springframework.beans.factory.BeanCreationException:
Dependency injection failure: can't find the bean definition about class
interface com.mycompany.service.ReportFacadeLocal; nested exception is
com.bea.core.repackaged.springframework.beans.factory.NoSuchBeanDefinitionException:
No unique bean of type [com.mycompany.service.ReportFacadeLocal] is
defined: No beans of type com.mycompany.service.ReportFacadeLocal;
owner=com.bea.core.repackaged.springframework.context.support.GenericApplicationContext
@6b4c9c: display name [com.bea.core.repackaged.springframework.context.support.GenericApplicationContext@6b4c9c];
startup date [Tue Oct 29 23:38:23 CST 2013]; parent:
com.bea.core.repackaged.springframework.context.support.GenericApplicationContext@1107db9 at
com.bea.core.repackaged.springframework.jee.inject.Jsr250Metadata.applyInjections(Jsr250Metadata.java:244) at
com.bea.core.repackaged.springframework.jee.inject.Jsr250Metadata.inject(Jsr250Metadata.java:226)
</code>
I don't know what's happening, since I'm not using Spring, the only from Spring thing I use is the dependency com.springsource.org.jboss.el, is this library attached in any way to Spring? Is there something else I need to do?
From now, thank you.
EDIT
What I needed to do is to add a name in each bean to force the jndi look up, and that was it.
Answer: It looks like you may have not defined an interface of com.mycompany.service.ReportFacadeLocal but have implemented it (or it could be the other way round, depending on names). Does the concrete class exist with the interface using the same name (or otherwise explicitly configured)?
Comment: Actually I have defined it. About the configuration, I've just annotated the class, it is needed to add some xml configuration?
Comment: @Omar You should just need to define it with annotations, '@Stateless' generally. In some builds you might need to define it in ejb-jar.xml instead. You should have the client defined using  though.
Comment: Ok. Do you have documentation on that regard?
Comment: The answer here basically covers the purpose of it (and it isn't essential if you have @Local/@Remote annotations), but not sure where otherwise to point you. [Link](http://stackoverflow.com/questions/3484063/using-the-client-jar-in-ejb-3-and-design-patterns)


Centering elements in space remaining after placing another element

Question: In my android app, I have a toolbar with an ImageView and two spinners. I would like the ImageView to appear flush with the left side of the screen, and the two spinners to be evenly spaced, horizontally centered in the remaining space (not horizontally centered on the screen, but horizontally centered in the space remaining after the ImageView is placed. What's the best way to achieve this?
Answer: <RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >
    <ImageView
        android:id="@+id\img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true" >
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id\img"
        android:orientation="vertical"
        android:layout_gravity="center_horizontal" >
        <Spinner
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <Spinner
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>
</RelativeLayout>

The relative layout fixes the relative positions of the image and spinners (as a group).  The Linear layout sets the spinners and centers them within the layout horizontally by setting the layout gravity.
I'm assuming you want them one on top of the other.  If you want them side by side, change the orientation.


Solve $y' + \frac1y + \frac1x =0$ Differential Equation

Question: Do you have any suggestions for how to sole this differential equation?
$y'+\frac1x + \frac1y =0$
? :)
I tried solving this by changing variable in the form of $v=x^\alpha*y^\beta$ but it didn't work!
Do you have any other ideas?! :)
Comment: Welcome to Mathematics Stack Exchange! I would suggest you to explain a little bit how you tried to solve it, so other people could help you better. Good luck!
Answer: $y'+\dfrac{1}{x}+\dfrac{1}{y}=0$
$y\dfrac{dy}{dx}+\dfrac{y}{x}=-1$
This belongs to an Abel equation of the second kind.
Let $x=e^{-t}$ ,
Then $\dfrac{dy}{dx}=\dfrac{\dfrac{dy}{dt}}{\dfrac{dx}{dt}}=\dfrac{\dfrac{dy}{dt}}{-e^{-t}}=-e^t\dfrac{dy}{dt}$
$\therefore-e^ty\dfrac{dy}{dt}+e^ty=-1$
$y\dfrac{dy}{dt}-y=e^{-t}$
This belongs to an Abel equation of the second kind in the canonical form.
Please follow the method in https://arxiv.org/ftp/arxiv/papers/1503/1503.05929.pdf


set up way of getting mysite.$domain

Question: I have several domains, only one website and one databse table for each domain.
example: wbesite.us - data from USA goes to database table main_usa
wbesite.co.uk - data form UK goes to database table main_uk
Only have one database with name of the website. Having only one website structured and having variables like this:
$sql="select * from main_".$countrycode." where bla..bla...

and many other variables to catch the domain extension, and so on...
Now, instead of having one full website for each domain, how can set a script and wher do I put it in order to detect the domain that the user uses.
In my server root do I create something like website.$domain?
Something like website OLX but for different purposes.
I hope I made myself clear.
Thank you.
Answer: You could use the $_SERVER['SERVER_NAME'] global and somehow parse it, to get the country code.
I didn't try it, but something like this should work:
$servername_array = explode('.', $_SERVER['SERVER_NAME']);
$country_code = array_pop($servername_array);
That way, $country_code will be com, uk, or whatever is after the last dot in the domain name.
Comment: Ok thaks. But were do I right it? In the index.php? If so, wich name of the folder that has the website called? Will be in the server root? usualy the folders were the website are has the name of the website with the extension like website.us or website.co.uk I hope you follow me. thanks
Comment: If you really only need one website, I would place it in one of the folders, for example website.us. The other domains could point to this one, too, this way if you need to change anything, you only have to do it on one file. Read up on .htaccess files. I don't know the file system of your site, but you could put my code in a function, then include it in every file where you need the country code.
Comment: Good idea. I will follow your tip. Iwill let you know if it works. Thanks a lot

set up way of getting mysite.$domain


Biased and Efficient estimators

Question: Is unbiasedness a necessary condition for an estimator to be efficient?
For example, if $\hat {\theta}= \frac{\sum_i^n X_i}{3}$, I assume $\hat {\theta}$ can't be efficient in a Cramer-Rao lower bound context because $E[\hat {\theta}]= \frac {\theta}{3}$.
Answer: Clearly not.
A possible way to compare two estimators is to use Mean Squared Error :
$\begin{align*}
MSE = Bias^2 + Variance
\end{align*}$.
There are some biased estimators with very good variances, this being better choices than some other unbiased estimators with awfullly high variances.
See this blog post for an illustration in Python.
Answer: Efficiency can be looked at in two different ways. Many times efficiency is reserved for estimators that are unbiased to begin with. In that case, if it achieves the Cramer-Rao lower bound, it is considered efficient.
The other interpretation of efficiency is from a relative perspective. That is, the relative efficiency of two estimators can be compared. In that situation, it is not reserved only for unbiased estimators. Both bias and variance are taken into account. The Mean Squared Error (MSE) is one risk function of many used to compare the relative efficiency of two estimators.

Biased and Efficient estimators


How to limit entity reference for new nodes only?

Question: In an institutional website, there's an archive section listing all events (content type: Event). Each event is coordinated by an event manager (content type: Event Manager). CT Event has an entityreference field to select an Event Manager. The available options are defined by an entityreference view. This process works well so far.
Next, I needed to limit the available managers depending on their status. The status is a simple boolean field in the CT Event Manager defining if that manager is still active or retired. This limitation also works such as new events can't be assigned to retired managers.
However, if I want to edit an (old) event which was managed by a now retired manager, I can't save the node since the reference is not valid anymore.
My question is, how can I restrict the number of available managers for new events but still maintain the relations between old events and retired managers?
Answer: You need to render views in the Entity Reference field.

Add a reference type display in a view.
Add a nid and title field in the view.
A list of views will be displayed in the field configuration. Select specific view in field's configuration.

Edit:
May be adding hook_form_alter to form can do the trick for you.
function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'your_node_form') {
    // $form['#node'] if it is node edit form.
    // $form['reference_field']['#options'] = $altered_list
  }
}

Comment: That's what I did, see my question: "The available options are defined by an entityreference view." - My question is how to limit the view for new entries only. I want to keep old (already stored) relationships even when editing old events.
Comment: I dont think if its possible without altering the form.
Comment: Checkout my updated answer.
Comment: I was hoping to achieve that without adding code. I will take a look into form altering although I don't really want to alter the form. I would think, I just need to alter the validation criteria, sth like `if (manager == retired && node[manager] == updated_node[manager]) { let it pass; }`.
Comment: I don't think if there is any solution other than custom code. If you just want to validate you can simply use `hook_node_validate`.
Answer: It can be done with a few short lines of code if you are prepared to write a custom module for it.
First, you need to alter your Entity Reference View. Add a Contextual filter of your boolean field that indicates whether the manager is active or not. Set it to 'Display all results for the specified field' WHEN THE FILTER VALUE IS NOT AVAILABLE.
Now note the machine name and display_id of your view, then create a custom module, and add these lines to it:
function MODULE_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == "VIEW_MACHINE_NAME" && $display_id == "DISPLAY_ID") {
    $node = menu_get_object();
    if (!$node) {
      $args[] = 1;
    }
  }
}

What happens here is that we are checking if we are on a node page and have an existing node object. If we do, we assign an argument of '1' to the view, which is boolean yes, and the view subsequently only displays active managers. If we do not have a node object, then we are in the process of creating a new node, so we leave the argument empty, and the view has been set to then display all nodes.
Comment: Interesting approach. I will see if I can fit that into the system.
Comment: Due to some other projects this got delayed but now I finally got around to try this approach. And it actually works. Kind of. Instead `menu_get_object()`(which returns nothing since the _current_ object is the view) I used `menu_get_item()`. This array has another sub-array called `page_arguments` which includes the nid for existing nodes (edit mode) or is "NULL" for new nodes (add). - Very nice and sleek solution!


Sports odds explanation for NFL

Question: I'm looking at sports odds at for the first time and am a little confused.
I understands that if ATS (against the spread) is negative, then the home team is predicted to win. Also, SP (spread) predicts the total point value difference.
However, I'm looking at the favorites column in a spreadsheet and I see "Home Favorite," "Away Dog," "Away Favorite," and "Home Dog" as options.
Doesn't "Home Favorite" = "Away Dog"?
Also, what exactly is the definition of ATS vs SP?
Answer: Against the Spread tells you how a team plays against the spread - so if you gave them their spread points for each game, what would their record then be?  For example (made up numbers):
Week 1: CHI -3 vs BUF.  Actual result: BUF by 5.  ATS loss.
Week 2: CHI +5 vs SF.   Actual result: CHI by 4.  ATS win.
Week 3: CHI +4 vs NE.  Actual result: NE by 2.  ATS win.

So here CHI is 1-2, but is 2-1 against the spread.  The SP itself is the spread for that game, the ATS is their overall record for past games when adding in the spread.  ATS doesn't really say anything about the current game, unless you believe a team's ATS record is indicative of future performance (hint: it's not in most cases*).
So you'd see something like:
Week 4: CHI @ ATL, SP: CHI -3, ATS: CHI 2-1, ATL 0-3.

That means Atlanta is a Home Dog, Chicago has a favorable record against the spread while Atlanta consistently underperforms (they might win games, but by less than they're expected to, and they lose by more than expected), and Chicago is favored to win this game by 3 points.
Home Favorite means a team favored to win (spread < 0) and playing at home.  So yes, a team that is a home favorite, their opponent would be an away dog.  This is important to some bettors because some teams overperform at home.
In football betting, being at home is commonly worth around a field goal - so a home team favored by 3 points would be essentially a 0 spread (pick'em) at a neutral site.
*In some cases, teams are consistently given slightly unfavorable odds and spreads, because they're known to have a lot of betting in their favor - the Yankees, Cubs, Patriots, etc.  They might underperform against the spread as a result slightly.  However, I wouldn't assume this as a general rule.  There's a ton of literature available on things like this if you're interested, but it's way beyond a SE answer.
Comment: Sorry -- still a little confused. Consider week 2. The odds makers say chicago has to win by at least 5. However it only wins by 4. So doesn't that mean it didn't "win"? It was 1 short of what it needed in order to win the bet? So wouldn't that be an ATS loss?
Comment: Week 2, Chicago has to _lose_ by 5 or less (or win).  +5 means "add 5 to Chicago's score, then re-evaluate the winner."  In that case SF was favored to win.
Comment: Ah, so for week 1, it's like BUF actually won by 8?
Comment: @user1357015 Exactly.
Comment: Ok, that's one thing figured out. Is the ATS always for the home team?
Comment: ATS should be listed for both teams, but I don't know for your particular site.
Comment: Gotcha, I think I have this almost figured out. Last question: "the ATS is their overall record for past games when adding in the spread". Does that mean the spreads are somehow added together to get the ATS?
Comment: No, it's on a game by game basis.  Each game is evaluated 'did they win when the spread is added for this game?'  It could indicate that the oddsmakers tend to favor them (or disfavor them), though like I said before it's really mostly just garbage intended to make people think they know what they're doing when they really don't.
Comment: That's what I thought ... when I ran the numbers on my data set I basically got my predictor to be right 50% of the time. It was a machine learning algorithm that predicted the outcome based on ATS, Spread, etc.. Given what you said that seems to validate my method :-).

Sports odds explanation for NFL


How to prove $W_t-tW_1$ is Markov?

Question: For a Brownian motion $W_t$, how do we prove the bridge process $W_t-tW_1$ is Markov? Essentially, we need to prove for $s< t$,
\begin{align}
\mathbb{P}(W_t-tW_1\in x\mid \mathcal{F}_s)=\mathbb{P}(W_t-tW_1\in x\mid W_s)
\end{align}
I understand I need to use $W_t-W_s$ being independent of $\mathcal{F}_s$, but how to use that for proving the above statement?
Comment: This follows because $X_t:=W_t-tW_1$, like $W_t$,  is a Gaussian process, whose covariance $E[X_sX_s]=s(1-t)$ ($0\leq s\leq t\leq 1$) factors into a function of $s$ and a function of $t$. You may need to review how to compute conditional distributions for a Gaussian process.
Answer: The Brownian bridge is a Markov process because it is an Itô process. In particular, we may use Itô's formula to check that $Y_t = W_t - tW_1$ satisfies the following SDE: $$dY_t = - \frac{Y_t}{1-t}dt + dB_t$$
Comment: I get from Ito's formula - $dY_t=dW_t-W_1+0.5dt$, how to get to your equation from there?

How to prove $W_t-tW_1$ is Markov?


Cannot set Java breakpoint in Intellij IDEA

Question: I'm trying to put breakpoints into the GoogleAppEngine sources (SDK 1.7.0) but IDEA Ultimate (11.0.2) just keeps telling me Warning: No executable code found at line 482 in class com.google.appengine.api.memcache.AsyncMemcacheServiceImpl.
I get this error message both when I run the code from unit tests and when I start up the development server.
It's quite annoying. Anyway, my sources are in an external (relative to both the IDEA home and the project home) directory, and my jar files are under the App engine SDK lib dir.
My jar files are added as a project library to the module, and my sources are attached to this library. I was playing around with module dependencies as well, but without any luck. Finally, I decided to put this library into Compile scope, but that was a bad idea since the SDK provides these jars at runtime, so I decided to fall back to Provided scope.
I also played with the export checkbox on the module dependencies tab, but I think this is irrelevant, according to the web help, export is only important when you have dependent modules and you want to make your library available in these modules as well.
Anyway, this question arose 4 years ago also. So I'm wondering now whether it is really so hard to solve this issue?
I'm very disappointed now. I hadn't had any problems with IDEA so far...I saw that this problem arose to other people as well, so this is not unique I guess.
Any help is appreciated.

I edited my question due to my javap experiments below: It seems that the classes and the sources are NOT out of sync. I checked out the 1.7.0 related revision from SVN, and I'm using the 1.7.0 SDK, so these should not be out of sync at all.
Answer: I had similar problems and various attempts has been applied. Below is my usual steps:

If you are using Maven dependencies, go to Maven Projects -> refresh
If that does not work, Try top menu --> Build --> Rebuild Project
If that still doesn't work, try top menu --> File --> Invalidate Cache/Restart
If that still doesn't work, then $CATALINA_BASE/bin/catalina.sh stop, then start

After this, usually it covers 99% of the problems. Otherwise, Probably you will have to examine some other possibilities.
Comment: Terminate the server from the task manager solved it in my case. Seems that intellij can't always terminate my server successfully
Comment: I tried all the steps from Intellilj, but it didn't work. Finally, I tried running -> mvn clean install from the command line and it fixed the problem
Comment: is there a way to invalidate caches without deleting the local history?
Comment: Rebuilding worked
Comment: I had a similar problem, issue was my source code was changed w.r.t jar deployed, so it was showing this error when I reverted back everything was fine
Answer: I had faced similar problem while debugging in intellij. I wasn't able to put breakpoint at one of the code snippet, then i changed the line number of the code and after that i was able to put breakpoint. Looks like a bug in intellij or some caching issue.
Comment: I have exactly the same situation :(
When I change the line I can put the breakpoint!
Answer: I found some other cases where people reported that IDEA says "No executable code found".  A common pattern is that they were trying to debug code that has been built without debug information.  Check that you are compiling with the "-g" flag (or equivalent) set.  Use javap to see if there is debug information in the .class file(s).
Comment: This didn't work for me. In fact, I have NEVER used the "-g" flag in IDEA and most of the times I was able to debug my code.
Comment: Hmmm.... That sounds logical... :) I'll try to figure out how was it built, but since I'm not the one who compiled the code (it's Google) I don't really know how shall I do that. Any suggestions on this?
Comment: OK... I just found your other answer related to how to see whether debug information is available... You're really a helpful guy! :) I'll give it a try.
Comment: So. I tried the `javap -v` command which successfully disassembled the class. Now what I see just assured my previous suspicion. The disassembled file says `LineNumberTable: line 481: 0` which is exactly the line number of the method header where I put my breakpoint in (I put it on the next line). So it seems that the class and the source is in sync (which is not a big surprise anyway).
Comment: @async and others, clearly there are multiple possible causes for this problem.  If my suggestion doesn't help, try some of the other suggestions.
Answer: I was able to fix this problem by recompiling the class in question:
Build - > Recompile (filename.java)
Comment: This resolved my problem. I was using another maven project containing the code I wanted to debug as a dependency for my main Spring project. Since the code that needs to be debugged isn't executing directly, but rather as a dependency for another project that does, this was causing some issues with the debugging. After recompiling the java file with my breakpoints, it was running as expected without having to restart the main project again!
Comment: This option is not available in Android Studio (2021.3).
Answer: I had same issue. I don't know why, but for me helped to add any modification in code, such as adding or removing comment. Strange, but it resolved my issue
Answer: The question is rather old but I thought my experience might help someone in the future. In my case I was trying to debug code that was not compiled with debug information. I am using maven in which the original parent pom file before modification looked something like below in the build section.
<build>
    <pluginManagement>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.1</version>
            <configuration>
              <target>${javaCompilerVersion}</target>
              <source>${javaCompilerVersion}</source>
              <encoding>UTF-8</encoding>
            </configuration>
        </plugin>

     </pluginManagement>
</build>

I changed the above section to make it look like below.
<build>
    <pluginManagement>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.1</version>
            <configuration>
              <target>${javaCompilerVersion}</target>
              <source>${javaCompilerVersion}</source>
              <encoding>UTF-8</encoding>
              <debug>true</debug>
              <debuglevel>lines,vars,source</debuglevel>
            </configuration>
        </plugin>

     </pluginManagement>
</build>

Note the added <debug> and <debuglevel> elements. debuglevel element can take any combination of the three arguments separated by commas.
After compiling with this change I finally managed to put break points in IDEA.
Answer: The essence of the problem is that the JVM executes a class file (either simple class or a class loaded from jar from the class path) which DOES NOT MATCH the source being used by debugger.
Once this is understood, the solution is simple: make sure that the source represents the class being executed.
So, to fix the problem you can refresh-synchronize sources to classes, etc.
Answer: Menu --> File --> Invalidate Cache/Restart
This worked for me under IntelliJ 13.0.2
Comment: This fixed it for me.
Answer: I had a similar problem and it was caused by a mistake in my Tomcat configuration, under the Deployment tab, the "Deploy at the server startup".  I had accidentally changed it to a very similar project with ":war exploded".  When I changed it back, it worked fine.
Answer: Had same issue, figured out that the version of code on the server and the one I'm debugging are different. After synching the code the issue was resolved.
Answer: In my case i was debugging remotely, found out that the version of code on the remote server and Intellij was not in sync. I re-build the latest code locally, placed the same change on remote server and it worked for me.
You can try out few more possible solutions that could be specific to your problems suggested by JetBrains.
Impossible to debug "Warning: no executable code found at line."
Answer: Please, make sure you have not run Proguard. It helped me.
Comment: This looks more like a comment.
Answer: If you are using some servers they will go into "low memory mode", that means they will not debug for you, no matter what options or caches you invalidate.
You should stop your server, increase the memory settings on the options that are passed to java and restart your server. Check logs to ensure you don't get a report such as "running in low memory mode".
Answer: In my case I killed all running processes on the device and disconnected and reconnected it.
Answer: I had the same issue using debug configuration in my case Tomcat.
I tried all above, but nothing.
when I just reconfigured the Tomcat (debug > edit configuration > remove the tomcat > add it again from scratch) it was finally working :)
Answer: Check your disc space and free up some memory. If you are running low on disc space, even if your server is not on "low memory mode", intelliJ would not allocate the space to cache the classes required for debugging. As a result it won't allow you to set the break-point.
Answer: I was working on an Intellij Plugin and when the sandbox Intellij popped up, what finally fixed my issue was, once the sandbox intellij popped up, I rebuilt from there.
After that I built both my Intellij and the sandbox Intellij and they synced finally.
Answer: Simply by stopping the debugging process and reinitiating it. In my case, simple as that.