问:
Laravel 5 Form request validation with parameters
I am using form request validation and there are some rules that needs external values as a parameters.

Here are my validation rules for editing a business profile inside a form request class,

```<code>public function rules()
{
    return [
        'name' => 'required|unique:businesses,name,'.$business->id,
        'url' => 'required|url|unique:businesses'
    ];
}
</code>```

I can use this on the controller by type hinting it.

```<code>public function postBusinessEdit(BusinessEditRequest $request, Business $business)
{
    //
}
</code>```

But how to pass the $business object as a parameter to the rules method?

答:
Since Laravel 5.6 you may type hint it in the rules method:

```<code>public function rules(Business $business)
{
    return [
        'name' => 'required|unique:businesses,name,'.$business->id,
        'url' => 'required|url|unique:businesses'
    ];
}
</code>```

See the docs for more:

You may type-hint any dependencies you need within the rules method's signature. They will automatically be resolved via the Laravel service container.

Body:
I am using form request validation and there are some rules that needs external values as a parameters.

Here are my validation rules for editing a business profile inside a form request class,

public function rules()
{
    return [
        'name' => 'required|unique:businesses,name,'.$business->id,
        'url' => 'required|url|unique:businesses'
    ];
}

I can use this on the controller by type hinting it.

public function postBusinessEdit(BusinessEditRequest $request, Business $business)
{
    //
}

But how to pass the $business object as a parameter to the rules method?

Body:
Since Laravel 5.6 you may type hint it in the rules method:

public function rules(Business $business)
{
    return [
        'name' => 'required|unique:businesses,name,'.$business->id,
        'url' => 'required|url|unique:businesses'
    ];
}

See the docs for more:

You may type-hint any dependencies you need within the rules method's signature. They will automatically be resolved via the Laravel service container.


来源: stackexchange

问:
Python incorrect ways to add to list when generating permutations
In this example, why does this generate the correct result:

```<code>nxt = path + [nums[i]]
</code>```

But not:

```<code>nxt = path ; nxt += [nums[i]]
</code>```

```<code>nxt = path ; nxt.append(nums[i])
</code>```

```<code>def permute(nums):
    def dfs(nums, path):
      if not nums: # empty, done with path
          all_perms.append(path)
          return

      for i in range(len(nums)):
        nxt = path + [nums[i]]
        # nxt = path ; nxt += [nums[i]]
        # nxt = path ; nxt.append(nums[i])
        print(nxt)
        dfs(nums[:i] + nums[i+1:], nxt)

    all_perms = []
    dfs(nums, [])
    return all_perms
</code>```

答:
In this example, why does this generate the correct result:

```<code>nxt = path + [nums[i]]
</code>```

This leaves path unmodified.

But not:

```<code>nxt = path ; nxt += [nums[i]]
</code>```

```<code>nxt = path ; nxt.append(nums[i])
</code>```

This appends nums[i] to path which is apparently incorrect.

ContentLicense: CC BY-SA 4.0

Body:
In this example, why does this generate the correct result:

nxt = path + [nums[i]]

But not:

nxt = path ; nxt += [nums[i]]

nxt = path ; nxt.append(nums[i])

def permute(nums):
    def dfs(nums, path):
      if not nums: # empty, done with path
          all_perms.append(path)
          return

      for i in range(len(nums)):
        nxt = path + [nums[i]]
        # nxt = path ; nxt += [nums[i]]
        # nxt = path ; nxt.append(nums[i])
        print(nxt)
        dfs(nums[:i] + nums[i+1:], nxt)

    all_perms = []
    dfs(nums, [])
    return all_perms

Body:
In this example, why does this generate the correct result:

nxt = path + [nums[i]]

This leaves path unmodified.

But not:

nxt = path ; nxt += [nums[i]]

nxt = path ; nxt.append(nums[i])

This appends nums[i] to path which is apparently incorrect.


问:
Is a "const member function" checked at compile time or runtime?
I am wondering when the checking for a const member function happens? I guess it happens at compile time, but cannot be sure.
Does anyone know?

答: A const member function is checked at compile time.

ContentLicense: CC BY-SA 3.0


问:
variables don't update after inheriting from subclass
Lets say I'm working on the following code in Kotlin:

```<code>class Human(var head: Head, var body: Body, var legs: Legs) {
   var height = this.head.length + this.body.length + this.legs.length
}

class Head(var length: Int) { }

class Body(var length: Int) { }

class Legs(var length: Int) { }
</code>```

Why is the correct height Human.height -> x returned on initialization but does not update if changes are made to the individual parts? Is my formatting for using these subclasses even correct? I have found some documentation on proper subclass usage but I haven't yet found a structure that matches the use case I have. Thanks in advance!

答:
You're not implementing a getter, you simply calculate and assign height value when your Human is initialized.

What you're looking for is getter implementation:

```<code>class Human(var head: Head, var body: Body, var legs: Legs) {
    val height
      get() = this.head.length + this.body.length + this.legs.length
}
</code>```

Body:
Lets say I'm working on the following code in Kotlin:

class Human(var head: Head, var body: Body, var legs: Legs) {
   var height = this.head.length + this.body.length + this.legs.length
}

class Head(var length: Int) { }

class Body(var length: Int) { }

class Legs(var length: Int) { }

Why is the correct height Human.height -> x returned on initialization but does not update if changes are made to the individual parts? Is my formatting for using these subclasses even correct? I have found some documentation on proper subclass usage but I haven't yet found a structure that matches the use case I have. Thanks in advance!

Body:
You're not implementing a getter, you simply calculate and assign height value when your Human is initialized.

What you're looking for is getter implementation:

class Human(var head: Head, var body: Body, var legs: Legs) {
    val height
      get() = this.head.length + this.body.length + this.legs.length
}


问:
How to represent scalar variables over geographic map in Jupyter Notebook
I am representing some geographical data in a Jupyter notebook: temperature, ocean wave height, etc. I have numpy arrays that have the latitude, longitude, and value for those variables. I would like to display these variables over a geographical map, preferably using ipyleaflet (because that is what I am already using). I am trying to get a result similar to a heatmap.

I tried to use the ipyleaflet Heatmap, but it seems to me that it is designed to represent agregation of points and not scalar uniform arrays, because I can't get it to show the results properly. I think ipyleaflet may lack a function to represent this kind of data, but seems odd since it has a very nice Velocity funtion to represent vectorial variables.

The only way I can think of to make this would be to generate an image with matplotlib and then adding it to the map in an  image layer, but I feel like that is not the proper way to do it.

答:
As you say, you can generate an image and overlay it onto the map. This is the suggestion I was given when I asked about this on Github.

There's an example notebook here.
Not quite as easy as matplotlib, but you get all the nice interactivity of ipyleaflet!

Here's the current version of the notebook in case the link changes (converted to markdown via jupyter-nbconvert --to markdown Numpy.ipynb)

From NumPy to Leaflet

This notebook shows how to display some raster geographic data in IPyLeaflet. The data is a NumPy array, which means that you have all the power of the Python scientific stack at your disposal to process it.

The following libraries are needed:
* requests
* tqdm
* rasterio
* numpy
* scipy
* pillow
* matplotlib
* ipyleaflet

The recommended way is to try to conda install them first, and if they are not found then pip install.

import requests
import os
from tqdm import tqdm
import zipfile
import rasterio
from affine import Affine
import numpy as np
import scipy.ndimage
from rasterio.warp import reproject, Resampling
import PIL
import matplotlib.pyplot as plt
from base64 import b64encode
try:
    from StringIO import StringIO
    py3 = False
except ImportError:
    from io import StringIO, BytesIO
    py3 = True
from ipyleaflet import Map, ImageOverlay, basemap_to_tiles, basemaps
```

<p>Download a raster file representing the flow accumulation for South America. This gives an idea of the river network.</p>

<pre class="lang-py prettyprint-override"><code>url = 'https://edcintl.cr.usgs.gov/downloads/sciweb1/shared/hydrosheds/sa_30s_zip_grid/sa_acc_30s_grid.zip'
filename = os.path.basename(url)
name = filename[:filename.find('_grid')]
adffile = name + '/' + name + '/w001001.adf'

if not os.path.exists(adffile):
    r = requests.get(url, stream=True)
    with open(filename, 'wb') as f:
        total_length = int(r.headers.get('content-length'))
        for chunk in tqdm(r.iter_content(chunk_size=1024), total=(total_length/1024) + 1):
            if chunk:
                f.write(chunk)
                f.flush()
    zip = zipfile.ZipFile(filename)
    zip.extractall('.')
</code>```

We transform the data a bit so that rivers appear thicker.

dataset = rasterio.open(adffile)
acc_orig = dataset.read()[0]
acc = np.where(acc_orig<0, 0, acc_orig)

shrink = 1 # if you are out of RAM try increasing this number (should be a power of 2)
radius = 5 # you can play with this number to change the width of the rivers
circle = np.zeros((2*radius+1, 2*radius+1)).astype('uint8')
y, x = np.ogrid[-radius:radius+1,-radius:radius+1]
index = x**2 + y**2 <= radius**2
circle[index] = 1
acc = np.sqrt(acc)
acc = scipy.ndimage.maximum_filter(acc, footprint=circle)
acc[acc_orig<0] = np.nan
acc = acc[::shrink, ::shrink]
```

<p>The original data is in the WGS 84 projection, but Leaflet uses Web Mercator, so we need to reproject.</p>

<pre class="lang-py prettyprint-override"><code># At this point if GDAL complains about not being able to open EPSG support file gcs.csv, try in the terminal:
# export GDAL_DATA=`gdal-config --datadir`

with rasterio.Env():
    rows, cols = acc.shape
    src_transform = list(dataset.transform)
    src_transform[0] *= shrink
    src_transform[4] *= shrink
    src_transform = Affine(*src_transform[:6])
    src_crs = {'init': 'EPSG:4326'}
    source = acc

    dst_crs = {'init': 'EPSG:3857'}
    dst_transform, width, height = rasterio.warp.calculate_default_transform(src_crs, dst_crs, cols, rows, *dataset.bounds)
    dst_shape = height, width

    destination = np.zeros(dst_shape)

    reproject(
        source,
        destination,
        src_transform=src_transform,
        src_crs=src_crs,
        dst_transform=dst_transform,
        dst_crs=dst_crs,
        resampling=Resampling.nearest)

acc_web = destination
</code>```

Let's convert our NumPy array to an image. For that we must specify a colormap (here plt.cm.jet).

acc_norm = acc_web - np.nanmin(acc_web)
acc_norm = acc_norm / np.nanmax(acc_norm)
acc_norm = np.where(np.isfinite(acc_web), acc_norm, 0)
acc_im = PIL.Image.fromarray(np.uint8(plt.cm.jet(acc_norm)*255))
acc_mask = np.where(np.isfinite(acc_web), 255, 0)
mask = PIL.Image.fromarray(np.uint8(acc_mask), mode='L')
im = PIL.Image.new('RGBA', acc_norm.shape[::-1], color=None)
im.paste(acc_im, mask=mask)
```

<p>The image is embedded in the URL as a PNG file, so that it can be sent to the browser.</p>

<pre class="lang-py prettyprint-override"><code>if py3:
    f = BytesIO()
else:
    f = StringIO()
im.save(f, 'png')
data = b64encode(f.getvalue())
if py3:
    data = data.decode('ascii')
imgurl = 'data:image/png;base64,' + data

Not quite as easy as matplotlib, but you get all the nice interactivity of ipyleaflet!
</code>```

Finally we can overlay our image and if everything went fine it should be exactly over South America.

b = dataset.bounds
bounds = [(b.bottom, b.left), (b.top, b.right)]
io = ImageOverlay(url=imgurl, bounds=bounds)
```

<pre class="lang-py prettyprint-override"><code>center = [-10, -60]
zoom = 2
m = Map(center=center, zoom=zoom, interpolation='nearest')
m
</code>```

tile = basemap_to_tiles(basemaps.Esri.WorldStreetMap)
m.add_layer(tile)
```

<p>You can play with the opacity slider and check that rivers from our data file match the rivers on OpenStreetMap.</p>

<pre class="lang-py prettyprint-override"><code>m.add_layer(io)
io.interact(opacity=(0.0,1.0,0.01))
</code>```

Body:
As you say, you can generate an image and overlay it onto the map. This is the suggestion I was given when I asked about this on Github.

There's an example notebook here.
Not quite as easy as matplotlib, but you get all the nice interactivity of ipyleaflet!

Here's the current version of the notebook in case the link changes (converted to markdown via jupyter-nbconvert --to markdown Numpy.ipynb)

From NumPy to Leaflet

This notebook shows how to display some raster geographic data in IPyLeaflet. The data is a NumPy array, which means that you have all the power of the Python scientific stack at your disposal to process it.

The following libraries are needed:
* requests
* tqdm
* rasterio
* numpy
* scipy
* pillow
* matplotlib
* ipyleaflet

The recommended way is to try to conda install them first, and if they are not found then pip install.

import requests
import os
from tqdm import tqdm
import zipfile
import rasterio
from affine import Affine
import numpy as np
import scipy.ndimage
from rasterio.warp import reproject, Resampling
import PIL
import matplotlib.pyplot as plt
from base64 import b64encode
try:
    from StringIO import StringIO
    py3 = False
except ImportError:
    from io import StringIO, BytesIO
    py3 = True
from ipyleaflet import Map, ImageOverlay, basemap_to_tiles, basemaps

Download a raster file representing the flow accumulation for South America. This gives an idea of the river network.

url = 'https://edcintl.cr.usgs.gov/downloads/sciweb1/shared/hydrosheds/sa_30s_zip_grid/sa_acc_30s_grid.zip'
filename = os.path.basename(url)
name = filename[:filename.find('_grid')]
adffile = name + '/' + name + '/w001001.adf'

if not os.path.exists(adffile):
    r = requests.get(url, stream=True)
    with open(filename, 'wb') as f:
        total_length = int(r.headers.get('content-length'))
        for chunk in tqdm(r.iter_content(chunk_size=1024), total=(total_length/1024) + 1):
            if chunk:
                f.write(chunk)
                f.flush()
    zip = zipfile.ZipFile(filename)
    zip.extractall('.')

We transform the data a bit so that rivers appear thicker.

dataset = rasterio.open(adffile)
acc_orig = dataset.read()[0]
acc = np.where(acc_orig<0, 0, acc_orig)

shrink = 1 # if you are out of RAM try increasing this number (should be a power of 2)
radius = 5 # you can play with this number to change the width of the rivers
circle = np.zeros((2*radius+1, 2*radius+1)).astype('uint8')
y, x = np.ogrid[-radius:radius+1,-radius:radius+1]
index = x**2 + y**2 <= radius**2
circle[index] = 1
acc = np.sqrt(acc)
acc = scipy.ndimage.maximum_filter(acc, footprint=circle)
acc[acc_orig<0] = np.nan
acc = acc[::shrink, ::shrink]

The original data is in the WGS 84 projection, but Leaflet uses Web Mercator, so we need to reproject.

# At this point if GDAL complains about not being able to open EPSG support file gcs.csv, try in the terminal:
# export GDAL_DATA=`gdal-config --datadir`

with rasterio.Env():
    rows, cols = acc.shape
    src_transform = list(dataset.transform)
    src_transform[0] *= shrink
    src_transform[4] *= shrink
    src_transform = Affine(*src_transform[:6])
    src_crs = {'init': 'EPSG:4326'}
    source = acc

    dst_crs = {'init': 'EPSG:3857'}
    dst_transform, width, height = rasterio.warp.calculate_default_transform(src_crs, dst_crs, cols, rows, *dataset.bounds)
    dst_shape = height, width

    destination = np.zeros(dst_shape)

    reproject(
        source,
        destination,
        src_transform=src_transform,
        src_crs=src_crs,
        dst_transform=dst_transform,
        dst_crs=dst_crs,
        resampling=Resampling.nearest)

acc_web = destination

Let's convert our NumPy array to an image. For that we must specify a colormap (here plt.cm.jet).

acc_norm = acc_web - np.nanmin(acc_web)
acc_norm = acc_norm / np.nanmax(acc_norm)
acc_norm = np.where(np.isfinite(acc_web), acc_norm, 0)
acc_im = PIL.Image.fromarray(np.uint8(plt.cm.jet(acc_norm)*255))
acc_mask = np.where(np.isfinite(acc_web), 255, 0)
mask = PIL.Image.fromarray(np.uint8(acc_mask), mode='L')
im = PIL.Image.new('RGBA', acc_norm.shape[::-1], color=None)
im.paste(acc_im, mask=mask)

The image is embedded in the URL as a PNG file, so that it can be sent to the browser.

if py3:
    f = BytesIO()
else:
    f = StringIO()
im.save(f, 'png')
data = b64encode(f.getvalue())
if py3:
    data = data.decode('ascii')
imgurl = 'data:image/png;base64,' + data

Not quite as easy as matplotlib, but you get all the nice interactivity of ipyleaflet!

Finally we can overlay our image and if everything went fine it should be exactly over South America.

b = dataset.bounds
bounds = [(b.bottom, b.left), (b.top, b.right)]
io = ImageOverlay(url=imgurl, bounds=bounds)

center = [-10, -60]
zoom = 2
m = Map(center=center, zoom=zoom, interpolation='nearest')
m

tile = basemap_to_tiles(basemaps.Esri.WorldStreetMap)
m.add_layer(tile)

You can play with the opacity slider and check that rivers from our data file match the rivers on OpenStreetMap.

m.add_layer(io)
io.interact(opacity=(0.0,1.0,0.01))


问:
What's the best way to avoid many if statements in Angular component to call specific function?
I'm creating a temperature conversion app in Angular 7, in my formGroup I have an input/output value, and 2 multi selects where the user can select a unit of temperature 'From' and 'To' to convert(celsius, Fahrenheit or Kelvin).

When the user submit the form in my component I get the input data

```<code>submitForm(data) {
    this.input = data.input;
    this.unitInput= data.unitInput;
    this.unitTarget= data.unitTarget;
    this.output= data.output;
  }
</code>```

I thought in just adding if statements to call the function that will make the conversion, but now looking at all if statements that i have seems a lot and not a good design.

```<code>if (this.inputUnit === 'Celsius' && this.targetUnit === 'Fahrenheit') {
        this.celsiusToFahrenheitConversion ();
}
if (this.inputUnit === 'Celsius' && this.targetUnit === 'Kelvin') {
      this.celsiusToKelvinConversion ();
}
if (this.inputUnit === 'Celsius' && this.targetUnit === 'Rankine') {
      this.celsiusToRankineConversion ();
}
</code>```

If's for Fahrenheit, If's for Kelvin, If's for Rankine, etc..
and what about if in the feature I want to add a different kind of unit?
What would be a better approach?

Thanks in advance

答:
I think the cleanest way to handle this would be using a switch statement. It doesn't get simpler than that, I personally hate it as well but sometimes there is just no way around it really.

```<code>switch(this.inputType) {
  case 'Celsius':
    switch(this.targetUnit) {
      case 'Fahrenheit':
        this.celsiusToFahrenheitConversion();
        break;
      case 'Kelvin':
        this.celsiusToKelvinConversion();
        break;
      case 'Rankine':
        this.celsiusToRankineConversion();
        break;
    }
    break;
  case 'Fahrenheit':
    break;
  case 'Rankine':
    break;
  case 'Kelvin':
    break;
}
</code>```

However! This is a mathematical conversion. F° to C° (32°F − 32) × 5/9, F° to Kelvin is (32°F − 32) × 5/9 + 273.15, F° to Rankine is 32°F + 459.67 and so on. And where is math, there is a system. My approach would be creating a conversion table - an object, and use the form values as lookup values. For example:

```<code>const magicalLookupTable = {
  celsius: {
    fahrenheit: () => {
      /** Implementation */
    },
    kelvin: () => {
      /** Implementation */
    }
  },
  fahrenheit: {
    celsius: () => {
      /** Implementation */
    },
    kelvin: () => {
      /** Implementation */
    }
  }
}
</code>```

Body:
I'm creating a temperature conversion app in Angular 7, in my formGroup I have an input/output value, and 2 multi selects where the user can select a unit of temperature 'From' and 'To' to convert(celsius, Fahrenheit or Kelvin).

When the user submit the form in my component I get the input data

submitForm(data) {
    this.input = data.input;
    this.unitInput= data.unitInput;
    this.unitTarget= data.unitTarget;
    this.output= data.output;
  }

I thought in just adding if statements to call the function that will make the conversion, but now looking at all if statements that i have seems a lot and not a good design.

if (this.inputUnit === 'Celsius' && this.targetUnit === 'Fahrenheit') {
        this.celsiusToFahrenheitConversion ();
}
if (this.inputUnit === 'Celsius' && this.targetUnit === 'Kelvin') {
      this.celsiusToKelvinConversion ();
}
if (this.inputUnit === 'Celsius' && this.targetUnit === 'Rankine') {
      this.celsiusToRankineConversion ();
}

If's for Fahrenheit, If's for Kelvin, If's for Rankine, etc..
and what about if in the feature I want to add a different kind of unit?
What would be a better approach?

Thanks in advance

Body:
I think the cleanest way to handle this would be using a switch statement. It doesn't get simpler than that, I personally hate it as well but sometimes there is just no way around it really.

switch(this.inputType) {
  case 'Celsius':
    switch(this.targetUnit) {
      case 'Fahrenheit':
        this.celsiusToFahrenheitConversion();
        break;
      case 'Kelvin':
        this.celsiusToKelvinConversion();
        break;
      case 'Rankine':
        this.celsiusToRankineConversion();
        break;
    }
    break;
  case 'Fahrenheit':
    break;
  case 'Rankine':
    break;
  case 'Kelvin':
    break;
}

However! This is a mathematical conversion. F° to C° (32°F − 32) × 5/9, F° to Kelvin is (32°F − 32) × 5/9 + 273.15, F° to Rankine is 32°F + 459.67 and so on. And where is math, there is a system. My approach would be creating a conversion table - an object, and use the form values as lookup values. For example:

const magicalLookupTable = {
  celsius: {
    fahrenheit: () => {
      /** Implementation */
    },
    kelvin: () => {
      /** Implementation */
    }
  },
  fahrenheit: {
    celsius: () => {
      /** Implementation */
    },
    kelvin: () => {
      /** Implementation */
    }
  }
}


问:
Create a timestamp in a specific cell in Google Sheets
I'm trying to create a timestamp in a Google Sheet when a specific cell is edited. I need the timestamp to be added to cell B2 when cell A3 is edited. I also need the timestamp to be written as uppercase (in the format of 'FEBRUARY 20'). I have amended the date format in Google Sheets so it is displayed as month then year, but it also needs capitalising (Google Sheets is automatically formatting as 'February 20'). The code I have is</p>

```<code>function onEdit(e) {

addTimestamp(e);

}

function addTimestamp(e){
//variables
var startRow = 3;
var targetColumn = 1;
var ws = "template";

//get modified row and column
var row = e.range.getRow();
var col = e.range.getColumn();

if(col === targetColumn && row >= startRow && e.source.getActiveSheet().getName() === ws){

var currentDate = new Date();

e.source.getActiveSheet().getRange(1,2).setValue(currentDate);
if(e.source.getActiveSheet().getRange(row,3),getValue() == ""){
  e.source.getActiveSheet().getRange(row,3).setValue(currentDate);
} //END IF check if date created exists
} //END IF check column, row, worksheet
} //END function addTimestamp
</code>```

答:
Try this:</p>

```<code>function onEdit(e) {
  //e.source.toast('Entry');
  var sh=e.range.getSheet();
  if(sh.getName()!='************Your sheet name here*********')return;
  if(e.range.columnStart==1 && e.range.rowStart==3) {
    var M=['JANUARY','FEBRUARY','MARCH','APRIL','MAY','JUNE','JULY','AUGUST','SEPTEMBER','OCTOBER','NOVEMBER','DECEMBER'];
    //e.source.toast('Flag1');
    var ts= M[new Date().getMonth()] + " " + new Date().getDate();
    //e.source.toast(ts);
    sh.getRange(2,2).setValue(ts);
  }
}
</code>```

Body:
I'm trying to create a timestamp in a Google Sheet when a specific cell is edited. I need the timestamp to be added to cell B2 when cell A3 is edited. I also need the timestamp to be written as uppercase (in the format of 'FEBRUARY 20'). I have amended the date format in Google Sheets so it is displayed as month then year, but it also needs capitalising (Google Sheets is automatically formatting as 'February 20'). The code I have is

function onEdit(e) {

addTimestamp(e);

}

function addTimestamp(e){
//variables
var startRow = 3;
var targetColumn = 1;
var ws = "template";

//get modified row and column
var row = e.range.getRow();
var col = e.range.getColumn();

if(col === targetColumn && row >= startRow && e.source.getActiveSheet().getName() === ws){

var currentDate = new Date();

e.source.getActiveSheet().getRange(1,2).setValue(currentDate);
if(e.source.getActiveSheet().getRange(row,3),getValue() == ""){
  e.source.getActiveSheet().getRange(row,3).setValue(currentDate);
} //END IF check if date created exists
} //END IF check column, row, worksheet
} //END function addTimestamp

Body:
Try this:

function onEdit(e) {
  //e.source.toast('Entry');
  var sh=e.range.getSheet();
  if(sh.getName()!='************Your sheet name here*********')return;
  if(e.range.columnStart==1 && e.range.rowStart==3) {
    var M=['JANUARY','FEBRUARY','MARCH','APRIL','MAY','JUNE','JULY','AUGUST','SEPTEMBER','OCTOBER','NOVEMBER','DECEMBER'];
    //e.source.toast('Flag1');
    var ts= M[new Date().getMonth()] + " " + new Date().getDate();
    //e.source.toast(ts);
    sh.getRange(2,2).setValue(ts);
  }
}


问:
Setting value to nested object not working in angular
I'm new to Angular and TypeScript so appologies if this is a stupid question. I'm trying to save the value of a returned object to a nested property in an object of type any. However, its not allowing me so could anyone enlighten me on my error.

```<code>  sharedData:any;

  constructor(private menuService: MenuService) { }

  addToBasket(item:any): void {
    this.sharedData.basketList.push(item);
  }

  ngOnInit() {
    this.sharedData.menu = this.menuService.getMenu();
  }
</code>```

It works fine when I have it as this.menu = this.menuService.getMenu();

答:
sharedData is not initialized with anything. from your code I would expect it to be

```<code> sharedData:any = {
  basketList: []
 };
</code>```

at least the lines you provided would run well and data would be stored in sharedData

Body:
I'm new to Angular and TypeScript so appologies if this is a stupid question. I'm trying to save the value of a returned object to a nested property in an object of type any. However, its not allowing me so could anyone enlighten me on my error.

  sharedData:any;

  constructor(private menuService: MenuService) { }

  addToBasket(item:any): void {
    this.sharedData.basketList.push(item);
  }

  ngOnInit() {
    this.sharedData.menu = this.menuService.getMenu();
  }

It works fine when I have it as this.menu = this.menuService.getMenu();

Body:
sharedData is not initialized with anything. from your code I would expect it to be

 sharedData:any = {
  basketList: []
 };

at least the lines you provided would run well and data would be stored in sharedData


答:
It happens at compile time. In C++ almost all the type checking is done at compile time. The only exception to this is when you use dynamic_cast.

So your const member function is checked at compile time.

Title: Is a "const member function" checked at compile time or runtime?

Body:
I am wondering when the checking for a const member function happens? I guess it happens at compile time, but cannot be sure.
Does anyone know?


问:
How to delete an element from a Slice in Golang
```<code>fmt.Println("Enter position to delete::")
fmt.Scanln(&pos)

new_arr := make([]int, (len(arr) - 1))
k := 0
for i := 0; i < (len(arr) - 1); {
    if i != pos {
        new_arr[i] = arr[k]
        k++
        i++
    } else {
        k++
    }
}

for i := 0; i < (len(arr) - 1); i++ {
    fmt.Println(new_arr[i])
}
</code>```

I am using this command to delete an element from a Slice but it is not working, please suggest.

答:
Maybe this code will help.

It deletes item with a given index.

Takes the array, and the index to delete and returns a new array pretty much like append function.

```<code>func deleteItem(arr []int, index int) []int{
  if index < 0 || index >= len(arr){
    return []int{-1}
  }

    for i := index; i < len(arr) -1; i++{
      arr[i] = arr[i + 1]

    }

    return arr[:len(arr)-1]
}
</code>```

Here you can play with the code : https://play.golang.org/p/aX1Qj40uTVs

Body:
fmt.Println("Enter position to delete::")
fmt.Scanln(&pos)

new_arr := make([]int, (len(arr) - 1))
k := 0
for i := 0; i < (len(arr) - 1); {
    if i != pos {
        new_arr[i] = arr[k]
        k++
        i++
    } else {
        k++
    }
}

for i := 0; i < (len(arr) - 1); i++ {
    fmt.Println(new_arr[i])
}

I am using this command to delete an element from a Slice but it is not working, please suggest.

Body:
Maybe this code will help.

It deletes item with a given index.

Takes the array, and the index to delete and returns a new array pretty much like append function.

func deleteItem(arr []int, index int) []int{
  if index < 0 || index >= len(arr){
    return []int{-1}
  }

    for i := index; i < len(arr) -1; i++{
      arr[i] = arr[i + 1]

    }

    return arr[:len(arr)-1]
}

Here you can play with the code : https://play.golang.org/p/aX1Qj40uTVs


问:
CSS Style in React
I don't know why my input element doesn't change color when hovering

```<code><input
                    id='running'
                    className={filterButtonsSytles.button}
                    style={{backgroundColor: this.state.running  ? 'grey':'white'}}
                    type="button"
                    value="Bieganie"
                    onClick={(e)=>this.clickHandler(e)}
                />
</code>```

css

```<code>.button {
    border: 1px solid black;
    cursor: pointer;
}

.button:hover {
    background-color: grey;
}
</code>```

答:
You have to give !important flag on hover because your style in in react element is inline style  and inline style does not let override by any external css

To make this right

```<code>.button:hover {
background-color: grey!important;
}
</code>```

To make it more precise !important is not recommended . you should be using classes for this.

Title: CSS Style in React

Body:
I don't know why my input element doesn't change color when hovering

<input
                    id='running'
                    className={filterButtonsSytles.button}
                    style={{backgroundColor: this.state.running  ? 'grey':'white'}}
                    type="button"
                    value="Bieganie"
                    onClick={(e)=>this.clickHandler(e)}
                />

css

.button {
    border: 1px solid black;
    cursor: pointer;
}

.button:hover {
    background-color: grey;
}

Body:
You have to give !important flag on hover because your style in in react element is inline style  and inline style does not let override by any external css

To make this right

.button:hover {
background-color: grey!important;
}

To make it more precise !important is not recommended . you should be using classes for this.


问:
Running an echo server as a daemon process for testing in python
I want to automate testing of an instrument and wrote a little server program to imitate the instrument which will send back the command except when it receives a special command "*IDN?". When I ran the echo server directly in its own script, and then run a client script separately, everything works great, and I am getting back the expected results. Now I wanted to run the server directly from the testing script. So I thought I would start it using multiprocessing. But the problem seems to be when the server socket gets to the s.accept() line it just waits there and never returns. So how do I accomplish automated testing if I cannot run this server in the same code as the test function?</p>

```<code>import socket
import multiprocessing as mp
import time,sys

HOST = '127.0.0.1'  # Standard loopback interface address (localhost),
PORT = 65432        # Port to listen on (non-privileged ports are > 1023),
FTP_PORT = 63217    # Port for ftp testing, change to 21 for device

def handle_connection(conn,addr):
    with conn:
        conn.send('Connected by', addr)
        print("Got connection")
        data = conn.recv(1024)
        if not data:
            return 'Nodata'
        elif (data == b'*IDN?\n'):
            print('SONY/TEK,AWG520,0,SCPI:95.0 OS:3.0 USR:4.0\n')
            conn.sendall(b'SONY/TEK,AWG520,0,SCPI:95.0 OS:3.0 USR:4.0\n')
            return 'IDN'
        else:
            conn.sendall(data)
            return 'Data'

def echo_server(c_conn,host=HOST,port=PORT):
    # this server simulates the AWG command protocol, simply echoing the command back except for IDN?
    p = mp.current_process()
    print('Starting echo server:', p.name, p.pid)
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.bind((host, port))
        s.listen()
        try:
            while True:
                print("Waiting for connection...")
                c_conn.send('waiting for connection...')
                conn, addr = s.accept()
                handle_connection(conn,addr)
                c_conn.send('serving client...')
        finally:
            conn.close()
            c_conn.send('done')
            time.sleep(2)
            print('Exiting echo server:', p.name, p.pid)
            sys.stdout.flush()

def test_echo_server():
    print("entering client part")
    with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as mysock:
        mysock.connect((HOST,PORT))
        mysock.sendall('test\n'.encode())
        data = mysock.recv(1024)
    print('received:',repr(data))

if __name__ == '__main__':
    parent_conn, child_conn = mp.Pipe()
    echo_demon = mp.Process(name='echo', target=echo_server(child_conn, ))
    echo_demon.daemon = True
    echo_demon.start()
    time.sleep(1)
    echo_demon.join(1)
    test_echo_server()
    if parent_conn.poll(1):
        print(parent_conn.recv())
    else:
        print('Waiting for echo server')

</code>```

答:
I managed to solve my own question using some code snippets I found in the book "Getting started with Python" by Romano, Baka, and Phillips. here is the code for the server:

```<code>with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind((HOST, PORT))
    s.listen()
    try:
        while True:
            print("Waiting for connection...")
            client, addr = s.accept()

            with client:
                data = client.recv(1024)
                if not data:
                    break
                elif (data == b'*IDN?\n'):
                    client.sendall(b'SONY/TEK,AWG520,0,SCPI:95.0 OS:3.0 USR:4.0\n')
                else:
                    client.sendall(data)
    finally:
        time.sleep(1)
        print('Exiting echo server:')

</code>```

and here is the code for the testing file which runs this server in a separate process, and a couple of simple tests:

```<code>@pytest.fixture(scope="session")
def awgserver():
    print("loading server")
    p = subprocess.Popen(["python3", "server.py"])
    time.sleep(1)
    yield p
    p.terminate()

@pytest.fixture
def clientsocket(request):
    print("entering client part")
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as mysock:
        mysock.connect((HOST, PORT))
        yield mysock
        mysock.close()

@pytest.mark.run_this
def test_echo(awgserver, clientsocket):
    clientsocket.send(b"*IDN?\n")
    #assert clientsocket.recv(1024) == b"SONY/TEK,AWG520,0,SCPI:95.0 OS:3.0 USR:4.0\n"
    assert clientsocket.recv(10) == b"TEK" # deliberately make test fail

@pytest.mark.run_this
def test_echo2(awgserver, clientsocket):
    clientsocket.send(b"def")
    assert clientsocket.recv(3) == b"def"
</code>```

Set HOST  to loopback IP, and PORT to > 1024

Body:
I want to automate testing of an instrument and wrote a little server program to imitate the instrument which will send back the command except when it receives a special command "*IDN?". When I ran the echo server directly in its own script, and then run a client script separately, everything works great, and I am getting back the expected results. Now I wanted to run the server directly from the testing script. So I thought I would start it using multiprocessing. But the problem seems to be when the server socket gets to the s.accept() line it just waits there and never returns. So how do I accomplish automated testing if I cannot run this server in the same code as the test function?

import socket
import multiprocessing as mp
import time,sys

HOST = '127.0.0.1'  # Standard loopback interface address (localhost),
PORT = 65432        # Port to listen on (non-privileged ports are > 1023),
FTP_PORT = 63217    # Port for ftp testing, change to 21 for device

def handle_connection(conn,addr):
    with conn:
        conn.send('Connected by', addr)
        print("Got connection")
        data = conn.recv(1024)
        if not data:
            return 'Nodata'
        elif (data == b'*IDN?\n'):
            print('SONY/TEK,AWG520,0,SCPI:95.0 OS:3.0 USR:4.0\n')
            conn.sendall(b'SONY/TEK,AWG520,0,SCPI:95.0 OS:3.0 USR:4.0\n')
            return 'IDN'
        else:
            conn.sendall(data)
            return 'Data'

def echo_server(c_conn,host=HOST,port=PORT):
    # this server simulates the AWG command protocol, simply echoing the command back except for IDN?
    p = mp.current_process()
    print('Starting echo server:', p.name, p.pid)
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.bind((host, port))
        s.listen()
        try:
            while True:
                print("Waiting for connection...")
                c_conn.send('waiting for connection...')
                conn, addr = s.accept()
                handle_connection(conn,addr)
                c_conn.send('serving client...')
        finally:
            conn.close()
            c_conn.send('done')
            time.sleep(2)
            print('Exiting echo server:', p.name, p.pid)
            sys.stdout.flush()

def test_echo_server():
    print("entering client part")
    with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as mysock:
        mysock.connect((HOST,PORT))
        mysock.sendall('test\n'.encode())
        data = mysock.recv(1024)
    print('received:',repr(data))

if __name__ == '__main__':
    parent_conn, child_conn = mp.Pipe()
    echo_demon = mp.Process(name='echo', target=echo_server(child_conn, ))
    echo_demon.daemon = True
    echo_demon.start()
    time.sleep(1)
    echo_demon.join(1)
    test_echo_server()
    if parent_conn.poll(1):
        print(parent_conn.recv())
    else:
        print('Waiting for echo server')

Body:
I managed to solve my own question using some code snippets I found in the book "Getting started with Python" by Romano, Baka, and Phillips. here is the code for the server:

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind((HOST, PORT))
    s.listen()
    try:
        while True:
            print("Waiting for connection...")
            client, addr = s.accept()

            with client:
                data = client.recv(1024)
                if not data:
                    break
                elif (data == b'*IDN?\n'):
                    client.sendall(b'SONY/TEK,AWG520,0,SCPI:95.0 OS:3.0 USR:4.0\n')
                else:
                    client.sendall(data)
    finally:
        time.sleep(1)
        print('Exiting echo server:')

and here is the code for the testing file which runs this server in a separate process, and a couple of simple tests:

@pytest.fixture(scope="session")
def awgserver():
    print("loading server")
    p = subprocess.Popen(["python3", "server.py"])
    time.sleep(1)
    yield p
    p.terminate()

@pytest.fixture
def clientsocket(request):
    print("entering client part")
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as mysock:
        mysock.connect((HOST, PORT))
        yield mysock
        mysock.close()

@pytest.mark.run_this
def test_echo(awgserver, clientsocket):
    clientsocket.send(b"*IDN?\n")
    #assert clientsocket.recv(1024) == b"SONY/TEK,AWG520,0,SCPI:95.0 OS:3.0 USR:4.0\n"
    assert clientsocket.recv(10) == b"TEK" # deliberately make test fail

@pytest.mark.run_this
def test_echo2(awgserver, clientsocket):
    clientsocket.send(b"def")
    assert clientsocket.recv(3) == b"def"

Set HOST  to loopback IP, and PORT to > 1024


问:
publicly accessible rds and public/private subnets
In AWS, if I have an RDS in a subnet that has had it's public accessibility feature turned off, do I need to worry about making its subnet private? If so, how would I go about making the subnet private? (assuming it was public beforehand)</p>

答:
The Publicly Accessible flag on an Amazon RDS database determines whether its DNS Name can be resolved outside of the VPC.

By setting Publicly Accessible = No, the database is unreachable from the Internet. However, if you wish to keep the database private, it is also advisable to modify the Security Group associated with the Amazon RDS instance to only permit access from the VPC or, preferably, only from the resources that need to access the database.

A further level of security can be obtained by putting the Amazon RDS database in a private subnet. This is an additional layer of security. It is not necessary to keep your database private (the above two methods are already doing that), but networking and security professionals like to keep most resources in a private subnet, and the only resources they put in a public subnet will be those that need to be accessible from the Internet (eg a Load Balancer or maybe a web server).

So, the choice is yours... you do not need to move it to a private subnet. It depends on your corporate security policies. But, at a minimum, do make sure it is locked-down via the Security Group.


答:
Your height variable has a backing field, which will be initialized to the value after the = sign. It will not be recomputed when you fetch it. So this Kotlin code will be equivalent to the follow Java code:

```<code>// Kotlin
var height = this.head.length + this.body.length + this.legs.length

// Java
// The backing field
private int height = this.head.length + this.body.length + this.legs.length

public int getHeight() {
    return height;
}

public void setHeight(int height) {
    this.height = height;
}
</code>```

What you really want is to recompute the value every time the get-method is called. Since you don't want to actually write to any height-field, you can use a val instead of a var. Like this:

```<code>// Kotlin
val height: Int
    get() = this.head.length + this.body.length + this.legs.length

// Which is equivalent to this Java code:
public int getHeight() {
    return this.head.length + this.body.length + this.legs.length;
}
</code>```

As you can see, the backing field will be gone because the value will be recomputed every time. There's also no setter, because we are now using a val.

Title: variables don't update after inheriting from subclass

Body:
Your height variable has a backing field, which will be initialized to the value after the = sign. It will not be recomputed when you fetch it. So this Kotlin code will be equivalent to the follow Java code:

// Kotlin
var height = this.head.length + this.body.length + this.legs.length

// Java
// The backing field
private int height = this.head.length + this.body.length + this.legs.length

public int getHeight() {
    return height;
}

public void setHeight(int height) {
    this.height = height;
}

What you really want is to recompute the value every time the get-method is called. Since you don't want to actually write to any height-field, you can use a val instead of a var. Like this:

// Kotlin
val height: Int
    get() = this.head.length + this.body.length + this.legs.length

// Which is equivalent to this Java code:
public int getHeight() {
    return this.head.length + this.body.length + this.legs.length;
}

As you can see, the backing field will be gone because the value will be recomputed every time. There's also no setter, because we are now using a val.


问:
Java Runtime crash when attempting to set JVM flags
I have a microservice (springboot) inside a docker container. I am also passing a long list of JVM flags so that the program runs on that VM environment to test the latency values with each flag combination.

I am using this command to start the container:

docker run --rm --name factorialorialContainer -p 8080:8080 -e
  JAVA_OPTIONS="$(cat
  /Users/sulekahelmini/Documents/fyp/fyp_work/MLscripts/flags.txt)"
  suleka96/factorial:latest

The flags.txt looks like this:

-XX:-ResizePLAB -XX:+ResizeOldPLAB -XX:+AlwaysPreTouch -XX:-ParallelRefProcEnabled -XX:-ParallelRefProcBalancingEnabled -XX:-UseTLAB -XX:-ResizeTLAB -XX:+ZeroTLAB -XX:+FastTLABRefill -XX:-UseAutoGCSelectPolicy -XX:-UseAdaptiveSizePolicy -XX:+UsePSAdaptiveSurvivorSizePolicy -XX:-UseAdaptiveGenerationSizePolicyAtMinorCollection -XX:+UseAdaptiveGenerationSizePolicyAtMajorCollection -XX:-UseAdaptiveSizePolicyWithSystemGC -XX:+UseAdaptiveGCBoundary -XX:+UseAdaptiveSizePolicyFootprintGoal -XX:YoungPLABSize=4354 -XX:OldPLABSize=1141 -XX:GCTaskTimeStampEntries=255 -XX:TargetPLABWastePct=5 -XX:PLABWeight=73 -XX:OldPLABWeight=21 -XX:MarkStackSize=5927008 -XX:MarkStackSizeMax=579749070 -XX:RefDiscoveryPolicy=1 -XX:InitiatingHeapOccupancyPercent=49 -XX:ErgoHeapSizeLimit=0 -XX:MaxRAMFraction=3 -XX:MinRAMFraction=3 -XX:InitialRAMFraction=74 -XX:AutoGCSelectPauseMillis=2934 -XX:AdaptiveSizeThroughPutPolicy=0 -XX:AdaptiveSizePausePolicy=0 -XX:AdaptiveSizePolicyInitializingSteps=24 -XX:AdaptiveSizePolicyOutputInterval=4060 -XX:AdaptiveSizePolicyWeight=11 -XX:AdaptiveTimeWeight=69 -XX:PausePadding=39200 -XX:PromotedPadding=3 -XX:SurvivorPadding=1 -XX:ThresholdTolerance=11 -XX:AdaptiveSizePolicyCollectionCostMargin=68 -XX:YoungGenerationSizeIncrement=28 -XX:YoungGenerationSizeSupplement=81 -XX:YoungGenerationSizeSupplementDecay=9 -XX:TenuredGenerationSizeIncrement=48 -XX:TenuredGenerationSizeSupplement=63 -XX:TenuredGenerationSizeSupplementDecay=2 -XX:MaxGCPauseMillis=16157174462788231168 -XX:GCPauseIntervalMillis=3009 -XX:GCTimeRatio=77 -XX:AdaptiveSizeDecrementScaleFactor=4 -XX:AdaptiveSizeMajorGCDecayTimeScale=9 -XX:MinSurvivorRatio=4 -XX:InitialSurvivorRatio=4 -XX:BaseFootPrintEstimate=463170010 -XX:GCHeapFreeLimit=4 -XX:ProcessDistributionStride=4 -Xms338224019 -Xmx1103493303

when I run the above-mentioned docker command I get the below error:

#

A fatal error has been detected by the Java Runtime Environment:

#

SIGSEGV (0xb) at pc=0x00007f9b014fe3c3, pid=1, tid=0x00007f9b10633b10

#

JRE version: OpenJDK Runtime Environment (8.0_212-b04) (build 1.8.0_212-b04)

Java VM: OpenJDK 64-Bit Server VM (25.212-b04 mixed mode linux-amd64 compressed oops)

Derivative: IcedTea 3.12.0

Distribution: Custom build (Sat May  4 17:33:35 UTC 2019)

Problematic frame:

j  java.net.URLStreamHandler.toExternalForm(Ljava/net/URL;)Ljava/lang/String;+88

#

Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again

#

An error report file with more information is saved as:

/usr/src/factorial/hs_err_pid1.log Compiled method (c1)    1054  256       1       java.net.URL::getRef (5 bytes)  total in heap

[0x00007f9b0166bad0,0x00007f9b0166bd60] = 656  relocation

  [0x00007f9b0166bbf8,0x00007f9b0166bc20] = 40  main code

  [0x00007f9b0166bc20,0x00007f9b0166bca0] = 128  stub code

  [0x00007f9b0166bca0,0x00007f9b0166bd30] = 144  scopes data

  [0x00007f9b0166bd30,0x00007f9b0166bd38] = 8  scopes pcs

  [0x00007f9b0166bd38,0x00007f9b0166bd58] = 32  dependencies

  [0x00007f9b0166bd58,0x00007f9b0166bd60] = 8
  #

If you would like to submit a bug report, please include

instructions on how to reproduce the bug and visit:

https://icedtea.classpath.org/bugzilla

#

What am I doing wrong here?

答:
It's -XX:+ZeroTLAB option which is broken. Just don't use this flag.

I guess a random option generator is involved here for the purpose of performance tuning. While the idea itself is fine, and there are known cases1,2 when Machine Learning with Bayesian Optimization helped to find better values of JVM options, the key point here is to include in the experiments only those options which meaning and implications you understand well.

Also the experiments should take care of the reasonable ranges of each option, as well as the mutual relationship between connected options.

However, the above option list looks totally random and does not make much sense (maybe, except for JVM testing). No surprise that such configuration may produce unpredictable results, including a JVM crash.

1 Automated Tuning of the JVM with Bayesian Optimization

2 Performance tuning Twitter services with Graal and Machine Learning


问:
Importing from directory gives ImportError
I have the following directory structure, in Ubuntu:

```<code>/Test/Foo
/Test/Foo/foo.py
</code>```

If I am in /Test, and I run python from the command line, followed by from Foo import foo, I get the following error: ImportError: No module named Foo.

But this is very confusing, since according to here, one of the directories used to search when importing is the directory from which the script was invoked. If I print out sys.path though, it does not include /Test, it just includes other standard Python directories.

Any idea what is going on?

答:
If I'm getting you right, what you are trying to achieve here is the Foo to be a package and foo be a module.

Since Foo is not made into a package (You don't have __init__.py in the directory), it is not recognized as a package and thus not imported.

When you move into /Test/Foo, then you are simply importing the module foo, which will work.

What you possibly need to do here is to create an __init__.py file inside /Test/Foo and then import the module from the package.

Or you can try relative imports. Something like from .Foo import foo.

Body:
I have the following directory structure, in Ubuntu:

/Test/Foo
/Test/Foo/foo.py

If I am in /Test, and I run python from the command line, followed by from Foo import foo, I get the following error: ImportError: No module named Foo.

But this is very confusing, since according to here, one of the directories used to search when importing is the directory from which the script was invoked. If I print out sys.path though, it does not include /Test, it just includes other standard Python directories.

Any idea what is going on?


问:
SwiftUI: How to Save value from a TextField in core data
I am building a very simple SwiftUI App, following a tutorial.
I created a View that contains a list of items which is @fetched from CoreData, and the list is shown with no problem.
Then I added a modal window with a TextField and a Button to save the data.
This is the code of the modal:

```<code>import SwiftUI

struct AddCategoryView: View {
    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
    @Environment(\.managedObjectContext) var context

    @State public var name: String = ""
    @State public var id = UUID()

    var body: some View {
        VStack {

            Button(action: {
               self.presentationMode.wrappedValue.dismiss()
            }) {
                Text("Close")
            }

            Text("Add a new Category")
                .font(.largeTitle)

            TextField("Enter category name", text: $name)
                .padding(.all)
                .textFieldStyle(RoundedBorderTextFieldStyle())

            Button(action: {
                let category = Category(context: self.context)
                category.name = self.name
                category.id = self.id
                do {
                    try self.context.save()
                } catch {
                    self.name = "There is an error!"
                }

            }) {
                Text("SAVE \(self.name)")
            }

        }
    }
}

struct AddCategoryView_Previews: PreviewProvider {
    static var previews: some View {
        AddCategoryView()
    }
}
</code>```

In this line,

```<code>Text("SAVE \(self.name)")
</code>```

I am printing (for debugging) the value of the variable name, and I can see that the variables changes to the value that is in the catch statement

```<code> self.name = "There is an error!"
</code>```

So I know that the saving is failing. But I have no idea why.

In the List View I have a button that will open this modal; I changed the value of this Button from

```<code>self.showAddModal.toggle()
</code>```

TO

```<code>let category = Category(context: self.context)
                category.name = "New Category"
                do {
                    try self.context.save()
                } catch {
                    self.name = "There is an error!"
                }
</code>```

And it works! I can see that the List View is updated with the value.
This is the code for the List View

```<code>struct CategoriesView: View {
    @Environment(\.managedObjectContext) var context
    @FetchRequest(entity: Category.entity(), sortDescriptors: []) var categories: FetchedResults<Category>
    @State private var showAddModal = false;
    @State public var name = ""
    var body: some View {
        VStack {
            Text("\(name)")
            List {
                ForEach(categories, id: \.id) { category in
                    VStack {
                        Text(category.name ?? "Unknown")
                    }
                }
            }

            Button(action: {
                let category = Category(context: self.context)
                category.name = "New Category"
                do {
                    try self.context.save()
                } catch {
                    self.name = "There is an error!"
                }

            }) {
                Text("+")
                    .font(.system(.largeTitle))
                    .fontWeight(.bold)
                    .foregroundColor(Color.white)
                    .multilineTextAlignment(.center)
                    .frame(width: 48, height: 48)
                    .background(Color.purple)
                    .cornerRadius(24)
                    .padding(.all)
                    .shadow(color: Color.black.opacity(0.3),
                            radius: 3,
                            x: 3,
                            y: 3)
            }.sheet(isPresented: $showAddModal) {
                AddCategoryView()
            }
        }
    }
}
struct CategoriesView_Previews: PreviewProvider {
    static var previews: some View {
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        return CategoriesView().environment(\.managedObjectContext, context)
    }
}
</code>```

I have spent the last 2 hours looking and googling for a solution, but I cannot find out what is wrong in my code. I also tried on the simulator but got the same error; I cannot save the core data from the TextField.

Thanks in advance!

答:
Ok I finally found the solution, which maybe is not the right one but at least it works.

```<code>.sheet(isPresented: $showAddModal) {
                AddCategoryView().environment(\.managedObjectContext, self.managedObjectContext)
            }
</code>```

Yep, just passing the Environment with the context to the Modal View fixed the issue. I am not sure this is the correct way to do it.

Body:
I am building a very simple SwiftUI App, following a tutorial.
I created a View that contains a list of items which is @fetched from CoreData, and the list is shown with no problem.
Then I added a modal window with a TextField and a Button to save the data.
This is the code of the modal:

import SwiftUI

struct AddCategoryView: View {
    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
    @Environment(\.managedObjectContext) var context

    @State public var name: String = ""
    @State public var id = UUID()

    var body: some View {
        VStack {

            Button(action: {
               self.presentationMode.wrappedValue.dismiss()
            }) {
                Text("Close")
            }

            Text("Add a new Category")
                .font(.largeTitle)

            TextField("Enter category name", text: $name)
                .padding(.all)
                .textFieldStyle(RoundedBorderTextFieldStyle())

            Button(action: {
                let category = Category(context: self.context)
                category.name = self.name
                category.id = self.id
                do {
                    try self.context.save()
                } catch {
                    self.name = "There is an error!"
                }

            }) {
                Text("SAVE \(self.name)")
            }

        }
    }
}

struct AddCategoryView_Previews: PreviewProvider {
    static var previews: some View {
        AddCategoryView()
    }
}

In this line,

Text("SAVE \(self.name)")

I am printing (for debugging) the value of the variable name, and I can see that the variables changes to the value that is in the catch statement

 self.name = "There is an error!"

So I know that the saving is failing. But I have no idea why.

In the List View I have a button that will open this modal; I changed the value of this Button from

self.showAddModal.toggle()

TO

let category = Category(context: self.context)
                category.name = "New Category"
                do {
                    try self.context.save()
                } catch {
                    self.name = "There is an error!"
                }

And it works! I can see that the List View is updated with the value.
This is the code for the List View

struct CategoriesView: View {
    @Environment(\.managedObjectContext) var context
    @FetchRequest(entity: Category.entity(), sortDescriptors: []) var categories: FetchedResults<Category>
    @State private var showAddModal = false;
    @State public var name = ""
    var body: some View {
        VStack {
            Text("\(name)")
            List {
                ForEach(categories, id: \.id) { category in
                    VStack {
                        Text(category.name ?? "Unknown")
                    }
                }
            }

            Button(action: {
                let category = Category(context: self.context)
                category.name = "New Category"
                do {
                    try self.context.save()
                } catch {
                    self.name = "There is an error!"
                }

            }) {
                Text("+")
                    .font(.system(.largeTitle))
                    .fontWeight(.bold)
                    .foregroundColor(Color.white)
                    .multilineTextAlignment(.center)
                    .frame(width: 48, height: 48)
                    .background(Color.purple)
                    .cornerRadius(24)
                    .padding(.all)
                    .shadow(color: Color.black.opacity(0.3),
                            radius: 3,
                            x: 3,
                            y: 3)
            }.sheet(isPresented: $showAddModal) {
                AddCategoryView()
            }
        }
    }
}
struct CategoriesView_Previews: PreviewProvider {
    static var previews: some View {
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        return CategoriesView().environment(\.managedObjectContext, context)
    }
}

I have spent the last 2 hours looking and googling for a solution, but I cannot find out what is wrong in my code. I also tried on the simulator but got the same error; I cannot save the core data from the TextField.

Thanks in advance!

Body:
Ok I finally found the solution, which maybe is not the right one but at least it works.

.sheet(isPresented: $showAddModal) {
                AddCategoryView().environment(\.managedObjectContext, self.managedObjectContext)
            }

Yep, just passing the Environment with the context to the Modal View fixed the issue. I am not sure this is the correct way to do it.


问:
The Calendar on Java doesn't working with "America/Santiago" DST timezone
I have a problem with Calendar object, it doesn't show correct offset on DST (Daily saving time) of America/Santiago timezone:
My Example Code:
    TimeZone fromTimeZone = TimeZone.getTimeZone("America/Santiago");

```<code>    // Get a Calendar instance using the default time zone and locale.
    Calendar calendar = Calendar.getInstance();

    // Set the calendar’s time with the given date
    calendar.setTimeZone(fromTimeZone);

    calendar.set(Calendar.YEAR, 2015); // 2015
     calendar.set(Calendar.MONTH, 2); // Mar
     calendar.set(Calendar.DATE, 31); // 31

    calendar.set(Calendar.HOUR_OF_DAY, 7);
    calendar.set(Calendar.MINUTE, 45);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);

    System.out.println("offset: " + fromTimeZone.getOffset(calendar.getTimeInMillis())/(TimeUnit.MINUTES.toMillis(1)*60));
</code>```

The output is: offset: -4
In the America/Santiago timezone at 3/31/2015, The offset should be -3.
(ref: http://www.timeanddate.com/worldclock/converted.html?iso=20150331T00&p1=218&p2=232)

Why did the calendar get correct offset on this case? I had test with other timezone, It works fine on the DST time.

Thank you.

答:
The other Answers are correct about you needing to keep your tzdata up-to-date in your JVM.

java.time

Also, you are using date-time classes that are now obsolete, supplanted by the modern java.time classes defined in JSR 310.

```<code>ZoneId z = ZoneId.of( "America/Santiago" ) ;
LocalDate ld = LocalDate.of( 2015 , Month.MARCH , 31 ) ;
LocalTime lt = LocalTime.of( 7 , 45 , 0 , 0 ) ;
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
</code>```

Adjust that moment into UTC. Same point on the timeline, different wall-clock time.

```<code>Instant instant = zdt.toInstant() ;
</code>```

Get the rules for that time zone, a ZoneRules object.

```<code>ZoneRules rules = z.getRules() ;
</code>```

Interrogate the rules. Get the offset-from-UTC in use at that moment, represented by ZoneOffset class.

```<code>ZoneOffset offset = rules.getOffset( instant ) ;
</code>```

Ask if Daylight Saving Time (DST) was in effect at that moment in that zone. Notice the common misspelling used by the Java team in naming this method (“Saving” should be singular).

```<code>boolean isDst = rules.isDaylightSavings( instant ) ;
</code>```

If in DST, get the amount of the DST adjustment as a Duration object. The Duration::toString method reports its value ( a number of hours, minutes, and seconds) in standard ISO 8601 format. For example, PT1H means 1 hour.

```<code>if( isDst ) {
    Duration d = getDaylightSavings( instant ) ;
}
</code>```

See this code run live at IdeOne.com.

zdt = 2015-03-31T07:45-03:00[America/Santiago]
instant = 2015-03-31T10:45:00Z
offset = -03:00
isDst = true
d = PT1H
```

Body:
I have a problem with Calendar object, it doesn't show correct offset on DST (Daily saving time) of America/Santiago timezone:
My Example Code:
    TimeZone fromTimeZone = TimeZone.getTimeZone("America/Santiago");

    // Get a Calendar instance using the default time zone and locale.
    Calendar calendar = Calendar.getInstance();

    // Set the calendar’s time with the given date
    calendar.setTimeZone(fromTimeZone);

    calendar.set(Calendar.YEAR, 2015); // 2015
     calendar.set(Calendar.MONTH, 2); // Mar
     calendar.set(Calendar.DATE, 31); // 31

    calendar.set(Calendar.HOUR_OF_DAY, 7);
    calendar.set(Calendar.MINUTE, 45);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);

    System.out.println("offset: " + fromTimeZone.getOffset(calendar.getTimeInMillis())/(TimeUnit.MINUTES.toMillis(1)*60));

The output is: offset: -4
In the America/Santiago timezone at 3/31/2015, The offset should be -3.
(ref: http://www.timeanddate.com/worldclock/converted.html?iso=20150331T00&p1=218&p2=232)

Why did the calendar get correct offset on this case? I had test with other timezone, It works fine on the DST time.

Thank you.

Body:
The other Answers are correct about you needing to keep your tzdata up-to-date in your JVM.

java.time

Also, you are using date-time classes that are now obsolete, supplanted by the modern java.time classes defined in JSR 310.

ZoneId z = ZoneId.of( "America/Santiago" ) ;
LocalDate ld = LocalDate.of( 2015 , Month.MARCH , 31 ) ;
LocalTime lt = LocalTime.of( 7 , 45 , 0 , 0 ) ;
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;

Adjust that moment into UTC. Same point on the timeline, different wall-clock time.

Instant instant = zdt.toInstant() ;

Get the rules for that time zone, a ZoneRules object.

ZoneRules rules = z.getRules() ;

Interrogate the rules. Get the offset-from-UTC in use at that moment, represented by ZoneOffset class.

ZoneOffset offset = rules.getOffset( instant ) ;

Ask if Daylight Saving Time (DST) was in effect at that moment in that zone. Notice the common misspelling used by the Java team in naming this method (“Saving” should be singular).

boolean isDst = rules.isDaylightSavings( instant ) ;

If in DST, get the amount of the DST adjustment as a Duration object. The Duration::toString method reports its value ( a number of hours, minutes, and seconds) in standard ISO 8601 format. For example, PT1H means 1 hour.

if( isDst ) {
    Duration d = getDaylightSavings( instant ) ;
}

See this code run live at IdeOne.com.

zdt = 2015-03-31T07:45-03:00[America/Santiago]
instant = 2015-03-31T10:45:00Z
offset = -03:00
isDst = true
d = PT1H


问:
Not able to read nested json array in SPLUNK
I am using "spath" to read json structure from a log file.

```<code>{"failure_reason":null,"gen_flag":"GENERATED","gen_date":"2020-02-15","siteid":"ABC","_action":"Change","order":"123"}
</code>```

I am able to parse above json.

However, "spath" function is not able to read nested array inside that json:

```<code>{"failure_reason":"[{"module":"Status Report","reason":"Status Report is not available","statusCode":"503"}]","gen_flag":"GENERATED_PARTIAL","gen_date":"2020-02-15","siteid":"ABC","_action":"Change","wonum":"321"}.
</code>```

please help!

答:
Your event is not valid JSON. A JSON array should not be surrounded by "s.

Copy your event into any of the following JSON validators, and confirm that it is incorrect.

https://jsonformatter.curiousconcept.com/

https://jsonlint.com/

https://jsonformatter.org/

Now, try with the corrected event.

```<code>{"failure_reason":[{"module":"Status Report","reason":"Status Report is not available","statusCode":"503"}],"gen_flag":"GENERATED_PARTIAL","gen_date":"2020-02-15","siteid":"ABC","_action":"Change","wonum":"321"}
</code>```

You can see that spath works correctly with the modified JSON with the following search.

```<code>| makeresults
| eval raw="{\"failure_reason\":[{\"module\":\"Status Report\",\"reason\":\"Status Report is not available\",\"statusCode\":\"503\"}],\"gen_flag\":\"GENERATED_PARTIAL\",\"gen_date\":\"2020-02-15\",\"siteid\":\"ABC\",\"_action\":\"Change\",\"wonum\":\"321\"}"
| spath input=raw
</code>```

If you need a way to pre-process your event to remove the "s from the array, you may be able to try the following, which may remove the extra "s. This is really dependent on the structure of the event, and may not be 100%, but should be enough to get you started. Try to fix the format of the event at the source.

```<code>| makeresults | eval raw="{\"failure_reason\":\"[{\"module\":\"Status Report\",\"reason\":\"Status Report is not available\",\"statusCode\":\"503\"}]\",\"gen_flag\":\"GENERATED_PARTIAL\",\"gen_date\":\"2020-02-15\",\"siteid\":\"ABC\",\"_action\":\"Change\",\"wonum\":\"321\"}"
| rex mode=sed field=raw "s/\"\[/[/" | rex mode=sed field=raw "s/\]\"/]/"
| spath input=raw
</code>```

Body:
I am using "spath" to read json structure from a log file.

{"failure_reason":null,"gen_flag":"GENERATED","gen_date":"2020-02-15","siteid":"ABC","_action":"Change","order":"123"}

I am able to parse above json.

However, "spath" function is not able to read nested array inside that json:

{"failure_reason":"[{"module":"Status Report","reason":"Status Report is not available","statusCode":"503"}]","gen_flag":"GENERATED_PARTIAL","gen_date":"2020-02-15","siteid":"ABC","_action":"Change","wonum":"321"}.

please help!

Body:
Your event is not valid JSON. A JSON array should not be surrounded by "s.

Copy your event into any of the following JSON validators, and confirm that it is incorrect.

https://jsonformatter.curiousconcept.com/

https://jsonlint.com/

https://jsonformatter.org/

Now, try with the corrected event.

{"failure_reason":[{"module":"Status Report","reason":"Status Report is not available","statusCode":"503"}],"gen_flag":"GENERATED_PARTIAL","gen_date":"2020-02-15","siteid":"ABC","_action":"Change","wonum":"321"}

You can see that spath works correctly with the modified JSON with the following search.

| makeresults
| eval raw="{\"failure_reason\":[{\"module\":\"Status Report\",\"reason\":\"Status Report is not available\",\"statusCode\":\"503\"}],\"gen_flag\":\"GENERATED_PARTIAL\",\"gen_date\":\"2020-02-15\",\"siteid\":\"ABC\",\"_action\":\"Change\",\"wonum\":\"321\"}"
| spath input=raw

If you need a way to pre-process your event to remove the "s from the array, you may be able to try the following, which may remove the extra "s. This is really dependent on the structure of the event, and may not be 100%, but should be enough to get you started. Try to fix the format of the event at the source.

| makeresults | eval raw="{\"failure_reason\":\"[{\"module\":\"Status Report\",\"reason\":\"Status Report is not available\",\"statusCode\":\"503\"}]\",\"gen_flag\":\"GENERATED_PARTIAL\",\"gen_date\":\"2020-02-15\",\"siteid\":\"ABC\",\"_action\":\"Change\",\"wonum\":\"321\"}"
| rex mode=sed field=raw "s/\"\[/[/" | rex mode=sed field=raw "s/\]\"/]/"
| spath input=raw


问:
Multiple Categorical Variables in a Column & The Prep
I have a survey data, with text answers, categorical variables, and numeric.

Converted into a dataframe in pandas, but the problem is multiple-choice columns, sometimes have more than 1 categorical variables, because the survey was designed as "choose all applies".

For example:

```<code>ID  Category    Num1 Num2 Num3
1   A, B, C     1    1    1
2   B, C, D     1    0    1
3   A, C        1    1    1
4   A           0    1    1
5   A, C, D     0    1    1
</code>```

I am trying to correlate these categories to the numerical variables.

Let's say the presence of A to value of Num1.

But when I use the dataframe, as it is, Python (and R) considers, for example [A, B, C] as another category, recognizes the whole cell as the category.

I think I need a method of parsing (exploding?) the value (in a hidden way), before feeding into a statistical analysis command.

How can I solve this problem?

答:
If you are willing to use tidyverse (or tidyr plus dplyr), I think you could use separate_rows. This will split up your categories, and then you can use pivot_wider to make additional columns for these categories.

```<code>library(tidyverse)

df %>%
  separate_rows(Category, sep = ",") %>%
  mutate(temp = TRUE) %>%
  pivot_wider(names_from = Category, values_from = temp, values_fill = list(temp = FALSE))
</code>```

Output

```<code># A tibble: 5 x 8
     ID  Num1  Num2  Num3 A     B     C     D
  <int> <int> <int> <int> <lgl> <lgl> <lgl> <lgl>
1     1     1     1     1 TRUE  TRUE  TRUE  FALSE
2     2     1     0     1 FALSE TRUE  TRUE  TRUE
3     3     1     1     1 TRUE  FALSE TRUE  FALSE
4     4     0     1     1 TRUE  FALSE FALSE FALSE
5     5     0     1     1 TRUE  FALSE TRUE  TRUE
</code>```

Body:
I have a survey data, with text answers, categorical variables, and numeric.

Converted into a dataframe in pandas, but the problem is multiple-choice columns, sometimes have more than 1 categorical variables, because the survey was designed as "choose all applies".

For example:

ID  Category    Num1 Num2 Num3
1   A, B, C     1    1    1
2   B, C, D     1    0    1
3   A, C        1    1    1
4   A           0    1    1
5   A, C, D     0    1    1

I am trying to correlate these categories to the numerical variables.

Let's say the presence of A to value of Num1.

But when I use the dataframe, as it is, Python (and R) considers, for example [A, B, C] as another category, recognizes the whole cell as the category.

I think I need a method of parsing (exploding?) the value (in a hidden way), before feeding into a statistical analysis command.

How can I solve this problem?

Body:
If you are willing to use tidyverse (or tidyr plus dplyr), I think you could use separate_rows. This will split up your categories, and then you can use pivot_wider to make additional columns for these categories.

library(tidyverse)

df %>%
  separate_rows(Category, sep = ",") %>%
  mutate(temp = TRUE) %>%
  pivot_wider(names_from = Category, values_from = temp, values_fill = list(temp = FALSE))

Output

# A tibble: 5 x 8
     ID  Num1  Num2  Num3 A     B     C     D
  <int> <int> <int> <int> <lgl> <lgl> <lgl> <lgl>
1     1     1     1     1 TRUE  TRUE  TRUE  FALSE
2     2     1     0     1 FALSE TRUE  TRUE  TRUE
3     3     1     1     1 TRUE  FALSE TRUE  FALSE
4     4     0     1     1 TRUE  FALSE FALSE FALSE
5     5     0     1     1 TRUE  FALSE TRUE  TRUE


问:
Okhttp3 Requestbody create() companion deprecated. Docs confusing
I have a glide module borrowed from a github repo. IDE says create() function is deprecated. But to me, okhttp docs seems confusing. Could anyone help changing this one into a valid one.

```<code>@GlideModule
class AppGlideModule : AppGlideModule()
const val MULTIPART_MEDIA_TYPE = "multipart/form-data"
const val IMAGE_MEDIA_TYPE = "image/*"
fun createRequestBody(s: String, type: String? = MULTIPART_MEDIA_TYPE): RequestBody {
    return RequestBody.create(MediaType.parse(type), s)
    }
}
</code>```

Thanks in advance

答:
Try this:</p>

```<code>fun createRequestBody(s: String, type: String? = MULTIPART_MEDIA_TYPE): RequestBody {
    return s.toRequestBody.create(MediaType.parse(type))
}
</code>```

Body:
I have a glide module borrowed from a github repo. IDE says create() function is deprecated. But to me, okhttp docs seems confusing. Could anyone help changing this one into a valid one.

@GlideModule
class AppGlideModule : AppGlideModule()
const val MULTIPART_MEDIA_TYPE = "multipart/form-data"
const val IMAGE_MEDIA_TYPE = "image/*"
fun createRequestBody(s: String, type: String? = MULTIPART_MEDIA_TYPE): RequestBody {
    return RequestBody.create(MediaType.parse(type), s)
    }
}

Thanks in advance

Body:
Try this:

fun createRequestBody(s: String, type: String? = MULTIPART_MEDIA_TYPE): RequestBody {
    return s.toRequestBody.create(MediaType.parse(type))
}


问:
Is there a way to copy BLOB records between databases in Oracle 10g?
We have a production table that has millions of rows in it and contains a BLOB field, I would like to copy a smaller selection of these records into our development database without getting a DBA involved if possible.  I tried the following COPY command but received a CPY-0012: Datatype cannot be copied

```<code>COPY FROM user/password@prod_db TO user/password@dev_db -
INSERT TABLE_A (COL1, COL2, COL3, BLOB_COL) USING -
SELECT COL1, COL2, COL3, BLOB_COL -
FROM TABLE_A WHERE COL1='KEY'
</code>```

Is there a way to copy records with a BLOB field between databases via SQL?

答: Oracle's Data Pump (started 10g+) supports moving BLOB data.</p>

Body:
We have a production table that has millions of rows in it and contains a BLOB field, I would like to copy a smaller selection of these records into our development database without getting a DBA involved if possible.  I tried the following COPY command but received a CPY-0012: Datatype cannot be copied

COPY FROM user/password@prod_db TO user/password@dev_db -
INSERT TABLE_A (COL1, COL2, COL3, BLOB_COL) USING -
SELECT COL1, COL2, COL3, BLOB_COL -
FROM TABLE_A WHERE COL1='KEY'

Is there a way to copy records with a BLOB field between databases via SQL?


问:
Change SwiftUI Text from UIViewController
I'm quite new to Swift and absolute new to SwiftUI.
I'm trying to combine UIViewController Google Maps and modern SwiftUI.
In SwiftUI i have a few Text objects, and I want my GmapsController class to be able to modify these Text values, and redraw SwiftUI struct.

My main struct:

```<code>var _swiftUIStruct : swiftUIStruct = swiftUIStruct() // to have access in GmapsController
struct GoogMapView: View {
    var body: some View {
        let gmap = GmapsControllerRepresentable()
        return  ZStack {
            gmap
            _swiftUIStruct
        }
    }
}
</code>```

UIViewControllerRepresentable wrapper of GmapsController :

```<code>struct GmapsControllerRepresentable: UIViewControllerRepresentable {
    func makeUIViewController(context: UIViewControllerRepresentableContext<GmapsControllerRepresentable>) -> GmapsController {
        return GmapsController()
    }
    func updateUIViewController(_ uiViewController: GmapsController, context: UIViewControllerRepresentableContext<GmapsControllerRepresentable>) {}
}
</code>```

The GmapsController itself:

```<code>class GmapsController: UIViewController, CLLocationManagerDelegate, GMSMapViewDelegate {
    var locationManager = CLLocationManager()
    var mapView: GMSMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        locationManager.requestWhenInUseAuthorization()
        locationManager.delegate = self

        let camera = GMSCameraPosition.camera(
            withLatitude: (locationManager.location?.coordinate.latitude)!,
            longitude: (locationManager.location?.coordinate.longitude)!,
            zoom: 15
        )

        mapView = GMSMapView.map(withFrame: view.bounds, camera: camera)
        mapView.delegate = self
        self.view = mapView
    }

// HERE I WANT TO CHANGE SOME swiftUIStruct Text FIELDS

// calls after map move
    func mapView(_ mapView: GMSMapView, idleAt сameraPosition: GMSCameraPosition) {
        _swiftUIStruct.someTxt = "I hope this will work" // compilation pass, but value doesn't change
    }
}
</code>```

And the swiftUIStruct struct:

```<code>struct swiftUIStruct {
    @State var someTxt = ""
    var body: some View {
        Text(someTxt) // THE TEXT I WISH I COULD CHANGE
    }
}
</code>```

Googling this a whole day just made me feel dumb, any help is appreciated.

答:
I hope my example code helps. Basically, move the model data outside, and pass it along, and change it. If you run this code, you will see the text "I hope this will work", NOT "Initial Content".

import SwiftUI

class ViewModel: ObservableObject {
  @Published var someTxt = "Initial Content"
}

struct ContentView: View {
  @ObservedObject var viewModel = ViewModel()

  var body: some View {
    ZStack {
      GoogleMapsView(viewModel: viewModel)
      Text(viewModel.someTxt)
    }
  }
}

struct GoogleMapsView: UIViewControllerRepresentable {
  var viewModel: ViewModel

  func makeUIViewController(context: Context) -> GmapsController {
    let controller = GmapsController()
    controller.viewModel = viewModel
    return controller
  }
  func updateUIViewController(_ uiViewController: GmapsController, context: Context) {}
}

class GmapsController: UIViewController {
  var viewModel: ViewModel?

  override func viewDidLoad() {
    viewModel?.someTxt = "I hope this will work"
  }
}

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    return ContentView()
  }
}
```

Body:
I'm quite new to Swift and absolute new to SwiftUI.
I'm trying to combine UIViewController Google Maps and modern SwiftUI.
In SwiftUI i have a few Text objects, and I want my GmapsController class to be able to modify these Text values, and redraw SwiftUI struct.

My main struct:

var _swiftUIStruct : swiftUIStruct = swiftUIStruct() // to have access in GmapsController
struct GoogMapView: View {
    var body: some View {
        let gmap = GmapsControllerRepresentable()
        return  ZStack {
            gmap
            _swiftUIStruct
        }
    }
}

UIViewControllerRepresentable wrapper of GmapsController :

struct GmapsControllerRepresentable: UIViewControllerRepresentable {
    func makeUIViewController(context: UIViewControllerRepresentableContext<GmapsControllerRepresentable>) -> GmapsController {
        return GmapsController()
    }
    func updateUIViewController(_ uiViewController: GmapsController, context: UIViewControllerRepresentableContext<GmapsControllerRepresentable>) {}
}

The GmapsController itself:

class GmapsController: UIViewController, CLLocationManagerDelegate, GMSMapViewDelegate {
    var locationManager = CLLocationManager()
    var mapView: GMSMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        locationManager.requestWhenInUseAuthorization()
        locationManager.delegate = self

        let camera = GMSCameraPosition.camera(
            withLatitude: (locationManager.location?.coordinate.latitude)!,
            longitude: (locationManager.location?.coordinate.longitude)!,
            zoom: 15
        )

        mapView = GMSMapView.map(withFrame: view.bounds, camera: camera)
        mapView.delegate = self
        self.view = mapView
    }

// HERE I WANT TO CHANGE SOME swiftUIStruct Text FIELDS

// calls after map move
    func mapView(_ mapView: GMSMapView, idleAt сameraPosition: GMSCameraPosition) {
        _swiftUIStruct.someTxt = "I hope this will work" // compilation pass, but value doesn't change
    }
}

And the swiftUIStruct struct:

struct swiftUIStruct {
    @State var someTxt = ""
    var body: some View {
        Text(someTxt) // THE TEXT I WISH I COULD CHANGE
    }
}

Googling this a whole day just made me feel dumb, any help is appreciated.


问:
How to seperate data from a file stream in c++
I just started learning c++ in college and for our first project we are asked to create a five function calculator (+, -, *, /, %) that reads input from a file, performs the arithmetic operation on it and outputs it to the screen. I am given an input file that as all the numbers like so :

```<code>/   100     10
109.5 +     1.0
25    /     2
25.5  /     2
0     /     0
8     *     8
10    -    10
ab    -    ab
100   -     1
10    *   -10
10.5  +  1000
1000  -  1.05
1000  *  1000
1000  /  1000
1000  /     0
</code>```

For my code, this is the best I have been able to come up with:

#include <iostream>
#include <string>
#include <fstream>
#include <sstream>

using namespace std;
const string file_name = "input.txt";

float calculate_number (float first_number, char symbol, float last_number);

int main () {
    ifstream input_file;
    ofstream output_file;

    // Open file to get input_file from
    input_file.open(file_name, ios::in);

    // Error checking
    if (!input_file) {
        cout << "Error: file input.txt does not exists\n";
        exit(1);
    } else {

        string data_from_file;           // Declare string to store data from file
        input_file >> data_from_file;    // Pass file content to data

        while (getline(input_file, data_from_file)) {
            istringstream ss(data_from_file);

            char symbol;
            int first_number, last_number;

            ss >> first_number >> symbol >> last_number;
            cout << first_number << symbol << last_number << endl;
        }
    }

    return 0;
}
```

<p>The above code gives the following output which is a mess, but still a huge step forward:</p>

```10010
109.5
25/2
25.5
0/0
8*8
10-10
0-10
100-1
10*-10
10.5
1000-1
1000*1000
1000/1000
1000/0

```

My question is, is their a way to separate each number and arithmetic operator from the input stream, add them together and display the output to the screen. Thanks in advance

答:
Your approach is basically not bad. However, you need to do a little bit more error checking. And there were also some semantic errors.

It is a very important rule that you always check there result of input/output operations.

I show you first a corrected version based on your original draft:

```<code>#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <cmath>

using namespace std;
const string file_name = "r:\\input.txt";

float calculate_number(float first_number, char symbol, float last_number) {
    float result{ 0 };
    switch (symbol) {
    case '+':
        result = first_number + last_number;
        break;
    case '-':
        result = first_number - last_number;
        break;
    case '*':
        result = first_number * last_number;
        break;
    case '/':
        result = first_number / last_number;
        break;
    case '%':
        result = fmod(first_number, last_number);
        break;
    default:
        break;
    }
    return result;
}

int main() {
    ifstream input_file;
    ofstream output_file;

    // Open file to get input_file from
    input_file.open(file_name, ios::in);

    // Error checking
    if (!input_file) {
        cout << "Error: file input.txt does not exists\n";
        exit(1);
    }
    else {

        string data_from_file;           // Declare string to store data from file
        //input_file >> data_from_file;    // Pass file content to data

        while (getline(input_file, data_from_file)) {
            istringstream ss(data_from_file);

            char symbol;
            float first_number, last_number;
            // Rad data and check, if that worked
            if (ss >> first_number >> symbol >> last_number) {
                // Check for a valid symbol
                if ((symbol == '+') || (symbol == '-') || (symbol == '*') || (symbol == '/') || (symbol == '%')) {
                    cout << first_number << " " << symbol << " " << last_number << " = "
                        << calculate_number(first_number, symbol, last_number) << endl;
                }
            }
        }
    }

    return 0;
}
</code>```

After learning more C++ you would use the below solution.

```<code>#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <numeric>
#include <map>
#include <utility>
#include <functional>

int main() {

    // All possible operations, defined in one place
    std::map<char, std::function<double(double,double)>> operation {
        {'+', std::plus<double>()},
        {'-', std::minus<double>()},
        {'*', std::multiplies<double>()},
        {'/', std::divides<double>()},
        {'%', static_cast<double(*)(double,double)>(std::fmod) }
    };

    // The file with the source data
    const std::string fileName{ "r:\\input.txt" };

    // Open the source file and check if it could be opened
    if (std::ifstream sourceStream(fileName); sourceStream) {

        // Read all lines of the source file
        for (std::string line{}; std::getline(sourceStream, line); ) {

            // For easier processing, put the line in a std::stringstream
            std::istringstream iss(line);

            // The operands and the operator
            double lhs{ 0.0 }, rhs{ 0.0 };
            char operationSymbol{};

            // Read the parts of the line and check, if read was OK
            if (iss >> lhs >> operationSymbol >> rhs) {

                // Now check, if we have read a valid operator
                if (operation.find(operationSymbol) != operation.end()) {

                    // Show the result
                    std::cout << lhs << " " << operationSymbol << " " << rhs << " = " << operation[operationSymbol](lhs, rhs) << "\n";
                }
                else std::cerr << "\n*** Error: Invalid operator '" << operationSymbol << "'\n\n";
            }
            else std::cerr << "\n*** Error: Problem while reading line:\n'" << line << "'\n\n";
        }
    }
    else std::cerr << "\n*** Error: Source file '" << fileName << "' could not be opened\n\n";

    return 0;
}
</code>```

I am sorry to say, but I would not recommend the answers from user Onyrew and Tijana, who is using even global variables. Sorry guys.

Body:
I just started learning c++ in college and for our first project we are asked to create a five function calculator (+, -, *, /, %) that reads input from a file, performs the arithmetic operation on it and outputs it to the screen. I am given an input file that as all the numbers like so :

/   100     10
109.5 +     1.0
25    /     2
25.5  /     2
0     /     0
8     *     8
10    -    10
ab    -    ab
100   -     1
10    *   -10
10.5  +  1000
1000  -  1.05
1000  *  1000
1000  /  1000
1000  /     0

For my code, this is the best I have been able to come up with:

#include <iostream>
#include <string>
#include <fstream>
#include <sstream>

using namespace std;
const string file_name = "input.txt";

float calculate_number (float first_number, char symbol, float last_number);

int main () {
    ifstream input_file;
    ofstream output_file;

    // Open file to get input_file from
    input_file.open(file_name, ios::in);

    // Error checking
    if (!input_file) {
        cout << "Error: file input.txt does not exists\n";
        exit(1);
    } else {

        string data_from_file;           // Declare string to store data from file
        input_file >> data_from_file;    // Pass file content to data

        while (getline(input_file, data_from_file)) {
            istringstream ss(data_from_file);

            char symbol;
            int first_number, last_number;

            ss >> first_number >> symbol >> last_number;
            cout << first_number << symbol << last_number << endl;
        }
    }

    return 0;
}

The above code gives the following output which is a mess, but still a huge step forward:

10010
109.5
25/2
25.5
0/0
8*8
10-10
0-10
100-1
10*-10
10.5
1000-1
1000*1000
1000/1000
1000/0

My question is, is their a way to separate each number and arithmetic operator from the input stream, add them together and display the output to the screen. Thanks in advance

Body:
Your approach is basically not bad. However, you need to do a little bit more error checking. And there were also some semantic errors.

It is a very important rule that you always check there result of input/output operations.

I show you first a corrected version based on your original draft:

#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <cmath>

using namespace std;
const string file_name = "r:\\input.txt";

float calculate_number(float first_number, char symbol, float last_number) {
    float result{ 0 };
    switch (symbol) {
    case '+':
        result = first_number + last_number;
        break;
    case '-':
        result = first_number - last_number;
        break;
    case '*':
        result = first_number * last_number;
        break;
    case '/':
        result = first_number / last_number;
        break;
    case '%':
        result = fmod(first_number, last_number);
        break;
    default:
        break;
    }
    return result;
}

int main() {
    ifstream input_file;
    ofstream output_file;

    // Open file to get input_file from
    input_file.open(file_name, ios::in);

    // Error checking
    if (!input_file) {
        cout << "Error: file input.txt does not exists\n";
        exit(1);
    }
    else {

        string data_from_file;           // Declare string to store data from file
        //input_file >> data_from_file;    // Pass file content to data

        while (getline(input_file, data_from_file)) {
            istringstream ss(data_from_file);

            char symbol;
            float first_number, last_number;
            // Rad data and check, if that worked
            if (ss >> first_number >> symbol >> last_number) {
                // Check for a valid symbol
                if ((symbol == '+') || (symbol == '-') || (symbol == '*') || (symbol == '/') || (symbol == '%')) {
                    cout << first_number << " " << symbol << " " << last_number << " = "
                        << calculate_number(first_number, symbol, last_number) << endl;
                }
            }
        }
    }

    return 0;
}

After learning more C++ you would use the below solution.

#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <numeric>
#include <map>
#include <utility>
#include <functional>

int main() {

    // All possible operations, defined in one place
    std::map<char, std::function<double(double,double)>> operation {
        {'+', std::plus<double>()},
        {'-', std::minus<double>()},
        {'*', std::multiplies<double>()},
        {'/', std::divides<double>()},
        {'%', static_cast<double(*)(double,double)>(std::fmod) }
    };

    // The file with the source data
    const std::string fileName{ "r:\\input.txt" };

    // Open the source file and check if it could be opened
    if (std::ifstream sourceStream(fileName); sourceStream) {

        // Read all lines of the source file
        for (std::string line{}; std::getline(sourceStream, line); ) {

            // For easier processing, put the line in a std::stringstream
            std::istringstream iss(line);

            // The operands and the operator
            double lhs{ 0.0 }, rhs{ 0.0 };
            char operationSymbol{};

            // Read the parts of the line and check, if read was OK
            if (iss >> lhs >> operationSymbol >> rhs) {

                // Now check, if we have read a valid operator
                if (operation.find(operationSymbol) != operation.end()) {

                    // Show the result
                    std::cout << lhs << " " << operationSymbol << " " << rhs << " = " << operation[operationSymbol](lhs, rhs) << "\n";
                }
                else std::cerr << "\n*** Error: Invalid operator '" << operationSymbol << "'\n\n";
            }
            else std::cerr << "\n*** Error: Problem while reading line:\n'" << line << "'\n\n";
        }
    }
    else std::cerr << "\n*** Error: Source file '" << fileName << "' could not be opened\n\n";

    return 0;
}

I am sorry to say, but I would not recommend the answers from user Onyrew and Tijana, who is using even global variables. Sorry guys.


问:
GET request to multiple pages of URL and 400 bad request
I am to get the data from this url: http://requests.task-sss.krasilnikov.spb.ru/data/9f66a575a6cfaaf7e43177317461d057 with a parameter page from 1 to 10 choosing the appropriate method from GET, POST, DELETE, PUT, OPTIONS. Tried this code to access the first page, but it didn't work:

```<code>import requests as rq
data_1 = rq.get('http://requests.task-sss.krasilnikov.spb.ru/data/9f66a575a6cfaaf7e43177317461d057/?page=1', params={'page': '1'})
data_1
</code>```

whatever I've tried - always getting 400 bad request in response.

答:
Your passing the GET parameters twice, which is likely resulting in a malformed URL. Try running</p>

```<code>import requests as rq
data_1 = rq.get(
    'http://requests.task-sss.krasilnikov.spb.ru/data/9f66a575a6cfaaf7e43177317461d057/',
    params={'page': '1'},
)
</code>```

Body:
I am to get the data from this url: http://requests.task-sss.krasilnikov.spb.ru/data/9f66a575a6cfaaf7e43177317461d057 with a parameter page from 1 to 10 choosing the appropriate method from GET, POST, DELETE, PUT, OPTIONS. Tried this code to access the first page, but it didn't work:

import requests as rq
data_1 = rq.get('http://requests.task-sss.krasilnikov.spb.ru/data/9f66a575a6cfaaf7e43177317461d057/?page=1', params={'page': '1'})
data_1

whatever I've tried - always getting 400 bad request in response.

Body:
Your passing the GET parameters twice, which is likely resulting in a malformed URL. Try running

import requests as rq
data_1 = rq.get(
    'http://requests.task-sss.krasilnikov.spb.ru/data/9f66a575a6cfaaf7e43177317461d057/',
    params={'page': '1'},
)