text:
Q: Select ID from costumers that do not have contacts last 7 days and 2 times in the month I have 2 tables: custumer, c_contact.
c_contact is all the e-mails I send to my custumers.
From now on I need to put a new rule that the costumer can't receive a new e-mail if:
1) It received an e-mail in the last 7 days
2) Have 2 or more e-mails sent in the current month
I thought something like that:
SELECT *
from costumer c inner join c_contact cc on cc.ID = c.ID
WHERE ID not in (select ID
                 from c_contact c1
                 where c1.ID = cc.ID
                   and c1.CONTDATE >= getdate()-7)
  AND ID not in (select count(ID)
                 from c_contact
                 where MONTH(contdate) = MONTH(getdate())
                   and YEAR(contdate) = YEAR(getdate())
                 HAVING count(ID) >= 2)

But the table c_contact is huge and it taking ages to run this.
Is there a way to do these 2 conditions in 1 "ID not in"? I thing it will run a lot faster.

A: These are the customers that have not received an e-mail in the last 7 days AND have received less than two e-mails this month:
SELECT *
FROM customer AS c
WHERE c.ID NOT IN (
    SELECT ID        --- the customer ID
    FROM c_contact
    WHERE contdate>=DATEADD(day, -31, SYSDATETIME()) -- for optimization
    GROUP BY ID
    HAVING MAX(contdate)>=DATEADD(day, -7, SYSDATETIME()) OR
           SUM((CASE WHEN contdate>=DATEFROMPARTS(
               YEAR(SYSDATETIME()),
               MONTH(SYSDATETIME()),
               1) THEN 1 ELSE 0 END))>=2);

Conversely, here are customers that have receive an e-mail in the last 7 days OR have received two or more e-mails this month:
SELECT *
FROM customer AS c
WHERE c.ID IN (
    SELECT ID        --- the customer ID
    FROM c_contact
    WHERE contdate>=DATEADD(day, -31, SYSDATETIME()) -- for optimization
    GROUP BY ID
    HAVING MAX(contdate)>=DATEADD(day, -7, SYSDATETIME()) OR
           SUM((CASE WHEN contdate>=DATEFROMPARTS(
               YEAR(SYSDATETIME()),
               MONTH(SYSDATETIME()),
               1) THEN 1 ELSE 0 END))>=2);

Because I've put the two conditions in a single HAVING clause, the two queries only scan the c_contact table once, making them much more efficient. In particular, an optimal index for this type of query would probably look something like this:
CREATE INDEX indexName ON c_contact (ID, contdate);

A: Since you don't have test data:i cant test the query myself.Can you try below query
SELECT * from
costumer c
 inner join
c_contact cc
on cc.ID = c.ID
WHERE
not exists(select  1 from c_contact c1 where c1.ID = cc.ID
 and
c1.CONTDATE >= getdate()-7) AND
not exists (select 1 from c_contact where MONTH(contdate) = MONTH(getdate())
and YEAR(contdate) = YEAR(getdate() HAVING count(ID) >= 2)


text:
Q: Image Slider using Range Slider and Dot Controls I am modifying w3schools basic image slideshow carousel to work with a range slider as well as clickable dots. The goal is to be able to move the slider, and the image changes. I'm not concerned with styling as much, as long as I can understand the concept or logic that needs to take place. I would imagine the clicked "dot value" matches the "slider value" somehow. Advice?

var slideIndex = 1;
showSlides(slideIndex);

function plusSlides(n) {
  showSlides(slideIndex += n);
}

function currentSlide(n) {
  showSlides(slideIndex = n);
}

function showSlides(n) {
  var i;
  var slides = document.getElementsByClassName("mySlides");
  var dots = document.getElementsByClassName("dot");

  var RangeValue = document.getElementById("myRange").value;

  if (n > slides.length) {
    slideIndex = 1
  }
  if (n < 1) {
    slideIndex = slides.length
  }
  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }
  for (i = 0; i < dots.length; i++) {
    dots[i].className = dots[i].className.replace(" active", "");
  }

  slides[slideIndex - 1].style.display = "block";
  dots[slideIndex - 1].className += " active";

}
.slide-container {
  font-size: 10px;
  position: fixed;
  bottom: 15%;
  right: 20%;
  text-align: center;
  width: 40%;
  height: 40%;
}

.slide-container h1 {
  float: left;
  font-size: 1em;
  color: white;
  font-family: 'Montserrat', sans-serif;
  text-transform: uppercase;
  text-shadow: 1px 1px 3px rgb(53, 53, 53);
}

#run {
  float: right;
  font-size: 1em;
  color: white;
  background-color: #95A56E;
  font-family: 'Montserrat', sans-serif;
  text-transform: uppercase;
  border-radius: 2px;
  padding: 3px;
  box-shadow: 1px 1px 3px rgb(53, 53, 53);
}

.slide-container img {
  box-shadow: 1px 1px 3px rgb(53, 53, 53);
  border-radius: 2px;
}

.mySlides {
  display: none;
}

.dot {
  cursor: pointer;
  height: 6px;
  width: 6px;
  margin: 0 2px;
  margin-top: 5px;
  background-color: #bbb;
  border-radius: 50%;
  display: inline-block;
  transition: background-color 0.6s ease;
}

.active,
.dot:hover {
  background-color: #95A56E;
}

/* Fading animation */

.fade {
  -webkit-animation-name: fade;
  -webkit-animation-duration: 1.5s;
  animation-name: fade;
  animation-duration: 1.5s;
}

@-webkit-keyframes fade {
  from {
    opacity: .4
  }
  to {
    opacity: 1
  }
}

@keyframes fade {
  from {
    opacity: .4
  }
  to {
    opacity: 1
  }
}

.range-slider {
  -webkit-appearance: none;
  width: 100%;
  height: 5px;
  background: #d3d3d3;
  outline: none;
  opacity: 0.7;
  -webkit-transition: .2s;
  transition: opacity .2s;
  border-radius: 10px;
}

.range-slider::-moz-range-thumb {
  width: 25px;
  height: 25px;
  background: #95A56E;
  cursor: pointer;
}

.range-slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 5px;
  height: 20px;
  background: #95A56E;
  cursor: pointer;
  border-radius: 10px;
  box-shadow: 0px 1px 2px rgb(53, 53, 53);
}

.range-slider:hover {
  opacity: 1;
}

Featured Cases

Run This Design

  <input type="range" min="1" max="3" value="2" class="range-slider" id="myRange" oninput="currentSlide()">

A: I figured it out on my own!
Added a onclick to the range slider and set it to the currentslide function like the dots above , except equal to the rangeslider's value.
HTML
<input type="range" min="1" max="3" value = "1" class="range-slider" id="myRange" onclick="currentSlide(value)" >

Added this to end of javascript, after dots[slideIndex - 1].className += " active";
JAVASCRIPT
document.getElementById("myRange").value = slideIndex;

very basic stuff I'm sure but I just wanted to learn. Now if I drag the slider or click the dots, it goes to the correct image.

redpajama_set_name: RedPajamaStackExchange


text:
Q: 301 Redirects working for hidden index.php but not for .php I am moving a client from a custom developed PHP site to Wordpress. I am now in the process of using 301 Redirects in the .htaccess file to move the old locations to the new ones in Wordpress.  Some of them are working and some not (meaning it serves up the "old" location). I have the standard "pretty permalinks" mod_rewrite section in the file and then all the 301's.
So, the ones that have an original location that are listed like a directory (re-written index.php) work and the ones that have an explicitly named php file do not. Examples:
This works:
Redirect 301 /about/ http://deanchiropractic.com/about-us/

This does (still serves dr-jon.php):
Redirect 301 /about/dr-jon.php http://deanchiropractic.com/about-us/dr-jon-dean/

I have tried changing the order around, tried having the 301s before and after the mod-rewrite section, tried with and without a DirectoryIndex line.  I've also verified that i am editing the .htaccess in the webserver root.
I'd rather get my .htaccess working than put php to do the 301 Redirects in all the files that aren't redirecting (I have tried, and verified that using one file).
Here is the entire thing for reference:
DirectoryIndex index.php index.html
Redirect 301 /about/dr-dean.php http://deanchiropractic.com/about-us/christophe-dean-dc/
Redirect 301 /about/dr-jon.php http://deanchiropractic.com/about-us/dr-jon-dean/
Redirect 301 /techniques/activator.php http://deanchiropractic.com/chiropractic-techniques/activator-method/
Redirect 301 /techniques/cox-technique.php http://deanchiropractic.com/chiropractic-techniques/cox-technique/
Redirect 301 /techniques/active-release.php http://deanchiropractic.com/chiropractic-techniques/active-release-technique/
Redirect 301 /community/dinner-talk.php http://deanchiropractic.com/get-healthy/
Redirect 301 /community/refer.php http://deanchiropractic.com/get-healthy/
Redirect 301 /resources/forms.php http://deanchiropractic.com/forms/
Redirect 301 /resources/faq.php http://deanchiropractic.com/faq/
Redirect 301 /resources/articles/low-back-pain-relief.php http://deanchiropractic.com/low-back-pain-relief/
Redirect 301 /resources/articles/about-the-activator-method.php http://deanchiropractic.com/achieve-wellness-with-the-activator-method/
Redirect 301 /resources/articles/spinal-disc-treatment.php http://deanchiropractic.com/spinal-disc-treatment/
Redirect 301 /resources/articles/headache-relief-benefits.php http://deanchiropractic.com/headache-relief/
Redirect 301 /resources/articles/carpal-tunnel-relief.php http://deanchiropractic.com/carpal-tunnel-relief/
Redirect 301 /resources/articles/neck-pain-relief.php http://deanchiropractic.com/neck-pain-relief/
Redirect 301 /testimonials.php http://deanchiropractic.com/reviews/
Redirect 301 /contact.php http://deanchiropractic.com/contact-us/
Redirect 301 /about/    http://deanchiropractic.com/about-us/
Redirect 301 /techniques/   http://deanchiropractic.com/chiropractic-techniques/
Redirect 301 /community/    http://deanchiropractic.com/get-healthy/
Redirect 301 /resources/    http://deanchiropractic.com/forms/
Redirect 301 /resources/articles/   http://deanchiropractic.com/category/articles/
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

I've searched wide, and on this site and can't find a match for my exact problem...though I've learned a lot about .htaccess in the process (still a n00b tho).  Thanks....

A: It's possible that mod_alias and mod_rewrite are interferring with each other because they both get applied to the same URL in the processing pipeline. In this case, it may be that the URI is changed and a redirection is flagged by mod_alias (via the Redirect directive) but then mod_rewrite does its thing and rewrites the URI to get routed through index.php, but the URI is flagged for a redirect so at the end of the pipeline, you have a mangled URI that gets sent as a redirect. You can avoid this by sticking with just mod_rewrite and using the L flag so the wordpress rules don't get applied:
RewriteEngine On
RewriteRule ^/?about/dr-dean.php http://deanchiropractic.com/about-us/christophe-dean-dc/ [L,R=301]
RewriteRule ^/?about/dr-jon.php http://deanchiropractic.com/about-us/dr-jon-dean/ [L,R=301]
RewriteRule ^/?techniques/activator.php http://deanchiropractic.com/chiropractic-techniques/activator-method/ [L,R=301]

etc...


text:
Q: Runtime polymorphism in C++ using data members I was studying OOP from here.
It says that runtime polymorphism is possible in C++ using data members.
Now,consider this code:-
#include <iostream>
using namespace std;
class Animal {                                 //  base class declaration.
    public:
    string color = "Black";
};
class Dog: public Animal                       // inheriting Animal class.
{
    public:
    string color = "Grey";
};
int main(void) {
     Animal d= Dog();
     Animal d1 = Animal();
     cout<<d.color<<endl;
     cout<<d1.color<<endl;
}

In both the cases above the color "black" is printed. So, how is this example of runtime polymorphism ?

A:
how is this example of runtime polymorphism ?

It is not an example of runtime polymorphism but rather of object slicing.
This is one of the reason why a good C++ book is recommended over online sites like this.
That is, the first choice/preference should always be(assuming you want to have a deep understanding of the subject) a good book. And then only, after you've read up the topic in the book you can look it up on sites for practical examples of the same. If you want to refer to legit C++ documentation sites you can refer to cppreference and learncpp. These two sites are C++ dedicated sites so you can rely on most of the info/example given there. Again referring to a book first is recommended.

A: If this was runtime polymorphism you could write a function:
void foo(Animal& a) {
    std::cout << a.color << "\n";
}

And it would print the respective color of the object based on the dynamic type of the parameter. However, there is no such thing as "Runtime-polymorphism based on member variables" in C++. The tutorial is wrong and misleading.
If compile and execute this:
#include <iostream>
using namespace std;
class Animal {                                          //  base class declaration.
    public:
    string color = "Black";
};
class Dog: public Animal                       // inheriting Animal class.
{
    public:
    string color = "Grey";

};

void foo(Animal& a) {
    std::cout << a.color << "\n";
}
int main(void) {
     Dog d= Dog();
     Animal d1 = Animal();
     foo(d);
     foo(d1);
}

The output will be
Black
Black

There is no such thing as virtual member variables. Only for virtual member functions use virtual dispatch:
#include <iostream>
using namespace std;
class Animal {                                          //  base class declaration.
    public:
    virtual std::string color() const { return "Black"; }
};
class Dog: public Animal                       // inheriting Animal class.
{
    public:
    std::string color() const override { return "Grey"; }

};

void foo(Animal& a) {
    std::cout << a.color() << "\n";
}
int main(void) {
     Dog d= Dog();
     Animal d1 = Animal();
     foo(d);
     foo(d1);
}

Output:
Grey
Black

The turial is wrong and misleading when it says that there would be runtime polymorphis with member variables. Moreover the example they present has object slicing. See here: What is object slicing?.


text:
Q: Como usar uma Array para sortear elementos? eu tenho esse código
 With SerialPort1
            .Write("AT" & vbCrLf)
            Threading.Thread.Sleep(1000)
            .Write("AT+CMGF=1" & vbCrLf)
            Threading.Thread.Sleep(1000)
            .Write("AT+CMGS=" & Chr(34) & txtnumber.Text & Chr(34) & vbCrLf)
            .Write(txtmessage.Text & Chr(26))
            Threading.Thread.Sleep(1000)
        End With

digamos que no txtmessage.Text eu queira colocar tipo mensagem[i].Text com uma lista de Array.
Exemplo:
    Private Sub menssagem(txtmessage, TextBox1, TextBox2, TextBox3, TextBox4, TextBox5, TextBox6, TextBox7, TextBox8)
    Dim menssagem(8) As Integer

End Sub

no total são 9 TextBox que eu quero que sejam sorteadas para seguir com a função.
Outra coisa, no SerialPort1 é possivel eu inserir uma lista de array também? E se o SerialPort12, digamos assim, ela esteja sem resposta, tem como dar um Next para o proximo da lista de array?

A: Se eu entendi, você só tem que usar Rnd():
    With SerialPort1
        .Write("AT" & vbCrLf)
        Threading.Thread.Sleep(1000)
        .Write("AT+CMGF=1" & vbCrLf)
        Threading.Thread.Sleep(1000)
        .Write("AT+CMGS=" & Chr(34) & txtnumber.Text & Chr(34) & vbCrLf)
        .Write(mensagem[CInt(Math.Ceiling(Rnd() * 9))].Text & Chr(26))
        Threading.Thread.Sleep(1000)
    End With

A: Olá fiz um exemplo em C#, você pode adaptá-lo para VB:
TextBox[] array = new TextBox[10];
array[0] = textBox1;
array[1] = textBox2;
array[2] = textBox3;
array[3] = textBox4;
array[4] = textBox5;
array[5] = textBox6;
array[6] = textBox7;
array[7] = textBox8;
array[8] = textBox9;
array[9] = textBox10;
Random r = new Random();
for (int i = 0; i < array.Length; i++)
{
     Thread.Sleep(200);
     var index = r.Next(array.Length);
     array[index].Text = $"Indice sortiado {index}, nome do textbox  {array[index].Name}";
}

Espero ter ajudado


text:
Q: How can I put the asp.net "Login" view on the layout page, instead of @Html.Actionlink to a separate login page? This may be something basic that I am overthinking, but I cannot seem to find a solid solution without getting model binding errors. Basically I want this _layout.cshtml markup:

        @Html.Partial("_LoginPartial")

To show the markup of the login form I have, rather than the link to a seperate View. The markup for the _LoginPartial page is what comes with the startup web site template:
@if (Request.IsAuthenticated)
{
using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-form pull-right" }))
{
    @Html.AntiForgeryToken()

            @Html.ActionLink("Hello " + User.Identity.Name + "!", "Manage", "Account", routeValues: null, htmlAttributes: new { title = "Manage" })

Log off

}
}
else
{
     @Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })
}

Particularly, I am looking to have the line in the 'else' branch show this markup:
@model Accepted.Web.Models.LoginModel

@if (Request.IsAuthenticated)
{
    using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-form pull-right" }))
    {
        @Html.AntiForgeryToken()

                @Html.ActionLink("Hello " + User.Identity.Name + "!", "Manage", "Account", routeValues: null, htmlAttributes: new { title = "Manage" })

Log off

    }
}
else
{
    ...
}

I tried to just throw the markup I want in the RenderPartial, but since it is strongly typed, the engine complains if I am passing a different model for another view. This obvious won't work since I am going to have lots of strongly typed views floating around, and this login/logout markup needs to be on every page. What design solution would work for the requirements I have? Include the LoginModel.cs in every ViewModel I create? Not sure I would like to go that route. Another option I saw was having a BaseViewModel that have the LoginModel in it, which helps keep the DRY principle, but I feel may violate KISS. Any ideas?

A: You could use RenderAction and let the controller create a ViewModel:
public class CommonController : Controller
{
    public ActionResult LoginForm()
    {
        var model = new LoginModel();
        return PartialView("_LoginPartial", model);
    }
}

Then use RenderAction in the _Layout.cshtml:
@{ Html.RenderAction("LoginPartial", "Common"); }

This approach has causes some overhead because it has to go through the controller pipeline, but I think it negligible.
Note: I took the liberty to name the controller Common, but this can be any name of course.


text:
Q: Slick 3.1.1 deduplication errors with sbt-assembly I'm using Slick 3.1.1 in a Scala project. My build.sbt libraryDependencies contains this:
"com.typesafe.slick"  %% "slick"           % "3.1.1",
"com.typesafe.slick"  %% "slick-hikaricp"  % "3.1.1",
"com.zaxxer"          % "HikariCP"         % "2.4.3",
"mysql"               % "mysql-connector-java" % "5.1.38",

Everything works. However, when I try to deploy with sbt-assembly I get errors like this:
[error] deduplicate: different file contents found in the following:
[error] /home/thunderkid/.ivy2/cache/com.zaxxer/HikariCP-java6/bundles/HikariCP-java6-2.3.7.jar:com/zaxxer/hikari/pool/HikariPool.class
[error] /home/thunderkid/.ivy2/cache/com.zaxxer/HikariCP/bundles/HikariCP-2.4.3.jar:com/zaxxer/hikari/pool/HikariPool.class

How do I fix these?
Previously I was using Slick 3.0, which doesn't need slick-hikaricp, and it worked fine. I tried deleting .ivy2/cache/com.zaxxer/HikariCP-java6, but that doesn't work - it's just recreated. My mergeStrategy is
mergeStrategy in assembly <<= (mergeStrategy in assembly) { (old) =>
    {
        case PathList(ps @ _*) if ps.last endsWith "ArgumentsProcessor.class" => MergeStrategy.first
        case PathList(ps @ _*) if ps.last endsWith "MatchersBinder.class" => MergeStrategy.first
        case "application.conf" => MergeStrategy.concat
        case "unwanted.txt"     => MergeStrategy.discard
        case x => old(x)
    }
}

A: Following @brettw's advice in his comment above, I got it to work by adding an exclude command into build.sbt as follows:
"com.typesafe.slick"  %% "slick-hikaricp"  % "3.1.1"   exclude("com.zaxxer", "HikariCP-java6"),


text:
Q: send HttpPostedFileBase in less time I am uploading file and sending it to controller, it takes 2 minutes to reach at server. Is it any way to send a file of 380KB in less time on form submit
From
<input type="file" />

To
public void uploadFile(HttpPostedFileBase[] files)


text:
Q: Carriage return, LineFeed and Sed behaviour I need to understand why sed is able to work for 1) and not for 2). Please do not post me any alternative solutions. I have already found them on this forum. I just need to understand the behavior of sed regarding point 1) and 2).
1) sed -i s/\\r//g file.txt
On checking od -c file.txt, sed has successfully removed \r
2) sed -i s/\\n//g file.txt
On checking od -c file.txt, sed has not removed \n
My question here is to just understand why its not working for point-2. Please do not post any alternative solutions. Wish to understand the internals thats it!

A: From GNU sed manual - How sed Works

sed operates by performing the following cycle on each line of input: first, sed reads one line from the input stream, removes any trailing newline, and places it in the pattern space. Then commands are executed; each command can have an address associated to it: addresses are a kind of condition code, and a command is only executed if the condition is verified before the command is to be executed.
When the end of the script is reached, unless the -n option is in use, the contents of pattern space are printed out to the output stream, adding back the trailing newline if it was removed. Then the next cycle starts for the next input line.

From POSIX spec (thanks steeldriver for the link)

In default operation, sed cyclically shall append a line of input, less its terminating newline, into the pattern space. Normally the pattern space will be empty, unless a D command terminated the last cycle. The sed utility shall then apply in sequence all commands whose addresses select that pattern space, and at the end of the script copy the pattern space to standard output (except when -n is specified) and delete the pattern space. Whenever the pattern space is written to standard output or a named file, sed shall immediately follow it with a newline.

tl;dr the input record separator (which is newline by default) is removed before executing the commands and then added back while printing the record

There are, however, cases where the newline character can be manipulated. Some examples given below:
$ # this would still not allow newline of second line to be manipulated
$ seq 5 | sed 'N; s/\n/ : /'
1 : 2
3 : 4
5

$ # here ASCII NUL is input record separator, so newline can be freely changed
$ seq 5 | sed -z 's/\n/ : /g'
1 : 2 : 3 : 4 : 5 :

$ # default newline separator, so NUL character can be changed
$ printf 'foo\0baz\0xyz\0' | sed 's/\x0/-/g'
foo-baz-xyz-
$ # NUL character is separator, so it cannot be changed now
$ printf 'foo\0baz\0xyz\0' | sed -z 's/\x0/-/g' | cat -A
foo^@baz^@xyz^@

A: A file for sed is a stream of lines delimited by \n. If \n is the delimiter, of course it can't handle it in substitutions.


text:
Q: pgfplots dateplot: how to add best fit line This is my plot:

I would like to add the best fit line in correspondence with the first straight section (from 16:23 to 16:33). The equation of the line is y = 0.022x + 19.018.
This is my attempt
\documentclass{standalone}

    \usepackage[T1]{fontenc}
    \usepackage[utf8]{inputenc}
    \usepackage{amsmath,amssymb,amsfonts,systeme}
    \usepackage{color}
    \usepackage{array}
    \usepackage{tikz}
    \usepackage{tkz-euclide}
    \usetkzobj{all}
    \usetikzlibrary{arrows.meta}
    \usepackage{siunitx}
    \usepackage{pgfplots}
    \usepgfplotslibrary{dateplot, statistics}
    \usepackage{filecontents}

\begin{filecontents*}{ab.txt}
date, value
2019-04-17 16:23:56, 18.94
2019-04-17 16:24:01, 18.96
2019-04-17 16:24:06, 18.97
2019-04-17 16:24:11, 18.98
2019-04-17 16:24:16, 18.99
2019-04-17 16:24:21,    19
2019-04-17 16:24:26, 19.01
2019-04-17 16:24:31, 19.01
2019-04-17 16:24:36, 19.02
2019-04-17 16:24:41, 19.03
2019-04-17 16:24:46, 19.03
2019-04-17 16:24:51, 19.04
2019-04-17 16:24:56, 19.04
2019-04-17 16:25:02, 19.05
2019-04-17 16:25:07, 19.05
2019-04-17 16:25:11, 19.05
2019-04-17 16:25:16, 19.06
2019-04-17 16:25:21, 19.06
2019-04-17 16:25:27, 19.06
2019-04-17 16:25:32, 19.07
2019-04-17 16:25:37, 19.07
2019-04-17 16:25:42, 19.07
2019-04-17 16:25:46, 19.08
2019-04-17 16:25:52, 19.08
2019-04-17 16:25:57, 19.08
2019-04-17 16:26:02, 19.09
2019-04-17 16:26:07, 19.09
2019-04-17 16:26:12, 19.09
2019-04-17 16:26:17, 19.09
2019-04-17 16:26:22,  19.1
2019-04-17 16:26:27,  19.1
2019-04-17 16:26:32,  19.1
2019-04-17 16:26:37, 19.11
2019-04-17 16:26:42, 19.11
2019-04-17 16:26:47, 19.11
2019-04-17 16:26:52, 19.11
2019-04-17 16:26:57, 19.12
2019-04-17 16:27:02, 19.12
2019-04-17 16:27:07, 19.12
2019-04-17 16:27:12, 19.12
2019-04-17 16:27:17, 19.12
2019-04-17 16:27:22, 19.13
2019-04-17 16:27:27, 19.13
2019-04-17 16:27:32, 19.13
2019-04-17 16:27:37, 19.13
2019-04-17 16:27:42, 19.14
2019-04-17 16:27:47, 19.14
2019-04-17 16:27:52, 19.14
2019-04-17 16:27:57, 19.14
2019-04-17 16:28:02, 19.14
2019-04-17 16:28:07, 19.15
2019-04-17 16:28:12, 19.15
2019-04-17 16:28:17, 19.15
2019-04-17 16:28:22, 19.15
2019-04-17 16:28:27, 19.16
2019-04-17 16:28:32, 19.16
2019-04-17 16:28:37, 19.16
2019-04-17 16:28:42, 19.16
2019-04-17 16:28:47, 19.16
2019-04-17 16:28:52, 19.17
2019-04-17 16:28:57, 19.17
2019-04-17 16:29:02, 19.17
2019-04-17 16:29:07, 19.17
2019-04-17 16:29:12, 19.17
2019-04-17 16:29:17, 19.17
2019-04-17 16:29:22, 19.17
2019-04-17 16:29:27, 19.18
2019-04-17 16:29:32, 19.18
2019-04-17 16:29:37, 19.18
2019-04-17 16:29:42, 19.18
2019-04-17 16:29:47, 19.18
2019-04-17 16:29:52, 19.19
2019-04-17 16:29:57, 19.19
2019-04-17 16:30:02, 19.19
2019-04-17 16:30:07, 19.19
2019-04-17 16:30:12,  19.2
2019-04-17 16:30:17,  19.2
2019-04-17 16:30:22,  19.2
2019-04-17 16:30:27,  19.2
2019-04-17 16:30:32,  19.2
2019-04-17 16:30:37,  19.2
2019-04-17 16:30:42,  19.2
2019-04-17 16:30:47, 19.21
2019-04-17 16:30:52, 19.21
2019-04-17 16:30:57, 19.21
2019-04-17 16:31:02, 19.21
2019-04-17 16:31:07, 19.21
2019-04-17 16:31:12, 19.21
2019-04-17 16:31:17, 19.21
2019-04-17 16:31:22, 19.22
2019-04-17 16:31:27, 19.22
2019-04-17 16:31:32, 19.22
2019-04-17 16:31:37, 19.22
2019-04-17 16:31:42, 19.23
2019-04-17 16:31:47, 19.23
2019-04-17 16:31:52, 19.23
2019-04-17 16:31:57, 19.23
2019-04-17 16:32:02, 19.23
2019-04-17 16:32:07, 19.23
2019-04-17 16:32:12, 19.23
2019-04-17 16:32:17, 19.23
2019-04-17 16:32:22, 19.24
2019-04-17 16:32:27, 19.24
2019-04-17 16:32:32, 19.24
2019-04-17 16:32:37, 19.24
2019-04-17 16:32:42, 19.24
2019-04-17 16:32:47, 19.24
2019-04-17 16:32:52, 19.25
2019-04-17 16:32:57, 19.25
2019-04-17 16:33:02, 19.25
2019-04-17 16:33:07, 19.25
2019-04-17 16:33:12, 19.25
2019-04-17 16:33:17, 19.25
2019-04-17 16:33:22, 19.25
2019-04-17 16:33:27, 19.26
2019-04-17 16:33:32, 19.26
2019-04-17 16:33:37, 19.26
2019-04-17 16:33:42, 19.28
2019-04-17 16:33:47, 19.45
2019-04-17 16:33:52, 19.73
2019-04-17 16:33:58, 20.18
2019-04-17 16:34:02, 20.44
2019-04-17 16:34:07, 20.77
2019-04-17 16:34:15, 21.11
2019-04-17 16:34:17, 21.19
2019-04-17 16:34:22,  21.3
2019-04-17 16:34:27,  21.4
2019-04-17 16:34:32, 21.51
2019-04-17 16:34:37, 21.58
2019-04-17 16:34:42, 21.65
2019-04-17 16:34:47,  21.7
2019-04-17 16:34:52, 21.75
2019-04-17 16:34:57, 21.79
2019-04-17 16:35:02, 21.81
2019-04-17 16:35:07, 21.84
2019-04-17 16:35:12, 21.87
2019-04-17 16:35:17, 21.89
2019-04-17 16:35:22, 21.91
2019-04-17 16:35:27, 21.93
2019-04-17 16:35:32, 21.94
2019-04-17 16:35:38, 21.96
2019-04-17 16:35:42, 21.97
2019-04-17 16:35:47, 21.99
2019-04-17 16:35:52,    22
2019-04-17 16:35:58, 22.01
2019-04-17 16:36:03, 22.02
2019-04-17 16:36:08, 22.03
2019-04-17 16:36:13, 22.04
2019-04-17 16:36:17, 22.05
2019-04-17 16:36:23, 22.06
2019-04-17 16:36:28, 22.07
2019-04-17 16:36:33, 22.08
2019-04-17 16:36:38, 22.09
2019-04-17 16:36:43, 22.09
2019-04-17 16:36:48,  22.1
2019-04-17 16:36:53, 22.11
2019-04-17 16:36:58, 22.12
2019-04-17 16:37:03, 22.12
2019-04-17 16:37:08, 22.13
2019-04-17 16:37:13, 22.14
2019-04-17 16:37:18, 22.15
2019-04-17 16:37:23, 22.15
2019-04-17 16:37:28, 22.16
2019-04-17 16:37:33, 22.16
2019-04-17 16:37:38, 22.17
2019-04-17 16:37:43, 22.17
2019-04-17 16:37:48, 22.18
2019-04-17 16:37:53, 22.18
2019-04-17 16:37:58, 22.19
2019-04-17 16:38:03, 22.19
2019-04-17 16:38:08,  22.2
2019-04-17 16:38:13,  22.2
2019-04-17 16:38:18,  22.2
2019-04-17 16:38:23, 22.21
2019-04-17 16:38:28, 22.21
2019-04-17 16:38:33, 22.22
2019-04-17 16:38:38, 22.23
2019-04-17 16:38:43, 22.22
2019-04-17 16:38:48, 22.23
2019-04-17 16:38:53, 22.23
2019-04-17 16:38:58, 22.24
2019-04-17 16:39:03, 22.24
2019-04-17 16:39:08, 22.24
2019-04-17 16:39:13, 22.25
2019-04-17 16:39:18, 22.25
2019-04-17 16:39:23, 22.25
2019-04-17 16:39:28, 22.26
2019-04-17 16:39:33, 22.26
2019-04-17 16:39:41, 22.26
2019-04-17 16:39:43, 22.26
2019-04-17 16:39:48, 22.27
2019-04-17 16:39:53, 22.27
2019-04-17 16:39:58, 22.27
2019-04-17 16:40:03, 22.27
2019-04-17 16:40:08, 22.28
2019-04-17 16:40:13, 22.28
2019-04-17 16:40:18, 22.28
2019-04-17 16:40:23, 22.28
2019-04-17 16:40:28, 22.29
2019-04-17 16:40:33, 22.29
2019-04-17 16:40:38,  22.3
2019-04-17 16:40:43, 22.29
2019-04-17 16:40:48,  22.3
2019-04-17 16:40:53,  22.3
2019-04-17 16:40:58,  22.3
2019-04-17 16:41:03,  22.3
2019-04-17 16:41:08, 22.31
2019-04-17 16:41:13, 22.31
2019-04-17 16:41:18, 22.31
2019-04-17 16:41:23, 22.31
2019-04-17 16:41:28, 22.31
2019-04-17 16:41:33, 22.31
2019-04-17 16:41:38, 22.32
2019-04-17 16:41:43, 22.32
2019-04-17 16:41:48, 22.32
\end{filecontents*}

\begin{document}
\begin{tikzpicture}
  \begin{axis}[xlabel=t/s,
  ylabel=$\theta / \si{\celsius}$,
  grid, grid style=dashed,
   date coordinates in=x,
   table/col sep=comma,
   date ZERO=2019-04-17 16:23:56,
   xticklabel=\hour:\minute,
   xticklabel style={rotate=90, anchor=near xticklabel},
   ymin=18,
   ymax=23.5,
   xmax=2019-04-17 16:43:56,
   xtick={2019-04-17 16:25:56,2019-04-17 16:27:56,2019-04-17 16:29:56,2019-04-17 16:31:56,2019-04-17 16:33:56,2019-04-17 16:35:56,2019-04-17 16:37:56,
   2019-04-17 16:39:56,2019-04-17 16:41:56},
   extra x ticks={2019-04-17 16:23:56},
   extra y ticks={18,18.5,19.5,20.5,21.5,22.5},
   axis lines = middle,
   set layers,
   axis on top,
   x label style={at={(1,0)},right},
   y label style={at={(0,1)},above},
   style={thick},
   ]
  \addplot+[red,no markers,smooth] table[x=date,y=value] {ab.txt};
  \addplot [yellow] table[x=date,y=value] {0.022*x + 19.018};
  \end{axis}
\end{tikzpicture}
\end{document}

And this is the error message:

! Package pgfplots Error: Could not read table file '"0.022x +
  19.018"' in 'search path=.'. In case you intended to provide inline data: maybe TeX screwed upyour end-of-lines? Try 'row sep=crcr' and
  terminate your lines with '\' (refer to the pgfplotstable manual for
  details).See the pgfplots package documentation for explanation.Type H
   for immediate help.... ...table[x=date,y=value] {0.022x +
  19.018};

Can you help me?
Thank you in advance

A: I don't have any brilliant solutions, but it is possible to get what you're after. After running some numbers in Octave I think the expression for the linear fit you give are in terms of minutes. So what you could do is to set xmin and xmax to specific values, and calculate the number of minutes the axis spans. After that, add a second axis environment where you plot the line. Here set xmin=0 and xmax to the number of minutes the first axis covers. Remember that when you do this you need to set ymin/ymax to the same for both axes. Use hide axis for the second axis, as you're only interested in the plot line.
\documentclass{standalone}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{siunitx}
\usepackage{pgfplots}
\usepgfplotslibrary{dateplot, statistics}
\usepackage{filecontents}

\begin{filecontents*}{ab.txt}
date, value
2019-04-17 16:23:56, 18.94
2019-04-17 16:24:01, 18.96
2019-04-17 16:24:06, 18.97
2019-04-17 16:24:11, 18.98
2019-04-17 16:24:16, 18.99
2019-04-17 16:24:21,    19
2019-04-17 16:24:26, 19.01
2019-04-17 16:24:31, 19.01
2019-04-17 16:24:36, 19.02
2019-04-17 16:24:41, 19.03
2019-04-17 16:24:46, 19.03
2019-04-17 16:24:51, 19.04
2019-04-17 16:24:56, 19.04
2019-04-17 16:25:02, 19.05
2019-04-17 16:25:07, 19.05
2019-04-17 16:25:11, 19.05
2019-04-17 16:25:16, 19.06
2019-04-17 16:25:21, 19.06
2019-04-17 16:25:27, 19.06
2019-04-17 16:25:32, 19.07
2019-04-17 16:25:37, 19.07
2019-04-17 16:25:42, 19.07
2019-04-17 16:25:46, 19.08
2019-04-17 16:25:52, 19.08
2019-04-17 16:25:57, 19.08
2019-04-17 16:26:02, 19.09
2019-04-17 16:26:07, 19.09
2019-04-17 16:26:12, 19.09
2019-04-17 16:26:17, 19.09
2019-04-17 16:26:22,  19.1
2019-04-17 16:26:27,  19.1
2019-04-17 16:26:32,  19.1
2019-04-17 16:26:37, 19.11
2019-04-17 16:26:42, 19.11
2019-04-17 16:26:47, 19.11
2019-04-17 16:26:52, 19.11
2019-04-17 16:26:57, 19.12
2019-04-17 16:27:02, 19.12
2019-04-17 16:27:07, 19.12
2019-04-17 16:27:12, 19.12
2019-04-17 16:27:17, 19.12
2019-04-17 16:27:22, 19.13
2019-04-17 16:27:27, 19.13
2019-04-17 16:27:32, 19.13
2019-04-17 16:27:37, 19.13
2019-04-17 16:27:42, 19.14
2019-04-17 16:27:47, 19.14
2019-04-17 16:27:52, 19.14
2019-04-17 16:27:57, 19.14
2019-04-17 16:28:02, 19.14
2019-04-17 16:28:07, 19.15
2019-04-17 16:28:12, 19.15
2019-04-17 16:28:17, 19.15
2019-04-17 16:28:22, 19.15
2019-04-17 16:28:27, 19.16
2019-04-17 16:28:32, 19.16
2019-04-17 16:28:37, 19.16
2019-04-17 16:28:42, 19.16
2019-04-17 16:28:47, 19.16
2019-04-17 16:28:52, 19.17
2019-04-17 16:28:57, 19.17
2019-04-17 16:29:02, 19.17
2019-04-17 16:29:07, 19.17
2019-04-17 16:29:12, 19.17
2019-04-17 16:29:17, 19.17
2019-04-17 16:29:22, 19.17
2019-04-17 16:29:27, 19.18
2019-04-17 16:29:32, 19.18
2019-04-17 16:29:37, 19.18
2019-04-17 16:29:42, 19.18
2019-04-17 16:29:47, 19.18
2019-04-17 16:29:52, 19.19
2019-04-17 16:29:57, 19.19
2019-04-17 16:30:02, 19.19
2019-04-17 16:30:07, 19.19
2019-04-17 16:30:12,  19.2
2019-04-17 16:30:17,  19.2
2019-04-17 16:30:22,  19.2
2019-04-17 16:30:27,  19.2
2019-04-17 16:30:32,  19.2
2019-04-17 16:30:37,  19.2
2019-04-17 16:30:42,  19.2
2019-04-17 16:30:47, 19.21
2019-04-17 16:30:52, 19.21
2019-04-17 16:30:57, 19.21
2019-04-17 16:31:02, 19.21
2019-04-17 16:31:07, 19.21
2019-04-17 16:31:12, 19.21
2019-04-17 16:31:17, 19.21
2019-04-17 16:31:22, 19.22
2019-04-17 16:31:27, 19.22
2019-04-17 16:31:32, 19.22
2019-04-17 16:31:37, 19.22
2019-04-17 16:31:42, 19.23
2019-04-17 16:31:47, 19.23
2019-04-17 16:31:52, 19.23
2019-04-17 16:31:57, 19.23
2019-04-17 16:32:02, 19.23
2019-04-17 16:32:07, 19.23
2019-04-17 16:32:12, 19.23
2019-04-17 16:32:17, 19.23
2019-04-17 16:32:22, 19.24
2019-04-17 16:32:27, 19.24
2019-04-17 16:32:32, 19.24
2019-04-17 16:32:37, 19.24
2019-04-17 16:32:42, 19.24
2019-04-17 16:32:47, 19.24
2019-04-17 16:32:52, 19.25
2019-04-17 16:32:57, 19.25
2019-04-17 16:33:02, 19.25
2019-04-17 16:33:07, 19.25
2019-04-17 16:33:12, 19.25
2019-04-17 16:33:17, 19.25
2019-04-17 16:33:22, 19.25
2019-04-17 16:33:27, 19.26
2019-04-17 16:33:32, 19.26
2019-04-17 16:33:37, 19.26
2019-04-17 16:33:42, 19.28
2019-04-17 16:33:47, 19.45
2019-04-17 16:33:52, 19.73
2019-04-17 16:33:58, 20.18
2019-04-17 16:34:02, 20.44
2019-04-17 16:34:07, 20.77
2019-04-17 16:34:15, 21.11
2019-04-17 16:34:17, 21.19
2019-04-17 16:34:22,  21.3
2019-04-17 16:34:27,  21.4
2019-04-17 16:34:32, 21.51
2019-04-17 16:34:37, 21.58
2019-04-17 16:34:42, 21.65
2019-04-17 16:34:47,  21.7
2019-04-17 16:34:52, 21.75
2019-04-17 16:34:57, 21.79
2019-04-17 16:35:02, 21.81
2019-04-17 16:35:07, 21.84
2019-04-17 16:35:12, 21.87
2019-04-17 16:35:17, 21.89
2019-04-17 16:35:22, 21.91
2019-04-17 16:35:27, 21.93
2019-04-17 16:35:32, 21.94
2019-04-17 16:35:38, 21.96
2019-04-17 16:35:42, 21.97
2019-04-17 16:35:47, 21.99
2019-04-17 16:35:52,    22
2019-04-17 16:35:58, 22.01
2019-04-17 16:36:03, 22.02
2019-04-17 16:36:08, 22.03
2019-04-17 16:36:13, 22.04
2019-04-17 16:36:17, 22.05
2019-04-17 16:36:23, 22.06
2019-04-17 16:36:28, 22.07
2019-04-17 16:36:33, 22.08
2019-04-17 16:36:38, 22.09
2019-04-17 16:36:43, 22.09
2019-04-17 16:36:48,  22.1
2019-04-17 16:36:53, 22.11
2019-04-17 16:36:58, 22.12
2019-04-17 16:37:03, 22.12
2019-04-17 16:37:08, 22.13
2019-04-17 16:37:13, 22.14
2019-04-17 16:37:18, 22.15
2019-04-17 16:37:23, 22.15
2019-04-17 16:37:28, 22.16
2019-04-17 16:37:33, 22.16
2019-04-17 16:37:38, 22.17
2019-04-17 16:37:43, 22.17
2019-04-17 16:37:48, 22.18
2019-04-17 16:37:53, 22.18
2019-04-17 16:37:58, 22.19
2019-04-17 16:38:03, 22.19
2019-04-17 16:38:08,  22.2
2019-04-17 16:38:13,  22.2
2019-04-17 16:38:18,  22.2
2019-04-17 16:38:23, 22.21
2019-04-17 16:38:28, 22.21
2019-04-17 16:38:33, 22.22
2019-04-17 16:38:38, 22.23
2019-04-17 16:38:43, 22.22
2019-04-17 16:38:48, 22.23
2019-04-17 16:38:53, 22.23
2019-04-17 16:38:58, 22.24
2019-04-17 16:39:03, 22.24
2019-04-17 16:39:08, 22.24
2019-04-17 16:39:13, 22.25
2019-04-17 16:39:18, 22.25
2019-04-17 16:39:23, 22.25
2019-04-17 16:39:28, 22.26
2019-04-17 16:39:33, 22.26
2019-04-17 16:39:41, 22.26
2019-04-17 16:39:43, 22.26
2019-04-17 16:39:48, 22.27
2019-04-17 16:39:53, 22.27
2019-04-17 16:39:58, 22.27
2019-04-17 16:40:03, 22.27
2019-04-17 16:40:08, 22.28
2019-04-17 16:40:13, 22.28
2019-04-17 16:40:18, 22.28
2019-04-17 16:40:23, 22.28
2019-04-17 16:40:28, 22.29
2019-04-17 16:40:33, 22.29
2019-04-17 16:40:38,  22.3
2019-04-17 16:40:43, 22.29
2019-04-17 16:40:48,  22.3
2019-04-17 16:40:53,  22.3
2019-04-17 16:40:58,  22.3
2019-04-17 16:41:03,  22.3
2019-04-17 16:41:08, 22.31
2019-04-17 16:41:13, 22.31
2019-04-17 16:41:18, 22.31
2019-04-17 16:41:23, 22.31
2019-04-17 16:41:28, 22.31
2019-04-17 16:41:33, 22.31
2019-04-17 16:41:38, 22.32
2019-04-17 16:41:43, 22.32
2019-04-17 16:41:48, 22.32
\end{filecontents*}

\begin{document}
\begin{tikzpicture}
% set common options for the two axes, such as y-range
% if you want any scaling, do that here as well
\pgfplotsset{
  ymin=18,
  ymax=23.5
  }

\begin{axis}[xlabel=t/s,
   ylabel=$\theta / \si{\celsius}$,
   grid, grid style=dashed,
   date coordinates in=x,
   table/col sep=comma,
   date ZERO=2019-04-17 16:23:56,
   xticklabel=\hour:\minute,
   xticklabel style={rotate=90, anchor=near xticklabel},
   xmin=2019-04-17 16:23, % <-- added
   xmax=2019-04-17 16:42, % <-- edited => 19minutes range on axis
   xtick={2019-04-17 16:25:56,2019-04-17 16:27:56,2019-04-17 16:29:56,2019-04-17 16:31:56,2019-04-17 16:33:56,2019-04-17 16:35:56,2019-04-17 16:37:56,
   2019-04-17 16:39:56,2019-04-17 16:41:56},
   extra x ticks={2019-04-17 16:23:56},
   extra y ticks={18,18.5,19.5,20.5,21.5,22.5},
   axis lines = middle,
   set layers,
   axis on top,
   x label style={at={(1,0)},right},
   y label style={at={(0,1)},above},
   style={thick},
   ]
  \addplot+[red,no markers,smooth] table[x=date,y=value] {ab.txt};

  \end{axis}
  \begin{axis}[
    hide axis,
    xmin=0,
    xmax=19, % <-- 19 units range on this axis
    domain=0:10, % plot line for first 10 minutes
    samples=2
    ]
   \addplot [dashed,black] {0.022*x + 19.018};
   \end{axis}
\end{tikzpicture}
\end{document}


text:
Q: Finding cumulative area in ArcGIS for selected polygons I have 50 polygons of 5 different classes viz. A,B,C,D,E. and a field in the attribute table for area of each polygons. I want to add a field which give the cumulative area of the polygons of a particular class. e.g. if I query the attribute table for class A polygons, the cumulative area field give the cumulative area of the class A polygons. Likewise for class B polygons and so on. How can I do this in ArcGIS? The field calculator in ArcGIS gives the cumulative area of all the polygons, but not of particular class after query?
Thanks.

A: An alternate approach is to run the Summary Statistics tool setting your class field to be the case field and statistics field to be the Shape Area field with Statistic Type set to SUM. This will create a non-spatial table listing sum of area by class which you could then join back to your original polygon layer using the class field.

A: I would run Dissolve GP tool and choose the class field as the Dissolve field. This will create a new polygon feature class which would have five features, each will represent "the merged" geometry of all polygons within a certain class. Create a new field and calculate the geometry (right-click column and choose Calculate Geometry). Then you can join this feature class to the source feature class by using the class field.
You will get:
name class area
aaa   1     567
bbb   1     567
ccc   2     453
ddd   2     453
eee   2     453

I hope you understand that the sum area for the class will be the same for each polygon in the feature class since they belong to the same class. It might be a bit redundant to store the data like this, but hope it will serve its purpose.


text:
Q: Consuming Platform Events on Microservices I am having few issues designing an architecture to use with Platform events and Microservices.
According to microservices principle(Kubernetes), there should be at least 3(odd number) services running so that it can handle the load properly. It works for callouts but for platform events it just gets bit tricky.
Here is our architecture :
Whenever some conditions, to send uploaded file to 3rd party for processing and get that data back in Salesforce. So flow goes like this

*

*Person X uploads a file(File can be big so can't do HTTP callouts to a 3rd party with file data)

*We fire a platform event with fileId(content version id)

*The 3rd party microservice listens to it and fetches that file from SF rest endpoint and then processes and updates its data back in SF

Now the problem is in microservice. There can be multiple instances of it listening and follows the independent processing architecture so that they can work without worrying what's going on in other instances.
So, in order to stop single point of failure there will be at least 3 services running,(Even more if peak load) and they listen to the same event and act independently. This is problematic as all 3(or evn more) will process and respond same data to SF.
We can't let a single microservice to listen to all events as it will be again a single point of failure. Also, we cannot pop an event out of the event bus as its an event bus and not an event queue.
Has anyone faced this and what possible solution can be built around it?

A: Ultimately, you need some cooperation. You can't have an event bus with multiple independent nodes that can't communicate with each other from each processing every event. It's impossible. At some point, you need a common point of communication. Either the microservices need to chat with each other, or they need to take turns in some coordinated manner, or you need a frontend to delegate the events evenly, or you need a central queue to place the events in, or something else that will ultimately lead to a break from what you're defining as a microservice architecture. The microservices architecture is not suitable for all possible applications. This is one of those applications.

A: While I haven't really been into such a design issue, but I do see a way to overcome the situation that you are facing on this part:

The 3rd party microservice listens to it and fetches that file from SF rest endpoint and then processes and updates its data back in SF

If you can break this into different pieces, you should be able to resolve this I assume. However, this is still from a very high level, you will need to definitely look towards parallel processing and deadlock scenarios and how to avoid it.

The approach I can think of is:

*

*Once your microservice (MS1) fetches the event details from SF, you capture the replayId and then store that in a table in your local db or elsewhere.

*You make the call to SF only if there does not exist the same replayId in your db

*Let's say in the meantime another microservice (MS2) fetches the same replayId, it doesn't make call to SF as it sees the value in the db

*In case of failures from MS1 callouts, you just delete the replayId from the db, so that any other microservice again getting that replayId can take care of making the updates.

Another approach I can think here is to utilize a Queue (say using Azure service bus or MuleSoft) along with the one mentioned above. In this approach, you can have services subscribed to the Events in Salesforce publish those events as messages in the queue. Here you will though need to make sure that the replayId being added to the Queue is unique in nature.
Now, you have another service reading from the queue which takes care of calling out to SF based on the replayId. Because you have a Queue implementation, the time you read a message from the Queue, a lock will be placed on the message and will not be available for any other service and thus you can handle any concurrency issues this way.

In summary, you will need to make sure your microservices can communicate with each other to avoid any deadlock or concurrency issues.


text:
Q: Error in dividing the column values into Top 20% and Bottom 80% I have a vector such that:
Vec <- data.frame( Vec = c("70.0600", "8.5100", "5.8600", "399.9800", "9.0600", "78.8200", "71.4600") )

And I want to divide the above values into Top 20% and Bottom 80% in a way such that the result should look like:
 Vec        Dec
 70.0600    Top_20
 .          .
 .          .
 5.8600     Bottom_80

I am trying with something like that:
Vec$Quartile <- quantile(Vec$Vec, probs = c(0.20, 0.80))

But I got exactly 50-50% values of data:
 sum( Vec$Quartile>20 )

I am not sure where I was wrong?

A: Like this?
library(dplyr)

Vec <- data.frame(Vec = c(70.0600, 8.5100, 5.8600, 399.9800, 9.0600, 78.8200, 71.4600))

Vec %>%
  mutate(up = quantile(Vec, .8),
         part = ifelse(Vec > up, "Top_20", "Bottom_80"))

     Vec     up      part
1  70.06 77.348 Bottom_80
2   8.51 77.348 Bottom_80
3   5.86 77.348 Bottom_80
4 399.98 77.348    Top_20
5   9.06 77.348 Bottom_80
6  78.82 77.348    Top_20
7  71.46 77.348 Bottom_80

A:
Very simple approach without loading additional libraries:
Result
   value       dec
1 399.98    Top_20
2  78.82    Top_20
3  70.06 Bottom_20
4   8.51 Bottom_20
5   5.86 Bottom_20
6   9.06 Bottom_20
7  71.46 Bottom_20

Code
Vec <- c(70.0600, 8.5100, 5.8600, 399.9800, 9.0600, 78.8200, 71.4600)

q <- quantile(Vec, .8)

Vec <- rbind(
    data.frame(value = subset(Vec, Vec > q), dec = "Top_20"),
    data.frame(value = subset(Vec, Vec <= q), dec = "Bottom_20"))


text:
Q: jquery mobile changePage on form submit not working properly I am trying to change page on a form submit in Jquery, however, it is not working. It slides to show the same page instead of navigating to the target page. Below is the code. Any insights please? I tried using "#mainpage" , "index.html#mainpage" as well and still the same result. Link: jsfiddle.net/7yRph/1
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Multi-page template</title>
    <link rel="stylesheet" href="jquery.mobile-1.0.min.css" />

Personal Details

        <form id="fhome" method="POST" >

 Lets begin:

                <fieldset data-role="controlgroup" data-type="horizontal" >
                    <legend>Are you providing information about yourself?</legend>
                        Yes
                        <input type="radio" name="radio-choice" id="launchradioyes" value="yes" />
                        No
                        <input type="radio" name="radio-choice" id="launchradiono" value="no" />
                </fieldset>

            <input type="submit" value="Next" data-theme="a" />

         </form>

Testing page navigation II

             ID:
             <input type="tel" name="idprimary" id="idprimary" value="" />

A: You are missing your action attribute in your form tag.  This often breaks functionality of forms in browsers. Try this:
<form id="fhome" method="POST" action="mainpage">

It shouldn't negatively affect your code as you hijack the submit action anyway.
UPDATE
Also, you are missing your closing </form> tag and another closing
 tag after that.
Do you need to use a submit button?  Would it work to use a button and its corresponding click event?
http://jsfiddle.net/shanabus/7yRph/3/
UPDATE 2, working with form submit
After you resolve the closing tags, add the preventDefault method call and the data-ajax="false" attribute as outlined here in the docs.
example: http://jsfiddle.net/shanabus/7yRph/9/

A: When you hook submit, you should make sure the handler returns false (or call preventDefault on the event object), to prevent the default behavior of the submission.


text:
Q: Transform Method of graphics class in Codenameone I am unable to find alternative to Transform Method of graphics class in CodenameOne. I have tried using Graphics setTransform Method but am unable to get that desired functionality. Can you please help with this. Thank you
AffineTransform saveAT = g2d.getTransform();
g2d.transform(getmyTranslation());
g2d.transform(getmyRotation());
g2d.fillRect((int)(0-getSize()/2), (int)(0-getSize()/2), getSize(), getSize());
for (Object f : obj)
{
   f.draw(g2d);
}
g2d.setTransform(saveAT);

We do not have g2d.transform in CodenameOne

A: The affine transform is built directly into graphics so you don't need the first few lines at all:
AffineTransform saveAT = g2d.getTransform();
g2d.transform(getmyTranslation());
g2d.transform(getmyRotation());

You can just do:
g2d.rotate(degrees, pivotX, pivotY);

The fill rect should be practically identical:
g2d.fillRect((int)(0-getSize()/2), (int)(0-getSize()/2), getSize(), getSize());

Draw should also work nicely for Shape objects:
for (Object f : feet)
{
   f.draw(g2d);
}

Restoring the affine like this isn't necessary:
g2d.setTransform(saveAT);

Just do this instead:
g2d.resetAffine();


text:
Q: Symfony2: How to design a resolve state by zip functionality on an address entity This is rather a design question. I have an address entity with a ZIP field.
use Doctrine\ORM\Mapping as ORM;

/**
* Address
*
* @ORM\Table(name="address")
* @ORM\Entity
*/
class Address
{

/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer", nullable=false)
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="IDENTITY")
 */
private $id;

/**
 * @var string
 *
 * @ORM\Column(name="street", type="string", length=128, nullable=false)
 */
private $street;

/**
 * @var string
 *
 * @ORM\Column(name="street2", type="string", length=128, nullable=false)
 */
private $street2;

/**
 * @var string
 *
 * @ORM\Column(name="zip", type="string", length=64, nullable=false)
 */
private $zip;

/**
 * @var string
 *
 * @ORM\Column(name="city", type="string", length=128, nullable=false)
 */
private $city;

/**
 * @var string
 *
 * @ORM\Column(name="country", type="string", length=128, nullable=false)
 */
private $country;

 /**
 * Set city
 *
 * @param string $city
 * @return Address
 */
public function setCity($city)
{
    $this->city = $city;
    return $this;
}

/**
 * Get city
 *
 * @return string
 */
public function getCity()
{
    return $this->city;
}

 /**
 * Set country
 *
 * @param string $country
 * @return Address
 */
public function setCountry($country)
{
    $this->country = $country;
    return $this;
}

/**
 * Get country
 *
 * @return string
 */
public function getCountry()
{
    return $this->country;
}

 /**
 * Set street
 *
 * @param string $street
 * @return Address
 */
public function setStreet($street)
{
    $this->street = $street;
    return $this;
}

/**
 * Get street
 *
 * @return string
 */
public function getStreet()
{
    return $this->street;
}

 /**
 * Set street2
 *
 * @param string $street2
 * @return Address
 */
public function setStreet2($street2)
{
    $this->street2 = $street2;
    return $this;
}

/**
 * Get street2
 *
 * @return string
 */
public function getStreet2()
{
    return $this->street2;
}

 /**
 * Set zip
 *
 * @param string $zip
 * @return Address
 */
public function setZip($zip)
{
    $this->zip = $zip;
    return $this;
}

/**
 * Get zip
 *
 * @return string
 */
public function getZip()
{
    return $this->zip;
}

}

In addition I have a geo database which I can use to resolve the state for a given zip.
CREATE TABLE IF NOT EXISTS `zipcode` (
`id` int(11) NOT NULL,
  `city_id` int(11) NOT NULL,
  `district_id` int(11) DEFAULT NULL,
  `zipcode` varchar(10) NOT NULL
) ENGINE=MyISAM AUTO_INCREMENT=8262 DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `city` (
`id` int(11) NOT NULL,
  `state_id` int(11) NOT NULL,
  `county_id` int(11) NOT NULL,
  `name` varchar(200) NOT NULL,
  `lat` float NOT NULL,
  `lng` float NOT NULL
) ENGINE=MyISAM AUTO_INCREMENT=12241 DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `state` (
`id` int(11) NOT NULL,
  `name` varchar(200) NOT NULL
) ENGINE=MyISAM AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;

SELECT state.name
FROM zipcode
left join city on zipcode.city_id = city.id
left join state on city.state_id = state.id
WHERE zipcode.zipcode = '26123'

I guess I want to have a getState() on the address entity. But I'm unsure in which way to design the database query. Does it make sense to create separate entities for the geo db? Or just create a helper function somewhere? Native sql calls?

A: You need to define service. Let it be GeoHelper, inject ZipRepository in it and define method for converting ZIP into state name:
public function getStateByZip($zip)
{
    return $zipRepository->findBy(array('zipcode' => $zip))->getState();
}

A: That's fine for me, you will put your function which queries the state name in your zipcode entity repository. Apparentely you need other data, like lat lng ,... so it makes sense to create 3 seperate entities yes.
so you just have to do in the controller :
$repository = $this->getDoctrine()->getManager()->getRepository('AcmeMyBundle:Adresse');
$state = $repository->getState($zipcode);

and in adresse repository something which will look like
public function getState($zipCode)
{
    $qb = $this->createQueryBuilder('a')
        ->select('a','z','c','s')
        ->leftJoin('a.zip', 'z')
        ->leftJoin('z.city', 'c')
        ->leftJoin('c.state', 's')
        ->where('a.zip = :zipcode')->setParameter('zipcode', $zipCode);

   return $qb->getResult();
}

The function you wrote would go in ZipCodeRepository,it's fine too, and makes one less join to do, but you asked for AdressRepository so your choice.
...on a side note , i had to do this to but i used google geolocalisation api, which was very convenient (converts whatever you have zipcode, street adress, .. into whatever you want ) , but it may not be what you are looking for!
hope i somehow helped you


text:
Q: numpy multidimensional (3d) matrix multiplication I get two 3d matrix A (32x3x3) and B(32x3x3), and I want to get matrix C with dimension 32x3x3. The calculation can be done using loop like:
a = numpy.random.rand(32, 3, 3)
b = numpy.random.rand(32, 3, 3)
c = numpy.random.rand(32, 3, 3)

for i in range(32):
    c[i] = numpy.dot(a[i], b[i])

I believe there must be a more efficient one-line solution to this problem. Can anybody help, thanks.

A: You could do this using np.einsum:
In [142]: old = orig(a,b)

In [143]: new = np.einsum('ijk,ikl->ijl', a, b)

In [144]: np.allclose(old, new)
Out[144]: True

One advantage of using einsum is that you can almost read off what it's doing from the indices: leave the first axis alone (i), and perform a matrix multiplication on the last two (jk,kl->jl)).


text:
Q: How can I pass a variable from JSON to PHP? I'm using JSON to produce some data on Wordpress which I need to store in a PHP session variable. Here's the current setup that I'm messing around with but having no luck:
jQuery(document).ready(function($) {
    $.ajax({
    url: 'url',
    type: 'POST',
    dataType:'json',
    data: {foo: 145},
    success: function(data){
        console.log(data);
        alert(data);
        }
    });
});

and the PHP:
session_start();
$_SESSION['bar'] = $_POST['foo'];

I can see the data in the console but nothing will display when I echo my sesh var. Using vardump returns an empty array. Where am I going wrong here?
(I realize there are plenty of other questions just like this, but believe me, I've tried them all - nada.)

A: Answer: You can't use javascript to store server side variables.
You must save the $_SESSION var in the PHP script that this AJAX calls. Which you have put URL?? In WordPress you can use JQuery to call a special hook which can be caught he functions.php that handles all AJAX.
There's info about this everywhere, see solution to this answer:
Using AJAX in a WordPress plugin

A: You would have to set a global variable for both languages and then transfer them via javascript you could do this on every page using php includes.


text:
Q: How to disable the 'Cc', 'Assign to' and 'Keywords' - fields from the "new ticket" form in Trac? Just want to simplify the form.

A: You can change the ticket template (/usr/share/pyshared/trac/ticket/templates/ticket.html on Debian-based systems) directly.  I have made the following changes in our Trac installation.
--- a/trunk/trac/usr-share-pyshared-trac-ticket-templates-ticket.html
+++ b/trunk/trac/usr-share-pyshared-trac-ticket-templates-ticket.html
@@ -266,5 +266,7 @@
                   </tr>
                 </py:if>
-                <tr py:for="row in group(fields, 2, lambda f: f.type != 'textarea')"
+
+                <!--! Do not show Remaining or Owner field when creating a ticket. -->
+                <tr py:for="row in group(filter(lambda f: ticket.exists or f.name != 'owner' and f.name != 'estimatedhours',fields), 2, lambda f: f.type != 'textarea')"
                     py:if="can_modify or can_create"
                     py:with="fullrow = len(row) == 1">

as well as putting the Description field first (but that is a longer story).

A: You want the Simple Ticket Plugin.  I'm not sure if it works with 0.12 or not since the tags for it only go through 0.11, but it's worth trying.


text:
Q: Django - Dynamicly set the contents of list_display (admin view) Is there a way to reset the contents of the list_display (in the admin view) for some model each time the model is filtered? (so that filtering by different objects will give a diffrent number of columns in the display table).

For example:
I have three model in my django application: Child, Family, Pet. Child has a foregin key to Family, and Pet also has a foregin key to Family.
Now, in the admin view of Child, I want to be able to filter by Family, and after the filtering, the table will display the child's name and the name of each one of the pets that his family owns. That way the number of columns in the displayed table changes according to the number of pets of the Family object the filtering was done by.
Thanks.

A: list_display is set in admin.py, and requires a server restart to become effective. As a result, it cannot be modified on the fly.
Additionally, Django does not seem to support the display of ManyToMany fields in this manner, so you cannot display the pet names in the list view "out of the box." According to the documentation:

If you want to do this nonetheless, give your model a custom method, and add that method's name to list_display.


text:
Q: Multiple users in a rails integration test I am looking how to do an integration for a flow that requires 2 users, in which you cannot JUMP around in the order.
User A does 1
User B does 2
User A does 3
User B does 4
User A does 5
...

Test code is executed in a random order therefor; I cannot write a series of tests such as: test "user A does 1" do ... end and expect them to execute in sequence
So, how should an integration test be written for the above situtation?
require 'test_helper'

class MyIntegrationTest < ActionController::IntegrationTest

  test "Test interaction between 2 users" do
    sign_in 'userA@mysite.com'
    assert_response :success

    get '/does/1'
    assert_response :success

    sign_out

    sign_in 'userB@mysite.com'
    assert_response :success

    get '/does/2'
    assert_response :success

    sign_out

    sign_in 'userA@mysite.com'
    assert_response :success

    get '/does/3'
    assert_response :success

    sign_out

    sign_in 'userB@mysite.com'
    # ahhhhhhhhhhhhhhhhhhhhhhhhhhh! .....
  end

Keep in mind, controller testing may be removed in Rails 5.
https://github.com/rails/rails/issues/18950#issuecomment-77924771

Found this in rails issues:
https://github.com/rails/rails/issues/22742

A: For the benefit of anyone else coming here: For some reason the relevant helpers seem to not be documented in the current Rails guides, but I found this example from https://guides.rubyonrails.org/v4.1/testing.html
require 'test_helper'

class UserFlowsTest < ActionDispatch::IntegrationTest
  test "login and browse site" do
    # User david logs in
    david = login(:david)
    # User guest logs in
    guest = login(:guest)

    # Both are now available in different sessions
    assert_equal 'Welcome david!', david.flash[:notice]
    assert_equal 'Welcome guest!', guest.flash[:notice]

    # User david can browse site
    david.browses_site
    # User guest can browse site as well
    guest.browses_site

    # Continue with other assertions
  end

  private

    module CustomDsl
      def browses_site
        get "/products/all"
        assert_response :success
        assert assigns(:products)
      end
    end

    def login(user)
      open_session do |sess|
        sess.extend(CustomDsl)
        u = users(user)
        sess.https!
        sess.post "/login", username: u.username, password: u.password
        assert_equal '/welcome', sess.path
        sess.https!(false)
      end
    end
end

This technique still seemed to work in a Rails 5.1 app.

A: There is sample code at this URL:
http://api.rubyonrails.org/classes/ActionDispatch/IntegrationTest.html
http://guides.rubyonrails.org/testing.html#integration-testing-examples

This is NOT present in the edgeguides as of Jan 10th, 2016.


text:
Q: Accessing a Sound-File via NSBundle - pathForResource So I'm just trying to get into iOS Programming by going through some Online-Video-Courses. The problem is, that those are not up-to-date with Swift 3.
In the project I am at the moment it is required to import a Sound-File via the NSBundle-Framework using the following:
let path = NSBundle.mainBundle().pathForResource(name, ofType:)

The problem is, that I won't get this running in Swift 3 and I'm not able to get the right pieces off the Apple Documentation. So my Code looks the following:
import AVFoundation
import Foundation //don't know if this is right by 100 per cent

let path = NSBundle.mainBundle().pathForResource("btn", ofType: "wav")

But it seems like It doesn't even know the Class NSBundle, because Auto-Completion isn't even offering me any functions of NSBundle. I can't seem to find the right pieces which changed in Swift 3 to get this thing working. Anybody here who's able to help me with this?

A: I believe this is the ticket:
let path = Bundle.main.path(forResource: "btn", ofType: "wav")


text:
Q: Session Cookie Not Expiring in Android I have a mobile and a desktop version of my site, and I automatically redirect mobile users who arrive on the desktop site to the mobile site.
When a mobile user requests a specific url on the desktop site, the redirection is bypassed so they can go to the desktop version of the site for the remainder of the session. To facilitate this, we set a session cookie on the desktop site--if that cookie's present, we bypass redirection, if not, we redirect to mobile.
This method works correctly with iPhones and with Android user agent simulators on the desktop; however, with the 2 android phones we tested, the redirection bypass continues after the session ends and only stops after we specifically remove the cookies. We tried force quitting the browser, clearing the browser cache, and even powering the phone off entirely.
What ends a session in Android? Is it browser/device-specific?
Are session cookies supported in Android?
Is there any way to view cookie values and expiration details?
Is there another recommended method for getting the functionality described above across all devices?
If anyone has any good documentation describing the expected behaviors and recommendations, I'd really appreciate it!
Thanks!

A: I discovered some problems for myself in this field.
On an Xperia Ray the closing of the Browser app did not end the session. In a Sammsung tab it will.
To test, if a cookie is set on a mobile device, you should use something similar to 'weinre' (Adobe Phonegap uses it, too, I think)


text: Q: Is there any plugin to integrate Amazon s3 within Tinymce editor I'm searching for a plugin to use within Tinymce to upload and retrieve. the images and files from amazon bucket. Can anyone suggest a best plugin to accomplish my goal


text:
Q: Qooxdoo -- Is there a way to delete an offline store by key? In Qooxdoo, is there a way to delete an offline store by its key? 'resetModel' doesn't appear to get rid of the entry and I couldn't find any other options that looked applicable. Thanks!

A: Thats possible with the upcoming 2.0 release. We fixed a bug which covered exactly that:
http://bugzilla.qooxdoo.org/show_bug.cgi?id=6000


text:
Q: How to pass a geolocation value to a propertie on polymer app i'm working on a weather app with polymer v1. So i made a custom element called weather-app, i use iron-ajax to make a request for weather data but i can't pass the value for longitude and latitude to computed property to make a request based on current location. Can anyone give me a hand please? thanks in advance.
Edit: Updated code
<link rel="import" href="..\..\bower_components/polymer/polymer.html">

<dom-module id="weather-app">
  <style>
    :host {
      display: block;
    }
  </style>
  <template>
    <iron-ajax
            auto
            url='[[apiUrl]]'
            params='[[_computeParams(key, latitude, longitude, days)]]'
            handle-as="json"
            on-response="handleResponse"
            last-response={{ajaxDataResponse}}
            debounce-duration="300"></iron-ajax>
    <content>
    </content>
  </template>
  <script>
  (function() {
    Polymer({
      is: 'weather-app',

      properties: {

        apiUrl: {
          type: String,
          value: 'http://api.apixu.com/v1/forecast.json'
        },

        key: {
          type: Number,
          readOnly: true,
          value: '0742801303e94a37a2d35509150000'
        },

        latitude: {
          type: Number,
          notify: true,
          value: ''
        },

        longitude: {
          type: Number,
          notify: true,
          value: ''
        },

        days: {
          type: Number,
          value: '7'
        }
      },

      created: function(){

        function getLocation(){

          var geoOptions = {
            enableHighAccuracy: true,
            timeout: 30000,
            maximumAge: 27000
          };

          function geoSuccess(position){
            console.log(position.coords.latitude + ',' + position.coords.longitude);

            this.latitude = position.coords.latitude;
            this.longitude = position.coords.longitude;

            return this.latitude + ',' + this.longitude;
          }

          function geoError(){
            console.log('error');
          }

          navigator.geolocation.getCurrentPosition(geoSuccess, geoError, geoOptions);

        }

        getLocation();

      },

      _computeParams: function(key, latitude, longitude, days){
        return {
          key: key,
          q: latitude + ',' + longitude,
          days: days
        };
      },

      handleResponse: function(){
        console.log('handleResponse');
      }
    });
  })();
  </script>
</dom-module>

A: I believe the issue is in the current lack of ability of the parent to notify the child. This is due to the notify property being disabled.
latitude: {
  type: Number,
  notify: true,
  value: ''
},

longitude: {
  type: Number,
  notify: true,
  value: ''
},

Then in your geosuccess you need to use the "set" method of the element in order for polymer to properly notify other elements of the change.
  function geoSuccess(position){
    console.log(position.coords.latitude + ',' + position.coords.longitude);

    this.set('latitude', position.coords.latitude);
    this.set('longitude', position.coords.longitude);

    return this.latitude + ',' + this.longitude;
  }

As a bonus, when using computation functions simply use the [[ ]] notation. It won't give the app a huge boost, but it is better for performance.
Also, having the observer for _getCoordinates seems to lead me to believe that this function could be infinitely recursive if the position changes slightly each time, given that it sets the location variables again and again each call. Use the created/ready/attach methods to initialize the element with the geolocation position. Set the position. The observer you have in place is probably not necessary.


text:
Q: Can't set variable in string So I'm trying to send a dynamic email with PHP. Now here's what I have
    $postString = '{
            "key": "xxx",
            "message": {
                    "html": "this is the emails html content",
                    "text": "this is the emails text content",
                    "subject": "this is the subject",
                    "from_email": "email@email.com",
                    "from_name": "Joe",
                    "to": [
                    {
                            "email": "Joe@ Joe",
                            "name": "Joe@ Joe"
                    }
                    ],

                    "attachments": [

                    ]
            },
            "async": false
    }';

Now I want "html" to be a variable. So I did this
"html": $var,

Sadly that doesn't work. Not does {} or using single quotes. Any ideas? It gets picked up as a string, by the way.

A: Variables are not interpolated in strings delimited by single quotes. There are a few ways around this. The following example uses concatenation.
$postString = '{
        "key": "xxx",
        "html": "' . $var . '",
        "message": {
                "html": "this is the emails html content",
                "text": "this is the emails text content",
                "subject": "this is the subject",
                "from_email": "email@email.com",
                "from_name": "Joe",
                "to": [
                {
                        "email": "Joe@ Joe",
                        "name": "Joe@ Joe"
                }
                ],

                "attachments": [

                ]
        },
        "async": false
}';

To be honest with you, this would be a lot easier if you just used an array and then encoded it into JSON using json_encode().

A: As mentioned in my comment, this would work a lot better
$post = [
    'key' => 'xxx',
    'message' => [
        'html' => $var,
        'text' => 'this is the emails text content',
        'subject' => 'this is the subject',
        'from_email' => 'email@email.com',
        'to' => [
            ['email' => 'Joe@ Joe', 'name' => 'Joe@ Joe']
        ],
        'attachments' => []
    ],
    'async' => false
];

$postString = json_encode($post);

Obligatory legacy PHP note: If you're stuck on a PHP version lower than 5.4, you obviously can't use the shorthand array notation. Substitute [] with array() if that's the case.


text:
Q: How to solve "Could not find artifact com.ohadr:authentication-flows"? I've tried a:
mvn clean install -DskipTests -DdownloadSources=true
for building https://github.com/OhadR/Authentication-Flows.git
and I'm having:

...Failed to execute goal on project client: Could not resolve
  dependencies for project
  com.ohadr.auth-flows:client:war:1.0.0-SNAPSHOT: Could not find
  artifact com.ohadr:authentication-flows:jar:1.6.2-SNAPSHOT... The POM
  for com.ohadr:authentication-flows:jar:1.6.2-SNAPSHOT is missing, no
  dependency information available...

Next, I tried adding this repository:
     <repository>
       <id>central-maven</id>
       <name>Central Maven</name>
       <url>http://central.maven.org/maven2</url>
     </repository>

as well as downloading the jar (http://central.maven.org/maven2/com/ohadr/authentication-flows/1.6.0-RELEASE/authentication-flows-1.6.2-RELEASE.jar) and installing it manually:
 mvn install:install-file -DgroupId=com.ohadr \
   -DartifactId=authentication-flows \
   -Dversion=1.6.2-SNAPSHOT \
   -Dpackaging=jar -Dfile=authentication-flows-1.6.2-RELEASE.jar

Now I have:

...Failed to execute goal
  org.apache.maven.plugins:maven-compiler-plugin:3.1:compile
  (default-compile) on project client: Compilation failure: Compilation
  failure:...impl/CustomCreateAccountEndpoint.java:[6,38] package
  com.ohadr.auth_flows.endpoints does not exist

What am I doing wrong? Thank you.

A: The latest version (master branch) of the client-app depends on the "latest" version - the SNAPSHOT version - of authentication-flows JAR. SNAPSHOTs do not exist in maven-repository, and this is why you get the error.
You can either clone authentication-flows project as well and build it locally, or change the dependency in
the client-pom to version 1.6.1-RELEASE.
HTH


text:
Q: How to use destructuring assignment to define enumerations in ES6? You can use destructuring assignment to define enumerations in ES6 as follows:
var [red, green, blue] = [0, 1, 2];

Instead, I'd like the right hand side of the destructuring assignment to be dynamic. For example:
var MAX_ENUM_SIZE = 32;
var ENUM = new Array(MAX_ENUM_SIZE);
for (var i = 0; i < MAX_ENUM_SIZE; i++) ENUM[i] = i;

var [red, green, blue] = ENUM;

Unfortunately, this seems like a hack. What if I want a bigger enumeration in the future? Hence, I was thinking of using destructuring assignment with an iterator as follows:
var [red, green, blue] = enumeration(/* I don't want to specify size */);

However, I don't think it's possible to use destructuring assignment with iterators[citation needed]. Is there any way to accomplish this goal?

A: Use a generator

function* enumerator() {
  let i = 0;
  while (true) yield i++;
};

let [red,green,blue] = enumerator();
console.log(red, green, blue); // 0 1 2

let [a,b,c,d,e] = enumerator();
console.log(a,b,c,d,e); // 0 1 2 3 4

The generator is flexible making this pretty neat for implementing different types of enums – for example, these cute bitmask enums

function* bitmask() {
  let i = 0;
  while (i < 32) yield 1 << i++;
  throw Error("bitmask enumerator exceeds 32 bits");
}

let [R,W,X] = bitmask();

const read = p => (p & R) !== 0;
const write = p => (p & W) !== 0;
const exec = p => (p & X) !== 0;

{
  let p = R | W; // read and write only
  console.log("can read?", read(p));   // true
  console.log("can write?", write(p)); // true
  console.log("can exec?", exec(p));   // false
}

{
  let p = R | X; // read and execute only
  console.log("can read?", read(p));    // true
  console.log("can write?", write(p));  // false
  console.log("can exec?", exec(p));    // true
}

A: Note, each of the below prospective approaches could probably be improved.
The variables appear to be global at Question. You can create an array of strings referencing the variable which should be created, define the variable from the element of the array

// not technically destructuring, though achieves same result;
// that is, setting variables globally
for (var prop of (props = ["a", "b", "c", "d"])) {
  // set identifier globally
  self[prop] = props.indexOf(prop); // set a value for each `prop`
}
// delete `prop`, `props`
prop = props = void 0;

console.log(a, b, c, d);

Other approaches
using object destructuring

var {
  red, blue, green
} = (function(data, props) {
      for (var prop of Object.keys(props)) {
        data[props[prop]] = props.indexOf(props[prop]); // or some other value
      };
      return data
    }({}, ["red", "blue", "green"]));

console.log(red, blue, green);

using a list of variables to be

var props = ["red", "blue", "green"]; // list of variables to be
var [red, blue, green] = props.map((v, k) => k);
console.log(red, blue, green, "window[\"red\"]:", window[props[0]]);


text:
Q: Facebook Page Tab FB.login Uncaught TypeError: Cannot read property 'postMessage' of null Hello I'm creating a facebook page tab in which the owner of the facebook page will be able to sell anything.
So, when someone visits the page and click the checkout button the app calls the FB.login method and I get the following error.
Uncaught TypeError: Cannot read property 'postMessage' of null
  at ha (sdk.js:95)
  at Object.ba [as send] (sdk.js:95)
  at i.<anonymous> (sdk.js:105)
  at i.window.FB.i.enqueue (sdk.js:89)
  at sa (sdk.js:105)
  at i.<anonymous> (sdk.js:105)
  at i.window.FB.i.enqueue (sdk.js:89)
  at i.$JSONRPC4 (sdk.js:99)
  at i.<anonymous> (sdk.js:98)
  at la (sdk.js:142)

My code is here.
$('.login-checkout').on('click', function(event){
    event.preventDefault();
    checkLoginState('checkout');
});

function facebookLogin(action) {
  FB.login(function(response) {
        window.location = '/facebook?action=' + action + '&access_token=' + response.authResponse.accessToken;
  }, {scope: 'public_profile,email'});
}

function checkLoginState(action) {
  FB.getLoginStatus(function(response) {
    if(response.status === 'connected') {
        window.location = '/facebook?action=' + action + '&access_token=' + response.authResponse.accessToken;
    } else {
        facebookLogin(action);
    }
  });
}

The response.status of FB.getLoginStatus is not_authorized.
I use the javascript SDK


text:
Q: Objective-C: minimal init versus init that calls initWith? The method init in most classes does a minimal initialization, because if you need more complexity, more has-a related behaviors, then you need to use an initWith method. So why would anybody call an initWith from within the init method? I have seen this, it's even mentioned on Apple's website, but it seems to conceal behaviors that should be explicitly named.

A: Objects have what is called a "designated initializer", which are (there can be multiple) the init... methods that should completely initialize and configure the object for use.
Using a UIView as an example, it's designated initializer is initWithFrame:CGRect. This initializes the view with a frame (duh).
If init was the designated initializer, it would still have to define a frame, probably CGRectZero, and initWithFrame: would have to call init and then setFrame:, which means setting the frame twice. We don't like doing things twice when they can be done once.
That's why in many cases init is used instead as a shortcut when the properties in the other initializers can have a default value, usually some kind of zero. In the case of CGRect, CGRectZero is the zero-value.
Also, since frame is an important property of UIView, if your designated initializer was init, you'd see a lot of this:
UIView *view = [[UIView alloc] init];
view.frame = CGRectMake(0, 0, 20, 20)

It just makes sense to combine those two lines into one, that's why initWithFrame: is the designated initializer.


text:
Q: How do I get the number of rows of a data.frame in R? After reading a dataset:
dataset <- read.csv("forR.csv")

*

*How can I get R to give me the number of cases it contains?

*Also, will the returned value include of exclude cases omitted with na.omit(dataset)?

A: Briefly:

*

*Run dim(dataset) to retrieve both n and k, you can also use nrow(df) and ncol(df) (and even NROW(df) and NCOL(df) -- variants are needed for other types too).

*If you transform e.g. via dataset <- na.omit(dataset), then the cases are gone and are not counted.  But if you do e.g. summary(dataset) the NA cases are accounted for.

A: dataset will be a data frame. As I don't have forR.csv, I'll make up a small data frame for illustration:
set.seed(1)
dataset <- data.frame(A = sample(c(NA, 1:100), 1000, rep = TRUE),
                      B = rnorm(1000))

> head(dataset)
   A           B
1 26  0.07730312
2 37 -0.29686864
3 57 -1.18324224
4 91  0.01129269
5 20  0.99160104
6 90  1.59396745

To get the number of cases, count the number of rows using nrow() or NROW():
> nrow(dataset)
[1] 1000
> NROW(dataset)
[1] 1000

To count the data after omitting the NA, use the same tools, but wrap dataset in na.omit():
> NROW(na.omit(dataset))
[1] 993

The difference between NROW() and NCOL() and their lowercase variants (ncol() and nrow()) is that the lowercase versions will only work for objects that have dimensions (arrays, matrices, data frames). The uppercase versions will work with vectors, which are treated as if they were a 1 column matrix, and are robust if you end up subsetting your data such that R drops an empty dimension.
Alternatively, use complete.cases() and sum it (complete.cases() returns a logical vector [TRUE or FALSE] indicating if any observations are NA for any rows.
> sum(complete.cases(dataset))
[1] 993


text:
Q: Second order, two-point boundary value problem Solve the BVP
$$\begin{cases}
u''+a^2u=sin\pi x, \quad 0<x<1 \\
u(0)=1,\quad u(1)=-2
\end{cases}$$
for all $a\in\mathbb{R}$. What are the solutions in the cases $a=\pm\pi$?
Here, $'=\frac{du}{dx}$.
I know I need the characteristic function, which I get $r^2+a^2=0\implies r=\pm ai$. Then the complementary solution is,
$$u_c=C_1e^{ai*t}+C_2e^{-ai*t}$$

A: HINT:
Since the homogeneous solutions to the ODE $u''+\pi^2 u=\sin(\pi x)$ are of the form $u_h=A\sin(\pi x)+B\cos(\pi x)$, try complementary solutions of the form $u_c=Cx\sin(\pi x)+Dx\cos(\pi x)$.

Alternatively, use Laplace Transforms.

Alternatively, find the Green (or Green's) function for the problem
$$G''(x,x')+\pi^2 G(x,x')=\delta(x-x')$$
with $G(0,x')=1$, $G(1,x')=-2$, $G$ is continuous at $x=x'$, and $\left.\frac{\partial G}{\partial x}\right|_{x=x'^+}-\left.\frac{\partial G}{\partial x}\right|_{x=x'^-}=1$ and integrate.

A: If you do not know about integral transforms and Green's functions go and learn it. But Here is the way of avoiding this stuff for your concrete problem:
$$y''+a^{2}y=f(x)$$
You note that
$$y''+a^{2}y=\frac{d}{dt}(y'+iay)-ia(y'+iay)$$
Now let
$$\xi(x)=y'+iay$$
Hence
$$\xi'-ia\xi=f(x)$$
Using the integrating factor
$$\xi(x)=\frac{d}{dx}y+aiy=e^{aix}\Big\{\int_{0}^{x}f(z)e^{-aiz}dz+\xi_{0}\Big\}$$
Using the integrating factor the second time you get
$$y(x)=e^{-aix}\Big\{\int_{0}^{x}e^{2aiw}\Big\{\int_{0}^{w}f(z)e^{-aiz}dz+\xi_{0}\Big\}dw+x_{0}\Big\}$$
Then do the integrals)


text:
Q: Clang Tool: rewrite ObjCMessageExpr I want to rewrite all messages in my code,
I need replace only selectors, but I need be able to replace nested expressions
f. e. :
[super foo:[someInstance someMessage:@""] foo2:[someInstance someMessage2]];

I tried do it with clang::Rewriter replaceText and just generate new string,
but there is a problem: It would not be work if I change selectors length, because I replace nested messages with those old positions.
So, I assumed that I need to use clang::Rewriter ReplaceStmt(originalStatement, newStatement);
I am using RecursiveASTVisitor to visit all messages, and I want to copy those messages objects, and replace selectors:
How can I do that?
I tried use ObjCMessageExpr::Create but there is so meny args, I don't know how to get ASTContext &Context and ArrayRef<SourceLocation> SeLocs and Expr *Receiver parameters from the original message.
What is the proper way to replace selectors in nested messages using clang tool (clang tooling interface)?
Update:
Should I use ReplaceStmtWithStmt callback and ASTMatchFinder ?
Update:
I am using following function to rewrite text in file:
void ReplaceText(SourceLocation start, unsigned originalLength, StringRef string) {
    m_rewriter.ReplaceText(start, originalLength, string);
    m_rewriter.overwriteChangedFiles();
}

And I want to replace all messageExpr in code with new selector f.e:
how it was:
[object someMessage:[object2 someMessage:obj3 calculate:obj4]];

how it should be:
[object newSelector:[object2 newSelector:obj3 newSelector:obj4]];

I am using ReqoursiveASTVisitor:
bool VisitStmt(Stmt *statement) {
    if (ObjCMessageExpr *messageExpr = dyn_cast<ObjCMessageExpr>(statement)) {
         ReplaceMessage(*messageExpr)
    }
    return true;
}

I created method for generating new message expr string:
string StringFromObjCMessageExpr(ObjCMessageExpr& messageExpression) {
    std::ostringstream stringStream;
    const string selectorString = messageExpression.getSelector().getAsString();
    cout << selectorString << endl;
    vector<string> methodParts;
    split(selectorString, ParametersDelimiter, methodParts);
    stringStream << "[" ;
    const string receiver = GetStringFromLocations(m_compiler, messageExpression.getReceiverRange().getBegin(), messageExpression.getSelectorStartLoc());
    stringStream << receiver;
    clang::ObjCMessageExpr::arg_iterator argIterator = messageExpression.arg_begin();
    for (vector<string>::const_iterator partsIterator = methodParts.begin();
         partsIterator != methodParts.end();
         ++partsIterator) {
        stringStream << "newSelector";
        if (messageExpression.getNumArgs() != 0) {
            const clang::Stmt *argument = *argIterator;
            stringStream << ":" << GetStatementString(*argument) << " ";
            ++argIterator;
        }
    }
    stringStream << "]";
    return stringStream.str();
}

void ReplaceMessage(ObjCMessageExpr& messageExpression) {
    SourceLocation locStart = messageExpression.getLocStart();
    SourceLocation locEnd = messageExpression.getLocEnd();
    string newExpr = StringFromObjCMessageExpr(messageExpression);
    const int exprStringLegth = m_rewriter.getRangeSize(SourceRange(locStart, locEnd));
    ReplaceText(locStart, exprStringLegth, newExpr);
}

The problem occurs when I try to replace nested messages, like that:
[simpleClass doSomeActionWithString:string3 andAnotherString:string4];
[simpleClass doSomeActionWithString:str andAnotherString:str2];
[simpleClass doSomeActionWithString:@"" andAnotherString:@"asdasdsad"];
[simpleClass setSimpleClassZAZAZAZAZAZAZAZA:[simpleClass getSimpleClassZAZAZAZAZAZAZAZA]];

the result is:
[simpleClass newSelector:string3 newSelector:string4 ];
[simpleClass newSelector:str newSelector:str2 ];
[simpleClass newSelector:@"" newSelector:@"asdasdsad" ];
[simpleClass newSelector:[simpleClass getSimp[simpleClass newSelector]];

because messageExpression has "old" value of getLocStart(); and getLocEnd(); How can I fix it?

A: You can rewrite selector name by replacing only continuous parts of selector name. For example, replace only underlined parts
[object someMessage:[object2 someMessage:obj3 calculate:obj4]];
        ^~~~~~~~~~~          ^~~~~~~~~~~      ^~~~~~~~~

To achieve this you require only

*

*number of selector parts - ObjCMessageExpr::getNumSelectorLocs()

*their locations - ObjCMessageExpr::getSelectorLoc(index)

*their lengths - ObjCMessageExpr::getSelector().getNameForSlot(index).size().

Overall, you can rewrite ObjCMessageExpr with the following RecursiveASTVisitor:
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Rewrite/Core/Rewriter.h"

namespace clang_tooling
{

using clang::SourceLocation;

class RewritingVisitor : public clang::ASTConsumer,
                         public clang::RecursiveASTVisitor<RewritingVisitor>
{
public:
    // You can obtain SourceManager and LangOptions from CompilerInstance when
    // you are creating visitor (which is also ASTConsumer) in
    // clang::ASTFrontendAction::CreateASTConsumer.
    RewritingVisitor(clang::SourceManager &sourceManager,
                     const clang::LangOptions &langOptions)
        : _sourceManager(sourceManager), _rewriter(sourceManager, langOptions)
    {}

    virtual void HandleTranslationUnit(clang::ASTContext &context)
    {
        TraverseDecl(context.getTranslationUnitDecl());
        _rewriter.overwriteChangedFiles();
    }

    bool VisitObjCMessageExpr(clang::ObjCMessageExpr *messageExpr)
    {
        if (_sourceManager.isInMainFile(messageExpr->getLocStart()))
        {
            clang::Selector selector = messageExpr->getSelector();
            for (unsigned i = 0, end = messageExpr->getNumSelectorLocs();
                 i < end; ++i)
            {
                SourceLocation selectorLoc = messageExpr->getSelectorLoc(i);
                _rewriter.ReplaceText(selectorLoc,
                                      selector.getNameForSlot(i).size(),
                                      "newSelector");
            }
        }
        return Base::VisitObjCMessageExpr(messageExpr);
    }

private:
    typedef clang::RecursiveASTVisitor<RewritingVisitor> Base;

    clang::SourceManager &_sourceManager;
    clang::Rewriter _rewriter;
};

} // end namespace clang_tooling


text:
Q: How to conserve the levels when subsetting for a vector? I've seen a solution for data frames which can definitely be applied in my case (just pop everything into a temporary data frame and do as the solution suggests, but does there exist a method just for vectors?
For example:
x = c('this', 'that', 'here', 'there')
data = c(0.1, 0.2, 0.5, 0.12)
categ = c('cat1', 'cat2', 'cat1', 'cat3')

So after having taken suggestions from comments, this is what I am trying to achieve. Let's take the data I present for example.
I want to yield the vectors
cat1 = c(0.1,0.5)
cat2 = c(0.2)
cat3 = c(0.12)

I want the names to be x and the levels to be categ. The way I want to retrieve these vectors is subsetting my data. How do I achieve this?

A: I'll be honest, I am not sure what you're trying to accomplish. I believe it is something like the following:
x = as.factor(c('this', 'that', 'here', 'there'))
x = factor(x,
           levels = ("0.1", "0.2", "0.5", "0.12"),
           labels = ("cat1", "cat2", "cat3", "cat4")
    )


text:
Q: Stability of a GI/G/1 queue with $\rho=1$? The final theorem in Chapter 19 of Meyn and Tweedie's Markov Chains and Stochastic Stability tells us that if the mean inter-arrival time $\lambda$ of a GI/G/1 queue is greater than its mean service time $\mu$, then the queue is positive Harris recurrent.

Question: What stability results are known for a continuous-time GI/G/1 queue for which $\lambda=\mu$, and in which the variances of the inter-arrival time and service time random variables are positive? Is it known that such a queue cannot be positive Harris recurrent? Regular?

The Lyapunov function used in Meyn-Tweedie, which is an expected hitting time, is not going to work for $\lambda=\mu$.
I searched in Morozov and Delgado's survey paper, which claims that "stability conditions of the classical GI/G/m queue are well known", and in other surveys, but found no mention of the $\lambda=\mu$ case there.

A: After some research I found the answer; essentially contained in cardinal's comment. Please let me know if you have anything to add.
For the Lindley process $Z_{n+1} = \max(0, Z_n+ U_n)$ with $\rho=1$, two results seem to be known:

*

*$\frac{Z_n}{\sqrt{n}}$ converges to a normal random variable with mean $0$ and variance $\sigma^2=\mathrm{Var}(U_n)$, where $\sigma\in(0,\infty)$. This is in Billingsley, Chapter 2, cited slightly inaccurately in Asmussen (condition $\sigma>0$ omitted), Proposition X.1.2.

*The expected first hitting time is 1 if the interarrival time equals the service time with probability 1 (`deterministic case'), and is infinite otherwise. This is in Kalashnikov, Mathematical Methods in Queueing Theory Section 5.3.3. It is mentioned slightly inaccurately in Asmussen, Proposition X.1.3.