Variable value got changed unexpectedly in nodeJS - node.js

let fulfillmentMessages = []
let multipleRides = formats.text_message
multipleRides.payload.data.text = predefined_responses.intent_report_lost_credential_confirmation_yes.case_ids.response
console.log("Multiple rides Message")
console.log(JSON.stringify(multipleRides))
let noRides = formats.text_message;
noRides.payload.data.text = predefined_responses.intent_report_lost_credential_confirmation_yes_2.response;
console.log("Multiple rides Message after")
console.log(JSON.stringify(multipleRides))
fulfillmentMessages.push(multipleRides)
fulfillmentMessages.push(noRides)
console.log("Going to send these messages")
console.log(JSON.stringify(fulfillmentMessages))
After this code executes multipleRides and noRides have same values in it and array contains the same value twice. Can someone please explain what I am doing wrong here?

The main problem here is that both variables, multipleRides and noRides, are referencing the same object, formats.text_message and thus, multipleRides.payload.data is the same object as noRides.payload.data. For that reason, the value stored in multipleRides.payload.data.text is overwritten by the assignment to noRides.payload.data.text. In JavaScript objects are copied by reference and not by value. You will need to do a deep clone of formats.text_message. A shallow copy wont be enough, due to how deep that text is.
This article will give you some hints for doing a deep clone. My advice is to use lodash, the code will be:
const _ = require('lodash')
let fulfillmentMessages = []
let multipleRides = _.cloneDeep(formats.text_message)
multipleRides.payload.data.text = predefined_responses.intent_report_lost_credential_confirmation_yes.case_ids.response
console.log("Multiple rides Message")
console.log(JSON.stringify(multipleRides))
let noRides = _.cloneDeep(formats.text_message);
noRides.payload.data.text = predefined_responses.intent_report_lost_credential_confirmation_yes_2.response;
console.log("Multiple rides Message after")
console.log(JSON.stringify(multipleRides))
fulfillmentMessages.push(multipleRides)
fulfillmentMessages.push(noRides)
console.log("Going to send these messages")
console.log(JSON.stringify(fulfillmentMessages))
You could also use JSON.parse(JSON.stringify(formats.text_message))
I hope this helps!

Related

How to resolve value error for a Youtube Comment and Reply Scraper function using Youtube API and Python

Am trying to create a function that uses Youtube API to fetch the comments and responses.
Please find my code below . This shows value error and doesn't work when am trying to store the data in DataFrame. I could understand that the issue is with the Reply Part but am not sure what went wrong. Any guidance or suggestions to tell me where I have gone wrong?
Update : I also noticed not all comments are getting extracted.
Thanks in Advance.
My Code :
def vid_comments():
Username = []
Comment = []
Comment_Likes = []
Comment_Date = []
Reply_Count = []
Reply = []
Replied_By = []
video_response=resource.commentThreads().list(part='snippet,replies',videoId=Video_ID).execute()
while video_response:
for item in video_response['items']:
item_info = item["snippet"]
topLevelComment = item_info["topLevelComment"]
comment_info = topLevelComment["snippet"]
Username.append(comment_info["authorDisplayName"])
Comment.append(comment_info["textDisplay"])
Comment_Likes.append(comment_info["likeCount"])
Comment_Date.append(comment_info['publishedAt'])
comment = item['snippet']['topLevelComment']['snippet']['textDisplay']
replycount = item['snippet']['totalReplyCount']
Reply_Count.append(replycount)
if replycount>0:
for reply in item['replies']['comments']:
reply_info = reply["snippet"]
Reply.append(reply_info['textDisplay'])
Replied_By.append(reply_info['authorDisplayName'])
if 'nextPageToken' in video_response:
p_token = video_response['nextPageToken']
video_response = resource.commentThreads().list(part = 'snippet,replies',videoId = Video_ID,pageToken = p_token).execute()
else:
break
vid_comments()
cmt_data = {'Comment': Comment,'Username':Username,'Comment Likes Count':Comment_Likes,'Comment Date':Comment_Date,'Reply Count':Reply_Count}
Comment_Section=pd.DataFrame(cmt_data)
reply_data = {'Reply':Reply,'Replied_By':Replied_By}
Reply_Section = pd.DataFrame(reply_data)
This issues is solved with few modifications in the code

How is the context treated?

I have a weird behaviour on Core Data with my App. I have an App where user can create their own words entries with translation. When deleting all my Core Data I checked the nb of item and it was 0. When adding later 4 items the nb of items was 5?? I found the issue after a lot of tests and it seems not consistent for me: the issue was with this code:
fileprivate func duplicateCheckAndImport() {
// Check for duplicates
do {
self.words = try context.fetch(Word.fetchRequest()) // grab all Words
let nbOfWords = words!.count
print ("The nb of words in duplicateCheck...: \(nbOfWords ?? 0)")
}
catch {
// error message to add
}
let newWord = Word(context: self.context)
do {
self.words = try context.fetch(Word.fetchRequest()) // grab all Words
let nbOfWords = words!.count
print ("The nb of words in duplicateCheck...: \(nbOfWords ?? 0)")
}
catch {
// error message to add
}
the result of the 2 prints is 0 for the first grab and 1 for the 2nd grab which means that just this line of code -> let newWord = Word(context: self.context) adds an entry in Core Data but my purpose was just to take the context add words later on like this:
let newWord = Word(context: self.context)
newWord.name = item.name.trimmingCharacters(in: .whitespaces)
newWord.definition = item.definition.trimmingCharacters(in: .whitespaces)
Can someone explain me?
The line of code you mention
let newWord = Word(context: self.context)
...creates a new instance. That's what Word(context: self.context) does-- it says, create a new instance of Word using the context that you pass in.
From the code you provide, it's hard to tell exactly what you're trying to do that would not create a new instance. Your variable is called newWord, which suggests that you do mean to create a new Word, and that's what's happening.
Update: If you don't want the new instance, you can delete it just like any other managed object. So if you don't want newWord, you can
context.delete(newWord)
And then save changes. There are other ways to do this, but this is the simplest.

How to set guild_subscriptions event to true in discord.py?

I am facing a problem in discord.py, the following code is running perfectly, but ctx.guild.owner returns none, and in documentation it says that if this happens the event guild_subscriptions is set to False, how can I set this event to True in order to make it work? I can't find any solution in discord.py documentation, neither Google.
The code of my serverstats command:
#commands.command(name="serverstats", aliases = ["serverinfo", "si", "ss", "check-stats", 'cs'])
async def serverstats(self, ctx: commands.Context):
embed = discord.Embed(
color = discord.Colour.orange(),
title = f"{ctx.guild.name}")
embed.set_thumbnail(url = f"{ctx.guild.icon_url}")
embed.add_field(name = "ID", value = f"{ctx.guild.id}")
embed.add_field(name = "👑Owner", value = f"{ctx.guild.owner}")
embed.add_field(name = "🌍Region", value = f"{ctx.guild.region}")
embed.add_field(name = "👥Member Count", value = f"{ctx.guild.member_count}")
embed.add_field(name = "📆Created at", value = f"{ctx.guild.created_at}")
embed.set_footer(icon_url = f"{ctx.author.avatar_url}", text = f"Requested by {ctx.author.name}")
await ctx.send(embed=embed)
the event guild_subscriptions is set to False
I can't find any solution in discord.py documentation
It's not an event. The docs say it's a parameter when creating a commands.Bot instance, and that you can find in the documentation for Clients, which you can. If you scroll down to the bottom of that list of parameters, you'll see guild_subscriptions(bool), which is what you're looking for.
To enable this, all you have to do is add it to the code where you create your Client:
client = commands.Bot(command_prefix=your_prefix, guild_subscriptions=True)
Also, since Discord 1.5 you now need to pass the correct Intents, and the documentation for Client states that you need to have Intents.members enabled if you don't want guild.owner to return None, which is also what's causing your issue. You also have to pass these intents as a parameter, so the final thing would end up looking something like this:
# Configure intents (1.5.0)
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix=your_prefix, guild_subscriptions=True, intents=intents)

Recursively getting body of email with Pyzmail module

I'm trying to create an app that needs to recursively check an email address for new emails and then do some other stuff; I'm having some problems with the getting the body of the emails, though. I'm using the pyzmail module alongside imapclient, and the Automate the Boring Stuff for guidance (with python 3.6). Here's my code:
mail = imapclient.IMAPClient('imap.gmail.com', ssl=True)
mail.login('email', 'password')
mail.select_folder('INBOX', readonly=False)
uid = mail.gmail_search('NC')
for i in uid:
message = mail.fetch(i, ['BODY[]'], 'FLAGS')
msg = pyzmail.PyzMessage.factory(message[i][b'BODY[]'])
msg.html_part.get_payload().decode(msg.text_part.charset)
But it's not working. I've basically tried different forms of this code but to no avail and there's really not that many examples that can help me along. I'm a bit of a python newbie. Can anybody help?
Thanks,
EDIT
I realized where I made a mistake and fixed a bit of the code:
server = imapclient.IMAPClient('imap.gmail.com', ssl=True)
server.login('p.imagery.serv#gmail.com', 'rabbitrun88ve')
server.select_folder('INBOX', readonly=True)
uids = server.gmail_search('NC')
for i in uids:
messages = server.fetch(i, ['BODY[]'])
msg = pyzmail.PyzMessage.factory(messages[b'BODY[]'])
The problem I'm having is with the last line, which I dont know how to fed using the variables that is created with the iterator. It throws out this message:
ValueError: input must be a string a bytes, a file or a Message
I'm not sure if you still have this problem but for those who might have similar issues in future.
I noticed a little omission in the last line which might be the culprit.
msg = pyzmail.PyzMessage.factory(messages[b'BODY[]'])
You omitted the 'i' variable of the for loop
msg = pyzmail.PyzMessage.factory(messages[i][b'BODY[]'])
I'd like to do next to get body text of searched messages:
server = imapclient.IMAPClient('imap.gmail.com', ssl=True)
server.login('p.imagery.serv#gmail.com', 'rabbitrun88ve')
server.select_folder('INBOX', readonly=True)
uids = server.gmail_search('NC')
rawmessage = server.fetch(uids, ['BODY[]'])
for i in rawmessage:
msg = pyzmail.PyzMessage.factory(rawmessage[i][b'BODY[]'])
msg.html_part.get_payload().decode(msg.text_part.charset)
In this case, you get iteration over fetched emails with body text. I checked similar example but I used text_part.get_payload() instead html regarding features of my server.

Odd behaviour of insertNewObjectForEntityForName leading to NSInternalInconsistencyException

I have a rather odd case of getting a core data error whilst experimenting with Swift. I am not sure whether it comes from Swift (beta error?) or whether it is me. However, here is the setup for my test cases (in VTModelTests.swift).
var bundle = NSBundle(forClass: VTModelTests.self)
var url = bundle.URLForResource("VTDocument", withExtension:"momd")
appleModel = NSManagedObjectModel(contentsOfURL: url)
assert (appleModel != nil)
var coord = NSPersistentStoreCoordinator(managedObjectModel: appleModel);
var store = coord.addPersistentStoreWithType(NSInMemoryStoreType,configuration:nil,URL:nil,options:nil,error:nil);
assert (store != nil)
ctx = NSManagedObjectContext();
ctx!.persistentStoreCoordinator=coord
ctx!.retainsRegisteredObjects=true;
var drwName = "Drawing"
var descs = ctx!.persistentStoreCoordinator.managedObjectModel.entitiesByName
for e : AnyObject in descs.allKeys{
assert (descs.objectForKey(e).name == e as String )
if (e as String == drwName) {
NSLog("yeah")
}
}
model = NSEntityDescription.insertNewObjectForEntityForName(drwName,inManagedObjectContext: ctx) as Drawing
My error message looks like this:
2014-06-22 22:12:25.584 xctest[63792:303] yeah
<unknown>:0: error: -[_TtC12VTModelTests12BaseTypeTest testTreeStructure] : failed: caught "NSInternalInconsistencyException", "+entityForName: could not locate an entity named 'Drawing' in this model."
In short, I can "prove" that the entity name is there (the 'yeah' in the log), but core data is showing the issue that the name would not be in the model. Previous versions of the loop printed out the entities and that looked good. I don't have any second versions, and a new changed name ('Model' is now called 'Drawing') is correctly shown in the model data when all entities are printed. The compiled model is in the resulting bundle.
Can anybody explain? Or do I have to wait for the next beta release of Xcode 6? What else did I overlook? Many thanks in advance!
I can confirm the issue. Not an answer but the way around I use is to split insertNewObjectForEntityForName into:
let entity = NSEntityDescription.entityForName("Photo", inManagedObjectContext:context)
let photo = Photo(entity:entity, insertIntoManagedObjectContext:context)

Resources