text:
Q: Doubt regarding proof that $\mathbb{Z}, \mathbb{Z}[x]$ are unique factorization domains The usual proof for unique factorization in $\mathbb{Z}$ proceeds via the concept of GCD (greatest common divisor) of two integers leading to the fundamental property of primes in $\mathbb{Z}$:
Theorem: If $p$ is prime and $a, b \in \mathbb{Z}$ such that $p\mid ab$ then either $p\mid a$ or $p\mid b$.
And this is the result which guarantees uniqueness of factorization. Note that the same procedure does not apply in $\mathbb{Z}[x]$ as we don't have a concept of GCD here. Thus for example we can't say that $2, x$ have GCD $1$ because we can't find polynomials $p(x), q(x) \in \mathbb{Z}[x]$ such that $$1 = 2p(x) + xq(x)$$ (contradiction arises when we put $x = 0$ in above equation).
The problem is eliminated by considering polynomials in $\mathbb{Q}[x]$ and then we have the GCD available here so that $\mathbb{Q}[x]$ is a unique factorization domain. Next we use the fact that $\mathbb{Z}[x]\subset\mathbb{Q}[x]$ to factorize elements of $\mathbb{Z}[x]$ as product of polynomials in $\mathbb{Q}[x]$ and then use Gauss lemma to prove that the factorization can also be done using polynomials in $\mathbb{Z}[x]$ only.

Thus it appears that existence of GCD is not necessary to guarantee existence of unique factorization. Does that mean we can prove unique factorization in $\mathbb{Z}$ via some other means rather than the approach I outlined in the beginning?
Also I would like to know if the property of prime numbers (mentioned in theorem at the beginning) is always a consequence of the existence of GCD in a more generally setting of integral domains?

Update: From the comments and in particular the wiki link given by Hand Lundmark it is clear that the ideas of the usual ring of integers have been generalized in many ways to give rise to the famous chain of class inclusions (see wiki link on GCD Domains) and this question is perhaps a very naive attempt to understand that all (or some of) those inclusions are proper.
Further Update: I was a bit hesitant about asking question related to a seemingly trivial matter (namely unique factorization in integers and polynomials with integer coefficients), but the way it has been received here is so much more than what I expected. MSE never ceases to amaze me (and perhaps other users too)! Thanks to all those who answered/commented/chatted. I have now got a lot of food for thought (and study).

A:
Thus it appears that existence of GCD is not necessary to guarantee existence of unique factorization.

Effectively there is not necessary the existence of GCD in order to prove the fundamental theorem of arithmetic. It's enough a weaker condition, namely we only need the four number lemma, see e.g., this answer. This lemma in a more abstract setting give rise to two special classes of domains known as Schreier domains and pre-Schreier domains (or Riesz domains).
Egreg wrote:

It turns out that this is one of the keys for a domain to have unique factorization. Indeed, a domain $R$ has unique factorization if and only if

*

*$R$ has the ascending chain condition on principal ideals;

*every irreducible element in $R$ is prime.
The first condition ensures existence of a factorization into a product of irreducible elements; the second condition ensures uniqueness.

Domains satisfying the first condition are called ACCP domains, whereas the domains satisfying the second condition are called AP-domains (atom $\implies$ prime), where atom=irreducible.
An important result is the following:
Theorem: If $R$ is an ACCP domain, then $R[x]$ is also an ACPP domain.
Proof: This is theorem 17a) in Pete L. Clark's notes on factorization in integral domains.
I'm not aware of any characterization of AP domains, but what I know is that every GCD domain is an AP-domain, even more: both Schreier and pre-Schreier domains are AP-domains and more exactly we have the following chain:
$$\text{GCD-domain} \implies \text{Schreier domain} \implies \text{pre-Schreier domain} \implies \text{AP-domain}.$$
Therefore we have the following characterization of unique factorization domains:
$$\text{UFD} \iff \text{ACCP domain}+\text{Schreier domain}\; (^*)$$
On the other hand, it turn out the being a Schreier domain behaves well under polynomial ring extensions, namely we have the following:
Theorem (Cohn): If $R$ is a Schreier domain, then so is $R[x]$.
Proof: This is theorem 2.7 in the paper Bezout rings and their subrings.
So we can apply (*) to the particular cases of $\Bbb Z$ and $\Bbb Z[x]$ in this way:
i) For $\Bbb Z$:

*

*We can use induction (or the well-ordering principle) to ensure the existence of a prime factorization. Note that $\Bbb Z$ satisfying the well-ordering principle is equivalent to $\Bbb Z$ being an ACPP domain.

*We can use the four number lemma to guarantee the uniqueness.

ii) For $\Bbb Z[x]$:

*

*Since $\Bbb Z$ satisfies the ACCP condition, then $\Bbb Z[x]$ also satisfies the ACCP condition, so this will give us the existence of the irreducible factorization.

*Since $\Bbb Z$ is a Schreier domain, then $\Bbb Z[x]$ is also a Schrier domain, so this will guarantee the uniqueness.

However, there is a little more to say. The classical proof of: $$D\; \text{UFD} \implies D[x]\; \text{UFD}\; (^{**})$$ uses, as you've noted, Gauss' lemma: the product of two primitive polynomials is primitive, but the above result isn't necessary because we can proof (**) without it. For instance, you can check theorem 27 of Pete L. Clark's notes cited lines above.
Returning to Gauss' lemma, this result gives rise to the class of domains known as GL-domains, and Anderson and Zafrullah proved that they are between the class of pre-Schreier and AP-domains. So in conclusion we have the chain:
$$\text{GCD-domain} \implies \text{Schreier domain} \implies \text{pre-Schreier domain}$$ $$\implies \text{GL-domain} \implies \text{AP-domain}.$$
For more info related to Schreier, pre-Schreier and GL-domains you can check these papers:

*

*M. Zafrullah, On a property of pre-Schreier domains, Communications in Algebra, 15 (1987), 1895-1920.

*S. McAdam and D. Rush, Schreier Rings, Bulletin of the London Mathematical Society, 10 (1978), 77-80.

*J. Arnold and P. Sheldon, Integral domains that satisfy Gauss's lemma, The Michigan Mathematical Journal, 22 (1975), 39-51.

*D. Anderson and M. Zafrullah The Schreier property and Gauss' lemma, Bollettino U. MI, 8 (2007), 43-62.

A: There are many similarities between passing from $\mathbb{Z}$ to $\mathbb{Z}[x]$ and from $k[x]$ to $k[x,y]$ ($k$ a field), because both $\mathbb{Z}$ and $k[x]$ are principal ideal domains.
One can see it by "unifying" Gauss' lemma.

Theorem. (General Gauss' lemma) If $R$ is a unique factorization domain with quotient field $Q$ and $f(x)\in R[x]$ is a primitive polynomial which factors in $Q[x]$, then $f$ also factors in $R[x]$.

A nonzero polynomial is primitive if a greatest common divisor of its coefficients is $1$.
But what's a greatest common divisor? In general an element $d$ of a domain is a greatest common divisor (GCD) of $a$ and $b$ if

*

*$d$ divides both $a$ and $b$;

*for all $c$, if $c$ divides both $a$ and $b$, then $c$ divides $d$.

Of course a greatest common divisor, if it exists, is only determined up to multiplication by invertible elements.
In a unique factorization domain (UFD) a GCD exists for every pair of elements: just take the product of all common irreducible divisors with the minimum exponent (irreducible elements differing in multiplication by an invertible should be identified). This is the empty product, that is, $1$ if the two elements have no common irreducible factors.
Note also that in general domains one has to distinguish between prime and irreducible elements. A nonzero and noninvertible element $p$ is

*

*prime if, for all $a,b$, if $p$ divides $ab$, then $p$ divides $a$ or $p$ divides $b$;

*irreducible if, for all $a,b$, if $p=ab$, then $a$ is invertible or $b$ is invertible.
It's easy to show that a prime element is also irreducible. On the other hand, an irreducible element may not be prime.
It turns out that this is one of the keys for a domain to have unique factorization. Indeed, a domain $R$ has unique factorization if and only if

*

*$R$ has the ascending chain condition on principal ideals;

*every irreducible element in $R$ is prime.

The first condition ensures existence of a factorization into a product of irreducible elements; the second condition ensures uniqueness.
The general Gauss' lemma, which is proved essentially the same way as it is proved for $R=\mathbb{Z}$ (and $Q=\mathbb{Q}$), is the key step in proving that if $R$ is a UFD, then also $R[x]$ is a UFD.
On the other hand, the Bézout property of the GCD need not hold for a UFD. It holds when $R$ is a principal ideal domain (PID), but as soon as we pass to $R[x]$, the Bézout property does not hold, unless $R$ is a field. Indeed, the example is the same as you used: take $r\in R$ a nonzero and noninvertible element (which exists if $R$ is not a field); then $1$ is easily seen to be a greatest common divisor of $r$ and $x$ in $R[x]$ according to the above definition, but there do not exist $f,g\in R[x]$ such that
$$
1=rf(x)+xg(x)
$$
(you have $r=2$ in $R=\mathbb{Z}$).
You can use $\mathbb{R}[x,y]$ to get a geometric interpretation of why the GCD cannot satisfy the Bézout property. Consider two irreducible distinct conics, say the circle defined by the polynomial $x^2+y^2-1$ and the parabola defined by $y-x^2$. A GCD of these polynomials is $1$, but there cannot exist polynomials $f(x)$ and $g(x)$ so that
$$
1=(x^2+y^2-1)f(x)+(y-x^2)g(x)
$$
for the simple reason that the relation cannot hold at the two points where the circle and the parabola intersect.


text:
Q: Unity program stopped responding because of a infinite while loop Hello stack overflow users! I was creating a game in unity 2018.2.2f1. All went great, but i missplaced the order of code lines in the program --> which caused a infite while loop appearing. I didn't know it would be infinite so I runned the program. Now my unity window is unselectable when i click on the icon, and when i enter the window, everything is frozen. I would close the program trough task manager, but i didnt save my files and i can't even save the project. Is there any way for me to save the project when it is in this state? My unity didn't crash, it just froze.
Here is my FIXED c# code if that somehow helps (and i am in visual studio):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour {

    public float speed = 10f;
    private Vector3 velocity = new Vector3();
    private string direction = "none";
    private bool canMoveAgain = true;
    private bool go = false;
    // Use this for initialization
    void Start () {
        speed = 10f;
    }

    // Update is called once per frame
    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.collider.name == "wall (3)" && direction == "down")
        {
            go = false;
        }
        if (collision.collider.name == "wall (2)" && direction == "up")
        {
            go = false;
        }
        if (collision.collider.name == "wall" && direction == "left")
        {
            go = false;
        }
        if (collision.collider.name == "wall (1)" && direction == "right")
        {
            go = false;
        }
    }
    void Update () {
        if (Input.GetKeyDown(KeyCode.DownArrow) && canMoveAgain)
        {
            direction = "down";
            go = true;
            canMoveAgain = false;
            while (go)
            {
                velocity = new Vector3(0,-1,0);
                transform.position += velocity;
            }
            velocity = new Vector3(0, 0, 0);
            direction = "none";
        } else if (Input.GetKeyDown(KeyCode.UpArrow) && canMoveAgain)
        {
            direction = "up";
            go = true;
            canMoveAgain = false;
            while (go)
            {
                velocity = new Vector3(0, +1, 0);
                transform.position += velocity;
            }
            velocity = new Vector3(0, 0, 0);
            direction = "none";
        } else if (Input.GetKeyDown(KeyCode.LeftArrow) && canMoveAgain)
        {
            direction = "left";
            go = true;
            canMoveAgain = false;
            while (go)
            {
                velocity = new Vector3(-1, 0, 0);
                transform.position += velocity;
            }
            velocity = new Vector3(0, 0, 0);
            direction = "none";
        } else if (Input.GetKeyDown(KeyCode.RightArrow) && canMoveAgain)
        {
            direction = "right";
            go = true;
            canMoveAgain = false;
            while (go)
            {
                velocity = new Vector3(+1, 0, 0);
                transform.position += velocity;
            }
            velocity = new Vector3(0, 0, 0);
            direction = "none";
        }
    }
}

A: You do
while (go)
{
    velocity = new Vector3(+1, 0, 0);
    transform.position += velocity;
}

but go is never set to false inside the loop.
OnCollisionEnter is never executed since the while is still being executed => freeze.
since Update is called each frame anyway you should rather move that part to a separate if(go) block after checking the Inputs ..
private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.collider.name == "wall (3)" && direction == "down"
        || collision.collider.name == "wall (2)" && direction == "up"
        || collision.collider.name == "wall" && direction == "left"
        || collision.collider.name == "wall (1)" && direction == "right")
    {
        go = false;
        velocity = Vector3.zero;
        direction = "none"
    }
}

void Update ()
{
    if (Input.GetKeyDown(KeyCode.DownArrow) && canMoveAgain)
    {
        direction = "down";
        go = true;
        canMoveAgain = false;
        velocity = -Vector3.up;
    }
    else if (Input.GetKeyDown(KeyCode.UpArrow) && canMoveAgain)
    {
        direction = "up";
        go = true;
        canMoveAgain = false;
        velocity = Vector3.up;
    }
    else if (Input.GetKeyDown(KeyCode.LeftArrow) && canMoveAgain)
    {
        direction = "left";
        go = true;
        canMoveAgain = false;

        velocity = -Vector3.right;
    }
    else if (Input.GetKeyDown(KeyCode.RightArrow) && canMoveAgain)
    {
        direction = "right";
        go = true;
        canMoveAgain = false;
        velocity = Vector3.right;
    }

    if(go)
    {
        transform.position += velocity;
    }
}

Note that currently your code is also frame rate dependent. You might want to rather use something like
public float moveSpeed;

...

transform.position += velocity * moveSpeed * Time.deltaTime;

For the direction I would rather recommend an enum like
private enum MoveDirection
{
    None,
    Up,
    Down,
    Left,
    Right
}

and use it e.g. like
direction = MoveDirection.Up;

and
if(direction == MoveDirection.Up)

which is more efficient than comparing strings.

Note: Typed on smartphone so no warranty but I hope the idea gets clear

A: First of all. Do not close Unity.
You got two things you can try to do.

*

*Luckily your code has a backup when you press run.
It is inside the Temp folder. The Temp folder will be replaced if you press run again. Copy the project to somewhere safe.

*Attach a Debugger, this can be either Visual Studio or MonoDevelop. Once they are attached to Unity just click pause. And you're free to save your project.
I hope you find this answer before it's too late.

redpajama_set_name: RedPajamaStackExchange


text:
Q: I have a drop down menu now how to create submenu inside one link using css I am very new to css trying to learn new language,  I have a dropdowm which i had done using css and html now how to create a submenu into it on hover  over one link
Check my code till now what i did :

.nav-collapse .nav li a {
  font-size: 13px;
  color: #7281a1;
  font-family: 'Noto Sans', sans-serif;
  font-weight: 700;
  text-shadow: none;
  padding: 25px 15px 26px 30px;
}

.nav-collapse .nav>li {
  margin-left: 3px;
  position: relative;
}

.nav-collapse .nav li a#home-nav {
  background: url('../images/home.png') 3px center no-repeat;
}

.nav-collapse .nav li a:hover {
  text-decoration: underline;
  color: #7281a1;
}

ul.dropdown {
  position: absolute;
  width: 150px;
  background: #fff;
  top: 110%;
  left: 0;
  border-top: 2px solid #8248ac;
  visibility: hidden;
  transition: all 0.2s linear;
  -moz-transition: all 0.2s linear;
  -webkit-transition: all 0.2s linear;
  -o-transition: all 0.2s linear;
}

ul.dropdown:before {
  position: absolute;
  content: '';
  width: 0;
  height: 0;
  border: 5px solid #8248ac;
  border-top-color: transparent;
  border-left-color: transparent;
  border-right-color: transparent;
  left: 20px;
  top: -10px;
}

ul.dropdown li {
  border-top: 1px solid #f7f8f9;
}

ul.dropdown li:first-child {
  border-top: none;
}

ul.dropdown li a {
  display: inline-block;
  padding: 10px 7px !important;
}

.nav-collapse .nav>li:hover ul.dropdown {
  visibility: visible;
  top: 100%;
}

      Menu

Dropdown

sub-dropdown

So when user hover on Menu dropdown should come and when user hover in dropdown sub-drop down should come
Thanks in advance!!!

A: You should hide the sub-menu and show it when you hover on the link, just like the first dropdown
add this code to your css file
ul.dropdown li ul {
  display:none;
}

ul.dropdown li.dropdown:hover ul {
  display:block;
}

See working snippet:

.nav-collapse .nav li a {
  font-size: 13px;
  color: #7281a1;
  font-family: 'Noto Sans', sans-serif;
  font-weight: 700;
  text-shadow: none;
  padding: 25px 15px 26px 30px;
}

.nav-collapse .nav>li {
  margin-left: 3px;
  position: relative;
}

.nav-collapse .nav li a#home-nav {
  background: url('../images/home.png') 3px center no-repeat;
}

.nav-collapse .nav li a:hover {
  text-decoration: underline;
  color: #7281a1;
}

ul.dropdown {
  position: absolute;
  width: 150px;
  background: #ccc;
  top: 110%;
  left: 0;
  border-top: 2px solid #8248ac;
  visibility: hidden;
  transition: all 0.2s linear;
  -moz-transition: all 0.2s linear;
  -webkit-transition: all 0.2s linear;
  -o-transition: all 0.2s linear;
}

ul.dropdown:before {
  position: absolute;
  content: '';
  width: 0;
  height: 0;
  border: 5px solid #8248ac;
  border-top-color: transparent;
  border-left-color: transparent;
  border-right-color: transparent;
  left: 20px;
  top: -10px;
}

ul.dropdown li {
  border-top: 1px solid #f7f8f9;
}

ul.dropdown li:first-child {
  border-top: none;
}

ul.dropdown li a {
  display: inline-block;
  padding: 10px 7px !important;
}

.nav-collapse .nav>li:hover ul.dropdown {
  visibility: visible;
  top: 100%;
}

ul.dropdown li ul {
  position: absolute;
  left: 100%;
  top: -2px;
  background: #ccc;
  width: 100%;
  border-top: 2px solid #8248ac;
  display: none;
}

ul.dropdown li.dropdown:hover ul {
  display: block;
}

      Menu

Dropdown

sub-dropdown


text:
Q: Struggling with Plural/Singular? Which of the following is a grammatically correct statement?

*

*The value of cars depreciate over time.

*The values of cars depreciate over time.

*The value of cars depreciates over time.
Thanks!

A: The first one is incorrect.

The value of cars depreciate over time.

The verb should agree with 'value', not cars.
For this reason, the 2nd and 3rd ones are both correct. Their usage depends on context.
Consider:

The values of (most) cars depreciate over time.

Values of different cars
and

The value of (my) cars depreciates over time.

Value of all my cars taken collectively


text:
Q: Keepalived/Haproxy docker-compose connection refused Docker Version: Version 17.03.0-ce-mac2 (15654)
OS: macOS Sierra
I am trying to setup an HA environment using docker-compose. A quick overview of the what the topology might look like is that I will have at least two instances of keepalived and haproxy running, the haproxy will be in front of multiple servers. However, in this posting I make reference to only one instance of keepalived, haproxy, and server for simplification.
The problem that I have right now is that I am unable to direct traffic to the virtual IP address that I assign to keepalived. For testing purposes in my docker compose file I have a client that tries to communicate using the VIP, and it results in a connection refused error.
dial tcp 192.168.99.120:80: getsockopt: connection refused

However, if I reach out directly to haproxy there is not a connection issue. Furthermore, I can communicate directly to the haproxy from host but not to keepalived.
I feel like this has something to do with how networks work in docker but I am pretty new to using docker and have not been able to track down the issue. Any help would be much appreciated.
My configuration files are all included below.

docker-compose.yml:
version: '2'

services:
keepalived1:
  image: neoassist/docker-keepalived:latest
  container_name: keepalived1
  volumes:
    - "./keepalived.conf:/etc/keepalived/keepalived.conf"
  environment:
    - VIRTUAL_IP=192.168.99.120
    - VIRTUAL_MASK=24
    - VRID=1
    - CHECK_IP=any
    - CHECK_PORT=80
    - INTERFACE=eth0
  entrypoint: sh -c 'sleep 4;/usr/bin/keepalived.sh'
  network_mode: "host"
  cap_drop:
    - NET_ADMIN
  privileged: true

haproxy1:
  image: haproxy:latest
  container_name: haproxy1
  ports:
    - 7054:7054
  volumes:
    - "./haproxy1.cfg:/usr/local/etc/haproxy/haproxy.cfg"
  environment:
    - EXPOSE=7054
  links:
    - fabric-ca-server1:fabric-ca-server1

fabric-ca-server1:
  image: hyperledger/fabric-ca
  container_name: fabric-ca-server1
  ports:
    - 7051:7054
  environment:
    - FABRIC_CA_HOME=/etc/hyperledger/fabric-ca-server
  volumes:
    - "./fabric-ca-server:/etc/hyperledger/fabric-ca-server"
  command: sh -c "fabric-ca-server start -d -b admin:adminpw"

admin-client:
  image: hyperledger/fabric-ca
  container_name: admin-client
  network_mode: "host"
  command: sh -c "sleep 14;fabric-ca-client enroll -d -u http://admin:adminpw@192.168.99.120"

haproxy.cfg
global
  maxconn 4096

defaults
  mode http
  maxconn 2000
  timeout connect 5000
  timeout client 50000
  timeout server 50000

frontend server
  bind *:7054
  mode tcp
  default_backend server_cluster

backend server_cluster
  balance source
  mode tcp
  option tcpka
  server server1 fabric-ca-server1:7054

keepalived.conf
vrrp_script haproxy {
 script "pidof haproxy"
 interval 2
 weight 2
}

vrrp_instance haproxy_1 {
 virtual_router_id 1
 advert_int 1
 interface eth0
 nopreempt
 state BACKUP
 virtual_ipaddress {
  192.168.99.120/24 dev eth0
 }

 track_script {
  haproxy
 }
}

ifconfig from my mac has:
vboxnet0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 1500
ether 0a:00:27:00:00:00
inet 192.168.99.1 netmask 0xffffff00 broadcast 192.168.99.255

A: I don't think this will ever work with Docker for Mac because it actually uses a VM under the covers to run your Docker containers.  This should work on a system with native Docker support if you try using host networking rather than bridge networking.
My suggestion would be to look at either Docker swarm mode (not the standalone Docker swarm) or Kubernetes which both provide mechanisms to scale services and provide load balancing across them via a single address


text:
Q: Push object to empty array if not exist angularjs I created an array is empty. I want to push unique object. I want to use for loop. But firstly array length is zero. So doesnt work for loop. How can I do?
$scope.arr=[];
$scope.result=[
   {category: "Home", categoryInt: 1, categoryPercent:50},
   {category: "Office", categoryInt: 1, categoryPercent:25},
   {category: "Office", categoryInt: 1, categoryPercent:25},
   {category: "Office", categoryInt: 1, categoryPercent:25}
[
for(var z=0; z<$scope.arr.length; z++){
    if ($scope.arr[z].percent === $scope.result[a].categoryPercent) {
        return;
    } else {
        $scope.arr.push({category: $scope.result[a].category, percent: $scope.result[a].categoryPercent, categoryInt: $scope.result[a].categoryInt});
    }
}

A: Use Array.reduce() to have array of object of unique objects. Below is working code:

let arr = [];
var result = [{category:"Home",categoryInt:1,categoryPercent:50},{category:"Office",categoryInt:1,categoryPercent:25},{category:"Office",categoryInt:1,categoryPercent:25},{category:"Office",categoryInt:1,categoryPercent:25}];

arr = Object.values(result.reduce((acc, cur) => Object.assign(acc, {
  [cur.categoryPercent]: cur
}), {}));

console.log(arr);


text:
Q: Web push library is failing to Create web push notification in Google Chrome with error type '(ArrayBuffer or ArrayBufferView)' I want to send push notification from java library called Web-push library for java. It is Working file in firefox but when it comes to Google Chrome then it failed to Subscribe the push manager with following.
Failed to execute 'subscribe' on 'PushManager': The provided value is not of type '(ArrayBuffer or ArrayBufferView)'
Here are the code and my folder structure of the project.
Before I have tried the same code for google chrome that time it is executed properly. That time it won't authorize the for Mozilla Firefox, That was the server-side error I figured out.

async function subscribe() {
const response =  await fetch('./VapidPublicKey');
const vapidPublicKey =  await response.text();
console.log(vapidPublicKey);
    const convertedVapidKey = urlB64ToUint8Array(vapidPublicKey);
    var browserOptions={};
    if(typeof InstallTrigger !== 'undefined'){
       browserOptions={userVisibleOnly: true};
    }else{
          browserOptions={
               userVisibleOnly: true,
               applicationServerKey: convertedVapidKey
           };
    }
       navigator.serviceWorker.ready.then(function
    (serviceWorkerRegistration)
       {
       serviceWorkerRegistration.pushManager.
        subscribe(browserOptions).then(function
        (subscription) {
              return sendSubscriptionToServer(subscription);
             })
             .catch(function (e) {
                if (Notification.permission === 'denied') {
                   console.warn('Permission for Notifications was denied');
                    } else {
                  alert('Unable to subscribe to push.'+ e);
                 }
            });
        });
        }

'
    ##And below is code for conversion from base64url to uint8Array ##'

      async function urlB64ToUint8Array(base64String){
        const padding = '='.repeat((4 - base64String.length % 4) % 4);
      const base64 = (base64String + padding)
      .replace(/\-/g, '+')
     .replace(/_/g, '/');

      const rawData = window.atob(base64);
      const outputArray = new Uint8Array(rawData.length);
      for (let i = 0; i < rawData.length; ++i) {
         outputArray[i] = rawData.charCodeAt(i);
       }
      console.log("output array is : "+outputArray);
         return outputArray;
        }

Folder structure

RootFolder
       |-WebCOntent
            |-index.html
            |-main.js
            |-sw.js
            |-manifest.json

The exception I am getting

TypeError: Failed to execute 'subscribe' on 'PushManager': The provided value is not of type '(ArrayBuffer or ArrayBufferView)'

I have Resolved above type error
below code worked for me

const urlB64ToUint8Array = (base64String)=>{
    const padding = "=".repeat((4 - base64String.length % 4) % 4);
    const base64 = (base64String + padding).replace(/\-/g, "+").replace(/_/g, "/");
    const rawData = window.atob(base64);
    const outputArray = new Uint8Array(rawData.length);
    for (let i = 0; i < rawData.length; ++i) {
      outputArray[i] = rawData.charCodeAt(i);
    }
    return outputArray;
}


text:
Q: Unable to read data from firebase Recently i am trying working on an IOS app and had just started using the newly revamp firebase for all the backend stuff. I was following the default IOS tutorial below
https://codelabs.developers.google.com/codelabs/firebase-ios-objc/index.html?index=..%2F..%2Findex#0
for firebase and trying to integrate a portion of the code in the tutorial into my IOS app project.
Basically, I am trying to read data from firebase and display it on my IOS app, however, i am unable to get it to work and I can't figure out why.
With the help of the tutorial, I had completed the below needed steps
1) Added GoogleService-Info.plist file
2) Input the correct bundle ID
3) Installed all the Firebase related pods
4) Added the rules to "read" and "write" the data
Below is an image of my firebase database:

Below is an image of my function to read data from firebase:

I do not encounter any major error when running the app. I can compile the code smoothly. However, I just can't get the code to print out the data in the Xcode console using NSLog.
Any kind advise? -- solved, look at the commends below for answer

A: You are not getting data because you are querying for a key hotel_bookings while on the firebase side you have key hotel bookings,
You can do either one thing , convert your key to hotel_bookings in your FireBase Database and its a good thing not have spaces in your keys.
See if this helps..


text:
Q: Extended Events - Not showing log file growth We have a standard extended event session to collect database and log file growth running on our SQL servers.  I was creating an index on a large table, knowing it might fill up the transaction log.  It did, however the DBA that went to investigate why the log drive was out of room, couldn't see the index build as the culprit.  It was showing every other transaction but the index build.   Does anyone know the reason behind this?  I killed the index build as soon as I realized there was a problem, and it released all of the space. I would like to know the WHY behind this.
This server is running SQL 2016 CU 15 - Enterprise edition.
Here is the query I was running:
CREATE NONCLUSTERED INDEX [ix_myIndex]
    ON [dbo].[MyTable]([MyField] ASC)
    WITH(PAD_INDEX=OFF, STATISTICS_NORECOMPUTE=OFF, SORT_IN_TEMPDB=ON, DROP_EXISTING=OFF, ONLINE=ON, ALLOW_ROW_LOCKS=ON, ALLOW_PAGE_LOCKS=ON);

Below is the event we have for capturing log file growth:
 ADD EVENT sqlserver.databases_log_file_size_changed
      (ACTION
            (package0.collect_system_time,
       sqlos.task_time,
       sqlserver.client_app_name,
       sqlserver.client_hostname,
       sqlserver.client_pid,
       sqlserver.database_id,
       sqlserver.database_name,
       sqlserver.server_instance_name,
       sqlserver.session_id,
       sqlserver.sql_text,
       sqlserver.username))

A: Let me extend an analogy. Let's say you had a swimming pool that was mostly filled with water (because who likes to swim in an empty pool?). Now it starts to rain and the swimming pool overflows! Would you say it was the rain that caused it to overflow or the fact that it was mostly full when it started to rain?
The extended event is capturing the rain event from my example. And it's technically right!


text:
Q: Calling a method from a model in a rails migration? Super new to rails, but is it possible to call methods from a model in a migration?
Lets say I have a model that looks like:
class Orders < ApplicationRecord

   def order_size
      Order.where(item_id: 1).count
   end

   def order_level (order_size)
     if order_size =< 2
       Order.update_all(customer_level: "Bronze")
     elsif order_size >= 3 && order_size < 6
       Order.update_all(customer_level: "Silver")
     elsif order_size >= 6
       Order.update_all(customer_level: "Gold")
     end
   end

end

Could I run a migration that will only update certain size orders, such as:
class SomeMigration < ActiveRecord::Migration
    def change
       if order_size == 10
         (call/do order_level)
       end
    end
 end

Just for context, I've implemented a separate functionality that will automatically update an order's customer_level when a new order is created with order_level, but I need to go back and update all of the orders that already exist. I only really care about orders that are 10+ in this case.
Hope this makes sense and isn't completely ridiculous!
Thanks

A:
is it possible to call methods from a model in a migration?

Yes. As illustrated in the docs, section 8 Migrations and Seed Data, you can call model methods in a migration. Here is the sample code from the docs:
class AddInitialProducts < ActiveRecord::Migration[5.0]
  def up
    5.times do |i|
      Product.create(name: "Product ##{i}", description: "A product.")
    end
  end

  def down
    Product.delete_all
  end
end

Whether it is a good idea or not is a separate question.


text:
Q: DateFormat with Milliseconds in standard Java Library? I'm wondering if there is a static String or DateFormat anywhere in the standard Java library for formatting dates 'completely'. By completely, I mean the date and time including milliseconds and timezone, something along the lines of "dd MMM yyyy HH:mm:ss.SSS zzz". It's easy to just declare the string myself, but it would be nice if I didn't have to do that for every project I use that needs millisecond-precision date parsing. I have been unable to find one so far.
As an aside, I think it's a little silly that java.util.Date#toString() doesn't account for milliseconds when the class it represents does.
Edit - Unfortunately, it is not as simple as beginning the conversion over to DateTime usage, as that is not something that is in my control. I am the 2nd most junior developer on the project. I would love to use DateTime going forward, but without the support of my supervisor, I cannot.

A: Also for Java 8 Date Time Api you can use
LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME);

for results like that
2017-03-27T20:46:03.852


text:
Q: Is this the right approach to read a DOCX file from a database and open it into the current document? I'm developing a Word Add-in (Taskpane) which the main goal is replacing some predefined content controls of documents persisted in a database. This add-in is a web app using Office.JS. Based on some user input the Add-in should get the file and open it.
My first approach based in the Office documentation was the following:
fetch(`/arquivo?id=${idModeloDocumento}`)
     .then(response => response.text())
     .then(base64String => {

         Word.run(async context => {
             const app = context.application;
             const doc = app.createDocument(base64String); // base64string comes from my backend app
             doc.open();
             await context.sync();
         });
     })

However, it opens the document on a new instance of Word App, different from the one where the add-in is already running. So I created the document and inserted each part of the document (just body and header at this context) into the current document like this:
fetch(`/arquivo?id=${idModeloDocumento}`)
     .then(response => response.text())
     .then(base64String => {

        Word.run(async context => {
             var base64doc = base64String
             const app = context.application
             const doc = app.createDocument(base64doc)
             await context.sync()
             console.log("Novo documento criado")

             let bodyOoxml = doc.body.getOoxml()
             let headerOoxml = doc.sections.getFirst().getHeader(Word.HeaderFooterType.primary).getOoxml()

             await context.sync()
             console.log("Preenchendo o body do documento corrente")

             let curHeader = context.document.sections.getFirst().getHeader(Word.HeaderFooterType.primary)
             curHeader.insertOoxml(headerOoxml.value, Word.InsertLocation.replace)

             let curBody = context.document.body
             curBody.insertOoxml(bodyOoxml.value, Word.InsertLocation.replace)

             await context.sync()
             console.log("Pronto")
         });

     })

It works, however, I'm not 100% sure if it is the right way to do that.
What's the recommended approach to open a Docx file in the current document using OfficeJS?


text:
Q: Python Selenium errors started showing up Earlier today I was able to access the website below and run my automated script using Python Selenium.
A few hours later, after taking a break, using the exact same script I get the following errors. Anyone know why that is? I didn't change anything on my end. Could the website have made changes on their end? I replaced the website name with XXXXX's.
[0615/185824.599:INFO:CONSOLE(2)] "jQuery.Deferred exception: Cannot read property 'top' of undefined TypeError: Cannot read property 'top' of undefined
    at isVisible (https://www.XXXXXX:207:32)
    at showAllTimesEnd (https://www.XXXXXX:199:18)
    at HTMLDocument.<anonymous> (https://www.XXXXXX:328:4)
    at l (https://www.XXXXXX.com/Scripts/jquery-3.3.1.min.js:2:29375)
    at c (https://www.XXXXXX.com/Scripts/jquery-3.3.1.min.js:2:29677) undefined", source: https://www.XXXXXX.com/Scripts/jquery-3.3.1.min.js (2)
[0615/185824.619:INFO:CONSOLE(2)] "Uncaught TypeError: Cannot read property 'top' of undefined", source: https://www.XXXXXX.com/Scripts/jquery-3.3.1.min.js (2)


text:
Q: Ruby on Rails - undefined method `split' for nil:NilClass / NoMethodError in StocksController#search I'm a Rails newbie and I'm taking the Complete Ruby on Rails Developer Course on Udemy. I'm getting the following error when I try to go to the /search_stocks route.

Here's the repo in its current state (I also have the code pasted below): https://github.com/sarahbasinger/rails-stock-tracker
Here's the Udemy course repo:
https://github.com/udemyrailscourse/finance-tracker
The TA for the course suggests it might be a gem version conflict. I'm using Rails 5.1.4 (maybe a newbie mistake - I thought using the latest and greatest would be a good way to go). The teacher in the course is using Rails 4. The TA suggested I use the same gem versions as the course, so I updated my Gemfile to match the course Gemfile, ran bundle install, and with that, I can't even get the rails server to run. I get a different error. So I'm back to trying to get this app running using Rails 5. However, I have no experience trying to resolve gem version conflicts, if that is the issue.
Here's the relevant code:
Model
class Stock < ActiveRecord::Base

    def self.new_from_lookup(ticker_symbol)
        looked_up_stock = StockQuote::Stock.quote(ticker_symbol)
        new(name: looked_up_stock.name, ticker: looked_up_stock.symbol, last_price: looked_up_stock.l)
    end
end

Controller
class StocksController < ApplicationController

    def search
        @stock = Stock.new_from_lookup(params[:stock])
        render json: @stock
    end
end

View

My portfolio

Search for stocks

<%= form_tag search_stocks_path, method: :get, id: "stock-lookup-form" do %>

                <%= text_field_tag :stock, params[:stock], placeholder: "Stock ticker symbol", autofocus: true, class: "form-control search-box input-lg" %>

                <%= button_tag(type: :submit, class: "btn btn-lg btn-success") do %>
                     Look up a stock
                <% end %>

    <% end %>

Gemfile
source 'https://rubygems.org'

git_source(:github) do |repo_name|
  repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
  "https://github.com/#{repo_name}.git"
end

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.1.4'
gem 'devise'
gem 'twitter-bootstrap-rails'
gem 'jquery-rails'
gem 'devise-bootstrap-views'
gem 'stock_quote'
# Use Puma as the app server
gem 'puma', '~> 3.7'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.2'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  gem 'sqlite3'
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  # Adds support for Capybara system testing and selenium driver
  gem 'capybara', '~> 2.13'
  gem 'selenium-webdriver'

end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '>= 3.0.5', '< 3.2'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'

end

group :production do
  gem 'pg'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

Any help is appreciated!

A: It looks to me that you need a parameter called "stock". In line 4
@stock = Stock.new_from_lookup(params[:stock])

It is looking for a URL parameter called "stock" which is a ticker symbol. Try something like:
localhost:3000/search_stocks?stock=goog

That will create a stock param and give it something to look up. You could also put in some code to handle the case where the param is nil.
def search
    if params[:stock]
        @stock = Stock.new_from_lookup(params[:stock])
    else
        # you should have some directions here for what happens if there is no stock param given.
        @stock = nil
    end
    render json: @stock
end

Probably even better to do that in the model, now that I think of it:
def self.new_from_lookup(ticker_symbol)
    if ticker_symbol
        looked_up_stock = StockQuote::Stock.quote(ticker_symbol)
    else
        # something here for a missing stock param
        looked_up_stock = Stock.first
    end
    new(name: looked_up_stock.name, ticker: looked_up_stock.symbol, last_price: looked_up_stock.l)
end

I hope this helps!

A: You can try the following because most of the time gem functionality updating that's why not working on implementing this code. I've recently worked this type of project write code the below which is tested.
Model
def self.find_by_ticker(ticker_symbol)
    where(ticker: ticker_symbol).first
end

def self.new_from_lookup(ticker_symbol)
    begin
        looked_up_stock = StockQuote::Stock.quote(ticker_symbol)
        price = strip_commas(looked_up_stock.l)
        new(name: looked_up_stock.name, ticker: looked_up_stock.symbol, last_price: price)
    rescue Exception => e
        return nil
    end
end

def self.strip_commas(number)
    number.gsub(",", "")
end

Hope to help


text:
Q: Inspecting first row In SSRS 2008 I have 10 columns, and the data is grouped up based on column one (lets call it employee number), and has multiple rows in each group, ordered by a weekly date with the most recent week is at the top.
In column 10 of the group header row, I would like to check if column 10 on the first row contains the value 1 and if so, set a red box/indicator in that header column 10. If any of the other rows below the first contain a 1 then return amber otherwise remain uncoloured.
Is this possible?

A: Have you tried using the FIRST function in the expression field of the BackgroundColor property?


text:
Q: Allow user to insert a custom image I was in the middle of making a VB.NET (Visual Basic 2010 Express) application when I hatched an idea. I want users to be able to insert their own images into my application. How would I do so? I know it has something to do with the open file dialog.

A: You can do it with the following code.
if you want to show it in a picturebox, you can follow the below code, else you can save the byte data of the image into DB.
    OpenFileDialog1.ShowDialog()
    PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)


text:
Q: What is the format of Eloqua Contact Id? Bulk api is returning ids as for ex: "CTPOP000000000007" ,does this mean eloqua format is: first 5 letters are characters and the rest represent a number?

A: Eloqua contact is an unique field.
It is formed of:

*

*C stands for contact

*TPOP is the instance login prefix

*000000000007 is the id , so this means that this is the 7th id registered in your eloqua system


text:
Q: Import categories programatically in magento 2 I have 250+ categories and sub categories with me. I want to import it in my magento 2. It is not possible to manually add it. Can anyone help me with some scripts or code to import categories from csv.  Please dont reccomend any extension unless it is free.

A: Check below link maybe that'll help you:

https://www.dckap.com/blog/magento-2-import-a-category-with-its-subcategories-programmatically/

And create a module as per the instruction.
This will Import a category with its subcategories programmatically.
I also suggest you to remove/disable this module once you have successfully imported category.


text:
Q: count items in col as rows MYSQL Dear developers and programmers,
I have a tabel with SHOP_ID, PROD_ID, ipadres and some more tables, but these are where its all about...
Looks like this:
id ip number        timestamp   shop_id prod_id
--------------------------------------------------
42  81.69.205.25    1319488326  2       3
43  81.205.141.48   1319492649  2       3
44  193.58.10.10    1319520579  14      17
45  84.28.22.226    1319529529  11      19
46  88.15.81.188    1319543745  2       1
47  178.17.241.191  1319563031  14      7
48  87.28.107.171   1319563038  2       6
49  80.156.47.144   1319572818  14      7
50  82.76.241.175   1319577506  11      1
51  82.76.241.175   1319577584  13      1
52  82.76.241.175   1319577785  14      1
53  82.76.241.175   1319577860  4       1
54  62.94.133.153   1319579221  14      1
55  62.94.133.153   1319579281  2       3
56  77.70.175.221   1319617238  11      1
57  77.70.175.221   1319621845  13      1
58  77.70.175.221   1319621848  2       1
59  77.70.175.221   1319621850  11      1
.... more
--------------------------------------------------------

Is there a way to see for each prod_id how many ip numbers there excist for each shop id?
output example
        1        2        3        4        5
---------------------------------------------
1       18       5        51       8        4
2       58       5        45       3        4
3       7        6        31       9        2

where horizontal is the prod_id and vertical is the shop_id
I've don this already:
select

shop_id,
count(distinct(ipadres)) amount

from table

GROUP BY    shop_id

order by amount desc

but this wil give me only the result of all prod_id's combined.
I would like to have the prod_id's seperate in columns.
I hope there is a solution!
Kind Regards

A: Try this
select `prod_id`,shop_id,
    count(distinct(ipadres)) amount
    from table
    GROUP BY shop_id,prod_id
    order by amount desc


text:
Q: Why 'textViewDidChangeSelection' method falls into an infinite loop in Swift? My application uses UITextView to enter text in chat view. I added a placeholder to this by using this answer. The problem occurs when trying to delete longer marked text, then the program falls into infinite loop. For shorter texts the program works correctly and removes selected text. Do you have any idea what might be wrong? How to fix it?
    func textViewDidChangeSelection(_ textView: UITextView) {
    if placeholderState == .enabled {
        if self.window != nil {
            textView.selectedTextRange = textView.textRange(from: textView.beginningOfDocument,
            to: textView.beginningOfDocument)
        }
    }
}

Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ffee7df4fb8)

A: Changing selectedTextRange will call again textViewDidChangeSelection of the delegate.
If you want to change the selection behavior of your text view, you can subclass UITextView.


text:
Q: How to get pHAT Stack to power multiple motor bonnets individually? We are working with a Raspberry Pi 4B and we are trying to power 6 different stepper motors with it. We have 3 different motor bonnets to drive 2 motors each and we bought the pHAT Stack to connect the 3 motor bonnets to the Raspberry Pi. We need each motor to be controlled individually but right now when we run our script all the motor bonnets do the same thing (i.e. if we control stepper1 on the code, all stepper1s do the same thing).
So our question is, how do we specify the address of each bonnet on the pHAT stack in order to power each motor individually? Or do the motor bonnets all use the same i2c address and the motors are not able to be controlled individually?
Any help would be amazing!
Here is an image of our setup without the power supply and with only 2 motor bonnets and 2 motors (1 in each bonnet as stepper1). For this example setup, how can we configure the address of each bonnet so that we can call it in our code to reference that bonnet when we want to control the motors it's driving?

The list of parts we are using:
Raspberry Pi 4 B
pHAT Stack
Motor Bonnet
Stepper Motor
We were expecting to be able to stack 3 different bonnets to be able to address each of them with a specific i2c address, but we might not be understanding the way i2c addresses work. We cannot initialize separate motorkits (we are using Adafruit's MotorKit library to drive the stepper motors) with different addresses on the pHAT stack.


text:
Q: how to disable "created" from SharePoint "When an item is created or modified" workflow? Is there any way to have this workflow trigger be "When an item is MODIFIED" only and not created???

A: In the workflow settings there is a checkbox that says when an item is created or when an item is modified. Make sure just the Start Workflow automatically when an item is changed is the only one checked.... see screenshot attached


text:
Q: jQuery deferred promise I have this code below which is not working as I am expecting.Here GetAllFileNames is Async function and I want to do some sequential action based on result of this funciton. So I am using Jquery promise. But I feel that statement return deferred.resolve(GetAllFileNames) is not correct.It immediately calls promise.then without even waiting for GatAllFileNames to finish.Please note this is not actually working code.
function getfilenames() {
  var deferred = $.Deferred();

  if(condition == true) {
    return deferred.resolve(JSON.parse(allFileNames));
  } else {
    return deferred.resolve(GetAllFileNames());
  }
}

var promise = getfilenames();
promise.then(function(fileNames) {
  result.fileNames = fileNames;
});

UPDATE: I tried some of your comments ,but none of them is working.Here is one of example which is not working
<!DOCTYPE html>

A: You should resolve the deffered when operation is acutully performed.
In this Example 'Got all files' will be displayed before 'get all files'

Got all file names
  Get all files names

function GetAllFileNames(ms) {
    //simulate delay
    setTimeout( function() { console.log('Get all files names') ; return 20;}, ms);
}

function getfilenames() {

    var def = $.Deferred();

    def.resolve(GetAllFileNames(2000));

    return def;
}

getfilenames().then( function() { console.log('Got all file names'); });

but here console log order would be

Get all file names
  Got all file names

function GetAllFileNames(ms, def) {
    setTimeout(function() {
        console.log('Get all file names');
        def.resolve();
        return 20;
    }, ms);
}

function getfilenames() {

    var def = $.Deferred();

    var result = GetAllFileNames(2000, def);

    return def;
}

getfilenames().then(function() {
    console.log('Got all file names');
});

because deffered is resolved when GotAllFilesNames is ready.

A: Edit, updated ; see comments at Question
Try (this pattern)
 var result = {};
 var GetAllFileNames = function () {
        return {
            "allFileNames": [1, 2, 3, 4, 5, 6, 7, 8, 9]
        };
    };
var getfilenames = function (condition) { // `condition` ?
    return $.when(
             condition
             ? JSON.parse(allFileNames)
             : GetAllFileNames()
           );
    };

    getfilenames(false) // `condition` ?
    .then(
    // `done`
      function (fileNames) {
        result.fileNames = fileNames;
        $("" + result.fileNames.allFileNames + "")
            .appendTo("body");
    }
    // `fail`
    , function () {
        console.log(new Error("getfilenames error").message);
    });

jsfiddle http://jsfiddle.net/guest271314/9f12san7/


text:
Q: Is there a way to automatically restart Apache on Mac OS X if it crashes? I've installed Apache using MacPorts. It crashes every once in a while, and I need to manually restart it.
Is there a way to get Apache to automatically restart if it dies for some reason? Perhaps using launchd somehow?

A: Use launchd to start Apache, and make Apache run in the foreground so launchd can monitor it and restart it if it crashes. Since the system includes a launchd item (/System/Library/LaunchDaemons/org.apache.httpd.plist) to start the built-in version of Apache, I'd just copy that to /Library/LaunchDaemons, change the filename and Label so launchd won't get them confused, remove the Disabled key, and change ProgramArguments to point to the MacPorts version of Apache. Be sure to keep the -D and FOREGROUND arguments to httpd, or it'll daemonize itself and launchd will start another instance and nothing useful will get done.
(And do follow @RedGrittyBrick's advice about finding the actual cause of the crash. While launchd is the "right" way to start a daemon like Apache on Mac OS X, it's just a band-aid for whatever problem Apache is having.)


text:
Q: How Can I fillup bootstrap grid using foreach? As I am trying to make bootstrap grid structure using foreach two column and inside it's one row and two rows structure. Attached a screen shot for better to better view.
Note: Not issue with CSS but first three items are goes in grid as picture.
Counter is not taking col-md-4 and not sure where to use Counter increment counter++? What if I want to show first three items using foreach?
Any other way to workaround on this layout? Tried so far as below
  <?php $counter = 0;
            foreach($view->result as $result) {

            <?php if( $counter == 0 || $counter % 3 == 0 ) {    ?>

                    // first element common body

       <?php if( $counter == 1 || $counter == 2 ) { ?>

           <?php if( $counter == 1){ ?>

                    // second element common body

          </php if ( $counter == 2){

                    // third element common body

         <?php counter++; } } ?>

 //closing row
      <?php } ?>  //closing foreach

A: There are couple of syntax errors in your code, such as:

*

*Opening and closing braces are not in sync i.e. foreach loop and if block(s) are not closed properly

*counter++; should be $counter++;
Plus, there are few logical errors as well. Change your code in the following way,
<?php
    $counter = 0;
    foreach($view->result as $result) {
    ?>

        <?php if( $counter == 0 || $counter % 3 == 0 ) { ?>

                    // first element common body

        <?php } ?>
        <?php if( $counter != 0 && $counter % 3 != 0 ) { ?>

            <?php if( $counter % 3 == 1){ ?>

                    // second element common body

            <?php } ?>
            <?php if ( $counter % 3 == 2){ ?>

                    // third element common body

            <?php } ?>

    <?php
        }
        ++$counter;
    }
?>


text:
Q: regex expression to extract css comments with a shell script I would like to extract css comments from style.css.
Comments are in the beginning of the css files and they are formatted like this
/*
Author:name
URI:link
etc
*/

After some searches I found :
sed -n '/^\/\*\$,/\*\/$/p' style.css

It didn't work, I had this error :
sed: -e expression #1, char 11: unknown command: `\'

Do you suggest a good solution.
If possible with a good link for a tutorial for basic sed uses for beginners.

A: This sed should work:
sed -n '/\/\*/,/\*\//{P;/\*\//q;D;}' style.css

A: I think you mean:
sed -n '/^\/\*$/,/\*\/$/p' style.css

You had $ and / in the first regep backwards.

A: If they are always in a colon delimited format like that, you can use:-
sed -n '/Author/p' | cut -d':' -f2

That will get you the author name.  I'd definitely recommend learning about cut for colon delimited files.


text:
Q: AR on Android - movement within an area I am totally new to Android development. I'm not looking for code but what I am looking for is suggestions for how I could approach a problem. Essentially I am looking for suggestions for how I could have a predefined square (consisting of 4 gps points) representing a square. When the app user physically moves (with their phone) outside of the grid area, a message is displayed onscreen telling them that they're outside the area.
I envisage having to use gps coordinates to determine if a user moves outside the area. However I'm looking for advice on how to tackle the problem of the user moving around with the phone in their hand. I imagine that the GPS would have to constantly poll the GPS service to determine the coordinates of the user as they move (on demand) in order to determine if the user is outside the area. However, I'm sure that this is inefficient due to battery exhaustion and also having to constantly poll the GPS service to get the current coordinates of the user as they are walking. Is there perhaps some sort of app for the android that can dynamically determine a user's coordinates within a predefined area locally without having to constantly poll GPS for coordinates? I'm shooting in the dark here. Any suggestions appreciated!
Thanks again

A: You will want to use a LocationListener
You'll find that there are many ways, with varying degrees of accuracy, to get someones location.  LocationManager is a service on android devices that takes care of dispatching location updates.
What your application would do is register a listener to the gps that says, in broad temrs, 'tell me when the users position changes by more then 10 meters, no more then once every 5 seconds'.  This gives a broad set of operational guidelines to the LocationManager about how to service your request.  It sounds like your use case would require GPS, because of the specifics of what you're request needs to be able to tell you.
Take a look at the documentation for LocationListener and LocationManager, thats where you would start.


text:
Q: Bootstrap button dropdown with custom content I'd like to use Bootstrap's button dropdown to display a form component instead of a list of other buttons with additional information. Is it possible?

A: Yes, this is possible by replacing the usual
text
 that is inside the button dropdown with
[form code]
; I have added a form into a dropdown like so;
Code:

    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">Click for form

    </button>

                Email address
                <input type="email" class="form-control" id="exampleInputEmail1"
                placeholder="Enter email">

                Password
                <input type="password" class="form-control" id="exampleInputPassword1"
                placeholder="Password">

                File input
                <input type="file" id="exampleInputFile">

Example block-level help text here.

                    <input type="checkbox">Check me out

            <button type="submit" class="btn btn-default">Submit</button>

Preview:

DEMO


text:
Q: Dot plot of all columns in R against the column number Suppose I have a data frame like below
mydf=data.frame(method=factor(1:10), x1=rpois(10,2), x2=round(rnorm(10),3), x3=rgeom(10,0.3))

I would like to make a dot plot of all variables from X1 through X3 in the same figure. I tried the following code
plot(mydf$x1~rep(1,10), xlab="", ylab = "")
plot(mydf$x2~rep(2,10), xlab="", ylab = "")
plot(mydf$x3~rep(3,10), xlab="", ylab = "")

How can I plot them in single figure?

A: Probably not what you had in mind, but maybe give ggplot a try?
library(dplyr)
library(tidyr)
library(ggplot)
mydf %>%
   pivot_longer(-method, names_to = "variable") %>%
ggplot(aes(x = variable, y = value)) +
  geom_point()

Otherwise, just use points instead of plot:
plot(mydf$x1~rep(1,10), xlab="", ylab = "", xlim = c(0.5,3.5), ylim = range(mydf[,2:4]), xaxt = 'n')
points(mydf$x2~rep(2,10))
points(mydf$x3~rep(3,10))
axis(1,at = 1:3)

A: You might be looking for matplot.
matplot(t(mydf[-1]), pch=16, col=1, xaxt="n")
axis(1, 1:3, names(mydf[-1]))

Data:
set.seed(42)
mydf=data.frame(method=factor(1:10), x1=rpois(10,2), x2=round(rnorm(10),3), x3=rgeom(10,0.3))


text:
Q: how do i ask the user to input integer up to 50 times, and add them all together at the end of the code in eclipse? Write a small sequence of statements that gets 50 integer inputs from the user, adds them together,
and prints out their total. Print input prompts for the user.
Properly use a counting loop, and your counting variable must be named 'inputCount'.
so far i only have this, i don't know how to do the rest
    Scanner in = new Scanner (System.in);

    System.out.println("Please enter an integer: ");

    int inputCount = in.nextInt();

A: You could create a for i<50;i++ loop or a while loop, put your integers in an array and afterwards iterate through it and add it all together.
I would recommend to add it in the first place in your loop, but as i understand your question you wanna do it after you received all 50.
I also would put the whole thing in a try except, otherwise you will have problems as somebody does not type in a valid int.
int iadded = 0;
int [] iarray = new int[50];

for (int i=0; i<50; i++){
   System.out.println("Please enter the " + i+1 + ". integer: ");
   iarray[i]=in.nextInt();
}

for (int i=0; i<50, i++){
   iadded += iarray[i];
}

System.out.println("All inputs added: " + iadded);


text:
Q: aria-expanded="false" Not working in bootstrap template I have downloaded this template
https://startbootstrap.com/themes/sb-admin-2/
And there is page in there called cards.html
On that page is a collapsible card example. I'm trying to get it so that it loads collapsed and the user has to expand it. So I changed this section to be:

Collapsable Card Example

    This is a collapsable card example using Bootstrap's built in collapse functionality. Click on the card header to see the card body collapse and expand!

It did have:
aria-expanded="true"

but I made it false.
Why is it still loading as expanded?

A: Bootstrap doesn't rely on aria things, it uses its own data attributes. (aria is for screen readers.
To hide it, remove the show class from collapseCardExample. See https://getbootstrap.com/docs/4.3/components/collapse/

A: In bootstrap 5, Simply replace class="accordion-collapse collapse show" into class="accordion-collapse collapse" to those u don't want to open initially. it works for me!


text:
Q: itunesconnect - in app purchase Product ID changed I've uploaded a Build on itunesconnect and it got passed the review and it's waiting for my release. I mistakenly have deleted the in app purchase products. now i cant reuse the same ID.
What would you guys prefer to do? Do i have to cancel the Build and resend again with the changed code - or is there a different way to solve this issue ?
I didnt tried any steps right now.

A:
You have to resend a new build since deleted app products would give
  invalid ids error in storekit now


text:
Q: drawing a wall in a snake game java i'm trying to draw a wall for my snake game, i did it thanks to the paintComponent method, i'm just wondering if there is some way of drawing the wall once and not redrawing it repetidly every time paintComponent method is called.
I tried a boolean that stops the method from redrawing the wall once done the first time, but this doesnt work since paintComponent removes all and redraws it all.
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    if(drawWall) {
        for(int i = 0; i < this.getWidth(); i++) {
            g.drawImage(wall.getWallImage(), i*32, 0, this);
        }
        drawWall = false;
    }

A: Draw the wall to a BufferedImage and then paint the BufferedImage using Graphics#drawImage


text:
Q: How to search columns in two workbooks for matching value and write a value from different column from same matching row to one of workbooks? I would like to to be able to open two Excel workbooks and compare a column from each that may have matching values.  Upon discovering a matching value, I would like to grab another value from the same row in workbook 1 and write it to the same matching value row in workbook 2.
For my output file, I am simply trying to add one column of data that will match up where the values matched in the other columns I am comparing between the two workbooks.
In the example below, I would like to compare Column A between the two workbooks.  Upon finding a matching value, I would like to write the value in the same row from column C in workbook 1 to Column C in Workbook 2.
Input workbook 1:
A      B    C
dog    1    red
cat    2    green
bird   3    blue

Input workbook 2:
A      B       C     D       E
pig    house         stuff   stuff
cat    car           stuff   stuff
horse  train         stuff   stuff

Output Workbook 2
A       B      C       D       E
pig     house          stuff  stuff
cat     car    green   stuff  stuff
horse   trian          stuff  stuff

I have tried many iterations of code with openpyxl and pandas, and have not had any success.  I feel like I was closest using merge, join, concat in pandas, but the values never ended up printing anywhere that made sense.
For example, things like this ended up copying data from one workbook to the other, but it didn't match up anywhere it was supposed to.
df2 = df1.merge(df2, 'A', 'C')
df2 = pd.merge(df2,df1, on=['A'], how='left')
df2 = pd.concat([df1.set_index('A') for d in [df1, df2]], axis=1).reset_index()

If it helps, my actual data has several hundred rows in each workbook.  There are only two columns that actually match by header name.  One is the column I am comparing, and the other is the data I am trying to write from one workbook to other.
I am open to using any method that can easily compare two excel workbooks and write data from one to other based on matching values in specified columns.
Any help would be greatly appreciated.


text:
Q: Checkbox is not working properly with React state I am building a form where the hotel owners will add a hotel and select a few amenities of the same hotel. The problem is If I use state in the onChange function the checkbox tick is not displayed. I don't know where I made a mistake?
import React from "react";
import { nanoid } from "nanoid";

const ListAmenities = ({
  amenities,
  className,
  setHotelAmenities,
  hotelAmenities,
}) => {
  const handleChange = (e) => {
    const inputValue = e.target.dataset.amenitieName;
    if (hotelAmenities.includes(inputValue) === true) {
      const updatedAmenities = hotelAmenities.filter(
        (amenitie) => amenitie !== inputValue
      );
      setHotelAmenities(updatedAmenities);
    } else {
      //If I remove this second setState then everything works perfectly.
      setHotelAmenities((prevAmenities) => {
        return [...prevAmenities, inputValue];
      });
    }
  };

  return amenities.map((item) => {
    return (

        <input
          onChange={handleChange}
          className="mr-2"
          type="checkbox"
          name={item}
          id={item}
          data-amenitie-name={item}
        />
        {item}

    );
  });
};

export default ListAmenities;

A: The problem is that you are using key={nanoid()}. Instead, using key={item] should solve your probem.
I believe your application that uses ListAmenities is something like this:
const App = () => {
  const [hotelAmenities, setHotelAmenities] = useState([]);
  return (
    <ListAmenities
      amenities={["A", "B", "C"]}
      className="test"
      setHotelAmenities={setHotelAmenities}
      hotelAmenities={hotelAmenities}
    />
  );
};

In your current implementation, when handleChange calls setHotelAmenities it changed hotelAmenities which is a prop of ListAmenities and causes the ListAmenities to rerender. Since you use key={nanoid()} react assumes that a new item has been added and the old one has been removed. So it re-renders the checkbox. Since there is no default value of checkbox, it is assumed that it is in unchecked state when it is re-rendered.


text:
Q: What approach to be followed to code this in Pinescript
*

*Buy signal to be generated if any candle closes above a line (let's say EMA20)

*Stoploss should get triggered only if any subsequent candle closes below it (buy signal candle).

*All candles formed prior to the "buy signal" candle should have a closing below EMA20.

Inversely for sell signal also.
I do not wish to know the code, only the logic would suffice for backtesting.
Thanks

A: *

*You can use ta.crossover(close, ema20) to check that

*Store entry price in a var, and check if the price closes below it when you are in a trade

*Use a counter to count when the price is below ema20

Below code should do it or at least give you an idea
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © vitruvius

//@version=5
indicator("My script", overlay=true)

ema_len = input.int(20)
below_ema_no = input.int(4)

_ema = ta.ema(close, ema_len)
ema_co = ta.crossover(close, _ema)

var below_ema_cnt = 0
below_ema_cnt := close < _ema ? below_ema_cnt + 1 : 0   // Increase the counter if it closed below EMA20, reset oterwise

var is_long = false
var float buy_price = na

is_buy = not is_long and ema_co and (below_ema_cnt[1] >= below_ema_no)  // Buy when we are not already long, ema crossover takes place, last n candles below ema20
is_long := not is_long ? is_buy ? true : false : is_long                // Update is_long flag
buy_price := not is_long[1] and is_long ? close : buy_price             // New position: Store buy price (close price)

is_sl = is_long ? close < buy_price : false     // SL is hit if price closes below entry price
is_long := is_sl ? false : is_long              // Update is_long flag in case SL is hit
buy_price := is_sl ? na : buy_price             // Reset buy_price in case SL is hit

plot(_ema, "EMA", color.yellow, 2)
plotshape(is_buy, "Buy", shape.triangleup, location.belowbar, color.green, 0, "Buy", size=size.small)
plotshape(is_sl, "SL", shape.triangledown, location.abovebar, color.red, 0, "SL", size=size.small)
plot(buy_price, "Buy Price", color.white, 1, plot.style_circles)


text:
Q: Unable to saveAsTextFile in spark but able to read the output I am quite new with python and spark and I have an issue that require your help. Before that, I have four different dataset and using the same code for all these dataset, two of them were able to saveAsTextFile, the other two is not. The code i try to run is a sentiment analysis, and when I print out the output, it is readable. However, when i try to saveAsTextFile, there's an error for the other two dataset.
Appreciate if anyone can try to figure out what is wrong with my code as below:
def main():

   data = sc.textFile("filename.csv").map(lambda x:x.split(",")).filter(lambda x:len(x) == 10).filter(lambda x:len(x[1]) > 0).map(lambda x:str(x).replace("'","")).map(lambda x:str(x).replace('"',''))
   data1 = data.map(lambda x:x[1]).map(lambda x:remove_features(x)).map(lambda x:abb_en(x)).map(lambda x:TextBlob(x).sentiment.polarity).map(lambda x:polarity(x))

   data_save=data.zip(data1)
   print(data_save.take(5))
   data_save.saveAsTextFile("filename_1")'

if __name__ == "__main__":

   # Configure your Spark environment
   conf = SparkConf().setMaster("local[2]").setAppName("My Spark_1 Application")
   sc = SparkContext.getOrCreate(conf = conf)

   main()

   sc.stop()

The error:
Py4JJavaError: An error occurred while calling o1418.saveAsTextFile.
: org.apache.spark.SparkException: Job aborted.
    at org.apache.spark.internal.io.SparkHadoopWriter$.write(SparkHadoopWriter.scala:100)
    at org.apache.spark.rdd.PairRDDFunctions.$anonfun$saveAsHadoopDataset$1(PairRDDFunctions.scala:1090)
    at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:23)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
    at org.apache.spark.rdd.RDD.withScope(RDD.scala:388)
    at org.apache.spark.rdd.PairRDDFunctions.saveAsHadoopDataset(PairRDDFunctions.scala:1088)
    at org.apache.spark.rdd.PairRDDFunctions.$anonfun$saveAsHadoopFile$4(PairRDDFunctions.scala:1061)
    at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:23)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
    at org.apache.spark.rdd.RDD.withScope(RDD.scala:388)
    at org.apache.spark.rdd.PairRDDFunctions.saveAsHadoopFile(PairRDDFunctions.scala:1026)
    at org.apache.spark.rdd.PairRDDFunctions.$anonfun$saveAsHadoopFile$3(PairRDDFunctions.scala:1008)
    at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:23)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
    at org.apache.spark.rdd.RDD.withScope(RDD.scala:388)
    at org.apache.spark.rdd.PairRDDFunctions.saveAsHadoopFile(PairRDDFunctions.scala:1007)
    at org.apache.spark.rdd.PairRDDFunctions.$anonfun$saveAsHadoopFile$2(PairRDDFunctions.scala:964)
    at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:23)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
    at org.apache.spark.rdd.RDD.withScope(RDD.scala:388)
    at org.apache.spark.rdd.PairRDDFunctions.saveAsHadoopFile(PairRDDFunctions.scala:962)
    at org.apache.spark.rdd.RDD.$anonfun$saveAsTextFile$2(RDD.scala:1552)
    at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:23)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
    at org.apache.spark.rdd.RDD.withScope(RDD.scala:388)
    at org.apache.spark.rdd.RDD.saveAsTextFile(RDD.scala:1552)
    at org.apache.spark.rdd.RDD.$anonfun$saveAsTextFile$1(RDD.scala:1538)
    at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:23)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
    at org.apache.spark.rdd.RDD.withScope(RDD.scala:388)
    at org.apache.spark.rdd.RDD.saveAsTextFile(RDD.scala:1538)
    at org.apache.spark.api.java.JavaRDDLike.saveAsTextFile(JavaRDDLike.scala:550)
    at org.apache.spark.api.java.JavaRDDLike.saveAsTextFile$(JavaRDDLike.scala:549)
    at org.apache.spark.api.java.AbstractJavaRDDLike.saveAsTextFile(JavaRDDLike.scala:45)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:282)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:238)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 8.0 failed 1 times, most recent failure: Lost task 0.0 in stage 8.0 (TID 8, 9LVT2H2.mh.corp.net, executor driver): org.apache.spark.SparkException: Task failed while writing rows
    at org.apache.spark.internal.io.SparkHadoopWriter$.executeTask(SparkHadoopWriter.scala:157)
    at org.apache.spark.internal.io.SparkHadoopWriter$.$anonfun$write$1(SparkHadoopWriter.scala:83)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
    at org.apache.spark.scheduler.Task.run(Task.scala:127)
    at org.apache.spark.executor.Executor$TaskRunner.$anonfun$run$3(Executor.scala:441)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1377)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:444)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.UnsatisfiedLinkError: org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(Ljava/lang/String;I)Z
    at org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(Native Method)
    at org.apache.hadoop.io.nativeio.NativeIO$Windows.access(NativeIO.java:645)
    at org.apache.hadoop.fs.FileUtil.canRead(FileUtil.java:1230)
    at org.apache.hadoop.fs.FileUtil.list(FileUtil.java:1435)
    at org.apache.hadoop.fs.RawLocalFileSystem.listStatus(RawLocalFileSystem.java:493)
    at org.apache.hadoop.fs.FileSystem.listStatus(FileSystem.java:1868)
    at org.apache.hadoop.fs.FileSystem.listStatus(FileSystem.java:1910)
    at org.apache.hadoop.fs.ChecksumFileSystem.listStatus(ChecksumFileSystem.java:678)
    at org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter.mergePaths(FileOutputCommitter.java:484)
    at org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter.commitTask(FileOutputCommitter.java:597)
    at org.apache.hadoop.mapred.FileOutputCommitter.commitTask(FileOutputCommitter.java:172)
    at org.apache.hadoop.mapred.OutputCommitter.commitTask(OutputCommitter.java:343)
    at org.apache.spark.mapred.SparkHadoopMapRedUtil$.performCommit$1(SparkHadoopMapRedUtil.scala:50)
    at org.apache.spark.mapred.SparkHadoopMapRedUtil$.commitTask(SparkHadoopMapRedUtil.scala:77)
    at org.apache.spark.internal.io.HadoopMapReduceCommitProtocol.commitTask(HadoopMapReduceCommitProtocol.scala:245)
    at org.apache.spark.internal.io.SparkHadoopWriter$.$anonfun$executeTask$1(SparkHadoopWriter.scala:140)
    at org.apache.spark.util.Utils$.tryWithSafeFinallyAndFailureCallbacks(Utils.scala:1411)
    at org.apache.spark.internal.io.SparkHadoopWriter$.executeTask(SparkHadoopWriter.scala:129)
    ... 9 more

Driver stacktrace:
    at org.apache.spark.scheduler.DAGScheduler.failJobAndIndependentStages(DAGScheduler.scala:1989)
    at org.apache.spark.scheduler.DAGScheduler.$anonfun$abortStage$2(DAGScheduler.scala:1977)
    at org.apache.spark.scheduler.DAGScheduler.$anonfun$abortStage$2$adapted(DAGScheduler.scala:1976)
    at scala.collection.mutable.ResizableArray.foreach(ResizableArray.scala:62)
    at scala.collection.mutable.ResizableArray.foreach$(ResizableArray.scala:55)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:49)
    at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1976)
    at org.apache.spark.scheduler.DAGScheduler.$anonfun$handleTaskSetFailed$1(DAGScheduler.scala:956)
    at org.apache.spark.scheduler.DAGScheduler.$anonfun$handleTaskSetFailed$1$adapted(DAGScheduler.scala:956)
    at scala.Option.foreach(Option.scala:407)
    at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:956)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:2206)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:2155)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:2144)
    at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:49)
    at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:758)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:2116)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:2137)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:2169)
    at org.apache.spark.internal.io.SparkHadoopWriter$.write(SparkHadoopWriter.scala:78)
    ... 50 more
Caused by: org.apache.spark.SparkException: Task failed while writing rows
    at org.apache.spark.internal.io.SparkHadoopWriter$.executeTask(SparkHadoopWriter.scala:157)
    at org.apache.spark.internal.io.SparkHadoopWriter$.$anonfun$write$1(SparkHadoopWriter.scala:83)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
    at org.apache.spark.scheduler.Task.run(Task.scala:127)
    at org.apache.spark.executor.Executor$TaskRunner.$anonfun$run$3(Executor.scala:441)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1377)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:444)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    ... 1 more
Caused by: java.lang.UnsatisfiedLinkError: org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(Ljava/lang/String;I)Z
    at org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(Native Method)
    at org.apache.hadoop.io.nativeio.NativeIO$Windows.access(NativeIO.java:645)
    at org.apache.hadoop.fs.FileUtil.canRead(FileUtil.java:1230)
    at org.apache.hadoop.fs.FileUtil.list(FileUtil.java:1435)
    at org.apache.hadoop.fs.RawLocalFileSystem.listStatus(RawLocalFileSystem.java:493)
    at org.apache.hadoop.fs.FileSystem.listStatus(FileSystem.java:1868)
    at org.apache.hadoop.fs.FileSystem.listStatus(FileSystem.java:1910)
    at org.apache.hadoop.fs.ChecksumFileSystem.listStatus(ChecksumFileSystem.java:678)
    at org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter.mergePaths(FileOutputCommitter.java:484)
    at org.apache.hadoop.mapreduce.lib.output.FileOutputCommitter.commitTask(FileOutputCommitter.java:597)
    at org.apache.hadoop.mapred.FileOutputCommitter.commitTask(FileOutputCommitter.java:172)
    at org.apache.hadoop.mapred.OutputCommitter.commitTask(OutputCommitter.java:343)
    at org.apache.spark.mapred.SparkHadoopMapRedUtil$.performCommit$1(SparkHadoopMapRedUtil.scala:50)
    at org.apache.spark.mapred.SparkHadoopMapRedUtil$.commitTask(SparkHadoopMapRedUtil.scala:77)
    at org.apache.spark.internal.io.HadoopMapReduceCommitProtocol.commitTask(HadoopMapReduceCommitProtocol.scala:245)
    at org.apache.spark.internal.io.SparkHadoopWriter$.$anonfun$executeTask$1(SparkHadoopWriter.scala:140)
    at org.apache.spark.util.Utils$.tryWithSafeFinallyAndFailureCallbacks(Utils.scala:1411)
    at org.apache.spark.internal.io.SparkHadoopWriter$.executeTask(SparkHadoopWriter.scala:129)
    ... 9 more

A: When I look at the exception, it appeared that the code is executed in Windows environment.
Caused by: java.lang.UnsatisfiedLinkError: org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(Ljava/lang/String;I)Z
at org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(Native Method)
at org.apache.hadoop.io.nativeio.NativeIO$Windows.access(NativeIO.java:645)

Not sure what is the file path specified. Please check if following things are in place
1. winutil.exe and hadoop.dll
2. add to $HADOOP_HOME/bin

Also, check the file location which you have specified having write access if it is a local file. In general it should not cause any issue if Hadoop path is set and file write access is given.


text:
Q: Dynamically adding or deleting widgets in google-app-maker I am trying to develop an interface that binds to a complex backend model. What I need is a way for scripting to enable me to have a page load different page fragments based on what list row a user clicks on.  As an example, on the left side of the page there would be a vertical list displaying different sections in a large assessment 'document' (mental health assessment)  (each section would be it's own data model [e.g. presenting problems family history, trauma history, etc...). In the main section of the page to the right, you would have room for a page fragment or some type of container that would contain the actual page or page fragments associated with each  section listed in the list on the left. When you click on the section name in the list to the left, scripting would be able to have the correct page fragment or page loaded inside the container.
The data model needs to be this complex because there are multiple types of "documents' and the system needs to be able to dynamically load a list of document sections and allow the user to load the form for each section type.

A: THIS IS FROM Markus Malessa: The dynamic page content is definitely possible, however since it sounds like a lot of your items are going to be based on hard data, the models really are not dynamic, so you really can't build in dynamic data at run time for example. Rather than visible/invisible properties I might suggest navigating to different pages instead and maybe having many-to-many relations to your list item and if your list item has OldFamilyHistory and NewFamilyHistory data relations incorporate a popup to select which page you may want to navigate to.


text:
Q: PDF Document tracking & logging information Once a PDF document has been sent through email, control is lost to the owner. Anyone could be viewing the data and the owner lost awareness about it. That's why as an owner of the document, I want to track the activities performed with the PDF document. I want to know about the movements of the document and whether the PDF is spread beyond the intended personnel. Also, want to track logging information like IP addresses of the devices. In my office sometimes we deal with confidential and sensitive documents. Please let me enlight how to handle these issues. Thanks in advance.

A: A PDF document is merely a file, it's not a program which call back the author or the sender of the E-Mail. You have the option to limit the use of the document, concerning modification, printing, etc.

A: You can't, not with a PDF document. It is a simple as that. That is, by the way, for almost all information. It was even so in the old paper-days: if someone shared the confidential memo with someone else, the author/writer/....  would not have known.
Once someone with access to a photocopier had the document, you would have lost awareness about who views the document. And whether the copying is done by a scriptorium full of monks or by cp yourfile.pdf myfile.pdf, the underlying principle is the same: once the genie is out of the bottle, it is free.
Almost all security people (outside film/music industry) understand this. Therefore they wish to control who has access to the data. You will limit the access to people that you trust. And you will divulge data on a need-to-know basis.
There are a few companies that will sell you DRM for PDF documents. Digify, Locklizard to name a pair. But DRM is always bothersome and there is always the 'analogue' loophole (a camera or screenshot for example).
And it is a PITA. Digify, on their website, describe it as follows:

Why is DRM not more widespread?
While DRM sounds great for protecting your documents, the ease of use and cost are typically two factors that hinder the adoption of the technology.
Many DRM solutions are difficult for both the sender and the recipient. The recipient will need to go through many steps to get to the document, including installing special software or validating their identity.

You can also watermark the individual documents. At least when you find a copy in a place where it doesn't belong, you know who spread it and you can administer appropriate castigations.

A: What you can do is control the access. The best Acrobat can provide is signing the document against a certificate received from the receipient. In this case, only that particular person can open the document.
With the other restrictions you can apply, you can find out who leaked (if you get your hands on the leaked document)


text:
Q: How do to resize flash dimensions via actionscript? If you include a flash file via:
<object width="550" height="400">
<param name="movie" value="somefilename.swf">
<embed src="somefilename.swf" width="550" height="400">
</embed>
</object>

Are you able to collapse or expand the dimensions to 100x100 or 1000x1000 for example via action-script without HTML, JavaScript or anything apart from the flash file itself?

A: In short, no. You might be able to use ExternalInterface to fire javascript at the DOM (assuming SWF and webpage originate from same domain), but pure Actionscript? No.
http://blog.sebastian-martens.de/2010/06/resize-flash-application-container/


text:
Q: How to use the data of cadvisor to calculate the cpu usage and load in Prometheus when I use the cadvisor to get the information about the cpu in a docker container,I get the information as follow:

my question is that how to caculate the cpu usage and load,which is the same as Prometheus,through the information returned by cadvisor?how Prometheus caculate the cpu usage?

A: The algorithm that Prometheus uses for rate() is a little intricate due to handling of issues like alignment and counter resets as explained in Counting with Prometheus.
The short version is to subtract first value from the last value, and divide by the time they are over. It's probably easiest to use Prometheus rather than doing this yourself.

A: Below query should return your top 10 containers which are consuming most CPU time:
topk(10, sum(irate(container_cpu_usage_seconds_total{container_label_com_docker_swarm_node_id=~".+", id=~"/docker/.*"}[$interval])) by (name)) * 100


text:
Q: android media player notification I have coded up a media player which streams MP3 from a website.
With a media player such as Winamp, I can go check my email or Facebook while its playing and then go back to win-amp by using the notification window. I wanted to know if I can do something like that with my media player.
I have looked at: Android Media Player Threading ,Notifications and many more.
I goggled this concept and found a lot of confusing topics. Some people made a service while some make a foreground service and then added notification to that. I am confused on how I can make this possible. If someone can explain this concept (going from my activity class to notification bar) to me, I will be grateful. Sample code will be greatly appreciated too.

A: I found an answer to my question and decided to share with fellow novice users/students who are learning android development.
Basically, you have to use a service side by side with your activity class if you want an effective media player. After making the service, you have to make it into a foreground service which will help you make your media player into a notification.
If I am incorrect then please correct me. Thank you
Sample code: http://www.java2s.com/Code/Android/Media/UsingServicetoplaymediafile.htm


text:
Q: How to use padding value with get_keras_embedding I try to integrate gensim's get_keras_embedding into a Keras model.
First I do text preprocessing

*

*text_to_word_sequence converts text into token sequence

*w2v.vocab[tok].index converts words into gensim's word indexes

*pad_sequences(sequences, maxlen=MAX_SEQUENCE_LENGTH, value=999999) padding with some value

Then I build a model
embedding_layer = w2v.get_keras_embedding(train_embeddings=False)
...
sequence_input = Input(shape=(MAX_SEQUENCE_LENGTH,), dtype='int32')
embedded_sequences = embedding_layer(sequence_input)
...
x = Conv1D(100, kernel_size, activation='relu', padding='same', strides=1)(embedded_sequences)

Apparently the problem is with the padding value. The default value is 0 which is 'the' in gensim word2vec, if I use non-existing value it fails with the following error message. What is the right way to use padding with gensim word2vec?
InvalidArgumentError (see above for traceback): indices[48,0] = 999999 is not in [0, 400000)
     [[Node: embedding_1/embedding_lookup = Gather[Tindices=DT_INT32, Tparams=DT_FLOAT, _class=["loc:@embedding_1/embeddings"], validate_indices=true, _device="/job:localhost/replica:0/task:0/device:CPU:0"](embedding_1/embeddings/read, _arg_input_1_0_3)]]

I would appreciate any help.


text:
Q: leaflet route360 using as input point geojson layer? hello I have read this examples about leaflet route 360 services.
is very interests but that examples work with static coordinates,my question is how to can use this services using some point GeoJSON layer ?
my GeoJSON layer example:
coords = [];
        var points = new L.GeoJSON.AJAX("{% url 'mylayer' %}",{
        onEachFeature:function (feature,layer) {
            coords.push(feature.geometry.coordinates.reverse());
            layer.on('click', function (e) {
               var field1=document.getElementById('f1');
               field1.innerHTML=e.target.feature.properties.name;
            });
            layer.bindPopup(feature.properties.name.toString())
        }
        });
        points.addTo(map);

leaflet route 360 example :


text:
Q: Getting an error while trying to apply gradients with respect to input I'm using StyleGANv2 (https://github.com/moono/stylegan2-tf-2.x) with original weights.
My TF version is 2.2.0. The default training process and inference work fine.
But I'm trying to do learning steps with respect to input:
rnd = np.random.RandomState(seed)
latents = rnd.randn(1, generator.z_dim).astype(np.float32)
labels = rnd.randn(1, generator.labels_dim).astype(np.float32)

initial_input = [tf.convert_to_tensor(latents), tf.convert_to_tensor(labels)]
input_tensor = tf.Variable([initial_input[0]])

for step in range(10):
    with tf.GradientTape() as tape:

        tape.watch(initial_input[0])
        if step == 0:
            generated_image = generator(initial_input)
        else:
            generated_image = generator([input_tensor[0,:,:], initial_input[1]])

        # target_image - the image I'm trying to learn latents for
        loss_value = mae_loss(generated_image, target_image)

    plt.imshow(postprocess_images(generated_image).numpy()[0])
    plt.show()

    print("Loss: ", loss_value)
    print("Tensor: ", input_tensor)
    print("Initial Input: ", [initial_input[0]])

    gradients = tape.gradient(loss_value, [initial_input[0]])

    print("Gradients: ", gradients)

    optimizer.apply_gradients(zip([gradients], [input_tensor]))

The first step completes successfully, but on the second step I'm getting an error:
ValueError: Attempt to convert a value (None) with an unsupported type (<class 'NoneType'>) to a Tensor.
And gradients = tape.gradient(loss_value, [initial_input[0]]) returns None on the second step.
So any idea what the problem could be?

A: It works now. Thanks to @klapeyron. I updated tf.Variable values with values from input_tensor:
optimizer = tf.keras.optimizers.Adam(learning_rate=0.01)

initial_input = [tf.convert_to_tensor(latents), tf.convert_to_tensor(labels)]
input_tensor = tf.Variable([initial_input[0]])

for step in range(100):
    with tf.GradientTape() as tape:
        tape.watch(initial_input[0])

        initial_input[0] = input_tensor[0,:,:]
        generated_image = generator(initial_input)initial_input[1]])

        loss_value = mse_loss(generated_image, target_image)

    plt.imshow(postprocess_images(generated_image).numpy()[0])
    plt.show()

    gradients = tape.gradient(loss_value, [initial_input[0]])
    optimizer.apply_gradients(zip([gradients], [input_tensor]))


text:
Q: php classes - how would one go about loading a "module" object within an existing object only when its needed? Ok so i have the following code setup which seems to work fine:
user handler "module":
class user_handler
{
    private $dbo;

    public function __construct($dbo)
    {
        $this->dbo = $dbo;
    }

    public function user_table_method()
    {
        $this->dbo->generic_db_method();
    }
}

the connection class:
class connection
{
    private $dbc;

    public $user;

    public function __construct()
    {
        $this->dbc = 'connection';
        $this->user = new user_handler($this);
    }

    public function generic_db_method()
    {
        echo '
doing stuff with ' . $this->dbc . '
';
    }
}

Then i can access user handler methods like so:
$dbc = new connection();
$dbc->user->user_table_method();

My question is this:
Would it be possible with a method in the connection class to create the _user object only when it's required?
What i'm thinking of is a method that would be used like so:
$dbc->add_handle('user', 'user_handler');

Which would create a new public property called user from scratch and set it as a new
user_handler object:
// in more detail
public function add_handle($name, $module)
{
    if(!isset($this->/*somehow use $name*/))
    {
        $this->/*somehow use $name*/ = new /*somehow use $module*/();
    }
}

..so the new way to set it up would be like:
$dbc = new connection();
$dbc->add_handle('user', 'user_handler');
$dbc->user->user_table_method();

Thanks in advance! (looking at php 5.2 and up)

A: public function add_handle($name, $module)
{
    if(!isset($this->$name))
    {
        $this->$name = new $module();
    }
}

Then you would just do similar to how you were thinking:
$dbc = new connection();
$name = 'user';
$module = 'somemodule';
$dbc->add_handle($name, $module);
$dbc->user->user_table_method();

I've also renamed it from $_user to $user as I mentioned in the comment since it is public.


text:
Q: Is there any way to make the below code in one-line I am trying a cipher technique (One Time Pad), I got the solution but want to make it one-line. Here's a sample input and output respectively.INPUT(TEXT) = 'HELLO', KEY = 'XMCKL', OUTPUT(CIPHERTEXT) = 'EQNVZ'.
def ciphertextFor(text, key):
    cpt = []
    for i in range(len(text)):
        cpt.append(chr((ord(text[i])+ord(key[i])) % 26+65))
    return ''.join(cpt)
    # return ''.join(chr((ord(text[j])+ord(key[j])) % 26+65)) for j in range(len(text)))

A: Try this with a simple list comprehension directly from your function above -
text, key = 'ajshwhsuhe','amchaksheo'

cipher = ''.join([chr((ord(text[i])+ord(key[i])) % 26+65) for i in range(len(text))])

print(cipher)

'MHGAIDWNXE'

A: You can use zip to iterate through the chars from input and key at the same time
>>> input, key = 'HELLO', 'XMCKL'
>>> ''.join(chr((ord(x)+ord(y)) % 26+65) for x,y in zip(input, key))
'EQNVZ'