问:
one bug in my code, I used Classes in python and define some functions inside but the values that passed to functions are not accurate
I am beginner on python and OOP. This is my first class code.
I wrote below python code and it will run, The Code is about 3 string that user enter them and the code check if these strings are valid or invalid(string are valid if string's length are between 1 to 50) But there is an issue on my code. I got always default values when I run my code. I think there is a problem on set_string functions. But I am not sure.
I would be appreciate for any help

Code:

```<code>class TripleString:
  string1=""
  string2=""
  string3=""
  Max_Len=50
  Min_Len=1
  def __init__(self,string1="Undefined1",string2="Undefined2",string3="Undefined3"):
    if(TripleString.get_string1_from_user()):
      self.string1=string1
    if(TripleString.get_string2_from_user()):
      self.string2=string2
    if(TripleString.get_string3_from_user()):
      self.string3=string3

  def valid_string(str):
    if(len(str)<TripleString.Min_Len or len(str)>TripleString.Max_Len):
      return False
    else:
      return True

  def set_string1(str1):
    if(TripleString.valid_string(str1)):
      TripleString.string1=str1
      print("String set")
      return True
    else:
      print("string not set since the len is not valid")
      return False

  def get_string1_from_user():
    str=input("STR1:")
    if(TripleString.set_string1(str)):
      return True
    else:
      return False

  def set_string2(str2):
    if(TripleString.valid_string(str2)):
      TripleString.string2=str2
      print("String set")
      return True
    else:
      print("string not set since the len is not valid")
      return False

  def get_string2_from_user():
    str=input("STR2:")
    if(TripleString.set_string2(str)):
      return True
    else:
      return False

  def set_string3(str3):
    if(TripleString.valid_string(str3)):
      TripleString.string3=str3
      print("String set")
      return True
    else:
      print("string not set since the len is not valid")
      return False

  def get_string3_from_user():
    str=input("STR3:")
    if(TripleString.set_string3(str)):
      return True
    else:
      return False

x=TripleString()

print(x.string1,x.string2,x.string3)
</code>```

Output1:

```<code>STR1: String1
String set
STR2: String2
String set
STR3: String3
String set
Undefined1 Undefined2 Undefined3
</code>```

output2:

```<code>STR1: strin1stringstringstringstringstringstringstringstringstringstringstringstringstringstring
string not set since the len is not valid
STR2: string2
String set
STR3: string3
String set
 Undefined2 Undefined3
</code>```

But I expect the output for

```<code>                        1st one : string1 string2 string3

                        2nd one: undefined1  string2 string3
</code>```

Appreciated!

Updated code for set_string1:

```<code>  def set_string1(self,str1):
    if(TripleString.valid_string(str1)):
      self.string1=str1
      print("String set")
      return True
    else:
      print("string not set since the len is not valid")
      return False

  def get_string1_from_user():
    str=input("STR1:")
    if(TripleString.set_string1(str)):
      return True
    else:
      return False
</code>```

output:

```<code>> STR1: kiarash Traceback (most recent call last):   File "python", line
> 71, in <module>   File "python", line 8, in __init__   File "python",
> line 32, in get_string1_from_user TypeError: set_string1() missing 1
> required positional argument: 'str1'
</code>```

答:
You assigned strings to the undefined on init every time . You need to use self on all defs. I updated your code here.
I hope it will work for you.

```<code>class TripleString:
  Max_Len=50
  Min_Len=1
  def __init__(self,string1="Undefined1",string2="Undefined2",string3="Undefined3"):
    if(TripleString.get_string1_from_user(self)):
      print("in init, string1=", string1)
    else:
      self.string1=string1
    if(TripleString.get_string2_from_user(self)):
      print("in init, string2=", string2)
    else:
      self.string2=string2
    if(TripleString.get_string3_from_user(self)):
      print("in init, string3=", string3)
    else:
      self.string3=string3

  def valid_string(self,str):
    if(len(str)<TripleString.Min_Len or len(str)>TripleString.Max_Len):
      return False
    else:
      return True

  def set_string1(self,str1):
    if(self.valid_string(str1)):
      self.string1=str1
      print("String set to",str1)
      return True
    else:
      print("string not set since the len is not valid")
      return False
  def set_string2(self,str2):
    if(self.valid_string(str2)):
      self.string2=str2
      print("String set to",str2)
      return True
    else:
      print("string not set since the len is not valid")
      return False
  def set_string3(self,str3):
    if(self.valid_string(str3)):
      self.string3=str3
      print("String set to",str3)
      return True
    else:
      print("string not set since the len is not valid")
      return False
  def get_string1_from_user(self):
    str=input("STR1:")
    print("in get_str1 from user, str=", str)
    if(self.set_string1(str)):
      return True
    else:
      return False
  def get_string2_from_user(self):
    str=input("STR2:")
    print("in get_str2 from user, str=", str)
    if(self.set_string2(str)):
      return True
    else:
      return False
  def get_string3_from_user(self):
    str=input("STR3:")
    print("in get_str3 from user, str=", str)
    if(self.set_string3(str)):
      return True
    else:
      return False

x=TripleString()
print(x.string1,x.string2,x.string3)
</code>```

Output1:

```<code>STR1: Sample1
in get_str1 from user, str= Sample1
String set to Sample1
in init, string1= Undefined1
STR2: Sample2
in get_str2 from user, str= Sample2
String set to Sample2
in init, string2= Undefined2
STR3: Sample3
in get_str3 from user, str= Sample3
String set to Sample3
in init, string3= Undefined3
Sample1 Sample2 Sample3
</code>```

output2:

```<code>STR1: Sample1
in get_str1 from user, str= Sample1
String set to Sample1
in init, string1= Undefined1
STR2: uduahydaugdadhjksahdjkahsjkdhasjdhjksahdjkashdjksahdjkashjkdsahkjdhjksahdjksad
in get_str2 from user, str= uduahydaugdadhjksahdjkahsjkdhasjdhjksahdjkashdjksahdjkashjkdsahkjdhjksahdjksad
string not set since the len is not valid
STR3: sample3
in get_str3 from user, str= sample3
String set to sample3
in init, string3= Undefined3
Sample1 Undefined2 sample3
</code>```

Body:
I am beginner on python and OOP. This is my first class code.
I wrote below python code and it will run, The Code is about 3 string that user enter them and the code check if these strings are valid or invalid(string are valid if string's length are between 1 to 50) But there is an issue on my code. I got always default values when I run my code. I think there is a problem on set_string functions. But I am not sure.
I would be appreciate for any help

Code:

class TripleString:
  string1=""
  string2=""
  string3=""
  Max_Len=50
  Min_Len=1
  def __init__(self,string1="Undefined1",string2="Undefined2",string3="Undefined3"):
    if(TripleString.get_string1_from_user()):
      self.string1=string1
    if(TripleString.get_string2_from_user()):
      self.string2=string2
    if(TripleString.get_string3_from_user()):
      self.string3=string3

  def valid_string(str):
    if(len(str)<TripleString.Min_Len or len(str)>TripleString.Max_Len):
      return False
    else:
      return True

  def set_string1(str1):
    if(TripleString.valid_string(str1)):
      TripleString.string1=str1
      print("String set")
      return True
    else:
      print("string not set since the len is not valid")
      return False

  def get_string1_from_user():
    str=input("STR1:")
    if(TripleString.set_string1(str)):
      return True
    else:
      return False

  def set_string2(str2):
    if(TripleString.valid_string(str2)):
      TripleString.string2=str2
      print("String set")
      return True
    else:
      print("string not set since the len is not valid")
      return False

  def get_string2_from_user():
    str=input("STR2:")
    if(TripleString.set_string2(str)):
      return True
    else:
      return False

  def set_string3(str3):
    if(TripleString.valid_string(str3)):
      TripleString.string3=str3
      print("String set")
      return True
    else:
      print("string not set since the len is not valid")
      return False

  def get_string3_from_user():
    str=input("STR3:")
    if(TripleString.set_string3(str)):
      return True
    else:
      return False

x=TripleString()

print(x.string1,x.string2,x.string3)

Output1:

STR1: String1
String set
STR2: String2
String set
STR3: String3
String set
Undefined1 Undefined2 Undefined3

output2:

STR1: strin1stringstringstringstringstringstringstringstringstringstringstringstringstringstring
string not set since the len is not valid
STR2: string2
String set
STR3: string3
String set
 Undefined2 Undefined3

But I expect the output for

                        1st one : string1 string2 string3

                        2nd one: undefined1  string2 string3

Appreciated!

Updated code for set_string1:

  def set_string1(self,str1):
    if(TripleString.valid_string(str1)):
      self.string1=str1
      print("String set")
      return True
    else:
      print("string not set since the len is not valid")
      return False

  def get_string1_from_user():
    str=input("STR1:")
    if(TripleString.set_string1(str)):
      return True
    else:
      return False

output:

> STR1: kiarash Traceback (most recent call last):   File "python", line
> 71, in <module>   File "python", line 8, in __init__   File "python",
> line 32, in get_string1_from_user TypeError: set_string1() missing 1
> required positional argument: 'str1'

Body:
You assigned strings to the undefined on init every time . You need to use self on all defs. I updated your code here.
I hope it will work for you.

class TripleString:
  Max_Len=50
  Min_Len=1
  def __init__(self,string1="Undefined1",string2="Undefined2",string3="Undefined3"):
    if(TripleString.get_string1_from_user(self)):
      print("in init, string1=", string1)
    else:
      self.string1=string1
    if(TripleString.get_string2_from_user(self)):
      print("in init, string2=", string2)
    else:
      self.string2=string2
    if(TripleString.get_string3_from_user(self)):
      print("in init, string3=", string3)
    else:
      self.string3=string3

  def valid_string(self,str):
    if(len(str)<TripleString.Min_Len or len(str)>TripleString.Max_Len):
      return False
    else:
      return True

  def set_string1(self,str1):
    if(self.valid_string(str1)):
      self.string1=str1
      print("String set to",str1)
      return True
    else:
      print("string not set since the len is not valid")
      return False
  def set_string2(self,str2):
    if(self.valid_string(str2)):
      self.string2=str2
      print("String set to",str2)
      return True
    else:
      print("string not set since the len is not valid")
      return False
  def set_string3(self,str3):
    if(self.valid_string(str3)):
      self.string3=str3
      print("String set to",str3)
      return True
    else:
      print("string not set since the len is not valid")
      return False
  def get_string1_from_user(self):
    str=input("STR1:")
    print("in get_str1 from user, str=", str)
    if(self.set_string1(str)):
      return True
    else:
      return False
  def get_string2_from_user(self):
    str=input("STR2:")
    print("in get_str2 from user, str=", str)
    if(self.set_string2(str)):
      return True
    else:
      return False
  def get_string3_from_user(self):
    str=input("STR3:")
    print("in get_str3 from user, str=", str)
    if(self.set_string3(str)):
      return True
    else:
      return False

x=TripleString()
print(x.string1,x.string2,x.string3)

Output1:

STR1: Sample1
in get_str1 from user, str= Sample1
String set to Sample1
in init, string1= Undefined1
STR2: Sample2
in get_str2 from user, str= Sample2
String set to Sample2
in init, string2= Undefined2
STR3: Sample3
in get_str3 from user, str= Sample3
String set to Sample3
in init, string3= Undefined3
Sample1 Sample2 Sample3

output2:

STR1: Sample1
in get_str1 from user, str= Sample1
String set to Sample1
in init, string1= Undefined1
STR2: uduahydaugdadhjksahdjkahsjkdhasjdhjksahdjkashdjksahdjkashjkdsahkjdhjksahdjksad
in get_str2 from user, str= uduahydaugdadhjksahdjkahsjkdhasjdhjksahdjkashdjksahdjkashjkdsahkjdhjksahdjksad
string not set since the len is not valid
STR3: sample3
in get_str3 from user, str= sample3
String set to sample3
in init, string3= Undefined3
Sample1 Undefined2 sample3


来源: stackexchange

问:
Pull ssh-client container via docker-compose
I'm new to Docker and may not understand something.

I have an app container and a dockerfile.

I want to install an ssh-client into the app container.
I want to be able to run ssh command to reach some external ip from the app container.

The simplest way I know is to add

RUN apk update && apk add openssh-client bash

to my dockerfile, but I'd like to use some ready image, so all my containers could use the same one.

Is it possible to do so?

答:
Write a Dockerfile (https://docs.docker.com/engine/reference/builder/):

```<code>FROM alpine:latest
# install ssh-client and bash
RUN apk --no-cache add openssh-client bash
# example ssh usage to print version
ENTRYPOINT ["ssh", "-V"]
</code>```

Build and run it with: docker build -t ssh . && docker run -t ssh ssh
Or use Docker-Compose.

After building with docker build you can reuse the ssh Docker image in your other projects in Dockerfiles.

```<code>FROM ssh
...
</code>```

Using Docker-Compose docker-compose.yml:

```<code>version: '3'
services:
  ssh:
    build: .
    image: ssh
</code>```

You can add multiple services in the compose file as you like.
The docker compose file from above uses the Dockerfile from above to build your ssh docker image.
See the compose file reference: https://docs.docker.com/compose/compose-file/

ContentLicense: CC BY-SA 4.0

Body:
Write a Dockerfile (https://docs.docker.com/engine/reference/builder/):

FROM alpine:latest
# install ssh-client and bash
RUN apk --no-cache add openssh-client bash
# example ssh usage to print version
ENTRYPOINT ["ssh", "-V"]

Build and run it with: docker build -t ssh . && docker run -t ssh ssh
Or use Docker-Compose.

After building with docker build you can reuse the ssh Docker image in your other projects in Dockerfiles.

FROM ssh
...

Using Docker-Compose docker-compose.yml:

version: '3'
services:
  ssh:
    build: .
    image: ssh

You can add multiple services in the compose file as you like.
The docker compose file from above uses the Dockerfile from above to build your ssh docker image.
See the compose file reference: https://docs.docker.com/compose/compose-file/

ContentLicense: CC BY-SA 3.0


问:
Multi Bit Logic Gate
I'm having trouble with this bit of code. I know that the problem is with the 7-bit output of my NAND and AND gate, but I don't know how to simplify it without making a separate gate for each bit. I'm also not sure what the anode_1_7 is for, or the buf statements. I was just told to include them.</p>

```<code>module seven_segment_top(sw, btnc, btnl, btnr, segment, anode, anode_1_7);
    input [3:0] sw;
    input btnc, btnl, btnr, anode_1_7;
    output [7:0] segment, anode;
    wire lnot;

    seven_segment S0(sw[3:0], segment[6:0]);
    not(segment[7], btnc);

    nor(anode[0], btnl, btnr);
    nand(anode[7:1], btnl, 1'b1);
    not(lnot, btnl);
    and(anode[7:1], btnr, lnot);

    buf(anode[1],anode_1_7);
    buf(anode[2],anode_1_7);
    buf(anode[3],anode_1_7);
    buf(anode[4],anode_1_7);
    buf(anode[5],anode_1_7);
    buf(anode[6],anode_1_7);
    buf(anode[7],anode_1_7);
endmodule
</code>```

答:
Two options:

Arrayed module instances. Not commonly used but is part if IEEE1364-1995. This approach works for simple iterations.

```<code>nand nd[7:1] (anode[7:1], btnl, 1'b1);
</code>```

Generate loop. Added in IEEE1364-2001 and commonly used. This approach is far more flexible and can be used for fancier compile/elaboration code expansion/slection.

```<code>genvar gidx;
generate
  for (gidx=1; gidx<8; gidx=gidx+1) begin : assign_anode
    nand(anode[gidx], btnl, 1'b1);
  end
endgenerate
</code>```

Title: Multi Bit Logic Gate

Body:
I'm having trouble with this bit of code. I know that the problem is with the 7-bit output of my NAND and AND gate, but I don't know how to simplify it without making a separate gate for each bit. I'm also not sure what the anode_1_7 is for, or the buf statements. I was just told to include them.

module seven_segment_top(sw, btnc, btnl, btnr, segment, anode, anode_1_7);
    input [3:0] sw;
    input btnc, btnl, btnr, anode_1_7;
    output [7:0] segment, anode;
    wire lnot;

    seven_segment S0(sw[3:0], segment[6:0]);
    not(segment[7], btnc);

    nor(anode[0], btnl, btnr);
    nand(anode[7:1], btnl, 1'b1);
    not(lnot, btnl);
    and(anode[7:1], btnr, lnot);

    buf(anode[1],anode_1_7);
    buf(anode[2],anode_1_7);
    buf(anode[3],anode_1_7);
    buf(anode[4],anode_1_7);
    buf(anode[5],anode_1_7);
    buf(anode[6],anode_1_7);
    buf(anode[7],anode_1_7);
endmodule

Body:
Two options:

Arrayed module instances. Not commonly used but is part if IEEE1364-1995. This approach works for simple iterations.

nand nd[7:1] (anode[7:1], btnl, 1'b1);

Generate loop. Added in IEEE1364-2001 and commonly used. This approach is far more flexible and can be used for fancier compile/elaboration code expansion/slection.

genvar gidx;
generate
  for (gidx=1; gidx<8; gidx=gidx+1) begin : assign_anode
    nand(anode[gidx], btnl, 1'b1);
  end
endgenerate


问:
dask performance apply along axis
I am trying to compute the linear trend over time on a large high resolution ocean model dataset using dask.

I have followed this example (Applying a function along an axis of a dask array) and found the syntax of apply_along_axis easier.

I am currently using dask.array.apply_along_axis to wrap a numpy function on 1 dimensional arrays and then package the resulting dask array into an xarray Dataarray. Using top -u <username> suggest that the computation is not executed in parallel (~100% cpu use).

Should I expect a better performance from map_blocks? Or are there any suggestions on how to improve the performance of apply_along_axis?
Any tips are highly appreciated.

```<code>import numpy as np
from scipy import optimize
import xarray as xr
import dask.array as dsa

def _lin_trend(y):
    x = np.arange(len(y))
    return np.polyfit(x, y, 1)

def linear_trend(da, dim, name='parameter'):
    da = da.copy()
    axis_num = da.get_axis_num(dim)

    dims = list(da.dims)
    dims[axis_num] = name
    coords = da.rename({dim:name}).coords
    coords[name] = ['slope', 'intercept']

    dsk = da.data
    dsk_trend = dsa.apply_along_axis(_lin_trend,0,dsk)
    out = xr.DataArray(dsk_trend, dims=dims, coords=coords)
    return out
</code>```

答:
I have been doing something similar using xarray's apply_ufunc (requires xarray v0.10 or later). This is likely to be a bit easier to manage than using the apply_along_axis function in dask.

```<code>import xarray as xr
import numpy as np
from scipy import stats

def _calc_slope(x, y):
    '''wrapper that returns the slop from a linear regression fit of x and y'''
    slope = stats.linregress(x, y)[0]  # extract slope only
    return slope

def linear_trend(obj):
    time_nums = xr.DataArray(obj['time'].values.astype(np.float),
                             dims='time',
                             coords={'time': obj['time']},
                             name='time_nums')
    trend = xr.apply_ufunc(_calc_slope, time_nums, obj,
                           vectorize=True,
                           input_core_dims=[['time'], ['time']],
                           output_core_dims=[[]],
                           output_dtypes=[np.float],
                           dask='parallelized')

    return trend
</code>```

Addressing your question about why the performance isn't as expected. This could be from a number of reasons. How is your dask array chunked? Which dask scheduler are you using? I'll update the second part of my answer after I get a better idea what your configuration is?

Title: dask performance apply along axis

Body:
I am trying to compute the linear trend over time on a large high resolution ocean model dataset using dask.

I have followed this example (Applying a function along an axis of a dask array) and found the syntax of apply_along_axis easier.

I am currently using dask.array.apply_along_axis to wrap a numpy function on 1 dimensional arrays and then package the resulting dask array into an xarray Dataarray. Using top -u <username> suggest that the computation is not executed in parallel (~100% cpu use).

Should I expect a better performance from map_blocks? Or are there any suggestions on how to improve the performance of apply_along_axis?
Any tips are highly appreciated.

import numpy as np
from scipy import optimize
import xarray as xr
import dask.array as dsa

def _lin_trend(y):
    x = np.arange(len(y))
    return np.polyfit(x, y, 1)

def linear_trend(da, dim, name='parameter'):
    da = da.copy()
    axis_num = da.get_axis_num(dim)

    dims = list(da.dims)
    dims[axis_num] = name
    coords = da.rename({dim:name}).coords
    coords[name] = ['slope', 'intercept']

    dsk = da.data
    dsk_trend = dsa.apply_along_axis(_lin_trend,0,dsk)
    out = xr.DataArray(dsk_trend, dims=dims, coords=coords)
    return out

Body:
I have been doing something similar using xarray's apply_ufunc (requires xarray v0.10 or later). This is likely to be a bit easier to manage than using the apply_along_axis function in dask.

import xarray as xr
import numpy as np
from scipy import stats

def _calc_slope(x, y):
    '''wrapper that returns the slop from a linear regression fit of x and y'''
    slope = stats.linregress(x, y)[0]  # extract slope only
    return slope

def linear_trend(obj):
    time_nums = xr.DataArray(obj['time'].values.astype(np.float),
                             dims='time',
                             coords={'time': obj['time']},
                             name='time_nums')
    trend = xr.apply_ufunc(_calc_slope, time_nums, obj,
                           vectorize=True,
                           input_core_dims=[['time'], ['time']],
                           output_core_dims=[[]],
                           output_dtypes=[np.float],
                           dask='parallelized')

    return trend

Addressing your question about why the performance isn't as expected. This could be from a number of reasons. How is your dask array chunked? Which dask scheduler are you using? I'll update the second part of my answer after I get a better idea what your configuration is?


问:
Why is Firefox missing the border on some HTML tables
I am using Firefox 3.5.7 and I have the same CSS used in multiple HTML tables, but there are some examples where parts of the borders are not shown.

What makes no sense to me is that the same CSS on the same page for another HTML table works fine. Also, the same page in Internet Explorer looks fine from a border point of view.

Here is an image with an example, as you can see in this case the bottom of the first table is missing a border.

Does anyone have a clue why this would happen here?

答:
I found a similar problem when zoomed out in Firefox on an application I am working on.

The main cause was having the CSS border-collapse property set to collapse.

Changing it to separate instead fixed the problem. However, that meant I did have to rethink the way borders are applied to various parts of the table, because otherwise your borders will appear to double in thickness. I ended up having to use jQuery to give a special "last" class to the last td or th in each tr, and to the last tr in the table. My query was something like:

```<code>$('table tr > th:last-child, table > tbody > tr > td:last-child, table > tbody > tr:last-child').addClass('last');
</code>```

My CSS rules were similar that:

```<code>table
{
    border-collapse: separate !important;
}

table tr, table th, table td
{
    border-right-width: 0;
    border-bottom-width: 0;
    border-left: 1px solid black;
    border-top: 1px solid black;
}

table td.last, table th.last
{
    border-right: 1px solid black;
}

table tr.last td
{
    border-bottom: 1px solid black;
}

table
{
    border: 0;
}
</code>```

I did end up using browser targeting so that I only applied these rules to Firefox users, but it may work for all browsers, I haven't tested.

Body:
I found a similar problem when zoomed out in Firefox on an application I am working on.

The main cause was having the CSS border-collapse property set to collapse.

Changing it to separate instead fixed the problem. However, that meant I did have to rethink the way borders are applied to various parts of the table, because otherwise your borders will appear to double in thickness. I ended up having to use jQuery to give a special "last" class to the last td or th in each tr, and to the last tr in the table. My query was something like:

$('table tr > th:last-child, table > tbody > tr > td:last-child, table > tbody > tr:last-child').addClass('last');

My CSS rules were similar that:

table
{
    border-collapse: separate !important;
}

table tr, table th, table td
{
    border-right-width: 0;
    border-bottom-width: 0;
    border-left: 1px solid black;
    border-top: 1px solid black;
}

table td.last, table th.last
{
    border-right: 1px solid black;
}

table tr.last td
{
    border-bottom: 1px solid black;
}

table
{
    border: 0;
}

I did end up using browser targeting so that I only applied these rules to Firefox users, but it may work for all browsers, I haven't tested.

ContentLicense: CC BY-SA 2.5


问:
Graphviz - What is a valid style attribute?
The Graphviz attributes documentation describes the style attribute but does not say what values it may hold:

Set style information for components of the graph. For cluster
  subgraphs, if style="filled", the cluster box's background is filled.
  If the default style attribute has been set for a component, an
  individual component can use style="" to revert to the normal default.
  For example, if the graph has

```<code>edge [style="invis"]
</code>```

making all edges invisible, a specific edge can overrride this via:

```<code>a -> b [style=""]
</code>```

Of course, the component can also explicitly set its style attribute
  to the desired value.

What is a valid style attribute in Graphviz?

答:
If you look closely, the same documentation page also specifies a Type named style describing valid styles. Excerpt:

At present, the recognized style names are "dashed", "dotted",
  "solid", "invis" and "bold" for nodes and edges, "tapered" for edges
  only, and "filled", "striped", "wedged", "diagonals" and "rounded" for
  nodes only. The styles "filled", "striped" and "rounded" are
  recognized for clusters. The style "radial" is recognized for nodes,
  clusters and graphs, and indicates a radial-style gradient fill if
  applicable.

Body:
The Graphviz attributes documentation describes the style attribute but does not say what values it may hold:

Set style information for components of the graph. For cluster
  subgraphs, if style="filled", the cluster box's background is filled.
  If the default style attribute has been set for a component, an
  individual component can use style="" to revert to the normal default.
  For example, if the graph has

edge [style="invis"]

making all edges invisible, a specific edge can overrride this via:

a -> b [style=""]

Of course, the component can also explicitly set its style attribute
  to the desired value.

What is a valid style attribute in Graphviz?


问:
Host an Ionic app into AWS S3 Bucket - Not working/rendering
I have created a simple app using ionic2 framework and is working well in local machine/behind a simple 'lite-server'

I wanted to deploy the same in AWS S3 - With "enable static web-hosting" and try it from mobile browsers

I ran - ionic build browser

This created a static web-page contents in \MyApp\platforms\browser\www.

I used a node tool 's3-website' - https://www.npmjs.com/package/s3-website

to publish my App content to S3

All went well, I enabled static web-hosting, had permission for everyone to view, but its not rendering.

Edited
Should the app module name "MyApp" and s3 bucket name match? curious?

In Chrome Console, I get these errors

```<code>Failed to load resource: the server responded with a status of 404 (Not Found)
main.js Failed to load resource: the server responded with a status of 404 (Not Found)
/build/main.css Failed to load resource: the server responded with a status of 404 (Not Found)
device.js Failed to load resource: the server responded with a status of 404 (Not Found)
statusbar.js Failed to load resource: the server responded with a status of 404 (Not Found)
main.js Failed to load resource: the server responded with a status of 404 (Not Found)
StatusBarProxy.js Failed to load resource: the server responded with a status of 404 (Not Found)
SplashScreenProxy.js Failed to load resource: the server responded with a status of 404 (Not Found)
splashscreen.js Failed to load resource: the server responded with a status of 404 (Not Found)
DeviceProxy.js Failed to load resource: the server responded with a status of 404 (Not Found)
keyboard.js Failed to load resource: the server responded with a status of 404 (Not Found)
cordova.js:1297 Uncaught Error: Module cordova-plugin-device.device does not exist.
    at addEntry (cordova.js:1297)
    at Object.exports.clobbers (cordova.js:1307)
    at onScriptLoadingComplete (cordova.js:1551)
    at HTMLScriptElement.scriptLoadedCallback (cordova.js:1584)
addEntry @ cordova.js:1297
exports.clobbers @ cordova.js:1307
onScriptLoadingComplete @ cordova.js:1551
scriptLoadedCallback @ cordova.js:1584
cordova.js:1582 [Violation] 'error' handler took 177ms
main.css Failed to load resource: the server responded with a status of 404 (Not Found)
cordova.js:1051 deviceready has not fired after 5 seconds.
cordova.js:1044 Channel not fired: onPluginsReady
cordova.js:1044 Channel not fired: onCordovaReady
</code>```

答: Looks like either files are missing or the folder structure is incorrect. Did you test the site from your local machine?  Create a folder and download/copy the entire website content to the local folder.  Now launch index.html and see what happens. </p>

Body:
I have created a simple app using ionic2 framework and is working well in local machine/behind a simple 'lite-server'

I wanted to deploy the same in AWS S3 - With "enable static web-hosting" and try it from mobile browsers

I ran - ionic build browser

This created a static web-page contents in \MyApp\platforms\browser\www.

I used a node tool 's3-website' - https://www.npmjs.com/package/s3-website

to publish my App content to S3

All went well, I enabled static web-hosting, had permission for everyone to view, but its not rendering.

Edited
Should the app module name "MyApp" and s3 bucket name match? curious?

In Chrome Console, I get these errors

Failed to load resource: the server responded with a status of 404 (Not Found)
main.js Failed to load resource: the server responded with a status of 404 (Not Found)
/build/main.css Failed to load resource: the server responded with a status of 404 (Not Found)
device.js Failed to load resource: the server responded with a status of 404 (Not Found)
statusbar.js Failed to load resource: the server responded with a status of 404 (Not Found)
main.js Failed to load resource: the server responded with a status of 404 (Not Found)
StatusBarProxy.js Failed to load resource: the server responded with a status of 404 (Not Found)
SplashScreenProxy.js Failed to load resource: the server responded with a status of 404 (Not Found)
splashscreen.js Failed to load resource: the server responded with a status of 404 (Not Found)
DeviceProxy.js Failed to load resource: the server responded with a status of 404 (Not Found)
keyboard.js Failed to load resource: the server responded with a status of 404 (Not Found)
cordova.js:1297 Uncaught Error: Module cordova-plugin-device.device does not exist.
    at addEntry (cordova.js:1297)
    at Object.exports.clobbers (cordova.js:1307)
    at onScriptLoadingComplete (cordova.js:1551)
    at HTMLScriptElement.scriptLoadedCallback (cordova.js:1584)
addEntry @ cordova.js:1297
exports.clobbers @ cordova.js:1307
onScriptLoadingComplete @ cordova.js:1551
scriptLoadedCallback @ cordova.js:1584
cordova.js:1582 [Violation] 'error' handler took 177ms
main.css Failed to load resource: the server responded with a status of 404 (Not Found)
cordova.js:1051 deviceready has not fired after 5 seconds.
cordova.js:1044 Channel not fired: onPluginsReady
cordova.js:1044 Channel not fired: onCordovaReady


问:
ReactJS examples fail
I am using the following example from ReactJS tutorial:

```<code>const Button = function() {
   return {<button>Go</button>;
   };

};
ReactDOM.render(<Button/>, mountNode);
</code>```

I tried it both in a file and int Javascript REPL and getting the same error:

```<code>  SyntaxError: unknown: Unexpected token (4:9)
  2 |
  3 | const Button = function() {
> 4 |   return {<button>Go</button>;
    |           ^
  5 |   };
  6 |
  7 | };
</code>```

Cannot figure out what is wrong - it seems to work fine in the same setting in the tutorial video.

答:
You component is a function component and you don't wrap the returned Elements within {}. If you do it means you are returning an object

const Button = function() {
   return <button>Go</button>;

};
const mountNode= document.getElementById('app');
ReactDOM.render(<Button/>, mountNode);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react-dom.min.js"></script>
<div id="app"></div></code>```

Title: ReactJS examples fail

Body:
I am using the following example from ReactJS tutorial:

const Button = function() {
   return {<button>Go</button>;
   };

};
ReactDOM.render(<Button/>, mountNode);

I tried it both in a file and int Javascript REPL and getting the same error:

  SyntaxError: unknown: Unexpected token (4:9)
  2 |
  3 | const Button = function() {
> 4 |   return {<button>Go</button>;
    |           ^
  5 |   };
  6 |
  7 | };

Cannot figure out what is wrong - it seems to work fine in the same setting in the tutorial video.

Body:
You component is a function component and you don't wrap the returned Elements within {}. If you do it means you are returning an object

const Button = function() {
   return <button>Go</button>;

};
const mountNode= document.getElementById('app');
ReactDOM.render(<Button/>, mountNode);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react-dom.min.js"></script>
<div id="app"></div>


问:
Powershell - How to make sure a parameter is of a certain type (ArrayList)?
```<code>function Global:Some-Function {
    param(
        [Parameter(Mandatory=$true)]$InputArrayList
    )

    $debug = $true

    # Empty Validation
    if(($InputArrayList -eq $null) -or ($InputArrayList.Count -le 0)) {
        if($debug) { Write-Host '$InputArrayList is null or count -le 0' }
        return
    }

    # Verify the Input is an ArrayList
    if($InputArrayList.GetType().Name -ne 'ArrayList')
    {
        if($debug) { Write-Host '$InputArrayList is not of type "ArrayList"' -ForegroundColor Red }
        return
    }
  } # Function
</code>```

While this works, it seems like too much code just to check $InputArrayList is  of type ArrayList and not $null.

How can I specify this in the param() section?

答:
Maybe Just:</p>

```<code>function Global:Some-Function {
    param(
    [Parameter(Mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    $InputArrayList
    )

    return $InputArrayList -is [System.Collections.ArrayList]
  } # Function
</code>```

Body:
function Global:Some-Function {
    param(
        [Parameter(Mandatory=$true)]$InputArrayList
    )

    $debug = $true

    # Empty Validation
    if(($InputArrayList -eq $null) -or ($InputArrayList.Count -le 0)) {
        if($debug) { Write-Host '$InputArrayList is null or count -le 0' }
        return
    }

    # Verify the Input is an ArrayList
    if($InputArrayList.GetType().Name -ne 'ArrayList')
    {
        if($debug) { Write-Host '$InputArrayList is not of type "ArrayList"' -ForegroundColor Red }
        return
    }
  } # Function

While this works, it seems like too much code just to check $InputArrayList is  of type ArrayList and not $null.

How can I specify this in the param() section?

Body:
Maybe Just:

function Global:Some-Function {
    param(
    [Parameter(Mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    $InputArrayList
    )

    return $InputArrayList -is [System.Collections.ArrayList]
  } # Function


答: You should change brackets return {<button>Go</button>;}; to return(<button>Go</button>);

Title: ReactJS examples fail


问:
Google sheets wrap cell content in other content
Im looking to create a formula in one column that takes the content from the adjacent column and wraps it inside some other content, can anyone help with this?

For example, given:

```
           A     |     B
    1|           | someText1
    2|           | someText2
    3|           | someText3
    4|           | someText4

```

expected outcome content for Col A, after applying appropriate formula:

```
                A        |     B
    1| wrap("someText1") | someText1
    2| wrap("someText2") | someText2
    3| wrap("someText3") | someText3
    4| wrap("someText4") | someText4

```

I hope this makes sense, any help would be appreciated. Thanks

答:
By combining MewX suggestion with  arrayformula one can achieve the same for all column, with one formula:

```<code>=arrayformula("wrap(""" & B1:B4 & """)")
</code>```

Explanation: & is the string concatenation operator, quote marks within a string are escaped by doubling them.

Body:
Im looking to create a formula in one column that takes the content from the adjacent column and wraps it inside some other content, can anyone help with this?

For example, given:

           A     |     B
    1|           | someText1
    2|           | someText2
    3|           | someText3
    4|           | someText4

expected outcome content for Col A, after applying appropriate formula:

                A        |     B
    1| wrap("someText1") | someText1
    2| wrap("someText2") | someText2
    3| wrap("someText3") | someText3
    4| wrap("someText4") | someText4

I hope this makes sense, any help would be appreciated. Thanks

Body:
By combining MewX suggestion with  arrayformula one can achieve the same for all column, with one formula:

=arrayformula("wrap(""" & B1:B4 & """)")

Explanation: & is the string concatenation operator, quote marks within a string are escaped by doubling them.


问:
App crashes on Back button when SCNCamera is rotating
Did not found question or answer so posting it myself. My app crashes when I have Allow camera control enabled for my SCNView, then swipe so camera starts rotating and then press Back button in navigation bar. Crash stacktrace:

```<code>* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x18)
    frame #0: 0x0000000113e3d94b libobjc.A.dylib`objc_msgSend + 11
    frame #1: 0x00000001158a2eb6 SceneKit`__42-[SCNCameraController _setInertiaRunning:]_block_invoke.166 + 31
    frame #2: 0x00000001173e33f7 libdispatch.dylib`_dispatch_call_block_and_release + 12
    frame #3: 0x00000001173e443c libdispatch.dylib`_dispatch_client_callout + 8
    frame #4: 0x00000001173ef6f0 libdispatch.dylib`_dispatch_main_queue_callback_4CF + 628
    frame #5: 0x00000001149bbee9 CoreFoundation`__CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9
    frame #6: 0x0000000114980592 CoreFoundation`__CFRunLoopRun + 2402
    frame #7: 0x000000011497f9b9 CoreFoundation`CFRunLoopRunSpecific + 409
    frame #8: 0x00000001199a29c6 GraphicsServices`GSEventRunModal + 62
    frame #9: 0x000000011029b5e8 UIKit`UIApplicationMain + 159
  * frame #10: 0x000000010e6f73e7 ShowIt`main at AppDelegate.swift:13
    frame #11: 0x0000000117460d81 libdyld.dylib`start + 1
    frame #12: 0x0000000117460d81 libdyld.dylib`start + 1
</code>```

So message send to deallocated camera and app crashes.

答:
Found this solution:

```<code>override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)

    if isMovingFromParentViewController {
        // Prevent crash on back tap when camera rotates
        scnView.pointOfView = nil
    }
}
</code>```

Basically just set camera node to nil when controller pops.

Body:
Did not found question or answer so posting it myself. My app crashes when I have Allow camera control enabled for my SCNView, then swipe so camera starts rotating and then press Back button in navigation bar. Crash stacktrace:

* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x18)
    frame #0: 0x0000000113e3d94b libobjc.A.dylib`objc_msgSend + 11
    frame #1: 0x00000001158a2eb6 SceneKit`__42-[SCNCameraController _setInertiaRunning:]_block_invoke.166 + 31
    frame #2: 0x00000001173e33f7 libdispatch.dylib`_dispatch_call_block_and_release + 12
    frame #3: 0x00000001173e443c libdispatch.dylib`_dispatch_client_callout + 8
    frame #4: 0x00000001173ef6f0 libdispatch.dylib`_dispatch_main_queue_callback_4CF + 628
    frame #5: 0x00000001149bbee9 CoreFoundation`__CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9
    frame #6: 0x0000000114980592 CoreFoundation`__CFRunLoopRun + 2402
    frame #7: 0x000000011497f9b9 CoreFoundation`CFRunLoopRunSpecific + 409
    frame #8: 0x00000001199a29c6 GraphicsServices`GSEventRunModal + 62
    frame #9: 0x000000011029b5e8 UIKit`UIApplicationMain + 159
  * frame #10: 0x000000010e6f73e7 ShowIt`main at AppDelegate.swift:13
    frame #11: 0x0000000117460d81 libdyld.dylib`start + 1
    frame #12: 0x0000000117460d81 libdyld.dylib`start + 1

So message send to deallocated camera and app crashes.

Body:
Found this solution:

override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)

    if isMovingFromParentViewController {
        // Prevent crash on back tap when camera rotates
        scnView.pointOfView = nil
    }
}

Basically just set camera node to nil when controller pops.


问:
Insert provider for SQLiteObject ionic 3
I'm working on a project on ionic 3 angular 4. I have to connect to a database and do other things...
So I have a page (.ts .html .scss .module.ts), a provider where I use sql. So my problem is this, I have this error :

core.es5.js:1084

ERROR Error: Uncaught (in promise): Error: No provider for SQLiteObject!

Error: No provider for SQLiteObject!

So in module.ts I added in provider flag i put SQLiteObject. But now I get this new error :

compiler.es5.js:1540
 Uncaught Error: Can't resolve all parameters for SQLiteObject: (?).

Also if I put SQLite it wants always the SQLiteObject provider.Anyway I never use SQLite just SQLiteObject

```<code>import { SQLiteObject } from '@ionic-native/sqlite';
</code>```

I google and I found that  SQLiteObject is not a provider but just an interface.

So? Any idea? I can put code but is long, if you have some idea please comment.

答:
You need to add its class in providers in your app.module.ts file as:</p>

```<code>import { SQLiteObject } from '@ionic-native/sqlite';

@NgModule({
  declarations: [
    MyApp
  ],
  imports: [
   //
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp
  ],
  providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}, SQLiteObject]
})

export class AppModule {}
</code>```

Body:
I'm working on a project on ionic 3 angular 4. I have to connect to a database and do other things...
So I have a page (.ts .html .scss .module.ts), a provider where I use sql. So my problem is this, I have this error :

core.es5.js:1084

ERROR Error: Uncaught (in promise): Error: No provider for SQLiteObject!

Error: No provider for SQLiteObject!

So in module.ts I added in provider flag i put SQLiteObject. But now I get this new error :

compiler.es5.js:1540
 Uncaught Error: Can't resolve all parameters for SQLiteObject: (?).

Also if I put SQLite it wants always the SQLiteObject provider.Anyway I never use SQLite just SQLiteObject

import { SQLiteObject } from '@ionic-native/sqlite';

I google and I found that  SQLiteObject is not a provider but just an interface.

So? Any idea? I can put code but is long, if you have some idea please comment.

Body:
You need to add its class in providers in your app.module.ts file as:

import { SQLiteObject } from '@ionic-native/sqlite';

@NgModule({
  declarations: [
    MyApp
  ],
  imports: [
   //
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp
  ],
  providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}, SQLiteObject]
})

export class AppModule {}


问:
How Do I Delete Item from Recycler View Holder Class
I am new to android, currently I am working on recyclerView implementations. The issue is I want to delete an item after onCreateContextMenu has been called. I am having some problems getting the right reference to my delete option.

Holder Class

```<code>  public class UploadDrugsHolder extends RecyclerView.ViewHolder  implements View.OnClickListener, View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener {
        //OUR VIEWS
        UploadDrugsAdapter uploadDrugsAdapter;
        TextView drugName;
        ImageView drugImage;
        ItemClickListener itemClickListener;
        ArrayList<UploadedDrugs> drugs;
        public UploadDrugsHolder(View itemView) {
            super(itemView);
            this.drugName= (TextView) itemView.findViewById(R.id.shopName);
            this.drugImage= (ImageView) itemView.findViewById(R.id.model_menu);
            itemView.setOnClickListener(this);
            itemView.setOnCreateContextMenuListener(this);
        }

        public void setItemClickListener(ItemClickListener itemClickListener) {
            this.itemClickListener=itemClickListener;
        }

        @Override
        public void onClick(View v) {
            this.itemClickListener.onItemClick(v,getLayoutPosition());
        }

        @Override
        public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
            MenuItem myActionItem = menu.add("delete");
            myActionItem.setOnMenuItemClickListener(this);
        }

        @Override
        public boolean onMenuItemClick(MenuItem item) {
// what do i need to write here?
            Toast.makeText(itemView.getContext(), "Drug deleted successfully", Toast.LENGTH_SHORT).show();
            return false;
        }

    }
</code>```

答:
Something like:</p>

```<code>drugs.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, drugs.size());
</code>```

Body:
I am new to android, currently I am working on recyclerView implementations. The issue is I want to delete an item after onCreateContextMenu has been called. I am having some problems getting the right reference to my delete option.

Holder Class

  public class UploadDrugsHolder extends RecyclerView.ViewHolder  implements View.OnClickListener, View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener {
        //OUR VIEWS
        UploadDrugsAdapter uploadDrugsAdapter;
        TextView drugName;
        ImageView drugImage;
        ItemClickListener itemClickListener;
        ArrayList<UploadedDrugs> drugs;
        public UploadDrugsHolder(View itemView) {
            super(itemView);
            this.drugName= (TextView) itemView.findViewById(R.id.shopName);
            this.drugImage= (ImageView) itemView.findViewById(R.id.model_menu);
            itemView.setOnClickListener(this);
            itemView.setOnCreateContextMenuListener(this);
        }

        public void setItemClickListener(ItemClickListener itemClickListener) {
            this.itemClickListener=itemClickListener;
        }

        @Override
        public void onClick(View v) {
            this.itemClickListener.onItemClick(v,getLayoutPosition());
        }

        @Override
        public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
            MenuItem myActionItem = menu.add("delete");
            myActionItem.setOnMenuItemClickListener(this);
        }

        @Override
        public boolean onMenuItemClick(MenuItem item) {
// what do i need to write here?
            Toast.makeText(itemView.getContext(), "Drug deleted successfully", Toast.LENGTH_SHORT).show();
            return false;
        }

    }

Body:
Something like:

drugs.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, drugs.size());


问:
How to properly stub a function return value?

Premise: JS ES6, NodeJS

Testing Framework: TAP

Mocking Library: testdouble.js

I am attempting to mock the return value for the method of my class and keep receiving this error:

not ok Unsatisfied verification on test double.    Wanted:     - called with (true).    But there were no invocations of the test double.

Here is my testing code:

```<code>// Imports for unit testing
const tap = require('tap');
const Subject = require('../src/iTunesClient.js');
const td = require('testdouble');

let reqJson;

// Ensure the iTunes class methods are called
tap.test('iTunesClient class methods function as intended', (t) => {
  t.beforeEach((ready) => {
    reqJson = td.replace('../src/reqJson.js');
    ready();
  });

  t.afterEach((ready) => {
    td.reset();
    ready();
  });

  t.test('iTunesClient.getData', (assert) => {
    const callback = td.function();
    const subject = new Subject();
    subject.setTerm('abc 123');
    subject.setURL();

    td.when(reqJson.get(td.callback)).thenCallback(true);

    subject.getData(callback);

    td.verify(callback(true));
    assert.end();
  });

  t.end();
});
</code>```

Specifically, this line is related to my issue:

```<code>td.verify(callback(true));
</code>```

How can I fake the callback value of true for reqJson.get()? Right now, Subject.geData() is a method of the iTunesClient class which calls another file, reqJson.js, to use its exported get() method.

答:
I wanted to update this question, as I recently solved this issue. Essentially, I had two issues:

Account for both reqJson function parameters

Account for all callback return values

Per testdouble documentation for item 1:

When passed td.matchers.anything(), any invocation of that test double function will ignore that parameter when determining whether an invocation satisfies the stubbing.

Hence, I adjusted my line of code as follows:

Before: td.when(reqJson.get(td.callback)).thenCallback(true);

After: td.when(reqJson.get(td.matchers.anything(), td.callback)).thenCallback(null, null, null);

Body:
Premise: JS ES6, NodeJS

Testing Framework: TAP

Mocking Library: testdouble.js

I am attempting to mock the return value for the method of my class and keep receiving this error:

not ok Unsatisfied verification on test double.    Wanted:     - called with (true).    But there were no invocations of the test double.

Here is my testing code:

// Imports for unit testing
const tap = require('tap');
const Subject = require('../src/iTunesClient.js');
const td = require('testdouble');

let reqJson;

// Ensure the iTunes class methods are called
tap.test('iTunesClient class methods function as intended', (t) => {
  t.beforeEach((ready) => {
    reqJson = td.replace('../src/reqJson.js');
    ready();
  });

  t.afterEach((ready) => {
    td.reset();
    ready();
  });

  t.test('iTunesClient.getData', (assert) => {
    const callback = td.function();
    const subject = new Subject();
    subject.setTerm('abc 123');
    subject.setURL();

    td.when(reqJson.get(td.callback)).thenCallback(true);

    subject.getData(callback);

    td.verify(callback(true));
    assert.end();
  });

  t.end();
});

Specifically, this line is related to my issue:

td.verify(callback(true));

How can I fake the callback value of true for reqJson.get()? Right now, Subject.geData() is a method of the iTunesClient class which calls another file, reqJson.js, to use its exported get() method.


问:
new Microsoft sliding website question
Does anyone here know what was used to make the new microsoft website slide over like it does?

I want to use something like this to show 2 sides of my company like they did for business/home.

http://www.microsoft.com/en-us/preview/default.aspx

Thank you,

答:
This appears to be nothing more than a basic content slider that would exist for just about any Javascript library. One very popular library is the jQuery library (you'll find it mentioned a lot around here). jQuery (having an open plugin model) has many content slider plugins - one popular one is jQuery Scrollable.

After a quick brush through the documentation for jQScrollable and loading both the plugin and the library into your page, you should be able to replicate this behavior pretty quickly.

Title: new Microsoft sliding website question


问:
Generate a video stream from Basler camera grabbing loop
I am a beginner in video streaming and handling.

I need to take the stream from a Basler GiGE camera and display it in a web container.

I am using the Basler.Pylon C# API to access the camera and grab images one by one. from the IGrabResult object returned, I can access various parameters such as width, height, stride, and of course the byte buffer.

On my PC, I can easily display that in an image window, but what do i need to do to display that in an ASP.NET web application?

EDIT

I am not looking for code but more for guidelines, if someone could explain how video streaming works in general, that would work too

答:
Video streaming is quite specialised and in general I would say if you want to stream high quality video over the internet to multiple end suers, its easiest to use a dedicated video streaming server rather than try to build one yourself.

Dedicated video streaming servers can be provided via a hosted service (e.g Vimeo), be a commercial server you install and run (e.g. Wowza) or a freeware streaming server you install and rune (e.g. GStreamer), so you have options there.

A a general rule, the streaming server will break your video into chunks and create multiple bit rate copies of your video. This allows a client to use Adaptive Bit Rate streaming (ABR) and download your video chunk by chunk, selecting the bit rate version for the next chunk depending on the current device and network conditions. HLS and MPEG-DASH are exmaples of ABR streaming protocols.

On a web page you then need a HTNML5 player which can understand this streaming protocol - again there are many examples such as the freeware Shaka and Dash.js players. Integrating these into a web page is very straightforward.

You can observe these in use on services like Netflix and YouTube which will often start at a lower bit rate to ensure a fast start and then 'step up' to higher bit rates until the optimal one for the current network conditions and device is reached. See here for some info on how you can see a graph of this when watching YouTube, for example:

https://stackoverflow.com/a/42365034/334402

Having said all the above, it is worth nothing that your case seems to be dealing with a stream of still images. Although all video is really a stream of still images under the covers, it may be that your image is changing infrequently, and hence you may not need some of the techniques above - a lot of the technology of video streaming is to deal with the very large amount of data streaming 30 or 60 high quality frames per second from a server to a client.

If your stream of images, for example, was one every 30 seconds then it may, as Nisus says, be just as easy to simply display the images in your web page and have the web page or app poll the server every 30 seconds (using ASP.NET AJAX in your case) to download the new image.


问:
Pandas dataframe fillna() only some columns in place
I am trying to fill none values in a Pandas dataframe with 0's for only some subset of columns.

When I do:

```<code>import pandas as pd
df = pd.DataFrame(data={'a':[1,2,3,None],'b':[4,5,None,6],'c':[None,None,7,8]})
print df
df.fillna(value=0, inplace=True)
print df
</code>```

The output:

```<code>     a    b    c
0  1.0  4.0  NaN
1  2.0  5.0  NaN
2  3.0  NaN  7.0
3  NaN  6.0  8.0
     a    b    c
0  1.0  4.0  0.0
1  2.0  5.0  0.0
2  3.0  0.0  7.0
3  0.0  6.0  8.0
</code>```

It replaces every None with 0's. What I want to do is, only replace Nones in columns a and b, but not c.

What is the best way of doing this?

答:
You can using dict , fillna with different value for different column

```<code>df.fillna({'a':0,'b':0})
Out[829]:
     a    b    c
0  1.0  4.0  NaN
1  2.0  5.0  NaN
2  3.0  0.0  7.0
3  0.0  6.0  8.0
</code>```

After assign it back

```<code>df=df.fillna({'a':0,'b':0})
df
Out[831]:
     a    b    c
0  1.0  4.0  NaN
1  2.0  5.0  NaN
2  3.0  0.0  7.0
3  0.0  6.0  8.0
</code>```

Body:
I am trying to fill none values in a Pandas dataframe with 0's for only some subset of columns.

When I do:

import pandas as pd
df = pd.DataFrame(data={'a':[1,2,3,None],'b':[4,5,None,6],'c':[None,None,7,8]})
print df
df.fillna(value=0, inplace=True)
print df

The output:

     a    b    c
0  1.0  4.0  NaN
1  2.0  5.0  NaN
2  3.0  NaN  7.0
3  NaN  6.0  8.0
     a    b    c
0  1.0  4.0  0.0
1  2.0  5.0  0.0
2  3.0  0.0  7.0
3  0.0  6.0  8.0

It replaces every None with 0's. What I want to do is, only replace Nones in columns a and b, but not c.

What is the best way of doing this?

Body:
You can using dict , fillna with different value for different column

df.fillna({'a':0,'b':0})
Out[829]:
     a    b    c
0  1.0  4.0  NaN
1  2.0  5.0  NaN
2  3.0  0.0  7.0
3  0.0  6.0  8.0

After assign it back

df=df.fillna({'a':0,'b':0})
df
Out[831]:
     a    b    c
0  1.0  4.0  NaN
1  2.0  5.0  NaN
2  3.0  0.0  7.0
3  0.0  6.0  8.0


问:
Print out an array in uppercase Java
So for this program I'm currently creating I have had to store 10 names in an array, which is simple enough, then print out that array with the 10 names displayed in uppercase, which is the part I'm currently stuck on. I've been told that using a for or for each loop will be able to achieve this.

This is the code I currently have:

```<code>package uploadTask8_uppercaseArrays;

import java.util.Arrays;
import java.util.Scanner;

public class uppercaseArrays {

    public static void main(String[] args) {
        // creates array that will store the 10 names
        String[] names10 = new String[10];

        System.out.println("Please enter the ten names: \n1: ");
        // create scanner object to get user input
        Scanner userInput = new Scanner(System.in);
        String firstName = userInput.nextLine();
        System.out.println("2: ");
        String secondName = userInput.nextLine();
        System.out.println("3: ");
        String thirdName = userInput.nextLine();
        System.out.println("4: ");
        String fourthName = userInput.nextLine();
        System.out.println("5: ");
        String fifthName = userInput.nextLine();
        System.out.println("6: ");
        String sixthName = userInput.nextLine();
        System.out.println("7: ");
        String seventhName = userInput.nextLine();
        System.out.println("8: ");
        String eigthName = userInput.nextLine();
        System.out.println("9: ");
        String ninthName = userInput.nextLine();
        System.out.println("10: ");
        String tenthName = userInput.nextLine();
        userInput.close();

        // assigns user input to each element in the array
        names10[0] = firstName;
        names10[1] = secondName;
        names10[2] = thirdName;
        names10[3] = fourthName;
        names10[4] = fifthName;
        names10[5] = sixthName;
        names10[6] = seventhName;
        names10[7] = eigthName;
        names10[8] = ninthName;
        names10[9] = tenthName;

        // prints out the array in lowercase
        System.out.println(Arrays.toString(names10));
        // prints out the array in uppercase

    }

}
</code>```

I've had a look at some other code,  but can't actually work out the code for the for or for each loop that changes the array into uppercase. Does anyone know how this would work?

答:
can't actually work out the code for the for or for each loop that
  changes the array into uppercase. Does anyone know how this would
  work?

You can simply convert your string variables to upper case at the time of storing them in the array.

```<code>    names10[0] = firstName.toUpperCase();
    names10[1] = secondName.toUpperCase();
    ...
</code>```

Or a more elegant option is to run a loop like following:

```<code>for (int i = 0; i < names10.length; i++) {
    System.out.println((i + 1) + ": ");
    names10[i] = userInput.nextLine().toUpperCase();
}
</code>```

Title: Print out an array in uppercase Java

Body:
So for this program I'm currently creating I have had to store 10 names in an array, which is simple enough, then print out that array with the 10 names displayed in uppercase, which is the part I'm currently stuck on. I've been told that using a for or for each loop will be able to achieve this.

This is the code I currently have:

package uploadTask8_uppercaseArrays;

import java.util.Arrays;
import java.util.Scanner;

public class uppercaseArrays {

    public static void main(String[] args) {
        // creates array that will store the 10 names
        String[] names10 = new String[10];

        System.out.println("Please enter the ten names: \n1: ");
        // create scanner object to get user input
        Scanner userInput = new Scanner(System.in);
        String firstName = userInput.nextLine();
        System.out.println("2: ");
        String secondName = userInput.nextLine();
        System.out.println("3: ");
        String thirdName = userInput.nextLine();
        System.out.println("4: ");
        String fourthName = userInput.nextLine();
        System.out.println("5: ");
        String fifthName = userInput.nextLine();
        System.out.println("6: ");
        String sixthName = userInput.nextLine();
        System.out.println("7: ");
        String seventhName = userInput.nextLine();
        System.out.println("8: ");
        String eigthName = userInput.nextLine();
        System.out.println("9: ");
        String ninthName = userInput.nextLine();
        System.out.println("10: ");
        String tenthName = userInput.nextLine();
        userInput.close();

        // assigns user input to each element in the array
        names10[0] = firstName;
        names10[1] = secondName;
        names10[2] = thirdName;
        names10[3] = fourthName;
        names10[4] = fifthName;
        names10[5] = sixthName;
        names10[6] = seventhName;
        names10[7] = eigthName;
        names10[8] = ninthName;
        names10[9] = tenthName;

        // prints out the array in lowercase
        System.out.println(Arrays.toString(names10));
        // prints out the array in uppercase

    }

}

I've had a look at some other code,  but can't actually work out the code for the for or for each loop that changes the array into uppercase. Does anyone know how this would work?

Body:
can't actually work out the code for the for or for each loop that
  changes the array into uppercase. Does anyone know how this would
  work?

You can simply convert your string variables to upper case at the time of storing them in the array.

    names10[0] = firstName.toUpperCase();
    names10[1] = secondName.toUpperCase();
    ...

Or a more elegant option is to run a loop like following:

for (int i = 0; i < names10.length; i++) {
    System.out.println((i + 1) + ": ");
    names10[i] = userInput.nextLine().toUpperCase();
}


问:
Implementing Generic Method
Trying to implement this:

Interface:

```<code>public interface IStoreReader
{
    Task<IEnumerable<T>> Get<T>(UserDb user);
}
</code>```

Implementation:

```<code>public async Task<IEnumerable<ConversationDb>> Get<ConversationDb>(UserDb user)
{
    return await _convoRepo.Get(user.UserId); // error here
}
</code>```

Convo repo:

```<code>public async Task<IEnumerable<ConversationDb>> Get(string userId)
{
      return await // get from db - this works fine
}
</code>```

Error:

答:
When you define the generic type on the method then when you implement it the name you give is just going to be a generic type.  Thus it's saying that the concrete class from your repo is not the same as the generic one that just happens to have the same name.  I believe you actually want to define the generic type on your interface instead.</p>

```<code>public interface IStoreReader<T>
{
    Task<IEnumerable<T>> Get(UserDb user);
}

public class ConversationReader : IStorReader<ConversationDb>
{
    public async Task<IEnumerable<ConversationDb>> Get(UserDb user)
    {
        return await _convoRepo.Get(user.UserId);
    }
}
</code>```

Title: Implementing Generic Method

Body:
Trying to implement this:

Interface:

public interface IStoreReader
{
    Task<IEnumerable<T>> Get<T>(UserDb user);
}

Implementation:

public async Task<IEnumerable<ConversationDb>> Get<ConversationDb>(UserDb user)
{
    return await _convoRepo.Get(user.UserId); // error here
}

Convo repo:

public async Task<IEnumerable<ConversationDb>> Get(string userId)
{
      return await // get from db - this works fine
}

Error:

Body:
When you define the generic type on the method then when you implement it the name you give is just going to be a generic type.  Thus it's saying that the concrete class from your repo is not the same as the generic one that just happens to have the same name.  I believe you actually want to define the generic type on your interface instead.

public interface IStoreReader<T>
{
    Task<IEnumerable<T>> Get(UserDb user);
}

public class ConversationReader : IStorReader<ConversationDb>
{
    public async Task<IEnumerable<ConversationDb>> Get(UserDb user)
    {
        return await _convoRepo.Get(user.UserId);
    }
}


问:
gRPC Java - Listening for successful calls on server
I am looking for a way to capture when a call is completed on the server and no errors were thrown.

I understand that SimpleForwardingServerCallListener exists, however,onComplete is called when an exception is thrown.

My use case is for transaction management.

答:
Yes, it currently only triggers onComplete(). There is a bug filed for that. If it's fixed, you can probably get onCancel() instead.

For now, you can wrap the ServerCall with SimpleForwardingServerCall in your ServerInterceptor, and override close(). If the RPC ends successfully, OK will be passed to close().


问:
Play 2.6.x Java Application works in Dev Mode but fails in Prod mode
I am unable to run my Application in Production mode, while Development mode works fine and can't find a reason for it.

I am using Play Framework 2.6.x and am connecting to a Postgresql database.

Here is the output of sbt run (which starts dev mode)

```<code>sbt run
--- (Running the application, auto-reloading is enabled) ---

[info] p.c.s.AkkaHttpServer - Listening for HTTP on /0:0:0:0:0:0:0:0:9000

(Server started, use Enter to stop and go back to the console...)

[info] application - Creating Pool for datasource 'default'
[info] p.a.d.DefaultDBApi - Database [default] connected at jdbc:postgresql://192.168.155.177/legato
[info] a.e.s.Slf4jLogger - Slf4jLogger started
[info] play.api.Play - Application started (Dev)
</code>```

Here is the output of sbt start (starting production mode)

```<code>sbt start
(Starting server. Type Ctrl+D to exit logs, the server will remain in background)

[info] application - Creating Pool for datasource 'default'
[info] p.a.d.DefaultDBApi - Database [default] connected at jdbc:postgresql://192.168.155.177/legato
[info] a.e.s.Slf4jLogger - Slf4jLogger started
[warn] o.h.v.m.ParameterMessageInterpolator - HV000184: ParameterMessageInterpolator has been chosen, EL interpolation will not be supported
Oops, cannot start the server.
com.google.inject.CreationException: Unable to create injector, see the following errors:

1) Error injecting constructor, org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
  at play.db.jpa.DefaultJPAApi$JPAApiProvider.<init>(DefaultJPAApi.java:40)
  at play.db.jpa.DefaultJPAApi$JPAApiProvider.class(DefaultJPAApi.java:35)
  while locating play.db.jpa.DefaultJPAApi$JPAApiProvider

1 error
        at com.google.inject.internal.Errors.throwCreationExceptionIfErrorsExist(Errors.java:470)
        at com.google.inject.internal.InternalInjectorCreator.injectDynamically(InternalInjectorCreator.java:184)
        at com.google.inject.internal.InternalInjectorCreator.build(InternalInjectorCreator.java:110)
        at com.google.inject.Guice.createInjector(Guice.java:99)
        at com.google.inject.Guice.createInjector(Guice.java:84)
        at play.api.inject.guice.GuiceBuilder.injector(GuiceInjectorBuilder.scala:185)
        at play.api.inject.guice.GuiceApplicationBuilder.build(GuiceApplicationBuilder.scala:137)
        at play.api.inject.guice.GuiceApplicationLoader.load(GuiceApplicationLoader.scala:21)
        at play.core.server.ProdServerStart$.start(ProdServerStart.scala:51)
        at play.core.server.ProdServerStart$.main(ProdServerStart.scala:25)
        at play.core.server.ProdServerStart.main(ProdServerStart.scala)
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:271)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:233)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
        at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51)
        at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:242)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
        at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352)
        at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111)
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:858)
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:885)
        at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:58)
        at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
        at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
        at play.db.jpa.DefaultJPAApi.lambda$start$1(DefaultJPAApi.java:61)
        at java.lang.Iterable.forEach(Iterable.java:75)
        at play.db.jpa.DefaultJPAApi.start(DefaultJPAApi.java:60)
        at play.db.jpa.DefaultJPAApi$JPAApiProvider.<init>(DefaultJPAApi.java:47)
        at play.db.jpa.DefaultJPAApi$JPAApiProvider$$FastClassByGuice$$dcd4cdbd.newInstance(<generated>)
        at com.google.inject.internal.DefaultConstructionProxyFactory$FastClassProxy.newInstance(DefaultConstructionProxyFactory.java:89)
        at com.google.inject.internal.ConstructorInjector.provision(ConstructorInjector.java:111)
        at com.google.inject.internal.ConstructorInjector.construct(ConstructorInjector.java:90)
        at com.google.inject.internal.ConstructorBindingImpl$Factory.get(ConstructorBindingImpl.java:268)
        at com.google.inject.internal.ProviderToInternalFactoryAdapter$1.call(ProviderToInternalFactoryAdapter.java:46)
        at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1092)
        at com.google.inject.internal.ProviderToInternalFactoryAdapter.get(ProviderToInternalFactoryAdapter.java:40)
        at com.google.inject.internal.SingletonScope$1.get(SingletonScope.java:194)
        at com.google.inject.internal.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:41)
        at com.google.inject.internal.InternalInjectorCreator$1.call(InternalInjectorCreator.java:205)
        at com.google.inject.internal.InternalInjectorCreator$1.call(InternalInjectorCreator.java:199)
        at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1085)
        at com.google.inject.internal.InternalInjectorCreator.loadEagerSingletons(InternalInjectorCreator.java:199)
        at com.google.inject.internal.InternalInjectorCreator.injectDynamically(InternalInjectorCreator.java:180)
        ... 9 more
Caused by: org.hibernate.engine.jndi.JndiException: Unable to lookup JNDI name [DefaultDS]
        at org.hibernate.engine.jndi.internal.JndiServiceImpl.locate(JndiServiceImpl.java:100)
        at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.configure(DatasourceConnectionProviderImpl.java:98)
        at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:242)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
        at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.buildJdbcConnectionAccess(JdbcEnvironmentInitiator.java:145)
        at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:66)
        at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
        at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:259)
        ... 41 more
Caused by: javax.naming.NameNotFoundException: DefaultDS not found
        at tyrex.naming.MemoryContext.internalLookup(Unknown Source)
        at tyrex.naming.MemoryContext.lookup(Unknown Source)
        at javax.naming.InitialContext.lookup(InitialContext.java:421)
        at org.hibernate.engine.jndi.internal.JndiServiceImpl.locate(JndiServiceImpl.java:97)
        ... 50 more
[info] a.a.CoordinatedShutdown - Starting coordinated shutdown from JVM shutdown hook
[INFO] [11/15/2017 18:13:25.905] [Thread-2] [CoordinatedShutdown(akka://sbt-web)] Starting coordinated shutdown from JVM shutdown hook
</code>```

Could anybody point me into a direction where this error could originate from?

Here is my application.conf

```<code># This is the main configuration file for the application.
# https://www.playframework.com/documentation/latest/ConfigFile

# Point JPA at our database configuration
jpa.default=defaultPersistenceUnit

# Number of database connections
# See https://github.com/brettwooldridge/HikariCP/wiki/About-Pool-Sizing
fixedConnectionPool = 9

play.http.secret.key="xxxxxxxx"

db.default {
  driver = org.postgresql.Driver
  url = "jdbc:postgresql://192.168.155.177/legato"
  username = "vagrant"
  password = "xxxxxxx"
}

ebean.default = ["models.*"]

play.evolutions.enabled=true

# disable the built in filters
play.http.filters = play.api.http.NoHttpFilters

# Job queue sized to HikariCP connection pool
post.repository {
  executor = "thread-pool-executor"
  throughput = 1
  thread-pool-executor {
    fixed-pool-size = ${fixedConnectionPool}
  }
}
</code>```

And my build.sbt

```<code>name := """Legato Core Backend"""

version := "stable"

inThisBuild(
  List(
    scalaVersion := "2.12.3",
    dependencyOverrides := Seq(
       "org.codehaus.plexus" % "plexus-utils" % "3.0.18",
       "com.google.code.findbugs" % "jsr305" % "3.0.1",
       "com.google.guava" % "guava" % "22.0",
       "com.typesafe.akka" %% "akka-stream" % "2.5.6",
       "com.typesafe.akka" %% "akka-actor" % "2.5.6"
    )
  )
)

lazy val root = (project in file(".")).enablePlugins(PlayJava, PlayEbean)

libraryDependencies += guice
libraryDependencies += javaJpa
libraryDependencies += evolutions
libraryDependencies += javaJdbc
libraryDependencies += "org.postgresql" % "postgresql" % "42.1.4"
libraryDependencies += "com.h2database" % "h2" % "1.4.194"

libraryDependencies += "org.hibernate" % "hibernate-core" % "5.2.9.Final"
libraryDependencies += "io.dropwizard.metrics" % "metrics-core" % "3.2.1"
libraryDependencies += "com.palominolabs.http" % "url-builder" % "1.1.0"
libraryDependencies += "net.jodah" % "failsafe" % "1.0.3"

libraryDependencies += "io.gatling.highcharts" % "gatling-charts-highcharts" % "2.3.0" % Test
libraryDependencies += "io.gatling" % "gatling-test-framework" % "2.3.0" % Test

PlayKeys.externalizeResources := false

testOptions in Test := Seq(Tests.Argument(TestFrameworks.JUnit, "-a", "-v"))
</code>```

And my plugins.sbt

```<code>// The Play plugin
addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.6.6")

// Load testing tool:
// http://gatling.io/docs/2.2.2/extensions/sbt_plugin.html
addSbtPlugin("io.gatling" % "gatling-sbt" % "2.2.2")

addSbtPlugin("com.typesafe.sbt" % "sbt-play-enhancer" % "1.2.2")
addSbtPlugin("com.typesafe.sbt" % "sbt-play-ebean" % "4.0.6")
</code>```

答:
Set PlayKeys.externalizeResources := false in your build.sbt. From the documentation:

Deploying Play with JPA

Running Play in development mode while using JPA will work fine, but in order to deploy the application you will need to add this to your build.sbt file.

```<code>PlayKeys.externalizeResources := false
</code>```

Note: Since Play 2.4 the contents of the conf directory are added to the classpath by default. This option will disable that behavior and allow a JPA application to be deployed. The content of conf directory will still be available in the classpath due to it being included in the application’s jar file.

Body:
I am unable to run my Application in Production mode, while Development mode works fine and can't find a reason for it.

I am using Play Framework 2.6.x and am connecting to a Postgresql database.

Here is the output of sbt run (which starts dev mode)

sbt run
--- (Running the application, auto-reloading is enabled) ---

[info] p.c.s.AkkaHttpServer - Listening for HTTP on /0:0:0:0:0:0:0:0:9000

(Server started, use Enter to stop and go back to the console...)

[info] application - Creating Pool for datasource 'default'
[info] p.a.d.DefaultDBApi - Database [default] connected at jdbc:postgresql://192.168.155.177/legato
[info] a.e.s.Slf4jLogger - Slf4jLogger started
[info] play.api.Play - Application started (Dev)

Here is the output of sbt start (starting production mode)

sbt start
(Starting server. Type Ctrl+D to exit logs, the server will remain in background)

[info] application - Creating Pool for datasource 'default'
[info] p.a.d.DefaultDBApi - Database [default] connected at jdbc:postgresql://192.168.155.177/legato
[info] a.e.s.Slf4jLogger - Slf4jLogger started
[warn] o.h.v.m.ParameterMessageInterpolator - HV000184: ParameterMessageInterpolator has been chosen, EL interpolation will not be supported
Oops, cannot start the server.
com.google.inject.CreationException: Unable to create injector, see the following errors:

1) Error injecting constructor, org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
  at play.db.jpa.DefaultJPAApi$JPAApiProvider.<init>(DefaultJPAApi.java:40)
  at play.db.jpa.DefaultJPAApi$JPAApiProvider.class(DefaultJPAApi.java:35)
  while locating play.db.jpa.DefaultJPAApi$JPAApiProvider

1 error
        at com.google.inject.internal.Errors.throwCreationExceptionIfErrorsExist(Errors.java:470)
        at com.google.inject.internal.InternalInjectorCreator.injectDynamically(InternalInjectorCreator.java:184)
        at com.google.inject.internal.InternalInjectorCreator.build(InternalInjectorCreator.java:110)
        at com.google.inject.Guice.createInjector(Guice.java:99)
        at com.google.inject.Guice.createInjector(Guice.java:84)
        at play.api.inject.guice.GuiceBuilder.injector(GuiceInjectorBuilder.scala:185)
        at play.api.inject.guice.GuiceApplicationBuilder.build(GuiceApplicationBuilder.scala:137)
        at play.api.inject.guice.GuiceApplicationLoader.load(GuiceApplicationLoader.scala:21)
        at play.core.server.ProdServerStart$.start(ProdServerStart.scala:51)
        at play.core.server.ProdServerStart$.main(ProdServerStart.scala:25)
        at play.core.server.ProdServerStart.main(ProdServerStart.scala)
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:271)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:233)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
        at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51)
        at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:242)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
        at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352)
        at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111)
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:858)
        at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:885)
        at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:58)
        at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
        at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
        at play.db.jpa.DefaultJPAApi.lambda$start$1(DefaultJPAApi.java:61)
        at java.lang.Iterable.forEach(Iterable.java:75)
        at play.db.jpa.DefaultJPAApi.start(DefaultJPAApi.java:60)
        at play.db.jpa.DefaultJPAApi$JPAApiProvider.<init>(DefaultJPAApi.java:47)
        at play.db.jpa.DefaultJPAApi$JPAApiProvider$$FastClassByGuice$$dcd4cdbd.newInstance(<generated>)
        at com.google.inject.internal.DefaultConstructionProxyFactory$FastClassProxy.newInstance(DefaultConstructionProxyFactory.java:89)
        at com.google.inject.internal.ConstructorInjector.provision(ConstructorInjector.java:111)
        at com.google.inject.internal.ConstructorInjector.construct(ConstructorInjector.java:90)
        at com.google.inject.internal.ConstructorBindingImpl$Factory.get(ConstructorBindingImpl.java:268)
        at com.google.inject.internal.ProviderToInternalFactoryAdapter$1.call(ProviderToInternalFactoryAdapter.java:46)
        at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1092)
        at com.google.inject.internal.ProviderToInternalFactoryAdapter.get(ProviderToInternalFactoryAdapter.java:40)
        at com.google.inject.internal.SingletonScope$1.get(SingletonScope.java:194)
        at com.google.inject.internal.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:41)
        at com.google.inject.internal.InternalInjectorCreator$1.call(InternalInjectorCreator.java:205)
        at com.google.inject.internal.InternalInjectorCreator$1.call(InternalInjectorCreator.java:199)
        at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1085)
        at com.google.inject.internal.InternalInjectorCreator.loadEagerSingletons(InternalInjectorCreator.java:199)
        at com.google.inject.internal.InternalInjectorCreator.injectDynamically(InternalInjectorCreator.java:180)
        ... 9 more
Caused by: org.hibernate.engine.jndi.JndiException: Unable to lookup JNDI name [DefaultDS]
        at org.hibernate.engine.jndi.internal.JndiServiceImpl.locate(JndiServiceImpl.java:100)
        at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.configure(DatasourceConnectionProviderImpl.java:98)
        at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:242)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
        at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.buildJdbcConnectionAccess(JdbcEnvironmentInitiator.java:145)
        at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:66)
        at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
        at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:259)
        ... 41 more
Caused by: javax.naming.NameNotFoundException: DefaultDS not found
        at tyrex.naming.MemoryContext.internalLookup(Unknown Source)
        at tyrex.naming.MemoryContext.lookup(Unknown Source)
        at javax.naming.InitialContext.lookup(InitialContext.java:421)
        at org.hibernate.engine.jndi.internal.JndiServiceImpl.locate(JndiServiceImpl.java:97)
        ... 50 more
[info] a.a.CoordinatedShutdown - Starting coordinated shutdown from JVM shutdown hook
[INFO] [11/15/2017 18:13:25.905] [Thread-2] [CoordinatedShutdown(akka://sbt-web)] Starting coordinated shutdown from JVM shutdown hook

Could anybody point me into a direction where this error could originate from?

Here is my application.conf

# This is the main configuration file for the application.
# https://www.playframework.com/documentation/latest/ConfigFile

# Point JPA at our database configuration
jpa.default=defaultPersistenceUnit

# Number of database connections
# See https://github.com/brettwooldridge/HikariCP/wiki/About-Pool-Sizing
fixedConnectionPool = 9

play.http.secret.key="xxxxxxxx"

db.default {
  driver = org.postgresql.Driver
  url = "jdbc:postgresql://192.168.155.177/legato"
  username = "vagrant"
  password = "xxxxxxx"
}

ebean.default = ["models.*"]

play.evolutions.enabled=true

# disable the built in filters
play.http.filters = play.api.http.NoHttpFilters

# Job queue sized to HikariCP connection pool
post.repository {
  executor = "thread-pool-executor"
  throughput = 1
  thread-pool-executor {
    fixed-pool-size = ${fixedConnectionPool}
  }
}

And my build.sbt

name := """Legato Core Backend"""

version := "stable"

inThisBuild(
  List(
    scalaVersion := "2.12.3",
    dependencyOverrides := Seq(
       "org.codehaus.plexus" % "plexus-utils" % "3.0.18",
       "com.google.code.findbugs" % "jsr305" % "3.0.1",
       "com.google.guava" % "guava" % "22.0",
       "com.typesafe.akka" %% "akka-stream" % "2.5.6",
       "com.typesafe.akka" %% "akka-actor" % "2.5.6"
    )
  )
)

lazy val root = (project in file(".")).enablePlugins(PlayJava, PlayEbean)

libraryDependencies += guice
libraryDependencies += javaJpa
libraryDependencies += evolutions
libraryDependencies += javaJdbc
libraryDependencies += "org.postgresql" % "postgresql" % "42.1.4"
libraryDependencies += "com.h2database" % "h2" % "1.4.194"

libraryDependencies += "org.hibernate" % "hibernate-core" % "5.2.9.Final"
libraryDependencies += "io.dropwizard.metrics" % "metrics-core" % "3.2.1"
libraryDependencies += "com.palominolabs.http" % "url-builder" % "1.1.0"
libraryDependencies += "net.jodah" % "failsafe" % "1.0.3"

libraryDependencies += "io.gatling.highcharts" % "gatling-charts-highcharts" % "2.3.0" % Test
libraryDependencies += "io.gatling" % "gatling-test-framework" % "2.3.0" % Test

PlayKeys.externalizeResources := false

testOptions in Test := Seq(Tests.Argument(TestFrameworks.JUnit, "-a", "-v"))

And my plugins.sbt

// The Play plugin
addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.6.6")

// Load testing tool:
// http://gatling.io/docs/2.2.2/extensions/sbt_plugin.html
addSbtPlugin("io.gatling" % "gatling-sbt" % "2.2.2")

addSbtPlugin("com.typesafe.sbt" % "sbt-play-enhancer" % "1.2.2")
addSbtPlugin("com.typesafe.sbt" % "sbt-play-ebean" % "4.0.6")

Body:
Set PlayKeys.externalizeResources := false in your build.sbt. From the documentation:

Deploying Play with JPA

Running Play in development mode while using JPA will work fine, but in order to deploy the application you will need to add this to your build.sbt file.

PlayKeys.externalizeResources := false

Note: Since Play 2.4 the contents of the conf directory are added to the classpath by default. This option will disable that behavior and allow a JPA application to be deployed. The content of conf directory will still be available in the classpath due to it being included in the application’s jar file.


问:
Can't use "insert picture from sharepoint" on sharepoint 2010 blog?
I am the admin for a site colelction and when I create a wiki I can use "insert from sharepoint" when I add pictures but when I create a blog is greyed out. Why can I use it on the wiki but not on the blog?

I have activated publishing on both the site collection level and on the site level.

Thanks.

答:
These components/content types

Enterprise Wiki

Publishing Page

Allow "Insert from Sharepoint" because the content field is of type "Publishing HTML"

These components

Wiki

Blog

Don't have the "Insert from Sharepoint" action, because the content field is of type "Multiple lines of text"