text:
Q: Is die function accept only strings? this code works:
if (isset($db->error)) {
    echo $db->error;
}

This code in not working:
if (isset($db->error)) {
    die($db->error);
}

This is my DB class:
class Db {

    private $db,
            $error;

    public function __construct() {
        return $this->db = new mysqli(DB_SERVER, DB_USER, DB_PASS, D_NAME);
        if ($this->db->connect_error) {
            $this->error = $this->db->connect_error;
        }
    }

}

"D_NAME" is wrong so an error appears but I didn't kill the page, content still appear after the error. Why? Thanks!

A: The if block in the constructor is never executed, because you are returning $this->db:
public function __construct() {
        return $this->db = new mysqli(DB_SERVER, DB_USER, DB_PASS, D_NAME);
        // the lines after return will never be executed!
}

This is the first reason why the $db->error is unset.
The second reason is that the $error member is private, which means that you are not allowed to access this property directly. So you should make it accessible in one of the following ways (at least):

*

*make it public;

*implement the __get and __isset magic methods;

*implement a getter method.

Using public $error
class Db {
  private $db;
  public $error;

  public function __construct() {
    $this->db = new mysqli('localhost', 'sss3', 'a4J1uQzQCasD', 's3_small');
    if ($this->db->connect_error) {
      $this->error = $this->db->connect_error;
    }
    return $this->db;
  }

}

$db = new Db;
if (isset($db->error)) {
  die($db->error);
}

echo 'xxx', PHP_EOL;

Using __isset and __get magic methods
class Db {
  private $db;
  private $error;

  public function __construct() {
    $this->db = new mysqli('localhost', 'sss3', 'a4J1uQzQCasD', 's3_small');
    if ($this->db->connect_error) {
      $this->error = $this->db->connect_error;
    }
    return $this->db;
  }

  public function __get($key) {
    if ($key === 'error') {
      return $this->error;
    }
  }

  public function __isset($key) {
    if ($key === 'error') {
      return isset($this->error);
    }
  }

}

$db = new Db;
if (isset($db->error)) {
  die($db->error);
}

echo 'xxx', PHP_EOL;

Implementing a getter method
A getter method is just a method returning value of a private member. In our case it is $error. So you might leave it private, but add a method to access its value. For instance:
public function getError() {
  return $this->error;
}


text:
Q: Let T(n) be defined by the following recurrence relation Let T(n) be defined by the following recurrence relation
$\begin{equation}
\begin{cases}
T(0) = T(1) = 1 \\
T(n) = T(n−1) + T(n−2) + 1 \quad for \quad n ≥ 2
\end{cases}
\end{equation}$
Show that T(n) = $2F_n − 1$  for $n \geq 0$,
where
$F_n$
is the
$n$'th Fibonacci number, i.e.
$\begin{equation}
\begin{cases}
F_0 = F_1 = 1 \\
F_n = F_{n−1} + F_{n − 2} \quad for \quad n ≥ 2
\end{cases}
\end{equation}$
I'm attempting to do this by induction, but perhaps it might not be the best route, I'm not entirely sure. I get stuck using that method. Any insight?

A: From the first equalities,
$$2T(0)-1=2T(1)-1=1$$
and from the recurrence
$$2T(n)-1=2(T(n-1)+T(n-2)+1)-1=2T(n-1)+2T(n-2)-1,$$
and you recognize the definition of the Fibonacci numbers.

redpajama_set_name: RedPajamaStackExchange


text:
Q: docker toolbox, can connect to containers launched with kitematic but not with the cli? I have docker toolbox 1.8.2c installed on my Mac running yosemite. If I launch hello-world-nginx from the docker hub in Kitematic, I can connect to its TCP port without an issue.
When trying to do the same thing from the CLI, I can't connect. Why?
Here is what I am running on the  docker CLI, which looks to me to be pretty standard:
docker run -d -i -t -P kitematic/hello-world-nginx /bin/sh

In the case above, docker ps shows that port 80 is mapped to 0.0.0.0:32769. So I try and connect on 192.168.99.100:32769 (that's my docker machine IP) and I can't connect.
I want to use the CLI so I can set the hostname/fqdn on the container, which it doesn't look like Kitematic supports. Here is another thing I tried, with the IP address of my docker machine in the args:
docker run -d -i -t -p 192.168.99.100:32769:80 -h nginx.example.com kitematic/hello-world-nginx /bin/sh

This doesn't work either.
In each case, the container starts successfully and I can attach to it with out an issue.
What am I doing wrong?

A: I had the same problem, but in windows 10 pro witn the same image  kitematic/hello-world-nginx. Kitematic was open a wep page by default with Internet Explorer and the message was inmediatetly can't connect, later I tried with another web browers, chrome, and it worked. maybe if you try with another web browser, this problem can be solved.


text:
Q: How to use unzip in linux terminal SSH? I just zip a file in my remote server using the command "unzip" in the SSH terminal. It works fine but leaves a new folder called "__MACOSX".
Is there any way to make that the command delete this file after the unzip?

A: This is an extra folder that OSX computers make, they are hidden on OSX.
To exclude the folder from the extraction do:
unzip ZipName.zip -x __MACOSX/*

Replace "ZipName" with the name of your zip. The important part is matching the folder which is made up of two underscores then MACOSX, /* so it doesn't extract the hidden file in that folder as well as the folder.


text:
Q: Java cannot find constructor Like most new programmers I have a small but significant issue that i cannot figure out.
My program will not pull my constructor. I have tried quite a few different ways and cant seem to figure it out. Any help would be greatly appreciated.

Error
EmployeeTest.java:13: cannot find symbol
symbol  : constructor Employee()
location: class Employee
    Employee x = new Employee();
                 ^
EmployeeTest.java:14: cannot find symbol
symbol  : constructor Employee()
location: class Employee
    Employee y = new Employee();

public class Employee
{
private double salaryValue; // variable that stores monthlySalary
private String firstName; // instance variable that stores first name
private String lastName; // variable that stores last name

 public Employee( String firstNameParameter , String lastNameParameter ,  double          salaryValueParameter )
{

    if ( salaryValueParameter < 0.0 ) // validate monthlySalary > 0.0
    salaryValue = 0.0; // if not salary is intitalized to default

    else

      firstName = firstNameParameter;
      lastName = lastNameParameter;
      salaryValue = salaryValueParameter;
}

 public class EmployeeTest
{
public static void main( String[] args )
{
String temp;
Double temp2;
Double temp3;

Employee x = new Employee();
Employee y = new Employee();

A: You're calling a constructor without any parameters:
new Employee()

This causes Java to look for this default constructor in your class:
public Employee() {}

Which it can't find because you have a custom constructor with parameters, hence the error. Your Employee class only has this constructor:
public Employee(String, String, double) {}

You should either pass parameters to the constructors in your new statements, or declare that default parameter-less constructor explicitly and implement it (as an overload of your other constructor, perhaps to pass in default values or something).

A: By default, a class has a no-arg constructor. I.e.
 public Employee()

If you later and go add your own constructor.. i.e.
 public Employee( String name )

Then the listed ones are the only ones you can use.
If you still want to call the default one, add it back in.
public Employee()

A: Because you've added a constructor that takes 3 arguments, the Employee class no longer has a default constructor - one which takes no arguments. So you can't do this:
Employee x = new Employee();

and you must include 3 arguments:
Employee x = new Employee("firstname", "lastname", 123.45);

If you want to instantiate an Employee without supplying any parameters, you must add a no-argument constructor:
public Employee() {
}

You can read more about default constructors in section 8.8.9 of the Java Language Specification.

A: You have to add a default public constructor:
public void Employee();

A: You have to define your default constructor. When you implement a custom one, the default is lost
public class Employee{
   public Employee(){}
...
}

Here is a short article on constructors

A: Your constructor defines
    String firstNameParameter , String lastNameParameter ,  double          salaryValueParameter
as parameters.  When you call
    Employee x = new Employee();
you are calling a non-existant constructor.  Try the following instead:
Employee x = new Employee('David', 'Jones', 50000);

A: You are attempting to create a new class with an empty constructor, but the only constructor you have declared is one requiring parameters.  You should probably try something like:
Employee x = new Employee("Bob", "Jones", "100.0");

Or, declare a default constructor:
public Employee() {
    //do cool stuff here
}

Hope that helps.

A: You provide only a constructor with three arguments, but you try to call a constructor without arguments. Such a constructur is included automatically by the compiler but only if your class has no other constructors.
So you have two options:

*

*Include another constructor without arguments

*call the constructor with the right number and types of arguments


text:
Q: Extract JSON tags and build a new Json Similar to this question I want to extract some pieces of a JSON and build a new one just with the info I need.
I tried with this code:
wanted_milestones_ids =  [ch_epic['milestone_id'],ch_epic['stats']['num_points'] for ch_epic in ch_epics if ch_epic['milestone_id'] is not None and set(CLUBHOUSE_PROJECT_IDS).intersection(ch_epic['project_ids']) and ch_epic['id'] == 16919]

Filter is working good, and actually I can get the values. The problem is that I obtain ALL values or ONE value, I need some of them, that's why I tried with: "ch_epic['milestone_id'],ch_epic['stats']['num_points']" But there was an error.
How can I achieve this task? Below is the original JSON code and I want to extract: Id, milestone_id and num_points.
{
    "archived": false,
    "started": false,
    "entity_type": "epic",
    "labels": [
      {
        "entity_type": "label",
        "id": 1305552,
        "created_at": "2018-10-01T16:37:13Z",
        "updated_at": "2018-11-13T14:25:23Z",
        "name": "random name",
        "color": "#e885d1",
        "external_id": null,
        "archived": false
      }
    ],
    "external_tickets": [],
    "mention_ids": [],
    "member_mention_ids": [],
    "project_ids": [
      2022
    ],
    "completed_at_override": null,
    "started_at": null,
    "completed_at": null,
    "name": "Randome Name",
    "completed": false,
    "state": "to do",
    "milestone_id": 195343762,
    "requested_by_id": "Goofy",
    "epic_state_id": 50230002327020,
    "started_at_override": null,
    "updated_at": "2019-08-08T21:19:00Z",
    "group_mention_ids": [],
    "support_tickets": [],
    "follower_ids": [
      "Donald"
    ],
    "owner_ids": [],
    "external_id": null,
    "id": 16965,
    "position": 961,
    "deadline": null,
    "stats": {
      "num_points_done": 1,
      "average_cycle_time": 32223231706,
      "num_stories_unstarted": 2,
      "last_story_update": "2019-10-02T12:24:08Z",
      "num_points_started": 1,
      "num_points_unstarted": 3,
      "num_stories_started": 1,
      "num_stories_unestimated": 2,
      "average_lead_time": 3305323270,
      "num_points": 5,
      "num_stories_done": 2
    },
    "created_at": "2019-03-28T16:39:50Z"
  }

A: I am not sure about why you are overcomplicating this...
Maybe I missed something?
Here's a simple extraction:
import json

data = r'{ "archived": false, "started": false, "entity_type": "epic", "labels": [ { "entity_type": "label", "id": 1305552, "created_at": "2018-10-01T16:37:13Z", "updated_at": "2018-11-13T14:25:23Z", "name": "random name", "color": "#e885d1", "external_id": null, "archived": false } ], "external_tickets": [], "mention_ids": [], "member_mention_ids": [], "project_ids": [ 2022 ], "completed_at_override": null, "started_at": null, "completed_at": null, "name": "Randome Name", "completed": false, "state": "to do", "milestone_id": 195343762, "requested_by_id": "Goofy", "epic_state_id": 50230002327020, "started_at_override": null, "updated_at": "2019-08-08T21:19:00Z", "group_mention_ids": [], "support_tickets": [], "follower_ids": [ "Donald" ], "owner_ids": [], "external_id": null, "id": 16965, "position": 961, "deadline": null, "stats": { "num_points_done": 1, "average_cycle_time": 32223231706, "num_stories_unstarted": 2, "last_story_update": "2019-10-02T12:24:08Z", "num_points_started": 1, "num_points_unstarted": 3, "num_stories_started": 1, "num_stories_unestimated": 2, "average_lead_time": 3305323270, "num_points": 5, "num_stories_done": 2 }, "created_at": "2019-03-28T16:39:50Z" }'

data = data.replace('\n', '')
json_data = json.loads(data)
id = json_data['labels'][0]['id']
milestone_id = json_data['milestone_id']
num_points = json_data['stats']['num_points']

print("id:\t\t{}".format(id))
print("milestone_id:\t{}".format(milestone_id))
print("num_points:\t{}".format(num_points))

output = {'id':id, 'milestone_id':milestone_id, 'num_points':num_points}
final_output = json.dumps(output)

print("\njson:\t\t" + final_output)

Output
id:             1305552
milestone_id:   195343762
num_points:     5

json:           {"num_points": 5, "id": 1305552, "milestone_id": 195343762}

A: You could try to use the JSON package.
If you have the JSON saved in a file called example.json in the same directory as your python script. You could use the following code to get the desired fields.
import json

with open("example.json", "r") as read_file:
    data = json.load(read_file)

output_file = json.dumps({'id':data['id'], 'milestone_id':data['milestone_id'], 'num_points':data['stats']['num_points']})

A: Adapt it to multiple values:
import json

data = r'[{ "archived": false, "started": false, "entity_type": "epic", "labels": [ { "entity_type": "label", "id": 1305552, "created_at": "2018-10-01T16:37:13Z", "updated_at": "2018-11-13T14:25:23Z", "name": "random name", "color": "#e885d1", "external_id": null, "archived": false } ], "external_tickets": [], "mention_ids": [], "member_mention_ids": [], "project_ids": [ 2022 ], "completed_at_override": null, "started_at": null, "completed_at": null, "name": "Randome Name", "completed": false, "state": "to do", "milestone_id": 195343762, "requested_by_id": "Goofy", "epic_state_id": 50230002327020, "started_at_override": null, "updated_at": "2019-08-08T21:19:00Z", "group_mention_ids": [], "support_tickets": [], "follower_ids": [ "Donald" ], "owner_ids": [], "external_id": null, "id": 16965, "position": 961, "deadline": null, "stats": { "num_points_done": 1, "average_cycle_time": 32223231706, "num_stories_unstarted": 2, "last_story_update": "2019-10-02T12:24:08Z", "num_points_started": 1, "num_points_unstarted": 3, "num_stories_started": 1, "num_stories_unestimated": 2, "average_lead_time": 3305323270, "num_points": 5, "num_stories_done": 2 }, "created_at": "2019-03-28T16:39:50Z" },{ "archived": false, "started": false, "entity_type": "epic", "labels": [ { "entity_type": "label", "id": 1305552, "created_at": "2018-10-01T16:37:13Z", "updated_at": "2018-11-13T14:25:23Z", "name": "random name", "color": "#e885d1", "external_id": null, "archived": false } ], "external_tickets": [], "mention_ids": [], "member_mention_ids": [], "project_ids": [ 2022 ], "completed_at_override": null, "started_at": null, "completed_at": null, "name": "Randome Name", "completed": false, "state": "to do", "milestone_id": 195343762, "requested_by_id": "Goofy", "epic_state_id": 50230002327020, "started_at_override": null, "updated_at": "2019-08-08T21:19:00Z", "group_mention_ids": [], "support_tickets": [], "follower_ids": [ "Donald" ], "owner_ids": [], "external_id": null, "id": 16965, "position": 961, "deadline": null, "stats": { "num_points_done": 1, "average_cycle_time": 32223231706, "num_stories_unstarted": 2, "last_story_update": "2019-10-02T12:24:08Z", "num_points_started": 1, "num_points_unstarted": 3, "num_stories_started": 1, "num_stories_unestimated": 2, "average_lead_time": 3305323270, "num_points": 5, "num_stories_done": 2 }, "created_at": "2019-03-28T16:39:50Z" }]'

data = data.replace('\n', '')
json_data = json.loads(data)
output = []
for milestone in json_data:
    id = milestone['labels'][0]['id']
    milestone_id = milestone['milestone_id']
    num_points = milestone['stats']['num_points']

# print("id:\t\t{}".format(id))
# print("milestone_id:\t{}".format(milestone_id))
# print("num_points:\t{}".format(num_points))

    output.append({'id':id, 'milestone_id':milestone_id, 'num_points':num_points})
final_output = json.dumps(output)
print("\njson:\t\t" + final_output)

output:
json: [{"id": 1305552, "milestone_id": 195343762, "num_points": 5}, {"id": 1305552, "milestone_id": 195343762, "num_points": 5}]


text:
Q: Given two 3D points and a length per point, find a shared endpoint closest to a given reference point I am reposting this because my original was really sloppy.
I am given the following information:
Two 3D points $P_1$ and $P_2$ that are starting points of two line segments in $3D$
The lengths $L_1$ and $L_2$ of the two line segments
A reference point $P_r$
With all this information, I need to find a shared endpoint of the two line segments with starting points $P_1$ and $P_2$ and with lengths $L_1$ and $L_2$ that is closest to $P_r$. The points can have any coordinates but cannot move from said coordinate, and their lengths can orient in any way. As for $P_r$, it cannot move, but it can have any length or direction and can be anywhere in space even within the intersection area.
What I know:
A sphere would perfectly represent all possible orientations of a line, given its starting point, so the information provided above can now become:
A Sphere $S_1$ with Center $C_1 = P_1$ and Radius $R_1 = L_1$
A Sphere $S_2$ with Center $C_2 = P_2$ and Radius $R_2 = L_2$
I followed this article, which seemed to be relevant up to Equation 9: https://mathworld.wolfram.com/Sphere-SphereIntersection.html
I am stuck past this point. I know that the plane of intersection lies in the $y^2+z^2$ plane and that I'm supposed to project the reference point onto that plane to get my resulting endpoint.
What I have gathered from other tutorials is that the plane equation provides a vector $(0, 1, 1)$ because $x$ is not on the plane and the $1$'s are the invisible $1$ coefficients on $y$ and $z$.From there I just use the projection equation, but my answers never come out correct.
I have found this on stack overflow which is identical in terms of what they are asking me but I cannot get their sample input to equate to the sample output: https://stackoverflow.com/questions/59599652/find-common-endpoint-of-two-3d-line-segments

A: Algorithm of finding closest shared point in general case. This is realization of my short comment.
If distance $L=P_1P_2$ is greater than $L_1+L_2$ there are no shared point at all.
If $L=L_1+L_2$ there is only one shared point and it is the closest as unique. Shared point is located in the edge $P_1P_2$ at distance $L_1$ from $P_1$, this allows find it coordinates easily as $x_1+\frac{L_1}{L}(x_2-x_1)$ and so on.
Let $P_1(x_1;y_1;z_1)$, $P_2(x_2;y_2;z_2)$ and $L=\sqrt{(x_2-x_1)^2+(y_2-y_1)^2+(z_2-z_1)^2} < L_1+L_2$.
Then equation of sphere $C_1$ is
$$(x-x_1)^2+(y-y_1)^2+(z-z_1)^2=L_1^2$$
Equation of sphere $C_2$ is
$$(x-x_2)^2+(y-y_2)^2+(z-z_2)^2=l_2^2$$
Subtracting equation of $C_2$ from equation of $C_1$ one can get
$$(x-x_1)^2+(y-y_1)^2+(z-z_1)^2-(x-x_2)^2-(y-y_2)^2-(z-z_2)^2=L_1^2-L_2^2$$
Expansion and elimination gives
$$2x(x_2-x_1)+2y(y_2-y_1)+2z(z_2-z_1)+L_2^2-L_1^2=0$$
This is equation of plane $\alpha$ containing circle $C$ of intersection of $C_1$ and $C_2$.
Center of circle $C$ is located in line $P_1P_2$ and is located in the plane. $\alpha$. Let this center has coordinates $(x_3,y_3,z_3)$ such that $$x_3=x_1+(x_2-x_1)t,y_3=y_1+(y_2-y_1)t,z_3=z_1+(z_2-z_1)t$$
Then $$2x_3(x_2-x_1)+2y_3(y_2-y_1)+2z_3(z_2-z_1)+L_2^2-L_1^2=0$$
$$2((x_2-x_1)^2+(y_2-y_1)^2+(z_2-z_1)^2)t=\\L_1^2-L_2^2-2x_1(x_2-x_1)-2y_1(y_2-y_1)-2z_1(z_2-z_1)$$
$$t=\frac{L_1^2-L_2^2-2x_1(x_2-x_1)-2y_1(y_2-y_1)-2z_1(z_2-z_1)}{2((x_1-x_1)^2+(y_2-y_1)^2+(z_2-z_1)^2)}$$
After calculation of $t$ we also know $x_3,y_3,z_3$.
Distance between center of circle and point $P_1$ is equal
$|t|L$. Then radius of circle is $R=\sqrt{L_1^2-t^2L^2}$.
Vector $\vec{P_1P_2}=(x_2-x_1;y_2-y_1;z_2-z_1)$ is normal to the plane. There are two possible options $\vec{P_1P_2}\parallel Ox$ or $\vec{P_1P_2}\nparallel Ox$. In first case we can take $\vec{a}=(0;R;0)$, $\vec{b}=(0;0;R)$. In second case we can take $\vec{a_1}=(1;0;0)\times\vec{P_1P_2}$, $\vec{b_1}=\vec{a_1}\times\vec{P_1P_2}$, $\vec{a}=R\frac{\vec{a_1}}{\sqrt{\vec{a_1}\cdot\vec{a_1}}}$, $\vec{b}=R\frac{\vec{b_1}}{\sqrt{\vec{b_1}\cdot\vec{b_1}}}$. In both cases $\vec{a}\perp \vec{P_1P_2}$, $\vec{b}\perp \vec{P_1P_2}$, $\vec{a}\perp\vec{b}$, $|\vec{a}|=|\vec{b}|=R$.
Then every point of circle $C$ is given by
$$x=x_3+a_x\cos u+b_x\sin u,y=y_3+a_y\cos u+b_y\sin u,z=z_3+a_z\cos u+b_z\sin u$$
Then square of distance from point of circle to point $P_r=(x_r;y_r;z_r)$ is equal
$$L_r^2=(x_3-x_r+a_x\cos u+b_x\sin u)^2+(y_3-y_r+a_y\cos u+b_y\sin u)^2+(z_3-z_r+a_z\cos u+b_z\sin u)^2$$
$$L_r^2=(x_3-x_r)^2+(y_3-y_r)^2+(z_3-z_r)^2+(a_x^2+a_y^2+a_z^2)\cos^2 u+\\(b_x^2+b_y^2+b_z^2)\sin^2 u+2(a_x b_x+a_y b_y+a_z b_z) \cos u \sin u+\\
2((x_3-x_r)a_x+(y_3-y_r)a_y+(z_3-z_r)a_z)\cos u+\\
2((x_3-x_r)b_x+(y_3-y_r)b_y+(z_3-z_r)b_z)\sin u$$
$|\vec{a}|=|\vec{b}|=R$, $\vec{a}\cdot\vec{b}=0$, then
$$L_r^2=(x_3-x_r)^2+(y_3-y_r)^2+(z_3-z_r)^2+R^2+\\
2((x_3-x_r)a_x+(y_3-y_r)a_y+(z_3-z_r)a_z)\cos u+\\
2((x_3-x_r)b_x+(y_3-y_r)b_y+(z_3-z_r)b_z)\sin u$$
Let $A=2((x_3-x_r)a_x+(y_3-y_r)a_y+(z_3-z_r)a_z)$, $B=2((x_3-x_r)b_x+(y_3-y_r)b_y+(z_3-z_r)b_z)$, then
$$L_r^2=(x_3-x_r)^2+(y_3-y_r)^2+(z_3-z_r)^2+R^2+A\cos u+B\sin u$$
Let $X=A\cos u+B\sin u$, then
$$X^2=A^2\cos^2u+B^2\sin^2u+2AB\sin u \cos u=\\
A^2+B^2-(A^2\sin^2u+B^2\cos^2u-2AB\sin u \cos u)=\\
A^2+B^2-(A\sin u-B\cos u)^2 \leq A^2+B^2$$
Then $X\geq-\sqrt{A^2+B^2}$. Consider $u_1$ such that $$\cos u_1=-\frac{A}{\sqrt{A^2+B^2}},\sin u_1=-\frac{B}{\sqrt{A^2+B^2}}$$
Then at $u=u_1$:
$$X=A\cos u_1+B\sin u_1=-\frac{A^2+B^2}{\sqrt{A^2+B^2}}=-\sqrt{A^2+B^2}$$
$u=u_1$ makes $X$ minimal then $L_r^2=(x_3-x_r)^2+(y_3-y_r)^2+(z_3-z_r)^2+R^2$ is also minimal.
Then closest shared point is point given by
$$x=x_3+a_x\cos u_1+b_x\sin u_1,y=y_3+a_y\cos u_1+b_y\sin u_1,z=z_3+a_z\cos u_1+b_z\sin u_1$$

A: First, find the distance between the two points $P_1$ and $P_2$
$d = \| P_1 P_2 \| $
Now form the triangle with sides $d, L_1, L_2$.  The intersection of the two spheres is a circle with radius $R$ where
$R = L_1 \sin(\phi) $
where $\phi = \cos^{-1} \left( \dfrac{L_1^2 + d^2 - L_2^2}{2 L_1 d } \right) $
If $V = \dfrac{P_2 - P_1}{d} $ , then the center of the circle is $C$ where
$ C = P_1 + L_1 \cos(\phi)  V $
Form the vector
$ U = P_r - C $
Project $P_r$ on the plane of the circle of intersection as follows
$ U' = C + U - (U \cdot V) V $
Form the vector
$W = U' - C $
Scale it, so that it has magnitude $R$
$W' = \dfrac{R}{\| W \| } W $
Now the desired point is
$ P_3 = C + W' $


text:
Q: multiline field in csv (logstash) I am trying to make the multiline field for csv file work in logstash.
But the multiline for a field is not working.
My log stash.conf content is:
input {

     file {
         type => "normal"
         path => "/etc/logstash/*.csv"
         start_position => "beginning"
         sincedb_path => "/dev/null"
         codec => multiline {
                        pattern => "."
                        negate => true
                        what => "previous"
        }
     }
}

filter {
  if [type] == "normal" {
     csv {
        separator => ","
        columns => ["make", "model", "doors"]
     }
     mutate {convert => ["doors","integer"] }

  }
}

output {
   if [type] == "normal" {
      elasticsearch {
                   hosts => "<put_local_ip>"
                   user => "<put_user>"
                   password => "<put_password>"
                   index => "cars"
                   document_type => "sold_cars"
      }
      stdout {}
   }

}

.csv with multiple line (in quotes) for a field make is:
make,model,doors
mazda,mazda6,4
"mitsubishi
4000k", galant,2
honda,civic,4

After I run "logstash -f /etc/logstash/logstash.conf"
I am getting parse failure, from the logs:
{
          "tags" => [
        [0] "_csvparsefailure"
    ],
    "@timestamp" => 2020-07-13T19:13:11.339Z,
          "type" => "normal",
          "host" => "<host_ip_greyedout>",
       "message" => "\"mitsubishi",
      "@version" => "1",
          "path" => "/etc/logstash/cars4.csv"
}


text:
Q: Local MongoDB server refuses to start I've been struggling to start my first MongoDB server for a few hours now and a lot of answers here suggested that I should turn off my firewall. I did that but the issue unfortunately is still present. At first, I thought that mongod command was completely fine and the problem occurs when I run the mongo command but after looking up some docs, the output I receive in the command prompt when I run mongod is nothing like what I see on the Internet, which makes me guess that the problem is not really from the mongo command.
Since the output of the console may be too large and unreadable here, I will attach photos of it but if a copyable snippet is required or wanted, I will add one.
Running the mongo --version and mongod commands:

Running the mongo command:

Any help and advice is appreciated!


text:
Q: grep should find a hex value in a file but doesn't Here is the beginning of a file:
# hexdump -n 550 myFile
0000000 f0f2 f5f0 f7f9 f1f1 f1f0 f0f0 e3f1 f3c8
0000010 f3f5 0000 0000 000c 0000 0000 0000 000c
0000020 0000 0c00 0000 0000 0000 0c00 0000 0000
0000030 000c 0000 0000 0000 000c 0000 0c00 0000
0000040 0000 0000 0c00 0000 0000 000c 0000 0000
0000050 0000 000c 0000 0c00 0000 0000 0000 0c00
0000060 0000 0000 000c 0000 0000 0000 000c 0000
*
00000b0 0000 0000 000c 0000 0000 0000 0000 0000
00000c0 0000 0000 0000 0c00 0000 0000 0000 0c00
00000d0 0000 0000 000c 0000 0000 0000 000c 0000
00000e0 0c00 0000 0000 0000 0c00 0000 0000 000c
00000f0 0000 0000 0000 000c 0000 0c00 0000 0000
0000100 0000 0c00 0000 0000 000c 0000 0000 0000
0000110 000c 0000 0c00 0000 0000 0000 0c00 0000
0000120 0000 0000 0c00 0000 0000 0000 0c00 0000
*
0000160 0000 0000 0c00 0000 0000 0000 0000 0000
0000170 0000 0000 0000 0000 000c 0000 0000 0000
0000180 000c 0000 0c00 0000 0000 0000 0c00 0000
0000190 0000 000c 0000 0000 0000 000c 0000 0c00
00001a0 0000 0000 0000 0c00 0000 0000 000c 0000
00001b0 0000 0000 000c 0000 0c00 0000 0000 0000
00001c0 0c00 0000 0000 000c 0000 0000 0000 000c
00001d0 0000 0000 0000 000c 0000 0000 0000 000c
*
0000210 0000 0000 0000 000c 0000 0000 0000 0000
0000220 0000 0000 0a00
0000226

in which we can see the hex values 0c and 0a
I don't understand why grep finds 0c but not 0a:
# grep -P '\x0c' myFile
Fichier binaire myFile correspondant
# grep -P '\x0a' myFile
<nothing in the output>

I am using CentOS.

A: \x0a isn't just any hex value - it's the hex value corresponding to the ASCII linefeed character.
Since grep is (by default) line-based, the linefeed characters are stripped out before pattern matching takes place. At least with GNU grep, you can change this behavior with the -z option:
   -z, --null-data
          Treat  input  and  output  data  as  sequences  of  lines,  each
          terminated by a zero byte (the ASCII NUL character) instead of a
          newline.

however note that this will strip out ASCII nulls, so that you will no longer be able to grep for those.


text:
Q: Use of partitioners in Spark Hy, I have a question about partitioning in Spark,in Learning Spark book, authors said that partitioning can be useful, like for example during PageRank at page 66 and they write :

since links is a static dataset, we partition it at the start with
  partitionBy(), so that it does not need to be shuffled across the
  network

Now I'm focused about this example, but my questions are general:

*

*why a partitioned RDD doesn't need to be shuffled?

*PartitionBy() is a wide transformation,so it will produce shuffle anyway,right?

*Could someone illustrate a concrete example and what happen into each  single node when partitionBy happens?
Thanks in advance

A:
Why a partitioned RDD doesn't need to be shuffled?

When the author does:
val links = sc.objectFile[(String, Seq[String])]("links")
 .partitionBy(new HashPartitioner(100))
 .persist()

He's partitioning the data set into 100 partitions where each key will be hashed to a given partition (pageId in the given example). This means that the same key will be stored in a single given partition. Then, when he does the join:
val contributions = links.join(ranks)

All chunks of data with the same pageId should already be located on the same executor, avoiding the need for a shuffle between different nodes in the cluster.

PartitionBy() is a wide transformation,so it will produce shuffle
  anyway, right?

Yes, partitionBy produces a ShuffleRDD[K, V, V]:
def partitionBy(partitioner: Partitioner): RDD[(K, V)] = self.withScope {
  if (keyClass.isArray && partitioner.isInstanceOf[HashPartitioner]) {
    throw new SparkException("HashPartitioner cannot partition array keys.")
  }
  if (self.partitioner == Some(partitioner)) {
    self
  } else {
    new ShuffledRDD[K, V, V](self, partitioner)
  }
}

Could someone illustrate a concrete example and what happen into each
  single node when partitionBy happens?

Basically, partitionBy will do the following:

It will hash the key modulu the number of partitions (100 in this case), and since it relys on the fact that the same key will always produce the same hashcode, it will package all data from a given id (in our case, pageId) to the same partition, such that when you join, all data will be available in that partition already, avoiding the need for a shuffle.


text:
Q: From a loop index k, obtain pairs i,j with i < j? I need to traverse all pairs i,j with 0 <= i < n, 0 <= j < n and i < j for some positive integer n.
Problem is that I can only loop through another variable, say k. I can control the bounds of k. So the problem is to determine two arithmetic methods, f(k) and g(k) such that i=f(k) and j=g(k) traverse all admissible pairs as k traverses its consecutive values.
How can I do this in a simple way?

A: I think I got it (in Python):
def get_ij(n, k):
  j = k // (n - 1)  # // is integer (truncating) division
  i = k - j * (n - 1)
  if i >= j:
    i = (n - 2) - i
    j = (n - 1) - j
  return i, j

for n in range(2, 6):
  print n, sorted(get_ij(n, k) for k in range(n * (n - 1) / 2))

It basically folds the matrix so that it's (almost) rectangular. By "almost" I mean that there could be some unused entries on the far right of the bottom row.
The following pictures illustrate how the folding works for n=4:

and n=5:

Now, iterating over the rectangle is easy, as is mapping from folded coordinates back to coordinates in the original triangular matrix.
Pros: uses simple integer math.
Cons: returns the tuples in a weird order.

A: I think I found another way, that gives the pairs in lexicographic order. Note that here i > j instead of i < j.
Basically the algorithm consists of the two expressions:
i = floor((1 + sqrt(1 + 8*k))/2)
j = k - i*(i - 1)/2

that give i,j as functions of k. Here k is a zero-based index.
Pros: Gives the pairs in lexicographic order.
Cons: Relies on floating-point arithmetic.
Rationale:
We want to achieve the mapping in the following table:
k -> (i,j)
0 -> (1,0)
1 -> (2,0)
2 -> (2,1)
3 -> (3,0)
4 -> (3,1)
5 -> (3,2)
....

We start by considering the inverse mapping (i,j) -> k. It isn't hard to realize that:
k = i*(i-1)/2 + j
Since j < i, it follows that the value of k corresponding to all pairs (i,j) with fixed i satisfies:
i*(i-1)/2 <= k < i*(i+1)/2

Therefore, given k, i=f(k) returns the largest integer i such that i*(i-1)/2 <= k. After some algebra:
i = f(k) = floor((1 + sqrt(1 + 8*k))/2)

After we have found the value i, j is trivially given by
j = k - i*(i-1)/2

A: I'm not sure to understand exactly the question, but to sum up, if 0 <= i < n, 0 <= j < n , then you want to traverse 0 <= k < n*n
for (int k = 0; k < n*n; k++) {
    int i = k / n;
    int j = k % n;
    // ...
}

[edit] I just saw that i < j ; so, this solution is not optimal since there's less that n*n necessary iterations ...

A: If we think of our solution in terms of a number triangle, where k is the sequence
1
2  3
4  5  6
7  8  9  10
11 12 13 14 15
...

Then j would be our (non zero-based) row number, that is, the greatest integer such that
j * (j - 1) / 2 < k

Solving for j:
j = ceiling ((sqrt (1 + 8 * k) - 1) / 2)

And i would be k's (zero-based) position in the row
i = k - j * (j - 1) / 2 - 1

The bounds for k are:
1 <= k <= n * (n - 1) / 2

A: Is it important that you actually have two arithmetic functions f(k) and g(k) doing this?  Because you could first create a list such as
L = []
for i in range(n-1):
    for j in range(n):
        if j>i:
            L.append((i,j))

This will give you all the pairs you asked for.  Your variable k can now just run along the index of the list.  For example, if we take n=5,
for x in L:
    print(x)

gives us
(0,1), (0,2), (0,3), (0,4), (1,2), (1,3), (1,4), (2,3), (2,4), (3,4)

Suppose your have 2<=k<5 for example, then
for k in range(2, 5)
    print L[k]

yields
(0,3), (0,4), (1,2)


text:
Q: Angular $http date issue I have an angularJs single-page app that posts data to an ASP.NET WebApi server application. Data is passed to the angular $http service as a javascript object:
saveData: function (data) {
    var deferred = $q.defer();

    $http({
        method: 'POST',
        url: 'api/Case/SaveData',
        data: data
    }).
    success(function (data, status, headers, config) {
        deferred.resolve(data);
    }).
    error(function (data, status, headers, config) {
        deferred.reject(data.Message || data);
    });

    return deferred.promise;
}

The data object contains several precise javascript dates (ie. they have a zero time component). When these dates are parsed by the WebApi model binder, their value is resolved taking into account the Daylight Saving state for the date in question. So "01/06/1965" resolves as "31/05/1965 23:00".
I suspect this is because when angular transforms the javascript object into JSON, it renders dates using the date.toString() method rather than date.toUTCString().
How can I configure the $http service so that it passes the dates to the server as UTC dates rather than with a local date?


text:
Q: Algorithm for creating the dual graph of a given planar graph Although I have some ideas on how to create a dual graph from a planar graph, I preferred to ask it here. Is there any algorithm for this purpose?
Thank you so much.

A: You may have heard of the Quad-Edge data structure for graph representation (https://en.wikipedia.org/wiki/Quad-edge). It has the advantage to represent the graph and its dual simultaneously, so once the graph is built, there is no need to "dualize" anymore.
I suspect that the Winged-edge structure (or even DCEL) has the same capability but this needs to be confirmed.

A: Take the set of faces as set of vertices and add an edge $f_1f_2$ whenever an edge separates these two faces.


text:
Q: why does this code not work for referencing a const from a class? why does this code not work for referencing a const from a class?
Background: I want to be able to reference a constant value from a class in a class variable type approach, as this is where it makes sense to source.  Trying find the best way to effectively have the class offer up an exposed constant.  I tried the below but it doesn't seem to work, I get "ERROR: property 'titleLablePrefix' not found on object of type 'DetailedAppointCell'"
@interface DetailedAppointCell : UITableViewCell {
}
  extern NSString * const titleLablePrefix;
@end

#import "DetailedAppointCell.h"
@implementation DetailedAppointCell
  NSString * const titleLablePrefix = @"TITLE: ";
@end

// usage from another class which imports
NSString *str = DetailedAppointCell.titleLablePrefix;  // ERROR: property 'titleLablePrefix' not found on object of type 'DetailedAppointCell'

A: You can use directly as NSString *str = titleLablePrefix;   if your external linkages are proper.

A: Objective C doesn't support class variables/constants, but it supports class methods. You can use the following solution:
@interface DetailedAppointCell : UITableViewCell {
}
+ (NSString*)titleLablePrefix;
@end

#import "DetailedAppointCell.h"
@implementation DetailedAppointCell
+ (NSString*)titleLablePrefix {
  return @"TITLE: ";
}
@end

// usage from another class which imports
NSString *str = [DetailedAppointCell titleLablePrefix];

p.s. Dot syntax is used for instance properties. You can learn more about Objective C here: http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocObjectsClasses.html


text:
Q: jQuery SELECT change trigger I use the following jQuery function to perform a slideDown on a DIV, based on the value of a SELECT dropdown:
$(function()
{
    $('#show-options').change(function(){
        if($(this).val() != '')
        {
            $('#' + $(this).val()).slideDown();
        }
    });
});

HTML:
<select id="show-options">
  <option value="">Select an Option</option>
  <option value="vehicle-type">Vehicle Type</option>
  <option value="vehicle-colour">Vehicle Colour</option>
</select>

Now when the form is submitted, any DIVs that were displayed before submission need to be displayed automatically. I can check for the GET variables in my PHP but I need the jQuery code that will mimic the 'change' function - I think this has something to do with triggers or binds.

A: I do this a lot actually.  The easiest way I've found is to just trigger the event after binding it like so:
function showByVal(val) {
    $('#' + val).slideDown();
}

$(function()
{
    $('#show-options').change(function(){
        if($(this).val() != '')
        {
            showByVal($(this).val());
        }
    });

    showByVal('<? echo $_GET["PreviousVal"]; ?>');
});

As long as the value is set ahead of time (by your PHP Code) then the event will fire after it binds and setup the initial display.

A: try this:
$("#" + $("#show-options :selected").val()).slideDown();

of course you'll have to write in php the selected attribute to the right option

A: If you're doing this in response to form submission, why not simply show the DIV (i.e., not make the style "display: none;") when you render the page for those things that have been displayed.  You'd need to either keep track, using hidden fields would be one way, or only show those sections that have both been displayed and had an item in the section selected.  Either way you can use the inputs that you get from the form to determine which sections have the default visibility set to be shown.

A: Whenever I need to do something like this I'll do $('#ele').trigger('change') thus not having to do anything special so when the page loads it just triggers the change event of the select list and as long as the correct value is set once the page loads it calls your already defined change handler.


text:
Q: Why do we need to set Max and Min thread in .Net? I am struggling in a thread project. I came across the setMaxThread , SetMinThread, GetMaxThread and GetAvailableThread. I didn't find any good reason to use those methods in the threadpool.
Help me out here,
why do we need it and when do we use it?

A: According to MSDN

There is one thread pool per process. Beginning with the .NET
  Framework 4, the default size of the thread pool for a process depends
  on several factors, such as the size of the virtual address space. A
  process can call the GetMaxThreads method to determine the number of
  threads. The number of threads in the thread pool can be changed by
  using the SetMaxThreads method.

If you don't want to use the default value, use setter method to change your process's thread pool.


text:
Q: How to change "mute" the function of \ll in latex-suite? I am trying to figure out where the compile mapping (<leader>ll) is defined in latex-suite and then mute that function. I want <leader>ll to do something else. But after I define the new mapping in .vimrc, I noticed that it will be overwritten by Latex-Suite when I edit a .tex file.
Could anybody help me to fix the issue?
Thanks!

A: That mapping is most likely defined by your plugin's ftplugin. You can see where it is defined by executing this command in a tex buffer:
:verbose map <leader>ll

If the mapping is defined in an ftplugin, you can override it in ~/.vim/after/ftplugin/<filetype>.vim:
nnoremap <buffer> <leader>ll dosomething


text:
Q: Как задать путь через folderbrowserdialog для picture box visual studio Вот строчка кода из программы, надо этот путь
@"C:\Users\ZULFAT\Desktop\Cars\avtophoto\

задавать через
folderbrowserdialog C# pictureBox9.ImageLocation = @"C:\\Users\ZULFAT\Desktop\Cars\avtophoto\"dataGridView1.Rows[e.RowIndex].Cells[21].FormattedValue.ToString();

A: Для начала создадим формочку, добавим PictureBox и Button:

Нажмем 2 раза ЛКМ по button1 в конструкторе, чтобы появился обработчик события. В него напишем следующий код:
private void button1_Click(object sender, EventArgs e)
{
    FolderBrowserDialog dialog = new FolderBrowserDialog();

        if(dialog.ShowDialog() == DialogResult.OK)
        {
            var files = Directory.GetFiles(dialog.SelectedPath)
                                                .Where(x => x.EndsWith(".jpeg")
                                                            || x.EndsWith(".jpg")
                                                            || x.EndsWith(".bmp")
                                                            || x.EndsWith(".png"))
                                                .Select(x => new { Path = x }).ToList();
            dataGridView1.DataSource = files;
        }
}

Затем, откроем свойства datagridview1 и выберем параметр CellContentDoubleClick, нажмем туда 2 раза ЛКМ, и напишем следующий код:
private void dataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
    string path = Convert.ToString(dataGridView1[e.ColumnIndex, e.RowIndex].Value);
    pictureBox1.Image = Image.FromFile(path);
}


text:
Q: Parent DIV to match Child height I am building a single page website using bootstrap.  The problem I am running into is, that I have a parent section where the height is set to 100% and is not contained.
However the rest of the content in the section is contained. So everything in the container is overflowing into the next section.  I want the parent section that is not contained to match the height of the child. I have tried using overflow:auto, however, I do not want a scrollbar to appear when the content is clipped.
Here is my code.
#map {
  border-top:2px solid #6d7873;
  background: #d7dbd9;
  padding-top:85px;
  height:100%;
  min-height: auto;
}

#regions_div {
  min-height: 100%;
  width:100%;
  border:1px solid #a1aaa6;
}

#dash {
  border-top:2px solid #6d7873;
  background: #bcc2bf;
  padding-top:85px;
  height:100%;
  min-height: auto;
}

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
          tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
          quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
          consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
          cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
          proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
          tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
          quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
          consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
          cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
          proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Disaster Maps

         Disaster Map    Disaster Dashboard

A: All Bootstrap classes have a specific purpose and place in the DOM tree. There were a couple of .containers were placed under the
 tags. There's 2 things about BS .container:

*

*There should be only one .container or .container-fluid per page.

*The .container or .container-fluid purpose is to wrap around everything in the page.
That would explain why content was bleeding out, because .container can only exert its influence on its own descendants.
Demo

html,
body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0
}

#map {
  border-top: 2px solid #6d7873;
  background: #d7dbd9;
  padding-top: 85px;
  min-height: 100%;
  height: auto;
}

#regions_div {
  min-height: 100%;
  width: 100%;
  border: 1px solid #a1aaa6;
}

#dash {
  border-top: 2px solid #6d7873;
  background: #bcc2bf;
  padding: 85px;
  min-height: 100%;
  height: auto;
}

footer {
  height: 50px;
}

article.content:first-of-type {
  padding: 10px 10px 0;
}

.row+.row .content {
  margin: -10px auto 0;
}

hr {
  margin: 20px auto;
}
<link href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta.3/css/bootstrap.css' rel='stylesheet'>
<link href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css' rel='stylesheet'>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
            irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
            irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Disaster Maps

           Disaster Map    Disaster Dashboard


text:
Q: Query with CONCAT inside JOIN is slow I need to get different values from 3 different tables (table1, table2, table3) where the common value is a reference number. This number appears on all 3 tables, except on table3 where the number is divided on three different columns. I tried to make a LEFT OUTER JOIN concatenating these three columns to make the whole reference number, but the query becomes significantly slower. This is the part of the query where the issue is found:
SELECT t1.type AS type, t2.client AS client, t3.somenumber AS somenumber, t4.anothernumber AS anothernumber

FROM table1 t1 JOIN table2 t2 ON t1.somevalue = t2.somevalue
JOIN table4 t4 ON t4.reference_number = t1.reference_number --Some validation I need to make on another table

--Here's the problem. table3's values 1 through 3 make the reference number found in the other tables.
--The CONCAT makes the query significantly slow.
LEFT OUTER JOIN table3 t3 ON CONCAT(t3.value1, t3.value2, t3.value3) = t1.reference_number

WHERE t1.date BETWEEN '2022-04-01' AND '2022-05-01'
AND t1.client IN ('client1', 'client2', 'client3', 'client4', 'client5')

GROUP BY t1.reference_number --Group by the reference number

I tried making a view to create a column where the reference number is 'stored', but it still takes a lot to run the query. Is there a way to optimize this?
Running on 10.3.32-MariaDB

A: The GROUP BY does not need CONCAT:
GROUP BY t3.value1, t3.value2, t3.value3

I don't understand why you tacked on t1.reference_number; it is either similar info or NULL.  The NULL case might lead to extra groups, by it seems like a waste.  (Add it on if necessary.)
Indexes:
t1:  INDEX(date)
t1:  INDEX(client, date)
t2:  INDEX(somevalue,  client)
t3:  INDEX(value1, value2, value3)
t4:  INDEX(reference_number)

Was t3.value a typo for t3.value3?
Consider getting rid of t4; you are not using any values from it.  The only thing it is doing is to verify that table4 has a matching row.
What version of MySQL are you using?
It may be useful to have VIRTUAL or PERSISTENT (generated) column that is CONCAT (value1, value2, value3) and index it.
(And I agree with the Commenters that the "reference number" is ambiguous.)


text:
Q: Is there a way to parse messages in Grafana with elasticsearch as the source? I am using Grafana v7.2.0 with Elasticsearch as a data source.
My logs look like
{
  "message": "Counter: 10",
  "id": "Rd57OnsBW_gLMXbXxjMh",
  "level": "info"
}

My aim is to filter out logs with values of counter > 5.
I am able to filter out logs with non zero values using
"Counter" NOT "Counter: 0"

*

*How can I filter out values of counter > 5

*Is there a way I can group these logs by id and take the max value of counter for each id?


text:
Q: How do I debug curl issues (CURLOPT_MAIL_FROM, text/html display) when a message is sent out successfully? I am successfully sending a mime message using libcurl. However, in the received email I can only see the "username" in the From: field.
    curlCode_ = curl_easy_setopt(curl, CURLOPT_MAIL_FROM,    from_field);
    recipients = curl_slist_append(recipients, (const char *)to_);
    recipients = curl_slist_append(recipients, cc.str().c_str());
    curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients);

I assume its a security feature at gmail, ensuring that the sender is always shown in the From field.
Another issues is that I send out a multi-part mime message with an alt text portion. In zoho mail, I can view the HTML, however gmail always shows the text part.
For reference, I make sure the HTML comes before the text.
    /* Build the mime message. */
    mime = curl_mime_init(curl);

    /* The inline part is an alternative proposing the html and the text
       versions of the e-mail. */
    alt = curl_mime_init(curl);

    /* HTML message. */
    part = curl_mime_addpart(alt);
    curl_mime_data(part, html_body_.c_str(), CURL_ZERO_TERMINATED);
    curl_mime_type(part, "text/html");

    /* Text message. */
    part = curl_mime_addpart(alt);
    curl_mime_data(part, body_.c_str(), CURL_ZERO_TERMINATED);

    /* Create the inline part. */
    part = curl_mime_addpart(mime);
    curl_mime_subparts(part, alt);
    curl_mime_type(part, "multipart/alternative");
    slist = curl_slist_append(NULL, "Content-Disposition: inline");
    curl_mime_headers(part, slist, 1);

The code is rather long and in multiple classes, so I can post any code deemed relevant to avoid clutter. Essentially I am unsure how to debug this.

A: The specific problem - The text part of a multi-format MIME has to be before the html part. Now both zohomail and gmail display the html.
A more general answer relating to libcurl debugging - I use the curl program instead. Use -libcurl option to generate C code that can be used in your C/C++ project. There are sample curl commands available with most REST APIs.


text:
Q: Echo Same Item Once In loop and echo unique or order Items once I am a beginner in PHP so please bear with my me.
My Current Situation is that I am having issues printing orders takes a lot of paper for our restaurant.
The Print out looks like this:
Receipt #: 0000
Cashier: Name here
Table #: table name
Client #: ID here
Date: 2017-03-11 8:26 PM
QTY: 4
Order:
Item 1
----------------------------------
Receipt #: 0000
Cashier: Name here
Table #: table name
Client #: ID here
Date: 2017-03-11 8:26 PM
QTY: 1
Order:
Item 2

I generally want to print it this way to save paper
Receipt #: 0000

Table #: table name
Client #: ID here
Date: 2017-03-11 8:26 PM
Cashier: Name here
QTY: 4
Order:
Item 1
Notes:

Cashier: Name here
QTY: 1
Order:
Item 2
Notes:

My current Query and Echo is this:
 $sql = "SELECT * FROM orders  WHERE  catid = 'Drinks' and printed = 'ticket' and status = 'active' and groupid = '".$_GET['groupid']."' and tid NOT LIKE 'Upstairs%'  Order By  oid asc ";

 $result = $conn->query($sql);
 if ($result->num_rows > 0) {
 while($row = $result->fetch_assoc()) {
 $oid = $row{'oid'};
 $product = $row['pname'];
 $groupidx = $row['groupid'];
 $printreceipt = $row['printreceipt'];
 ?>

 <h4 class="printableArea" style="line-height:20px;font-size:15px; margin:0px  0px 0px 5px; color: <?php echo $color;?>;   font-family: Courier New ">
 Receipt #: <?php  $newinfo =     $row{'info'}; echo $row{'info'}; ?>
 Cashier: <?php echo $row['user'];?>
       Table #:
 <?php  echo $row['tid']; ?>
 Client #: <?php  echo $row['cid']; ?>
 Date:      <?php echo date('Y-m-d h:i A', strtotime($row['date']))?>
 QTY: <?php  echo $row['qty']; ?>
Order:
 <?php if($row['viet']==""){ echo $product;}else{ echo $row['viet']; } ?  >
 <?php  echo $row['attr']; ?>
 Notes:
 <?php  echo    $row['extraoptions']; ?>

 <?php
 // Check connection
 if ($conn->connect_error) {
 die("Connection failed: " . $conn->connect_error);
 }
  $sql2 = "UPDATE orders SET printed='Yes' WHERE catid = 'Drinks' and oid = '$oid'           and (status <> 'waiting' and status <> 'deleted')";
      if ($conn->query($sql2) === TRUE) {
    //   echo "Record updated successfully";
      ?>


text:
Q: get a specific value from an xml I am trying to get a specific value from an xml. When I iterate over the nodes, the value is never returned. Here is the xml sample
<Fields>
    <Field FieldName="NUMBER">
      <String>1234</String>
    </Field>
    <Field FieldName="TYPE">
      <String>JAVA</String>
    </Field>
        <Field FieldName="ATYPE">
      <String>BB</String>
    </Field>
</Fields>

Here is what I have attempted based on this online resource that looks like my sample xml file
private static void updateElementValue(Document doc) {
        NodeList employees = doc.getElementsByTagName("Field");
        Element emp = null;
        //loop for each
        for(int i=0; i<employees.getLength();i++){
            emp = (Element) employees.item(i);
            System.out.println("here is the emp " + emp);
            Node name = emp.getElementsByTagName("NUMBER").item(0).getFirstChild();
            name.setNodeValue(name.getNodeValue().toUpperCase());
        }

    }

This is the online resource guiding my attempts
https://www.journaldev.com/901/modify-xml-file-in-java-dom-parser

Please assist

A: If you want to get a specific value from XML, XPath API may be more convenient in compare to DOM parser API. Here an example for retrieving value of a "String" elements, which are children of "Field" elements, having attribute "FieldName" with value "NUMBER":
// parse XML document from file
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(new FileInputStream(fileName));

// prepare an XPath expression
XPathExpression xpath = XPathFactory.newInstance().newXPath().compile("/Fields/Field[@FieldName='NUMBER']/String");

// retrieve from XML nodes using XPath
NodeList list = (NodeList)xpath.evaluate(doc, XPathConstants.NODESET);

// iterate over resulting nodes and retrieve their values
for(int i = 0; i < list.getLength(); i ++) {
    Node node = list.item(i);
    // udate node content
    node.setTextContent("New text");
}

// output edited XML document
StringWriter writer = new StringWriter(); // Use FileWriter to output to the file
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
System.out.println(writer.toString());


text:
Q: How is the absolute gRPC deadline communicated over the wire The gRPC Protocol Spec specifies that the grpc-timeout header uses relative values (eg: 100m). However, gRPC prefers absolute deadlines and I'm struggling to understand how this absolute deadline is communicated over the wire.
for eg: Lets say that the one-way geographic latency between the client and server is 100ms. Let's use a linear scale for time in millis for simplicity.
If a client makes a requests at time 0 with "grpc-timeout: 300m" Header then the server will receive the request at time 100. How does the server recognize that it only has 200ms remaining to process the request?

A:
How does the server recognize that it only has 200ms remaining to process the request?

It doesn't. Network latency is not taken into account. And understand in your example that the server actually only has 100ms to process, because it will take 100ms for the response to be received. The round-trip time (RTT) is 200ms. Note that RTTs are dynamic (they change over time) and the network links may not be symmetric (it might be 80ms in one direction and 120ms in the other).
There's no guarantee the client and server have their clocks synchronized. So there is no "absolute" time for gRPC to rely on when communicating between them. There's also no guarantee that the clocks progress at the same rate; one clock may be slower than the other (aka clock drift). Using a timeout on-the-wire generally covers up any issues caused by clock drift.
Communicating a timeout on-the-wire but deadlines within-a-process is simple and effective. Trying to be 100% precise about the deadline requires supporting assumptions or systems. In practice, the RTT shouldn't be a substantial portion of the time remaining before the deadline as that does not provide enough time for lost packets and retransmits (ignoring that gRPC might even need to establish a TCP connection). If the deadline is aggressive compared to the RTT, then the server computing results that went unused would just need to be accepted or requires vastly different networking designs and tradeoffs.


text:
Q: Passing # values with ajax not working I am trying to get weinre working via Ajax by calling this on dom ready:
$.ajax({
    url: 'http://debug.build.phonegap.com/target/target-script-min.js#hutber',
    dataType: "script",
    crossDomain: true,
    error: function(data){
        c(data.status);
    },
    success: function(data){
        c(data);
    }
});

Now, this is what is being sent:
 http://debug.build.phonegap.com/target/target-script-min.js?_=1381476442102

Which means that, for me to debug i have to use a randomly generated ID. I have tried this also: url: 'http://debug.build.phonegap.com/target/target-script-min.js?_=hutber', Just shooting in the dark.
So, am i write in thinking that the #hutber isn't being correctly sent with the request?
Edit
Just a quick thought, using $.ajax means that I am loading a script dynamically via a http request. As mentioned by Quentin you cannot pass #vars as these are client side. It occured to me however that I could pass the pass if I added the element into the body as if it were there on page load:
var s = document.createElement('script');
s.setAttribute("src","http://debug.build.phonegap.com/target/target-script-min.js#hutber");
document.getElementsByTagName('body')[0].appendChild(s);

Now, things should work out a little better, can't test this theory with a mobile phone however. But fingers crossed.

A: Yes and No. You are right in thinking that #hutber not being sent with the request, but you are wrong in thinking that this is incorrect.
The fragment identifier portion of a URL is handled purely client side so should never be sent to the server.
If you want to attach data to a URL for the server to process, then use a query string (starting with a ? character and not a # character). If you have both a query string and a fragment identifier then the query string must come first.
jQuery will generate a query string for you if you include a data property to the object you pass to ajax (if you are using GET, as you are here).
data { "_": "hutber" }


text:
Q: Adding a check next to the selected item in tkinter OptionMenu How could I add a check sign next to the currently selected item (or highlight it) in a OptionMenu in a tkinter GUI? The idea is that when I click again to select another item, I can see easily which one is selected (similar to the following picture)

I just added a new example:
from tkinter import *

OptionList = [
"Aries",
"Taurus",
"Gemini",
"Cancer"
]

app = Tk()

app.geometry('100x200')

variable = StringVar(app)
variable.set(OptionList[0])

opt = OptionMenu(app, variable, *OptionList)
opt.config(width=90, font=('Helvetica', 12))
opt.pack(side="top")

labelTest = Label(text="", font=('Helvetica', 12), fg='red')
labelTest.pack(side="top")

def callback(*args):
    labelTest.configure(text="The selected item is {}".format(variable.get()))

variable.trace("w", callback)

app.mainloop()

A: Just use ttk widgets for this modern looking style, try saying something like:
from tkinter import ttk
....
     #arguments  -  master  variable     default      *values
opt = ttk.Optionmenu(app, variable, OptionList[0], *OptionList)

The effect given by this is pretty similar or maybe identical to what your trying to achieve.
You might notice an additional third positional argument here, it is actually default=OptionList[0] argument specified here(specific to just ttk.Optionmenu), it is just the default value that the optionmenu will display, ignoring this might lead to some bugs in the looks of optionmenu, like this.
And also keep in mind, it does not have a font option too. To overcome this, check this out
Hope this was of some help to you, do let me know if any errors or doubts.
Cheers

A: You can get similar effect using tk.OptionMenu:
from tkinter import *

OptionList = [
"Aries",
"Taurus",
"Gemini",
"Cancer"
]

app = Tk()

app.geometry('300x200')

variable = StringVar(app)
variable.set(OptionList[0])

opt = OptionMenu(app, variable, None) # need to supply at least one menu item
opt.config(width=90, font=('Helvetica', 12))
opt.pack(side="top")

# populate the menu items
menu = opt['menu']
menu.delete(0) # remove the None item
for item in OptionList:
    menu.add_radiobutton(label=item, variable=variable)

labelTest = Label(text="", font=('Helvetica', 12), fg='red')
labelTest.pack(side="top")

def callback(*args):
    labelTest.configure(text="The selected item is {}".format(variable.get()))

variable.trace("w", callback)

app.mainloop()


text:
Q: Hosting free content for download by cross-platform app What are some good options for hosting free downloadable content for use in a Titanium app that will run on iOS and Android?
I know Apple allows you to host content for in-app purchases, however only some of my content will be paid, but majority will be free, so I need a way of hosting the free content.
The content is mostly audio files up to a maximum of 60Mb each with total of under 2 gigs of content.
Note: I don't want to stream the audio from the server, just download the audio files for use in the app.
I am looking for a solution that is cheap, easy to maintain, and scales well to lots of downloads (because you never know :)

A: Well... this is very subjective, and solution dependent. I personally use Amazon S3 for several projects. It can scale, is pretty cheap, and I've had reliable performance out of it. Easy to setup too.


text:
Q: This error while debugging eclipse source attachement I get this error while debugging. I put a breakpoint somewhere in the code.
The project is built and run on my device, but in debugging I get this code, which is looking for android.jar
My target version of android is 2.2. I chose /appcompat_v7/bin/appcompat_v7.jar instead of android.jar, assuming this version of Android is based on appcompat_v7.jar. I don't know.... I was just assuming. Nevertheless, it's not working.
I checked some of Similar Questions and I couldn't find the exactly my answer, this was the most similar problem, yet my problem wasn't solved:
Eclipse java debugging: source not found
This is a screenshot of the error:
 http://i.stack.imgur.com/6m45J.png
Thhanks. :)
package com.thenewboston.travis;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

public class OpenedClass extends Activity implements OnClickListener,
        OnCheckedChangeListener {
    TextView question, test;
    Button returnData;
    RadioGroup selectionList;
    String gotBread;
    String setData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.send);
        initialize();
        // Bundle gotBasket = getIntent().getExtras();
        // gotBread = gotBasket.getString("key");
        // question.setText(gotBread);
    }

    private void initialize() {
        // TODO Auto-generated method stub
        question = (TextView) findViewById(R.id.tvQuestion);
        test = (TextView) findViewById(R.id.tvText);
        returnData = (Button) findViewById(R.id.bReturn);
        returnData.setOnClickListener(this);
        selectionList = (RadioGroup) findViewById(R.id.rgAnswers);
        selectionList.setOnCheckedChangeListener(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Intent person = new Intent();
        Bundle backpack = new Bundle();
        backpack.putString("answer", setData);
        person.putExtras(backpack);
        setResult(RESULT_OK, person);
        finish();
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        // TODO Auto-generated method stub
        switch (checkedId) {
        case R.id.rCrazy:
            setData = "Probably right!";
            break;
        case R.id.rSexy:
            setData = "Definitely right!";
            break;
        case R.id.rBoth:
            setData = "Spot On!";
            break;
        default:
            break;
        }
        test.setText(setData);
    }
}

A: This is not an error.
You try to open the source of the class, but you only have access to the .class file (which is all you need to run it).
You can attach the code (for instance by clicking the Change attached sources button), but this is in no way mandatory.

A: You have skip that point by pressing F8 instead of F6 cause you have limitation of it. So try this one.


text:
Q: Como faço para 'limpar os resultados' quando o usuário clicar novamente em SOMAR(ativando o a função calc onclick)? Segue o código

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>

      <button id="som" onclick="calc()">SOMAR</button>
      <button id="sub">SUBITRAIR</button>
      <button id="divi">DIVIDIR</button>
      <button id="mut">MULTIPLICAR</button>

Sei que o código não deve ta muito bom, e esse é o primeiro "projeto" que estou tentando fazer sozinho, praticando um pouco sabe..
Quando ativo a função calc, ele cria tudo de novo em baixo da div principal. eu queria que limpasse o resultado ou algo do tipo.

Sei que muita coisa daria pra fazer com html ou CSS, mas tava querendo praticar JS mesmo.

A: Olá,
Acontece que o método appendChild sempre adiciona um novo filho no elemento. Você pode criar uma variável global chamada oldChild, e na hora de calcular a soma, você verifica se oldChild existe, e aí ele usa o método replaceChild(newChild, oldChild), se não, ele usa o appendChild(newChild) normal.
Segue um exemplo:
var oldChild;

// Segue o código normalmente

// No método do onclick:
if (oldChild) div4.replaceChild(res, oldChild);
else div4.appendChild(res);

oldChild = res;

Ficando inteiramente assim:
somarb.onclick = function () {
  var n1 = Number(inp1.value);
  var n2 = Number(inp2.value);
  var soma = n1 + n2;

  var res = document.createTextNode(
    `A soma entre ${n1} e ${n2} é igual a ${soma}`
  );

  div4.style.margin = "10% 10%";

  if (oldChild) div4.replaceChild(res, oldChild);
  else div4.appendChild(res);

  oldChild = res;
};

Código completo:

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>

      <button id="som" onclick="calc()">SOMAR</button>
      <button id="sub">SUBITRAIR</button>
      <button id="divi">DIVIDIR</button>
      <button id="mut">MULTIPLICAR</button>


text:
Q: Is there a way to load sheets with a specific regex with pandas.read_excel() Is there a way to load sheets with a specific regex with pandas.read_excel() ?
Maybe with the parameter sheet_name
But can't figure how...
Example of regex :
regex_sheet = "\s*[d^D][A^a][y^Y]\D*\s*[1-9]\s*"

A: You can use pandas.ExcelFile to have a peek at the sheet names, then select the sheets to keep with any method (here your regex), finally load with pandas.read_excel:
import re

xl = pd.ExcelFile('filename.xlsx')

regex = re.compile('your_regex')

sheets = [n for n in xl.sheet_names if regex.match(n)]
# ['matching_sheet1', 'matching_sheet2']

dfs = pd.read_excel(xl, sheet_name=sheets)
#  {'matching_sheet1': DataFrame1,
#   'matching_sheet2': DataFrame2}


text:
Q: How do I remove the status bar from a PKPaymentAuthorizationViewController? I am developing an app that will include Apple Pay. When I present a PKPaymentAuthorizationViewController it shows the status bar on top of the screen, which I would like to keep hidden since it does not appear anywhere else in the app.
I tried overriding the view controller's behavior through subclassing:
@interface MyPaymentAuthorizationViewController : PKPaymentAuthorizationViewController

@end

@implementation MyPaymentAuthorizationViewController

- (BOOL)prefersStatusBarHidden
{
    return YES;
}

@end

Though this results in a console message saying "PKPaymentAuthorizationViewController does not support subclassing." and the app crashing. Is it possible to present the view controller without the status bar appearing?


text:
Q: Running Jenkins job with docker command on kubernetes cluster fails "docker: not found" We are running a Kubernetes cluster for building Jenkins jobs. For the pods we are using the odavid/jenkins-jnlp-slave JNLP docker image. I mounted the /var/run/docker.sock to the pod container and added jenkins(uid=1000) user to the docker group on the host systems.
When running a shell script job in Jenkins with e.g. docker ps it fails with error docker: not found.
$ /bin/sh -xe /tmp/jenkins6501091583256440803.sh
+ id
uid=1000(jenkins) gid=1000(jenkins) groups=1000(jenkins)
+ docker ps
/tmp/jenkins2079497433467634278.sh: 8: /tmp/jenkins2079497433467634278.sh: docker: not found
Build step 'Execute shell' marked build as failure
Finished: FAILURE

The interesting thing is that when connecting into the pod manually and executing docker commands directly in the container as jenkins user, it works:
kubectl exec -it jenkins-worker-XXX -- /bin/bash
~$ su - jenkins
~$ id
uid=1000(jenkins) gid=1000(jenkins) groups=1000(jenkins),1000(jenkins)
~$ docker ps
CONTAINER ID        IMAGE        COMMAND         CREATED         STATUS

What is doing Jenkins in its job differently? Same user, same container, only groups=1000(jenkins),1000(jenkins) lists 1000(jenkins) as group 2 times when connecting manually. What am i missing?

A: /var/run/docker.sock is just the host socket that allows docker client to  run  docker commands from the container.
What you are missing is the docker client in your container.
Download the docker client manually and place it on a persistent volume and ensure that he docker client is in the system path. Also, ensure that the docker client is executable.
This command will do it  for you.  You may have to get the right version of the docker client for your environment
curl -fsSLO https://get.docker.com/builds/Linux/x86_64/docker-17.03.1-ce.tgz &&
tar --strip-components=1 -xvzf docker-17.03.1-ce.tgz -C /usr/local/bin

You may even be able to install the  docker using the  package manager for your image.


text:
Q: symfony 3 : "this value is Not valide" i have a problem when i insert date from calender using jquery !there is a problem of conversion i think .
II try to use
{{ form_widget(form.dateArrivage|date("m/d/Y") , {'attr': {'class': 'from'}}) }}

but :
An exception has been thrown during the rendering of a template

Catchable Fatal Error: Object of class Symfony\Component\Form\FormView could not be converted to string

in GestionHotelBundle:Default:index.html.twig at line 147.
this is ReservationType
 public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('dateArrivage',DateTimeType::class, array(
            'widget' => 'single_text',
            'format' => 'dd/MM/yyyy',
            'attr' => array('class' => 'date')
        ))
        ->add('dateSortie',DateTimeType::class, array(
            'widget' => 'single_text',
            'format' => 'dd/MM/yyyy',
            'attr' => array('class' => 'date')
        ))
        ->add('nbjour')
        ->add('dateReser',DateType::class)
        ->add('chambres', CollectionType::class, array(
            'entry_type' => ChambreType::class,
            'allow_add'    => true,
            'allow_delete' => true,
            'by_reference' => false,
        ))
        ->add('save',SubmitType::class)
    ;
    ;
}

and this is the vue :


text:
Q: I am trying to write a program for Armstrong number in PL/SQL.Can anyone tell me where i am wrong? while  N !=0
LOOP

R:=MOD(N,10);
R1:=power(R,3);
A:=A+R1;
N:=TRUNC(N/10);

END LOOP;

After this it comes IF N=A THEN
SYS.DBMS_OUTPUT.PUT_LINE(' number is armstrong ');
ELSE
SYS.DBMS_OUTPUT.PUT_LINE(' number is  not an armstrong ');

A: Your problem is when you compare (N=A) because N is zero at the end of LOOP. Then you must compare A with the original number entered, (NOrig=A).
This procedure you can help:
create or replace procedure amstrong_number(pNumber int)
is

  NOrig int:=0;
  N int:=0;
  R int:=0;
  R1 int:=0;
  A int:=0;

begin

  NOrig:=pNumber;
  N:=pNumber;

  WHILE N!= 0
  LOOP

    R:=MOD(N,10);
    R1:=POWER(R,3);
    A:=A+R1;
    N:=TRUNC(N/10);

  END LOOP;

  IF NOrig = A THEN
    dbms_output.put_line(' number is amstrong ');
  ELSE
    dbms_output.put_line(' number is not an amstrong ');
  END IF;

end;

Regards

A: In a comment you say you want to take user input from the keyboard. It is not clear how you plan to do that; in general, PL/SQL does not have facilities for interaction with end users, it is a language for processing on the server.
One way to have the user provide a number is to have a procedure with an in parameter. Below is one example of how you can do it. You must compile the procedure first (for example, I saved it in a script, "Armstrong.sql", and then I ran the command "start Armstrong" in SQL*Plus). Then the user can use the procedure, which I called is_Armstrong, from SQL*Plus or a graphical interface like SQL Developer or Toad, like this:  exec is_Armstrong(...)  where in parentheses is the user's input number.
I built in two application exception checks - for negative or non-integer numbers and for numbers that are too long (more than 20 digits). I wrote it for Armstrong numbers of arbitrary length (<= 20), limiting it to three digits doesn't save almost any work so why not make it general. There are other possible application exceptions - for example, what if the user inputs a string instead of a number? I didn't handle all the errors - the very last example below shows an unhandled one. Write your own error handling code for whatever else you want to handle explicitly.
Content of Armstrong.sql:
create or replace procedure is_Armstrong(p_input_number number)
as
   l_string varchar2(20);
   l_sum number := 0;
   l_loop_counter number;
   l_len number;
   not_a_positive_integer exception;
   number_too_large exception;
begin
   l_string := to_char(p_input_number);
   l_len    := length(l_string);
   if p_input_number <= 0 or p_input_number != floor(p_input_number) then
      raise not_a_positive_integer;
   elsif l_len > 20 then
      raise number_too_large;
   end if;
   for l_loop_counter in 1..l_len
   loop
      l_sum := l_sum + power(to_number(substr(l_string, l_loop_counter, 1)), l_len);
   end loop;
   if p_input_number = l_sum then
      dbms_output.put_line('Number ' || l_string || ' is an Armstrong number.');
   else
      dbms_output.put_line('Number ' || l_string || ' is not an Armstrong number.');
   end if;
exception
   when not_a_positive_integer then
      dbms_output.put_line('Input number must be a positive integer.');
   when number_too_large then
      dbms_output.put_line('Input number must be no more than twenty digits.');
end;
/

Compiling the procedure:
SQL> start Armstrong.sql
Procedure created.
Elapsed: 00:00:00.03

Usage examples:
SQL> exec is_Armstrong(-33);
Input number must be a positive integer
PL/SQL procedure successfully completed.
Elapsed: 00:00:00.08

SQL> exec is_Armstrong(1.5);
Input number must be a positive integer
PL/SQL procedure successfully completed.
Elapsed: 00:00:00.08

SQL> exec is_Armstrong(1234512345123451234512345);
Input number must be no more than twenty digits
PL/SQL procedure successfully completed.
Elapsed: 00:00:00.01

SQL> exec is_Armstrong(3);
Number 3 is an Armstrong number.
PL/SQL procedure successfully completed.
Elapsed: 00:00:00.00

SQL> exec is_Armstrong(100);
Number 100 is not an Armstrong number.
PL/SQL procedure successfully completed.
Elapsed: 00:00:00.00

SQL> exec is_Armstrong(371);
Number 371 is an Armstrong number.
PL/SQL procedure successfully completed.
Elapsed: 00:00:00.00

SQL> exec is_Armstrong('abc')
BEGIN is_Armstrong('abc'); END;
*
ERROR at line 1:
ORA-06502: PL/SQL: numeric or value error: character to number conversion error
ORA-06512: at line 1
Elapsed: 00:00:00.00


text:
Q: Does WordPress have something like timer hook? Are there some timer hooks to trigger event like this?
add_action("one_min_timer", "my_handler");
function my_handler() {
   //checking something every 1 min
}

A: You can use the native PHP sleep() function in WordPress for timers in seconds, or usleep() for timers in microseconds:
http://php.net/manual/en/function.sleep.php
http://php.net/manual/en/function.usleep.php


text:
Q: InDesign style variable Is there a way to use variables in styles (script?) to share styles with some variations, like color?
Example: I am laying out a book, with multiple chapters. Each chapter is an InDesign document. I would like to use common styles for all the documents in the book, but they would vary in color. So instead of having multiple objects styles like: RoundedBox-red, RoundedBox-blue etc, I would only have one style, RoundedBox, and just input the value of the color variable somewhere…

A: Do you have a reason to examine only rectangles, ovals, and polygons? If not, you can use pageItems. Ditch the shape selection and the switch, and use:
shapes = myDoc.allPageItems;
for (var i=0; i<shapes.length; i++)
{
    if (shapes[i].appliedObjectStyle.name === oldStyle.name)
    {
        shapes[i].applyObjectStyle( newStyle );
    }
}

Since you have each chapter in a separate document, you could also just change the definition of your object style:
oldStyle.fillColor = newSwatch;

so you don't have to loop over the actual objects. Not tested but it should work.

A: Well, I found out. The hardest part was really to find a good documentation for the Indesign javascript scripting API... Adobe's documentation is either hard to find or lacking. In addition, they publish everything as PDFs, which IMHO is really annoying. I found a good online documentation for CS6. I am working on CC but everything I used seems the same. Anyhow, I have created the following script, very incomplete and not perfect, but works for me...
// Setup the dialog UI
   var myDialog = app.dialogs.add({
       name: "Style Variables",
       canCancel: true
   });

// I usually never use 'with', but this is how it is done
// in Adobe's documentation...
with(myDialog.dialogColumns.add()) {
    staticTexts.add({staticLabel: "Main Color swatch name:"});
    staticTexts.add({staticLabel: "Style to replace:"});
    staticTexts.add({staticLabel: "Replace style with:"});
    staticTexts.add({staticLabel: "Choose shape type to target:"});
}
with(myDialog.dialogColumns.add()){
    var swatchField     = textEditboxes.add({editContents:'', minWidth:180}),
        oldStyleField   = textEditboxes.add({editContents:'', minWidth:180}),
        newStyleField   = textEditboxes.add({editContents:'', minWidth:180}),
        shapeTypeField  = dropdowns.add({stringList:['Rectangles', 'Ovals', 'Polygons']});     // Defaults to rectangles
}

// Get the user input and do stuff with it
var myResult = myDialog.show();
if (myResult === true)
{
    var docs        = app.documents,
        myDoc       = docs[0],
        allStyles   = myDoc.objectStyles,
        oldStyle    = allStyles.itemByName(oldStyleField.editContents),
        newStyle    = allStyles.itemByName(newStyleField.editContents),
        swatches    = app.documents[0].swatches,
        newSwatch   = swatches.itemByName(swatchField.editContents),
        shapes;

// Get the shape type we are targetting:
switch(shapeTypeField.selectedIndex)
{
    case 0:
        shapes = myDoc.rectanges;
        break;
    case 1:
        shapes = myDoc.ovals;
    break;
case 2:
    shapes = myDoc.polygons;
    break;

default:
    shapes = myDoc.rectangles;
}
// Set the base style color to the user chosen swatch:
newStyle.fillColor = newSwatch;

    for (var i=0; i<shapes.length; i++)
    {
        if (shapes[i].appliedObjectStyle.name === oldStyle.name)
        {
            shapes[i].applyObjectStyle( newStyle );
        }
    }
}
else
{
    alert('Script cancelled, nothing was done.');
}

// Destroy dialog box
myDialog.destroy();


text:
Q: How can I get JsonConvert.DeserializeXmlNode to serialize arrays under a single node? When I call JsonConvert.DeserializeXmlNode with a JSON string that contains an array like this:
{"Name":"Brian","Wife":{"Name":"Christine"},"Children":[{"Name":"Kiara"},{"Name":"Abrian"},{"Name":"Brooke"}]}

I get XML that looks like this:
<Root>
  <Name>Brian</Name>
  <Wife>
    <Name>Christine</Name>
  </Wife>
  <Children>
    <Name>Kiara</Name>
  </Children>
  <Children>
    <Name>Abrian</Name>
  </Children>
  <Children>
    <Name>Brooke</Name>
  </Children>
</Root>

What I want is something that looks like this:
<Root>
  <Name>Brian</Name>
  <Wife>
    <Name>Christine</Name>
  </Wife>
  <Children>
    <Child>
      <Name>Kiara</Name>
    </Child>
    <Child>
      <Name>Abrian</Name>
    </Child>
    <Child>
      <Name>Brooke</Name>
    </Child>
  </Children>
</Root>

To make this more complex, I'm trying to do this in framework code, so I don't really know what the data is that's coming in, which means that I have no idea what to call the child element, but perhaps just one problem at a time :).

A: The following custom XmlNodeConverter will serialize arrays under a single node, with each array element assigned a specified name. Given you don't know the incoming data, you could opt for a generic name like "Element", in which case your example json would translate to:
<Children>
   <Element>
      <Name>Christine</Name>
   </Element>
   <Element>
      <Name>Kiara</Name>
   </Element>
</Children>

The custom XmlNodeConverter:
public class SingleArrayNodeXmlConverter : XmlNodeConverter
{
    public string ArrayElementName { get; set; }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var token = JObject.Load(reader);
        InjectArrayElements(token, ArrayElementName);
        var innerReader = token.CreateReader();
        innerReader.Read();
        return base.ReadJson(innerReader, objectType, existingValue, serializer);
    }

    private static void InjectArrayElements(JToken token, string elementName)
    {
        foreach (var childToken in token)
        {
            InjectArrayElements(childToken, elementName);
        }
        if (token.Type == JTokenType.Array)
        {
            var arrayHolder = new JObject { { elementName, token } };
            token.Replace(arrayHolder);
        }
    }
}

Usage:
var converter = new SingleArrayNodeXmlConverter
{
    DeserializeRootElementName = "Root",
    WriteArrayAttribute = false,
    ArrayElementName = "Element"
};
return (XmlDocument)JsonConvert.DeserializeObject(json, typeof(XmlDocument), converter);

This solution is obviously a compromise, but in our situation even a generic array element is better than repeating the array node itself.

A: {"Name":"Brian","Wife":{"Name":"Christine"},"Children":["Child":{"Name":"Kiara"},"Child":{"Name":"Abrian"},"Child":{"Name":"Brooke"}]}


text:
Q: With clang and libstdc++ on Linux, is it currently feasible to use any standard library types in a module interface? So far it seems to me that including almost any libstdc++ header in a C++ module interface causes compile errors on clang 14.0.0 and the libstdc++ that comes bundled with GCC 11.2.0. I wonder if I am doing something wrong or if this is just not something that is supported yet. (I see that the Clang modules support is "partial", but haven't been able to find what is implemented and what is not.)
Here's a trivial module example that I got to work with clang-14 in Linux, linked with libstdc++. It demonstrates that libstdc++ headers can be used in a module implementation, but this example does not #include anything in the module interface:
// mod_if.cc
export module mod;
export int foo();

// mod.cc
module;
#include <iostream>
module mod;
int foo() {
    std::cout << "Hello world from foo()" << std::endl;
    return 42;
}

// use.cc
import mod;
#include <iostream>

int main() {
    std::cout << foo() << std::endl;
}

This works:
$ CXXFLAGS="-std=c++20 -fmodules -fprebuilt-module-path=prebuilt"
$ clang++ -c $CXXFLAGS -Xclang -emit-module-interface -o prebuilt/mod.pcm mod_if.cc
$ clang++ -c $CXXFLAGS -fmodule-file=prebuilt/mod.pcm mod.cc -o mod.o
$ clang++ $CXXFLAGS use.cc mod.o prebuilt/mod.pcm -o use
$ ./use
Hello world from foo()
42

However, suppose I wanted foo to return a std::string:
// mod_if.cc
module;
#include <string>
export module mod;
export std::string foo();

// mod.cc
module;
#include <string>
module mod;
std::string foo() {
    return "42";
}

// no use.cc needed since the error happens when building mod.cc

This does not compile (first of many similar errors shown):
$ clang++ -c $CXXFLAGS -Xclang -emit-module-interface -o prebuilt/mod.pcm mod_if.cc
$ clang++ -c $CXXFLAGS -fmodule-file=prebuilt/mod.pcm mod.cc -o mod.o

In file included from mod.cc:2:
In file included from /usr/lib64/gcc/x86_64-pc-linux-gnu/11.2.0/../../../../include/c++/11.2.0/string:40:
In file included from /usr/lib64/gcc/x86_64-pc-linux-gnu/11.2.0/../../../../include/c++/11.2.0/bits/char_traits.h:39:
In file included from /usr/lib64/gcc/x86_64-pc-linux-gnu/11.2.0/../../../../include/c++/11.2.0/bits/stl_algobase.h:64:
In file included from /usr/lib64/gcc/x86_64-pc-linux-gnu/11.2.0/../../../../include/c++/11.2.0/bits/stl_pair.h:65:
/usr/lib64/gcc/x86_64-pc-linux-gnu/11.2.0/../../../../include/c++/11.2.0/compare:348:33: error: redefinition of '__cmp_cat_id<std::partial_ordering>'
      inline constexpr unsigned __cmp_cat_id<partial_ordering> = 2;
                                ^
/usr/lib64/gcc/x86_64-pc-linux-gnu/11.2.0/../../../../include/c++/11.2.0/bits/stl_pair.h:65:11: note: '/usr/lib64/gcc/x86_64-pc-linux-gnu/11.2.0/../../../../include/c++/11.2.0/compare' included multiple times, additional include site in header from module 'mod.<global>'
# include <compare>
          ^
/usr/lib64/gcc/x86_64-pc-linux-gnu/11.2.0/../../../../include/c++/11.2.0/bits/stl_pair.h:65:11: note: '/usr/lib64/gcc/x86_64-pc-linux-gnu/11.2.0/../../../../include/c++/11.2.0/compare' included multiple times, additional include site in header from module '<global>'
# include <compare>
          ^
mod.cc:1:1: note: <global> defined here
module;
^

Is there currently a way to make this code work (without resorting to writing module maps for the libstdc++ headers)? Why does this error happen? It sounds strange that the inline constexpr declaration included in the global module fragment gets exported, but then I don't claim to understand modules well.

A: Ok, this is something that sort of worked for a large project. Note that this was half a year ago, so the world may have moved on.
I ended up creating a single header, "sys.hh", that #includes pretty much all the system headers used in the project. What seems to be important is that nothing directly or indirectly #included by this file gets #included directly or indirectly (outside the module system) in anything that gets linked into the final binary.
My "sys.hh" looks something like this:
#include <algorithm>
#include <array>
#include <assert.h>
#include <atomic>
#include <bits/std_abs.h>
// 100+ lines omitted, including things like glib, gtk, libjpeg
#include <vector>
#include <x86intrin.h>
#include <zlib.h>

// Macros won't get exported, so whatever the code needs, redefine as
// constexpr (or consteval functions) here. Unfortunately, I don't think
// there's a way to retain the name of the macro; so add an underscore.
// Also put them in a namespace.
#define MEXP(X) constexpr auto X ## _ = X;

namespace sys {
    MEXP(INTENT_PERCEPTUAL);
    MEXP(INTENT_RELATIVE_COLORIMETRIC);
    MEXP(INTENT_SATURATION);
    MEXP(INTENT_ABSOLUTE_COLORIMETRIC);
    MEXP(G_PRIORITY_DEFAULT_IDLE);
}

And my my modulemap file contains an entry like this:
module sys {
    header "prebuilt/sys.hh"
    use _Builtin_intrinsics
    export *
}

Compiling this header/module is a bit of an incremental process; you will run into modules that fail to compile because they indirectly include the same headers, so you add them into this file and rebuild until it works.
Note that managing build dependencies becomes much more of a thing with modules. At least half a year ago no good (automatic) ways seemed to exist to discover what needs to be rebuilt. This is made trickier by the fact that the name of the module does not tell where it lives in the source code.


text:
Q: Why am I allowed to load an image in the non-GUI thread? Well known is that you cannot change the GUI with any other thread than the GUI thread. So a simple trick that is commonly used (which I use) is invoking:
this.Invoke((MethodInvoker)delegate { pictureBox1.Visible = false; });

I was building my program and started it, quickly noticing that I forgot to put an PictureBox.Load(string url) in the invoker, however no error had occurred.
So I am curious, why am I not allowed to do (in non-GUI thread):
pictureBox1.Visible = false; // eg.

But am allowed to do:
pictureBox1.Load(url); // url = link to image

A: When you load a new image, this is what happens inside the PictureBox (this is called from the Load method):
    private void InstallNewImage(Image value,
                                 ImageInstallationType installationType)
    {
        StopAnimate();
        this.image = value;

        LayoutTransaction.DoLayoutIf(AutoSize, this, this, PropertyNames.Image);

        Animate();
        if (installationType != ImageInstallationType.ErrorOrInitial)
        {
            AdjustSize();
        }
        this.imageInstallationType = installationType;

        Invalidate();
        CommonProperties.xClearPreferredSizeCache(this);
    }

So you can see that all it really does is set the image and then call Invalidate, which can be called from other threads.
Visible (inherited from Control), which you can see here, does a lot of stuff through p/invoke and must be done on the main UI thread.
    protected virtual void SetVisibleCore(bool value) {
        try {
            System.Internal.HandleCollector.SuspendCollect();

            if (GetVisibleCore() != value) {
                if (!value) {
                    SelectNextIfFocused();
                }

                bool fireChange = false;

                if (GetTopLevel()) {

                    // The processing of WmShowWindow will set the visibility
                    // bit and call CreateControl()
                    //
                    if (IsHandleCreated || value) {
                            SafeNativeMethods.ShowWindow(new HandleRef(this, Handle), value ? ShowParams : NativeMethods.SW_HIDE);
                    }
                }
                else if (IsHandleCreated || value && parent != null && parent.Created) {

                    // We want to mark the control as visible so that CreateControl
                    // knows that we are going to be displayed... however in case
                    // an exception is thrown, we need to back the change out.
                    //
                    SetState(STATE_VISIBLE, value);
                    fireChange = true;
                    try {
                        if (value) CreateControl();
                        SafeNativeMethods.SetWindowPos(new HandleRef(window, Handle),
                                                       NativeMethods.NullHandleRef,
                                                       0, 0, 0, 0,
                                                       NativeMethods.SWP_NOSIZE
                                                       | NativeMethods.SWP_NOMOVE
                                                       | NativeMethods.SWP_NOZORDER
                                                       | NativeMethods.SWP_NOACTIVATE
                                                       | (value ? NativeMethods.SWP_SHOWWINDOW : NativeMethods.SWP_HIDEWINDOW));
                    }
                    catch {
                        SetState(STATE_VISIBLE, !value);
                        throw;
                    }
                }
                if (GetVisibleCore() != value) {
                    SetState(STATE_VISIBLE, value);
                    fireChange = true;
                }

                if (fireChange) {
                    // We do not do this in the OnPropertyChanged event for visible
                    // Lots of things could cause us to become visible, including a
                    // parent window.  We do not want to indescriminiately layout
                    // due to this, but we do want to layout if the user changed
                    // our visibility.
                    //

                    using (new LayoutTransaction(parent, this, PropertyNames.Visible)) {
                        OnVisibleChanged(EventArgs.Empty);
                    }
                }
                UpdateRoot();
            }
            else { // value of Visible property not changed, but raw bit may have

                if (!GetState(STATE_VISIBLE) && !value && IsHandleCreated) {
                    // PERF - setting Visible=false twice can get us into this else block
                    // which makes us process WM_WINDOWPOS* messages - make sure we've already
                    // visible=false - if not, make it so.
                     if (!SafeNativeMethods.IsWindowVisible(new HandleRef(this,this.Handle))) {
                        // we're already invisible - bail.
                        return;
                     }
                }

                SetState(STATE_VISIBLE, value);

                // If the handle is already created, we need to update the window style.
                // This situation occurs when the parent control is not currently visible,
                // but the child control has already been created.
                //
                if (IsHandleCreated) {

                    SafeNativeMethods.SetWindowPos(
                                                      new HandleRef(window, Handle), NativeMethods.NullHandleRef, 0, 0, 0, 0, NativeMethods.SWP_NOSIZE |
                                                      NativeMethods.SWP_NOMOVE | NativeMethods.SWP_NOZORDER | NativeMethods.SWP_NOACTIVATE |
                                                      (value ? NativeMethods.SWP_SHOWWINDOW : NativeMethods.SWP_HIDEWINDOW));
                }
            }
        }
        finally {
            System.Internal.HandleCollector.ResumeCollect();
        }
    }

Just as a side-note, a lot of these "what happens under the hood" can be figured out by browsing the reference source, or creating a small application and decompiling it (I would recommend JetBrains DotPeek, or ildasm works too).

A: The reason you do not get the "Cross-thread operation not valid" message is because the exception is thrown when the control Handle property is accessed:
public IntPtr Handle {
    get {
        if (checkForIllegalCrossThreadCalls &&
            !inCrossThreadSafeCall &&
            InvokeRequired) {
            throw new InvalidOperationException(SR.GetString(SR.IllegalCrossThreadCall,
                                                             Name));
        }

        if (!IsHandleCreated)
        {
            CreateHandle();
        }

        return HandleInternal;
    }
}

As you can see from the accepted answer, SetVisibleCore (called by Visible) uses Handle several times, but InstallNewImage (used by Load) does not.  (Actually, Invalidate does access the Handle property, but it does so within a thread safe call scope which is fine.)