« first day (3412 days earlier)      last day (1535 days later) » 

4:00 PM
Is there an efficient way to flatten several dicts into one? For set I can reduce with | but I can't think of something similar for dict.
 
the server makes it in the way that when no appropriate file was uploaded, it will refresh the page
 
Have you verified that result.png has not been saved anywhere in your system? It might not be where you expect.
 
@MisterMiyagi {**d1, **d2} not working?
 
I don't know offhand what Flask uses as its current working directory. print(os.getcwd()) might help there.
 
the server didnt start at all, so result.png did not save
 
4:04 PM
@paul23 it's an arbitrary number of dicts
 
I'm not sure not able to test atm but theoretically: {**(*list_of_dicts)}
 
Neo
Hi guys, I have a question. I have an API that can return any # of results and I am having hard time figuring out how do I know how many results it returned inside a dict.
The result/output from API looks like this:
{'results': [{'RemoteSW': 'Swi_1', 'RemoteIP': '10.10.10.1', 'RemotePort': 'Fa0/1', 'RemotePlatform': 'cisco 4560'},
	     {'RemoteSW': 'Swi_2', 'RemoteIP': '10.10.20.1', 'RemotePort': 'Fa0/2', 'RemotePlatform': 'cisco 4560'},
	     {'RemoteSW': 'Swi_3', 'RemoteIP': '10.10.30.1', 'RemotePort': 'Fa0/3', 'RemotePlatform': 'cisco 4560'}]}
 
@paul23 nope, can't do ** unpack in a dict comprehension or * unpack to a dict literal.
 
@Neo try number_of_results = len(the_dict["results"])
 
Neo
I tried len, json.loads, dumps but can't get it to work
 
4:10 PM
@MisterMiyagi I'd use collections.ChainMap, it doesn't actually flatten, but it'd give the same output.
 
Neo
print (len(cdp_query['results']))
I tried that .. I says 1
 
Strange, that's not what it prints on my machine.
>>> cdp_query = {'results': [{'RemoteSW': 'Swi_1', 'RemoteIP': '10.10.10.1', 'RemotePort': 'Fa0/1', 'RemotePlatform': 'cisco 4560'},
...      {'RemoteSW': 'Swi_2', 'RemoteIP': '10.10.20.1', 'RemotePort': 'Fa0/2', 'RemotePlatform': 'cisco 4560'},
...      {'RemoteSW': 'Swi_3', 'RemoteIP': '10.10.30.1', 'RemotePort': 'Fa0/3', 'RemotePlatform': 'cisco 4560'}]}
>>> print (len(cdp_query['results']))
3
 
Neo
let me try again, sorry
 
@Peilonrayz Interesting, that should solve the X to my Y.
 
Neo
Ok, now its working .. I swear it was saying 1 before :)
 
4:13 PM
Ah, the old "code mysteriously starts working after I make a public proclamation that it doesn't work". My old foe.
 
Neo
lol
What is the best way to storing and keeping all 3 results into separate
probably create an obj
 
That happens so often to me that I've integerated it into my workflow - I'll describe a bug to someone, fully expecting it to vanish forever when I try to demonstrate it
 
Neo
hehe .. modern problems require modern solutions
I am using flask and need to send this data back to an API call
 
@Neo If you know with complete certainty that there will always be exactly three results, you can do a,b,c = cdp_query['results']. If you don't know how many results there will be, you should not be trying to make separate variables for each one. Simply store all three of them in one data structure. You could put them in a list... Or just keep them in the dict the way they are now.
 
Neo
It can be 1 - >100 based on which switch I query
 
4:16 PM
@MisterMiyagi If you need it to flatten, you can just pass it to dict; dict(ChainMap()).
 
99.999999% of the time, "dynamically created variables" is a bad idea
 
Neo
flask wont let me return dict .. I believe it works with str, JSON / Obj
I dont think dynamic will work too
 
dicts can (usually) be converted to JSON quite easily, so that's not a problem
 
Neo
I can only return 1 var
 
return json.dumps(the_dict), job's done
 
4:17 PM
@Peilonrayz I'm fine with the actual flattening happening lazily, so collecting them in a ChainMap actually works pretty well.
 
I thought flask had a return_json or similar that did that and set the response header accordingly
 
Neo
yea, that should work. I will have to later figure out how AngularJS will know how many results are in that JSON and try to extract related data
 
Presumably JS has something equivalent to len()
 
Neo
yea, there should be a way. I will deal with that later
thanks as usual :)
or I can do something like count = len(cdp_query['results']))
and push that into json and have JS read count
 
>>> cdp_query = {'results': [{'RemoteSW': 'Swi_1', 'RemoteIP': '10.10.10.1', 'RemotePort': 'Fa0/1', 'RemotePlatform': 'cisco 4560'},
         {'RemoteSW': 'Swi_2', 'RemoteIP': '10.10.20.1', 'RemotePort': 'Fa0/2', 'RemotePlatform': 'cisco 4560'},
         {'RemoteSW': 'Swi_3', 'RemoteIP': '10.10.30.1', 'RemotePort': 'Fa0/3', 'RemotePlatform': 'cisco 4560'}]}
<- Object { results: (3) […] }

>>> cdp_query["results"].length
<- 3
 
Neo
4:21 PM
awesome
 
Exercise left to the reader: ensuring that the data passed to JS is an actual Object and not a JSON-looking string
 
Well, also, depends... if you're always going to return one huge lump of all data... normally you might also include meta data about the response that not only includes the "results" but also metadata about how many there are in total/whether there's a not chunk of results to request etc...
 
@Neo IIUC you want return jsonify
 
@roganjosh that's the one I was thinking of :)
 
Neo
I will give it a try
 
4:23 PM
anyway... rbrb for a bit... got all my emails/jobs done for the day done so far, so going to have a bite to eat and see if last night's Inside No. 9 was any good
 
@MisterMiyagi dict(itertools.chain.from_iterable(map(operator.methodcaller('items'), list_of_dicts)))? :P
 
now that's a beauty!
 
Hmm, disappointing that assexps on their own aren't enough to replicate the functionality of reduce within a comprehension. You still have to specify the default value on another line. For example, if you wanted to get the sum of a sequence, you could do [a := a+item for item in seq], but only if a is already bound to zero
Zero points to anyone that suggests (a:=0) or [a := a+item for item in seq]
[a := item + (0 if idx == 0 else a) for idx, item in enumerate(seq)], perhaps
Iterating over anything but the bare seq isn't as fun though
>>> dicts = [{"a": 1}, {"a": 2, "b": 3}, {"c": 4}]
>>> [c:={**(c if idx > 0 else {}), **d} for idx, d in enumerate(dicts)][-1]
{'a': 2, 'b': 3, 'c': 4}
 
4:42 PM
>:|
 
I think you mean 😍, just look at how much pythonicness I jammed in there
List comps! Negative indices! Double asterisks that nobody can google the name of!
 
Asspressions!
 
Neo
I am not even decent with python but that line gave me chills
 
Chills of joy surely
(disclaimer: please do not actually do this or anything like it)
 
Neo
confusion mostly
 
4:47 PM
In the absence of a default initial value, reduce takes the first element of the sequence. If only sum() did the same - I suspect the main reason sum() inits with 0 is to make it difficult to do sum(list_of_lists) or sum(list_of_strs).
 
I think that's a big part of it. I wonder if performance is a concern at all. What's faster - having to do an additional integer add, or starting the function with if len(seq) == 0: return 0?
 
It seems unclean to junk up sum's signature with this kind of micromanaging
sum(list_of_ParseResults) works because ParseResults implements __radd__ and if added to 0, just returns self. My practicality beats your sum-should-only-sum-numerics purity.
 
Neo
another stupid question
print (results)   	#Returns: {'results': []}
print (type(results)) 	#Returns: <class 'str'>

if not results:
    print ('No Result')
else:
    print ('Results Found')
Any clean way of checking for empty results
other than saying something like
if "'results: []'" in results
 
Where did you concoct results from in the first place?
 
I wouldn't mind living in the alternate universe where sum() takes any type of argument... As long as sum(["a", "sequence of", "strings"]) delegates out to "".join
 
Neo
4:53 PM
It is scoming straight from 3rd party API
coming*
 
I can't be bothered to campaign to actually change things, though
@Neo, not 100% sure I understand the question, but try if not results["results"]:
Or, hang on, results isn't a dict
 
Ah, so you have an API that is returning JSON? Then do results_dict = json.loads(results), and then evaluate results_dict['results']
 
Agreed
99% of the time, the first thing you should do with JSON data is convert it into a usable data structure. Trying to work with it while it's still a string is rarely worthwhile
 
Neo
so I am converting it to JSOn and then evaluating
lemme try
 
You might already know this, but terminology clarification: {'results': []} is a dict. "{'results': []}" is a string. Python does not have a type called "JSON".
 
Neo
4:58 PM
TypeError: the JSON object must be str, bytes or bytearray, not 'dict'
 
I see a lot of users get hung up on trying to manipulate "a JSON", even though they already know how to manipulate dicts, lists, and strings. So this is worth repeating
 
cbg all
 
@Neo Strange. If you're calling json.loads(results), and results is a string, then you shouldn't get that error. Something strange is going on. I'm interested in investigating further if you can provide an MCVE.
 
Neo
results = sqlClient.query("QUERY")
result = json.loads(results)

if not result['results']:
    print ('No Results')

else:
    print ('Result Found)
 
:) Ah, JSON. It gives me an unnatural amount of pleasure to query this api and get the location of the ISS: curl -s http://api.open-notify.org/iss-now.json | jq
 
That code doesn't give me TypeError, it gives me SyntaxError: EOL while scanning string literal. A good MCVE produces exactly the same error that you're seeing in your real code. Take your time, I'll be here all day.
 
Hmm is it possible to "emulate" the non-strict behaviour of Path.resolve (docs.python.org/3/library/pathlib.html#pathlib.Path.resolve) in python 3.5?
 
If all else fails, you could copy-paste the current implementation of resolve, and any related methods it depends on, into your code
"any related methods it depends on" may or may not be the entire pathlib module
 
@Neo this is getting more confusing. What is sqlClient and why is it returning json? It looks like it's already doing the deserialization for you but we can't see how or why
 
Neo
I think it is complaining when I try json.loads on an empty var
 
5:14 PM
oh actually reading the implementation that's kind of "silly": it just encapsulates the internal function by catching the error, removing the leaf and then trying again.
 
@Neo no, the error does not suggest such a situation. It's saying you're trying to load a python object as though it was a json string
 
"I can do that too"
 
Oh how I thirst for an mcve
 
@Dodge as I understand maybe (but I'm not an expert). It seems more like that they've discovered this new phenomenon, and now that they know it exists they can start proactively looking for it.
 
I just experienced how demotivating programming can be... I'm spending almost a full day to get a working code base (for python 3.6) to work on python 3.5 hunting all places where differences are.
 
5:18 PM
@AndrasDeak Coincidentally, that topic came up a couple of days ago on Physics: physics.stackexchange.com/q/531559/123208
 
no answers in a day; suspicious!
 
hi
anyone has experience with OpenAI Gym?
 
@AndrasDeak That happens a fair bit on Physics. But if we're lucky one of the astrophysicists who know about that stuff might see it & answer it.
 
@Neo Please reconcile this with your earlier comment where type(results) was a str.
 
@PM2Ring There's probably a very short and a very long answer there... "it does, but it's not that noticable" through to "it does, manifesting in abc small but verifiable observations, and it is dissipated through xyz".
 
Neo
5:24 PM
import json

results = {'results': []}
result = json.loads(results)
print (result)
if not result['results']:
    print ('No Results')

else:
    print ('Result Found')
 
@Neo - should be results = "{'results': []}"
You are getting results as a str, not a dict.
When printing out vars, sometimes it is confusing whether you are looking at a str, or the str representation of some other kind of thing. Instead of print(results), try print(repr(results)). If results is a str, it will print with surrounding quote marks.
 
His previous code had print (type(results)) #Returns: <class 'str'>, so I'm confused how this kind of type confusion could come about
 
Because he did print(results) and then just copy/pasted that into his recent test example, without the surrounding quote marks
 
@toonarmycaptain Well, the Van Allen belts are caused by the interaction between the solar wind and the Earth's magnetic field, so my guess is that any dynamo effect will end up as kinetic energy of the plasma in the Van Allen belts, and I guess it may also have some effect on the auroras.
 
{'results': []} and "{'results': []}" look the same when you print them, but the first is a dict, the second is a str. Which is why I suggest to use print(repr(whatever)) when trying to debug, so that the output will show whether whatever is a str or not.
 
5:30 PM
@PM2Ring But not enough to detect in an EM sense down here on earth, to the degree that we could capture such effects to power a cell phone, or am I presuming a lot? It sounds like the question is inspired by the idea of generating electrical power from the phenomenon.
 
... not detecting any glimmer of understanding. @Neo, are you any closer to seeing what is going on here?
 
@toonarmycaptain There's a fair amount of energy in the Earth's electromagnetic field, but it's not easy to harvest it. Although there's stuff like this: en.wikipedia.org/wiki/Electrodynamic_tether
 
5:47 PM
Me: Maybe today is the day I finally learn how magnets work.
Wikipedia: the magnetic flux through a surface is the surface integral of the normal component of the magnetic field flux density B passing through that surface.
Me: ... Maybe today is not the day.
 
relatable :P
Except it probably happens with a lot more things in my case compared to yours.
 
You've been listening to Feynman Kevin?
 
I want to say "the sun's magnetic field is, more or less, rotationally symmetrical, so moving a magnet in a circle on the ecliptic won't do anything" but I'm pretty sure that line of reasoning would also disprove the existence of electrical engines, so.
 
Hi everyone
 
5:51 PM
None of the comments on the Physics.SE question say "fool, the electrical current is zero, derived by simple application of Steve's Law" so I'm guessing I'm oversimplifying
 
be prepared to understand less about trivial things like ice though.
 
@PM2Ring I'd imagine a satellite orbiting in the right direction relative to the EM field might be able to generate something, but not so much down on the ground.
 
I need your expertise to know why the user that created when flask app is running (through register form) is not exist when flask app restart
 
@Kevin Steve's Law states that "Working on live wiring keeps things interesting," but maybe that's only one my family is aware of?
 
@Kevin what about orbital excentricity, though. We're not orbiting in a perfect circle
 
5:56 PM
@SalmanMushtaq is there any part of the code responsible for storing and reading in state from previous runs?
 
@SalmanMushtaq I'm going to need a bit more information please
 
@Kevin If something is "more or less X", and you observe something conflicting with X, it's less X than you thought.
 
@roganjosh True. Having an elliptical orbit, or periodically moving above/below the ecliptic plane, would change the potential magnetic energy* of the orbiting object over time
(*a term I just made up)
 
My first guess is that you didn't do db.session.commit() (if using flask-sqlalchemy)
@Kevin I just wanted to feel like I had a decent point to make :P i have nothing to follow up with so I'm happy to leave it with speculation beyond that :)
 
Once It close use db.session.ŕemove instead
 
6:02 PM
I was going to say "surely the stellar magnetic field is pretty regular, at least to a precision our instruments can measure", but the video at en.wikipedia.org/wiki/Stellar_magnetic_field looks like one of those cool lightning balls you can buy at Spencer's, so I guess not.
Sharks The stellar magnetic field is smooth as heck, I'm feeling it right now. Smooth in all directions.
 
@Kevin magnetic fields are one of the most complicated things in stars lol
 
@SalmanMushtaq that's the opposite of their (implied) expected output
 
Sunspots caused by magnetic field fluctuations aren't real, I look at the sun every day and it's all completely homogeneous
Plasma is well-known for being very orderly
 
Actually I get the python app from net to learn. Now once I run flask run --host=0.0.0.0 --port=80 and open create_user and login. Work fine. But when I hit ctrl+c and restart the app i need to create user again
 
I imagine the solar magnetic field gets pretty orderly far enough where things no longer die due to its radiation
 
6:04 PM
@SalmanMushtaq I understand that. I gave a suggested issue. Do you commit the user to the database? Do you even have a database?
 
@SalmanMushtaq 1) do you know how to program? 2) do you know how to program in python?
 
I try to understand the code and guess it used sqlalchamy and table User , but I dont know where to save the data permanently
Yes I know basic
 
basic is a pretty old language ;)
 
Wait, now I'm super confused. I'm talking to you as two people because names are mini on my phone and db.session.remove seemed completely at odds with what you're trying to do
 
@Kevin haven't played much recently... but was looking to get some MTG Arena in at the weekend... got 7 mythic rare and 12 rare wildcards I can use to help build a deck... any ideas of what's good these days?
 
6:06 PM
Programming I know, but in python I am new
 
@AndrasDeak There are flares which could supposedly knock out electronics in an orbit around earth
so depending your scale (time and distance) it's not really smooth
 
well, yeah, but those are isolated and transient events
and probably more EM than M
(but I don't know anything about this physics)
 
I need to create a user i.e. admin so my user always use this account. Its on rasbary board.
 
Please don't just re-state the problem @SalmanMushtaq. Twice now I've asked if you commit() the changes
 
Small flares we have observed "burst" from magnetic line changes though. (Large flares that could reach earth we have only in theory/historical data, it's supposed to happen once very 100ish years).
 
6:09 PM
@AndrasDeak Pretty sure an otherwise functional spacesuit that provided no radiation shielding would be deady, if not in LEO, than on the moon, so I presume far enough doesn't include anywhere near as close as Earth?
 
Ok, From where I commit the changings?
 
@toonarmycaptain yeah, I just meant "where planets don't boil"
 
@SalmanMushtaq after you create the new User object. Presumably you have db.session.add(user)?
 
@AndrasDeak Oh, lol, 'things' here meaning planets.
 
Yes in routes.py after I have user db.session.add(user) changings ate commit db.session.commit()
And it works until the flask app is running.
 
6:14 PM
No, don't change it
You need to add db.session.commit() after adding the user to the session
 
@roganjosh i did not change this code. But other than this where I need to commit
 
The alt-text on that one is excellent.
 
12 messages moved to mtg
 
6:17 PM
@SalmanMushtaq please go back through my last messages. For the sake of not pinging you on every message, you can be assured that I am addressing you alone on this issue
 
./curious what's mtg
 
magic: the gathering
 
@roganjosh thanks for your support dear. When the user is created I put the code to commit, db.session.commit() , but still the behavior is same.
 
What database are you using?
 
Sqlite3
 
6:19 PM
If it's an in-memory sqlite database then we can't fix this, so we need to look at that now to rule it out
Huh, prescience +5 is helping. So please show me how you connect
 
In code also used sqlalchemy to handle the sqlite3 i guess
 
I would like to see the specific line of code where you connect to sqlite
 
i see, nifty
 
Db = SQLAlchemy() then is configure_database(app) db.create_all()
 
Neo
sorry to all who were helping me with the issue. My laptop went to sleep and wont wake up
I believe it is working now per your suggestion .. I will test more .. thanks!
 
6:25 PM
That isnt where you actually connect to the db. It's likely to be in your config.py file. We need to see the actual database. I'm on a phone so I cant draw on my own code and it takes time for me to look things up to link back. This is getting pretty difficult; you're going to struggle here without learning some basics of SQL itself
 
Let me look for config.py, can you help me with directory
 
Thanks for the update @Neo. Too often people just drop off in mid-session while we are helping them, and our only recourse is to think less of them. Just remember, when you print something, the output you get is not necessarily the full story.
 
SQLALCHEMY_DATABASE_URI from this
 
from where I get the code they shows
Session-Based authentication (via flask_login) ~ now I am not confirm there is DB or not
 
Neo
@PaulMcG, so the best way to check actual type is 'print(repr(whatever)) ' right?
 
6:29 PM
Ok, I'm giving up sorry. We'll be here all day at this rate. You need a foundational understanding of the tools you're using here before we can meaningfully move forward
 
I get the file
# -*- encoding: utf-8 -*-
"""
License: MIT
Copyright (c) 2019 - present AppSeed.us
"""

from os import environ

class Config(object):
SECRET_KEY = 'key'
SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'
SQLALCHEMY_TRACK_MODIFICATIONS = False

# THEME SUPPORT
# if set then url_for('static', filename='', theme='')
# will add the theme name to the static URL:
# /static/<DEFAULT_THEME>/filename
# DEFAULT_THEME = "themes/dark"
DEFAULT_THEME = None


class ProductionConfig(Config):
DEBUG = False

# Security
 
Right. So the answer is right there
 
 SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'
 
SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'. It's as I expected; it's an in-memory database
As soon as you shut the app down, that database is just lost
 
So its in-memory, can you suggest what I need to used, please.
In down there is also some code for PostgreSQL

# PostgreSQL database
SQLALCHEMY_DATABASE_URI = 'postgresql://{}:{}@{}:{}/{}'.format(
environ.get('APPSEED_DATABASE_USER', 'appseed'),
environ.get('APPSEED_DATABASE_PASSWORD', 'appseed'),
environ.get('APPSEED_DATABASE_HOST', 'db'),
environ.get('APPSEED_DATABASE_PORT', 5432),
environ.get('APPSEED_DATABASE_NAME', 'appseed')
)
 
6:33 PM
Change to `SQLALCHEMY_DATABASE_URI = 'sqlite:///app.db'
 
wim
nice password
 
@roganjosh okay, then next/
 
Ok, I'm just gonna pretend that postgres connection string doesn't exist. That should be enough of a change to get your development version of the app to work
 
Ok great, so I only need to change DQLALCHEMY_DATABASE_URI = 'sqlite:///app.db' ?
 
@Neo That, plus this statement that you did before print(type(whatever))
 
6:37 PM
Yes. That will persist data to an actual file
 
That's how we all know you were working with a str, not a dict
@Neo - good luck!
 
wim
I have to award bounty here but can not choose the best answer, help?
 
okay thanks, just one question, I need to create this app.db some where?
 
It will be created at the root directory of your application. Just start your app and you'll see the file appear. If you dont want it there, then modify that URI to add a relative path and restart. I dont wanna go through trying to figure out the app structure, it'll be easier for you to just try it and see
 
Thanks a lot @roganjosh, let me try and will update you
 
6:52 PM
Is it appropriate to ask questions about documentation?
 
ok I'm officially annoyed... Anyone experience with synology?
On synocommunity the newest version of python is 3.5.6 - anyone knows how to get newer version running?
 
@Pandasncode python docs? go ahead.
 
Neo
@PaulMcG, cool, thanks!
 
7:11 PM
@roganjosh yes it works fine, thank you very much dear. God bless you with a lot of happiness. Thanks again
 
rb folks
 
WOOT!
 
Just kind of happened without me noticing - it was only @JonClements' post of i.stack.imgur.com/eSWj8.png that made me look!
 
58 bronze badges... congrats! coughs :p
 
7:16 PM
No idea whether that's good or bad!
 
20K, very nice!
 
@holdenweb it means people appreciate your efforts
 
It's always nice to be appreciated.
 
(or they did anyway but just because they didn't have an account or not enough rep. to do so)
 
hmm does docker forward the main application's exit code when exiting?
 
7:19 PM
@holdenweb so, I guess in SO terms, welcome to be able to cast a delete vote more quickly than you could or something? :p
 
@paul23 medium.com/better-programming/… implies not., since docker has exit codes of its own.
 
afraid so :(
 
@JonClements I'll probably never find out about some of the privs.
 
meh... gave some of the most useful ones I've had up anyway... wouldn't worry about it
you still down in B?
 
quick question, what is this time called? 34309403943
merely a long integer
and how do i convert a datetime to that long integer?
 
7:24 PM
@JoeSaad timestamp, probably
 
Do you know what " 34309403943" is supposed to represent?
 
yes timestamp
but how do i convert in python to this timestamp for now for example
 
datetime.datetime.now().timestamp()
Surprisingly
 
Isn't 34309403943 like a thousand years in the future, though
The current timestamp is 1582053922 and that's one less digit
 
errr no... what I meant was.... you presumably know what "34309403943" should be?
 
7:27 PM
@Kevin yeah, 3057
 
then you've also got Excel for instance that offsets timestamps from either 1900/1901 and the unix timestamp of 1970 etc...
 
If the explanation turns out to be "oh, 34309403943 doesn't correspond to any particular date. I just mashed the keypad until I had something that looked timestampy", my jimmies will enter over-rustle
 
so the only way to answer this @JoeSaad is what is 34309403943
 
@Kevin you're in for a treat I think :D
 
Producing sample data by keymashing is a time honored tradition, but that kind of information should be in the first message
 
7:30 PM
Or the answer is "that time is called the century of the fruit bat"
 
mlekmlefmnleenefn
who's to break tradition... didn't seem to get numbers though
 
M and L are valid roman numerals, but then you went a bit off the rail there
 
apparently they didn't even use M - they used a little squiggly thingy in a circle
(according to QI anyway or something)
 
@JonClements Theta?
 
I'm worried that Joe is reluctant to say "yes, it's a keymash" out of concern for my jimmies. Don't worry about me, Joe. My jimmies are extremely pliant.
 
7:38 PM
But who wants to get a reputation for being a jimmy-russler (or is that jimmy-rustler)?
 
@PaulMcG rhetorical I hope?
 
Just trying to be sympathetic
 
understood
 
I'd go with "rustler" I think
 
@SalmanMushtaq Was driving home sorry. You're welcome, glad it's working. Before continuing with an ORM I think it would be worth taking a step back and getting some base understanding of SQLite otherwise you will find the code base quite confusing
 
8:03 PM
@JonClements H(astings)
 
@holdenweb brain burp... wrong southern one... I knew it was (B) or (H) - I was trying to be discreet
 
Neo
I am back :) .. Any reason I am not able to merge two dict?
host = {'results': [{'RemoteSW': 'Swi_1', 'RemoteIP': '10.10.10.1', 'RemotePort': 'Fa0/1', 'RemotePlatform': 'cisco 4560'},
	     {'RemoteSW': 'Swi_2', 'RemoteIP': '10.10.20.1', 'RemotePort': 'Fa0/2', 'RemotePlatform': 'cisco 4560'},
	     {'RemoteSW': 'Swi_3', 'RemoteIP': '10.10.30.1', 'RemotePort': 'Fa0/3', 'RemotePlatform': 'cisco 4560'}]}

cdp = {'results': [{'CDPSW': 'cdp_1', 'CDPIP': '10.10.101.1', 'CDPPort': 'Fa1/1', 'CDPPlatform': 'CDP', 'Type': '4k'},
	     	   {'CDPSW': 'cdp_2', 'CDPIP': '10.10.102.1', 'CDPPort': 'Fa2/2', 'CDPPlatform': 'CDP', 'Type': '2k'}]}
 
Shouldn't worry - even assassins don't get to Hastings muxh.
 
.update is effectively a "shallow" merge, it completely overwrites one results list with the other
If you know with complete certainty that both dicts have exactly one key, "results", whose value is always a list, perhaps you could do results["results"].extend(cdp["results"])
 
Neo
hmmm .. thats what I been finding people suggesting to do
 
8:07 PM
Only semi-relatedly, print (cdp.update(host)) prints None because the return value of update is always None. If you want to print the contents of cdp after calling update on it, you have to do print(cdp)
 
@Neo What are you actually looking for: a dict with a "results" key that merges the lists represented by same key from both dicts?
 
It may or may not make sense to "strip" your data by one layer, and remove the dict part entirely, and only store the underlying list. If "results" is the only key you ever expect to have, it's basically pointless
 
@holdenweb don't ruin my job these days :)
 
@Neo, also check out the pprint module. pprint.pprint() is very nice for listing out dicts, lists, lists of dicts. pprint.pprint(vars(obj)) is good for listing out the attributes of an object.
 
It's clearly causing some conceptual confusion here. You're looking up how to merge dicts when really what you want to do is merge lists.
 
8:10 PM
@JonClements Sorry, that went right over my head.
 
Neo
host_result = json.dumps(list(host.values()))
something like this?
convert to list and then merge?
 
No.
 
@Neo Perhaps you could say a) what keys would you expect to result from merging host and cdp, and b) what values would they have?
 
Forget I said anything. The purpose of my suggestion is to make things less confusing. If you're adding an extra three layers of dumps() and list() and values(), then that defeats the purpose
Just keep doing what you're doing if it works for you
 
[I quite liked vaules]
 
Neo
8:13 PM
all keys are unique so all data will be preserved
 
(I low-key anticipate a "this is what I want: <syntax error>")
 
Neo
if thats what you are asing @holdenweb
 
@Kevin You are getting old and cynical!
 
Bugrit
 
Neo
this works but it is ugly
host_result = json.dumps(list(host.values()))
cdp_result = json.dumps(list(cdp.values()))

print (host_result + cdp_result)
 
8:15 PM
@Neo No, I mean write out what you expect the interpreter would print as the merged result. Tell us explicitly what you want.
 
I feel like my results["results"].extend(cdp["results"]) suggestion went unnoticed, so here I am posting it again
 
@holdenweb poor humour about an assassin when knowing where you live blah blah
 
Neo
{'results': [{'RemoteSW': 'Swi_1', 'RemoteIP': '10.10.10.1', 'RemotePort': 'Fa0/1', 'RemotePlatform': 'cisco 4560'},
{'RemoteSW': 'Swi_2', 'RemoteIP': '10.10.20.1', 'RemotePort': 'Fa0/2', 'RemotePlatform': 'cisco 4560'},
{'RemoteSW': 'Swi_3', 'RemoteIP': '10.10.30.1', 'RemotePort': 'Fa0/3', 'RemotePlatform': 'cisco 4560'},
{'CDPSW': 'cdp_1', 'CDPIP': '10.10.101.1', 'CDPPort': 'Fa1/1', 'CDPPlatform': 'CDP', 'Type': '4k'},
{'CDPSW': 'cdp_2', 'CDPIP': '10.10.102.1', 'CDPPort': 'Fa2/2', 'CDPPlatform': 'CDP', 'Type': '2k'}]}
this would be he idea end dict
@Kevin, I had it in notepad and need to test
be assured, anything you say will never get un noticed :)
where did results come from kevin?
 
From your code: results = host.copy()
 
Neo
oh ok, so I still copy
 
8:19 PM
I actually suspect that copy is useless here since the mutation we're doing is more than one level deep, but it doesn't really matter if you don't want to preserve the state of the original data structures
 
Neo
host["results"].extend(cdp["results"])
I get None
print (host["results"].extend(cdp["results"]))
 
If you did print(host["results"].extend(cdp["results"])), that's exactly what you should get, because the return value of extend is always None.
Rule of thumb: the return value of a mutating function is typically None. If you want to see the result of the operation, print the object directly
i.e. print(host)
 
Neo
host['results'].extend(cdp['results'])
print (host)
like this?
 
8:23 PM
@Neo Side note: don't put a space between function names and their arguments in a function call, it looks weird. This isn't a syntax problem, just a style problem.
 
Neo
ok will do
Awesome
that did it!
thanks!
 
If you had asked me, I would have said it was. I learned something.
Somewhere, somehow, that is a hard to find bug where the person expects a tuple single argument, and gets two arguments.
 
well if they use ancient python...
 
eh? I don't follow. How could (host) be two arguments?
 
I think they meant in general
 
Oh, I thought the suggestion was that some old version of python would actually have seen (host) as a tuple
 
8:55 PM
> where the person expects a tuple single argument, and gets two arguments.
OK, I guess that isn't conclusive as a response to your message, depends on how you read it
 
Ok, so the "ancient" version would have been print (host,) in Python 2? So it's lacking the comma, but at least I wasn't going mad that the brackets themselves were once enough to create a single-item tuple
Or, maybe they were. That's not actually been settled :P
 
think print ('this', 'that') expecting to print a 2-tuple, and seeing 'this that' being printed instead
 
@roganjosh print (1, 2) expected to be print((1,2)) or in 2.x: print (1,2)
 
Ah, ok. I was looking at it from the wrong angle
 

« first day (3412 days earlier)      last day (1535 days later) »