问:
Is it normal to have a lot of action in ngrx?
I am trying to implement ngrx and I have a few api call. For each, the best practice is apparently to add a success and a fail so that my effect will dispatch the accurate sub action. but the action file is already very huge and this is only like 6 calls...

```<code>import { HttpErrorResponse } from '@angular/common/http';
import { Action } from '@ngrx/store';
import { IOrganization } from './organization.models';

export enum ActionTypes {
  GetOrganizationsRequest = '[Organizations] Get Organizations Request',
  GetOrganizationsSuccess = '[Organizations] Get Organizations Success',
  GetOrganizationsFailed = '[Organizations] Get Organizations Failed',

  PostOrganizationsRequest = '[Organizations] Post Organizations Request',
  PostOrganizationsSuccess = '[Organizations] Post Organizations Success',
  PostOrganizationsFailed = '[Organizations] Post Organizations Failed',

  UpdateOrganizationRequest = '[Organizations] Update Organizations Request',
  UpdateOrganizationSuccess = '[Organizations] Update Organizations Success',
  UpdateOrganizationFailed = '[Organizations] Update Organizations Failed',

  RefreshOrganizationRequest = '[Organizations] Refresh Organizations Request',
  RefreshOrganizationSuccess = '[Organizations] Refresh Organizations Success',
  RefreshOrganizationFailed = '[Organizations] Refresh Organizations Failed',

  DeleteOrganizationRequest = '[Organizations] Delete Organizations Request',
  DeleteOrganizationSuccess = '[Organizations] Delete Organizations Success',
  DeleteOrganizationFailed = '[Organizations] Delete Organizations Failed',

  GetOrganizationsUsersRequest = '[Organizations] Get Users Organizations Request',
  GetOrganizationsUsersSuccess = '[Organizations] Get Users Organizations Success',
  GetOrganizationsUsersFailed = '[Organizations] Get Users Organizations Failed',

}

export class GetOrganizationsRequest implements Action {
  public readonly type = ActionTypes.GetOrganizationsRequest;
  constructor() {}
}

export class GetOrganizationsSuccess implements Action {
  public readonly type = ActionTypes.GetOrganizationsSuccess;
  constructor(public payload: {organization: Array<IOrganization>}) {}
}

export class GetOrganizationsFailed implements Action {
  public readonly type = ActionTypes.GetOrganizationsFailed;
  constructor(public payload: {error: HttpErrorResponse}) {}
}

export class PostOrganizationsRequest implements Action {
  public readonly type = ActionTypes.PostOrganizationsRequest;
  constructor(public payload: {organization: IOrganization}) {}
}

export class PostOrganizationsSuccess implements Action {
  public readonly type = ActionTypes.PostOrganizationsSuccess;
  constructor(public payload: {response: any}) {}
}

export class PostOrganizationsFailed implements Action {
  public readonly type = ActionTypes.PostOrganizationsFailed;
  constructor(public payload: {error: HttpErrorResponse}) {}
}

export class UpdateOrganizationRequest implements Action {
  public readonly type = ActionTypes.GetOrganizationsRequest;
  constructor(public payload: {organizationId: string, organization: IOrganization}) {}
}

export class UpdateOrganizationSuccess implements Action {
  public readonly type = ActionTypes.UpdateOrganizationSuccess;
  constructor(public payload: {response: any}) {}
}

export class UpdateOrganizationFailed implements Action {
  public readonly type = ActionTypes.UpdateOrganizationFailed;
  constructor(public payload: {error: HttpErrorResponse}) {}
}

export class RefreshOrganizationRequest implements Action {
  public readonly type = ActionTypes.RefreshOrganizationRequest;
  constructor(public payload: {organizationId: string}) {}
}

export class RefreshOrganizationSuccess implements Action {
  public readonly type = ActionTypes.RefreshOrganizationSuccess;
  constructor(public payload: {response: any}) {}
}

export class RefreshOrganizationFailed implements Action {
  public readonly type = ActionTypes.RefreshOrganizationFailed;
  constructor(public payload: {error: HttpErrorResponse}) {}
}

export class DeleteOrganizationRequest implements Action {
  public readonly type = ActionTypes.DeleteOrganizationRequest;
  constructor(public payload: {organizationId: string}) {}
}

export class DeleteOrganizationSuccess implements Action {
  public readonly type = ActionTypes.DeleteOrganizationSuccess;
  constructor(public payload: {response: any}) {}
}

export class DeleteOrganizationFailed implements Action {
  public readonly type = ActionTypes.DeleteOrganizationFailed;
  constructor(public payload: {error: HttpErrorResponse}) {}
}

export class GetOrganizationsUsersRequest implements Action {
  public readonly type = ActionTypes.GetOrganizationsUsersRequest;
  constructor(public payload: {organizationId: string}) {}
}

export class GetOrganizationsUsersSuccess implements Action {
  public readonly type = ActionTypes.GetOrganizationsUsersSuccess;
  constructor(public payload: {response: any}) {}
}

export class GetOrganizationsUsersFailed implements Action {
  public readonly type = ActionTypes.GetOrganizationsUsersFailed;
  constructor(public payload: {error: HttpErrorResponse}) {}
}

export type Actions =   GetOrganizationsRequest |
                        GetOrganizationsSuccess |
                        GetOrganizationsFailed |
                        PostOrganizationsRequest |
                        PostOrganizationsSuccess |
                        PostOrganizationsFailed |
                        UpdateOrganizationRequest |
                        UpdateOrganizationSuccess |
                        UpdateOrganizationFailed |
                        RefreshOrganizationRequest |
                        RefreshOrganizationSuccess  |
                        RefreshOrganizationFailed |
                        DeleteOrganizationRequest |
                        DeleteOrganizationSuccess  |
                        DeleteOrganizationFailed  |
                        GetOrganizationsUsersRequest |
                        GetOrganizationsUsersSuccess |
                        GetOrganizationsUsersFailed;
</code>```

How many action do an big angular app contain, isn't this a bit of a mess ?

答:
Yes, this is "normal". Mainly because an action describes an unique event within your application. Starting from NgRx some of this code will become smaller (but the main principles remain) with createAction and createReducer.

Also, there is @ngrx/entity and @ngrx/data (or ngrx-data pre v8) to get rid of some of this code.

Body:
I am trying to implement ngrx and I have a few api call. For each, the best practice is apparently to add a success and a fail so that my effect will dispatch the accurate sub action. but the action file is already very huge and this is only like 6 calls...

import { HttpErrorResponse } from '@angular/common/http';
import { Action } from '@ngrx/store';
import { IOrganization } from './organization.models';

export enum ActionTypes {
  GetOrganizationsRequest = '[Organizations] Get Organizations Request',
  GetOrganizationsSuccess = '[Organizations] Get Organizations Success',
  GetOrganizationsFailed = '[Organizations] Get Organizations Failed',

  PostOrganizationsRequest = '[Organizations] Post Organizations Request',
  PostOrganizationsSuccess = '[Organizations] Post Organizations Success',
  PostOrganizationsFailed = '[Organizations] Post Organizations Failed',

  UpdateOrganizationRequest = '[Organizations] Update Organizations Request',
  UpdateOrganizationSuccess = '[Organizations] Update Organizations Success',
  UpdateOrganizationFailed = '[Organizations] Update Organizations Failed',

  RefreshOrganizationRequest = '[Organizations] Refresh Organizations Request',
  RefreshOrganizationSuccess = '[Organizations] Refresh Organizations Success',
  RefreshOrganizationFailed = '[Organizations] Refresh Organizations Failed',

  DeleteOrganizationRequest = '[Organizations] Delete Organizations Request',
  DeleteOrganizationSuccess = '[Organizations] Delete Organizations Success',
  DeleteOrganizationFailed = '[Organizations] Delete Organizations Failed',

  GetOrganizationsUsersRequest = '[Organizations] Get Users Organizations Request',
  GetOrganizationsUsersSuccess = '[Organizations] Get Users Organizations Success',
  GetOrganizationsUsersFailed = '[Organizations] Get Users Organizations Failed',

}

export class GetOrganizationsRequest implements Action {
  public readonly type = ActionTypes.GetOrganizationsRequest;
  constructor() {}
}

export class GetOrganizationsSuccess implements Action {
  public readonly type = ActionTypes.GetOrganizationsSuccess;
  constructor(public payload: {organization: Array<IOrganization>}) {}
}

export class GetOrganizationsFailed implements Action {
  public readonly type = ActionTypes.GetOrganizationsFailed;
  constructor(public payload: {error: HttpErrorResponse}) {}
}

export class PostOrganizationsRequest implements Action {
  public readonly type = ActionTypes.PostOrganizationsRequest;
  constructor(public payload: {organization: IOrganization}) {}
}

export class PostOrganizationsSuccess implements Action {
  public readonly type = ActionTypes.PostOrganizationsSuccess;
  constructor(public payload: {response: any}) {}
}

export class PostOrganizationsFailed implements Action {
  public readonly type = ActionTypes.PostOrganizationsFailed;
  constructor(public payload: {error: HttpErrorResponse}) {}
}

export class UpdateOrganizationRequest implements Action {
  public readonly type = ActionTypes.GetOrganizationsRequest;
  constructor(public payload: {organizationId: string, organization: IOrganization}) {}
}

export class UpdateOrganizationSuccess implements Action {
  public readonly type = ActionTypes.UpdateOrganizationSuccess;
  constructor(public payload: {response: any}) {}
}

export class UpdateOrganizationFailed implements Action {
  public readonly type = ActionTypes.UpdateOrganizationFailed;
  constructor(public payload: {error: HttpErrorResponse}) {}
}

export class RefreshOrganizationRequest implements Action {
  public readonly type = ActionTypes.RefreshOrganizationRequest;
  constructor(public payload: {organizationId: string}) {}
}

export class RefreshOrganizationSuccess implements Action {
  public readonly type = ActionTypes.RefreshOrganizationSuccess;
  constructor(public payload: {response: any}) {}
}

export class RefreshOrganizationFailed implements Action {
  public readonly type = ActionTypes.RefreshOrganizationFailed;
  constructor(public payload: {error: HttpErrorResponse}) {}
}

export class DeleteOrganizationRequest implements Action {
  public readonly type = ActionTypes.DeleteOrganizationRequest;
  constructor(public payload: {organizationId: string}) {}
}

export class DeleteOrganizationSuccess implements Action {
  public readonly type = ActionTypes.DeleteOrganizationSuccess;
  constructor(public payload: {response: any}) {}
}

export class DeleteOrganizationFailed implements Action {
  public readonly type = ActionTypes.DeleteOrganizationFailed;
  constructor(public payload: {error: HttpErrorResponse}) {}
}

export class GetOrganizationsUsersRequest implements Action {
  public readonly type = ActionTypes.GetOrganizationsUsersRequest;
  constructor(public payload: {organizationId: string}) {}
}

export class GetOrganizationsUsersSuccess implements Action {
  public readonly type = ActionTypes.GetOrganizationsUsersSuccess;
  constructor(public payload: {response: any}) {}
}

export class GetOrganizationsUsersFailed implements Action {
  public readonly type = ActionTypes.GetOrganizationsUsersFailed;
  constructor(public payload: {error: HttpErrorResponse}) {}
}

export type Actions =   GetOrganizationsRequest |
                        GetOrganizationsSuccess |
                        GetOrganizationsFailed |
                        PostOrganizationsRequest |
                        PostOrganizationsSuccess |
                        PostOrganizationsFailed |
                        UpdateOrganizationRequest |
                        UpdateOrganizationSuccess |
                        UpdateOrganizationFailed |
                        RefreshOrganizationRequest |
                        RefreshOrganizationSuccess  |
                        RefreshOrganizationFailed |
                        DeleteOrganizationRequest |
                        DeleteOrganizationSuccess  |
                        DeleteOrganizationFailed  |
                        GetOrganizationsUsersRequest |
                        GetOrganizationsUsersSuccess |
                        GetOrganizationsUsersFailed;

How many action do an big angular app contain, isn't this a bit of a mess ?


来源: stackexchange

问:
PHP How to remove white spaces, obfuscating the output HTML CODE on the fly at the Server
I have a simple website in PHP.

My website does not use any Data Source, just some simple PHP scripts to allow some basic functionality.

As for my understanding when a User request my website the PHP code generates the HTML code that will be read by their browser.

I need to make difficult (in some how obfuscate) the HTML generated, so if the user would save a HTML page the code would be difficult to modify and uneasy to interpreter.

My basic need are basically COMPRESSING the HTML:

Eliminate white space. So all code would be packed in few line. Making it in some how human unreadable

Encode the HTML (optional)

Because I have many pages in my website. I'm looking for an automatic solution so I can add some code in one place and have for the next moment all pages output as described above.

Any idea how to do it?

Thanks for your time.

答:
You can use eval function: http://php.net/manual/en/function.eval.php or output buffering: http://php.net/manual/en/book.outcontrol.php and than modify the result. But obfuscating HTML itself is pointless. There are many tools for code formating capable of reverting the code to human-friendly form.

If you want the result to by hard to change, why don't you output a PDF file?

ContentLicense: CC BY-SA 3.0


问:
Are there any REST apis which can be used like Telnet
I am looking for some REST API provider which will allow to send email like how Telnet does. API will accept all parameters like SMTP server, username, password, message etc. and then will send email.

I understand I can do it programmatically using Java or NodeJS. If anyone has used such API please help.

答: Apache commons email "https://commons.apache.org/proper/commons-email/" can be used to send mail. </p>

ContentLicense: CC BY-SA 4.0


问:
Django, browser display filename instead of the picture
I am missing some element to display picture  attatched with each post on a blog created with Django instead of picture file name.

Many solutions to this kind of a problem were:

```<code><img src="{{Object.picture.url}}"/>
</code>```

On template I have tried:

1

```<code><img src="{{ posts.title_picture.url }}"/>
</code>```

2

```<code><img src="{{title_picture.url}}"/>
</code>```

Which resulted respectively in displaying those on the browser:

1.

pictureforpost1.png

2.

img

model:

```<code>class Post(models.Model):
    title = models.CharField(max_length=255, blank=True, null=True)
    title_picture = models.FileField(blank=True,null=True)
</code>```

view:

```<code>class IndexView(ListView):
    model = Post
    context_object_name = 'posts'
</code>```

Seems like Django is finding the file. It is just not displaying the picture.

****Solution thanks to the below answers:****

changed

```<code>STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

to

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
</code>```

and added the following

```<code>urls.py

urlpatterns = [
   ...
]
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# when served with STATIC_URL and STATIC_ROOT instead it
# is not working so check difference in MEDIA and STATIC.

</code>```

In general I was lacking (and still do :) ) basic knowledge on uploads and displaying the static files.

Thanks.

答:
When you will create the new record for table Post then you have to upload the Image File so if you set the media url then it will store at the specified location.
Try to set the MEDIA_ROOT and MEDIA_URL in settings.py file Eg.

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
```

You can seen the details in the django documentation.

Body:
I am missing some element to display picture  attatched with each post on a blog created with Django instead of picture file name.

Many solutions to this kind of a problem were:

On template I have tried:

1

2

Which resulted respectively in displaying those on the browser:

1.

pictureforpost1.png

2.

img

model:

class Post(models.Model):
    title = models.CharField(max_length=255, blank=True, null=True)
    title_picture = models.FileField(blank=True,null=True)

view:

class IndexView(ListView):
    model = Post
    context_object_name = 'posts'

Seems like Django is finding the file. It is just not displaying the picture.

****Solution thanks to the below answers:****

changed

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

to

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

and added the following

urls.py

urlpatterns = [
   ...
]
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# when served with STATIC_URL and STATIC_ROOT instead it
# is not working so check difference in MEDIA and STATIC.

In general I was lacking (and still do :) ) basic knowledge on uploads and displaying the static files.

Thanks.

Body:
When you will create the new record for table Post then you have to upload the Image File so if you set the media url then it will store at the specified location.
Try to set the MEDIA_ROOT and MEDIA_URL in settings.py file Eg.

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

You can seen the details in the django documentation.


问:
Can a class inside a class call a getter method from the outer class?
I have a class inside a class.

The outer class does some processing to generate an array of values.

I want the inner class to be able to access the outer class' array.

Is there a clean way to achieve this?

I'm thinking to have a method in the outer class that calls a method in the inner class sending him the address of the array and the inner class needs to hold a pointer in its private member section in order to later point to it by assignment from the method that receives the address. But this feels a little clunky.

答:
C++ has a concept of the nested class. A nested class, which is declared in another enclosing class. It is a member and has the same access rights as any other member of the enclosing class. But the members of an enclosing class have no special access to members of a nested class.you can refer to this sample code. Hope this will help

```<code>class Outer {
   private:
       int arry[];

   class inner {
         private:
         int innerArr[];
      void Fun(Outer *e) {
        innerArr = e->arry;

      }
   };
};
int main(){
Outer out;
Outer::inner in;
in.Fun(out);
</code>```

}

Body:
C++ has a concept of the nested class. A nested class, which is declared in another enclosing class. It is a member and has the same access rights as any other member of the enclosing class. But the members of an enclosing class have no special access to members of a nested class.you can refer to this sample code. Hope this will help

class Outer {
   private:
       int arry[];

   class inner {
         private:
         int innerArr[];
      void Fun(Outer *e) {
        innerArr = e->arry;

      }
   };
};
int main(){
Outer out;
Outer::inner in;
in.Fun(out);

}


问:
Unable to take Input values from Tensorflow Serving client request
I am trying to deploy my tensorflow model in a tensorflow serving using tensorflow saved model. Input for my tf model is a string value and i have defined my signature as below

```<code>        prediction_signature = (
            tf.saved_model.signature_def_utils.build_signature_def(
                inputs={'input_path': tensor_info_input},
                outputs={'output_prediction': tensor_info_output},
                method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME))

        builder.add_meta_graph_and_variables(
            sess, [tf.saved_model.tag_constants.SERVING],
            signature_def_map={
                'predict_images':
                    prediction_signature,
            })
</code>```

My objective is to read a image from the path specified in signature definition. How do i get the input_path from input definition and convert the tensor into actual string value to read the path

答:
You can place the below mentioned code in a Python file say, Client.py. And for inference, you can run the below mentioned command in the Terminal

```<code>python Client.py --image abc/0.png --model mnist --signature_name predict
</code>```

This will take the path of the image, "abc/0.png" and will convert it to Numeric Values, and will run the inference.

Code for Client.py is mentioned below. The below code is for MNIST Images. You can reshape your images accordingly:

```<code>from __future__ import print_function

import argparse
import time
import numpy as np
from scipy.misc import imread

import grpc
from tensorflow.contrib.util import make_tensor_proto

from tensorflow_serving.apis import predict_pb2
from tensorflow_serving.apis import prediction_service_pb2_grpc

def run(host, port, image, model, signature_name):

    channel = grpc.insecure_channel('{host}:{port}'.format(host=host, port=port))
    stub = prediction_service_pb2_grpc.PredictionServiceStub(channel)

    # Read an image
    data = imread(image)
    data = data.astype(np.float32)
    print(data)

    start = time.time()

    # Call classification model to make prediction on the image
    request = predict_pb2.PredictRequest()
    request.model_spec.name = model
    request.model_spec.signature_name = signature_name
    request.inputs['image'].CopyFrom(make_tensor_proto(data, shape=[1, 28, 28, 1]))

    result = stub.Predict(request, 10.0)

    end = time.time()
    time_diff = end - start

    # Reference:
    # How to access nested values
    # https://stackoverflow.com/questions/44785847/how-to-retrieve-float-val-from-a-predictresponse-object
    print(result)
    print('time elapased: {}'.format(time_diff))

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--host', help='Tensorflow server host name', default='localhost', type=str)
    parser.add_argument('--port', help='Tensorflow server port number', default=8500, type=int)
    parser.add_argument('--image', help='input image', type=str)
    parser.add_argument('--model', help='model name', type=str)
    parser.add_argument('--signature_name', help='Signature name of saved TF model',
                        default='serving_default', type=str)

    args = parser.parse_args()
    run(args.host, args.port, args.image, args.model, args.signature_name)
</code>```

For more information, you can refer this beautiful article on Tensorflow Serving,
https://medium.com/@yuu.ishikawa/serving-pre-modeled-and-custom-tensorflow-estimator-with-tensorflow-serving-12833b4be421

Body:
I am trying to deploy my tensorflow model in a tensorflow serving using tensorflow saved model. Input for my tf model is a string value and i have defined my signature as below

        prediction_signature = (
            tf.saved_model.signature_def_utils.build_signature_def(
                inputs={'input_path': tensor_info_input},
                outputs={'output_prediction': tensor_info_output},
                method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME))

        builder.add_meta_graph_and_variables(
            sess, [tf.saved_model.tag_constants.SERVING],
            signature_def_map={
                'predict_images':
                    prediction_signature,
            })

My objective is to read a image from the path specified in signature definition. How do i get the input_path from input definition and convert the tensor into actual string value to read the path

Body:
You can place the below mentioned code in a Python file say, Client.py. And for inference, you can run the below mentioned command in the Terminal

python Client.py --image abc/0.png --model mnist --signature_name predict

This will take the path of the image, "abc/0.png" and will convert it to Numeric Values, and will run the inference.

Code for Client.py is mentioned below. The below code is for MNIST Images. You can reshape your images accordingly:

from __future__ import print_function

import argparse
import time
import numpy as np
from scipy.misc import imread

import grpc
from tensorflow.contrib.util import make_tensor_proto

from tensorflow_serving.apis import predict_pb2
from tensorflow_serving.apis import prediction_service_pb2_grpc

def run(host, port, image, model, signature_name):

    channel = grpc.insecure_channel('{host}:{port}'.format(host=host, port=port))
    stub = prediction_service_pb2_grpc.PredictionServiceStub(channel)

    # Read an image
    data = imread(image)
    data = data.astype(np.float32)
    print(data)

    start = time.time()

    # Call classification model to make prediction on the image
    request = predict_pb2.PredictRequest()
    request.model_spec.name = model
    request.model_spec.signature_name = signature_name
    request.inputs['image'].CopyFrom(make_tensor_proto(data, shape=[1, 28, 28, 1]))

    result = stub.Predict(request, 10.0)

    end = time.time()
    time_diff = end - start

    # Reference:
    # How to access nested values
    # https://stackoverflow.com/questions/44785847/how-to-retrieve-float-val-from-a-predictresponse-object
    print(result)
    print('time elapased: {}'.format(time_diff))

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--host', help='Tensorflow server host name', default='localhost', type=str)
    parser.add_argument('--port', help='Tensorflow server port number', default=8500, type=int)
    parser.add_argument('--image', help='input image', type=str)
    parser.add_argument('--model', help='model name', type=str)
    parser.add_argument('--signature_name', help='Signature name of saved TF model',
                        default='serving_default', type=str)

    args = parser.parse_args()
    run(args.host, args.port, args.image, args.model, args.signature_name)

For more information, you can refer this beautiful article on Tensorflow Serving,
https://medium.com/@yuu.ishikawa/serving-pre-modeled-and-custom-tensorflow-estimator-with-tensorflow-serving-12833b4be421


问:
How to persist file upload fields after a rails validation error
I have a form with multiple file uploads, The issue is when i am submitting the form and an validation error occurs, the file input field gets reset.

I basically wanted to persist those files inside the file input field for the complete process.

I have also gone through few links

How can I "keep" the uploaded image on a form validation error?

Please let me know what are the various options in such cases that one can follow.

答:
Browsers block against setting the value attribute on input of file
  type for security reasons so that you can't upload a file without the
  user's selected any file itself.

Pre-Populate HTML form file input

You can use carrierwave: https://github.com/carrierwaveuploader/carrierwave

Or validate the model via js request.


问:
How to set edit mask where zero means 0 and not any other number?
Situation:
Character 0 has special meaning in number display formats. My code picks date on certain conditions and make display format for another edit field (column in DW) for example 1905 where 19 is last 2 digits of current year and 05 is the current month + "-" + "####" so final display format that i want to set becomes like 1905-####.

Problem:
The zero in 1905 shows up in the target edit field (column) as 19 5. There is space shown at the location where 0 resides. The final result of the edit mask 1905-#### shows in edit field as 19 5- and cursor points exactly after digit 9 which i dont want.

Expecting:
I want to have the display format as "1905-    " and keyboard cursor pointing after dash '-' for remaining 4 digits entry.

Question:
How to set number display format or edit mask to ignore special meaning of 0 and take 0 as digit zero and not as any other number?

For example this is how i set mask for Trans_ID column which is string type column.

```<code>dw_1.Object.Trans_ID.EditMask.Mask = Right(String(Date(dw_1.Object.DOB[1]), "YYYY"),2) +  String(Date(dw_1.Object.DOB[1]), "MM") + "-####"
</code>```

PowerBuilder v12.5

答:
Try

```<code>string(month(today()), '00')
</code>```

or, for the whole string

```<code>Right(String(Date(dw_1.Object.DOB[1]), "YYYY"),2) +  String(month(Date(dw_1.Object.DOB[1]), "00") + "-####"
</code>```

Body:
Situation:
Character 0 has special meaning in number display formats. My code picks date on certain conditions and make display format for another edit field (column in DW) for example 1905 where 19 is last 2 digits of current year and 05 is the current month + "-" + "####" so final display format that i want to set becomes like 1905-####.

Problem:
The zero in 1905 shows up in the target edit field (column) as 19 5. There is space shown at the location where 0 resides. The final result of the edit mask 1905-#### shows in edit field as 19 5- and cursor points exactly after digit 9 which i dont want.

Expecting:
I want to have the display format as "1905-    " and keyboard cursor pointing after dash '-' for remaining 4 digits entry.

Question:
How to set number display format or edit mask to ignore special meaning of 0 and take 0 as digit zero and not as any other number?

For example this is how i set mask for Trans_ID column which is string type column.

dw_1.Object.Trans_ID.EditMask.Mask = Right(String(Date(dw_1.Object.DOB[1]), "YYYY"),2) +  String(Date(dw_1.Object.DOB[1]), "MM") + "-####"

PowerBuilder v12.5

Body:
Try

string(month(today()), '00')

or, for the whole string

Right(String(Date(dw_1.Object.DOB[1]), "YYYY"),2) +  String(month(Date(dw_1.Object.DOB[1]), "00") + "-####"


问:
python mutable string class not working correctly
I created a mutable String class in Python, based on the builtin str class.

I can change the first character, but when I call capitalize(), it uses the old value instead

```<code>class String(str):

    def __init__(self, string):
        self.string = list(string)

    def __repr__(self):
        return "".join(self.string)

    def __str__(self):
        return "".join(self.string)

    def __setitem__(self, index, value):
        self.string[index] = value

    def __getitem__(self, index):
        if type(index) == slice:
            return "".join(self.string[index])
        return self.string[index]

    def __delitem__(self, index):
        del self.string[index]

    def __add__(self, other_string):
        return String("".join(self.string) + other_string)

    def __len__(self):
        return len(self.string)

text = String("cello world")
text[0] = "h"
print(text)
print(text.capitalize())
</code>```

Expected Output :

```<code>hello world

Hello world
</code>```

Actual Output :

```<code>hello world

Cello world
</code>```

答:
Your implementation inherits from str, so it brings along all the methods that str implements. However, the implementation of the str.capitalize() method is not designed to take that into account. Methods like str.capitalize() return a new str object with the required change applied.

Moreover, the Python built-in types do not store their state in a __dict__ mapping of attributes, but use internal struct data structures) only accessible on the C level; your self.string attribute is not where the (C equivalent of) str.__new__() stores the string data. The str.capitalize() method bases its return value on the value stored in the internal data structure when the instance was created, which can't be altered from Python code.

You'll have to shadow all the str methods that return a new value, including str.capitalize() to behave differently. If you want those methods from returning a new instance to changing the value in-place, you have to do so yourself:

```<code>class String(str):
    # ...

    def capitalize(self):
        """Capitalize the string, in place"""
        self.string[:] ''.join(self.string).capitalize()
        return self  # or return None, like other mutable types would do
</code>```

That can be a lot of work, writing methods like these for every possible str method that returns an updated value. Instead, you could use a __getattribute__ hook to redirect methods:

```<code>_MUTATORS = {'capitalize', 'lower', 'upper', 'replace'}  # add as needed

class String(str):
    # ...

    def __getattribute__(self, name):
        if name in _MUTATORS:
            def mutator(*args, **kwargs):
                orig = getattr(''.join(self.string), name)
                self.string[:] = orig(*args, **kwargs)
                return self  # or return None for Python type consistency
            mutator.__name__ = name
            return mutator
        return super().__getattribute__(name)
</code>```

Demo with the __getattribute__ method above added to your class:

```<code>>>> text = String("cello world")
>>> text[0] = "h"
>>> print(text)
hello world
>>> print(text.capitalize())
Hello world
>>> print(text)
Hello world
</code>```

One side note: the __repr__ method should use repr() to return a proper representation, not just the value:

```<code>def __repr__(self):
    return repr(''.join(self.string))
</code>```

Also, take into account that most Python APIs that are coded in C and take a str value as input, are likely to use the C API for Unicode strings and so not only completely ignore your custom implementations but like the original str.capitalize() method will also ignore the self.string attribute. Instead, they too will interact with the internal str data.

Body:
I created a mutable String class in Python, based on the builtin str class.

I can change the first character, but when I call capitalize(), it uses the old value instead

class String(str):

    def __init__(self, string):
        self.string = list(string)

    def __repr__(self):
        return "".join(self.string)

    def __str__(self):
        return "".join(self.string)

    def __setitem__(self, index, value):
        self.string[index] = value

    def __getitem__(self, index):
        if type(index) == slice:
            return "".join(self.string[index])
        return self.string[index]

    def __delitem__(self, index):
        del self.string[index]

    def __add__(self, other_string):
        return String("".join(self.string) + other_string)

    def __len__(self):
        return len(self.string)

text = String("cello world")
text[0] = "h"
print(text)
print(text.capitalize())

Expected Output :

hello world

Hello world

Actual Output :

hello world

Cello world

Body:
Your implementation inherits from str, so it brings along all the methods that str implements. However, the implementation of the str.capitalize() method is not designed to take that into account. Methods like str.capitalize() return a new str object with the required change applied.

Moreover, the Python built-in types do not store their state in a __dict__ mapping of attributes, but use internal struct data structures) only accessible on the C level; your self.string attribute is not where the (C equivalent of) str.__new__() stores the string data. The str.capitalize() method bases its return value on the value stored in the internal data structure when the instance was created, which can't be altered from Python code.

You'll have to shadow all the str methods that return a new value, including str.capitalize() to behave differently. If you want those methods from returning a new instance to changing the value in-place, you have to do so yourself:

class String(str):
    # ...

    def capitalize(self):
        """Capitalize the string, in place"""
        self.string[:] ''.join(self.string).capitalize()
        return self  # or return None, like other mutable types would do

That can be a lot of work, writing methods like these for every possible str method that returns an updated value. Instead, you could use a __getattribute__ hook to redirect methods:

_MUTATORS = {'capitalize', 'lower', 'upper', 'replace'}  # add as needed

class String(str):
    # ...

    def __getattribute__(self, name):
        if name in _MUTATORS:
            def mutator(*args, **kwargs):
                orig = getattr(''.join(self.string), name)
                self.string[:] = orig(*args, **kwargs)
                return self  # or return None for Python type consistency
            mutator.__name__ = name
            return mutator
        return super().__getattribute__(name)

Demo with the __getattribute__ method above added to your class:

>>> text = String("cello world")
>>> text[0] = "h"
>>> print(text)
hello world
>>> print(text.capitalize())
Hello world
>>> print(text)
Hello world

One side note: the __repr__ method should use repr() to return a proper representation, not just the value:

def __repr__(self):
    return repr(''.join(self.string))

Also, take into account that most Python APIs that are coded in C and take a str value as input, are likely to use the C API for Unicode strings and so not only completely ignore your custom implementations but like the original str.capitalize() method will also ignore the self.string attribute. Instead, they too will interact with the internal str data.


问:
What is the most efficient way to convert list of structs to dictionary?
I have a struct that consists of multiple type elements as follows:

public struct mystruct
{
        int key;
        string value;
}
```

<p>What is the most efficient way to convert list of this struct to a dictionary that its keys are <code>mystruct.key</code> and values are list of <code>mystruct.value</code>?</p>

<p>i implement it as follows</p>

<pre class="lang-cs prettyprint-override"><code>Dictionary<int, List<string>> mydictionary = new Dictionary<int, List<string>>();
foreach (var item in mystruct_list)
            {
                if (!mydictionary.ContainsKey(item.key))
                    mydictionary.Add(item.key, new List<string>());
                mydictionary[item.key].Add(item.value);
            }
</code>```

答:
Assuming that there is collection of mystruct objects and key and value fields are public you can use code below:</p>

```<code>List<mystruct> myElements ... //just declaration
var result = myElements
    .GroupBy(c => c.key)
    .ToDictionary(
         c => c.Key,
         c => c.Select(i => i.value).ToList());
</code>```

Body:
I have a struct that consists of multiple type elements as follows:

public struct mystruct
{
        int key;
        string value;
}

What is the most efficient way to convert list of this struct to a dictionary that its keys are mystruct.key and values are list of mystruct.value?

i implement it as follows

Dictionary<int, List<string>> mydictionary = new Dictionary<int, List<string>>();
foreach (var item in mystruct_list)
            {
                if (!mydictionary.ContainsKey(item.key))
                    mydictionary.Add(item.key, new List<string>());
                mydictionary[item.key].Add(item.value);
            }

Body:
Assuming that there is collection of mystruct objects and key and value fields are public you can use code below:

List<mystruct> myElements ... //just declaration
var result = myElements
    .GroupBy(c => c.key)
    .ToDictionary(
         c => c.Key,
         c => c.Select(i => i.value).ToList());


问:
How do I activate the click event for a button on Android?
How do I activate the click event for a button on Android?</p>

答:
In your layout file, include this in the button definition:

```<code>android:onClick="myClickHandler"
</code>```

In your activity code, implement the handler:

```<code>void myClickHandler(View view) {
    ...
}
</code>```

Body:
In your layout file, include this in the button definition:

android:onClick="myClickHandler"

In your activity code, implement the handler:

void myClickHandler(View view) {
    ...
}


问:
Unable to copy files from current directory to Remote directory path
I have an application hosted in IIS server and it executes a batch file. The batch file contains few CMD command such as mkdir, xcopy etc. When I run the same application from Visual Studio, it copies all the files inside the new folder successfully. When I try to run the same application from IIS, it ends without throwing any error. The authentication used in the application is Windows and it is configured inside config file, not in internet manager.

So, below are the point of concerns:

While running the application, which user helps to authenticate the folder access, is that IIS user or the current user?

Is that access related issue or any other configuration related?

What is the preferable solution?

Thanks in advance.

答:
The user that is used to authenticate the folder access is the user with whom your IIS application pool is associated

Without any error message it is hard to say. However it is most likely to be because of an authorization issue yes

What you can try is to allow access to the folder for the user that is associated with your IIS application pool and see if the problem persists

Hope it helps.


问:
Access service api exposed as clusterIP in kubernete
I have two application, both deployed in same cluster.

Now from web, there is an ajax request to get data from api, but it always return 502 Connection refused.

here is my jquery code (web).

```<code>$.get("http://10.43.244.118/api/users", function (data) {
        console.log(data);
        $('#table').bootstrapTable({
            data: data
        });
    });
</code>```

Note: when I change the service type to LoadBalancer from ClusterIP then it works fine.

答:
```<code>1\Ajax is a front-end call to api.
2\The front-end call is to directly communicate with the user(Browser) and the called end and the api service.
3\ ClusterIP is internal to the cluster,User(Browser) cannot communicate with it.
4\ NodePort and LoadBalancer can expose the internal network, of course, it can be accessed normally.
</code>```

Body:
I have two application, both deployed in same cluster.

Now from web, there is an ajax request to get data from api, but it always return 502 Connection refused.

here is my jquery code (web).

$.get("http://10.43.244.118/api/users", function (data) {
        console.log(data);
        $('#table').bootstrapTable({
            data: data
        });
    });

Note: when I change the service type to LoadBalancer from ClusterIP then it works fine.


问:
Laravel 5 : How to redirect to login page on invalid URL input?
I'm new to laravel 5. I just want know how to protect routes from invalid URL input. An example of an invalid input URL is shown below:

```<code> http://localhost:90/csadcsvs
</code>```

If someone enters invalid URL from my laravel project, I just want to redirect to login page.

答:
```<code>Route::get('/{any}','Pagecontroller@index');
</code>```

any url which is not declared in the route will be accepted by {any} and the will be controlled back to index.

Body:
I'm new to laravel 5. I just want know how to protect routes from invalid URL input. An example of an invalid input URL is shown below:

 http://localhost:90/csadcsvs

If someone enters invalid URL from my laravel project, I just want to redirect to login page.

Body:
Route::get('/{any}','Pagecontroller@index');

any url which is not declared in the route will be accepted by {any} and the will be controlled back to index.


问:
Converting audio file when uploaded to google cloud storage
I have an app, where users record audio and then "send" to each other. I'm writing "send", because actually the file is stored on server, and just provided to the recipient, when they want to listen.

My issue is, that I need to reformat the recording (currently .caf) to .mp3, so they will be both smaller and so I can play them with the audioplayer I'm using.

My question then is:
Is it possible to have a cloud function trigger on user upload, that would take the .caf file, convert it and in its place put a .mp3 file? Can't find anywhere in the docs where it says whether the new file would have same or different url.

答:
Yes, this would be possible if it exists a Node.js library that does the conversion from .caf to .mp3. You should preferably work with a library that handle asynchronous tasks through promises.

Since you are going to write a different file (different extension) the download URL will be different. But it should not be a problem to manage this situation: you can generate a new download URL for the mp3 file and, for example, save it in the database (or generate this URL on the fly, as shown here in the doc).

You will find in the collection of official Cloud Functions samples some Cloud Functions that manipulate files (and in particular use the tmp directory for that). For example there is the generate-thumbnail and the moderate-images.

However, you have to take into account that the maximum execution time for a Cloud Function is 9 minutes. So if some of your audio files need more than 9 minutes of transformation processing it will be a problem.


问:
Undefined is not an object for react navigation
I have two components for my project, and I have gone through all the steps for react navigation as follow:

```<code>// App.js
import React from 'react';
import Main from './app/componenets/Main'
import details from './app/componenets/details'
import { createStackNavigator, createAppContainer } from 'react-navigation'

const mainNavigator = createStackNavigator(
  {
    MainScreen: Main,
    detailsScreen: details,
  },
  {
   initialRouteName :'MainScreen'
  }
);
const AppContainer = createAppContainer(mainNavigator);

export default class App extends React.Component{

render() {
return(
  <AppContainer />
);
}
}
</code>```

Then I have my Main.js which I have a method as follow:

```<code>    import React from 'react';
import {
    StyleSheet ,
     Text,
     View,
    } from 'react-native'
import Note from './Note'
import detail from './details'
import { createStackNavigator, createAppContainer } from "react-navigation";

export default class Main extends React.Component {

  static navigationOptions = {
    title: 'To do list',
    headerStyle: {
      backgroundColor: '#f4511e',
    },
  };

  constructor(props){
    super(props);
    this.state = {
      noteArray: [],
      noteText: ''
    }
  }

render() {
    let notes = this.state.noteArray.map((val,key) => {
      return <Note key={key} keyval={key} val={val}
      goToDetailPage= {() => this.goToNoteDetail(key)} />
    });
    const { navigation } = this.props;
    return(
        <View style={styles.container}>
            <View style={styles.footer}>
                <TextInput
                onChangeText={(noteText) => this.setState({noteText})}
                style={styles.textInput}
                placeholder='What is your next Task?'
                placeholderTextColor='white'
                underlineColorAndroid = 'transparent'
                >
                </TextInput>
            </View>
            <TouchableOpacity onPress={this.addNote.bind(this)} style={styles.addButton}>
                <Text style={styles.addButtonText}> + </Text>
            </TouchableOpacity>
        </View>
      );
    }
    //This method is declared in my Note.js
    goToNoteDetail=(key)=>{
      this.props.navigation.navigate('detailsScreen')
      }
}
</code>```

//Styles which I didn't post to be short in code here
But when I try to do the navigation I get this error:
'undefined is not and object(evaluating 'this.props.val.date')
Do I need to pass the props in a way? or should I do anything else? I am new to React native and confused!

答:
Just remove createAppContainer

```<code>const AppContainer = mainNavigator;
</code>```

and tell me what react-navigation that you work with

Body:
I have two components for my project, and I have gone through all the steps for react navigation as follow:

// App.js
import React from 'react';
import Main from './app/componenets/Main'
import details from './app/componenets/details'
import { createStackNavigator, createAppContainer } from 'react-navigation'

const mainNavigator = createStackNavigator(
  {
    MainScreen: Main,
    detailsScreen: details,
  },
  {
   initialRouteName :'MainScreen'
  }
);
const AppContainer = createAppContainer(mainNavigator);

export default class App extends React.Component{

render() {
return(
  <AppContainer />
);
}
}

Then I have my Main.js which I have a method as follow:

    import React from 'react';
import {
    StyleSheet ,
     Text,
     View,
    } from 'react-native'
import Note from './Note'
import detail from './details'
import { createStackNavigator, createAppContainer } from "react-navigation";

export default class Main extends React.Component {

  static navigationOptions = {
    title: 'To do list',
    headerStyle: {
      backgroundColor: '#f4511e',
    },
  };

  constructor(props){
    super(props);
    this.state = {
      noteArray: [],
      noteText: ''
    }
  }

render() {
    let notes = this.state.noteArray.map((val,key) => {
      return <Note key={key} keyval={key} val={val}
      goToDetailPage= {() => this.goToNoteDetail(key)} />
    });
    const { navigation } = this.props;
    return(
        <View style={styles.container}>
            <View style={styles.footer}>
                <TextInput
                onChangeText={(noteText) => this.setState({noteText})}
                style={styles.textInput}
                placeholder='What is your next Task?'
                placeholderTextColor='white'
                underlineColorAndroid = 'transparent'
                >
                </TextInput>
            </View>
            <TouchableOpacity onPress={this.addNote.bind(this)} style={styles.addButton}>
                <Text style={styles.addButtonText}> + </Text>
            </TouchableOpacity>
        </View>
      );
    }
    //This method is declared in my Note.js
    goToNoteDetail=(key)=>{
      this.props.navigation.navigate('detailsScreen')
      }
}

//Styles which I didn't post to be short in code here
But when I try to do the navigation I get this error:
'undefined is not and object(evaluating 'this.props.val.date')
Do I need to pass the props in a way? or should I do anything else? I am new to React native and confused!

Body:
Just remove createAppContainer

const AppContainer = mainNavigator;

and tell me what react-navigation that you work with


问:
@angular/service-worker/src/module.d.ts (30,9): Type 'ModuleWithProviders' is not generic
I have implemented "angular-push-notifications" in angular-4 using this link:

https://blog.angular-university.io/angular-push-notifications/

I have done set-up "Service Workers" in the following way

```<code>1. add this package npm i -S @angular/pwa
2. enable service-worker in .angular-cli.json
"apps": [
    {
      "root": "src",
      "outDir": "dist",
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      },
      "serviceWorker": true
    }
</code>```

and then start my server using npm start, and the server will throw me this error

ERROR in ./node_modules/@angular/service-worker/src/module.d.ts (30,9): Type 'ModuleWithProviders' is not generic.

I don't understand what I need to do in this case.

please help me to short out this error.

thank you in advance

答:
I have removed the Service Workers module and remove package angular-push-notifications in angular-4

and use custom push notification using socket.io with my database,
I have set the logic when new record added in the DB, I have notified the user using custom notification

Body:
I have implemented "angular-push-notifications" in angular-4 using this link:

https://blog.angular-university.io/angular-push-notifications/

I have done set-up "Service Workers" in the following way

1. add this package npm i -S @angular/pwa
2. enable service-worker in .angular-cli.json
"apps": [
    {
      "root": "src",
      "outDir": "dist",
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      },
      "serviceWorker": true
    }

and then start my server using npm start, and the server will throw me this error

ERROR in ./node_modules/@angular/service-worker/src/module.d.ts (30,9): Type 'ModuleWithProviders' is not generic.

I don't understand what I need to do in this case.

please help me to short out this error.

thank you in advance


问:
How to communicate between the different pieces when using MVVM in iOS
I did my research but because I don't have enough experience I don't know what is the best way to implement communication of the UserManger class when using MVVM design pattern.

So my timer app that got sync to the Cloud.
So far I'm having HomeViewController, TimerViewModel, TimerModel, UserManager.

The UserManager object is taking care of authenticating User and also of communicating the authentication state to other classes.

The states are:
.notSigned, .signing and .signed

Here I would need more explanation. To which object should the UserManager communicate the updated authentication state? Is it owned by the view controller or view model?

And another question. I don't know if UserManager suppose to communicate only to one class or is it ok to talk to many objects at the same time.
I think that most of the objects simultaneously need to know if the user is signed or not. If this is true, what kind of communication do I implement?

For one to many, I'm thinking to implement the Observable protocol described in this article. If necessary I can copy the code  instead of the article link.

I hope I described it well. I will appreciate any kind of answer. Or any new insights, big picture ideas about how to set up object communication throught the app. Do you know any good article about that?

答:
All the business logic should be inside the ViewModel. The ViewModel should be the thing that invokes any method inside the UserManager. The UserManager should return the result parsed as the Model to the ViewModel. The ViewModel then needs to format the data and alert the ViewController to the event/data/network completion etc.

Examples of formatting the data:

Lets say a networking request gives you firstName and lastName. But you only have 1 label to display the full thing. The viewModel should add those strings together (with a space) and provide a fullName property to the VC.

If you got back a Double, but need to format it into currency and display a symbol.

Taking a timestamp and formatting to a date string.

These are the kinds of things that a ViewModel should do. So that they can be tested independently of the UI code and lifecycle.

Communication:

You can use the standard Apple API designs and create a ViewModel protocol, with a delegate and a callback. Each VM would confirm to the protocol, VC would set itself as the delegate of its VM and run your code inside the VC's delegate callback function.

Naming:

The word "Manager" has fallen out of favour because it is typically a default word used when the use of the class is unclear. For this reason it has a thousand different definitions. A class responsible for making networking requests and/or storing state should be called a "Service". i.e. "UserService".

Sharing state:

I'm probably going to make a lot of people angry with this one. But when state needs to be shared across multiple VC's, components, VM's etc. I follow the design patterns / architecture that Angular has setup. I make my service classes singletons. Have them store the state. Then Each ViewModel has one source of truth for each item and can format it at will.

Other people use frameworks such as RxSwift and use Observables and similar technologies. My personal opinion is that this is tremendous overkill, involves a huge learning curve, means adding a lot of big libraries and brings in a lot of risk to the project. I prefer to stick to the patterns already available and working in the eco-system and keep things simple.

Edit: one-to-many:

It can depend on your use case and architecture decisions. I've found it possible to avoid the one-to-many issue in the majority of my uses cases, by having the singleton store the state and have the VC trigger something in the ViewModel on each call to viewDidAppear. Each time the VC opened, it got the latest data and continued on. The reason I bring up avoiding the one-to-many is that in the majority of cases there is only 1 VC on screen and running code at any point in time (using childViewControllers is the exception). I've found it possible to just side step this issue entirely and keep the apps simple by changing how I interact with the data, rather than changing the structure of Apples APIs.

Now depending on your use case, this might not work if you have multiple timers and lots of screen switching, there could be a chance to miss an event.

NotificationCenter is not my favourite approach, but if I had a one-to-many situation I couldn't avoid, I would give it a go. As mentioned in the article there are some downsides with swift features you can access through this means. It at least has the added benefit of being something thats been around for a long time and is well understood and unlikely to change much. There won't be any huge learning curve if other developers are working on this app.

The other approach mentioned in the article is interesting, building your own stripped down version of RxSwift to add Observers into the project. My problem at the minute with RxSwift is when people don't use it in conjunction with singletons or some sort of central point of control. When you have an Observable on object A, Observed by B that also has another Observable Observed by C, which calls a function on D which is Observed by E, F and G .... and so on. This style of code is incredibly messy, hard to read, error prone and difficult to debug. So long as that is avoided and its the singleton that has the observable and all the ViewModels are observing, I think something like that would be ok if you are willing to put the effort in to build and maintain it.


问:
How to create generic Default Empty Cell for TableViewSource
In my application, I have a lot of List and every time I want to make sure that I always have a default cell for safety. That why, every time I create a list in my application, I recreate an empty Cell in my tableView.

I can't see any solution, except to use XIB for reusesability.

答:
You need to create a TableSourceBase that is going to manage your DefaultEmptyCell and any other cell that is commun to your app.
The trick here is to yield all your xib before using them. Otherwise you will have a crash.

```<code>public abstract class TableViewSourceBase : UITableViewSource
    {
        protected const string DefaultEmptyCellIdentifier = "DefaultEmptyCell";

        protected virtual IEnumerable<(UINib, string)> GetNibsForCellReuse()
        {
            yield return (UINib.FromName(DefaultEmptyCellIdentifier, null), DefaultEmptyCellIdentifier);
        }

        public void RegisterNibs(UITableView tableView)
        {
            foreach (var (xib, key) in GetNibsForCellReuse())
            {
                tableView.RegisterNibForCellReuse(xib, key);
            }
        }

        public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
        {
            UITableViewCell cell = null;
            cell = (DefaultEmptyCell)tableView.DequeueReusableCell(DefaultEmptyCellIdentifier);
            return cell;
        }

        public override nint RowsInSection(UITableView tableview, nint section)
        {
            return 0;
        }
    }
</code>```

Now that we have our Base Class

You can manage you empty cell in every TableSource.

```<code>public class ListTableViewSource : TableViewSourceBase
    {
        private const string SimpleCellIdentifier = "SimpleCell";

        public ListTableViewSource()
        {
        }

        public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
        {
            UITableViewCell cell = null;

            if (indexPath.Row >= [COUNT])
                return base.GetCell(tableView, indexPath);

            //Load your other cells here according to your need

            return cell;
        }

        protected override IEnumerable<(UINib, string)> GetNibsForCellReuse()
        {
            yield return (UINib.FromName(SimpleCellIdentifier, null), SimpleCellIdentifier);

            foreach (var tuple in base.GetNibsForCellReuse())
            {
                yield return tuple;
            }
        }
    }
</code>```

Like that you won’t have to bother to initiate your Xib, handle your identifier which is simpler like you ask.

Body:
You need to create a TableSourceBase that is going to manage your DefaultEmptyCell and any other cell that is commun to your app.
The trick here is to yield all your xib before using them. Otherwise you will have a crash.

public abstract class TableViewSourceBase : UITableViewSource
    {
        protected const string DefaultEmptyCellIdentifier = "DefaultEmptyCell";

        protected virtual IEnumerable<(UINib, string)> GetNibsForCellReuse()
        {
            yield return (UINib.FromName(DefaultEmptyCellIdentifier, null), DefaultEmptyCellIdentifier);
        }

        public void RegisterNibs(UITableView tableView)
        {
            foreach (var (xib, key) in GetNibsForCellReuse())
            {
                tableView.RegisterNibForCellReuse(xib, key);
            }
        }

        public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
        {
            UITableViewCell cell = null;
            cell = (DefaultEmptyCell)tableView.DequeueReusableCell(DefaultEmptyCellIdentifier);
            return cell;
        }

        public override nint RowsInSection(UITableView tableview, nint section)
        {
            return 0;
        }
    }

Now that we have our Base Class

You can manage you empty cell in every TableSource.

public class ListTableViewSource : TableViewSourceBase
    {
        private const string SimpleCellIdentifier = "SimpleCell";

        public ListTableViewSource()
        {
        }

        public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
        {
            UITableViewCell cell = null;

            if (indexPath.Row >= [COUNT])
                return base.GetCell(tableView, indexPath);

            //Load your other cells here according to your need

            return cell;
        }

        protected override IEnumerable<(UINib, string)> GetNibsForCellReuse()
        {
            yield return (UINib.FromName(SimpleCellIdentifier, null), SimpleCellIdentifier);

            foreach (var tuple in base.GetNibsForCellReuse())
            {
                yield return tuple;
            }
        }
    }

Like that you won’t have to bother to initiate your Xib, handle your identifier which is simpler like you ask.


问:
PDO with parameter
I would like to have various option to change $this_var that contain different fieldname
such as 'apple'=1 or 'orange'=1, is it possible?</p>

```<code>$statement->prepare(SELECT * table WHERE $this_var = 1);
</code>```

答:
Given

```<code>$this_var = 'apple';
$statement->prepare("SELECT * table WHERE $this_var = 1");
</code>```

the query would be SELECT * table WHERE apple = 1;

Title: PDO with parameter

Body:
I would like to have various option to change $this_var that contain different fieldname
such as 'apple'=1 or 'orange'=1, is it possible?

$statement->prepare(SELECT * table WHERE $this_var = 1);

Body:
Given

$this_var = 'apple';
$statement->prepare("SELECT * table WHERE $this_var = 1");

the query would be SELECT * table WHERE apple = 1;


答:
You inherited str's definition of capitalize, which ignores your class's behaviors and just uses the underlying data of the "real" str.

Inheriting from a built-in type like this effectively requires you to reimplement every method, or do some metaprogramming with __getattribute__; otherwise, the underlying type's behaviors will be inherited unmodified.

Title: python mutable string class not working correctly


问:
how to handle ValueState of HyperLogLogPlus in flink
When using ValueState of java object that is not POJO, like HyperLogLogPlus, how to handle the serialization problem?

I have tried defining HyperLogLogPlusSerializer extends TypeSerializer, code as:

```<code>public class HyperLogLogPlusSerializer extends TypeSerializer<HyperLogLogPlus> {

    private static Logger logger = LoggerFactory.getLogger(HyperLogLogPlusSerializer.class);

    private static final long serialVersionUID = 1L;

    @Override
    public boolean isImmutableType() {
        return false;
    }

    @Override
    public TypeSerializer<HyperLogLogPlus> duplicate() {
        logger.info("duplicate invoked.");
        return this;
    }

    @Override
    public HyperLogLogPlus createInstance() {
        return new HyperLogLogPlus(20,25);
    }

    @Override
    public HyperLogLogPlus copy(HyperLogLogPlus from) {
        try{
            byte[] bytes = from.getBytes();
            return HyperLogLogPlus.Builder.build(bytes);
        }catch (Exception e){

        }
        return null;
    }

    @Override
    public HyperLogLogPlus copy(HyperLogLogPlus from, HyperLogLogPlus reuse) {
        return copy(from);
    }

    @Override
    public int getLength() {
        return -1;
    }

    @Override
    public void serialize(HyperLogLogPlus record, DataOutputView target) throws IOException {
        byte[] bytes = record.getBytes();
        target.writeInt(bytes.length);
        target.write(bytes);
        logger.info("serialize:{}", bytes.length);
    }

    @Override
    public HyperLogLogPlus deserialize(DataInputView source) throws IOException {
        int dataLength = source.readInt();
        byte[] bytes = new byte[dataLength];
        source.read(bytes);
        logger.info("deserialize:{}", bytes.length);
        return HyperLogLogPlus.Builder.build(bytes);
    }

    @Override
    public HyperLogLogPlus deserialize(HyperLogLogPlus reuse, DataInputView source) throws IOException {
        return deserialize(source);
    }

    @Override
    public void copy(DataInputView source, DataOutputView target) throws IOException {
        int dataLength = source.readInt();
        byte[] bytes = new byte[dataLength];
        source.read(bytes);
        target.writeInt(dataLength);
        target.write(bytes);
    }

    @Override
    public boolean equals(Object obj) {
        if(obj instanceof HyperLogLogPlusSerializer){
            return true;
        }else{
            return false;
        }
    }

    @Override
    public boolean canEqual(Object obj) {
        return obj instanceof HyperLogLogPlusSerializer;
    }

    @Override
    public int hashCode() {
        return this.getClass().hashCode();
    }

    @Override
    public TypeSerializerSnapshot<HyperLogLogPlus> snapshotConfiguration() {
        logger.error("snapshotConfiguration invoked.");
        return new HyperLogLogPlusSerializerSnapshot();
    }

    public static final class HyperLogLogPlusSerializerSnapshot extends SimpleTypeSerializerSnapshot<HyperLogLogPlus> {

        public HyperLogLogPlusSerializerSnapshot(){
            super(HyperLogLogPlusSerializer.class);
        }
    }
}
</code>```

ValueState defined:

```<code>private ValueState<HyperLogLogPlus> showUVState;

showUVState = getRuntimeContext().getState(new ValueStateDescriptor("showUVState",new HyperLogLogPlusSerializer()));
</code>```

flink job runs nomally with checkpoint, but throws Exception when restoring from savepoint:

```<code>Caused by: org.apache.flink.util.FlinkException: Could not restore keyed state backend for LegacyKeyedProcessOperator_306d8342cb5b2ad8b53f1be57f65bee8_(28/32) from any of the 1 provided restore options.
    at org.apache.flink.streaming.api.operators.BackendRestorerProcedure.createAndRestore(BackendRestorerProcedure.java:137)
    at org.apache.flink.streaming.api.operators.StreamTaskStateInitializerImpl.keyedStatedBackend(StreamTaskStateInitializerImpl.java:284)
    at org.apache.flink.streaming.api.operators.StreamTaskStateInitializerImpl.streamOperatorStateContext(StreamTaskStateInitializerImpl.java:135)
    ... 5 more
Caused by: java.lang.NullPointerException
    at org.apache.flink.runtime.state.heap.HeapKeyedStateBackend.readKeyGroupStateData(HeapKeyedStateBackend.java:479)
    at org.apache.flink.runtime.state.heap.HeapKeyedStateBackend.readStateHandleStateData(HeapKeyedStateBackend.java:453)
    at org.apache.flink.runtime.state.heap.HeapKeyedStateBackend.restorePartitionedState(HeapKeyedStateBackend.java:410)
    at org.apache.flink.runtime.state.heap.HeapKeyedStateBackend.restore(HeapKeyedStateBackend.java:358)
    at org.apache.flink.runtime.state.heap.HeapKeyedStateBackend.restore(HeapKeyedStateBackend.java:104)
    at org.apache.flink.streaming.api.operators.BackendRestorerProcedure.attemptCreateAndRestore(BackendRestorerProcedure.java:151)
    at org.apache.flink.streaming.api.operators.BackendRestorerProcedure.createAndRestore(BackendRestorerProcedure.java:123)
</code>```

答:
HyperLogLogPlus is serializable and has a Builder object which can deserialize a byte array representation to a HyperLogLogPlus object. Therefore, you can:

Get a byte array representation of the HyperLogLogPlus object by calling .getBytes().

Store the byte array with kryo

On deserialization, call Builder.build(byte[]) and receive an HyperLogLogPlus object.

Body:
When using ValueState of java object that is not POJO, like HyperLogLogPlus, how to handle the serialization problem?

I have tried defining HyperLogLogPlusSerializer extends TypeSerializer, code as:

public class HyperLogLogPlusSerializer extends TypeSerializer<HyperLogLogPlus> {

    private static Logger logger = LoggerFactory.getLogger(HyperLogLogPlusSerializer.class);

    private static final long serialVersionUID = 1L;

    @Override
    public boolean isImmutableType() {
        return false;
    }

    @Override
    public TypeSerializer<HyperLogLogPlus> duplicate() {
        logger.info("duplicate invoked.");
        return this;
    }

    @Override
    public HyperLogLogPlus createInstance() {
        return new HyperLogLogPlus(20,25);
    }

    @Override
    public HyperLogLogPlus copy(HyperLogLogPlus from) {
        try{
            byte[] bytes = from.getBytes();
            return HyperLogLogPlus.Builder.build(bytes);
        }catch (Exception e){

        }
        return null;
    }

    @Override
    public HyperLogLogPlus copy(HyperLogLogPlus from, HyperLogLogPlus reuse) {
        return copy(from);
    }

    @Override
    public int getLength() {
        return -1;
    }

    @Override
    public void serialize(HyperLogLogPlus record, DataOutputView target) throws IOException {
        byte[] bytes = record.getBytes();
        target.writeInt(bytes.length);
        target.write(bytes);
        logger.info("serialize:{}", bytes.length);
    }

    @Override
    public HyperLogLogPlus deserialize(DataInputView source) throws IOException {
        int dataLength = source.readInt();
        byte[] bytes = new byte[dataLength];
        source.read(bytes);
        logger.info("deserialize:{}", bytes.length);
        return HyperLogLogPlus.Builder.build(bytes);
    }

    @Override
    public HyperLogLogPlus deserialize(HyperLogLogPlus reuse, DataInputView source) throws IOException {
        return deserialize(source);
    }

    @Override
    public void copy(DataInputView source, DataOutputView target) throws IOException {
        int dataLength = source.readInt();
        byte[] bytes = new byte[dataLength];
        source.read(bytes);
        target.writeInt(dataLength);
        target.write(bytes);
    }

    @Override
    public boolean equals(Object obj) {
        if(obj instanceof HyperLogLogPlusSerializer){
            return true;
        }else{
            return false;
        }
    }

    @Override
    public boolean canEqual(Object obj) {
        return obj instanceof HyperLogLogPlusSerializer;
    }

    @Override
    public int hashCode() {
        return this.getClass().hashCode();
    }

    @Override
    public TypeSerializerSnapshot<HyperLogLogPlus> snapshotConfiguration() {
        logger.error("snapshotConfiguration invoked.");
        return new HyperLogLogPlusSerializerSnapshot();
    }

    public static final class HyperLogLogPlusSerializerSnapshot extends SimpleTypeSerializerSnapshot<HyperLogLogPlus> {

        public HyperLogLogPlusSerializerSnapshot(){
            super(HyperLogLogPlusSerializer.class);
        }
    }
}

ValueState defined:

private ValueState<HyperLogLogPlus> showUVState;

showUVState = getRuntimeContext().getState(new ValueStateDescriptor("showUVState",new HyperLogLogPlusSerializer()));

flink job runs nomally with checkpoint, but throws Exception when restoring from savepoint:

Caused by: org.apache.flink.util.FlinkException: Could not restore keyed state backend for LegacyKeyedProcessOperator_306d8342cb5b2ad8b53f1be57f65bee8_(28/32) from any of the 1 provided restore options.
    at org.apache.flink.streaming.api.operators.BackendRestorerProcedure.createAndRestore(BackendRestorerProcedure.java:137)
    at org.apache.flink.streaming.api.operators.StreamTaskStateInitializerImpl.keyedStatedBackend(StreamTaskStateInitializerImpl.java:284)
    at org.apache.flink.streaming.api.operators.StreamTaskStateInitializerImpl.streamOperatorStateContext(StreamTaskStateInitializerImpl.java:135)
    ... 5 more
Caused by: java.lang.NullPointerException
    at org.apache.flink.runtime.state.heap.HeapKeyedStateBackend.readKeyGroupStateData(HeapKeyedStateBackend.java:479)
    at org.apache.flink.runtime.state.heap.HeapKeyedStateBackend.readStateHandleStateData(HeapKeyedStateBackend.java:453)
    at org.apache.flink.runtime.state.heap.HeapKeyedStateBackend.restorePartitionedState(HeapKeyedStateBackend.java:410)
    at org.apache.flink.runtime.state.heap.HeapKeyedStateBackend.restore(HeapKeyedStateBackend.java:358)
    at org.apache.flink.runtime.state.heap.HeapKeyedStateBackend.restore(HeapKeyedStateBackend.java:104)
    at org.apache.flink.streaming.api.operators.BackendRestorerProcedure.attemptCreateAndRestore(BackendRestorerProcedure.java:151)
    at org.apache.flink.streaming.api.operators.BackendRestorerProcedure.createAndRestore(BackendRestorerProcedure.java:123)


问:
How to replace with for loop statement by matching different files in shell/bash script
With my shell script i'm trying to match 2 different files and replace the occurencies in File1 with the lines of File2:

```<code>File1 occurency 1 <-- File2 row 1
File1 occurency 2 <-- File2 row 2
File1 occurency 3 <-- File2 row 3
...
</code>```

The number of rows in File 2 is equal to occurencies in File 1 because initialy they were taken from File 1

File1 - is a Json file

```<code>...
"@type" : "Review",
"@id":"https://google.com/social/profile/xxxxxxx.jpg"
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",

"@type" : "Review",
"@id":"https://google.com/social/profile/xxxxxxx.jpg"
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",
 ...
</code>```

File2 - is a formated "json like" file

```<code>"profilePhoto":"https://someurl.ltd/aaaa_90.jpg"
"profilePhoto":"https://someurl.ltd/bbbb_90.jpg"
"profilePhoto":"https://someurl.ltd/cccc_90.jpg"
 ....
</code>```

Actually the part of script that have to make this job looks like

```<code>IFS=$'\n'
set -f
for i in $(cat < File2.txt); do

sed -i "s|.*social.*|$i|g" File1.json

done
</code>```

This script replace all occurencies in File1 with the first line of File2, so on second loop there is no more matching to find.
output example

```<code>...
"@type" : "Review",
"profilePhoto":"https://someurl.ltd/cccc_90.jpg"
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",

"@type" : "Review",
"profilePhoto":"https://someurl.ltd/cccc_90.jpg"
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",
 ...
</code>```

I need instead the output like this

```<code>...
"@type" : "Review",
*"profilePhoto":"https://someurl.ltd/**aaaa**_90.jpg"*
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",

"@type" : "Review",
*"profilePhoto":"https://someurl.ltd/**bbbb**_90.jpg"*
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",
 ...
</code>```

Thank you in advance for any help.

答:
Thank you all guys!

After checking the suggestion of @goose i just make a little change
and the final solution that works for that issue is

```<code>for i in `cat jsonlike.txt`; do

awk -v i="$i" 'NR==1,/.*social.*/{sub(/.*social.*/, i)} 1 { rec = rec $0 RS } END { close(FILENAME); printf "%s", rec > FILENAME }' File1.json

done
</code>```

i know that it can be done withe the while loop too, but it's ok even like this for me.
thank you

Body:
With my shell script i'm trying to match 2 different files and replace the occurencies in File1 with the lines of File2:

File1 occurency 1 <-- File2 row 1
File1 occurency 2 <-- File2 row 2
File1 occurency 3 <-- File2 row 3
...

The number of rows in File 2 is equal to occurencies in File 1 because initialy they were taken from File 1

File1 - is a Json file

...
"@type" : "Review",
"@id":"https://google.com/social/profile/xxxxxxx.jpg"
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",

"@type" : "Review",
"@id":"https://google.com/social/profile/xxxxxxx.jpg"
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",
 ...

File2 - is a formated "json like" file

"profilePhoto":"https://someurl.ltd/aaaa_90.jpg"
"profilePhoto":"https://someurl.ltd/bbbb_90.jpg"
"profilePhoto":"https://someurl.ltd/cccc_90.jpg"
 ....

Actually the part of script that have to make this job looks like

IFS=$'\n'
set -f
for i in $(cat < File2.txt); do

sed -i "s|.*social.*|$i|g" File1.json

done

This script replace all occurencies in File1 with the first line of File2, so on second loop there is no more matching to find.
output example

...
"@type" : "Review",
"profilePhoto":"https://someurl.ltd/cccc_90.jpg"
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",

"@type" : "Review",
"profilePhoto":"https://someurl.ltd/cccc_90.jpg"
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",
 ...

I need instead the output like this

...
"@type" : "Review",
*"profilePhoto":"https://someurl.ltd/**aaaa**_90.jpg"*
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",

"@type" : "Review",
*"profilePhoto":"https://someurl.ltd/**bbbb**_90.jpg"*
"datePublished" : "Tue Sep 18 16:32:53 CEST 2012",
 ...

Thank you in advance for any help.

Body:
Thank you all guys!

After checking the suggestion of @goose i just make a little change
and the final solution that works for that issue is

for i in `cat jsonlike.txt`; do

awk -v i="$i" 'NR==1,/.*social.*/{sub(/.*social.*/, i)} 1 { rec = rec $0 RS } END { close(FILENAME); printf "%s", rec > FILENAME }' File1.json

done

i know that it can be done withe the while loop too, but it's ok even like this for me.
thank you


问:
How to add line break to Swashbuckle documentation?
I'm generating documentation for an api implemented in Web Api 2 using swagger/swashbuckle.

The only xml documentation tags recognized are the , <remarks> and <param>.

This means I cannot use <para> tag to format my text in new lines or paragraphs, everything is generated as a continuous long paragraph in the Implementation Notes entry of the docs.

Is there any way to do this?

答:
Using the structure below, both the Swashbuckle UI and the ReDoc UI will work:

```<code>/// <summary>
/// Title
///
/// <para>Content line 1</para>
/// <para>Content line 2</para>
/// <para>Content line 3/</para>
/// </summary>
</code>```

Important note: Do not ignore the spaces at the end of each line

Body:
Using the structure below, both the Swashbuckle UI and the ReDoc UI will work:

/// <summary>
/// Title
///
/// <para>Content line 1</para>
/// <para>Content line 2</para>
/// <para>Content line 3/</para>
/// </summary>

Important note: Do not ignore the spaces at the end of each line


问:
Reading xml value inside tag from class with Xml serialization
I have some issues about read a xml file. I have to fill xml tag as a class properties. Is there a way to get to solve this problem?

I looked every xml serialization article. When I try to run my code, I got null value from class

Here is my Program.cs

```<code>    Log lg = new Log();
        XmlReader reader = XmlReader.Create(@"C:\Logs\Workflow User
  Functions\2019\05\15\01.xml");
        while (reader.Read())
        {
            if (reader.HasAttributes && lg.date !=null && lg.datetime !=null)
            {
                Console.WriteLine(reader.GetAttribute(lg.date) +
   reader.GetAttribute(lg.datetime));
            }
        }
        Console.ReadLine();
</code>```

And my Log.cs

```<code>[XmlAttribute(AttributeName ="date")]
public string date { get; set; }

[XmlAttribute(AttributeName = "datetime")]
public string datetime { get; set; }
</code>```

Also my xml file which I try to get attribute value

```<code><?xml version="1.0"?><Logs version="1" appname="Workflow User Functions" id="fed9fc29-f6bf-4814-8401-f8742ea0ceef" date="15/30/2019 01">
<Log id="" logtype="Error" datetime="30:52" user="workflow" logname="ScheduledJobs.fnExecute_Execute">Process Id : 69705
</code>```

答:
Thanks for your all responses.

I did a few changes and then it works.

Program.cs;

```<code>                          List<Log> logs = new List<Log>();
                  XmlReader reader = XmlReader.Create(@"C:\Logs\Workflow User
                          Functions\2019\03\05\13.xml");
                  reader.MoveToContent();
                     while (reader.Read())
      {
      if (reader.HasAttributes)
      {
      var lg = new Log
      {
        date = reader.GetAttribute("date"),
        datetime = reader.GetAttribute("datetime")
      };
    logs.Add(lg);

    Console.WriteLine($"{lg.date} {lg.datetime}");
}
</code>```

}
            Console.ReadLine();

Body:
I have some issues about read a xml file. I have to fill xml tag as a class properties. Is there a way to get to solve this problem?

I looked every xml serialization article. When I try to run my code, I got null value from class

Here is my Program.cs

    Log lg = new Log();
        XmlReader reader = XmlReader.Create(@"C:\Logs\Workflow User
  Functions\2019\05\15\01.xml");
        while (reader.Read())
        {
            if (reader.HasAttributes && lg.date !=null && lg.datetime !=null)
            {
                Console.WriteLine(reader.GetAttribute(lg.date) +
   reader.GetAttribute(lg.datetime));
            }
        }
        Console.ReadLine();

And my Log.cs

[XmlAttribute(AttributeName ="date")]
public string date { get; set; }

[XmlAttribute(AttributeName = "datetime")]
public string datetime { get; set; }

Also my xml file which I try to get attribute value

<?xml version="1.0"?><Logs version="1" appname="Workflow User Functions" id="fed9fc29-f6bf-4814-8401-f8742ea0ceef" date="15/30/2019 01">
<Log id="" logtype="Error" datetime="30:52" user="workflow" logname="ScheduledJobs.fnExecute_Execute">Process Id : 69705

Body:
Thanks for your all responses.

I did a few changes and then it works.

Program.cs;

                          List<Log> logs = new List<Log>();
                  XmlReader reader = XmlReader.Create(@"C:\Logs\Workflow User
                          Functions\2019\03\05\13.xml");
                  reader.MoveToContent();
                     while (reader.Read())
      {
      if (reader.HasAttributes)
      {
      var lg = new Log
      {
        date = reader.GetAttribute("date"),
        datetime = reader.GetAttribute("datetime")
      };
    logs.Add(lg);

    Console.WriteLine($"{lg.date} {lg.datetime}");
}

}
            Console.ReadLine();


答:
I would read through this document. It contains all you need and more:

http://d.android.com/guide/topics/ui/ui-events.html

Title: How do I activate the click event for a button on Android?


问:
How to prevent FCM from converting nested json objects to string in Data Message notifications in react-native
I'm using firebase in my react-native project (with typescript), I set up all thing correctly and it works fine with data messages like below:

```<code>{
  "to": "fcm-token",

  "data": {
    "field1": "value1",
    "field2": "value1",
    "field3": "value1"
  }
}
</code>```

in my App, I can access my data using data filed of RemoteMessage like below:

```<code>const data: MyDataType = remoteMessage.data;
const {/* destructed fields */} = data;
</code>```

But when my server send nested Object to FCM server, it converts them to string and so I can not access them directly like above.

this is what my server send to FCM server:

```<code>{
  "to": "fcm-token",

  "data": {
    "field1": {
      "subfield1": "subvalue1",
      "subfield2": "subvalue2",
    },
    "field2": "value1",
    "field3": "value1"
  }
}
</code>```

and this is what I get in my application:

```<code>{
  "to": "fcm-token",

  "data": {
    "field1": "{"subfield1": "subvalue1","subfield2": "subvalue2"}", <--- the problem is here, it must be a nested object not string
    "field2": "value1",
    "field3": "value1"
  }
}
</code>```

I set Content-Type header to application/json in my server post requests, so I don't think there is any problem with my headers.

Am I doing something wrong? How can I prevent FCM from converting my nested objects?

答:
react-native-firebase author here,

We don't internally convert anything to strings on our implementation, these come through to native as strings already, for example on Android this uses the RemoteMessage FCM class - where we call getData() which as you can see here returns strings only.

They way I've got around this myself if I want nested data is to have just a single data field where I provide all my data to as a single JSON string, then when receiving it I only need to JSON.parse a single field to get the structure back. E.g.

const data = {
  "field1": "value1",
  "field2": "value1",
  "field3": {
    "subfield1": "subvalue1",
  }
}

const payload = {
  "to": "fcm-token",
  "data": {
    "json": JSON.stringify(data),
  }
}
```

<pre class="lang-js prettyprint-override"><code>const data: MyDataType = remoteMessage.data;
const { field1, field2, field3 } = JSON.parse(data.json);

console.log(field3.subfield1);
</code>```

Alternatively, you can flatten your data object before sending using something like this and then unflatten on the receiving end using something like this.

Hope this helps.

Body:
I'm using firebase in my react-native project (with typescript), I set up all thing correctly and it works fine with data messages like below:

{
  "to": "fcm-token",

  "data": {
    "field1": "value1",
    "field2": "value1",
    "field3": "value1"
  }
}

in my App, I can access my data using data filed of RemoteMessage like below:

const data: MyDataType = remoteMessage.data;
const {/* destructed fields */} = data;

But when my server send nested Object to FCM server, it converts them to string and so I can not access them directly like above.

this is what my server send to FCM server:

{
  "to": "fcm-token",

  "data": {
    "field1": {
      "subfield1": "subvalue1",
      "subfield2": "subvalue2",
    },
    "field2": "value1",
    "field3": "value1"
  }
}

and this is what I get in my application:

{
  "to": "fcm-token",

  "data": {
    "field1": "{"subfield1": "subvalue1","subfield2": "subvalue2"}", <--- the problem is here, it must be a nested object not string
    "field2": "value1",
    "field3": "value1"
  }
}

I set Content-Type header to application/json in my server post requests, so I don't think there is any problem with my headers.

Am I doing something wrong? How can I prevent FCM from converting my nested objects?

Body:
 react-native-firebase author here,

We don't internally convert anything to strings on our implementation, these come through to native as strings already, for example on Android this uses the RemoteMessage FCM class - where we call getData() which as you can see here returns strings only.

They way I've got around this myself if I want nested data is to have just a single data field where I provide all my data to as a single JSON string, then when receiving it I only need to JSON.parse a single field to get the structure back. E.g.

const data = {
  "field1": "value1",
  "field2": "value1",
  "field3": {
    "subfield1": "subvalue1",
  }
}

const payload = {
  "to": "fcm-token",
  "data": {
    "json": JSON.stringify(data),
  }
}

const data: MyDataType = remoteMessage.data;
const { field1, field2, field3 } = JSON.parse(data.json);

console.log(field3.subfield1);

Alternatively, you can flatten your data object before sending using something like this and then unflatten on the receiving end using something like this.

Hope this helps.


问:
Null-aware operator when traversing a nested map
How do you check for nulls when accessing second level map elements?
E.g.

```<code>var clientName = item['client']['name'];
</code>```

will throw an exception if item does not contain client
I'd like something like

```<code>item['client']?['name']
</code>```

or

```<code>item['client']?.['name']
</code>```

But that won't compile.

Surely I can do item['client'] twice or introduce a local var for it but that feels subpar.

答:
With putIfAbsent, you can use ? operator.

item.putIfAbsent("client", (){})
    ?.putIfAbsent("name", (){});
```

https://api.dartlang.org/stable/2.3.1/dart-core/Map/putIfAbsent.html

Body:
How do you check for nulls when accessing second level map elements?
E.g.

var clientName = item['client']['name'];

will throw an exception if item does not contain client
I'd like something like

item['client']?['name']

or

item['client']?.['name']

But that won't compile.

Surely I can do item['client'] twice or introduce a local var for it but that feels subpar.

Body:
With putIfAbsent, you can use ? operator.

item.putIfAbsent("client", (){})
    ?.putIfAbsent("name", (){});

https://api.dartlang.org/stable/2.3.1/dart-core/Map/putIfAbsent.html


问:
How to get data of a child in Firebase
I have my database tree structure like this:

Please tell me how do I get the value of "username" if I have the value of "userid"

答:
how do I get the value of "username" if I have the value of "userid"

To solve this, please use the following lines of code:

```<code>String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("users").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String username = dataSnapshot.child("username").getValue(String.class);
        Log.d(TAG, username);
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
    }
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
</code>```

The output in the logcat will be:

```<code>hisoka
</code>```

Title: How to get data of a child in Firebase

Body:
how do I get the value of "username" if I have the value of "userid"

To solve this, please use the following lines of code:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("users").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String username = dataSnapshot.child("username").getValue(String.class);
        Log.d(TAG, username);
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
    }
};
uidRef.addListenerForSingleValueEvent(valueEventListener);

The output in the logcat will be:

hisoka