问:
laravel websocket in homestead not working
I've tried all the ways to implement this package Laravel Websockets with homestead,
locally it works but using nginx Homestead doesn't.

1 -> configuration for /etc/nginx/sites-available/example.test :

```<code>server {
    listen 80;
    listen 443 ssl http2;
    server_name website.test;
    root "/home/vagrant/website/public";

index index.html index.htm index.php;

charset utf-8;

location / {
    try_files $uri $uri/ /index.php?$query_string;
}

location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt  { access_log off; log_not_found off; }

access_log off;
error_log  /var/log/nginx/website.test-error.log error;

sendfile off;

client_max_body_size 100m;

location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

    fastcgi_intercept_errors off;
    fastcgi_buffer_size 16k;
    fastcgi_buffers 4 16k;
    fastcgi_connect_timeout 300;
    fastcgi_send_timeout 300;
    fastcgi_read_timeout 300;
}

location /ws {
    proxy_pass             http://127.0.0.1:6001;
    proxy_set_header Host  $host;
    proxy_read_timeout     60;
    proxy_connect_timeout  60;
    proxy_redirect         off;

    # Allow the use of websockets
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;}

location ~ /\.ht {
    deny all;
}

ssl_certificate     /etc/nginx/ssl/website.test.crt;
ssl_certificate_key /etc/nginx/ssl/website.test.key;
</code>```

}

2 -> my js config :

```<code>import Echo from "laravel-echo"

window.Pusher = require('pusher-js');

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    wsHost: window.location.hostname,
    wsPort: 6001,
    disableStats: true,
});
</code>```

3 -> My Event :

```<code><?php

namespace App\Events\CrudsEvents;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class DashboardEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $data ;

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

    public function broadcastOn()
    {

        return new Channel('chat-channel');
        // return new PrivateChannel('channel-name');
    }
}
</code>```

4 -> i run in homestead the command php artisan websockets:serve

5 -> and try to listen in my client side using this code :

```<code>  mounted(){
    window.Echo.channel('chat-channel')
        .listen('DashboardEvent',(e)=>{
          console.log(e)
      })
  },
</code>```

6 -> after broadcasting the event, nothing is received on my client side.

答:
I figured it out

Your nginx config is almost correct, except if you are using Homestead, change the IP to

```<code>location /ws {
    proxy_pass             http://192.168.10.10:6001;
    proxy_set_header Host  $host;
    proxy_read_timeout     60;
    proxy_connect_timeout  60;
    proxy_redirect         off;

    # Allow the use of websockets
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
}
</code>```

This is the only extra code that needs to be added to a default Homestead nginx site which you can find by ssh-ing into the VM and editing

sudo nano /etc/nginx/sites-available/mysite.test

Also change your host in broadcasting.php to

'host'       => env('WEBSOCKET_BROADCAST_HOST'),

and in your .env

WEBSOCKET_BROADCAST_HOST=192.168.10.10

Next, set up Laravel Horizon and run the process

php artisan horizon

In another window, run

php artisan websockets:serve --host=192.168.10.10

In a third window, you can now open up tinker and run

event (new \App\Events\NewMessage("Hello world"));

If you are implementing ShouldBroadcast, it should work !

Alternatively, you could otherwise implement ShouldBroadcastNow which doesn't need horizon.

Body:
I've tried all the ways to implement this package Laravel Websockets with homestead,
locally it works but using nginx Homestead doesn't.

1 -> configuration for /etc/nginx/sites-available/example.test :

server {
    listen 80;
    listen 443 ssl http2;
    server_name website.test;
    root "/home/vagrant/website/public";

index index.html index.htm index.php;

charset utf-8;

location / {
    try_files $uri $uri/ /index.php?$query_string;
}

location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt  { access_log off; log_not_found off; }

access_log off;
error_log  /var/log/nginx/website.test-error.log error;

sendfile off;

client_max_body_size 100m;

location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

    fastcgi_intercept_errors off;
    fastcgi_buffer_size 16k;
    fastcgi_buffers 4 16k;
    fastcgi_connect_timeout 300;
    fastcgi_send_timeout 300;
    fastcgi_read_timeout 300;
}

location /ws {
    proxy_pass             http://127.0.0.1:6001;
    proxy_set_header Host  $host;
    proxy_read_timeout     60;
    proxy_connect_timeout  60;
    proxy_redirect         off;

    # Allow the use of websockets
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;}

location ~ /\.ht {
    deny all;
}

ssl_certificate     /etc/nginx/ssl/website.test.crt;
ssl_certificate_key /etc/nginx/ssl/website.test.key;

}

2 -> my js config :

import Echo from "laravel-echo"

window.Pusher = require('pusher-js');

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    wsHost: window.location.hostname,
    wsPort: 6001,
    disableStats: true,
});

3 -> My Event :

<?php

namespace App\Events\CrudsEvents;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class DashboardEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $data ;

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

    public function broadcastOn()
    {

        return new Channel('chat-channel');
        // return new PrivateChannel('channel-name');
    }
}

4 -> i run in homestead the command php artisan websockets:serve

5 -> and try to listen in my client side using this code :

  mounted(){
    window.Echo.channel('chat-channel')
        .listen('DashboardEvent',(e)=>{
          console.log(e)
      })
  },

6 -> after broadcasting the event, nothing is received on my client side.

Body:
I figured it out

Your nginx config is almost correct, except if you are using Homestead, change the IP to

location /ws {
    proxy_pass             http://192.168.10.10:6001;
    proxy_set_header Host  $host;
    proxy_read_timeout     60;
    proxy_connect_timeout  60;
    proxy_redirect         off;

    # Allow the use of websockets
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
}

This is the only extra code that needs to be added to a default Homestead nginx site which you can find by ssh-ing into the VM and editing

sudo nano /etc/nginx/sites-available/mysite.test

Also change your host in broadcasting.php to

'host'       => env('WEBSOCKET_BROADCAST_HOST'),

and in your .env

WEBSOCKET_BROADCAST_HOST=192.168.10.10

Next, set up Laravel Horizon and run the process

php artisan horizon

In another window, run

php artisan websockets:serve --host=192.168.10.10

In a third window, you can now open up tinker and run

event (new \App\Events\NewMessage("Hello world"));

If you are implementing ShouldBroadcast, it should work !

Alternatively, you could otherwise implement ShouldBroadcastNow which doesn't need horizon.


来源: stackexchange

问:
Essentially a 2 dimensional Enum?
Not sure how to phrase this, but I have a class called Lane for different lanes of a road.

A Lane has two parts - the Direction (an Enum of left or right or other) and then the number, an integer. So lanes look like this: L1, L2, R1, R3 etc..

There should only be one instance of the lane class for each lane. L1 shouldn't exist twice.

Because of this, I want to be able to assign the Lane of an object the way you can assign an enum, by typing Lane.L1 or Lane.R4 etc.. I currently have to use a method which finds the existing Lane object that corresponds to the Lane I'm trying to reference.

Is this a way to do this better? Like by simply typing lane = Lane.L1, other than making the Lane class have private constructors and manually creating a public Getter for each possible Lane and assigning references in a static constructor for the Lane class?

This is the current state of the lane class:

```<code>public enum Direction { INCREASING = 1, DECREASING = 2, BOTH = 3, OTHER = 4, UNSPECIFIED = 5 }
public class Lane : IComparable
{
    public Direction Direction;
    public int Number = 1;
    public Lane(Direction direction, int number = 1)
    {
        Direction = direction;
        Number = number;
    }

    public override string ToString()
    {
        if (Direction == Direction.UNSPECIFIED)
        {
            return Direction.AsCharLR().ToString();
        }
        return Direction.AsCharLR() + Number.ToString();
    }

    public override bool Equals(object obj)
    {
        if (obj is Lane)
        {
            Lane l = obj as Lane;
            return Direction == l.Direction && Number == l.Number;
        }
        return false;
    }

    public override int GetHashCode()
    {
        return (int)Direction * 100 + Number;
    }

    public static Lane Parse(char lane)
    {
        lane = char.ToUpper(lane);
        switch (lane)
        {
            case 'L':
            case 'I':
                return new Lane(Direction.INCREASING);
            case 'R':
            case 'D':
                return new Lane(Direction.DECREASING);
            case 'B':
                return new Lane(Direction.BOTH);
            case 'U':
                return new Lane(Direction.UNSPECIFIED);
            case 'O':
            default:
                return new Lane(Direction.OTHER);
        }
    }
    public static Lane Parse(string text)
    {
        Lane lane = Parse(text[0]);
        lane.Number = int.Parse(text.Substring(1));
        return lane;
    }

    public int CompareTo(object l)
    {
        return GetHashCode() - l.GetHashCode();
    }
}
</code>```

答:
You can't do what you want with an enum because it doesn't sound like you're placing a limit on the "number" part, and you can't define or use new enums at runtime.

This might be all you need:

```<code>public static class Lanes
{
    private static readonly Dictionary<string, Lane> LanesDictionary =
        new Dictionary<string, Lane>();

    public static Lane GetLane(Direction direction, int number)
    {
        var key = direction.ToString() + number;
        if (LanesDictionary.ContainsKey(key))
        {
            return LanesDictionary[key];
        }
        var lane = new Lane(direction, number);
        LanesDictionary.Add(key, lane);
        return lane;
    }
}
</code>```

Now every time you reference Lanes.GetLane(Direction.INCREASING, 4) you'll always get the same Lane. If it doesn't already exist it will be created.

That gets you a convenient, readable way to reference a given lane. If for some reason you wanted shorthand for some lanes - although, as mentioned, you don't want to hardcode them (I wouldn't either) - you could do this:

```<code>public static Lane L4 { get; } = GetLane(Direction.INCREASING, 4);
</code>```

ContentLicense: CC BY-SA 4.0

Title: Essentially a 2 dimensional Enum?

Body:
Not sure how to phrase this, but I have a class called Lane for different lanes of a road.

A Lane has two parts - the Direction (an Enum of left or right or other) and then the number, an integer. So lanes look like this: L1, L2, R1, R3 etc..

There should only be one instance of the lane class for each lane. L1 shouldn't exist twice.

Because of this, I want to be able to assign the Lane of an object the way you can assign an enum, by typing Lane.L1 or Lane.R4 etc.. I currently have to use a method which finds the existing Lane object that corresponds to the Lane I'm trying to reference.

Is this a way to do this better? Like by simply typing lane = Lane.L1, other than making the Lane class have private constructors and manually creating a public Getter for each possible Lane and assigning references in a static constructor for the Lane class?

This is the current state of the lane class:

public enum Direction { INCREASING = 1, DECREASING = 2, BOTH = 3, OTHER = 4, UNSPECIFIED = 5 }
public class Lane : IComparable
{
    public Direction Direction;
    public int Number = 1;
    public Lane(Direction direction, int number = 1)
    {
        Direction = direction;
        Number = number;
    }

    public override string ToString()
    {
        if (Direction == Direction.UNSPECIFIED)
        {
            return Direction.AsCharLR().ToString();
        }
        return Direction.AsCharLR() + Number.ToString();
    }

    public override bool Equals(object obj)
    {
        if (obj is Lane)
        {
            Lane l = obj as Lane;
            return Direction == l.Direction && Number == l.Number;
        }
        return false;
    }

    public override int GetHashCode()
    {
        return (int)Direction * 100 + Number;
    }

    public static Lane Parse(char lane)
    {
        lane = char.ToUpper(lane);
        switch (lane)
        {
            case 'L':
            case 'I':
                return new Lane(Direction.INCREASING);
            case 'R':
            case 'D':
                return new Lane(Direction.DECREASING);
            case 'B':
                return new Lane(Direction.BOTH);
            case 'U':
                return new Lane(Direction.UNSPECIFIED);
            case 'O':
            default:
                return new Lane(Direction.OTHER);
        }
    }
    public static Lane Parse(string text)
    {
        Lane lane = Parse(text[0]);
        lane.Number = int.Parse(text.Substring(1));
        return lane;
    }

    public int CompareTo(object l)
    {
        return GetHashCode() - l.GetHashCode();
    }
}

Body:
You can't do what you want with an enum because it doesn't sound like you're placing a limit on the "number" part, and you can't define or use new enums at runtime.

This might be all you need:

public static class Lanes
{
    private static readonly Dictionary<string, Lane> LanesDictionary =
        new Dictionary<string, Lane>();

    public static Lane GetLane(Direction direction, int number)
    {
        var key = direction.ToString() + number;
        if (LanesDictionary.ContainsKey(key))
        {
            return LanesDictionary[key];
        }
        var lane = new Lane(direction, number);
        LanesDictionary.Add(key, lane);
        return lane;
    }
}

Now every time you reference Lanes.GetLane(Direction.INCREASING, 4) you'll always get the same Lane. If it doesn't already exist it will be created.

That gets you a convenient, readable way to reference a given lane. If for some reason you wanted shorthand for some lanes - although, as mentioned, you don't want to hardcode them (I wouldn't either) - you could do this:

public static Lane L4 { get; } = GetLane(Direction.INCREASING, 4);


问:
Why does dataframe.show() crash my program in PyCharm but not in the terminal
I'm trying to run a simple pyspark example that I've written myself for learning purposes:

```<code>from pyspark import SQLContext
from pyspark import SparkContext
from pyspark.sql.types import StringType
from pyspark.sql.functions import udf

from urllib.parse import urlsplit

def extractPath(host, url):
    if host in url:
        return urlsplit(url).path
    else:
        return '-'

sc = SparkContext.getOrCreate()

sqlContext = SQLContext(sc)

# preconstruct custom spark functions, used in method processFile
getPathUdf = udf(extractPath, StringType())

df = sqlContext.read.csv(
    path="resources/smalldatafile.csv",
    header=True,
    inferSchema=True
)

previousPagePathField = 'previous page path'
hostnameField = 'host name'
dataCsRefererField = 'data_cs_referer'

# do mappings
dfMapped = (
    df
        .withColumnRenamed('data_cs_host', hostnameField)
)

# split referrer url
print(previousPagePathField)
print(hostnameField)
print(dataCsRefererField)
print(getPathUdf(hostnameField, dataCsRefererField))
dfRefUrl = dfMapped.withColumn(previousPagePathField, getPathUdf(hostnameField, dataCsRefererField))
dfRefUrl.show(1)
</code>```

The last line crashes my program with the trace:

```<code>2019-03-27 16:49:43 WARN  Utils:66 - Truncated the string representation of a plan since it was too large. This behavior can be adjusted by setting 'spark.debug.maxToStringFields' in SparkEnv.conf.
Traceback (most recent call last):
  File "/home/me/spark/venv/lib/python3.6/site-packages/pyspark/sql/utils.py", line 63, in deco
    return f(*a, **kw)
  File "/home/me/spark/venv/lib/python3.6/site-packages/py4j/protocol.py", line 328, in get_return_value
    format(target_id, ".", name), value)
py4j.protocol.Py4JJavaError: An error occurred while calling o46.showString.
: java.lang.IllegalArgumentException: Unsupported class file major version 55
    at org.apache.xbean.asm6.ClassReader.<init>(ClassReader.java:166)
    at org.apache.xbean.asm6.ClassReader.<init>(ClassReader.java:148)
    at org.apache.xbean.asm6.ClassReader.<init>(ClassReader.java:136)
    at org.apache.xbean.asm6.ClassReader.<init>(ClassReader.java:237)
    at org.apache.spark.util.ClosureCleaner$.getClassReader(ClosureCleaner.scala:49)
    at org.apache.spark.util.FieldAccessFinder$$anon$3$$anonfun$visitMethodInsn$2.apply(ClosureCleaner.scala:517)
    at org.apache.spark.util.FieldAccessFinder$$anon$3$$anonfun$visitMethodInsn$2.apply(ClosureCleaner.scala:500)
    at scala.collection.TraversableLike$WithFilter$$anonfun$foreach$1.apply(TraversableLike.scala:733)
    at scala.collection.mutable.HashMap$$anon$1$$anonfun$foreach$2.apply(HashMap.scala:134)
    at scala.collection.mutable.HashMap$$anon$1$$anonfun$foreach$2.apply(HashMap.scala:134)
    at scala.collection.mutable.HashTable$class.foreachEntry(HashTable.scala:236)
    at scala.collection.mutable.HashMap.foreachEntry(HashMap.scala:40)
    at scala.collection.mutable.HashMap$$anon$1.foreach(HashMap.scala:134)
    at scala.collection.TraversableLike$WithFilter.foreach(TraversableLike.scala:732)
    at org.apache.spark.util.FieldAccessFinder$$anon$3.visitMethodInsn(ClosureCleaner.scala:500)
    at org.apache.xbean.asm6.ClassReader.readCode(ClassReader.java:2175)
    at org.apache.xbean.asm6.ClassReader.readMethod(ClassReader.java:1238)
    at org.apache.xbean.asm6.ClassReader.accept(ClassReader.java:631)
    at org.apache.xbean.asm6.ClassReader.accept(ClassReader.java:355)
    at org.apache.spark.util.ClosureCleaner$$anonfun$org$apache$spark$util$ClosureCleaner$$clean$14.apply(ClosureCleaner.scala:307)
    at org.apache.spark.util.ClosureCleaner$$anonfun$org$apache$spark$util$ClosureCleaner$$clean$14.apply(ClosureCleaner.scala:306)
    at scala.collection.immutable.List.foreach(List.scala:392)
    at org.apache.spark.util.ClosureCleaner$.org$apache$spark$util$ClosureCleaner$$clean(ClosureCleaner.scala:306)
    at org.apache.spark.util.ClosureCleaner$.clean(ClosureCleaner.scala:162)
    at org.apache.spark.SparkContext.clean(SparkContext.scala:2326)
    at org.apache.spark.rdd.RDD$$anonfun$mapPartitions$1.apply(RDD.scala:798)
    at org.apache.spark.rdd.RDD$$anonfun$mapPartitions$1.apply(RDD.scala:797)
    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:363)
    at org.apache.spark.rdd.RDD.mapPartitions(RDD.scala:797)
    at org.apache.spark.sql.execution.python.EvalPythonExec.doExecute(EvalPythonExec.scala:89)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:131)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:127)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:155)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:152)
    at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:127)
    at org.apache.spark.sql.execution.InputAdapter.inputRDDs(WholeStageCodegenExec.scala:374)
    at org.apache.spark.sql.execution.ProjectExec.inputRDDs(basicPhysicalOperators.scala:41)
    at org.apache.spark.sql.execution.WholeStageCodegenExec.doExecute(WholeStageCodegenExec.scala:610)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:131)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:127)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:155)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:152)
    at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:127)
    at org.apache.spark.sql.execution.SparkPlan.getByteArrayRdd(SparkPlan.scala:247)
    at org.apache.spark.sql.execution.SparkPlan.executeTake(SparkPlan.scala:339)
    at org.apache.spark.sql.execution.CollectLimitExec.executeCollect(limit.scala:38)
    at org.apache.spark.sql.Dataset.org$apache$spark$sql$Dataset$$collectFromPlan(Dataset.scala:3384)
    at org.apache.spark.sql.Dataset$$anonfun$head$1.apply(Dataset.scala:2545)
    at org.apache.spark.sql.Dataset$$anonfun$head$1.apply(Dataset.scala:2545)
    at org.apache.spark.sql.Dataset$$anonfun$53.apply(Dataset.scala:3365)
    at org.apache.spark.sql.execution.SQLExecution$$anonfun$withNewExecutionId$1.apply(SQLExecution.scala:78)
    at org.apache.spark.sql.execution.SQLExecution$.withSQLConfPropagated(SQLExecution.scala:125)
    at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:73)
    at org.apache.spark.sql.Dataset.withAction(Dataset.scala:3364)
    at org.apache.spark.sql.Dataset.head(Dataset.scala:2545)
    at org.apache.spark.sql.Dataset.take(Dataset.scala:2759)
    at org.apache.spark.sql.Dataset.getRows(Dataset.scala:255)
    at org.apache.spark.sql.Dataset.showString(Dataset.scala:292)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    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.base/java.lang.Thread.run(Thread.java:834)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/me/spark/webtrends-processing/playground.py", line 44, in <module>
    dfRefUrl.show(1)
  File "/home/me/spark/venv/lib/python3.6/site-packages/pyspark/sql/dataframe.py", line 378, in show
    print(self._jdf.showString(n, 20, vertical))
  File "/home/me/spark/venv/lib/python3.6/site-packages/py4j/java_gateway.py", line 1257, in __call__
    answer, self.gateway_client, self.target_id, self.name)
  File "/home/me/spark/venv/lib/python3.6/site-packages/pyspark/sql/utils.py", line 79, in deco
    raise IllegalArgumentException(s.split(': ', 1)[1], stackTrace)
pyspark.sql.utils.IllegalArgumentException: 'Unsupported class file major version 55'
</code>```

Changing show(1) to just show() results in the same crash. I'm using pyspark 2.4.0 on python 3.6. My JAVA_HOME is set to /usr/lib/jvm/java-8-openjdk-amd64. Additionally, running the program in the terminal results in no crash. So I'm led to believe that this has to do with some kind of PyCharm configuration, which is the IDE that I'm using.

答:
TLDR; PyCharm has issues pointing to the right JDK

I had the same problem today. I just solved it by setting the JAVA_HOME variable in the runtime configs in PyCharm to the home directory of my Java 8 SE install. In my case, JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_92.jdk/Contents/home

My JAVA_HOME is set to /usr/lib/jvm/java-8-openjdk-amd64

Is this referring to your actual environment variable JAVA_HOME (i.e., what you get when you type echo $JAVA_HOME to the terminal), or an environment variable set in the runtime config on PyCharm? Because PyCharm will only know of the latter as JAVA_HOME is not a system-wide variable.

Body:
I'm trying to run a simple pyspark example that I've written myself for learning purposes:

from pyspark import SQLContext
from pyspark import SparkContext
from pyspark.sql.types import StringType
from pyspark.sql.functions import udf

from urllib.parse import urlsplit

def extractPath(host, url):
    if host in url:
        return urlsplit(url).path
    else:
        return '-'

sc = SparkContext.getOrCreate()

sqlContext = SQLContext(sc)

# preconstruct custom spark functions, used in method processFile
getPathUdf = udf(extractPath, StringType())

df = sqlContext.read.csv(
    path="resources/smalldatafile.csv",
    header=True,
    inferSchema=True
)

previousPagePathField = 'previous page path'
hostnameField = 'host name'
dataCsRefererField = 'data_cs_referer'

# do mappings
dfMapped = (
    df
        .withColumnRenamed('data_cs_host', hostnameField)
)

# split referrer url
print(previousPagePathField)
print(hostnameField)
print(dataCsRefererField)
print(getPathUdf(hostnameField, dataCsRefererField))
dfRefUrl = dfMapped.withColumn(previousPagePathField, getPathUdf(hostnameField, dataCsRefererField))
dfRefUrl.show(1)

The last line crashes my program with the trace:

2019-03-27 16:49:43 WARN  Utils:66 - Truncated the string representation of a plan since it was too large. This behavior can be adjusted by setting 'spark.debug.maxToStringFields' in SparkEnv.conf.
Traceback (most recent call last):
  File "/home/me/spark/venv/lib/python3.6/site-packages/pyspark/sql/utils.py", line 63, in deco
    return f(*a, **kw)
  File "/home/me/spark/venv/lib/python3.6/site-packages/py4j/protocol.py", line 328, in get_return_value
    format(target_id, ".", name), value)
py4j.protocol.Py4JJavaError: An error occurred while calling o46.showString.
: java.lang.IllegalArgumentException: Unsupported class file major version 55
    at org.apache.xbean.asm6.ClassReader.<init>(ClassReader.java:166)
    at org.apache.xbean.asm6.ClassReader.<init>(ClassReader.java:148)
    at org.apache.xbean.asm6.ClassReader.<init>(ClassReader.java:136)
    at org.apache.xbean.asm6.ClassReader.<init>(ClassReader.java:237)
    at org.apache.spark.util.ClosureCleaner$.getClassReader(ClosureCleaner.scala:49)
    at org.apache.spark.util.FieldAccessFinder$$anon$3$$anonfun$visitMethodInsn$2.apply(ClosureCleaner.scala:517)
    at org.apache.spark.util.FieldAccessFinder$$anon$3$$anonfun$visitMethodInsn$2.apply(ClosureCleaner.scala:500)
    at scala.collection.TraversableLike$WithFilter$$anonfun$foreach$1.apply(TraversableLike.scala:733)
    at scala.collection.mutable.HashMap$$anon$1$$anonfun$foreach$2.apply(HashMap.scala:134)
    at scala.collection.mutable.HashMap$$anon$1$$anonfun$foreach$2.apply(HashMap.scala:134)
    at scala.collection.mutable.HashTable$class.foreachEntry(HashTable.scala:236)
    at scala.collection.mutable.HashMap.foreachEntry(HashMap.scala:40)
    at scala.collection.mutable.HashMap$$anon$1.foreach(HashMap.scala:134)
    at scala.collection.TraversableLike$WithFilter.foreach(TraversableLike.scala:732)
    at org.apache.spark.util.FieldAccessFinder$$anon$3.visitMethodInsn(ClosureCleaner.scala:500)
    at org.apache.xbean.asm6.ClassReader.readCode(ClassReader.java:2175)
    at org.apache.xbean.asm6.ClassReader.readMethod(ClassReader.java:1238)
    at org.apache.xbean.asm6.ClassReader.accept(ClassReader.java:631)
    at org.apache.xbean.asm6.ClassReader.accept(ClassReader.java:355)
    at org.apache.spark.util.ClosureCleaner$$anonfun$org$apache$spark$util$ClosureCleaner$$clean$14.apply(ClosureCleaner.scala:307)
    at org.apache.spark.util.ClosureCleaner$$anonfun$org$apache$spark$util$ClosureCleaner$$clean$14.apply(ClosureCleaner.scala:306)
    at scala.collection.immutable.List.foreach(List.scala:392)
    at org.apache.spark.util.ClosureCleaner$.org$apache$spark$util$ClosureCleaner$$clean(ClosureCleaner.scala:306)
    at org.apache.spark.util.ClosureCleaner$.clean(ClosureCleaner.scala:162)
    at org.apache.spark.SparkContext.clean(SparkContext.scala:2326)
    at org.apache.spark.rdd.RDD$$anonfun$mapPartitions$1.apply(RDD.scala:798)
    at org.apache.spark.rdd.RDD$$anonfun$mapPartitions$1.apply(RDD.scala:797)
    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:363)
    at org.apache.spark.rdd.RDD.mapPartitions(RDD.scala:797)
    at org.apache.spark.sql.execution.python.EvalPythonExec.doExecute(EvalPythonExec.scala:89)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:131)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:127)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:155)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:152)
    at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:127)
    at org.apache.spark.sql.execution.InputAdapter.inputRDDs(WholeStageCodegenExec.scala:374)
    at org.apache.spark.sql.execution.ProjectExec.inputRDDs(basicPhysicalOperators.scala:41)
    at org.apache.spark.sql.execution.WholeStageCodegenExec.doExecute(WholeStageCodegenExec.scala:610)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:131)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:127)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:155)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:152)
    at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:127)
    at org.apache.spark.sql.execution.SparkPlan.getByteArrayRdd(SparkPlan.scala:247)
    at org.apache.spark.sql.execution.SparkPlan.executeTake(SparkPlan.scala:339)
    at org.apache.spark.sql.execution.CollectLimitExec.executeCollect(limit.scala:38)
    at org.apache.spark.sql.Dataset.org$apache$spark$sql$Dataset$$collectFromPlan(Dataset.scala:3384)
    at org.apache.spark.sql.Dataset$$anonfun$head$1.apply(Dataset.scala:2545)
    at org.apache.spark.sql.Dataset$$anonfun$head$1.apply(Dataset.scala:2545)
    at org.apache.spark.sql.Dataset$$anonfun$53.apply(Dataset.scala:3365)
    at org.apache.spark.sql.execution.SQLExecution$$anonfun$withNewExecutionId$1.apply(SQLExecution.scala:78)
    at org.apache.spark.sql.execution.SQLExecution$.withSQLConfPropagated(SQLExecution.scala:125)
    at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:73)
    at org.apache.spark.sql.Dataset.withAction(Dataset.scala:3364)
    at org.apache.spark.sql.Dataset.head(Dataset.scala:2545)
    at org.apache.spark.sql.Dataset.take(Dataset.scala:2759)
    at org.apache.spark.sql.Dataset.getRows(Dataset.scala:255)
    at org.apache.spark.sql.Dataset.showString(Dataset.scala:292)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    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.base/java.lang.Thread.run(Thread.java:834)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/me/spark/webtrends-processing/playground.py", line 44, in <module>
    dfRefUrl.show(1)
  File "/home/me/spark/venv/lib/python3.6/site-packages/pyspark/sql/dataframe.py", line 378, in show
    print(self._jdf.showString(n, 20, vertical))
  File "/home/me/spark/venv/lib/python3.6/site-packages/py4j/java_gateway.py", line 1257, in __call__
    answer, self.gateway_client, self.target_id, self.name)
  File "/home/me/spark/venv/lib/python3.6/site-packages/pyspark/sql/utils.py", line 79, in deco
    raise IllegalArgumentException(s.split(': ', 1)[1], stackTrace)
pyspark.sql.utils.IllegalArgumentException: 'Unsupported class file major version 55'

Changing show(1) to just show() results in the same crash. I'm using pyspark 2.4.0 on python 3.6. My JAVA_HOME is set to /usr/lib/jvm/java-8-openjdk-amd64. Additionally, running the program in the terminal results in no crash. So I'm led to believe that this has to do with some kind of PyCharm configuration, which is the IDE that I'm using.


问:
How to move without VR or AR device?
Most if not all MR devices drive the camera automatically. How is this supposed to be achieved using Windows Standalone for example, where I use the mouse as input device. I suppose there is some sort of WASD movement, either already available, or implementable?</p>

答: You can use the Input Simulation Service to move the camera in Windows Standalone. Then the camera will move using WASD. To enable this for Windows Standalone, just enable the Input Simulation Service for the Windows Standalone Platform:

Title: How to move without VR or AR device?


问:
Qt's signal / slot mechanism over the network
I want to be able to send Qt signals over the network. Serializing a signal call is quite straight forward using Qt's meta type system:

Create a qMetaMethod using the static method ::fromSignal

Get the method name, parameter names, their typeIds [1] and values using the created meta method.

Pack everything into your preferred format (JSON, XML) and send it.

But so far I could not figure out how to invoke a signal using serialized data: QMetaObject::invokeMethod(..) takes the signal / method name as string. The problem are the arguments: They must be provided as QGenericArgument and those can only be created by using the Q_ARG macro which requires the actual type (not a string of it's name or the typeId) and the concerning value. Also the number of arguments must be defined at compile time, there is is no invokeMethod(..) which takes a list of arguments.

Am I missing something? Or is there a better / alternative way to do this?

[1] Further question: How do I ensure that types always get the same typeId when they are registered using Q_DECLARE_METATYPE(..)?

答:
You really should consider using Qt Remote Object since they accomplish everything that you need and more (heartbeat, automatic re-connection upon disconnect, works with either QLocalSocket or QTcpSocket under the hood, etc) It the easiest to get signals across the network with minimal effort that I know of.

https://doc.qt.io/qt-5/qtremoteobjects-index.html

You just need to define .rep text file, which is like an IDL definition file

```<code>class MyRemoteObject {
{
    SIGNAL(foo(int value));
    SIGNAL(bar(float value));
    SLOT(somethingChanged(int newValue));
};
</code>```

and then it takes that .rep file to generate code for the server side (known as 'source') and code for the client side (known as 'replica') using a built-in repc compiler that is called by qmake or cmake.  Every signals called by the 'source' is automatically sent across every connected 'replicas', and slots called by 'replicas' are received by the 'source'

ContentLicense: CC BY-SA 3.0

Body:
You really should consider using Qt Remote Object since they accomplish everything that you need and more (heartbeat, automatic re-connection upon disconnect, works with either QLocalSocket or QTcpSocket under the hood, etc) It the easiest to get signals across the network with minimal effort that I know of.

https://doc.qt.io/qt-5/qtremoteobjects-index.html

You just need to define .rep text file, which is like an IDL definition file

class MyRemoteObject {
{
    SIGNAL(foo(int value));
    SIGNAL(bar(float value));
    SLOT(somethingChanged(int newValue));
};

and then it takes that .rep file to generate code for the server side (known as 'source') and code for the client side (known as 'replica') using a built-in repc compiler that is called by qmake or cmake.  Every signals called by the 'source' is automatically sent across every connected 'replicas', and slots called by 'replicas' are received by the 'source'


问:
How to efficiently find a specific substring in PHP?
OK, I know how to do this but I'm interested in better/more elegant solutions (if any) for this problem.

Imagine I have the following string :

Mozilla/4.0 (compatible; MSIE 7.0;
  Windows NT 5.1; Trident/4.0; GTB6.6;
  Mozilla/4.0 (compatible; MSIE 6.0;
  Windows NT 5.1; SV1) ; .NET CLR
  1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)

I'm interested to find the highest MSIE version in that string (in that case 7.0).

Currently I use explode and preg_match a couple of times in combination with str_replace then I loop between matches and then compare the version string. It works but it's far from elegant. Any ideas on how to improve this?

Keep in mind that:

The string can have any number of MSIE occurrences (or even none)

MSIE is case insensitive

MSIE is followed by a white space (space, tab...) then by the version. The version can contain number letters and dots. The version string is ended by either a white space, a ; or the end of the line.

Thanks!

答:
Try:</p>

```<code><?php
$str = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; GTB6.6; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1), MSIE 8.7abc; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729) MSIE 9.0';

if (preg_match_all('/msie\s*([^\s;$]+)/i', $str, $m)) {
    usort($m[1], 'version_compare');
    $max = array_pop($m[1]);

    echo $max;
}
</code>```

Body:
Try:

<?php
$str = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; GTB6.6; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1), MSIE 8.7abc; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729) MSIE 9.0';

if (preg_match_all('/msie\s*([^\s;$]+)/i', $str, $m)) {
    usort($m[1], 'version_compare');
    $max = array_pop($m[1]);

    echo $max;
}


问:
Accessing previous member based on strtomember
I've created a simple named set [Latest] which uses the previous day's date. This works as required, and can be used by any measures that reference the date dimension:

```<code>CREATE DYNAMIC SET CURRENTCUBE.[Latest]
AS strtomember('[Date].[Date Key].&['+
vba!Format(DateAdd('d',-1,Now()),'yyyyMMdd')+']');
</code>```

Now I have a requirement to go back an additional business day, and to have this displayed as a separate calculation.

The date dimension is populated only with business dates, but also has an IsBusinessDay attribute. As the 'Latest' calculation uses the dateadd vba function, I can't simply increase the dateadd parameter, as there are gaps in the dates (for holidays/weekends) (though I have the option to go back to the source view and change this if required).

I was able achieve the create a working calculation when using a specific measure, but what I am looking to achieve is to have a single named set calculation that that can be used with any measure, and not hard-coded into the calculation like this:

```<code>CREATE MEMBER [TwoDaysBack] AS
(
      [Date].[Date Key].currentmember.prevmember,
      [Measures].[PL]
    ) ;
</code>```

Any suggestion or pointers greatly appreciated.

答:
As per my understanding, you just have bussiness days in your Date dimension. So for any member in your date dimension ,Prevmember will get the day before the last date. If that is the case your initial named set will work with a slight change.</p>

```<code>CREATE DYNAMIC SET CURRENTCUBE.[Latest]
AS strtomember('[Date].[Date Key].&['+
vba!Format(DateAdd('d',-1,Now()),'yyyyMMdd')+']').prevmember;
</code>```

Body:
I've created a simple named set [Latest] which uses the previous day's date. This works as required, and can be used by any measures that reference the date dimension:

CREATE DYNAMIC SET CURRENTCUBE.[Latest]
AS strtomember('[Date].[Date Key].&['+
vba!Format(DateAdd('d',-1,Now()),'yyyyMMdd')+']');

Now I have a requirement to go back an additional business day, and to have this displayed as a separate calculation.

The date dimension is populated only with business dates, but also has an IsBusinessDay attribute. As the 'Latest' calculation uses the dateadd vba function, I can't simply increase the dateadd parameter, as there are gaps in the dates (for holidays/weekends) (though I have the option to go back to the source view and change this if required).

I was able achieve the create a working calculation when using a specific measure, but what I am looking to achieve is to have a single named set calculation that that can be used with any measure, and not hard-coded into the calculation like this:

CREATE MEMBER [TwoDaysBack] AS
(
      [Date].[Date Key].currentmember.prevmember,
      [Measures].[PL]
    ) ;

Any suggestion or pointers greatly appreciated.

Body:
As per my understanding, you just have bussiness days in your Date dimension. So for any member in your date dimension ,Prevmember will get the day before the last date. If that is the case your initial named set will work with a slight change.

CREATE DYNAMIC SET CURRENTCUBE.[Latest]
AS strtomember('[Date].[Date Key].&['+
vba!Format(DateAdd('d',-1,Now()),'yyyyMMdd')+']').prevmember;


问:
List all possible combinations of pandas dataframe values to reach a certain sum
I have a pandas dataframe that looks like this:

```<code>party seats
A      34
B      26
C      19
D      12
E      10
</code>```

There are always 101 seats in total. I need to get a list of all possible combinations of parties, which have 51 or more seats together.

For instance,

```<code>[A, B]
[A, C]
[A, B, C]
[A, B, D]
...
[A, B, C, D, E]
</code>```

or something like this. Any help or tips would be much appreciated.

答:
Since you mentioned "all combinations", I think you are not looking at one optimal solution. The only possibility would be to brute-force and generate all combinations of parties and choose the ones that have a sum greater than 51.

Here is one way of doing it.

```<code>import pandas as pd
import numpy as np
import itertools

# Data Generation
alphabets = [chr(i) for i in range(ord('a'),ord('z')+1)]
party_size = 6
seats = 51
df = pd.DataFrame(np.random.randint(20,100,party_size), index=alphabets[:party_size])

#Algo
parties = df.index
a = []
for r in range(parties.shape[0]): # Generate combinations
    ls = list(itertools.combinations(parties, r))
    ls1 = [inx for inx in ls if df.loc[inx,:].sum()[0] > seats] # Choose only what qualifies
    a.extend(ls1) # Generate master list
</code>```

Body:
I have a pandas dataframe that looks like this:

party seats
A      34
B      26
C      19
D      12
E      10

There are always 101 seats in total. I need to get a list of all possible combinations of parties, which have 51 or more seats together.

For instance,

[A, B]
[A, C]
[A, B, C]
[A, B, D]
...
[A, B, C, D, E]

or something like this. Any help or tips would be much appreciated.

Body:
Since you mentioned "all combinations", I think you are not looking at one optimal solution. The only possibility would be to brute-force and generate all combinations of parties and choose the ones that have a sum greater than 51.

Here is one way of doing it.

import pandas as pd
import numpy as np
import itertools

# Data Generation
alphabets = [chr(i) for i in range(ord('a'),ord('z')+1)]
party_size = 6
seats = 51
df = pd.DataFrame(np.random.randint(20,100,party_size), index=alphabets[:party_size])

#Algo
parties = df.index
a = []
for r in range(parties.shape[0]): # Generate combinations
    ls = list(itertools.combinations(parties, r))
    ls1 = [inx for inx in ls if df.loc[inx,:].sum()[0] > seats] # Choose only what qualifies
    a.extend(ls1) # Generate master list


问:
How to elegantly customize the collection key name in laravel

For example, there is such a collection

$phone_Id = $request->get('q');
$colors = Phone::find($phone_Id)->color->toArray();
dd($colors);
```

<ol start="2">
<li>print result</li>
</ol>

<pre class="lang-sh prettyprint-override"><code>array:2 [▼
  0 => array:6 [▼
    "id" => 8
    "name" => "red"
    "value" => "#fb6250"
    "created_at" => "2019-05-29 01:42:51"
    "updated_at" => "2019-05-29 01:42:51"
    "pivot" => array:4 [▼
      "phone_id" => 1
      "color_id" => 8
      "created_at" => "2019-05-29 01:42:51"
      "updated_at" => "2019-05-29 01:42:51"
    ]
  ]
  1 => array:6 [▼
    "id" => 11
    "name" => "blue"
    "value" => "#202020"
    "created_at" => "2019-05-29 01:42:51"
    "updated_at" => "2019-05-29 01:42:51"
    "pivot" => array:4 [▼
      "phone_id" => 1
      "color_id" => 11
      "created_at" => "2019-05-29 01:42:51"
      "updated_at" => "2019-05-29 01:42:51"
    ]
  ]
]
</code>```

The end result I want is an array like this

array:2 [▼
  0 => array:2 [▼
    "id" => 8
    "text" => "red"
  ]
  1 => array:2 [▼
    "id" => 11
    "text" => "blue"
  ]
]
```

<ol start="4">
<li>So my current practice is like this.</li>
</ol>

<pre class="lang-php prettyprint-override"><code>$data = [];
foreach ($colors as $key => $val) {
    $data[$key]['id'] = $val->id;
    $data[$key]['text'] = $val->name;
}
dd($data);
</code>```

print result

array:2 [▼
  0 => array:2 [▼
    "id" => 8
    "text" => "red"
  ]
  1 => array:2 [▼
    "id" => 11
    "text" => "blue"
  ]
]
```

I want to know if there is a better and more beautiful implementation for this kind of demand in laravel?

答:
Use select('id', 'name')

Try this one.

```<code>$colors = Phone::find($phone_Id)->color()->select('id', 'name')->get()->toArray()

dd($colors);
</code>```

Body:
For example, there is such a collection

$phone_Id = $request->get('q');
$colors = Phone::find($phone_Id)->color->toArray();
dd($colors);

print result

array:2 [▼
  0 => array:6 [▼
    "id" => 8
    "name" => "red"
    "value" => "#fb6250"
    "created_at" => "2019-05-29 01:42:51"
    "updated_at" => "2019-05-29 01:42:51"
    "pivot" => array:4 [▼
      "phone_id" => 1
      "color_id" => 8
      "created_at" => "2019-05-29 01:42:51"
      "updated_at" => "2019-05-29 01:42:51"
    ]
  ]
  1 => array:6 [▼
    "id" => 11
    "name" => "blue"
    "value" => "#202020"
    "created_at" => "2019-05-29 01:42:51"
    "updated_at" => "2019-05-29 01:42:51"
    "pivot" => array:4 [▼
      "phone_id" => 1
      "color_id" => 11
      "created_at" => "2019-05-29 01:42:51"
      "updated_at" => "2019-05-29 01:42:51"
    ]
  ]
]

The end result I want is an array like this

array:2 [▼
  0 => array:2 [▼
    "id" => 8
    "text" => "red"
  ]
  1 => array:2 [▼
    "id" => 11
    "text" => "blue"
  ]
]

So my current practice is like this.

$data = [];
foreach ($colors as $key => $val) {
    $data[$key]['id'] = $val->id;
    $data[$key]['text'] = $val->name;
}
dd($data);

print result

array:2 [▼
  0 => array:2 [▼
    "id" => 8
    "text" => "red"
  ]
  1 => array:2 [▼
    "id" => 11
    "text" => "blue"
  ]
]

I want to know if there is a better and more beautiful implementation for this kind of demand in laravel?

Body:
Use select('id', 'name')

Try this one.

$colors = Phone::find($phone_Id)->color()->select('id', 'name')->get()->toArray()

dd($colors);


问:
How to fix pip error when installing requests
I was trying to use the Terminal on Ubuntu 16.04 to install Requests for API calls in Python and had this error. How would I go about fixing it?

I have already tried creating a virtualenv to install it only there but it did not work either.

I typed in "pip install requests"

```<code>Exception:
Traceback (most recent call last):

File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 209, in main status = self.run(options, args)

  File "/usr/local/lib/python2.7/dist-packages/pip/commands/install.py", line 317, in run prefix=options.prefix_path,

  File "/usr/local/lib/python2.7/dist-packages/pip/req/req_set.py", line 726, in install requirement.uninstall(auto_confirm=True)

  File "/usr/local/lib/python2.7/dist-packages/pip/req/req_install.py", line 746, in uninstall paths_to_remove.remove(auto_confirm)

  File "/usr/local/lib/python2.7/dist-packages/pip/req/req_uninstall.py", line 115, in remove renames(path, new_path)

  File "/usr/local/lib/python2.7/dist-packages/pip/utils/__init__.py", line 267, in renames shutil.move(old, new)

  File "/usr/lib/python2.7/shutil.py", line 300, in move
    rmtree(src)

  File "/usr/lib/python2.7/shutil.py", line 252, in rmtree
    onerror(os.remove, fullname, sys.exc_info())

  File "/usr/lib/python2.7/shutil.py", line 250, in rmtree
    os.remove(fullname)

OSError: [Errno 13] Permission denied: '/usr/lib/python2.7/dist-packages/idna/codec.pyc'
</code>```

答:
When you are opening the command prompt, make sure you open it as administrator. You can do this by: (assuming you are on windows)

1: Clicking the windows key

2: Typing in Command Prompt

3: Right Clicking the first option and choosing Run as Administrator

4: Clicking yes in the box that should appear.

After all of that, you should be able to use pip install Requests and install it. If that doesn't work, you can use this command instead (still in administrator mode):

python -m easy_install Requests
or
python -m pip install Requests

Body:
I was trying to use the Terminal on Ubuntu 16.04 to install Requests for API calls in Python and had this error. How would I go about fixing it?

I have already tried creating a virtualenv to install it only there but it did not work either.

I typed in "pip install requests"

Exception:
Traceback (most recent call last):

File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 209, in main status = self.run(options, args)

  File "/usr/local/lib/python2.7/dist-packages/pip/commands/install.py", line 317, in run prefix=options.prefix_path,

  File "/usr/local/lib/python2.7/dist-packages/pip/req/req_set.py", line 726, in install requirement.uninstall(auto_confirm=True)

  File "/usr/local/lib/python2.7/dist-packages/pip/req/req_install.py", line 746, in uninstall paths_to_remove.remove(auto_confirm)

  File "/usr/local/lib/python2.7/dist-packages/pip/req/req_uninstall.py", line 115, in remove renames(path, new_path)

  File "/usr/local/lib/python2.7/dist-packages/pip/utils/__init__.py", line 267, in renames shutil.move(old, new)

  File "/usr/lib/python2.7/shutil.py", line 300, in move
    rmtree(src)

  File "/usr/lib/python2.7/shutil.py", line 252, in rmtree
    onerror(os.remove, fullname, sys.exc_info())

  File "/usr/lib/python2.7/shutil.py", line 250, in rmtree
    os.remove(fullname)

OSError: [Errno 13] Permission denied: '/usr/lib/python2.7/dist-packages/idna/codec.pyc'


问:
PyCharm import external library
I am using PyCharm as an editor for python code in Houdini. Whenever I try to import the main Houdini library (hou) I get an error flagged in PyCharm. If I include the code snippet:-

```<code>try:
   import hou
except ImportError:
    # Add $HFS/houdini/python2.6libs to sys.path so Python can find the
    # hou module.
    sys.path.append(os.environ['HFS'] + "/houdini/python%d.%dlibs" % sys.version_info[:2])
    import hou
</code>```

my code executes, without problem, from both Houdini and my selected interpreter.

My problem is with PyCharm itself. The editor flags 'import hou' as an error and any subsequent files that import this file flag modules imported by this file as errors as well. Hence I loose type ahead functionality and get an over abundance of error messages that make it hard to spot the real problems.

How do I get PyCharm to recognize the path to the hou module.

I have tried, for a couple of days, to Google a solution to this problem but they all seem to refer to tabs and settings that are not in my version of PyCharm (Community Edition 3.4.1). E.G. my 'Project Interpreter' setting only has a list of Packages and has no 'path' tab as stated in many 'fixes' to closely related problems.

答:
In order to reference an external library in a project
File -> Settings -> Project -> Project structure -> select the folder and mark as a source</p>

Title: PyCharm import external library

Body:
I am using PyCharm as an editor for python code in Houdini. Whenever I try to import the main Houdini library (hou) I get an error flagged in PyCharm. If I include the code snippet:-

try:
   import hou
except ImportError:
    # Add $HFS/houdini/python2.6libs to sys.path so Python can find the
    # hou module.
    sys.path.append(os.environ['HFS'] + "/houdini/python%d.%dlibs" % sys.version_info[:2])
    import hou

my code executes, without problem, from both Houdini and my selected interpreter.

My problem is with PyCharm itself. The editor flags 'import hou' as an error and any subsequent files that import this file flag modules imported by this file as errors as well. Hence I loose type ahead functionality and get an over abundance of error messages that make it hard to spot the real problems.

How do I get PyCharm to recognize the path to the hou module.

I have tried, for a couple of days, to Google a solution to this problem but they all seem to refer to tabs and settings that are not in my version of PyCharm (Community Edition 3.4.1). E.G. my 'Project Interpreter' setting only has a list of Packages and has no 'path' tab as stated in many 'fixes' to closely related problems.


问:
What is an idiomatic Scala way to "remove" one element from an immutable List?
I have a List, which may contain elements that will compare as equal. I would like a similar List, but with one element removed. So from (A, B, C, B, D) I would like to be able to "remove" just one B to get e.g. (A, C, B, D). The order of the elements in the result does not matter.

I have working code, written in a Lisp-inspired way in Scala. Is there a more idiomatic way
to do this?

The context is a card game where two decks of standard cards are in play, so there may
be duplicate cards but still played one at a time.

```<code>def removeOne(c: Card, left: List[Card], right: List[Card]): List[Card] = {
  if (Nil == right) {
    return left
  }
  if (c == right.head) {
    return left ::: right.tail
  }
  return removeOne(c, right.head :: left, right.tail)
}

def removeCard(c: Card, cards: List[Card]): List[Card] = {
  return removeOne(c, Nil, cards)
}
</code>```

答:
Unfortunately, the collections hierarchy got itself into a bit of a mess with - on List.  For ArrayBuffer it works just like you might hope:

```<code>scala> collection.mutable.ArrayBuffer(1,2,3,2,4) - 2
res0: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 3, 2, 4)
</code>```

but, sadly, List ended up with a filterNot-style implementation and thus does the "wrong thing" and throws a deprecation warning at you (sensible enough, since it is actually filterNoting):

```<code>scala> List(1,2,3,2,4) - 2
warning: there were deprecation warnings; re-run with -deprecation for details
res1: List[Int] = List(1, 3, 4)
</code>```

So arguably the easiest thing to do is convert List into a collection that does this right, and then convert back again:

```<code>import collection.mutable.ArrayBuffer._
scala> ((ArrayBuffer() ++ List(1,2,3,2,4)) - 2).toList
res2: List[Int] = List(1, 3, 2, 4)
</code>```

Alternatively, you could keep the logic of the code you've got but make the style more idiomatic:

```<code>def removeInt(i: Int, li: List[Int]) = {
  def removeOne(i: Int, left: List[Int], right: List[Int]): List[Int] = right match {
    case r :: rest =>
      if (r == i) left.reverse ::: rest
      else removeOne(i, r :: left, rest)
    case Nil => left.reverse
  }
  removeOne(i, Nil, li)
}

scala> removeInt(2, List(1,2,3,2,4))
res3: List[Int] = List(1, 3, 2, 4)
</code>```

Body:
I have a List, which may contain elements that will compare as equal. I would like a similar List, but with one element removed. So from (A, B, C, B, D) I would like to be able to "remove" just one B to get e.g. (A, C, B, D). The order of the elements in the result does not matter.

I have working code, written in a Lisp-inspired way in Scala. Is there a more idiomatic way
to do this?

The context is a card game where two decks of standard cards are in play, so there may
be duplicate cards but still played one at a time.

def removeOne(c: Card, left: List[Card], right: List[Card]): List[Card] = {
  if (Nil == right) {
    return left
  }
  if (c == right.head) {
    return left ::: right.tail
  }
  return removeOne(c, right.head :: left, right.tail)
}

def removeCard(c: Card, cards: List[Card]): List[Card] = {
  return removeOne(c, Nil, cards)
}

Body:
Unfortunately, the collections hierarchy got itself into a bit of a mess with - on List.  For ArrayBuffer it works just like you might hope:

scala> collection.mutable.ArrayBuffer(1,2,3,2,4) - 2
res0: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 3, 2, 4)

but, sadly, List ended up with a filterNot-style implementation and thus does the "wrong thing" and throws a deprecation warning at you (sensible enough, since it is actually filterNoting):

scala> List(1,2,3,2,4) - 2
warning: there were deprecation warnings; re-run with -deprecation for details
res1: List[Int] = List(1, 3, 4)

So arguably the easiest thing to do is convert List into a collection that does this right, and then convert back again:

import collection.mutable.ArrayBuffer._
scala> ((ArrayBuffer() ++ List(1,2,3,2,4)) - 2).toList
res2: List[Int] = List(1, 3, 2, 4)

Alternatively, you could keep the logic of the code you've got but make the style more idiomatic:

def removeInt(i: Int, li: List[Int]) = {
  def removeOne(i: Int, left: List[Int], right: List[Int]): List[Int] = right match {
    case r :: rest =>
      if (r == i) left.reverse ::: rest
      else removeOne(i, r :: left, rest)
    case Nil => left.reverse
  }
  removeOne(i, Nil, li)
}

scala> removeInt(2, List(1,2,3,2,4))
res3: List[Int] = List(1, 3, 2, 4)


问:
Do datalakes offered from amazon and azure support rosbag files?
I have a lot of camera, radar and lidar data stored with me in a hard-disk in rosbag formats. I would now like to shift this to a cloud service, preferably trying to preserve the rosbag format.

From what I understand in data lakes you can store data in their natural format. Is there a also limit the formats supported by datalakes.

Any help is much appreciated.

答:
Data Lake gives the freedom to store data in natural format. So far there is no limit, in whatever format you can store data in data lake.

Aws Datalake documents
https://aws.amazon.com/lake-formation/

Azure Datalake
https://azure.microsoft.com/en-us/solutions/data-lake/


问:
RegEx for matching various dates
I am trying to put together a regex statement to match on each of the below date formats.

```<code>* Mar 7, 2017
Mar. 7, 2017
* March 7, 2017
3-7-2017
03-07-2017
3-7-17
03-07-17
* 03/7/2017
* 03/07/17
* 3/7/17
Mar-07-2017
Mar-7-2017
March-07-2017
</code>```

The below regex matches on the date formats that are indicated by an asterisk above. I have tried in vain to add to what I already have but have been unsuccessful.

([0-9]+)/([0-9]+)/([0-9]+)|([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))|\w+\s\d{2},\s\d{4}|(?i)\b(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec](?:ember)?)\b
  (?:0?[1-9]|[1-2][0-9]|3[01]),? \d{4}

Any help is always appreciated!

* Bonus question *

On some occasions, there may be multiple date matches and I need it to find a match following a certain word. In the past I've used the below syntax by enclosing the regex statement between the parenthesis after the period.

```<code>(?<=Word).(StatementHere)
</code>```

Title: RegEx for matching various dates

Body:
I am trying to put together a regex statement to match on each of the below date formats.

* Mar 7, 2017
Mar. 7, 2017
* March 7, 2017
3-7-2017
03-07-2017
3-7-17
03-07-17
* 03/7/2017
* 03/07/17
* 3/7/17
Mar-07-2017
Mar-7-2017
March-07-2017

The below regex matches on the date formats that are indicated by an asterisk above. I have tried in vain to add to what I already have but have been unsuccessful.

([0-9]+)/([0-9]+)/([0-9]+)|([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))|\w+\s\d{2},\s\d{4}|(?i)\b(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec](?:ember)?)\b
  (?:0?[1-9]|[1-2][0-9]|3[01]),? \d{4}

Any help is always appreciated!

* Bonus question *

On some occasions, there may be multiple date matches and I need it to find a match following a certain word. In the past I've used the below syntax by enclosing the regex statement between the parenthesis after the period.

(?<=Word).(StatementHere)

Body:
Try this then ...

([0-9]+)/([0-9]+)/([0-9]+)|((0?[1-9]|1[0-2])-(0?[1-9]|[12]\d|3[01])-(\d{4}|\d{2}))|\w+\s\d{2},\s\d{4}|(?i)\b(Jan(?:uary|\.)?|Feb(?:ruary|\.)?|Mar(?:ch|\.)?|Apr(?:il|\.)?|May|Jun(?:e|\.)?|Jul(?:y|\.)?|Aug(?:ust|\.)?|Sep(?:tember|\.)?|Oct(?:ober|\.)?|Nov(?:ember|\.)?|Dec(?:ember|\.)?)([ ](?:0?[1-9]|[1-2][0-9]|3[01]),?[ ]|-(?:0?[1-9]|[1-2][0-9]|3[01])-)(\d{4})

https://regex101.com/r/k1vaVN/1

Readable version

    ( [0-9]+ )                    # (1)
    /
    ( [0-9]+ )                    # (2)
    /
    ( [0-9]+ )                    # (3)
 |
    (                             # (4 start)
         ( 0? [1-9] | 1 [0-2] )        # (5)
         -
         ( 0? [1-9] | [12] \d | 3 [01] )  # (6)
         -
         ( \d{4} | \d{2} )             # (7)
    )                             # (4 end)
 |
    \w+ \s \d{2} , \s \d{4}
 |
    (?i)
    \b
    (                             # (8 start)
         Jan
         (?: uary | \. )?
      |  Feb
         (?: ruary | \. )?
      |  Mar
         (?: ch | \. )?
      |  Apr
         (?: il | \. )?
      |  May
      |  Jun
         (?: e | \. )?
      |  Jul
         (?: y | \. )?
      |  Aug
         (?: ust | \. )?
      |  Sep
         (?: tember | \. )?
      |  Oct
         (?: ober | \. )?
      |  Nov
         (?: ember | \. )?
      |  Dec
         (?: ember | \. )?
    )                             # (8 end)
    (                             # (9 start)
         [ ]
         (?: 0? [1-9] | [1-2] [0-9] | 3 [01] )
         ,? [ ]
      |  -
         (?: 0? [1-9] | [1-2] [0-9] | 3 [01] )
         -
    )                             # (9 end)
    ( \d{4} )                     # (10)

update

Just wrap the dates in a (?: ) group, then add whatever qualifier before

it that you need.

word[ ]or[ ]phrase[ ]+\K(?:([0-9]+)/([0-9]+)/([0-9]+)|((0?[1-9]|1[0-2])-(0?[1-9]|[12]\d|3[01])-(\d{4}|\d{2}))|\w+\s\d{2},\s\d{4}|(?i)\b(Jan(?:uary|\.)?|Feb(?:ruary|\.)?|Mar(?:ch|\.)?|Apr(?:il|\.)?|May|Jun(?:e|\.)?|Jul(?:y|\.)?|Aug(?:ust|\.)?|Sep(?:tember|\.)?|Oct(?:ober|\.)?|Nov(?:ember|\.)?|Dec(?:ember|\.)?)([ ](?:0?[1-9]|[1-2][0-9]|3[01]),?[ ]|-(?:0?[1-9]|[1-2][0-9]|3[01])-)(\d{4}))


问:
Best practice to handle data from API call and render React components
I am somewhat new to React and looking for best practices for a particular situation within my React/Redux/Firebase PWA. Right now, the part I am concerned with is essentially a wrapper for the Yelp API.

I have a main component that queries the Yelp API when loaded (inside componentDidMount) based on user preferences received elsewhere in the app. This component also queries the API on a form submit with user inputs. It loops thru the data from both, and passes props to a child component. This view looks like a list of all the businesses received from the API. Here's what an example looks like:

```<code>"businesses": [
    {
      "rating": 4,
      "price": "$",
      "phone": "+14152520800",
      "id": "E8RJkjfdcwgtyoPMjQ_Olg",
      "alias": "four-barrel-coffee-san-francisco",
      "is_closed": false,
      "categories": [
        {
          "alias": "coffee",
          "title": "Coffee & Tea"
        }
      ],
      "review_count": 1738,
      "name": "Four Barrel Coffee",
      "url": "https://www.yelp.com/biz/four-barrel-coffee-san-francisco",
      "coordinates": {
        "latitude": 37.7670169511878,
        "longitude": -122.42184275
      },
      "image_url": "http://s3-media2.fl.yelpcdn.com/bphoto/MmgtASP3l_t4tPCL1iAsCg/o.jpg",
      "location": {
        "city": "San Francisco",
        "country": "US",
        "address2": "",
        "address3": "",
        "state": "CA",
        "address1": "375 Valencia St",
        "zip_code": "94103"
      },
      "distance": 1604.23,
      "transactions": ["pickup", "delivery"]
    },
    // ...
  ],
</code>```

As mentioned before, the main component passes down data to the child component, which renders each single object that list. This child component also creates a Link to another component based on the id of each business. This other component for now is simply the exact same look as one individual child component, just on a different URL. For example, the main component is "/venues" and the individual page for a business would be "/venue/E8RJkjfdcwgtyoPMjQ_Olg". The data is pulled from the Redux state (its a HOC), and filtered out to find that id.

The problem I'm running in to is when I refresh the page while on a businesses's individual page, Redux state is cleared out and hence is unable to render properly with the data. To try and work around this I attempted to have a service worker cache everything it would need, but this does not work. Refreshing ends up just showing the loading page I created, because its not making the call (which is expected - don't want it doing this) and its also not pulling data from the caches.

Is there a better way to accomplish getting data all the way to the individual business component after a refresh? Or a better way to cache the entire page/API response so it will render properly on a refresh?

I suppose I could have it reach out to the API for that specific business but I was trying to avoid that.

答:
I remember Yelp API has an endpoint where you can get details of an individual business. That said, you should have a dynamic route for your individual business page; e.g. /businesses/:id. Then you can access this query param in your route props and go from there to fetch data for that specific business.

Something like this:

```<code>class IndividualBusiness extends Component {
  // ...

  componentDidMount() {
    fetchBusinessById(this.props.match.id).then(setState(...))
    // ...
  }

  // ...
}
</code>```

The route would look like something like this:

```<code><Route exact path="/businesses/:id" render={(routeProps) => <IndividualBusiness {...routeProps} />}/>
</code>```

But what about when data is already in redux store? Simple, just add the control flow in your componentDidMount().

Body:
I am somewhat new to React and looking for best practices for a particular situation within my React/Redux/Firebase PWA. Right now, the part I am concerned with is essentially a wrapper for the Yelp API.

I have a main component that queries the Yelp API when loaded (inside componentDidMount) based on user preferences received elsewhere in the app. This component also queries the API on a form submit with user inputs. It loops thru the data from both, and passes props to a child component. This view looks like a list of all the businesses received from the API. Here's what an example looks like:

"businesses": [
    {
      "rating": 4,
      "price": "$",
      "phone": "+14152520800",
      "id": "E8RJkjfdcwgtyoPMjQ_Olg",
      "alias": "four-barrel-coffee-san-francisco",
      "is_closed": false,
      "categories": [
        {
          "alias": "coffee",
          "title": "Coffee & Tea"
        }
      ],
      "review_count": 1738,
      "name": "Four Barrel Coffee",
      "url": "https://www.yelp.com/biz/four-barrel-coffee-san-francisco",
      "coordinates": {
        "latitude": 37.7670169511878,
        "longitude": -122.42184275
      },
      "image_url": "http://s3-media2.fl.yelpcdn.com/bphoto/MmgtASP3l_t4tPCL1iAsCg/o.jpg",
      "location": {
        "city": "San Francisco",
        "country": "US",
        "address2": "",
        "address3": "",
        "state": "CA",
        "address1": "375 Valencia St",
        "zip_code": "94103"
      },
      "distance": 1604.23,
      "transactions": ["pickup", "delivery"]
    },
    // ...
  ],

As mentioned before, the main component passes down data to the child component, which renders each single object that list. This child component also creates a Link to another component based on the id of each business. This other component for now is simply the exact same look as one individual child component, just on a different URL. For example, the main component is "/venues" and the individual page for a business would be "/venue/E8RJkjfdcwgtyoPMjQ_Olg". The data is pulled from the Redux state (its a HOC), and filtered out to find that id.

The problem I'm running in to is when I refresh the page while on a businesses's individual page, Redux state is cleared out and hence is unable to render properly with the data. To try and work around this I attempted to have a service worker cache everything it would need, but this does not work. Refreshing ends up just showing the loading page I created, because its not making the call (which is expected - don't want it doing this) and its also not pulling data from the caches.

Is there a better way to accomplish getting data all the way to the individual business component after a refresh? Or a better way to cache the entire page/API response so it will render properly on a refresh?

I suppose I could have it reach out to the API for that specific business but I was trying to avoid that.

Body:
I remember Yelp API has an endpoint where you can get details of an individual business. That said, you should have a dynamic route for your individual business page; e.g. /businesses/:id. Then you can access this query param in your route props and go from there to fetch data for that specific business.

Something like this:

class IndividualBusiness extends Component {
  // ...

  componentDidMount() {
    fetchBusinessById(this.props.match.id).then(setState(...))
    // ...
  }

  // ...
}

The route would look like something like this:

<Route exact path="/businesses/:id" render={(routeProps) => <IndividualBusiness {...routeProps} />}/>

But what about when data is already in redux store? Simple, just add the control flow in your componentDidMount().


问:
Get Permission denied (publickey) for Git push to Google Cloud Source Repository with Google Cloud SDK authentication method on Windows 10
I'm trying to use Google Cloud Source Repository as a remote repository. I followed all the procedures to authenticate with the Google Cloud SDK authentication method that allows me to not use SSH keys (as they say).

The problem is: I always get Permission denied (publickey) fatal: Could not read from remote repository. message when I try git push --all google.

The gcloud command is in my Windows PATH (C:\Users\xxxxx\AppData\Local\Google\Cloud SDK\;) and my user has enough permission as I'm the owner of the project in Google Cloud.

I know this message is usually a simple SSH key problem that can be resolved by adding my public key to the project, but this method is supposed to work without ssh keys, so I would like to learn what I am doing wrong.

Here the 2 first commands I made following the Google Cloud Source Repository procedure:

```<code>gcloud init && git config --global credential.https://source.developers.google.com.helper gcloud.cmd
git remote add google ssh://username@gmail.com@source.developers.google.com:2022/p/my-website-project/r/my_website
</code>```

These 2 worked well.

Maybe someone could help me to find what to do to fix that.

Thank you.

答:
I have the same issue on Linux (Mint/Ubuntu) when I was trying to set the remote of an existing repository to Google Cloud Source Repos. This is what it looks like you are attempting. However, this was the empty git repository generated by Expo CLI Quickstart, which had no files or source history at all.

What I did instead was clone the existing repository on Google Cloud Source Repos to my computer, add a dummy file, commit it and push. That worked for me. Hopefully it works for you.

Body:
I'm trying to use Google Cloud Source Repository as a remote repository. I followed all the procedures to authenticate with the Google Cloud SDK authentication method that allows me to not use SSH keys (as they say).

The problem is: I always get Permission denied (publickey) fatal: Could not read from remote repository. message when I try git push --all google.

The gcloud command is in my Windows PATH (C:\Users\xxxxx\AppData\Local\Google\Cloud SDK\;) and my user has enough permission as I'm the owner of the project in Google Cloud.

I know this message is usually a simple SSH key problem that can be resolved by adding my public key to the project, but this method is supposed to work without ssh keys, so I would like to learn what I am doing wrong.

Here the 2 first commands I made following the Google Cloud Source Repository procedure:

gcloud init && git config --global credential.https://source.developers.google.com.helper gcloud.cmd
git remote add google ssh://username@gmail.com@source.developers.google.com:2022/p/my-website-project/r/my_website

These 2 worked well.

Maybe someone could help me to find what to do to fix that.

Thank you.


问:
How to add same values to different keys in dictionaries?
I have 2 JSON files. 1 file with the the student numbers and 1 file with the students.

I have a list of dictionaries with the name, e-mail, and student number of students.

What I want to do is if there are 60 students I want to give them a unique student number. That part is working in the elif statement. The part which I dont know how to implement is:

If there are 20 students, I want to give for example 2 students the same studentnumber(which sounds stupid but I need it). In this case the student is the key and studentnumber is the value.

What I have now:

```<code>
# student
[{"Student1":029182,"e-mail":"example@.com"},{"Student2":0591238,"e-mail":"example@.com"},{"Student3":9213189,"e-mail":"example@.com"}]

studentnumbers = [{"studentnumber":"029182","ID":0},{"studentnumber":"0591238","ID":1},{"studentnumber":"9213189","ID":2}]

students = [list(data.values())[0] for data in studentnumbers]

ID = 0
# students is a list of studentnumbers
if len(students) <= 20:
    # studentInfo is my dictionary with the key and values
    for data in studentnumbers:
        try:
            pass

        except IndexError:
            pass

elif len(students) <= 60:
    for data in studentnumbers:
        try:
            studentnumbers[ID] = students[ID]
            ID += 1
            break
        except IndexError:
            pass
    print("..")
else:
    print("...")

with open('Students.json','w') as instudent:
    json.dump(studentnumbers,instudent,indent=2)

</code>```

output what I have now:

```<code>[{"Student1":029182,"e-mail":"example@.com","studentnumber":029182},
{"Student2":0591238,"e-mail":"example@.com","studentnumber":9213189},
{"Student3":9213189,"e-mail":"example@.com","studentnumber":0591238},
{"Student4":9213189,"e-mail":"example@.com","studentnumber":0294832},
{"Student5":9213189,"e-mail":"example@.com","studentnumber":0591823},
{"Student6":9213189,"e-mail":"example@.com","studentnumber":0501852}]
</code>```

What I want:

```<code>[{"Student1":029182,"e-mail":"example@.com","studentnumber":029182},
{"Student2":0591238,"e-mail":"example@.com","studentnumber":029182},
{"Student3":9213189,"e-mail":"example@.com","studentnumber":029182},
{"Student4":9213189,"e-mail":"example@.com","studentnumber":9213189},
{"Student5":9213189,"e-mail":"example@.com","studentnumber":9213189},
{"Student6":9213189,"e-mail":"example@.com","studentnumber":9213189}]
</code>```

答:
I personally don't like using dictionaries, I just think a class object is much more convenient, although maybe slower in large scale.

I'm not sure what your issue is, I'm not aware that there can't be two same valued things in a dictionary.

here is how I would do it

```<code>import random as r

class student():
    def __init__(self,ID,numb):
        self.number = ID
        self.email = 'example@mail.com'
        self.name = 'student{}'.format(numb)

students = []
for i in range(60):
    x = student(r.randint(10000,99999),i)
    students.append(x)
def test():
    ID = 0
    for i in list(students):
        print(i.name,i.number,i.email)

test()
</code>```

if you want to set the student number just change the r.randint bit

hope it helps if you have to use a dictionary
or if you have any problem please ask :)

Body:
I have 2 JSON files. 1 file with the the student numbers and 1 file with the students.

I have a list of dictionaries with the name, e-mail, and student number of students.

What I want to do is if there are 60 students I want to give them a unique student number. That part is working in the elif statement. The part which I dont know how to implement is:

If there are 20 students, I want to give for example 2 students the same studentnumber(which sounds stupid but I need it). In this case the student is the key and studentnumber is the value.

What I have now:

# student
[{"Student1":029182,"e-mail":"example@.com"},{"Student2":0591238,"e-mail":"example@.com"},{"Student3":9213189,"e-mail":"example@.com"}]

studentnumbers = [{"studentnumber":"029182","ID":0},{"studentnumber":"0591238","ID":1},{"studentnumber":"9213189","ID":2}]

students = [list(data.values())[0] for data in studentnumbers]

ID = 0
# students is a list of studentnumbers
if len(students) <= 20:
    # studentInfo is my dictionary with the key and values
    for data in studentnumbers:
        try:
            pass

        except IndexError:
            pass

elif len(students) <= 60:
    for data in studentnumbers:
        try:
            studentnumbers[ID] = students[ID]
            ID += 1
            break
        except IndexError:
            pass
    print("..")
else:
    print("...")

with open('Students.json','w') as instudent:
    json.dump(studentnumbers,instudent,indent=2)

output what I have now:

[{"Student1":029182,"e-mail":"example@.com","studentnumber":029182},
{"Student2":0591238,"e-mail":"example@.com","studentnumber":9213189},
{"Student3":9213189,"e-mail":"example@.com","studentnumber":0591238},
{"Student4":9213189,"e-mail":"example@.com","studentnumber":0294832},
{"Student5":9213189,"e-mail":"example@.com","studentnumber":0591823},
{"Student6":9213189,"e-mail":"example@.com","studentnumber":0501852}]

What I want:

[{"Student1":029182,"e-mail":"example@.com","studentnumber":029182},
{"Student2":0591238,"e-mail":"example@.com","studentnumber":029182},
{"Student3":9213189,"e-mail":"example@.com","studentnumber":029182},
{"Student4":9213189,"e-mail":"example@.com","studentnumber":9213189},
{"Student5":9213189,"e-mail":"example@.com","studentnumber":9213189},
{"Student6":9213189,"e-mail":"example@.com","studentnumber":9213189}]

Body:
I personally don't like using dictionaries, I just think a class object is much more convenient, although maybe slower in large scale.

I'm not sure what your issue is, I'm not aware that there can't be two same valued things in a dictionary.

here is how I would do it

import random as r

class student():
    def __init__(self,ID,numb):
        self.number = ID
        self.email = 'example@mail.com'
        self.name = 'student{}'.format(numb)

students = []
for i in range(60):
    x = student(r.randint(10000,99999),i)
    students.append(x)
def test():
    ID = 0
    for i in list(students):
        print(i.name,i.number,i.email)

test()

if you want to set the student number just change the r.randint bit

hope it helps if you have to use a dictionary
or if you have any problem please ask :)


答:
Laravel Collection have an ->only() method and ->map() which can be used like this:

```<code>$colors = Phone::find($phone_Id)->color()->only(['id', 'name'])toArray();

$colors->map(function($color) {
    $color->text = $color->name;
    unset($color->text);
})
</code>```

https://laravel.com/docs/5.8/collections#method-only

https://laravel.com/docs/5.8/collections#method-map

Title: How to elegantly customize the collection key name in laravel

Body:
Laravel Collection have an ->only() method and ->map() which can be used like this:

$colors = Phone::find($phone_Id)->color()->only(['id', 'name'])toArray();

$colors->map(function($color) {
    $color->text = $color->name;
    unset($color->text);
})

https://laravel.com/docs/5.8/collections#method-only

https://laravel.com/docs/5.8/collections#method-map


问:
mysql_affected_rows() returns 1 on a 'real' REPLACE INTO
I have a MySQL table with one primary key.

Nightly I run a job to insert and update records. I use REPLACE INTO for each operation so it'll either add or replace the existing row.

After the REPLACE INTO query I call mysql_affected_rows() which is returning a count of 1 for many rows which are actually replaced and not 'new' (it returns 2 for the vast majority of rows which are replaced).

I know that some of these 'inserts' are false because I track the count of rows at the start and end of the batch update; the table has no duplicates to throw off that count, plus I've verified the faux 'new' rows existed before the batch update.

This table has nothing special about it; a similar table works as behaved with the same code. Anyone have any ideas why mysql_affected_rows() is returning 1 for an operation which is really a replace and not an insert?

答:
REPLACE INTO actually does a DELETE and then INSERT, not an UPDATE.

You might want to consider using  INSERT … ON DUPLICATE KEY UPDATE   syntax instead.


问:
What is the time complexity of the following method?
I'm trying to understand how to check time complexity but I cannot solve this example:

Image :

Could someone help me solve it and explain how to do it step by step?

答:
The algorithm loops until m reaches 0.  In each iteration m is either halved (if it was even) or reduced by 1 (if it was odd).  If the algorithm would just halve m in each iteration, then this would take log(m) steps (in the context of complexity, log() is typically meant to be of base 2).  In our case, however, we might have at most double the amount of iterations, namely if after each halving of an even number we get an odd number.  These odd numbers are reduced by 1 which results in creating the next even number.

Doubling the amount of steps is a constant factor which isn't taken into account when calculating complexities in the Big-O notation, so the complexity stays at O(log(n)).


问:
Extract attribute 'value' from BeautifulSoup xml
I am trying to extract search keywords from SOAP xml schema with BeautifulSoup and cannot figure out how to extract value attributes.

I have tried using soap.find_all but it will not let me extract the value attribute.

Here is what I have so far:

```<code>soap = requests.get('http://ecp.iedadata.org/soap_search_schema.xsd')
soapXML = soap.content.decode("utf-8")
soapSoup = BeautifulSoup(soapXML, "xml")
level1 = soapSoup.findAll('xs:attribute', {'name':'level1'})[0]
level1['value']
</code>```

And this is where I have an issue. According to BeautifulSoup documentation this should output all the 'value' attributes.

```<code>print(level1):

<xs:attribute name="level1" use="optional">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value=""/>
<xs:enumeration value="alteration"/>
<xs:enumeration value="igneous"/>
<xs:enumeration value="metamorphic"/>
<xs:enumeration value="notfound"/>
<xs:enumeration value="ore"/>
<xs:enumeration value="sedimentary"/>
<xs:enumeration value="vein"/>
<xs:enumeration value="xenolith"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
</code>```

So as you can see, I am trying to get the text from the value attribute in all of the xs:enumeration tags. The end result would be a list of search terms for level1. i.e.:

(alteration, igneous, metamorphic, notfound, ore, sedimentary, vein, xenolith)

I cannot just call on the xs:enumeration tag as there are multiple keywords (i.e. level2, level3, SampleType... etc.) and each have different xs:enumeration values.

Here is the error on the last line (level1['value'])

KeyError                                  Traceback (most recent call last)
   in
  ----> 1 level1test['value']

~/anaconda3/envs/py37/lib/python3.7/site-packages/bs4/element.py in getitem(self, key)
     1069         """tag[key] returns the value of the 'key' attribute for the tag,
     1070         and throws an exception if it's not there."""
  -> 1071         return self.attrs[key]
     1072
     1073     def iter(self):

KeyError: 'value'

答:
Just replace level1['value'] with:

```<code>for i in level1:
    if type(i) is not bs4.element.NavigableString:
        data = i.contents
        for k in data[1]:
            if type(k) is not bs4.element.NavigableString:
                print(k['value'])
</code>```

Output:

```<code>alteration
igneous
metamorphic
notfound
ore
sedimentary
vein
xenolith
</code>```

Body:
I am trying to extract search keywords from SOAP xml schema with BeautifulSoup and cannot figure out how to extract value attributes.

I have tried using soap.find_all but it will not let me extract the value attribute.

Here is what I have so far:

soap = requests.get('http://ecp.iedadata.org/soap_search_schema.xsd')
soapXML = soap.content.decode("utf-8")
soapSoup = BeautifulSoup(soapXML, "xml")
level1 = soapSoup.findAll('xs:attribute', {'name':'level1'})[0]
level1['value']

And this is where I have an issue. According to BeautifulSoup documentation this should output all the 'value' attributes.

print(level1):

<xs:attribute name="level1" use="optional">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value=""/>
<xs:enumeration value="alteration"/>
<xs:enumeration value="igneous"/>
<xs:enumeration value="metamorphic"/>
<xs:enumeration value="notfound"/>
<xs:enumeration value="ore"/>
<xs:enumeration value="sedimentary"/>
<xs:enumeration value="vein"/>
<xs:enumeration value="xenolith"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>

So as you can see, I am trying to get the text from the value attribute in all of the xs:enumeration tags. The end result would be a list of search terms for level1. i.e.:

(alteration, igneous, metamorphic, notfound, ore, sedimentary, vein, xenolith)

I cannot just call on the xs:enumeration tag as there are multiple keywords (i.e. level2, level3, SampleType... etc.) and each have different xs:enumeration values.

Here is the error on the last line (level1['value'])

KeyError                                  Traceback (most recent call last)
   in
  ----> 1 level1test['value']

~/anaconda3/envs/py37/lib/python3.7/site-packages/bs4/element.py in getitem(self, key)
     1069         """tag[key] returns the value of the 'key' attribute for the tag,
     1070         and throws an exception if it's not there."""
  -> 1071         return self.attrs[key]
     1072
     1073     def iter(self):

KeyError: 'value'

Body:
Just replace level1['value'] with:

for i in level1:
    if type(i) is not bs4.element.NavigableString:
        data = i.contents
        for k in data[1]:
            if type(k) is not bs4.element.NavigableString:
                print(k['value'])

Output:

alteration
igneous
metamorphic
notfound
ore
sedimentary
vein
xenolith


问:
Can you set a Route53 Resource Record as the IP of an EC2 instance in the same cloudformation script?
I have a cloudformation script that makes an EC2 instance and sets up some alarms. I would like to add a Route53 record for this instance in the same cloudformation, but I am having trouble figuring out what to put for the Resource Record field. Is there a way to reference the newly created EC2 instance's IP address for the ResourceRecord field of the AWS::Route53::RecordSetGroup?

I have already tried to use "ResourceRecords":"EC2Instance" but that got me "Encountered unsupported property Type." I don't know how else to accomplish this outside of manually setting the DNS entry after creation, but I would like to do it in one step so it is done automatically.

Here is what I have:

```<code>"Resources": {
    "EC2Instance": {
      "Type": "AWS::EC2::Instance",
      "Properties": {"ImageId": {
          "Ref": "AMI"
        },
        "IamInstanceProfile": {
          "Ref": "InstanceProfile"
        },
        "InstanceType": {
          "Ref": "InstanceSize"
        },
        "BlockDeviceMappings": [{
            "DeviceName": "/dev/xvda",
            "Ebs": {
              "Encrypted": true,
              "VolumeSize": 100,
              "DeleteOnTermination": false
            }
          }]
      }
    },
    "DNS": {
      "Type": "AWS::Route53::RecordSetGroup",
      "Properties": {
        "HostedZoneName": {"Ref": "HostedZoneName"},
        "Comment": "Alias Record",
        "ResourceRecords":"EC2Instance",
        "Type": "A",
        "Name": {"Fn::Join" : ["",[{"Ref": "ComponentDNSName"},{"Ref": "HostedZoneName"}]]}
      }
    }
  },
</code>```

I would expect there would be someway to find the newly created IP for the EC2 instance, but I am not sure how. I am thinking I have to use an elastic IP, but I still do not know how to reference that. Thanks for any help or suggestions.

答:
From AWS::EC2::Instance - AWS CloudFormation:

Fn::GetAtt

The Fn::GetAtt intrinsic function returns a value for a specified attribute of this type. The following are the available attributes and sample return values.

PrivateIp

The private IP address of the specified instance. For example: 10.24.34.0.

So, it would be something like:

```<code>{ "Fn::GetAtt" : [ "EC2Instance", "PrivateIp" ] }
</code>```

Body:
I have a cloudformation script that makes an EC2 instance and sets up some alarms. I would like to add a Route53 record for this instance in the same cloudformation, but I am having trouble figuring out what to put for the Resource Record field. Is there a way to reference the newly created EC2 instance's IP address for the ResourceRecord field of the AWS::Route53::RecordSetGroup?

I have already tried to use "ResourceRecords":"EC2Instance" but that got me "Encountered unsupported property Type." I don't know how else to accomplish this outside of manually setting the DNS entry after creation, but I would like to do it in one step so it is done automatically.

Here is what I have:

"Resources": {
    "EC2Instance": {
      "Type": "AWS::EC2::Instance",
      "Properties": {"ImageId": {
          "Ref": "AMI"
        },
        "IamInstanceProfile": {
          "Ref": "InstanceProfile"
        },
        "InstanceType": {
          "Ref": "InstanceSize"
        },
        "BlockDeviceMappings": [{
            "DeviceName": "/dev/xvda",
            "Ebs": {
              "Encrypted": true,
              "VolumeSize": 100,
              "DeleteOnTermination": false
            }
          }]
      }
    },
    "DNS": {
      "Type": "AWS::Route53::RecordSetGroup",
      "Properties": {
        "HostedZoneName": {"Ref": "HostedZoneName"},
        "Comment": "Alias Record",
        "ResourceRecords":"EC2Instance",
        "Type": "A",
        "Name": {"Fn::Join" : ["",[{"Ref": "ComponentDNSName"},{"Ref": "HostedZoneName"}]]}
      }
    }
  },

I would expect there would be someway to find the newly created IP for the EC2 instance, but I am not sure how. I am thinking I have to use an elastic IP, but I still do not know how to reference that. Thanks for any help or suggestions.

Body:
From AWS::EC2::Instance - AWS CloudFormation:

Fn::GetAtt

The Fn::GetAtt intrinsic function returns a value for a specified attribute of this type. The following are the available attributes and sample return values.

PrivateIp

The private IP address of the specified instance. For example: 10.24.34.0.

So, it would be something like:

{ "Fn::GetAtt" : [ "EC2Instance", "PrivateIp" ] }


问:
Is toString() only useful for debugging?
Besides of course, their use with primitives. Most (if not all) of the implementations I see are only useful from a programmer viewpoint.

EDIT: I understand that I'm supposed to override the default behavior, that's why I mentioned implementations :). And I do get the value of overriding it in some components requiring a String representation inside a GUI. However, in the JDK at least, I see lots of implementations that only come to use whenever you need to debug the object instances.

Why is it rooted at the Object class, since that is only seems useful for GUI/debugging stuff? are there other uses I'm not aware of?

答:
toString() is useful whenever you want a string representation of an object. Naturally that happens for debugging purposes, but can also be valid to output results of operations to the user.

For example, let's say you have a Complex class which handles complex numbers. If you want to print them out to an user in a format like 3 + 2i, it is handy if they define toString() as you do not have to write the format every time and the output will be consistent. If you ever want to change that representation, for example to 3 + 2j, you only need to touch the toString() method in the Complex class.

So toString() is not for debugging purposes also, but is a good way to get consistent string representations of your objects.

OwnerDisplayName: Camilo Díaz

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Camilo Díaz

OwnerDisplayName: Raim


问:
How to extract text following a keyword in UNIX
I have a text file (file.txt) that contains a wall of results (no newlines, whitespaces etc) that I received from an external source.  From this file, I need to find all mentions of the word serId, and then print out the alpha-numeric sequence following it.  The alpha-numeric sequence is of any length but will end with the character ,.  How can I extract these alpha-numeric sequences?

I've tried finding scripts/code using sed / awk but the results seem to revolve around a known sequence to find, rather than an unknown sequence.

For example, I would like to extract 28655784-EE from the following sample text:

```<code>{"preRollbackCheckResults":[],"patchingHistory":[{"backupStatus":"Available","rollbackStatus":"Available","additionalNote":"Patching CDS as planned","appliedBy":"xxrbsgCDS02services","appliedDate":"2019-01-18T12:45:33.926+0000","totalTime":"29 min, 47 sec","serId":"28655784-EE","patchDescription":"DB 18.4.0.0.0 Oct 2018 PSU
</code>```

Body:
I have a text file (file.txt) that contains a wall of results (no newlines, whitespaces etc) that I received from an external source.  From this file, I need to find all mentions of the word serId, and then print out the alpha-numeric sequence following it.  The alpha-numeric sequence is of any length but will end with the character ,.  How can I extract these alpha-numeric sequences?

I've tried finding scripts/code using sed / awk but the results seem to revolve around a known sequence to find, rather than an unknown sequence.

For example, I would like to extract 28655784-EE from the following sample text:

{"preRollbackCheckResults":[],"patchingHistory":[{"backupStatus":"Available","rollbackStatus":"Available","additionalNote":"Patching CDS as planned","appliedBy":"xxrbsgCDS02services","appliedDate":"2019-01-18T12:45:33.926+0000","totalTime":"29 min, 47 sec","serId":"28655784-EE","patchDescription":"DB 18.4.0.0.0 Oct 2018 PSU

Body:
With any sed:

$ sed 's/.*"serId":"\([^"]*\).*/\1/' file
28655784-EE