问:
Receving an attribute error for module in Lambda but not on local machine
I am trying to retrieve an object from S3 using boto3 as follows:

```<code>s3 = boto3.resource('s3')
    streaming_body = s3.Object(bucket_name=s3bucket,
                               key=documentPath
                               )

    body = {}
    body['filename'] = documentName
    body['file'] = streaming_body.get()['Body'].read()
</code>```

This works fine on my local machine in PyCharm. However, when I upload to Lambda and make an API call, the following error is returned:

```<code>Traceback (most recent call last):
'File "/var/task/s3getdocument.py", line 73, in lambda_handler
 body['file'] = streaming_body.get()['Body'].read()
 File "/opt/python/lib/python3.7/site-packages/boto3/resources/factory.py", line 520, in do_action
response = action(self, *args, **kwargs)
File "/opt/python/lib/python3.7/site-packages/boto3/resources/action.py", line 83, in __call__
response = getattr(parent.meta.client, operation_name)(**params)
File "/opt/python/lib/python3.7/site-packages/botocore/client.py", line 357, in _api_call
return self._make_api_call(operation_name, kwargs)
File "/opt/python/lib/python3.7/site-packages/botocore/client.py", line 648, in _make_api_call
operation_model, request_dict, request_context)
File "/opt/python/lib/python3.7/site-packages/botocore/client.py", line 667, in _make_request
return self._endpoint.make_request(operation_model, request_dict)
File "/opt/python/lib/python3.7/site-packages/botocore/endpoint.py", line 102, in make_request
return self._send_request(request_dict, operation_model)
File "/opt/python/lib/python3.7/site-packages/botocore/endpoint.py", line 135, in _send_request
request, operation_model, context)
File "/opt/python/lib/python3.7/site-packages/botocore/endpoint.py", line 167, in _get_response
request, operation_model)
File "/opt/python/lib/python3.7/site-packages/botocore/endpoint.py", line 218, in _do_get_response
response_dict, operation_model.output_shape)
File "/opt/python/lib/python3.7/site-packages/botocore/parsers.py", line 242, in parse
parsed = self._do_parse(response, shape)
File "/opt/python/lib/python3.7/site-packages/botocore/parsers.py", line 774, in _do_parse
member_shapes, final_parsed)
File "/opt/python/lib/python3.7/site-packages/botocore/parsers.py", line 833, in _parse_non_payload_attrs
member_shape, headers[header_name])
File "/opt/python/lib/python3.7/site-packages/botocore/parsers.py", line 302, in _parse_shape
return handler(shape, node)
File "/opt/python/lib/python3.7/site-packages/botocore/parsers.py", line 175, in _get_text_content
return func(self, shape, text)
File "/opt/python/lib/python3.7/site-packages/botocore/parsers.py", line 462, in _handle_timestamp
return self._timestamp_parser(text)
File "/opt/python/lib/python3.7/site-packages/botocore/utils.py", line 567, in parse_timestamp
return dateutil.parser.parse(value, tzinfos={'GMT': tzutc()})
File "/opt/python/lib/python3.7/site-packages/dateutil/parser/_parser.py", line 1358, in parse
return DEFAULTPARSER.parse(timestr, **kwargs)
File "/opt/python/lib/python3.7/site-packages/dateutil/parser/_parser.py", line 657, in parse
ret = self._build_tzaware(ret, res, tzinfos)
File "/opt/python/lib/python3.7/site-packages/dateutil/parser/_parser.py", line 1175, in _build_tzaware
aware = self._assign_tzname(aware, res.tzname)
File "/opt/python/lib/python3.7/site-packages/dateutil/parser/_parser.py", line 1238, in _assign_tzname
new_dt = tz.enfold(dt, fold=1)
AttributeError: module 'dateutil.tz' has no attribute 'enfold
</code>```

All modules are the same versions in the lambda as they are on my local machine. I am using the latest version of boto3 and botocore as of today (5/30).

Any advise on what the difference might be that would cause this?

答:
This worked perfectly fine for me (on a small file):

import boto3

s3bucket = 'my-bucket'
documentPath='foo.txt'

def lambda_handler(event, context):

    s3 = boto3.resource('s3')
    streaming_body = s3.Object(bucket_name=s3bucket,
                               key=documentPath
                               )

    body = {}
    body['filename'] = documentPath # Changed this
    body['file'] = streaming_body.get()['Body'].read()
    print(body['file'])
```

Body:
I am trying to retrieve an object from S3 using boto3 as follows:

s3 = boto3.resource('s3')
    streaming_body = s3.Object(bucket_name=s3bucket,
                               key=documentPath
                               )

    body = {}
    body['filename'] = documentName
    body['file'] = streaming_body.get()['Body'].read()

This works fine on my local machine in PyCharm. However, when I upload to Lambda and make an API call, the following error is returned:

Traceback (most recent call last):
'File "/var/task/s3getdocument.py", line 73, in lambda_handler
 body['file'] = streaming_body.get()['Body'].read()
 File "/opt/python/lib/python3.7/site-packages/boto3/resources/factory.py", line 520, in do_action
response = action(self, *args, **kwargs)
File "/opt/python/lib/python3.7/site-packages/boto3/resources/action.py", line 83, in __call__
response = getattr(parent.meta.client, operation_name)(**params)
File "/opt/python/lib/python3.7/site-packages/botocore/client.py", line 357, in _api_call
return self._make_api_call(operation_name, kwargs)
File "/opt/python/lib/python3.7/site-packages/botocore/client.py", line 648, in _make_api_call
operation_model, request_dict, request_context)
File "/opt/python/lib/python3.7/site-packages/botocore/client.py", line 667, in _make_request
return self._endpoint.make_request(operation_model, request_dict)
File "/opt/python/lib/python3.7/site-packages/botocore/endpoint.py", line 102, in make_request
return self._send_request(request_dict, operation_model)
File "/opt/python/lib/python3.7/site-packages/botocore/endpoint.py", line 135, in _send_request
request, operation_model, context)
File "/opt/python/lib/python3.7/site-packages/botocore/endpoint.py", line 167, in _get_response
request, operation_model)
File "/opt/python/lib/python3.7/site-packages/botocore/endpoint.py", line 218, in _do_get_response
response_dict, operation_model.output_shape)
File "/opt/python/lib/python3.7/site-packages/botocore/parsers.py", line 242, in parse
parsed = self._do_parse(response, shape)
File "/opt/python/lib/python3.7/site-packages/botocore/parsers.py", line 774, in _do_parse
member_shapes, final_parsed)
File "/opt/python/lib/python3.7/site-packages/botocore/parsers.py", line 833, in _parse_non_payload_attrs
member_shape, headers[header_name])
File "/opt/python/lib/python3.7/site-packages/botocore/parsers.py", line 302, in _parse_shape
return handler(shape, node)
File "/opt/python/lib/python3.7/site-packages/botocore/parsers.py", line 175, in _get_text_content
return func(self, shape, text)
File "/opt/python/lib/python3.7/site-packages/botocore/parsers.py", line 462, in _handle_timestamp
return self._timestamp_parser(text)
File "/opt/python/lib/python3.7/site-packages/botocore/utils.py", line 567, in parse_timestamp
return dateutil.parser.parse(value, tzinfos={'GMT': tzutc()})
File "/opt/python/lib/python3.7/site-packages/dateutil/parser/_parser.py", line 1358, in parse
return DEFAULTPARSER.parse(timestr, **kwargs)
File "/opt/python/lib/python3.7/site-packages/dateutil/parser/_parser.py", line 657, in parse
ret = self._build_tzaware(ret, res, tzinfos)
File "/opt/python/lib/python3.7/site-packages/dateutil/parser/_parser.py", line 1175, in _build_tzaware
aware = self._assign_tzname(aware, res.tzname)
File "/opt/python/lib/python3.7/site-packages/dateutil/parser/_parser.py", line 1238, in _assign_tzname
new_dt = tz.enfold(dt, fold=1)
AttributeError: module 'dateutil.tz' has no attribute 'enfold

All modules are the same versions in the lambda as they are on my local machine. I am using the latest version of boto3 and botocore as of today (5/30).

Any advise on what the difference might be that would cause this?


来源: stackexchange

问:
Suggestion about creating custom File Storage Service
In my project one of the services is a File Storage service with just 2 tasks: upload file and get an ID, download file by ID. Nothing else. No fancy stuff, like UI, encryption (HTTPS will suffice), 100% availability, deduplication, etc. Just 2 simple tasks.

Using ASP .Net Core this service takes half an hour to create and start using, since it will be used only in organization's local network.

But there are a few things i would like to consider before start:

Which Db engine?

How to store files?

While investigating, i came to 2 variants:

SQLite + storing files in subfolders like year/month/day/guid.bin. The database will contain full path to the file with an appropriate GUID.

LiteDB and store everything in it.

Pros of (1):

no file system trashing with a lot of files in one folder

simple file based DB with simple queries

Cons of (1):

not sure here, stability of DB perhaps? file corruption? any means of file integrity restoration?

usage of an SQL based engine where NO-SQL based would work better?

Pros of (2):

everything in one place (the files binary data with it's GUID)

Cons of (2):

everything in one place? in other words, a very-very large single file after some time. a small glitch in it and all gone, whereas when storing files in subfolders, it will be unlikely, that all of them will be corrupt (not accouting for complete hard drive failure).

Also, picking an embedded file-based database is forcing to use some manual backuping (third party service) and relying only on that. It makes things simple to develop and deploy (for example, files will always be in sync with database when backuping), but hard on the other end.

What would be the best choice? Or perhaps there are more better solutions? Perhaps a simple third-party service without a lot of bloating of functionality?

答:
Assuming multiple users will use the same database, I recommend using a database server (Sql Server / MongoDB) instead of a file-based database (SqlLite/LiteDb). Even if it's not a separate physical server, using technology designed to be accessed by multiple simultaneous clients will give you much better scalability. File-based databases are typically designed for single-user scenarios and will quickly become a bottleneck since only a single thread can access the file at a time.

Regarding whether to use Sql or NoSql - I recommend designing the code you write to minimize the cost of changing your mind. Your current list of requirements don't seem to benefit much from picking one over the other, and, in my personal experience, this situation typically leads to one of two outcomes:

the project is used in a limited capacity and the choice of technology didn't matter

the project is adopted widely, being used in ways we couldn't have anticipated, and now we're rushing to catch up

In either case, time spent up-front trying to decide doesn't do much good. That being said, it is still worthwhile to research up-front (as you have) since prior knowledge is an excellent tool for making good decisions while under time pressure.

Lastly, you didn't mention anything about security - if your organization has security experts I highly recommend working closely with them as you design the system. Arbitrary file uploads can be used as an attack vector, so validating the contents and destination of an upload is very important.

ContentLicense: CC BY-SA 4.0


问:
Acknowledge network parameter in Network map service
I'm developing a network map service, it has rest end-points as mentioned in the Corda network map(https://docs.corda.net/network-map.html). What is the need of POST '/network-map/ack-parameters'?
What should be the test file for testing this rest end-point?</p>

答:
When there is a change to the network-parameters of the network (for example, maxMessageSize or adding a new notary), the network of Corda nodes will need to accept the new network-parameters in order to continue transacting.  There is an updateDeadline which sets the deadline time when nodes must accept these new network-parameters by, before the new network-parameters are essentially enforced.

The endpoint /network-map/ack-parameters provides a way to accept the new network-parameters.  The payload would be the hash of the new network-parameters, which can be retrieved in 2 ways: either from the network operator OR from the Corda node crash shell, using the command run networkParametersFeed.

To note, this endpoint is the equivalent of using the Corda node crash shell command (with example hash):

```<code>run acceptNewNetworkParameters parametersHash: "ba19fc1b9e9c1c7cbea712efda5f78b53ae4e5d124c89d02c9da44ec50e9c17d"
</code>```

More information on flag days can be found here: https://docs.corda.net/network-map.html#manual-acceptance

Body:
When there is a change to the network-parameters of the network (for example, maxMessageSize or adding a new notary), the network of Corda nodes will need to accept the new network-parameters in order to continue transacting.  There is an updateDeadline which sets the deadline time when nodes must accept these new network-parameters by, before the new network-parameters are essentially enforced.

The endpoint /network-map/ack-parameters provides a way to accept the new network-parameters.  The payload would be the hash of the new network-parameters, which can be retrieved in 2 ways: either from the network operator OR from the Corda node crash shell, using the command run networkParametersFeed.

To note, this endpoint is the equivalent of using the Corda node crash shell command (with example hash):

run acceptNewNetworkParameters parametersHash: "ba19fc1b9e9c1c7cbea712efda5f78b53ae4e5d124c89d02c9da44ec50e9c17d"

More information on flag days can be found here: https://docs.corda.net/network-map.html#manual-acceptance


问:
is this correctly work on predict next value in keras?
here is my code

```<code>...
look_back = 20
train_size = int(len(data) * 0.80)
test_size = len(data) - train_size

train = data[0:train_size]
test = data[train_size:len(data)]
x_train, y_train = create_dataset(train, look_back)
x_test, y_test = create_dataset(test, look_back)

x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))
y_train=np.repeat(y_train.reshape(-1,1), 20, axis=1).reshape(-1,20,1)
y_test=np.repeat(y_test.reshape(-1,1), 20, axis=1).reshape(-1,20,1)
...
model = Sequential()

model.add(LSTM(512,  return_sequences=True))
model.add(Dropout(0.3))

model.add(LSTM(512,  return_sequences=True))
model.add(Dropout(0.3))

model.add(LSTM(1, return_sequences=True))

model.compile(loss='mean_squared_error', optimizer='rmsprop', metrics=['accuracy'])
model.summary()
model.fit(x_train, y_train, epochs=10, batch_size=64)
p = model.predict(x_test)
</code>```

and I want to predict the next value So,
predictions = model.predict(x_train) and shape is (62796, 20, 1)

and I coded the following site how to use the Keras model to forecast for future dates or events?

```<code>future = []
currentStep = predictions[-20:, :, :] # -20 is last look_back number

for i in range(10):
    currentStep = model.predict(currentStep)
    future.append(currentStep)
</code>```

in this code future's result is

but p = model.predict(x_test)'s [:4000] result is

The difference between the two results is very large.

is this right way to Predict the next value??

I don't know where it went wrong or the code went wrong.

I hope for your opinion.

full source is https://gist.github.com/Lay4U/654f70bd1fb9c4f7d5bdb21ddcb588ab

答:
There are multiple methods you can try. There is no one right way at the moment. You can train a seperate model for predicting t+1, t+2 ... t+n. One LSTM model predicts t+1 while another predicts t+n. That is called a DIRMO strategy.

Your strategy (recursive strategy) is particularly risky because the model can propagate the error through multiple time horizons.

You can find a good comparison of alternative strategies in this paper.
https://www.sciencedirect.com/science/article/pii/S0957417412000528?via%3Dihub

Body:
here is my code

...
look_back = 20
train_size = int(len(data) * 0.80)
test_size = len(data) - train_size

train = data[0:train_size]
test = data[train_size:len(data)]
x_train, y_train = create_dataset(train, look_back)
x_test, y_test = create_dataset(test, look_back)

x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))
y_train=np.repeat(y_train.reshape(-1,1), 20, axis=1).reshape(-1,20,1)
y_test=np.repeat(y_test.reshape(-1,1), 20, axis=1).reshape(-1,20,1)
...
model = Sequential()

model.add(LSTM(512,  return_sequences=True))
model.add(Dropout(0.3))

model.add(LSTM(512,  return_sequences=True))
model.add(Dropout(0.3))

model.add(LSTM(1, return_sequences=True))

model.compile(loss='mean_squared_error', optimizer='rmsprop', metrics=['accuracy'])
model.summary()
model.fit(x_train, y_train, epochs=10, batch_size=64)
p = model.predict(x_test)

and I want to predict the next value So,
predictions = model.predict(x_train) and shape is (62796, 20, 1)

and I coded the following site how to use the Keras model to forecast for future dates or events?

future = []
currentStep = predictions[-20:, :, :] # -20 is last look_back number

for i in range(10):
    currentStep = model.predict(currentStep)
    future.append(currentStep)

in this code future's result is

but p = model.predict(x_test)'s [:4000] result is

The difference between the two results is very large.

is this right way to Predict the next value??

I don't know where it went wrong or the code went wrong.

I hope for your opinion.

full source is https://gist.github.com/Lay4U/654f70bd1fb9c4f7d5bdb21ddcb588ab


问:
Strongly typed dataset using variables for column names
I am currently referencing a generic DataSet via an index and would like to convert this to a strongly-typed DataSet of the table type.  The issue is that my index to the DataRow is a variable.

Currently I am doing the following where the History_Column value is pulled from the database.

    e.Dr[c.History_Column.ToString()] = Entry;

I would like to define the DataRow ('Dr' in the example) as a type of the table so I can do something similar to the following:

    e.Dr.COLUMN_NAME = Entry;

How can I use dynamic variables in this fashion?

Thanks!

答:
You could use a dynamic type to get you part of the way there, but your goal sounds kind of contradictory.

```<code>dynamic Dr = new ExpandoObject();
Dr.whatever = 6;
Dr.anything = "asdf";
</code>```

If you use ExpandoObject with dynamic, you can assign any property.

ContentLicense: CC BY-SA 3.0

Body:
You could use a dynamic type to get you part of the way there, but your goal sounds kind of contradictory.

dynamic Dr = new ExpandoObject();
Dr.whatever = 6;
Dr.anything = "asdf";

If you use ExpandoObject with dynamic, you can assign any property.


问:
How to find list of missing characters in a column from another column
I have two tables. Tab_1.col_2 has characters and Tab2.col_2 has strings

```<code>Tab_1
col_1   col_2
1       A
2       B
3       C
4       N

Tab_2
col_1   col_2
101     CCNCCN
102     ABCNSN
103     TABGNN
</code>```

I want to be able to search Tab2.col_2 using Tab_1.col_2 and identify all the missing characters

There is no join condition available between these two table. I tried to substring each character on Tab_2.col_2 and then do a simple not in function.

Expected result:

I expect the output to give two characters that are missing from Tab_1.col_2 - T and G as two rows

```<code>Output:
T
G
</code>```

答:
This is only half an answer.

You can remove the unwanted characters by using translate()

```<code>select translate(t2.col_2, rem || ' ', ' ')
from (select listagg(col_2, '') within group (order by col_2) as rem
      from table_1
     ) t cross join
     table_2 t2;
</code>```

You can even aggregate these back together:

```<code>select listagg(translate(t2.col_2, rem || ' ', ' '), '') within group (order by rem)
from (select listagg(col_2, '') within group (order by col_2) as rem
      from table_1
     ) t cross join
     table_2 t2;
</code>```

Body:
I have two tables. Tab_1.col_2 has characters and Tab2.col_2 has strings

Tab_1
col_1   col_2
1       A
2       B
3       C
4       N

Tab_2
col_1   col_2
101     CCNCCN
102     ABCNSN
103     TABGNN

I want to be able to search Tab2.col_2 using Tab_1.col_2 and identify all the missing characters

There is no join condition available between these two table. I tried to substring each character on Tab_2.col_2 and then do a simple not in function.

Expected result:

I expect the output to give two characters that are missing from Tab_1.col_2 - T and G as two rows

Output:
T
G

Body:
This is only half an answer.

You can remove the unwanted characters by using translate()

select translate(t2.col_2, rem || ' ', ' ')
from (select listagg(col_2, '') within group (order by col_2) as rem
      from table_1
     ) t cross join
     table_2 t2;

You can even aggregate these back together:

select listagg(translate(t2.col_2, rem || ' ', ' '), '') within group (order by rem)
from (select listagg(col_2, '') within group (order by col_2) as rem
      from table_1
     ) t cross join
     table_2 t2;


问:
Bootstrap : Add a junction between div
I'm trying to add a junction (a line) between 2 divs in the middle.

```<code><div class="row">
<div class="col-xs-6 col-md-6">
    <div style="background-color:#f39a6f;width:100%;height:100px;">
    ....1
    </div>
</div>
<div class="col-xs-6 col-md-6">
    <div style="background-color:#ffff00;width:100%;height:100px;">
    ....2
    </div>
</div>
</code>```

Thanks for help.

答:
I don't believe you can have this and have your column sizes at 6 each.  I can think of 2 ways.  Make them 5 and use this. This comes from their documentation on the grid system.

https://getbootstrap.com/docs/4.0/layout/grid/

```<code><div class="row justify-content-between">
    <div class="col-5">
        One of two columns
    </div>
    <div class="col-5">
        One of two columns
    </div>
 </div>
</code>```

Or if you don't mind that junction being static width then you could do this. Effectively making the junction width static and each side equal in the remaining width.

```<code><div class="row">
    <div class="col">
        1 of 2
    </div>
    <div class="col-auto" style="width:30px"></div>
    <div class="col">
        2 of 2
    </div>
</div>
</code>```

Title: Bootstrap : Add a junction between div

Body:
I'm trying to add a junction (a line) between 2 divs in the middle.

    ....1

    ....2

Thanks for help.

Body:
I don't believe you can have this and have your column sizes at 6 each.  I can think of 2 ways.  Make them 5 and use this. This comes from their documentation on the grid system.

https://getbootstrap.com/docs/4.0/layout/grid/

<div class="row justify-content-between">
    <div class="col-5">
        One of two columns
    </div>
    <div class="col-5">
        One of two columns
    </div>
 </div>

Or if you don't mind that junction being static width then you could do this. Effectively making the junction width static and each side equal in the remaining width.

<div class="row">
    <div class="col">
        1 of 2
    </div>
    <div class="col-auto" style="width:30px"></div>
    <div class="col">
        2 of 2
    </div>
</div>


问:
ipython - get list of all kernels (user + default)
I am looking for a way to get a list (or dict) with the names of all installed ipython kernels in the systems programmatically (not via command line). So far I have this:

```<code>from jupyter_client.kernelspecapp import KernelSpecManager
print(KernelSpecManager().find_kernel_specs())
</code>```

or (but it gives a deprecation warning):

```<code>from IPython.kernel.kernelspec import find_kernel_specs
print(find_kernel_specs())
</code>```

There is also a way using ipykernel, but haven't found any docs.

All of the above give me a dictionary with the kernels I have installed using ipykernel, but not the default kernel (e.g. Python 3) which shows in the notebook:

```<code>{'lab2': '/home/alex/.local/share/jupyter/kernels/lab2',
 'lab3': '/home/alex/.local/share/jupyter/kernels/lab3',
 'python2': '/usr/local/share/jupyter/kernels/python2'}
</code>```

Is there a way to get the list of ALL kernels?

答:
When I follow a slightly different procedure than what you have above, I see a python3 kernel.  I'm doing the following with Jupyter 4.4.0 installed.

import jupyter_client
M = jupyter_client.kernelspec.KernelSpecManager()
M.find_kernel_specs()
```

<p>It outputs a dict, with content like the following.</p>

```{'javascript': '/Users/someone/Library/Jupyter/kernels/javascript', 'python3': '/anaconda3/share/jupyter/kernels/python3'}
```

Here's a link to the relevant docs.

Body:
I am looking for a way to get a list (or dict) with the names of all installed ipython kernels in the systems programmatically (not via command line). So far I have this:

from jupyter_client.kernelspecapp import KernelSpecManager
print(KernelSpecManager().find_kernel_specs())

or (but it gives a deprecation warning):

from IPython.kernel.kernelspec import find_kernel_specs
print(find_kernel_specs())

There is also a way using ipykernel, but haven't found any docs.

All of the above give me a dictionary with the kernels I have installed using ipykernel, but not the default kernel (e.g. Python 3) which shows in the notebook:

{'lab2': '/home/alex/.local/share/jupyter/kernels/lab2',
 'lab3': '/home/alex/.local/share/jupyter/kernels/lab3',
 'python2': '/usr/local/share/jupyter/kernels/python2'}

Is there a way to get the list of ALL kernels?

Body:
When I follow a slightly different procedure than what you have above, I see a python3 kernel.  I'm doing the following with Jupyter 4.4.0 installed.

import jupyter_client
M = jupyter_client.kernelspec.KernelSpecManager()
M.find_kernel_specs()

It outputs a dict, with content like the following.

{'javascript': '/Users/someone/Library/Jupyter/kernels/javascript', 'python3': '/anaconda3/share/jupyter/kernels/python3'}

Here's a link to the relevant docs.


问:
RadDataForm nativescript vue show/hide password
Have this part of code form:

```<code><RadDataForm id="loginForm" ref="loginForm" :source="user">
  <TKEntityProperty v-tkDataFormProperty name="password" displayName imageResource="res://lock" hintText="Password" index="0">
    <TKPropertyEditor v-tkEntityPropertyEditor type="Password">
      <TKPropertyEditorStyle v-tkPropertyEditorStyle labelWidth="4" />
    </TKPropertyEditor>
  </TKEntityProperty>
</RadDataForm>
</code>```

Need to append icon/image can tap to show/hide password

答:
If I'm not wrong, CustomPropertyEditor is not yet exposed as Vue directive in latest version of nativescript-ui-dataform plugin (as of today v4.0.0).

So you will have to register it first along with RadDataForm, may be something like

```<code>import Vue from 'nativescript-vue';
import * as RadDataFormModule from "nativescript-ui-dataform";

import RadDataForm from "nativescript-ui-dataform/vue";
Vue.use(RadDataForm);

Vue.registerElement("TKCustomPropertyEditor", function () {
    return RadDataFormModule.CustomPropertyEditor;
});
</code>```

Now simply use TKCustomPropertyEditor instead of TKPropertyEditor

```<code>        <TKEntityProperty v-tkDataFormProperty name="password">
            <TKCustomPropertyEditor v-tkEntityPropertyEditor
                @editorNeedsView="onPasswordEditorNeedsView">
            </TKCustomPropertyEditor>
        </TKEntityProperty>
</code>```

Now you can create and assign the view you like on the editorNeedsView event as described in the docs.

Body:
Have this part of code form:

<RadDataForm id="loginForm" ref="loginForm" :source="user">
  <TKEntityProperty v-tkDataFormProperty name="password" displayName imageResource="res://lock" hintText="Password" index="0">
    <TKPropertyEditor v-tkEntityPropertyEditor type="Password">
      <TKPropertyEditorStyle v-tkPropertyEditorStyle labelWidth="4" />
    </TKPropertyEditor>
  </TKEntityProperty>
</RadDataForm>

Need to append icon/image can tap to show/hide password

Body:
If I'm not wrong, CustomPropertyEditor is not yet exposed as Vue directive in latest version of nativescript-ui-dataform plugin (as of today v4.0.0).

So you will have to register it first along with RadDataForm, may be something like

import Vue from 'nativescript-vue';
import * as RadDataFormModule from "nativescript-ui-dataform";

import RadDataForm from "nativescript-ui-dataform/vue";
Vue.use(RadDataForm);

Vue.registerElement("TKCustomPropertyEditor", function () {
    return RadDataFormModule.CustomPropertyEditor;
});

Now simply use TKCustomPropertyEditor instead of TKPropertyEditor

        <TKEntityProperty v-tkDataFormProperty name="password">
            <TKCustomPropertyEditor v-tkEntityPropertyEditor
                @editorNeedsView="onPasswordEditorNeedsView">
            </TKCustomPropertyEditor>
        </TKEntityProperty>

Now you can create and assign the view you like on the editorNeedsView event as described in the docs.


问:
Not able to reset input field in laravel
I need to reset the input field when user clicks on the rest button, I have other content on the page which is getting cleared except input field, I'm not sure if this is happening because I'm using old values after post request.

```<code> <input type="text" name="app_number" class="form-control" onreset="this.value=''" value="{!! Request::input('app_number') !!}" id="app_number" placeholder="Application Number" required>
</code>```

JS for reset button:

```<code>document.getElementById("appForm").onreset = function() {
   document.getElementById("app_number").value = "";
  };
</code>```

Reset Button:

```<code><button class="btn btn-primary" id="reset-button" type="reset">Reset</button>
</code>```

答:
try using reset():
document.getElementById("app_number").reset();</p>

Body:
I need to reset the input field when user clicks on the rest button, I have other content on the page which is getting cleared except input field, I'm not sure if this is happening because I'm using old values after post request.

 <input type="text" name="app_number" class="form-control" onreset="this.value=''" value="{!! Request::input('app_number') !!}" id="app_number" placeholder="Application Number" required>

JS for reset button:

document.getElementById("appForm").onreset = function() {
   document.getElementById("app_number").value = "";
  };

Reset Button:

<button class="btn btn-primary" id="reset-button" type="reset">Reset</button>


问:
Azure Function v2 references a project with a higher version of Newtonsoft.Json than Microsoft.NET.Sdk.Functions
I am writing a v2 Azure Durable Function. When passing a C# object to a helper activity Function, I get a runtime error in my custom JsonConverterused in serializing the type being passed. The custom JsonConverter is in a library that must reference Newtonsoft.Json 12.x, while Microsoft.NET.Sdk.Functions is locked into 11.0.2.

jObject  error CS1705: Assembly 'ContractLibrary' with identity 'ContractLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' uses 'Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' which has a higher version than referenced assembly 'Newtonsoft.Json' with identity 'Newtonsoft.Json, Version=11.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'

I believe this GitHub Issue is relevant. This comment on that Issue seems to indicate that adding Newtonsoft.Json 12.x as a direct dependency of your Function project may help. This helped in another Function project, but now I have hit this wall again. Is there anything I can do to mitigate this?

答:
One thing you can try is to bypass the serialization logic used by Durable Functions and do your own serialization. For example, instead of doing this:

public static void MyFunc([ActivityTrigger] MyCustomType input)
{
    // ...
}
```

<p>Try doing this:</p>

<pre class="lang-cs prettyprint-override"><code>public static void MyFunc([ActivityTrigger] JObject json)
{
    // manually convert the JObect into MyCustomType
}
</code>```

Let me know if that gets you any further.

Body:
One thing you can try is to bypass the serialization logic used by Durable Functions and do your own serialization. For example, instead of doing this:

public static void MyFunc([ActivityTrigger] MyCustomType input)
{
    // ...
}

Try doing this:

public static void MyFunc([ActivityTrigger] JObject json)
{
    // manually convert the JObect into MyCustomType
}

Let me know if that gets you any further.


问:
Reordering Month and Year in formatted Fiscal Period column
I am trying to reorder a fiscal period column from alphabetical order to chronological order. That is, I have this column, which displays values as month-year (showing all distinct values in Query Editor):
 Period_Name Column

I would like to order this column chronologically, like this: JAN-18, FEB-18, MAR-18, APR-18, etc. in order to use it to plot a time series.

Right now if I try to change the column's data type in Query Editor to Date, it thinks that year is actually the day, and then assumes the year to be the current year (namely 2019); that is, APR-18 becomes April 18, 2019 instead of what it should be, April 2018, with no day (this is a fiscal period column). The custom date and time formats with the FORMAT function (https://learn.microsoft.com/en-us/dax/custom-date-and-time-formats-for-the-format-function) do not appear to recognize the current format that this column is in as month-year, and just spit out the same values back when I try to use it in a new calculated column.

Any help would be much appreciated!

答:
You should not change the datatype of Month-Year, instead sort the month-year column by another column, that could be of another datatype:
Go into the table/data view, click in the column to be sorted, click "sort by column" and then select the surrogate sort column

You should also start working with a related Calendar table to manage these type of sortings correctly.

For example in your calendar table you have two columns. Month-year that contains data like "Feb-2019" like you want to use, then another column called YearMonth that contain values like 201902 and is of type Int.

Then simply sort the Month-Year column based on the YearMonth column and it will be sorted correctly.


问:
Swiper renderExternal example in Virtual Slides with React
Need to render a Custom React component array as Virtual Slides using Swiper.

Document says renderExternal can be used for this but there's no example in the API doc http://idangero.us/swiper/api/#virtual

Need to know on how this can be done using renderExternal function.

答:
The documentation got updated and now you can find an example of how to use it with React. For reference, here is the example that is given:</p>

```<code>import React from 'react';
import Swiper from 'swiper/dist/js/swiper.esm.bundle';

export default class extends React.Component {
  constructor() {
    this.state = {
      // dummy slides data
      slides: (function () {
        var slides = [];
        for (var i = 0; i < 600; i += 1) {
          slides.push('Slide ' + (i + 1));
        }
        return slides;
      }()),
      // virtual data
      virtualData: {
        slides: [],
      },
    }
  }
  componentDidMount() {
    const self = this;
    const swiper = new Swiper('.swiper-container', {
      // ...
      virtual: {
        slides: self.state.slides,
        renderExternal(data) {
          // assign virtual slides data
          self.setState({
            virtualData: data,
          });
        }
      },
    });
  }
  render() {
    {/* ... */}
    <div className="swiper-container">
      <div className="swiper-wrapper">
        {/* It is important to set "left" style prop on every slide */}
        {this.state.virtualData.slides.map((slide, index) => (
          <div className="swiper-slide"
            key={index}
            style={{left: `${virtualData.offset}px`}}
          >{slide}</div>
        ))}
      </div>
    </div>
    {/* ... */}
  }
}
</code>```

Body:
The documentation got updated and now you can find an example of how to use it with React. For reference, here is the example that is given:

import React from 'react';
import Swiper from 'swiper/dist/js/swiper.esm.bundle';

export default class extends React.Component {
  constructor() {
    this.state = {
      // dummy slides data
      slides: (function () {
        var slides = [];
        for (var i = 0; i < 600; i += 1) {
          slides.push('Slide ' + (i + 1));
        }
        return slides;
      }()),
      // virtual data
      virtualData: {
        slides: [],
      },
    }
  }
  componentDidMount() {
    const self = this;
    const swiper = new Swiper('.swiper-container', {
      // ...
      virtual: {
        slides: self.state.slides,
        renderExternal(data) {
          // assign virtual slides data
          self.setState({
            virtualData: data,
          });
        }
      },
    });
  }
  render() {
    {/* ... */}
    <div className="swiper-container">
      <div className="swiper-wrapper">
        {/* It is important to set "left" style prop on every slide */}
        {this.state.virtualData.slides.map((slide, index) => (
          <div className="swiper-slide"
            key={index}
            style={{left: `${virtualData.offset}px`}}
          >{slide}</div>
        ))}
      </div>
    </div>
    {/* ... */}
  }
}


问:
What does the ! mean in the angular syntax?
I've been seeing this creep up in a few places now but have not found any answers on it.

I'm curious what the '!' bang does in the angular syntax.

答:
From the Angular documentation:

The non-null assertion operator ( ! )

As of Typescript 2.0, you can enforce strict null checking with the
--strictNullChecks flag. TypeScript then ensures that no variable is unintentionally null or undefined.

In this mode, typed variables disallow null and undefined by default.
The type checker throws an error if you leave a variable unassigned or
try to assign null or undefined to a variable whose type disallows
null and undefined.

The type checker also throws an error if it can't determine whether a
variable will be null or undefined at runtime. You may know that can't
happen but the type checker doesn't know. You tell the type checker
that it can't happen by applying the post-fix non-null assertion
operator (!).

The Angular non-null assertion operator (!) serves the same purpose in
an Angular template.

For example, after you use *ngIf to check that hero is defined, you
can assert that hero properties are also defined.

```<code><!-- No hero, no text -->
<div *ngIf="hero">
  The hero's name is {{hero!.name}}
</div>
</code>```

When the Angular compiler turns your template into TypeScript code, it
prevents TypeScript from reporting that hero.name might be null or
undefined.

Unlike the safe navigation operator, the non-null assertion operator
does not guard against null or undefined. Rather it tells the
TypeScript type checker to suspend strict null checks for a specific
property expression.

You'll need this template operator when you turn on strict null
checks. It's optional otherwise.

Body:
From the Angular documentation:

The non-null assertion operator ( ! )

As of Typescript 2.0, you can enforce strict null checking with the
--strictNullChecks flag. TypeScript then ensures that no variable is unintentionally null or undefined.

In this mode, typed variables disallow null and undefined by default.
The type checker throws an error if you leave a variable unassigned or
try to assign null or undefined to a variable whose type disallows
null and undefined.

The type checker also throws an error if it can't determine whether a
variable will be null or undefined at runtime. You may know that can't
happen but the type checker doesn't know. You tell the type checker
that it can't happen by applying the post-fix non-null assertion
operator (!).

The Angular non-null assertion operator (!) serves the same purpose in
an Angular template.

For example, after you use *ngIf to check that hero is defined, you
can assert that hero properties are also defined.

<!-- No hero, no text -->
<div *ngIf="hero">
  The hero's name is {{hero!.name}}
</div>

When the Angular compiler turns your template into TypeScript code, it
prevents TypeScript from reporting that hero.name might be null or
undefined.

Unlike the safe navigation operator, the non-null assertion operator
does not guard against null or undefined. Rather it tells the
TypeScript type checker to suspend strict null checks for a specific
property expression.

You'll need this template operator when you turn on strict null
checks. It's optional otherwise.


问:
Use awk, or sed commands to remove the letters and parenthesis from the rows of a file
I have an input file as below,

```<code>group_velocity: [     0.0000000      0.0000000      0.0000000 ]
group_velocity: [     6.8213667      5.2673206      0.0002496 ]
group_velocity: [    19.0751734     29.0686833      0.0006979 ]
</code>```

Now, I want to use the awk/sed command, such that the output file would look as:

```<code>   0.0000000      0.0000000      0.0000000
   6.8213667      5.2673206      0.0002496
   19.0751734     29.0686833     0.0006979
</code>```

Any help would be appreciated.

Body:
I have an input file as below,

group_velocity: [     0.0000000      0.0000000      0.0000000 ]
group_velocity: [     6.8213667      5.2673206      0.0002496 ]
group_velocity: [    19.0751734     29.0686833      0.0006979 ]

Now, I want to use the awk/sed command, such that the output file would look as:

   0.0000000      0.0000000      0.0000000
   6.8213667      5.2673206      0.0002496
   19.0751734     29.0686833     0.0006979

Any help would be appreciated.

Body:
If data are in same format all time, this should do:

awk '{print $3,$4,$5}' file
0.0000000 0.0000000 0.0000000
6.8213667 5.2673206 0.0002496
19.0751734 29.0686833 0.0006979

If formatting is important:

awk '{print $3,$4,$5}' OFS="\t" file
0.0000000       0.0000000       0.0000000
6.8213667       5.2673206       0.0002496
19.0751734      29.0686833      0.0006979


问:
How to give docker container based on scratch access to /var/run/docker.sock
I would like to use the Docker socket on the host from Go code running inside a container based on scratch.

The Dockerfile looks something like this:

```<code>
    FROM golang:1.12.4-alpine3.9 as builder

    RUN mkdir /user && \
        echo 'nobody:x:65534:65534:nobody:/:' > /user/passwd && \
        echo 'nobody:x:65534:' > /user/group

    RUN apk add --no-cache ca-certificates git

    WORKDIR /src

    COPY go.mod ./
    RUN go mod download

    COPY . .
    RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .

    FROM scratch as final

    COPY --from=builder /user/group /user/passwd /etc/
    COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
    COPY --from=builder /src/app /app
    COPY --chown=nobody:nobody data /.local

    USER nobody:nobody

    ENTRYPOINT ["/app"]

</code>```

The docker service itself includes a mount for the /var/run/docker.sock

Output from docker service inspect:

```<code>
  "Mounts": [
        {
            "Type": "bind",
            "Source": "/var/run/docker.sock",
            "Target": "/var/run/docker.sock"
        }
    ],

</code>```

Things I've tried:

touch /var/run/docker.sock on the builder and COPY --chown=nobody:nobody --from=builder /var/run /var/run in final

Different user (I refuse to run as root. It's bad practice).

Adding nobody in final to the docker group.

EDIT:

Under this configuration I get the following error as nobody as a user does not have permission to access /var/run/docker.socket

Got permission denied while trying to connect to the Docker daemon
  socket at unix:///var/run/docker.sock: Get
  http://%2Fvar%2Frun%2Fdocker.sock/v1.25/services: dial unix
  /var/run/docker.sock: connect: permission denied

答:
To communicate with the docker daemon you either need to run the command as root (or sudo), or your user must be a member of the docker group.

In order to use it from a non-root user and without sudo, you will need to create the docker group inside the container and add your user to that group.  NOTE: the docker group inside the container must have the same GID as the actual docker group on the host.

Body:
I would like to use the Docker socket on the host from Go code running inside a container based on scratch.

The Dockerfile looks something like this:

    FROM golang:1.12.4-alpine3.9 as builder

    RUN mkdir /user && \
        echo 'nobody:x:65534:65534:nobody:/:' > /user/passwd && \
        echo 'nobody:x:65534:' > /user/group

    RUN apk add --no-cache ca-certificates git

    WORKDIR /src

    COPY go.mod ./
    RUN go mod download

    COPY . .
    RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .

    FROM scratch as final

    COPY --from=builder /user/group /user/passwd /etc/
    COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
    COPY --from=builder /src/app /app
    COPY --chown=nobody:nobody data /.local

    USER nobody:nobody

    ENTRYPOINT ["/app"]

The docker service itself includes a mount for the /var/run/docker.sock

Output from docker service inspect:

  "Mounts": [
        {
            "Type": "bind",
            "Source": "/var/run/docker.sock",
            "Target": "/var/run/docker.sock"
        }
    ],

Things I've tried:

touch /var/run/docker.sock on the builder and COPY --chown=nobody:nobody --from=builder /var/run /var/run in final

Different user (I refuse to run as root. It's bad practice).

Adding nobody in final to the docker group.

EDIT:

Under this configuration I get the following error as nobody as a user does not have permission to access /var/run/docker.socket

Got permission denied while trying to connect to the Docker daemon
  socket at unix:///var/run/docker.sock: Get
  http://%2Fvar%2Frun%2Fdocker.sock/v1.25/services: dial unix
  /var/run/docker.sock: connect: permission denied


问:
Using LAG/LEAD to find peaks in data gives decade changes (ie 9, 99, 999) as well as correct peaks
The data in the dbase is collected once every minute.  Weld_Minutes will increment up until reset at the end of shift or product change.  The code finds the peak Weld_Minutes.  Unfortunately it see the transition from 9 to 10 minutes as a peak as well as 99 minutes to 100.  I'm at a loss as to why.  Also I am a noob.

```<code>        select
                case when pt = 1 then DateInserted end as Day_and_Time,
        case when pt = 1 then Weld_Time end as Weld_Minutes,
        case when pt = 1 then Ft_Ran end as Feet_Ran
from (
      select *, case
                 when DateInserted BETWEEN '2019-05-19 06:00:00' AND '2019-05-21 06:10:00'
              and lag(Weld_Time) over(order by DateInserted) <= Weld_Time
                  and lead(Weld_Time) over(order by DateInserted) < Weld_Time then 1 -- peak
            end as pt
      from mill_30
     ) sq
where pt is not null;
</code>```

The results from the query:

```<code>+-------------------------+--------------+----------+
|      Day_and_Time       | Weld_Minutes | Feet_Ran |
+-------------------------+--------------+----------+
| 2019-05-20 09:40:54.157 |            9 |      208 |
| 2019-05-20 16:51:00.130 |           34 |      595 |
| 2019-05-20 17:48:01.207 |            9 |      148 |
| 2019-05-20 20:48:01.567 |           99 |     1628 |
| 2019-05-21 01:06:04.083 |          308 |     5933 |
| 2019-05-21 01:15:04.263 |            9 |      185 |
| 2019-05-21 01:41:04.217 |           34 |      721 |
+-------------------------+--------------+----------+
The Weld_Minutes 9, 9, 99, and 9 are not peaks.  34, 308, and 34 are the correct peaks.
</code>```

答:
Your question is a bit hard to follow.  There is no weld_time column in your sample data.  And no weld_minutes in the question.  These might be related.

You would see this problem if the column you are comparing is a string, not a number.  I would suggest that you cast it to a number (integer, numeric, float) for your comparisons.

Because the data and the question are out-of-synch, I'm describing the solution rather than writing out the code.

Body:
The data in the dbase is collected once every minute.  Weld_Minutes will increment up until reset at the end of shift or product change.  The code finds the peak Weld_Minutes.  Unfortunately it see the transition from 9 to 10 minutes as a peak as well as 99 minutes to 100.  I'm at a loss as to why.  Also I am a noob.

        select
                case when pt = 1 then DateInserted end as Day_and_Time,
        case when pt = 1 then Weld_Time end as Weld_Minutes,
        case when pt = 1 then Ft_Ran end as Feet_Ran
from (
      select *, case
                 when DateInserted BETWEEN '2019-05-19 06:00:00' AND '2019-05-21 06:10:00'
              and lag(Weld_Time) over(order by DateInserted) <= Weld_Time
                  and lead(Weld_Time) over(order by DateInserted) < Weld_Time then 1 -- peak
            end as pt
      from mill_30
     ) sq
where pt is not null;

The results from the query:

+-------------------------+--------------+----------+
|      Day_and_Time       | Weld_Minutes | Feet_Ran |
+-------------------------+--------------+----------+
| 2019-05-20 09:40:54.157 |            9 |      208 |
| 2019-05-20 16:51:00.130 |           34 |      595 |
| 2019-05-20 17:48:01.207 |            9 |      148 |
| 2019-05-20 20:48:01.567 |           99 |     1628 |
| 2019-05-21 01:06:04.083 |          308 |     5933 |
| 2019-05-21 01:15:04.263 |            9 |      185 |
| 2019-05-21 01:41:04.217 |           34 |      721 |
+-------------------------+--------------+----------+
The Weld_Minutes 9, 9, 99, and 9 are not peaks.  34, 308, and 34 are the correct peaks.


问:
Trying to loop and display a JSON file with PHP
I have a JSON file that has an array inside. I want to loop inside each element of the JSON and display it. I can succesfully do it but I want when using the foreach loop refer to the field like this: $value["pessoa_id"];

When I'm doing like this I get it to display but after displaying it gets a message: "Notice: Undefined index: nome", like it was trying to access it again.

This is the JSON file:

```<code>{"Clientes": {
      "Pessoa": [
        {"pessoa_id" : 1,  "nome": "INDUSTRIAL JAVARI LTDA",  "endereco": "ENGENHO SANTA TERESA"},
        {"pessoa_id" : 2,  "nome": "AGROISA-AGRO IND. TRAVESSIA S/A",  "endereco": "FAZENDA TRAVESSIA S/N"}
      ],
      "Clientes": [
        {"cliente_id" : 1,  "loja" : 1,  "cliente" : 1,  "tpcli": "J",  "pontoref": ""},
        {"cliente_id" : 2,  "loja" : 1,  "cliente" : 2,  "tpcli": "J",  "pontoref": ""}
      ]
    }
  }
</code>```

And the php code:

```<code>$jsondata = file_get_contents("clitest.json");
$json = json_decode($jsondata, true);
foreach ($json as $key => $value){
    foreach ($value as $key => $val){
      foreach ($val as $key => $v){
          echo $v["nome"] . " " . $v["endereco"];
          echo "<br>";
        }
    }
}
</code>```

I want to be able to in one foreach see if it's a "Pessoa" or "Clientes" and loop throught it by getting the fields by the name.

答:
You also iterate over the 2nd array Clientes. You could access the array directly and only iterate over that data:

$jsondata = file_get_contents("clitest.json");
$json = json_decode($jsondata, true);
$pessoa = $json["Clientes"]["Pessoa"];
foreach ($pessoa as $key => $value){
  echo $value["nome"] . " " . $value["endereco"];
  echo "
";
}
```

<p><strong>Update:</strong></p>

<p>If you need/want to loop over the whole data-set like you did in your question, you can check if you are in the correct element of the object and only than iterate and output the data.</p>

<pre class="lang-php prettyprint-override"><code>$jsondata = file_get_contents("clitest.json");
$json = json_decode($jsondata, true);
foreach ($json as $key1 => $value){
  if ($key1 == "Clientes") {
    foreach ($value as $key2 => $val){
      if ($key2 == "Pessoa") {
        foreach ($val as $key3 => $v){
          echo $v["nome"] . " " . $v["endereco"];
          echo "<br>";
        }
      }
    }
  }
}

</code>```

Body:
I have a JSON file that has an array inside. I want to loop inside each element of the JSON and display it. I can succesfully do it but I want when using the foreach loop refer to the field like this: $value["pessoa_id"];

When I'm doing like this I get it to display but after displaying it gets a message: "Notice: Undefined index: nome", like it was trying to access it again.

This is the JSON file:

{"Clientes": {
      "Pessoa": [
        {"pessoa_id" : 1,  "nome": "INDUSTRIAL JAVARI LTDA",  "endereco": "ENGENHO SANTA TERESA"},
        {"pessoa_id" : 2,  "nome": "AGROISA-AGRO IND. TRAVESSIA S/A",  "endereco": "FAZENDA TRAVESSIA S/N"}
      ],
      "Clientes": [
        {"cliente_id" : 1,  "loja" : 1,  "cliente" : 1,  "tpcli": "J",  "pontoref": ""},
        {"cliente_id" : 2,  "loja" : 1,  "cliente" : 2,  "tpcli": "J",  "pontoref": ""}
      ]
    }
  }

And the php code:

$jsondata = file_get_contents("clitest.json");
$json = json_decode($jsondata, true);
foreach ($json as $key => $value){
    foreach ($value as $key => $val){
      foreach ($val as $key => $v){
          echo $v["nome"] . " " . $v["endereco"];
          echo "
";
        }
    }
}

I want to be able to in one foreach see if it's a "Pessoa" or "Clientes" and loop throught it by getting the fields by the name.

Body:
You also iterate over the 2nd array Clientes. You could access the array directly and only iterate over that data:

$jsondata = file_get_contents("clitest.json");
$json = json_decode($jsondata, true);
$pessoa = $json["Clientes"]["Pessoa"];
foreach ($pessoa as $key => $value){
  echo $value["nome"] . " " . $value["endereco"];
  echo "<br>";
}

Update:

If you need/want to loop over the whole data-set like you did in your question, you can check if you are in the correct element of the object and only than iterate and output the data.

$jsondata = file_get_contents("clitest.json");
$json = json_decode($jsondata, true);
foreach ($json as $key1 => $value){
  if ($key1 == "Clientes") {
    foreach ($value as $key2 => $val){
      if ($key2 == "Pessoa") {
        foreach ($val as $key3 => $v){
          echo $v["nome"] . " " . $v["endereco"];
          echo "<br>";
        }
      }
    }
  }
}


问:
Configure AutoFac in ASP.NET Core 3.0 Preview 5 or higher
Following the AutoFac documentation, I was able to use AutoFac in ASP.NET Core 3.0 Preview 3.
ASP.NET Core 3.0 Preview 4 and ASP.NET Core 3.0 Preview 5 introduced breaking changes and AutoFac no longer works.
My controller methods return runtime errors.

The differences between ASP.NET Core 3.0 Preview 3 and ASP.NET Core 3.0 Preview 5 in my code is as follows:

IWebHostBuilder -> IHostBuilder

CreateWebHostBuilder -> CreateHostBuilder

WebHost.CreateDefaultBuilder(args) -> Host.CreateDefaultBuilder(args)

```<code>public IServiceProvider ConfigureServices(IServiceCollection services)
</code>```

to

```<code>public void ConfigureServices(IServiceCollection services)
</code>```

```<code>System.AggregateException
  HResult=0x80131500
  Message=Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: API.Controllers.CityController Lifetime: Transient ImplementationType: CityController': Unable to resolve service for type 'IUnitOfWork' while attempting to activate 'CityController'.) (Error while validating the service descriptor 'ServiceType: LocationController Lifetime: Transient ImplementationType: LocationController': Unable to resolve service for type 'IUnitOfWork' while attempting to activate 'LocationController'.) (Error while validating the service descriptor 'ServiceType: PersonController Lifetime: Transient ImplementationType: PersonController': Unable to resolve service for type 'IUnitOfWork' while attempting to activate 'PersonController'.) (Error while validating the service descriptor 'ServiceType: SchoolController Lifetime: Transient ImplementationType: SchoolController': Unable to resolve service for type 'IUnitOfWork' while attempting to activate 'SchoolController'.) (Error while validating the service descriptor 'ServiceType: TestParentController Lifetime: Transient ImplementationType: TestParentController': Unable to resolve service for type 'IUnitOfWork' while attempting to activate 'TestParentController'.) (Error while validating the service descriptor 'ServiceType: TypeController Lifetime: Transient ImplementationType: TypeController': Unable to resolve service for type 'IUnitOfWork' while attempting to activate 'TypeController'.)
  Source=Microsoft.Extensions.DependencyInjection
  StackTrace:
   at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(IEnumerable`1 serviceDescriptors, ServiceProviderOptions options)
   at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services, ServiceProviderOptions options)
   at Microsoft.Extensions.DependencyInjection.DefaultServiceProviderFactory.CreateServiceProvider(IServiceCollection containerBuilder)
   at Microsoft.Extensions.Hosting.Internal.ServiceFactoryAdapter`1.CreateServiceProvider(Object containerBuilder)
   at Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()
   at Microsoft.Extensions.Hosting.HostBuilder.Build()
   at API.Program.Main(String[] args) in C:\Projects\FirstResponse\API\Program.cs:line 13

Inner Exception 1:
InvalidOperationException: Error while validating the service descriptor 'ServiceType: CityController Lifetime: Transient ImplementationType: CityController': Unable to resolve service for type 'IUnitOfWork' while attempting to activate 'CityController'.

Inner Exception 2:
InvalidOperationException: Unable to resolve service for type 'IUnitOfWork' while attempting to activate 'CityController'.

</code>```

Program.cs

public static IHostBuilder CreateHostBuilder(string[] args) =>
  Host.CreateDefaultBuilder(args)
    .ConfigureWebHostDefaults(webBuilder =>
    {
      webBuilder
        .UseStartup<Startup>()
        .ConfigureLogging((hostingContext, builder) =>
        {
          builder.ClearProviders();
          builder.SetMinimumLevel(LogLevel.Trace);
          builder.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
          builder.AddConsole();
          builder.AddDebug();
        })
        .UseNLog();
    });
```

<p>Startup.cs</p>

<pre class="lang-cs prettyprint-override"><code>public void ConfigureServices(IServiceCollection services)
{
  services
    .AddCustomOptions(Configuration)
    .AddCors()
    .AddJwtAuthentication()
    .AddHttpClients()
    .AddCustomMVC()
    .AddIIS()
    .AddCaching()
    .AddCustomDbContext(Configuration, Environment)
    .AddSwagger()
    .AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies())
    .AddHealthChecksUI();

  var serviceProvider = services.BuildServiceProvider();

  _appSettings = serviceProvider.GetService<IOptionsSnapshot<AppSettings>>().Value;

  var connectionString = Configuration.GetConnectionString(nameof(FirstResponseContext));

  // Create a Autofac container builder
  var builder = new ContainerBuilder();

  // Read service collection to Autofac
  builder.Populate(services);

  // Use and configure Autofac
  builder.RegisterModule(new MediatorModule());
  builder.RegisterModule(new ApplicationModule(connectionString));

  // build the Autofac container
  ApplicationContainer = builder.Build();

  // creating the IServiceProvider out of the Autofac container
  //return new AutofacServiceProvider(ApplicationContainer);
}
</code>```

ApplicationModule.cs

protected override void Load(ContainerBuilder builder)
{
  builder.RegisterType<HttpContextAccessor>().As<IHttpContextAccessor>().SingleInstance();
  builder.RegisterType<ModelValidationAttribute>().InstancePerLifetimeScope();
  builder.RegisterType<ETagCache>().InstancePerLifetimeScope();

  builder.RegisterType<FirstResponseContext>().As<DbContext>().As<IUnitOfWork>().InstancePerLifetimeScope();
}
```

答:
A few changes would need to be done to conform to the new syntax

You need to plug in the service provider factory for AutoFac

```<code>public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
      .UseServiceProviderFactory(new AutofacServiceProviderFactory()) //<--NOTE THIS
      .ConfigureWebHostDefaults(webBuilder => {
          webBuilder
            .UseStartup<Startup>()
            .ConfigureLogging((hostingContext, builder) => {
                builder.ClearProviders();
                builder.SetMinimumLevel(LogLevel.Trace);
                builder.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                builder.AddConsole();
                builder.AddDebug();
            })
            .UseNLog();
    });
</code>```

Then in the ConfigureContainer method of your Startup class, register things directly into an Autofac ContainerBuilder.

```<code>public IConfigurationRoot Configuration { get; private set; }

public void ConfigureServices(IServiceCollection services) {
    services
        .AddCustomOptions(Configuration)
        .AddCors()
        .AddJwtAuthentication()
        .AddHttpClients()
        .AddCustomMVC()
        .AddIIS()
        .AddCaching()
        .AddCustomDbContext(Configuration, Environment)
        .AddSwagger()
        .AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies())
        .AddHealthChecksUI();
}

public void ConfigureContainer(ContainerBuilder builder) {
   var connectionString = Configuration.GetConnectionString(nameof(FirstResponseContext));

    // Use and configure Autofac
    builder.RegisterModule(new MediatorModule());
    builder.RegisterModule(new ApplicationModule(connectionString));
}
</code>```

The IServiceProvider will automatically be created for you, so there’s nothing you have to do but register things.

Some of this was taken directly from Autofac documentation for Asp.Net Core

Body:
Following the AutoFac documentation, I was able to use AutoFac in ASP.NET Core 3.0 Preview 3.
ASP.NET Core 3.0 Preview 4 and ASP.NET Core 3.0 Preview 5 introduced breaking changes and AutoFac no longer works.
My controller methods return runtime errors.

The differences between ASP.NET Core 3.0 Preview 3 and ASP.NET Core 3.0 Preview 5 in my code is as follows:

IWebHostBuilder -> IHostBuilder

CreateWebHostBuilder -> CreateHostBuilder

WebHost.CreateDefaultBuilder(args) -> Host.CreateDefaultBuilder(args)

public IServiceProvider ConfigureServices(IServiceCollection services)

to

public void ConfigureServices(IServiceCollection services)

System.AggregateException
  HResult=0x80131500
  Message=Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: API.Controllers.CityController Lifetime: Transient ImplementationType: CityController': Unable to resolve service for type 'IUnitOfWork' while attempting to activate 'CityController'.) (Error while validating the service descriptor 'ServiceType: LocationController Lifetime: Transient ImplementationType: LocationController': Unable to resolve service for type 'IUnitOfWork' while attempting to activate 'LocationController'.) (Error while validating the service descriptor 'ServiceType: PersonController Lifetime: Transient ImplementationType: PersonController': Unable to resolve service for type 'IUnitOfWork' while attempting to activate 'PersonController'.) (Error while validating the service descriptor 'ServiceType: SchoolController Lifetime: Transient ImplementationType: SchoolController': Unable to resolve service for type 'IUnitOfWork' while attempting to activate 'SchoolController'.) (Error while validating the service descriptor 'ServiceType: TestParentController Lifetime: Transient ImplementationType: TestParentController': Unable to resolve service for type 'IUnitOfWork' while attempting to activate 'TestParentController'.) (Error while validating the service descriptor 'ServiceType: TypeController Lifetime: Transient ImplementationType: TypeController': Unable to resolve service for type 'IUnitOfWork' while attempting to activate 'TypeController'.)
  Source=Microsoft.Extensions.DependencyInjection
  StackTrace:
   at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(IEnumerable`1 serviceDescriptors, ServiceProviderOptions options)
   at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services, ServiceProviderOptions options)
   at Microsoft.Extensions.DependencyInjection.DefaultServiceProviderFactory.CreateServiceProvider(IServiceCollection containerBuilder)
   at Microsoft.Extensions.Hosting.Internal.ServiceFactoryAdapter`1.CreateServiceProvider(Object containerBuilder)
   at Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()
   at Microsoft.Extensions.Hosting.HostBuilder.Build()
   at API.Program.Main(String[] args) in C:\Projects\FirstResponse\API\Program.cs:line 13

Inner Exception 1:
InvalidOperationException: Error while validating the service descriptor 'ServiceType: CityController Lifetime: Transient ImplementationType: CityController': Unable to resolve service for type 'IUnitOfWork' while attempting to activate 'CityController'.

Inner Exception 2:
InvalidOperationException: Unable to resolve service for type 'IUnitOfWork' while attempting to activate 'CityController'.

Program.cs

public static IHostBuilder CreateHostBuilder(string[] args) =>
  Host.CreateDefaultBuilder(args)
    .ConfigureWebHostDefaults(webBuilder =>
    {
      webBuilder
        .UseStartup<Startup>()
        .ConfigureLogging((hostingContext, builder) =>
        {
          builder.ClearProviders();
          builder.SetMinimumLevel(LogLevel.Trace);
          builder.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
          builder.AddConsole();
          builder.AddDebug();
        })
        .UseNLog();
    });

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
  services
    .AddCustomOptions(Configuration)
    .AddCors()
    .AddJwtAuthentication()
    .AddHttpClients()
    .AddCustomMVC()
    .AddIIS()
    .AddCaching()
    .AddCustomDbContext(Configuration, Environment)
    .AddSwagger()
    .AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies())
    .AddHealthChecksUI();

  var serviceProvider = services.BuildServiceProvider();

  _appSettings = serviceProvider.GetService<IOptionsSnapshot<AppSettings>>().Value;

  var connectionString = Configuration.GetConnectionString(nameof(FirstResponseContext));

  // Create a Autofac container builder
  var builder = new ContainerBuilder();

  // Read service collection to Autofac
  builder.Populate(services);

  // Use and configure Autofac
  builder.RegisterModule(new MediatorModule());
  builder.RegisterModule(new ApplicationModule(connectionString));

  // build the Autofac container
  ApplicationContainer = builder.Build();

  // creating the IServiceProvider out of the Autofac container
  //return new AutofacServiceProvider(ApplicationContainer);
}

ApplicationModule.cs

protected override void Load(ContainerBuilder builder)
{
  builder.RegisterType<HttpContextAccessor>().As<IHttpContextAccessor>().SingleInstance();
  builder.RegisterType<ModelValidationAttribute>().InstancePerLifetimeScope();
  builder.RegisterType<ETagCache>().InstancePerLifetimeScope();

  builder.RegisterType<FirstResponseContext>().As<DbContext>().As<IUnitOfWork>().InstancePerLifetimeScope();
}

Body:
A few changes would need to be done to conform to the new syntax

You need to plug in the service provider factory for AutoFac

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
      .UseServiceProviderFactory(new AutofacServiceProviderFactory()) //<--NOTE THIS
      .ConfigureWebHostDefaults(webBuilder => {
          webBuilder
            .UseStartup<Startup>()
            .ConfigureLogging((hostingContext, builder) => {
                builder.ClearProviders();
                builder.SetMinimumLevel(LogLevel.Trace);
                builder.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                builder.AddConsole();
                builder.AddDebug();
            })
            .UseNLog();
    });

Then in the ConfigureContainer method of your Startup class, register things directly into an Autofac ContainerBuilder.

public IConfigurationRoot Configuration { get; private set; }

public void ConfigureServices(IServiceCollection services) {
    services
        .AddCustomOptions(Configuration)
        .AddCors()
        .AddJwtAuthentication()
        .AddHttpClients()
        .AddCustomMVC()
        .AddIIS()
        .AddCaching()
        .AddCustomDbContext(Configuration, Environment)
        .AddSwagger()
        .AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies())
        .AddHealthChecksUI();
}

public void ConfigureContainer(ContainerBuilder builder) {
   var connectionString = Configuration.GetConnectionString(nameof(FirstResponseContext));

    // Use and configure Autofac
    builder.RegisterModule(new MediatorModule());
    builder.RegisterModule(new ApplicationModule(connectionString));
}

The IServiceProvider will automatically be created for you, so there’s nothing you have to do but register things.

Some of this was taken directly from Autofac documentation for Asp.Net Core


问:
@JsonProperty being ignored in enum
I have a simple enum that has to properties, OK and FAULT. I am trying to return the value in lowercase when returning it as a Json Object by using the @JsonProperty annotation. First I thought that because I was mixing java.xmlbind.annotation with com.fasterxml was the problem, but after removing the java.xmlbind it still does not work.

The Object that uses this enum always shows either OK or FAULT with json requests, and not ok and fault as it does when requesting XML.

Using Jackson 2.5.x

Any insights or suggestions will be greatly appreciated.

```<code>import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 *
 */
@XmlEnum
public enum RequestStatusType {
    /**
     * Generic server A-OK ;)
     */
    @XmlEnumValue(value="ok")
    @JsonProperty(value="ok")
    OK,

    /**
     * Generic unknown server fault
     */
    @XmlEnumValue(value="fault")
    @JsonProperty(value="fault")
    FAULT;

    /**
     * Returns a RequestStatusType based on the string passed in
     * @param requestStatusType the requestStatusType to get
     */
    public static RequestStatusType getRequestStatus (String requestStatusTypeStr) {
        try {
            return valueOf( requestStatusTypeStr.toUpperCase() );
        } catch (Exception e) {
            return null;
        }
    }

    /* (non-Javadoc)
     * @see java.lang.Enum#toString()
     */
    @Override
    public String toString() {
        return super.toString().toLowerCase();
    }
}
</code>```

答: You need check your Jackson version. Your way only works with Jackson 2.7.2 or newer. Please refer to When is the @JsonProperty property used and what is it used for?  .  Hope can help.</p>

Title: @JsonProperty being ignored in enum

Body:
I have a simple enum that has to properties, OK and FAULT. I am trying to return the value in lowercase when returning it as a Json Object by using the @JsonProperty annotation. First I thought that because I was mixing java.xmlbind.annotation with com.fasterxml was the problem, but after removing the java.xmlbind it still does not work.

The Object that uses this enum always shows either OK or FAULT with json requests, and not ok and fault as it does when requesting XML.

Using Jackson 2.5.x

Any insights or suggestions will be greatly appreciated.

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 *
 */
@XmlEnum
public enum RequestStatusType {
    /**
     * Generic server A-OK ;)
     */
    @XmlEnumValue(value="ok")
    @JsonProperty(value="ok")
    OK,

    /**
     * Generic unknown server fault
     */
    @XmlEnumValue(value="fault")
    @JsonProperty(value="fault")
    FAULT;

    /**
     * Returns a RequestStatusType based on the string passed in
     * @param requestStatusType the requestStatusType to get
     */
    public static RequestStatusType getRequestStatus (String requestStatusTypeStr) {
        try {
            return valueOf( requestStatusTypeStr.toUpperCase() );
        } catch (Exception e) {
            return null;
        }
    }

    /* (non-Javadoc)
     * @see java.lang.Enum#toString()
     */
    @Override
    public String toString() {
        return super.toString().toLowerCase();
    }
}


问:
React-Redux Dispatch design
Overview

We have a page with a header (Blue color) and content section (Green color) that can be seen in image below. The requirement is when a user selects a year in header, then the content page will show data as per the selected year.

What is happening right now Technically

When user selects a year in header, we dispatch the selected value and the active container's mapStateToProps function is triggered and the selected year is passed to the component.

```<code>class Page1Content extends Component {
}

function mapStateToProps(state) {
    return { selectedYear : state.userSelectedValue };
}

export default connect(mapStateToProps, null)(Page1Content);
</code>```

Question 1

How will data on Page1Content will refresh? Few approaches:

In ComponentDidUpdate react life cycle method of the Page1Content API to fetch data can be called. However have seen opinions where we should avoid React hooks and life cycle methods with Redux.

In mapStateToProps function API can be called.

Can any one suggest what is the better place to call the API?

Question 2

Data on Page1Content will be used only by this page. This data will not be used by any other component and hence need not be shared by any other Component. Now question 2 is

In case we decide to use ComponentDidUpdate should we again dispatch the API call using Thunk or any other library and then catch the response in mapStatesToProps again?

Or we should make the API call and resolve it in the component itself as a promise. Then the response will be set in State and respective Template will be refreshed.

答:
ComponentDidUpdate is a lifecycle method not a hook. Hooks is functionality that allows functional components to have class based functionality such as state.
You are using a class based component in your example so you are not using hooks.

https://reactjs.org/docs/hooks-intro.html

Yes Redux shouldnt be used with hooks since context is a better option.

You can lift state up so to speak and update the local state in the parent component getting rid of redux completely.

Just pass down the setState function and the state itself to the appropriate children.

```<code>class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
               some_prop: false
             }
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    this.setState({some_prop: true})
    console.log('Click happened');
  }
  render() {
    return (
     <Header onClick={this.handleClick } />
     <Page1Component props={this.state.some_prop} />
  }
}
</code>```

Edit:

Question 1

How will data on Page1Content will refresh?

best option is with a ternary expression in your render method, there is no need to check if the state updated. In react if the state is changed your component will automatically re render.

```<code>  render() {
    return (
      <div>
        {this.props.selectedYear
           ? <p> {this.props.selectedYear}</p>
           : null
         }
      </div>

  }
}
</code>```

Question 2

Data on Page1Content will be used only by this page. This data will not be used by any other component and hence need not be shared by any other Component. Now question 2 is

If I understand this correctly you will need to use an action creators, redux thunk is overkill here.

```<code>class Header extends Component {
  constructor(props) {
    super(props);
  }

  handleClick() {
    this.props.dispatchActionCreator({some_value})
    console.log('Click happened');
  }
  render() {
    return (
      <button onClick={(some_value) => this.handleClick(some_value)}>Click </button>
  }
}

function mapDispatchToProps(state) {
    return {
       dispatchActioNCreator: (some_value) => dispatch(ACTIONS.action_creator(some_value) };
}
</code>```

This will save your value from your header to the global redux state and then you can just access with mapStateToProps in your Page1Component.

Title: React-Redux Dispatch design

Body:
Overview

We have a page with a header (Blue color) and content section (Green color) that can be seen in image below. The requirement is when a user selects a year in header, then the content page will show data as per the selected year.

What is happening right now Technically

When user selects a year in header, we dispatch the selected value and the active container's mapStateToProps function is triggered and the selected year is passed to the component.

class Page1Content extends Component {
}

function mapStateToProps(state) {
    return { selectedYear : state.userSelectedValue };
}

export default connect(mapStateToProps, null)(Page1Content);

Question 1

How will data on Page1Content will refresh? Few approaches:

In ComponentDidUpdate react life cycle method of the Page1Content API to fetch data can be called. However have seen opinions where we should avoid React hooks and life cycle methods with Redux.

In mapStateToProps function API can be called.

Can any one suggest what is the better place to call the API?

Question 2

Data on Page1Content will be used only by this page. This data will not be used by any other component and hence need not be shared by any other Component. Now question 2 is

In case we decide to use ComponentDidUpdate should we again dispatch the API call using Thunk or any other library and then catch the response in mapStatesToProps again?

Or we should make the API call and resolve it in the component itself as a promise. Then the response will be set in State and respective Template will be refreshed.

Body:
ComponentDidUpdate is a lifecycle method not a hook. Hooks is functionality that allows functional components to have class based functionality such as state.
You are using a class based component in your example so you are not using hooks.

https://reactjs.org/docs/hooks-intro.html

Yes Redux shouldnt be used with hooks since context is a better option.

You can lift state up so to speak and update the local state in the parent component getting rid of redux completely.

Just pass down the setState function and the state itself to the appropriate children.

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
               some_prop: false
             }
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    this.setState({some_prop: true})
    console.log('Click happened');
  }
  render() {
    return (
     <Header onClick={this.handleClick } />
     <Page1Component props={this.state.some_prop} />
  }
}

Edit:

Question 1

How will data on Page1Content will refresh?

best option is with a ternary expression in your render method, there is no need to check if the state updated. In react if the state is changed your component will automatically re render.

  render() {
    return (
      <div>
        {this.props.selectedYear
           ? <p> {this.props.selectedYear}</p>
           : null
         }
      </div>

  }
}

Question 2

Data on Page1Content will be used only by this page. This data will not be used by any other component and hence need not be shared by any other Component. Now question 2 is

If I understand this correctly you will need to use an action creators, redux thunk is overkill here.

class Header extends Component {
  constructor(props) {
    super(props);
  }

  handleClick() {
    this.props.dispatchActionCreator({some_value})
    console.log('Click happened');
  }
  render() {
    return (
      <button onClick={(some_value) => this.handleClick(some_value)}>Click </button>
  }
}

function mapDispatchToProps(state) {
    return {
       dispatchActioNCreator: (some_value) => dispatch(ACTIONS.action_creator(some_value) };
}

This will save your value from your header to the global redux state and then you can just access with mapStateToProps in your Page1Component.


问:
What would be best practice If I am trying to constantly check if a directory exists? JAVA
I have a Java application that creates multiple threads. There is 1 producer thread which reads from a 10gb file, parses that information, creates objects from it and puts them into multiple blocking queues (5 queues).

The rest of the 5 consumer threads read from a blockingqueue (each consumer thread has its own blockingqueue). The consumer threads then each write to an individual file, so 5 files in total get created. It takes around 30min to create all files.

The problem:
The threads are writing to an external mount directory in a linux box. We've experience problems where other linux mounts have gone down and applications crash so I want to prevent that in this application.

What I would like to do is keep checking if the mount (directory) exists before writing to it. Im assuming if the directory goes down it will throw a FileNotFoundException. If that is the case I want it to keep checking if the directory is there for about 10-20min before completely crashing. Because I dont want to have to read the 10gb file again I want the consumer threads to be able to pick up from where they last left off.

What Im not sure would be best practice is:

Is it best to check if the directory exists in the main class before creating the threads? Or check in each consumer thread?

If I keep checking if the directory exists in each consumer thread it seems like repeatable code. I can check in the main class but it takes 30min to create these files. What if in those 30min the mount goes down then if Im only checking in the main class whether the directory exists the application will crash. Or if Im already writing to a directory is it impossible for an external directory to go down? Does it get locked?

thank you

答:
We have something similar in our application, but in our case we are running a web app and if our mounted file system goes down we just throw an exception, but we want to do something more elegant, like you do...

I would recommend using a combination of the following patterns:  State, CircuitBreaker, which I believe CircuitBreaker is a more specific version of the State pattern, and Observer/Observable.

These would work in the following way...

Create something that represents your file system.  Maybe a class called MountedFileSystem.  Make all your write calls to this particular class.

This class will catch all FileNotFoundException and one occurs, the CircutBreaker gets triggered.  This change will be like the State pattern.  One state is when things are working 'fine', the other state is when things aren't working 'fine', meaning that the mount has gone away.

Then, in the background, I would have a task that starts on a thread and checks the actual underlying file system to see if it is back.  When the file system is back, change the state in the MountedFileSystem, and fire an Event (Observer/Observable) to try writing the files again to disk.

And as yuan quigfei stated, I am fairly certain you're going to have to rewrite those files.  I just don't see being able to restart writing to them, but perhaps someone else has an idea.