问:
Make Node REST Client expect UTF-8 JSON content to avoid BOM parsing error
I have a Node.js application using Node REST Client to make an HTTP GET request to a server, targeting a file in JSON format. Everything goes well when this file is encoded in UTF-8 without BOM.

However, the app crashes during the client.get call when the target file encoding is UTF-8 with BOM. Even when I wrap that call in a try / catch in an attempt to prevent the crash and get the error, I get this stacktrace:

```<code>events.js:188
      throw err;
      ^

Error: Unhandled "error" event. (Error parsing response. response: [{}], error: [SyntaxError: Unexpected token  in JSON at position 0])
    at exports.Client.emit (events.js:186:19)
    at C:\PFD\workspace\web_adherent\dev\eamnh-front\node_modules\node-rest-client\lib\node-rest-client.js:457:57
    at Object.parse (C:\PFD\workspace\web_adherent\dev\eamnh-front\node_modules\node-rest-client\lib\nrc-parser-manager.js:140:17)
    at ConnectManager.handleResponse (C:\PFD\workspace\web_adherent\dev\eamnh-front\node_modules\node-rest-client\lib\node-rest-client.js:538:32)
    at ConnectManager.handleEnd (C:\PFD\workspace\web_adherent\dev\eamnh-front\node_modules\node-rest-client\lib\node-rest-client.js:531:18)
    at IncomingMessage.<anonymous> (C:\PFD\workspace\web_adherent\dev\eamnh-front\node_modules\node-rest-client\lib\node-rest-client.js:678:34)
    at emitNone (events.js:111:20)
    at IncomingMessage.emit (events.js:208:7)
    at endReadableNT (_stream_readable.js:1064:12)
    at _combinedTickCallback (internal/process/next_tick.js:139:11)
</code>```

What the code block doesn't show here that IntelliJ does is the U+FEFF zero width no-break space Unicode code point, marked by < X > in the following stack trace line: Error: Unhandled "error" event. (Error parsing response. response: [< X >{}], error: [SyntaxError: Unexpected token < X > in JSON at position 0]). So what sems to happens is that the Client is trying to read the file content as a Unicode encoded String, instead of an UTF-8 JSON with no BOM. So it thinks the BOM is the U+FEFF Unicode character.

I have scoured SO and found quite a few questions about setting mimetypes for the Client but I still get the error. I have also read the node-rest-client docs and it seems that setting a response parser would be the way to go but scrolling to JSON parser shows that it is the same thing as setting mimetypes.

So I ended up with this:

```<code>const options ={
    mimetypes:{
        json:["application/json","application/json; charset=utf-8","application/json;charset=utf-8"]
    }
};
const client = new Client(options);
</code>```

Trying to set the charset to UTF-8 but the error is the same.

Does someone know what I am doing wrong or is this an issue with Node REST Client?

Thank you for your help.

-- Edit
This is my code for the GET request function:

```<code>let Client = require('node-rest-client').Client;

const options ={
    mimetypes:{
        json:["application/json","application/json; charset=utf-8","application/json;charset=utf-8"]
    }
};
const client = new Client(options);

// Reads file contents and calls callback function with data
exports.readFromUrl = (req, fileUrl, callback) => {

    client.get(fileUrl, (data, resp) => {

        if (resp.statusCode === 200) {

            callback(data);

        } else {

            callback("");
        }
    }).on('error', (err) => {

        callback("");
    });
};
</code>```

Final solution:

Just in case someone stumbles here because of a similar issue, I ended up replacing the Node REST Client JSON parser with a custom one which filters out invalid characters to pass a valid JSON to the callback.

Here's how I did it (using docs previously mentionned).

```<code>const Client = require('node-rest-client').Client;
const client = new Client();

// Remove existing regular parsers (otherwise JSON parser still gets called first)
client.parsers.clean();

client.parsers.add({
    "name": "cleanInput",
    "isDefault": false,
    "match": function (response) {

        // Match evey response to replace default parser
        return true;
    },
    "parse": function (byteBuffer, nrcEventEmitter, parsedCallback) {

        let parsedData = null;

        try {

            const cleanData = cleanString(byteBuffer.toString());

            parsedData = JSON.parse(cleanData);
            parsedData.parsed = true;

            // Emit custom event
            nrcEventEmitter('parsed', 'Data has been parsed ' + parsedData);

            // Pass parsed data to client request method callback
            parsedCallback(parsedData);

        } catch(err) {

            nrcEventEmitter('error', err);
        }
    }
});

// Only keeps unicode characters with codes lesser than 127 to avoid forbidden characters in JSON
function cleanString(input) {

    let output = "";

    for (let i=0; i < input.length; i++) {

        if (input.charCodeAt(i) < 127) {

            output += input.charAt(i);
        }
    }
    return output;
}
</code>```

答:
https://stackoverflow.com/a/38036753/7316335

JSON parsers are specified to NOT accept Byte-Order marks.

Hence, your server is crashing due to a 'malformed' client GET request.

The issue should be resolved in your server's processing of the GET request, and not through a change in the JSON parser specification.

I would advise to filter Byte Order marks in all GET requests before parsing at the server.

in express how multiple callback works in app.get

This shows you how a single middleware can perform your pre-filtering of GET bodies before passing over to the actual callback for that GET path.

Body:
I have a Node.js application using Node REST Client to make an HTTP GET request to a server, targeting a file in JSON format. Everything goes well when this file is encoded in UTF-8 without BOM.

However, the app crashes during the client.get call when the target file encoding is UTF-8 with BOM. Even when I wrap that call in a try / catch in an attempt to prevent the crash and get the error, I get this stacktrace:

events.js:188
      throw err;
      ^

Error: Unhandled "error" event. (Error parsing response. response: [{}], error: [SyntaxError: Unexpected token  in JSON at position 0])
    at exports.Client.emit (events.js:186:19)
    at C:\PFD\workspace\web_adherent\dev\eamnh-front\node_modules\node-rest-client\lib\node-rest-client.js:457:57
    at Object.parse (C:\PFD\workspace\web_adherent\dev\eamnh-front\node_modules\node-rest-client\lib\nrc-parser-manager.js:140:17)
    at ConnectManager.handleResponse (C:\PFD\workspace\web_adherent\dev\eamnh-front\node_modules\node-rest-client\lib\node-rest-client.js:538:32)
    at ConnectManager.handleEnd (C:\PFD\workspace\web_adherent\dev\eamnh-front\node_modules\node-rest-client\lib\node-rest-client.js:531:18)
    at IncomingMessage.<anonymous> (C:\PFD\workspace\web_adherent\dev\eamnh-front\node_modules\node-rest-client\lib\node-rest-client.js:678:34)
    at emitNone (events.js:111:20)
    at IncomingMessage.emit (events.js:208:7)
    at endReadableNT (_stream_readable.js:1064:12)
    at _combinedTickCallback (internal/process/next_tick.js:139:11)

What the code block doesn't show here that IntelliJ does is the U+FEFF zero width no-break space Unicode code point, marked by < X > in the following stack trace line: Error: Unhandled "error" event. (Error parsing response. response: [< X >{}], error: [SyntaxError: Unexpected token < X > in JSON at position 0]). So what sems to happens is that the Client is trying to read the file content as a Unicode encoded String, instead of an UTF-8 JSON with no BOM. So it thinks the BOM is the U+FEFF Unicode character.

I have scoured SO and found quite a few questions about setting mimetypes for the Client but I still get the error. I have also read the node-rest-client docs and it seems that setting a response parser would be the way to go but scrolling to JSON parser shows that it is the same thing as setting mimetypes.

So I ended up with this:

const options ={
    mimetypes:{
        json:["application/json","application/json; charset=utf-8","application/json;charset=utf-8"]
    }
};
const client = new Client(options);

Trying to set the charset to UTF-8 but the error is the same.

Does someone know what I am doing wrong or is this an issue with Node REST Client?

Thank you for your help.

-- Edit
This is my code for the GET request function:

let Client = require('node-rest-client').Client;

const options ={
    mimetypes:{
        json:["application/json","application/json; charset=utf-8","application/json;charset=utf-8"]
    }
};
const client = new Client(options);

// Reads file contents and calls callback function with data
exports.readFromUrl = (req, fileUrl, callback) => {

    client.get(fileUrl, (data, resp) => {

        if (resp.statusCode === 200) {

            callback(data);

        } else {

            callback("");
        }
    }).on('error', (err) => {

        callback("");
    });
};

Final solution:

Just in case someone stumbles here because of a similar issue, I ended up replacing the Node REST Client JSON parser with a custom one which filters out invalid characters to pass a valid JSON to the callback.

Here's how I did it (using docs previously mentionned).

const Client = require('node-rest-client').Client;
const client = new Client();

// Remove existing regular parsers (otherwise JSON parser still gets called first)
client.parsers.clean();

client.parsers.add({
    "name": "cleanInput",
    "isDefault": false,
    "match": function (response) {

        // Match evey response to replace default parser
        return true;
    },
    "parse": function (byteBuffer, nrcEventEmitter, parsedCallback) {

        let parsedData = null;

        try {

            const cleanData = cleanString(byteBuffer.toString());

            parsedData = JSON.parse(cleanData);
            parsedData.parsed = true;

            // Emit custom event
            nrcEventEmitter('parsed', 'Data has been parsed ' + parsedData);

            // Pass parsed data to client request method callback
            parsedCallback(parsedData);

        } catch(err) {

            nrcEventEmitter('error', err);
        }
    }
});

// Only keeps unicode characters with codes lesser than 127 to avoid forbidden characters in JSON
function cleanString(input) {

    let output = "";

    for (let i=0; i < input.length; i++) {

        if (input.charCodeAt(i) < 127) {

            output += input.charAt(i);
        }
    }
    return output;
}


来源: stackexchange

问:
How to POST multiple list of fields data to child model along with parent model
I have two models Visit(parent model) and VisitAccessories(Child Model). when i Post(VisitAccessories) data only last element of the list get added and record gets created. but others element are ignored.

models.py

```<code>class Visit(models.Model):
    name = models.CharField(max_length=200, name="name")

class VisitAccessories(models.Model):
     title = models.CharField(max_length=100)
     code = models.CharField(max_length=100, null=True, blank=True)
     accessories_photo = models.FileField(upload_to="accessories/", null=True, blank=True)
     description = models.TextField(null=True, blank=True)
     visit = models.ForeignKey(Visit,on_delete=models.CASCADE)
</code>```

serializer.py

```<code>class VisitAccessoriesSerializers(serializers.ModelSerializer):

    class Meta:
       model = VisitAccessories
       exclude = ("visit",)#visit is foregin key to visit model

class ListAccessoriesSerializers(serializers.ModelSerializer):
     visit_accessories = VisitAccessoriesSerializers(many=True,source='visitaccessories_set', required=False,)

      class Meta:
         model = VisitAccessories
         exclude = ("visit",) #visit is foregin key to visit model

class VisitSerializers(serializers.ModelSerializer):
      visit_accessories = VisitAccessoriesSerializers(many=True, source='visitaccessories_set', required=False)
    class Meta:
       model = Visit
       fields = ('__all__')
</code>```

views.py

```<code>    def post(self, request):
       serializer = VisitSerializers(data=request.data)
       accessories_serializer = ListAccessoriesSerializers(data=request.data)
       if serializer.is_valid(raise_exception=ValueError) and accessories_serializer.is_valid(raise_exception=ValueError):
           visit_obj = serializer.save() # Visit Created
           accessories_serializer.save(visit=visit_obj) # VisitAccessories
           return Response(serializer.data, status=status.HTTP_201_CREATED)
       return Response(serializer.error_messages, status=status.HTTP_400_BAD_REQUEST)
</code>```

variable accessories_serializer data i get is

```<code>ListAccessoriesSerializers(data=<QueryDict: {'name': ['Axxx'], 'gender': ['M'], 'mobile': ['900000'], 'visit_time': ['2019-06-04T17:00:56.901634+05:30'], 'to_meet': ['15'], 'title': ['pppp', 'ttttttt', 'vvvvv'], 'accessories_photo': [<InMemoryUploadedFile: Syndicate_Bank.svg.png (image/png)>, <InMemoryUploadedFile: maruti-suzuki-reuters-small.jpg (image/jpeg)>, <InMemoryUploadedFile: rupee11.jpg (image/jpeg)>]}>):
</code>```

from title list only vvvvv(last element) 1 record gets created. instead of 3 Records

答:
Try this</p>

```<code>class VisitSerializers(serializers.ModelSerializer):

    visit_accessories = VisitAccessoriesSerializers(many=True, source='visitaccessories_set', required=False)

    class Meta:
       model = Visit
       fields = ('__all__')

    def create(self, validated_data):
        request = self.context.get('request')
        accessories_data = validated_data.pop('visit_accessories') # pop the nested data
        serializer = VisitSerializers(data=validated_data)
        instance = super().create(validated_data) # create base object

        accessories_serializer = ListAccessoriesSerializers(many=True,
            context={'request': request, 'visit_id': instance.id}
        )
        accessories_serializer.create(accessories_data) # create nested objects
        return instance
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have two models Visit(parent model) and VisitAccessories(Child Model). when i Post(VisitAccessories) data only last element of the list get added and record gets created. but others element are ignored.

models.py

class Visit(models.Model):
    name = models.CharField(max_length=200, name="name")

class VisitAccessories(models.Model):
     title = models.CharField(max_length=100)
     code = models.CharField(max_length=100, null=True, blank=True)
     accessories_photo = models.FileField(upload_to="accessories/", null=True, blank=True)
     description = models.TextField(null=True, blank=True)
     visit = models.ForeignKey(Visit,on_delete=models.CASCADE)

serializer.py

class VisitAccessoriesSerializers(serializers.ModelSerializer):

    class Meta:
       model = VisitAccessories
       exclude = ("visit",)#visit is foregin key to visit model

class ListAccessoriesSerializers(serializers.ModelSerializer):
     visit_accessories = VisitAccessoriesSerializers(many=True,source='visitaccessories_set', required=False,)

      class Meta:
         model = VisitAccessories
         exclude = ("visit",) #visit is foregin key to visit model

class VisitSerializers(serializers.ModelSerializer):
      visit_accessories = VisitAccessoriesSerializers(many=True, source='visitaccessories_set', required=False)
    class Meta:
       model = Visit
       fields = ('__all__')

views.py

    def post(self, request):
       serializer = VisitSerializers(data=request.data)
       accessories_serializer = ListAccessoriesSerializers(data=request.data)
       if serializer.is_valid(raise_exception=ValueError) and accessories_serializer.is_valid(raise_exception=ValueError):
           visit_obj = serializer.save() # Visit Created
           accessories_serializer.save(visit=visit_obj) # VisitAccessories
           return Response(serializer.data, status=status.HTTP_201_CREATED)
       return Response(serializer.error_messages, status=status.HTTP_400_BAD_REQUEST)

variable accessories_serializer data i get is

ListAccessoriesSerializers(data=<QueryDict: {'name': ['Axxx'], 'gender': ['M'], 'mobile': ['900000'], 'visit_time': ['2019-06-04T17:00:56.901634+05:30'], 'to_meet': ['15'], 'title': ['pppp', 'ttttttt', 'vvvvv'], 'accessories_photo': [<InMemoryUploadedFile: Syndicate_Bank.svg.png (image/png)>, <InMemoryUploadedFile: maruti-suzuki-reuters-small.jpg (image/jpeg)>, <InMemoryUploadedFile: rupee11.jpg (image/jpeg)>]}>):

from title list only vvvvv(last element) 1 record gets created. instead of 3 Records

Body:
Try this

class VisitSerializers(serializers.ModelSerializer):

    visit_accessories = VisitAccessoriesSerializers(many=True, source='visitaccessories_set', required=False)

    class Meta:
       model = Visit
       fields = ('__all__')

    def create(self, validated_data):
        request = self.context.get('request')
        accessories_data = validated_data.pop('visit_accessories') # pop the nested data
        serializer = VisitSerializers(data=validated_data)
        instance = super().create(validated_data) # create base object

        accessories_serializer = ListAccessoriesSerializers(many=True,
            context={'request': request, 'visit_id': instance.id}
        )
        accessories_serializer.create(accessories_data) # create nested objects
        return instance


问:
Can't see Access control (IAM) under Subscriptions
I want to give an account access to an Azure account but I can't see "Access control (IAM)" in the subscriptions area. Why might this be? Does it disappear when Active Directory is in use on the account?</p>

答:
It should be simply enabled and possible to see the IAM under subscription. There are three things you could do it,

(i)  Check if you are the global administrator for the subscription

(ii) Check if you have multiple subscription, select the proper one you hold the administrator right

(ii) Open a ticket to the subscription and billing team. They should be able to help point us to what is blocking you and if anything possibly add that subscription for you.


问:
Why this sprintf statement crashing?
```<code>char filebuf[256];
path current = current_path();
std::cout<<"CurrentWorking "<<current<<endl;
string _UserDir = "TTiTraceLogs";
sprintf(filebuf,"%s/%s",current,_UserDir); ///crashing here
</code>```

If I format only current, then it is ok.

```<code>sprintf(filebuf,"%s",current);
</code>```

Output:

```<code>CurrentWorking D:/working/eclipse_projects/sadftp/CollectTTiTraceSept10_1009_174
_higher/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/Release
</code>```

答: How long is current_path? Maybe strlen(current_path)+strlen(_UserDir)+2 > 256.

ContentLicense: CC BY-SA 3.0

Title: Why this sprintf statement crashing?

Body:
char filebuf[256];
path current = current_path();
std::cout<<"CurrentWorking "<<current<<endl;
string _UserDir = "TTiTraceLogs";
sprintf(filebuf,"%s/%s",current,_UserDir); ///crashing here

If I format only current, then it is ok.

sprintf(filebuf,"%s",current);

Output:

CurrentWorking D:/working/eclipse_projects/sadftp/CollectTTiTraceSept10_1009_174
_higher/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/Release


问:
Sketch Plugin - NSFileManager contentsOfDirectoryAtPath - not a function
I'm trying to make a plugin for Sketch that allows me to automate the production of multilingual assets.

Right now, I select a list of languages files that kick off the process. I use NSOpen Panel to select these. For each language file, it makes a new page for that language, and finds text layers with a special tag and replaces the copy with the translated copy.

While it's doing this, I'd like it to check to see if there are any screenshots in another folder screenshots/lang, and store a list of the filepaths for those images. This is where I'm getting stuck at the moment.

Currently I have:

```<code>var screenShotPaths = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:mySourcePath error:NULL];
</code>```

When I try to run my Plugin in sketch in its current state, the console is saying:

```<code>(Sketch Plugin)[6547]: TypeError: fileManager.contentsOfDirectoryAtPath_ is not a function.
(In 'fileManager.contentsOfDirectoryAtPath_( mySourcePath)', 'fileManager.contentsOfDirectoryAtPath_' is undefined)
</code>```

I've tried looking all over I see a lot of issues where the list isn't coming back,coming back null, etc, but I can't find anything where contentsOfDirectoryAtPath is coming back as not a function.

Is this because it's a plugin getting run by an application and navigating the filesystem is a security issue?

Any help would be much appreciated. Thank you!

答:
Works for me: (Sketch 55)

```<code>var fileManager = [NSFileManager defaultManager];
var paths = [fileManager contentsOfDirectoryAtPath:filePath error:null];
</code>```

Body:
I'm trying to make a plugin for Sketch that allows me to automate the production of multilingual assets.

Right now, I select a list of languages files that kick off the process. I use NSOpen Panel to select these. For each language file, it makes a new page for that language, and finds text layers with a special tag and replaces the copy with the translated copy.

While it's doing this, I'd like it to check to see if there are any screenshots in another folder screenshots/lang, and store a list of the filepaths for those images. This is where I'm getting stuck at the moment.

Currently I have:

var screenShotPaths = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:mySourcePath error:NULL];

When I try to run my Plugin in sketch in its current state, the console is saying:

(Sketch Plugin)[6547]: TypeError: fileManager.contentsOfDirectoryAtPath_ is not a function.
(In 'fileManager.contentsOfDirectoryAtPath_( mySourcePath)', 'fileManager.contentsOfDirectoryAtPath_' is undefined)

I've tried looking all over I see a lot of issues where the list isn't coming back,coming back null, etc, but I can't find anything where contentsOfDirectoryAtPath is coming back as not a function.

Is this because it's a plugin getting run by an application and navigating the filesystem is a security issue?

Any help would be much appreciated. Thank you!

Body:
Works for me: (Sketch 55)

var fileManager = [NSFileManager defaultManager];
var paths = [fileManager contentsOfDirectoryAtPath:filePath error:null];


问:
Panda dataframe conversion into table
After applying the group by I got a data frame like this

```<code>                                 indi_percentage
publishedAt status
2019-05-29  Guidelines reason        14.065392
            accepted                 0.555213
            unfit                    0.246761
            repeat                   0.123381
2019-05-30  Guidelines reason        11.217712
            accepted                 0.073801
            unfit                    0.221402
            no action                90.943396
</code>```

The shape of the data frame is 8 X 1. The indi_percentage is a column. Rest are index. I want to transform this data frame in such a way that on each day, values of status are columns and indi_percentage are the values these columns. Here is a sample output

```<code>publishedAt   Guidelines reason     accepted
2019-05-29     14.065392            0.555213
</code>```

How can we implement this?

答:
reset_index() and df.pivot_table() assuming df is the name after grouby()

```<code>df.reset_index().pivot_table(index='publishedAt',columns='status',values='indi_percentage')
</code>```

```<code> status       Guidelines reason  accepted  no action    repeat     unfit
publishedAt
2019-05-29           14.065392  0.555213        NaN  0.123381  0.246761
2019-05-30           11.217712  0.073801  90.943396       NaN  0.221402
</code>```

Title: Panda dataframe conversion into table

Body:
After applying the group by I got a data frame like this

                                 indi_percentage
publishedAt status
2019-05-29  Guidelines reason        14.065392
            accepted                 0.555213
            unfit                    0.246761
            repeat                   0.123381
2019-05-30  Guidelines reason        11.217712
            accepted                 0.073801
            unfit                    0.221402
            no action                90.943396

The shape of the data frame is 8 X 1. The indi_percentage is a column. Rest are index. I want to transform this data frame in such a way that on each day, values of status are columns and indi_percentage are the values these columns. Here is a sample output

publishedAt   Guidelines reason     accepted
2019-05-29     14.065392            0.555213

How can we implement this?

Body:
reset_index() and df.pivot_table() assuming df is the name after grouby()

df.reset_index().pivot_table(index='publishedAt',columns='status',values='indi_percentage')

 status       Guidelines reason  accepted  no action    repeat     unfit
publishedAt
2019-05-29           14.065392  0.555213        NaN  0.123381  0.246761
2019-05-30           11.217712  0.073801  90.943396       NaN  0.221402


问:
Is there any ways to make `#pragma warning disable` usage more elegant?
I got enabled "treat warnings as errors" option in Visual Studio. And I want to ignore some warnings in places where I know that it's ok. So I use #pragma warning disable but I think that this directive makes my code less readable and noisy.

```<code>#pragma warning disable 618
            // explanation here
            var target = new DevelopersAndGroupsCondition();
#pragma warning restore 618
            target.Set( t => t.DevelopersOnly, true );
</code>```

Maybe there is some more elegant way exisits to ignore this warnings. If that so, please let me know.

答:
There is no other way to disable a build warning on a case-by-case basis. Your only other option is to disable the warning for the entire project by adding 618 to the list of warnings to suppress in your project settings.

All that said, warning 618 is usage of code marked with the Obsolete attribute. If it were me, I'd remove the need to use pragma disable/restore 618 by removing references to obsolete code. When code is marked with the Obsolete attribute, there is typically an updated alternate to use, often indicated by the attribute message. You say you want to "ignore some warnings in places where I know that it's ok". If the code is explicitly marked as obsolete, are you sure it's OK, and if so, how much longer will it be before it's either not OK, or the obsolete code is removed? That's my opinion, anyway.

Body:
I got enabled "treat warnings as errors" option in Visual Studio. And I want to ignore some warnings in places where I know that it's ok. So I use #pragma warning disable but I think that this directive makes my code less readable and noisy.

#pragma warning disable 618
            // explanation here
            var target = new DevelopersAndGroupsCondition();
#pragma warning restore 618
            target.Set( t => t.DevelopersOnly, true );

Maybe there is some more elegant way exisits to ignore this warnings. If that so, please let me know.


问:
Am I missing some important fact about interning symbols in LISP?
To be brief. Here is my several tries to intern and use a symbol in clisp.

```<code> [1]> (setq sym (intern "foo"))
 |foo|
 [2]> (eq sym 'foo)
 NIL
</code>```

Why???

```<code> [3]> (defun internup (me &optional (package *package*))
   (intern (string-upcase me) package))
 INTERNUP

 [4]> (eq 'abc (internup "abc"))
 T
</code>```

Probably must be upcase.

```<code> [12]>(let ((abc 2))
   (eval '(+ 2 abc)))

 *** - EVAL: variable ABC has no value
 The following restarts are available:
</code>```

ok

```<code> [18]> (let ((abc 2))
 (eval '(+ 2 'abc)))

 *** - +: ABC is not a number
 The following restarts are available:
</code>```

Interesting. Should I set it before.

```<code> [14]> (setq a (internup "abc"))
 ABC

 [15]> (let ((abc 2))
 (eval '(+ 2 a)))

 *** - +: ABC is not a number
 The following restarts are available:
</code>```

And again wrong. Hmm I must be missing some important fact about interning symbols in LISP. Can you help me ?

答:
The case-sensitivity of the Common Lisp reader is determined by the readtable:

```<code>(readtable-case *readtable*)
</code>```

Typically the reader will initially intern symbols in uppercase (unless you explicitly escape characters). Hence:

(eq (intern "foo") 'foo) => NIL

(eq (intern "FOO") 'foo) => T

(eq (intern "FOo") 'fo\o) => T

You can use backquote syntax to build the form for eval:

```<code>(let ((abc 2))
  (eval `(+ 2 ,abc)))
</code>```

=> 4

Body:
To be brief. Here is my several tries to intern and use a symbol in clisp.

 [1]> (setq sym (intern "foo"))
 |foo|
 [2]> (eq sym 'foo)
 NIL

Why???

 [3]> (defun internup (me &optional (package *package*))
   (intern (string-upcase me) package))
 INTERNUP

 [4]> (eq 'abc (internup "abc"))
 T

Probably must be upcase.

 [12]>(let ((abc 2))
   (eval '(+ 2 abc)))

 *** - EVAL: variable ABC has no value
 The following restarts are available:

ok

 [18]> (let ((abc 2))
 (eval '(+ 2 'abc)))

 *** - +: ABC is not a number
 The following restarts are available:

Interesting. Should I set it before.

 [14]> (setq a (internup "abc"))
 ABC

 [15]> (let ((abc 2))
 (eval '(+ 2 a)))

 *** - +: ABC is not a number
 The following restarts are available:

And again wrong. Hmm I must be missing some important fact about interning symbols in LISP. Can you help me ?

Body:
The case-sensitivity of the Common Lisp reader is determined by the readtable:

(readtable-case *readtable*)

Typically the reader will initially intern symbols in uppercase (unless you explicitly escape characters). Hence:

(eq (intern "foo") 'foo) => NIL

(eq (intern "FOO") 'foo) => T

(eq (intern "FOo") 'fo\o) => T

You can use backquote syntax to build the form for eval:

(let ((abc 2))
  (eval `(+ 2 ,abc)))

=> 4


问:
Iterator-class for nested dictionaries
Initial situation

Lets say we have a dictionary storing time-series data in form of:

dic = {'M15':
        {
            '100001': { 0: [0,1,2,...],
                        1: [0,1,2,...]
                    },
            '100002': { 0: [0,1,2,...],
                        1: [0,1,2,...]
                    },
                    ...
        },
        'H1': {
            '200001': { 0: [0,1,2,...],
                        1: [0,1,2,...]
                    },
            ...
        },
        ...
}
```

<p>Now, lets assume this dictionary is stored within a class called data like this:</p>

<pre class="lang-py prettyprint-override"><code>class data:

    def __init__(self, input: dict):
        self.data = input

newData = data(dic)
</code>```

As may be obvious, this class shall store the time-series data and return it within an iteration for further processing at some point.

My questions

I want to make the class iterable, meaning __next__ shall iterate through all the data within the dictionary (the upcoming question is not about how to iterate over a nested dictionary, so please do not answer this). Data means I only need the arrays at the lowest level within the dictionary, e.g. [0,1,2,...].

Lets assume the data within the dictionary is quite huge - it can fit within memory, but it shall not be duplicated.
Therefore, list comprehension is not an option as far as I know because the data would also be stored within this new list besides the dictionary (the dictionary is still needed and an array is not an option in this example).
For the sake of completeness, this would look like:

class data:
    def __init__(self, input: dict):
        self.dictionary = input
        self.data  = [series_array for series_key, series_array in series.items() for ... in self.dictionary.items()]
        self.index = 0
    def __iter__(self):
        return self
    def __next__(self):
        self.index += 1
        return self.data[self.index - 1]
```

Question 1:

Would the list comprehension just point to the data within the
dictionary or would it really copy the data?

This means I would have to use a normal iteration over the dictionary, but I cannot think of a way to implement this in __iter__and __next__.

Question 2:

How would I implement this nested dictionary-loop within __iter__and __next__?

Please note that I am seeking an answer for this concrete question and not on "why don't use generators" or "why don't do it this/that way".

答:
Question 1:

```<code>Would the list comprehension just point to the data within the dictionary or would it really copy the data?
</code>```

It will hold a reference to the lists in the dictionary

Question 2:

```<code>How would I implement this nested dictionary-loop within __iter__and __next__?
</code>```

You just need to return an iterator in __iter__ (instead of having the list for example), in this case a the generator expression within your list should be enough:

```<code>class Data:
    def __init__(self, input: dict):
        self.dictionary = input
    def __iter__(self):
        return (series_array for series_key, series_array in series.items() for ... in self.dictionary.items())
</code>```

Title: Iterator-class for nested dictionaries

Body:
Initial situation

Lets say we have a dictionary storing time-series data in form of:

dic = {'M15':
        {
            '100001': { 0: [0,1,2,...],
                        1: [0,1,2,...]
                    },
            '100002': { 0: [0,1,2,...],
                        1: [0,1,2,...]
                    },
                    ...
        },
        'H1': {
            '200001': { 0: [0,1,2,...],
                        1: [0,1,2,...]
                    },
            ...
        },
        ...
}

Now, lets assume this dictionary is stored within a class called data like this:

class data:

    def __init__(self, input: dict):
        self.data = input

newData = data(dic)

As may be obvious, this class shall store the time-series data and return it within an iteration for further processing at some point.

My questions

I want to make the class iterable, meaning __next__ shall iterate through all the data within the dictionary (the upcoming question is not about how to iterate over a nested dictionary, so please do not answer this). Data means I only need the arrays at the lowest level within the dictionary, e.g. [0,1,2,...].

Lets assume the data within the dictionary is quite huge - it can fit within memory, but it shall not be duplicated.
Therefore, list comprehension is not an option as far as I know because the data would also be stored within this new list besides the dictionary (the dictionary is still needed and an array is not an option in this example).
For the sake of completeness, this would look like:

class data:
    def __init__(self, input: dict):
        self.dictionary = input
        self.data  = [series_array for series_key, series_array in series.items() for ... in self.dictionary.items()]
        self.index = 0
    def __iter__(self):
        return self
    def __next__(self):
        self.index += 1
        return self.data[self.index - 1]

Question 1:

Would the list comprehension just point to the data within the
dictionary or would it really copy the data?

This means I would have to use a normal iteration over the dictionary, but I cannot think of a way to implement this in __iter__and __next__.

Question 2:

How would I implement this nested dictionary-loop within __iter__and __next__?

Please note that I am seeking an answer for this concrete question and not on "why don't use generators" or "why don't do it this/that way".

Body:
Question 1:

Would the list comprehension just point to the data within the dictionary or would it really copy the data?

It will hold a reference to the lists in the dictionary

Question 2:

How would I implement this nested dictionary-loop within __iter__and __next__?

You just need to return an iterator in __iter__ (instead of having the list for example), in this case a the generator expression within your list should be enough:

class Data:
    def __init__(self, input: dict):
        self.dictionary = input
    def __iter__(self):
        return (series_array for series_key, series_array in series.items() for ... in self.dictionary.items())


问:
How to format multiple Strings so that they are flush with each other

Description

I want to format multiple strings so that they are flush with each other. (See actual result and expected result)

what i tried

I have implemented this solution: https://stackoverflow.com/a/31613297/11582550
(See code)
It also works, but only if I print the result in the console. I want to save the text in label.text, that doesn't work.

some code

func formattedString(left:String, right:String) -> String {
        let left = (left as NSString).utf8String
        let right = (right as NSString).utf8String
        print(String(format:"%-20s %-20s", left!, right!))
        return String(format:"%-20s %-20s", left!, right!)
    }

label.text += formattedString(left: "Firstname: ", right: "Alfred") + "\n" + formattedString(left:"Lastname: ", right: "LongLastname") + "\n" + formattedString(left:"Note:", right: "private")

// actual result

```

<h1>what i expected</h1>

```## actual result (saved in label.text)
Firstname:    Alfred
Lastname:    LongLastname
Note:    private

## expected result (saved in label.text)
Firstname:    Alfred
Lastname:     LongLastname
Note:         private
```

答:
Your issue is that you are using a proportional font instead of a fixed-width font for your label.  In proportional fonts, the character widths vary, so you can't expect the characters to align.

Change the font that your label is using to a fixed-width font (such as Courier, Courier New, or Menlo) and that will fix your issue.

Body:
Description

I want to format multiple strings so that they are flush with each other. (See actual result and expected result)

what i tried

I have implemented this solution: https://stackoverflow.com/a/31613297/11582550
(See code)
It also works, but only if I print the result in the console. I want to save the text in label.text, that doesn't work.

some code

func formattedString(left:String, right:String) -> String {
        let left = (left as NSString).utf8String
        let right = (right as NSString).utf8String
        print(String(format:"%-20s %-20s", left!, right!))
        return String(format:"%-20s %-20s", left!, right!)
    }

label.text += formattedString(left: "Firstname: ", right: "Alfred") + "\n" + formattedString(left:"Lastname: ", right: "LongLastname") + "\n" + formattedString(left:"Note:", right: "private")

// actual result

what i expected

## actual result (saved in label.text)
Firstname:    Alfred
Lastname:    LongLastname
Note:    private

## expected result (saved in label.text)
Firstname:    Alfred
Lastname:     LongLastname
Note:         private


问:
How does an update from the child component in React get conveyed to the parent?
I am working on a react-express Todo list and cant seem to update the Todo item from the TodoItem component which is in the main App component. when i write the axios function to modify the database from the child component itself the Todo is getting blanked out after a state refresh.

I have tried sending data from the Child component to the parent but with no result.

//App.jsx

```<code>                {this.state.data.map(data => (
                  <TodoItem
                    data={data}
                    key={data.id}
                    delete={() => this.removeFromDatabase(data)}
                    edit={() => this.setState({ editing: data.id })}
                    update={(data)=>this.updateDatabase(data)}
                  />
                ))}
</code>```

//TodoItem.jsx

```<code>  handleSubmit = ()=>{
      var data = this.props.data;
      console.log(this.state.editText,data);
    // this.props.update(this.state.editText);
    axios.post('http://localhost:3007/todo/updateTodo',{
        id:data._id,
        update:this.state.editText
    })
    this.setState({isEditing:false})
  }
  //the input where we enter the edited value.
            <input
            type="text"
            style={editStyle}
            value={this.state.editText}
            className="form-control"
            onChange={this.handleChange}
            onBlur = {this.handleSubmit}
            onKeyDown ={this.handleKeydown}
          />

</code>```

After submitting, the updated value must be shown, instead the todo is blank.

答: To pass the data from child to parent component you need to use redux. With redux you can can dispatch actions from child component which will mutate the reducer state. And then you can use this state anywhere in your project. In your case this reducer state can be used to update the parent component.

Body:
I am working on a react-express Todo list and cant seem to update the Todo item from the TodoItem component which is in the main App component. when i write the axios function to modify the database from the child component itself the Todo is getting blanked out after a state refresh.

I have tried sending data from the Child component to the parent but with no result.

//App.jsx

                {this.state.data.map(data => (
                  <TodoItem
                    data={data}
                    key={data.id}
                    delete={() => this.removeFromDatabase(data)}
                    edit={() => this.setState({ editing: data.id })}
                    update={(data)=>this.updateDatabase(data)}
                  />
                ))}

//TodoItem.jsx

  handleSubmit = ()=>{
      var data = this.props.data;
      console.log(this.state.editText,data);
    // this.props.update(this.state.editText);
    axios.post('http://localhost:3007/todo/updateTodo',{
        id:data._id,
        update:this.state.editText
    })
    this.setState({isEditing:false})
  }
  //the input where we enter the edited value.
            <input
            type="text"
            style={editStyle}
            value={this.state.editText}
            className="form-control"
            onChange={this.handleChange}
            onBlur = {this.handleSubmit}
            onKeyDown ={this.handleKeydown}
          />

After submitting, the updated value must be shown, instead the todo is blank.


问:
"Jwplayer not loading ts file just loading m3u8 file"
I am working with live stream for that JWplaye loading m3u8 and ts file. But after playing video for some time it's just loading m3u8 file with statuscode 200. it's not loading ts file.

I checked jwplayer state it's showing 'playing'. I checked with onError and onBuffer event but it's not going in those condition.

I expect it should load ts file or show some error

My code:

```<code>jwplayer("playback").setup({
  playlist: [{
    'sources': [{
      'file': "myPlaylist.m3u8"
    }]
  }]
});
</code>```

答:
You can't load a .ts URL directly in JW Player. You would need to load the .m3u8 manifest instead or MP4 URL over HTTP protocol.

Reference:

https://jwplayer-support-archive.netlify.com/questions/16327329--ts-file-not-loading

Body:
I am working with live stream for that JWplaye loading m3u8 and ts file. But after playing video for some time it's just loading m3u8 file with statuscode 200. it's not loading ts file.

I checked jwplayer state it's showing 'playing'. I checked with onError and onBuffer event but it's not going in those condition.

I expect it should load ts file or show some error

My code:

jwplayer("playback").setup({
  playlist: [{
    'sources': [{
      'file': "myPlaylist.m3u8"
    }]
  }]
});


问:
What's the difference between %TMP% and %TEMP% in Vista environment variables?
On my computer, the environment variables %TMP% and %TEMP% both point to the same location.

Are those for backward compatibility issues only, or is there a real difference?

答:
Raymond Chen talks about the historical use of TMP and TEMP, and says this specifically about Windows:

For whatever reason, the original authors of the GetTempFileName function chose to look for TMP before looking for TEMP.

The rest of the article is worth a read in explaining the historical use of both in DOS.  It sounds like DOS preferred TEMP semi-officially, rather than TMP, but third-party programmers were free to use what they liked, particularly given the lack of the standard API functions that Windows has.

OwnerDisplayName: Brann

LastEditorDisplayName: abatishchev


问:
Unit Test Function which Contains Promises
I have this function:

```<code>function _init()
{
    return _getNetDesc() // this is a promise
    .then(data => {

       // do something
    })
    .then(() => {

        return _getNetOperation(); // this is a promise
    })
    .then( () =>{
        return _getNetNodeList(); // this is a promise
    })

    .catch( e =>
    {
        logger.error("JZW","init",e);

    });
}
</code>```

In order to test if this function throws, I wrote in mocha/sinon/chai:

```<code>it("should throw eception for no GW", async () => {
        _getNetDesc = sinon.stub().throws();
        const test = await jzw.init;
        expect(test).to.be.rejected;

    });
</code>```

But I get

```<code> TypeError: [Function: _init] is not a thenable.
</code>```

答:
You're missing to call the function and reject the promise:</p>

```<code>it("should throw eception for no GW", async () => {
  _getNetDesc = sinon.stub().returns(Promise.reject(...)); // returns a rejected promise
  const test = await jzw.init(); // call the function to get the promise
  expect(test).to.be.rejected;
});
</code>```

Body:
I have this function:

function _init()
{
    return _getNetDesc() // this is a promise
    .then(data => {

       // do something
    })
    .then(() => {

        return _getNetOperation(); // this is a promise
    })
    .then( () =>{
        return _getNetNodeList(); // this is a promise
    })

    .catch( e =>
    {
        logger.error("JZW","init",e);

    });
}

In order to test if this function throws, I wrote in mocha/sinon/chai:

it("should throw eception for no GW", async () => {
        _getNetDesc = sinon.stub().throws();
        const test = await jzw.init;
        expect(test).to.be.rejected;

    });

But I get

 TypeError: [Function: _init] is not a thenable.

Body:
You're missing to call the function and reject the promise:

it("should throw eception for no GW", async () => {
  _getNetDesc = sinon.stub().returns(Promise.reject(...)); // returns a rejected promise
  const test = await jzw.init(); // call the function to get the promise
  expect(test).to.be.rejected;
});


问:
What is the correct way to pass data to a running thread
In most cases when you create your thread you can prepare the data beforehand and pass it into the constructor or method.

However in cases like an open socket connection you will typically already have a thread created but wish to tell it to perform some action.

Basic idea:

```<code>C#

private Thread _MyThread = new Thread(MyMethod);
this._MyThread.Start(param);

Java

private Thread _MyThread = new Thread(new MyRunnableClass(param));
this._MyThread.start();

Now what?
</code>```

So what is the correct way to pass data to a running thread in C# and Java?

答:
You could run your worker thread within a loop (if that makes sense for your requirement) and check a flag on each execution of the loop. The flag would be set by the other thread to signal the worker thread that some state had changed, it could also set a field at the same time to pass the new state.

Additionally, you could use monitor.wait and monitor.pulse to signal the state changes between the threads.

Obviously, the above would need synchronization.

Body:
In most cases when you create your thread you can prepare the data beforehand and pass it into the constructor or method.

However in cases like an open socket connection you will typically already have a thread created but wish to tell it to perform some action.

Basic idea:

C#

private Thread _MyThread = new Thread(MyMethod);
this._MyThread.Start(param);

Java

private Thread _MyThread = new Thread(new MyRunnableClass(param));
this._MyThread.start();

Now what?

So what is the correct way to pass data to a running thread in C# and Java?


问:
How to run a thread from a page in mainwindow ? (WPF)
I created a page and added a button to this page.

And I put this page in a frame in the main window.

MainUi.Content = new Page1();

I want to start a thread in mainwindow when I click the button.

In MainWindow

```<code>namespace WpfApp3
{

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    public void SendMessage()
    {
        MessageBox.Show("This is a test massage.");
        //And more
    }
}
</code>```

In Page

```<code>namespace WpfApp3.Pages
{

    public partial class Page1: Page
    {
        public Page1()
        {
            InitializeComponent();
        }

        private void SendMessage_Click(object sender, RoutedEventArgs e)
        {
             SendMessage();
             //I want run this thread from here
        }
    }
}
</code>```

Thanks.

答:
You could inject the Page with a reference to the window as suggested by @Nawed Nabi Zada, or you could get a reference to the parent window of the page using the static Window.GetWindow method:

```<code>private void SendMessage_Click(object sender, RoutedEventArgs e)
{
    MainWindow win = Window.GetWindow(this) as MainWindow;
    win.SendMessage();
}
</code>```

Body:
I created a page and added a button to this page.

And I put this page in a frame in the main window.

MainUi.Content = new Page1();

I want to start a thread in mainwindow when I click the button.

In MainWindow

namespace WpfApp3
{

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    public void SendMessage()
    {
        MessageBox.Show("This is a test massage.");
        //And more
    }
}

In Page

namespace WpfApp3.Pages
{

    public partial class Page1: Page
    {
        public Page1()
        {
            InitializeComponent();
        }

        private void SendMessage_Click(object sender, RoutedEventArgs e)
        {
             SendMessage();
             //I want run this thread from here
        }
    }
}

Thanks.

Body:
You could inject the Page with a reference to the window as suggested by @Nawed Nabi Zada, or you could get a reference to the parent window of the page using the static Window.GetWindow method:

private void SendMessage_Click(object sender, RoutedEventArgs e)
{
    MainWindow win = Window.GetWindow(this) as MainWindow;
    win.SendMessage();
}


问:
encodedOffset deprecation
In my application, I have some code to fetch the range of the host in a URL. It looks like this:

```<code>private func rangeOfHost(text: String) -> NSRange? {
    let url = URL(string: text)
    if let host: String = url?.host {
        if let range = text.range(of: host) {
            return NSRange(
                location: range.lowerBound.encodedOffset,
                length: range.upperBound.encodedOffset - range.lowerBound.encodedOffset
            )
        }
    }
    return nil
}
</code>```

Xcode has been warning me that 'encodedOffset' is deprecated: encodedOffset has been deprecated as the most common usage is incorrect. Use utf16Offset(in:) to achieve the same behavior.. However, it's not clear to me how I can replace those encodedOffsets with these suggestions. Any ideas?

Title: encodedOffset deprecation

Body:
In my application, I have some code to fetch the range of the host in a URL. It looks like this:

private func rangeOfHost(text: String) -> NSRange? {
    let url = URL(string: text)
    if let host: String = url?.host {
        if let range = text.range(of: host) {
            return NSRange(
                location: range.lowerBound.encodedOffset,
                length: range.upperBound.encodedOffset - range.lowerBound.encodedOffset
            )
        }
    }
    return nil
}

Xcode has been warning me that 'encodedOffset' is deprecated: encodedOffset has been deprecated as the most common usage is incorrect. Use utf16Offset(in:) to achieve the same behavior.. However, it's not clear to me how I can replace those encodedOffsets with these suggestions. Any ideas?

Body: yourString1.yourIndex.utf16Offset(in: yourString2)


问:
Scroll to bottom of div with Vue.js
I have a Vue.js component with several elements in it. I want to automatically scroll to the bottom of that element when a method in the component is called.

Basically, do the same as this. However, I haven't found a way to get the element within my component and modify scrollTop

I'm currently using Vue.js 2.0.8.

答:
I had the same need in my app (with complex nested components structure) and I unfortunately did not succeed to make it work. </p>

<p>Finally I used vue-scrollto that works fine ! </p>

Title: Scroll to bottom of div with Vue.js

Body:
I had the same need in my app (with complex nested components structure) and I unfortunately did not succeed to make it work.

Finally I used vue-scrollto that works fine !


答:
Is string actually std::string? And path a boost::filesystem::path? In that case, you should know that C library functions (like sprintf and printf) don't support C++ classes like std::string. That's only natural.

What you need to do is:

```<code>sprintf(filebuf, "%s%s", current.c_str(), _UserDir.c_str());
</code>```

But a more elegant solution, if you're already using C++, is to either use std::stringstream or boost::format. As a bonus won't have to mess with allocating buffers on the stack and worrying that the result might be longer than the buffer (which may lead to buffer overruns and security exploits - sprintf() is probably the culprit behind many of those...).

std::stringstream

```<code>std::stringstream filebuf;
filebuf << current_path().c_str() << _UserDir;
std::string filename = filebuf.str();
</code>```

boost::format

```<code>std::string filename = "%s%s" % current_path().c_str() % _UserDir;
</code>```

By the way, if you just want to concatenate directories, the 'proper' way to do that with boost::filesystem::path would be:

```<code>boost::filesystem::path fullPath = current_path() / _UserDir;
</code>```

Yes, the / operator is used for adding path components. They are separated by slashes after all, aren't they?

That being said, if you still choose, against all good advice, to use the old C library functions, please, for all that's good in the world, don't use sprintf(). Use the slightly-safer snprintf(), which takes the maximum buffer size as an argument.

Title: Why this sprintf statement crashing?

Body:
char filebuf[256];
path current = current_path();
std::cout<<"CurrentWorking "<<current<<endl;
string _UserDir = "TTiTraceLogs";
sprintf(filebuf,"%s/%s",current,_UserDir); ///crashing here

If I format only current, then it is ok.

sprintf(filebuf,"%s",current);

Output:

CurrentWorking D:/working/eclipse_projects/sadftp/CollectTTiTraceSept10_1009_174
_higher/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/Release

Body:
Is string actually std::string? And path a boost::filesystem::path? In that case, you should know that C library functions (like sprintf and printf) don't support C++ classes like std::string. That's only natural.

What you need to do is:

sprintf(filebuf, "%s%s", current.c_str(), _UserDir.c_str());

But a more elegant solution, if you're already using C++, is to either use std::stringstream or boost::format. As a bonus won't have to mess with allocating buffers on the stack and worrying that the result might be longer than the buffer (which may lead to buffer overruns and security exploits - sprintf() is probably the culprit behind many of those...).

std::stringstream

std::stringstream filebuf;
filebuf << current_path().c_str() << _UserDir;
std::string filename = filebuf.str();

boost::format

std::string filename = "%s%s" % current_path().c_str() % _UserDir;

By the way, if you just want to concatenate directories, the 'proper' way to do that with boost::filesystem::path would be:

boost::filesystem::path fullPath = current_path() / _UserDir;

Yes, the / operator is used for adding path components. They are separated by slashes after all, aren't they?

That being said, if you still choose, against all good advice, to use the old C library functions, please, for all that's good in the world, don't use sprintf(). Use the slightly-safer snprintf(), which takes the maximum buffer size as an argument.


问:
How to ignore DST adjustments made by java while retrieving date column from an Oracle database?
I have an Oracle table with Date column in it.

```<code>+--------+-----------------------+
|  ID    | CURR_DATE             |
+--------+-----------------------+
|   1    |2003-04-06 02:59:59    |
+--------+-----------------------+
</code>```

When I do a

```<code>select * from tablename
</code>```

in the database console, I get the correct column value for CURR_DATE.

But when I do the same from a java program using JDBC, the time shifts one hour forward due to daylight saving. Here is a link that explains it. https://www.timeanddate.com/time/change/usa/new-york?year=2003.

So I receive the value 2003-04-06 03:59:59 instead of 2003-04-06 02:59:59.

This happens because the DB and the JVM are in PST and PST follows DST.(Pls correct me if I am wrong)

Here is my code

```<code>String query="select * from tablename";
PreparedStatement psmt = con.prepareStatement(query);
ResultSet results=psmt.executeQuery();
while(results.next()) {
    System.out.println(results.getString(2));
}
</code>```

What can be done so that results.getString() returns me the same value which is in the database(without any adjustments).

I want it to return me the original value 2003-04-06 02:59:59 instead of the adjusted value 2003-04-06 03:59:59.

答:
As @gord-thompson explained you should use an up to date ojdbc8 or ojdbc10, ideally 19.3 or 18.3, you can use these even if your database is 11.2g https://www.oracle.com/technetwork/database/enterprise-edition/jdbc-faq-090281.html#01_02

```<code>results.getObject(2, LocalDateTime.class)
</code>```

Explanation

The issue is really with the implementation of the java.sql.Timestamp class. It represents the milliseconds since 1970-01-01 00:00:00 GMT and 2003-04-06 02:59:59 in JVM time zone, 2003-04-06 02:59:59 does not exist in JVM time zone so the parser is off by the DST change.

LocalDateTime is not bound to any time zone and just year-month-day-hour-minute-second-nano and therefore has no issues representing 2003-04-06 02:59:59 whatever the JVM time zone.

Body:
I have an Oracle table with Date column in it.

+--------+-----------------------+
|  ID    | CURR_DATE             |
+--------+-----------------------+
|   1    |2003-04-06 02:59:59    |
+--------+-----------------------+

When I do a

select * from tablename

in the database console, I get the correct column value for CURR_DATE.

But when I do the same from a java program using JDBC, the time shifts one hour forward due to daylight saving. Here is a link that explains it. https://www.timeanddate.com/time/change/usa/new-york?year=2003.

So I receive the value 2003-04-06 03:59:59 instead of 2003-04-06 02:59:59.

This happens because the DB and the JVM are in PST and PST follows DST.(Pls correct me if I am wrong)

Here is my code

String query="select * from tablename";
PreparedStatement psmt = con.prepareStatement(query);
ResultSet results=psmt.executeQuery();
while(results.next()) {
    System.out.println(results.getString(2));
}

What can be done so that results.getString() returns me the same value which is in the database(without any adjustments).

I want it to return me the original value 2003-04-06 02:59:59 instead of the adjusted value 2003-04-06 03:59:59.

Body:
As @gord-thompson explained you should use an up to date ojdbc8 or ojdbc10, ideally 19.3 or 18.3, you can use these even if your database is 11.2g https://www.oracle.com/technetwork/database/enterprise-edition/jdbc-faq-090281.html#01_02

results.getObject(2, LocalDateTime.class)

Explanation

The issue is really with the implementation of the java.sql.Timestamp class. It represents the milliseconds since 1970-01-01 00:00:00 GMT and 2003-04-06 02:59:59 in JVM time zone, 2003-04-06 02:59:59 does not exist in JVM time zone so the parser is off by the DST change.

LocalDateTime is not bound to any time zone and just year-month-day-hour-minute-second-nano and therefore has no issues representing 2003-04-06 02:59:59 whatever the JVM time zone.


问:
Regex to encode an URL with special characters
I need to encode a string that contains special characters such as whitespaces, ' and ".

I don't know how to create a regex.

I've tried many solutions but none of them seem to work.

My final objective is to have a string such as "black cat" encoded like this "black%20cat".

EDIT:
Guys I'm working with a specific software called "Axway policy studio" and it has a component where you put in a regex and a string, in the end you get boolean output such as true or false.

答:
It sounds more like your trying to encode things to make them more appropriate for a URL, which does not require you to write your own regex in most platforms.

For instance, in Python, there's the function urllib.parse.urlencode which would do this. In Javascript, there's encodeURI and encodeURIComponent.

TL;DR Look up urlencode in  and you'll probably find what you need. Don't bother writing regexes for it unless you really need to.

P.S. Most of the urlencoding is just replacing characters with % followed by their ascii hex value (' ' => %20, '!' => %21, ...)


问:
PayPal documentation ( REST, Classic : SOAP & NVP ) What to choose ?
I need to develop a payment solution using PayPal APIs. Actually I started the documentation phase ( on http://developers.paypal.com )

I found the REST APIs understandable, I still don't have an idea how to implement them with SpringMVC so I'm just using cURL to test them. ( any help on this ? )

On the other hand, the Classic APIs are confusing. ( for example what can we do with the Adaptive Accounts and what's the difference between Express Checkout and Adaptive Payments, etc.. ).

Another thing, is that we need to choose between creating a hidden form ( html ) or using APIs. ( I need explanation )

The documentation is very long and I'm really confused, I don't know what to choose ( obviously the REST APIs are better for simple payments, but I really want to know more about the SOAP & NVP .. )

I'm novice, s can someone be a volunteer and help me on this ?

Thank you !

答: NVP & SOAP methods are now deprecated since January 2017. https://developer.paypal.com/docs/classic/express-checkout/</p>


问:
What does completionHandler in userNotificationCenter actually do?
I'm currently implementing push notifications and I was wondering, what does completionHandler in userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler: actually do?

Apple's documentation says:

The block to execute when you have finished processing the user’s response. You must execute this block at some point after processing the user's response to let the system know that you are done. The block has no return value or parameters.

But this is very cryptic and doesn't actually answer my question. Does it kill the app because I "finished handling the action"? Does it not kill the app? What if I have some async calls (like replying to a message) and I call the completionHandler? For now it seems to be working but what if the connection is slow?

答:
If your app is in background when it receives the push notification, calling the handler signify to iOS that your application no longer needs to be assigned CPU cycles for processing until you either receive another push notification or the user interacts with your app in some way.

If your app is in foreground and active, it should have no effect.

In any case, you should be a "good iOS citizen" and only do the strict minimum when receiving a push notification. Note that there are some background download services available if you need, which you can trigger when receiving the push notification.

And as the text says, you HAVE to call this completion handler.


问:
Use jQuery to hide a DIV when the user clicks outside of it
I am using this code:

```<code>$('body').click(function() {
   $('.form_wrapper').hide();
});

$('.form_wrapper').click(function(event){
   event.stopPropagation();
});
</code>```

And this HTML:

```<code><div class="form_wrapper">
   <a class="agree" href="javascript:;">I Agree</a>
   <a class="disagree" href="javascript:;">Disagree</a>
</div>
</code>```

The problem is that I have links inside the div and when they no longer work when clicked.

答:
This solution should work fine, it's easy :

```<code>jQuery(document).ready(function($) {
    jQuery(document).click(function(event) {
        if(typeof  jQuery(event.target).attr("class") != "undefined") {
            var classnottobeclickforclose = ['donotcountmeforclickclass1', 'donotcountmeforclickclass2','donotcountmeforclickclass3'];
            var arresult = jQuery.inArray(jQuery(event.target).attr("class"), classnottobeclickforclose);
            if (arresult < 0) {
                jQuery(".popup").hide();
            }
        }
    });
});
</code>```

In Above code change donotcountmeforclickclass1 , donotcountmeforclickclass2 etc with classes which you have used to show popup or on it's click popup should not effect so you have to definitely add class which you are using to open popup.

Change .popup class with popup class.

Body:
I am using this code:

$('body').click(function() {
   $('.form_wrapper').hide();
});

$('.form_wrapper').click(function(event){
   event.stopPropagation();
});

And this HTML:

   I Agree
   Disagree

The problem is that I have links inside the div and when they no longer work when clicked.

Body:
This solution should work fine, it's easy :

jQuery(document).ready(function($) {
    jQuery(document).click(function(event) {
        if(typeof  jQuery(event.target).attr("class") != "undefined") {
            var classnottobeclickforclose = ['donotcountmeforclickclass1', 'donotcountmeforclickclass2','donotcountmeforclickclass3'];
            var arresult = jQuery.inArray(jQuery(event.target).attr("class"), classnottobeclickforclose);
            if (arresult < 0) {
                jQuery(".popup").hide();
            }
        }
    });
});

In Above code change donotcountmeforclickclass1 , donotcountmeforclickclass2 etc with classes which you have used to show popup or on it's click popup should not effect so you have to definitely add class which you are using to open popup.

Change .popup class with popup class.


问:
Can't get activation URL after publishing a Closed Alpha Testing using email liste tester
After publishing a version of my application on Google Play Console, I don't receive the activation URL.

I've waited many day after publishing and no changes. On the top right of the "Application Version" Under my application name, it still noted "not published" ( I don't know if it matter ). But under my version name, it's noted Full deployment.

https://i.imgur.com/sz8aiQp.jpg

答: Going to "Presence on the Play Store" > "Price and availability" > "Availability of the application" and turn to PUBLISHED fixed it.</p>


问:
Using a Cursor in a Stored Procudure
I have the following code extremely slow code in a MS SQL 2016 Stored Procedure (I think it is stuck in a never ending loop):

```<code>@DBID Integer
AS
BEGIN

DECLARE TagCursor CURSOR FOR SELECT MemberID
FROM           ADMIN_API_Master_Members_List
WHERE DBID= @DBID AND Len(Pending) > 0

DECLARE @ProgramCode VARCHAR(10)
DECLARE @Values VARCHAR(MAX)
DECLARE @tag nvarchar(10)

  OPEN TagCursor

      FETCH NEXT FROM TagCursor INTO @tag
      WHILE (@@FETCH_STATUS = 0)
      BEGIN

     SELECT @ProgramCode = Program_Code, @Values= Pending FROM  ADMIN_API_Master_Members_List WHERE MemberID= @tag

     DELETE FROM ADMIN_API_PMID_PROGRAM_CODE_HOLDING_TABLE
     WHERE  (MemberID =@tag)

     INSERT INTO ADMIN_API_PMID_PROGRAM_CODE_HOLDING_TABLE ( ProgramCode, MemberID, DBID, PMID)
     SELECT    @ProgramCode, @tag, @DBID ,  Value FROM STRING_SPLIT(@Values, ',')
     END

      CLOSE TagCursor
      DEALLOCATE TagCursor
END
</code>```

This Procedure is only a maintenance process and does not get run very often but when it does it would be nice to only take a few seconds.  The purpose is to normalize in a Table one record for each comma seperated value in the ADMIN_API_Master_Members_List Table and put it into the ADMIN_API_PMID_PROGRAM_CODE_HOLDING_TABLE with the Program_Code and MemberID and DBID.

There are only about 150 records in the Master Table and the comma separated strings may have 5 values.  I am receptive to other solutions.

Thanks in advance

答:
The reason for the infinite loop may be that you have no "Fetch next" inside your loop
Try the below:</p>

```<code>  @DBID Integer
  AS
  BEGIN

  DECLARE TagCursor CURSOR FOR SELECT MemberID
  FROM           ADMIN_API_Master_Members_List
  WHERE DBID= @DBID AND Len(Pending) > 0

  DECLARE @ProgramCode VARCHAR(10)
  DECLARE @Values VARCHAR(MAX)
  DECLARE @tag nvarchar(10)

    OPEN TagCursor
        FETCH NEXT FROM TagCursor INTO @tag

        WHILE (@@FETCH_STATUS = 0)
        BEGIN

       SELECT @ProgramCode = Program_Code, @Values= Pending FROM  ADMIN_API_Master_Members_List WHERE MemberID= @tag

       DELETE FROM ADMIN_API_PMID_PROGRAM_CODE_HOLDING_TABLE
       WHERE  (MemberID =@tag)

       INSERT INTO ADMIN_API_PMID_PROGRAM_CODE_HOLDING_TABLE ( ProgramCode, MemberID, DBID, PMID)
       SELECT    @ProgramCode, @tag, @DBID ,  Value FROM STRING_SPLIT(@Values, ',')
      FETCH NEXT FROM TagCursor INTO @tag
       END

        CLOSE TagCursor
        DEALLOCATE TagCursor
  END
</code>```

Title: Using a Cursor in a Stored Procudure

Body:
I have the following code extremely slow code in a MS SQL 2016 Stored Procedure (I think it is stuck in a never ending loop):

@DBID Integer
AS
BEGIN

DECLARE TagCursor CURSOR FOR SELECT MemberID
FROM           ADMIN_API_Master_Members_List
WHERE DBID= @DBID AND Len(Pending) > 0

DECLARE @ProgramCode VARCHAR(10)
DECLARE @Values VARCHAR(MAX)
DECLARE @tag nvarchar(10)

  OPEN TagCursor

      FETCH NEXT FROM TagCursor INTO @tag
      WHILE (@@FETCH_STATUS = 0)
      BEGIN

     SELECT @ProgramCode = Program_Code, @Values= Pending FROM  ADMIN_API_Master_Members_List WHERE MemberID= @tag

     DELETE FROM ADMIN_API_PMID_PROGRAM_CODE_HOLDING_TABLE
     WHERE  (MemberID =@tag)

     INSERT INTO ADMIN_API_PMID_PROGRAM_CODE_HOLDING_TABLE ( ProgramCode, MemberID, DBID, PMID)
     SELECT    @ProgramCode, @tag, @DBID ,  Value FROM STRING_SPLIT(@Values, ',')
     END

      CLOSE TagCursor
      DEALLOCATE TagCursor
END

This Procedure is only a maintenance process and does not get run very often but when it does it would be nice to only take a few seconds.  The purpose is to normalize in a Table one record for each comma seperated value in the ADMIN_API_Master_Members_List Table and put it into the ADMIN_API_PMID_PROGRAM_CODE_HOLDING_TABLE with the Program_Code and MemberID and DBID.

There are only about 150 records in the Master Table and the comma separated strings may have 5 values.  I am receptive to other solutions.

Thanks in advance

Body:
The reason for the infinite loop may be that you have no "Fetch next" inside your loop
Try the below:

  @DBID Integer
  AS
  BEGIN

  DECLARE TagCursor CURSOR FOR SELECT MemberID
  FROM           ADMIN_API_Master_Members_List
  WHERE DBID= @DBID AND Len(Pending) > 0

  DECLARE @ProgramCode VARCHAR(10)
  DECLARE @Values VARCHAR(MAX)
  DECLARE @tag nvarchar(10)

    OPEN TagCursor
        FETCH NEXT FROM TagCursor INTO @tag

        WHILE (@@FETCH_STATUS = 0)
        BEGIN

       SELECT @ProgramCode = Program_Code, @Values= Pending FROM  ADMIN_API_Master_Members_List WHERE MemberID= @tag

       DELETE FROM ADMIN_API_PMID_PROGRAM_CODE_HOLDING_TABLE
       WHERE  (MemberID =@tag)

       INSERT INTO ADMIN_API_PMID_PROGRAM_CODE_HOLDING_TABLE ( ProgramCode, MemberID, DBID, PMID)
       SELECT    @ProgramCode, @tag, @DBID ,  Value FROM STRING_SPLIT(@Values, ',')
      FETCH NEXT FROM TagCursor INTO @tag
       END

        CLOSE TagCursor
        DEALLOCATE TagCursor
  END


问:
What is the 3rd argument type for getSupportLoaderManager(id, args, ??)
I've an AsyncTaskLoader method which restarts the current Loader,

It's for school purpose,

```<code>private void startAsyncTaskLoader()
{
    getSupportLoaderManager().restartLoader(TASK_ID, null, this);
}
</code>```

I can check the solution online on the school github but this is the good one,
But in my android studio "this" (3rd argument) is incorrect type...

```<code>-->
Wrong 3rd argument type. Found: 'com.openclassrooms.freezap.Controllers.MainActivity', required: 'android.support.v4.app.LoaderManager.LoaderCallbacks<java.lang.Object>'
</code>```

I understand I placed a context argument (MainActivity) but I don't have an instance of LoaderManager.

答:
What is the 3rd argument type for getSupportLoaderManager(id, args, ??)

That method takes no arguments.

If you really mean restartLoader(), the third parameter is android.support.v4.app.LoaderManager.LoaderCallbacks, as you can tell from your error message and from the documentation for restartLoader().

Body:
I've an AsyncTaskLoader method which restarts the current Loader,

It's for school purpose,

private void startAsyncTaskLoader()
{
    getSupportLoaderManager().restartLoader(TASK_ID, null, this);
}

I can check the solution online on the school github but this is the good one,
But in my android studio "this" (3rd argument) is incorrect type...

-->
Wrong 3rd argument type. Found: 'com.openclassrooms.freezap.Controllers.MainActivity', required: 'android.support.v4.app.LoaderManager.LoaderCallbacks<java.lang.Object>'

I understand I placed a context argument (MainActivity) but I don't have an instance of LoaderManager.


问:
How should AutoMapper access my DAL?
I have an InvoiceInputModel with a ProjectId property which is a reference to a Project entity. Ideally, I want AutoMapper to be able to map an entire Invoice entity from an InvoiceInputModel, which looks like this:

```<code>public class InvoiceInputModel
{
    public Guid Id { get; set; }
    public DateTime Date { get; set; }
    public string Reference { get; set; }
    public Guid ProjectId { get; set; }
}
</code>```

Obviously the following is bad:

```<code>Mapper.CreateMap<InvoiceInputModel, Invoice>()
    .ForMember(src => src.Project, opt => opt.MapFrom(
        dest => _unitOfWork.CurrentSession.Get<Project>(dest.ProjectId)
    )
);
</code>```

How do I tell AutoMapper that invoice.Project should be mapped to a Project entity based off of the ProjectId property in InvoiceInputModel while preserving loose coupling?

Invoice/Edit in my InvoiceController:

```<code>[HttpPost]
[Authorize]
public ActionResult Edit(InvoiceInputModel invoiceInputModel)
{
    var invoice = _unitOfWork.CurrentSession.Get<Invoice>(invoiceInputModel.Id);

    Mapper.Map<InvoiceInputModel, Invoice>(invoiceInputModel, invoice);

    invoice.Project = _unitOfWork.CurrentSession.Get<Project>(invoiceInputModel.ProjectId);
    // I want AutoMapper to do the above.

    _unitOfWork.CurrentSession.SaveOrUpdate(invoice);
    _unitOfWork.Commit();

    return View(invoice);
}
</code>```

I spotted something about "Resolvers" and ResolveUsing, but I have no experience using it.

How do I tell AutoMapper to do this while preserving loose coupling between my entity models, input models and view models? Or is there a better way?

答:
I personally have entities in viewmodels instead of IDs, so that binding happens automatically.

http://sprokhorenko.blogspot.com/2011/03/bind-to-entity-id.html

Title: How should AutoMapper access my DAL?

Body:
I have an InvoiceInputModel with a ProjectId property which is a reference to a Project entity. Ideally, I want AutoMapper to be able to map an entire Invoice entity from an InvoiceInputModel, which looks like this:

public class InvoiceInputModel
{
    public Guid Id { get; set; }
    public DateTime Date { get; set; }
    public string Reference { get; set; }
    public Guid ProjectId { get; set; }
}

Obviously the following is bad:

Mapper.CreateMap<InvoiceInputModel, Invoice>()
    .ForMember(src => src.Project, opt => opt.MapFrom(
        dest => _unitOfWork.CurrentSession.Get<Project>(dest.ProjectId)
    )
);

How do I tell AutoMapper that invoice.Project should be mapped to a Project entity based off of the ProjectId property in InvoiceInputModel while preserving loose coupling?

Invoice/Edit in my InvoiceController:

[HttpPost]
[Authorize]
public ActionResult Edit(InvoiceInputModel invoiceInputModel)
{
    var invoice = _unitOfWork.CurrentSession.Get<Invoice>(invoiceInputModel.Id);

    Mapper.Map<InvoiceInputModel, Invoice>(invoiceInputModel, invoice);

    invoice.Project = _unitOfWork.CurrentSession.Get<Project>(invoiceInputModel.ProjectId);
    // I want AutoMapper to do the above.

    _unitOfWork.CurrentSession.SaveOrUpdate(invoice);
    _unitOfWork.Commit();

    return View(invoice);
}

I spotted something about "Resolvers" and ResolveUsing, but I have no experience using it.

How do I tell AutoMapper to do this while preserving loose coupling between my entity models, input models and view models? Or is there a better way?


问:
loopback event stream causing race condition
My overall goal is to watch my database for any changes and automatically broadcast those changes to any user connected to my website.
The problem that I am seeing is that I have an action triggering a post request to my database and then the event stream is triggered at the same time because the model that I am watching has changed. Which results in the initial action fulfilling and the action triggered by the event stream is being interrupted before it is fulfilled.

this is the first action that is triggered to create a new blog post entry in my database

export const topicSubmit = (date, newTopic, newTopicBody, memberId, name) => {
    return {
        type: 'TOPIC_SUBMIT',
        payload: axios({
            method: 'post',
            url: `/api/blogPosts`,
            data: {
                "blogTitle": newTopic,
                "blogBody": newTopicBody,
                "date": date,
                "upVotes": 0,
                "numComments": 0,
                "voteNames": [],
                "memberId": memberId,
                "steamNameId": name
            }
        })
            .then(response => {
                return response.data
            })
            .catch(err => err)
    }
}

// this is the boot script that creates the change stream

var es = require('event-stream');
module.exports = function (app) {
    console.log('realtime boot script')
    var BlogPost = app.models.BlogPost;
    BlogPost.createChangeStream(function (err, changes) {
        changes.pipe(es.stringify()).pipe(process.stdout);
    });
}

// this is the event listener on my front end that will dispatch all
// changes made in my database to my front end

componentDidMount() {
        const { dispatch } = this.props;
          let urlToChangeStream = '/api/blogPosts/change-stream?_format=event-stream';
          let src = new EventSource(urlToChangeStream);
          src.addEventListener('data', function (msg) {
              let data = JSON.parse(msg.data);
          dispatch(liveChangeBlogs(data))
          });
```

I am expecting that the 'TOPIC_SUBMIT' action should return fulfilled before the 'liveChangeBlogs' action is dispatched by the event listener
Here is the documentation that I found on loopback event stream https://loopback.io/doc/en/lb3/Realtime-server-sent-events.html

答:
I am expecting that the 'TOPIC_SUBMIT' action should return fulfilled before the 'liveChangeBlogs' action is dispatched by the event listener

I am afraid this is not possible. Even if the LoopBack server withheld sending of the event-stream entry until a response to the POST request was sent, it still won't be able to guarantee that the client will receive (and process!) the response to the POST request before it processes the event-stream entry.

My recommendation is to keep track of in-flight requests in your client and drop event-stream entries for changes made by the same client.

Something along the following lines:

const pendingRequests = [];

export const topicSubmit = (date, newTopic, newTopicBody, memberId, name) => {
    const data = {
                "blogTitle": newTopic,
                "blogBody": newTopicBody,
                "date": date,
                "upVotes": 0,
                "numComments": 0,
                "voteNames": [],
                "memberId": memberId,
                "steamNameId": name
            };
    const entry = {type: 'CREATE', data}
    pendingRequests.push(entry);

    return {
        type: 'TOPIC_SUBMIT',
        payload: axios({
            method: 'post',
            url: `/api/blogPosts`,
            data,

        })
            .then(response => {
                return response.data
            })
            .catch(err => err)
            .finally(() => {
              // remove the entry from pending requests
              const ix = pendingRequests.indexOf(entry);
              if (ix > -1) pendingRequests.splice(ix, 1);
            })
    }
}

// this is the event listener on my front end that will dispatch all
// changes made in my database to my front end
// (...)
          src.addEventListener('data', function (msg) {
              let data = JSON.parse(msg.data);
              const ours = pendingRequests.find(it => {
                it.type === data.type && /* check fields that uniquely identify model instance and/or the change being made */
              });
              if (ours) {
                // this event was triggered by us, discard it
                return;
              }
          dispatch(liveChangeBlogs(data))
          });
```

Body:
My overall goal is to watch my database for any changes and automatically broadcast those changes to any user connected to my website.
The problem that I am seeing is that I have an action triggering a post request to my database and then the event stream is triggered at the same time because the model that I am watching has changed. Which results in the initial action fulfilling and the action triggered by the event stream is being interrupted before it is fulfilled.

this is the first action that is triggered to create a new blog post entry in my database

export const topicSubmit = (date, newTopic, newTopicBody, memberId, name) => {
    return {
        type: 'TOPIC_SUBMIT',
        payload: axios({
            method: 'post',
            url: `/api/blogPosts`,
            data: {
                "blogTitle": newTopic,
                "blogBody": newTopicBody,
                "date": date,
                "upVotes": 0,
                "numComments": 0,
                "voteNames": [],
                "memberId": memberId,
                "steamNameId": name
            }
        })
            .then(response => {
                return response.data
            })
            .catch(err => err)
    }
}

// this is the boot script that creates the change stream

var es = require('event-stream');
module.exports = function (app) {
    console.log('realtime boot script')
    var BlogPost = app.models.BlogPost;
    BlogPost.createChangeStream(function (err, changes) {
        changes.pipe(es.stringify()).pipe(process.stdout);
    });
}

// this is the event listener on my front end that will dispatch all
// changes made in my database to my front end

componentDidMount() {
        const { dispatch } = this.props;
          let urlToChangeStream = '/api/blogPosts/change-stream?_format=event-stream';
          let src = new EventSource(urlToChangeStream);
          src.addEventListener('data', function (msg) {
              let data = JSON.parse(msg.data);
          dispatch(liveChangeBlogs(data))
          });

I am expecting that the 'TOPIC_SUBMIT' action should return fulfilled before the 'liveChangeBlogs' action is dispatched by the event listener
Here is the documentation that I found on loopback event stream https://loopback.io/doc/en/lb3/Realtime-server-sent-events.html


问:
Android Get/Set Value to an ImageView
I have an ImageView as such:

```<code><ImageView
    android:id="@+id/p4"
    android:layout_width="32dp"
    android:layout_height="32dp"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    android:onClick="getPriority"
    android:value="P4"
    android:contentDescription="@string/ContentDescription_fromAddItemActivity_Priority4Icon"
    app:srcCompat="@drawable/ic_priority_4"/>
</code>```

I want to get the value "P4" programatically. How do i do that ?

I've already tried ".getValue()" and it doesn't exists.

Please help me. Thank you.

答: instead of android:value="P4" You can use android:tag="P4" and then you can use getTag() and setTag() methods of it.

Title: Android Get/Set Value to an ImageView

Body:
I have an ImageView as such:

<ImageView
    android:id="@+id/p4"
    android:layout_width="32dp"
    android:layout_height="32dp"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    android:onClick="getPriority"
    android:value="P4"
    android:contentDescription="@string/ContentDescription_fromAddItemActivity_Priority4Icon"
    app:srcCompat="@drawable/ic_priority_4"/>

I want to get the value "P4" programatically. How do i do that ?

I've already tried ".getValue()" and it doesn't exists.

Please help me. Thank you.


问:
Problems creating Docker container with python code
I'm very new to both python and docker, but nevertheless I'm trying to create a Docker container for password-generator app I wrote.
But after building the app, I am getting error messages that I don't know if they are related to the python code or to the way I built the Docker.

I expected the app to run normally but instead I got this error message:

```<code>URL? >>  Traceback (most recent call last):
  File "pwd1.py", line 6, in <module>
    url = input('URL? >>  ')
EOFError: EOF when reading a line
</code>```

This was never a problem in my computer or in Sublime, where the app always functioned normally.

This was the original code (the "(...) in the end of variable "a", is due to Nano not transcribing the rest of the carachters outside the visible screen):

```<code>import random

a = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'A', 'a', 'B', 'b', 'C', 'c', 'D', 'd', 'E', 'e', 'F', 'f', 'G','g', 'H', 'h', 'I', 'i', 'J', 'j', 'K', 'k', 'L', 'l', 'M', 'm', 'N', 'n', 'O', 'o', 'P', 'p'(...)]

file = open('/home/mic/python/password-generator/list.py', 'a')
url = input('URL? >>  ')
file.write(url)
file.write('  -  ')
k: int = int(input('How long? >>  '))
b = (str(''.join(random.sample(a, k))))
print(b)
file.write(b)
file.write('\n')
file.close()
</code>```

After researching the error I altered the code to this:

```<code>import random

a = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'A', 'a', 'B', 'b', 'C', 'c', 'D', 'd', 'E', 'e', 'F', 'f', 'G','g', 'H', 'h', 'I', 'i', 'J', 'j', 'K', 'k', 'L', 'l', 'M', 'm', 'N', 'n', 'O', 'o', 'P', 'p'(...)]

file = open('list.py', 'a')
url = input('URL? >>  ')
while True:
    try:
        line = input()
    except EOFError:
        print ("EOFError")
file.write(url)
file.write('  -  ')
k: int = int(input('How long? >>  '))
b = (str(''.join(random.sample(a, k))))
print(b)
file.write(b)
file.write('\n')
file.close()
</code>```

But I get the same error message. I tried this code on sublime, the computer and on online editors and not one complained about it.

It's because of this thqat I started thinking if it had something to do with my Docker files.

This is my Dockerfile:

```<code># Use an official Python runtime as a parent image
FROM python:3.7.3

# Set the working directory to /app
WORKDIR /password

# Copy the current directory contents into the container at /app
COPY . /password

# Make port 80 available to the world outside this container
EXPOSE 80

# Define environment variable
ENV NAME World

# Run app.py when the container launches
CMD ["python", "pwd1.py"]
</code>```

I followed the directions explained here https://docs.docker.com/get-started, and when I try to run the app with "sudo docker run pwdmanager", I get the aforementioned error message.

Any help would be greatly appreciated

答:
Please run your Docker container using the -i flag (interactive).

Example:

```<code>docker run -i -t <your-options>
</code>```

This, of course, will leave the biggest problem on the table, as correctly pointed out in a comment from @MisterMiyagi:

input asks for input on stdin, for example from a terminal. How do you
  provide this in the container? Your docker file seems not to include
  any input for pwd1.py

In order to solve this I would suggest you to read this answer on SO.

Or, imho, just skip using Docker for this use case.

Body:
I'm very new to both python and docker, but nevertheless I'm trying to create a Docker container for password-generator app I wrote.
But after building the app, I am getting error messages that I don't know if they are related to the python code or to the way I built the Docker.

I expected the app to run normally but instead I got this error message:

URL? >>  Traceback (most recent call last):
  File "pwd1.py", line 6, in <module>
    url = input('URL? >>  ')
EOFError: EOF when reading a line

This was never a problem in my computer or in Sublime, where the app always functioned normally.

This was the original code (the "(...) in the end of variable "a", is due to Nano not transcribing the rest of the carachters outside the visible screen):

import random

a = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'A', 'a', 'B', 'b', 'C', 'c', 'D', 'd', 'E', 'e', 'F', 'f', 'G','g', 'H', 'h', 'I', 'i', 'J', 'j', 'K', 'k', 'L', 'l', 'M', 'm', 'N', 'n', 'O', 'o', 'P', 'p'(...)]

file = open('/home/mic/python/password-generator/list.py', 'a')
url = input('URL? >>  ')
file.write(url)
file.write('  -  ')
k: int = int(input('How long? >>  '))
b = (str(''.join(random.sample(a, k))))
print(b)
file.write(b)
file.write('\n')
file.close()

After researching the error I altered the code to this:

import random

a = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'A', 'a', 'B', 'b', 'C', 'c', 'D', 'd', 'E', 'e', 'F', 'f', 'G','g', 'H', 'h', 'I', 'i', 'J', 'j', 'K', 'k', 'L', 'l', 'M', 'm', 'N', 'n', 'O', 'o', 'P', 'p'(...)]

file = open('list.py', 'a')
url = input('URL? >>  ')
while True:
    try:
        line = input()
    except EOFError:
        print ("EOFError")
file.write(url)
file.write('  -  ')
k: int = int(input('How long? >>  '))
b = (str(''.join(random.sample(a, k))))
print(b)
file.write(b)
file.write('\n')
file.close()

But I get the same error message. I tried this code on sublime, the computer and on online editors and not one complained about it.

It's because of this thqat I started thinking if it had something to do with my Docker files.

This is my Dockerfile:

# Use an official Python runtime as a parent image
FROM python:3.7.3

# Set the working directory to /app
WORKDIR /password

# Copy the current directory contents into the container at /app
COPY . /password

# Make port 80 available to the world outside this container
EXPOSE 80

# Define environment variable
ENV NAME World

# Run app.py when the container launches
CMD ["python", "pwd1.py"]

I followed the directions explained here https://docs.docker.com/get-started, and when I try to run the app with "sudo docker run pwdmanager", I get the aforementioned error message.

Any help would be greatly appreciated

Body:
Please run your Docker container using the -i flag (interactive).

Example:

docker run -i -t <your-options>

This, of course, will leave the biggest problem on the table, as correctly pointed out in a comment from @MisterMiyagi:

input asks for input on stdin, for example from a terminal. How do you
  provide this in the container? Your docker file seems not to include
  any input for pwd1.py

In order to solve this I would suggest you to read this answer on SO.

Or, imho, just skip using Docker for this use case.


问:
Does git pull change HEAD?
I understand how git checkout changes the HEAD pointer but what about git pull?

HEAD can be seen as the 'current branch' but when you execute git pull and your current branch is altered. Does it affect HEAD pointer? Why?

答:
Does it affect HEAD pointer?

It's easy to find out for yourself. In you local clone of some git repo, create a new branch (so that you can mess around without endangering any of your work), and make sure that it's up to date with the remote:

```<code>git checkout -b test-branch
git pull
</code>```

Next, take a look at HEAD in that branch:

```<code>git log
</code>```

Note the value of HEAD, which is the most recent commit. Now change HEAD using the reset command to go back a few commits:

```<code>git reset --hard HEAD~3
</code>```

Now you've intentionally changed HEAD -- that's what reset does. The synopsis of the reset command is: Reset current HEAD to the specified state. That is, you've just gone back in time to 3 commits before the latest commit. Let's look at HEAD again:

```<code>git log
</code>```

You can see that HEAD has changed from what it was before. Now, use pull to add the "new" commits from the remote back to your branch, and look again at HeAD:

```<code>git pull
git log
</code>```

You should see that HEAD is back to where it was before the reset, and this should show you that git pull does change HEAD and why.

HEAD isn't special for any reason other than being a name for the latest commit. Anything you do that changes what git sees as the latest commit in your branch changes the value of HEAD.

Title: Does git pull change HEAD?

Body:
Does it affect HEAD pointer?

It's easy to find out for yourself. In you local clone of some git repo, create a new branch (so that you can mess around without endangering any of your work), and make sure that it's up to date with the remote:

git checkout -b test-branch
git pull

Next, take a look at HEAD in that branch:

git log

Note the value of HEAD, which is the most recent commit. Now change HEAD using the reset command to go back a few commits:

git reset --hard HEAD~3

Now you've intentionally changed HEAD -- that's what reset does. The synopsis of the reset command is: Reset current HEAD to the specified state. That is, you've just gone back in time to 3 commits before the latest commit. Let's look at HEAD again:

git log

You can see that HEAD has changed from what it was before. Now, use pull to add the "new" commits from the remote back to your branch, and look again at HeAD:

git pull
git log

You should see that HEAD is back to where it was before the reset, and this should show you that git pull does change HEAD and why.

HEAD isn't special for any reason other than being a name for the latest commit. Anything you do that changes what git sees as the latest commit in your branch changes the value of HEAD.


问:
how to be sure in Linq to SQL that record has been added successfully or not?
I am just learning Linq to SQL and don't know much. Kindly guide and help me.

I am adding a new record by using a SubmitChanges();  How I can be confirmed that record has been added? For example, in using stored procedures we use to send a flag back to application but how is it done in LINQ to SQL? Please guide me.

答:
Check this http://msdn.microsoft.com/en-us/library/bb399378.aspx

At this point, any errors detected by the database cause the submission process to stop, and an exception is raised. All changes to the database are rolled back as if no submissions ever occurred. The DataContext still has a full recording of all changes. You can therefore try to correct the problem and call SubmitChanges again

```<code>Northwnd db = new Northwnd(@"c:\northwnd.mdf");
// Make changes here.
try
{
    db.SubmitChanges();
}
catch (ChangeConflictException e)
{
    Console.WriteLine(e.Message);
    // Make some adjustments.
    // ...
    // Try again.
    db.SubmitChanges();
}
</code>```

Body:
Check this http://msdn.microsoft.com/en-us/library/bb399378.aspx

At this point, any errors detected by the database cause the submission process to stop, and an exception is raised. All changes to the database are rolled back as if no submissions ever occurred. The DataContext still has a full recording of all changes. You can therefore try to correct the problem and call SubmitChanges again

Northwnd db = new Northwnd(@"c:\northwnd.mdf");
// Make changes here.
try
{
    db.SubmitChanges();
}
catch (ChangeConflictException e)
{
    Console.WriteLine(e.Message);
    // Make some adjustments.
    // ...
    // Try again.
    db.SubmitChanges();
}