sub
stringclasses
1 value
title
stringlengths
7
303
selftext
stringlengths
0
8.65k
upvote_ratio
float64
0.08
1
id
stringlengths
9
9
created_utc
float64
1.65B
1.65B
Python
CLI macro for Windows
Hey everyone, I built a cli program for windows that can open files,websites, create temporary python enviroments. This is kind of my first full scale project that really eases my workflow.I would love to get suggestions on this program. :) [https://github.com/Sidharth-S/do](https://github.com/Sidharth-S/do)
0.7
t3_u51ud3
1,650,127,715
Python
Python Virtual Environments: A Primer
0.96
t3_u51l5b
1,650,126,979
Python
A lightweight way to profile Python Code non-intrusively
Latency: [https://github.com/oracle-samples/hiq/blob/henry\_dev/hiq/examples/paddle/demo.ipynb](https://github.com/oracle-samples/hiq/blob/henry_dev/hiq/examples/paddle/demo.ipynb) Memory: [https://github.com/oracle-samples/hiq/blob/main/hiq/examples/paddle/demo\_memory.ipynb](https://github.com/oracle-samples/hiq/blob/main/hiq/examples/paddle/demo_memory.ipynb) ​ [Latency Graph](https://preview.redd.it/qgc7upex3xt81.png?width=512&format=png&auto=webp&s=87a0a0cbf34e2ee4fd560d5c0768179ec5d95d76) ​ More details at: [https://github.com/oracle-samples/hiq](https://github.com/oracle-samples/hiq)
0.59
t3_u51h29
1,650,126,645
Python
How to make annoy any interviewer with the fizzbuzz challenge
I was bored so I decided to solve the fizzbuzz in an obnoxious way. Hope you enjoy (: `output = ["fizzbuzz", "buzz", "fizz"]` `iterList = lambda x: [x%i for i in [15, 5, 3]]` `fizzBuzz = [output[iterList(x).index(0)] if 0 in iterList(x) else x for x in range(1, 101)]` `print(fizzBuzz)` `[1, 2, 'fizz', 4, 'buzz', 'fizz', 7, 8, 'fizz', 'buzz', 11, 'fizz', 13, 14, 'fizzbuzz', 16, 17, 'fizz', 19, 'buzz', 'fizz', 22, 23, 'fizz', 'buzz', 26, 'fizz', 28, 29, 'fizzbuzz', 31, 32, 'fizz', 34, 'buzz', 'fizz', 37, 38, 'fizz', 'buzz', 41, 'fizz', 43, 44, 'fizzbuzz', 46, 47, 'fizz', 49, 'buzz', 'fizz', 52, 53, 'fizz', 'buzz', 56, 'fizz', 58, 59, 'fizzbuzz', 61, 62, 'fizz', 64, 'buzz', 'fizz', 67, 68, 'fizz', 'buzz', 71, 'fizz', 73, 74, 'fizzbuzz', 76, 77, 'fizz', 79, 'buzz', 'fizz', 82, 83, 'fizz', 'buzz', 86, 'fizz', 88, 89, 'fizzbuzz', 91, 92, 'fizz', 94, 'buzz', 'fizz', 97, 98, 'fizz', 'buzz']` Edit: yes I know the title is messed
0.64
t3_u4zs3s
1,650,121,763
Python
Live flame graph rendering in the terminal
Austin TUI 1.2.0 has just been released, with the new live flame graph mode. [https://github.com/P403n1x87/austin-tui](https://github.com/P403n1x87/austin-tui) This is what it looks like in VS Code. The graph can be paused and files opened directly in the editor with a Ctrl + Click on the path for further inspection. The VS Code extension is also available for more insight into performance [https://marketplace.visualstudio.com/items?itemName=p403n1x87.austin-vscode](https://marketplace.visualstudio.com/items?itemName=p403n1x87.austin-vscode) https://i.redd.it/5kh8pn811wt81.gif
0.72
t3_u4x741
1,650,113,643
Python
"Safe" way to install Python 3 on MBA M1
Hi. I just want to ask if there's something like a "safe" way to install Python 3 on Macbook Air m1. I'm learning Python right now, and MBA has Python 2.7 something version.
0.82
t3_u4uji2
1,650,103,050
Python
Recover deleted and overwritten files with RecoverPy 1.5.0
​ https://i.redd.it/qg7rwesb1vt81.gif Hi! I recently release RecoverPy v1.5.0 and I think I might give you some news. **-> Repo:** [https://github.com/PabloLec/RecoverPy](https://github.com/PabloLec/RecoverPy) # What is it? RecoverPy is a 100% Python tool to not only recover deleted but also overwritten files. I got the idea when I was quite new to some programming best practices, especially version control... Long story short, I accidentally piped my output into my precious script... Just spent the day working on something and instead of typing myscript > log, I typed log > myscript, oh boy what a feeling. I knew some tools to recover deleted files, but my problem was quite different, I didn't deleted the file (in system words, marked the file blocks as deleted/available), I just replaced it's content. Talk about an impostor syndrome. After a long ride in the abysses of unix stackexchange, I found some dark combination of grep and dd command to search directly in your raw system partitions blocks and eventually recovered my file! But as the process was really slow and painful, I thought it might be a good idea to make a tool out of it. That's how RecoverPy was born. # 1.5.0 Since then, the tool has had quite some success. Especially in the hacker community (wasn't the initial intent but still). It even appeared in hakin9 magazine. Last releases have been quite stable, lastly I mostly added QoL updates and better binary file search handling. Feel free to have a look and tell me what you think of it! It's my biggest personal project and I'm beginning to be quite proud of my baby :)
0.93
t3_u4u8mb
1,650,101,676
Python
Python Web Frameworks
0.29
t3_u4u85t
1,650,101,619
Python
Python for complete begginers Medium
I wrote this cool article about python for complete begginers about 2 months ago and I thought I'd share it. In this article you will learn about: 1) what coding is , what python is 2) The advantages of python 3) How to download and install python 4) What an ide is 5) Maths in python 6) Variables Here is the link : https://4rkal.medium.com/python-for-beginners-f1df170bcc08
0.33
t3_u4tsp2
1,650,099,636
Python
GitHub - AlexEidt/ASCII-Video: Blazing fast ASCII Image/Video Renderer.
0.95
t3_u4rpyc
1,650,090,494
Python
Run python (and sql) with dbt
0.84
t3_u4mwco
1,650,072,702
Python
Saturday Daily Thread: Resource Request and Sharing! Daily Thread
Found a neat resource related to Python over the past week? Looking for a resource to explain a certain topic? Use this thread to chat about and share Python resources!
0.79
t3_u4l9am
1,650,067,210
Python
i created my own music player in Python3
i always wanted an offline music player that was low on ram, and functioned properly, and for the love of god i could not find one so i created mine. i would be glad if you tested it, here's the github link: [https://github.com/AvivHamagniv69/music-player](https://github.com/AvivHamagniv69/music-player)
0.83
t3_u4l7re
1,650,067,079
Python
How to build a disease prediction service
0.86
t3_u4jf15
1,650,061,429
Python
TL;DR: Dictionary Comprehension + Early\Late Binding of Lambdas in Python is Mental
Hello, I found a behaviour I couldn't explain when using lambdas in a dictionary comprehension so I decided to post a little Intermediate Showcase to inform you about my struggles and give you a solution, in the end (no spoilers) I like to minify python code in my spare time to relax and it often takes some iterations for each different function or class, alongside those iterations I was golfing a function in a progress bar script I wrote a very long time ago, this is the brief description of what the function should have done: `The function has to take a list of n elements and color them green, yellow or red according to a given condition.` This was the last *functioning* function in the process of being golfed: def paint(total, done, elements): color_str = lambda x, y: f'{x}{y}\033[00m' colors = {'r' : lambda x: color_str('\033[91m',x), 'g' : lambda x: color_str('\033[92m',x), 'y': lambda x: color_str('\033[93m',x) }['g' if total == done else 'y' if total/2 <= done else 'r'] return [*map(colors,elements)] I thought, that's easy, this has to be equivalent to this golfed function: def paint(total, done, elements): return [*map({'rgy'[i]:lambda x:f'\033[9{i+1}m{x}\033[00m' for i in range(len('rgy')) }['g' if total == done else 'y' if done <= total/2 else 'r'],elements)] *Until it's not*, in fact, while the first function outputs a correct response, the last one is **somehow** stuck on the color yellow, so I thought the dictionary comprehension wasn't working properly and thus I tried: dict_comp = {'rgy'[i]:lambda x:f'\033[9{i+1}m{x}\033[00m' for i in range(len('rgy'))} print(dict_comp) This prompted what I thought it would prompt, a dictionary with `r`,`g` and `y` as keys and a list of lambdas in different memory locations `{'r': <function <dictcomp>.<lambda> at 0x0000018D3E986200>, 'g': <function <dictcomp>.<lambda> at 0x0000018D3E9860E0>, 'y': <function <dictcomp>.<lambda> at 0x0000018D3E986050>}` so I tried to print all the key and lambda pairs with a test for each lambda: for key, lmbd in dict_comp.items(): print(key, lmbd(f'Testing {key}')) This was the output: [Horrific Minion-Colored Results](https://preview.redd.it/o216rv5pjrt81.png?width=139&format=png&auto=webp&s=eb4882d1c3114792c06656ac59204a08f297a790) I decided to remove the slash to check the text value of the lambda and the correct progression of `i` and this why I noticed the problem: each lambda stored the last value of `i`! dict_comp = {'rgy'[i]:lambda x:f'033[9{i+1}m{x}\033[00m' for i in range(len('rgy'))} for key, lmbd in dict_comp.items(): print(key, lmbd(f'Testing {key}')) >> r 033[93mTesting r # the value after the square bracket is 93 (it's supposed to be 91) >> g 033[93mTesting g # the value after the square bracket is 93 (it's supposed to be 92) >> y 033[93mTesting y # the value after the square bracket is 93 Here's the whole code in order to try both functions: from time import sleep def paint(total, done, elements): color_str = lambda x, y: f'{x}{y}\033[00m' colors = {'r' : lambda x: color_str('\033[91m',x), 'g' : lambda x: color_str('\033[92m',x), 'y': lambda x: color_str('\033[93m',x) }['g' if total == done else 'y' if total/2 <= done else 'r'] return [*map(colors,elements)] # UNCOMMENT THIS IN ORDER TO TEST THE FUNCTION DOWN BELOW """ def paint(total, done, elements): return [*map({'rgy'[i]:lambda x:f'\033[9{i+1}m{x}\033[00m' for i in range(len('rgy')) }['g' if total == done else 'y' if done <= total/2 else 'r'],elements)] """ def CustomProgressBar(task, completeness) -> None: size = 100 // 5 empty = size - completeness//5 fill = size - empty percent = f'{completeness:>3}% ' filler = f'{"═"*fill}' isComplete = fill==size progress_bar, percent = paint(size,fill, [filler, percent]) progress_bar+=f'{"─"*empty}' print(f'\r{task:<25}{percent}{progress_bar}', end='\n' if isComplete else '') for i in range(101): sleep(0.05) CustomProgressBar('Range 0-100', i) I then asked myself: >Why does this happen? Isn't each anonymous function different? After some scavenger hunt in StackOverFlow (thanks you Stack for the duplicate question tootip) I found out that the issue might be in [late binding in functions and lambdas in particular](https://stackoverflow.com/questions/3431676/creating-functions-in-a-loop), so the answer, apparently, is that even if the functions are stored in a different memory location as part of the dictionary, the lambda function captures the ***NAME*** of the variable, not the ***VALUE*** of the variable and assigns the value after the dict comprehension is called, so each value becomes the last value in the loop, as the friendliest guy on StackOverFlow explains [here](https://stackoverflow.com/questions/70862614/how-does-python-dict-comprehension-work-with-lambda-functions-inside). And so, the solution was there, after several hours of head scratches and articles about early and late bind and (anonymous) functions in loop variables inside loops, I had to tie (or late-bind, if you will) the value name of the variable in the lambda function to the value of the variable in the loop. This means I had to create another value in the lambda and that the value HAS to be the last in the lambda function because it will be created as a keyword argument and lambdas respect the rule of \*args first, \*\*kwargs last. So, the solution was finally here: def paint(total, done, elements): return [*map({'rgy'[i]:lambda x, y=i+1:f'\033[9{y}m{x}\033[00m'for i in range(len('rgy'))}['g' if total == done else 'y' if done >= total/2 else 'r'],elements)] If you have any question, you find this interesting, you have any feedback, you want to talk about Python or you just want to send me death threats because I wrote a long-ass post about lambdas and how they work in loops, HMU or comment down below. Have fun, and happy easter: [Easter Bunny](https://preview.redd.it/c2qo8krnmrt81.png?width=564&format=png&auto=webp&s=354dfac6c9adada4c4e5a57d531b073aa4967968)
0.73
t3_u4j0jn
1,650,060,242
Python
Learn Python from Scratch to Advance with Detailed Hands-on
0.38
t3_u4hgpj
1,650,055,769
Python
Archimedes Spiral: Converting old-school BASIC to Python
A little bit retro, a little bit Python. This is pretty much a direct conversion of the BASIC code to Python. Perhaps you can make it even better! https://goto10.substack.com/p/archimedes-spiral https://i.imgur.com/eHdCPrK.jpg
0.87
t3_u4h485
1,650,054,739
Python
Creating an HTTPS Lambda Endpoint without API Gateway
0.57
t3_u4gkfx
1,650,053,153
Python
Python module for Notion
Notionpy is a python module that helps you integrate notion with your programme\\workflow utilizing notion's API, the module helps you create, retrieve and update pages or databases with ease Someone will ask "what is the difference between this module and the other plenty of modules out there !?", as far as I have seen searching the web, this is the most versatile, user-friendly one you can start using it by typing in your terminal : pip install auto-py-notion Github repo : [https://github.com/kareemmahlees/NotionPy.git](https://github.com/kareemmahlees/NotionPy.git) Note : this module is still basic stage with fairly simple functionality, so all your suggestions, issues, and contributions are very welcome
0.6
t3_u4da5o
1,650,044,005
Python
How to build a RSS from scraping using Python
0.94
t3_u4d17u
1,650,043,321
Python
Python, Flask, Elasticsearch - front controller and API documentation - Part 3 Tutorial
Hi, the 3d article devoted to the theme: “How to work with ElasticSearch, Python and Flask” already ready for reading. Here will speak about package dependencies we are going to use, some project structure aspects, controller, REST API, flask\_apispec package and response/request models. All details are here: ["Symfony, elasticsearch - front controller and api documentation"](https://sergiiblog.com/python-flask-elasticsearch-front-controller-and-api-documentation/). Have a pleasant reading.
0.4
t3_u4aplz
1,650,036,900
Python
Geometry Calculation
0.25
t3_u4a3sa
1,650,035,177
Python
How To Build Your Own Crypto News Aggregator [Streamlit]
0.23
t3_u49yxj
1,650,034,812
Python
A simple email app
I made a simple email app in python [gocrazygh/emailapp: A simple email app in python (github.com)](https://github.com/gocrazygh/emailapp)
0.6
t3_u48ux2
1,650,031,662
Python
Fun project to notify my boss if I’m at my desk or not each morning.
I made a script that utilizes opencv to help me identify if I’m at my desk or not and then let my boss know. Made a fun video on how it turned out. [Video](https://youtu.be/AV7qLsYnOWY)
0.92
t3_u48iqw
1,650,030,683
Python
Running Python in the Browser with WebAssembly
0.72
t3_u47p54
1,650,028,107
Python
2 Use Cases of Python Pre-commit Hooks to Tidy Up Your Git Repositories
0.64
t3_u47kk6
1,650,027,739
Python
Like httpie? Might need to like it again...
A great Python project, [HTTPie](https://github.com/httpie/httpie) recently lost all of its Github stars due to an easy-to-make mistake. [Read more at their blog](https://httpie.io/blog/stardust). I enjoy [HTTPie](https://github.com/httpie/httpie) as a cURL-like command line tool for interacting with APIs and other web resources. A very clever UI, and a good example of using [rich](https://rich.readthedocs.io/) and [requests](https://docs.python-requests.org/). You may want to consider helping them restore or even increase their online community, sadly lost due to this error. You can star and/or watch the repo at https://github.com/httpie/httpie
0.96
t3_u46vhe
1,650,025,435
Python
Firedm repos no longer exist.
FireDM is a python open source (Internet Download Manager) with multi-connections, high speed engine, it downloads general files and videos from youtube and tons of other streaming websites . Yesterday I tried to go to the GitHub page to download the latest release but the repo returns a 404 which means it does not exist. The pypi package still exists and here's the link: https://pypi.org/project/FireDM/ The project page clearly shows that the repository is inaccessible.No forks of it even exist on Github. I can't seem to find any news or complaints anywhere on the internet about this so I was wondering is there some announcement I missed? And to my last question, is there a way we can save the project through pypi and create forks of it? Edit : my package manager still has a copy(Manjaro and AUR)
0.92
t3_u44t8y
1,650,017,535
Python
Vitrix - An open source FPS video game coded in Python!
Vitrix is a fully open source video game coded in Python! It makes use of Ursina Engine and TKinter for its GUIs and has with prebuilt releases that come bundled with a Python binary and all necessary libraries preinstalled! Even though Vitrix is still in the early stages of its development, it is still perfectly playable and has actively maintained code and a wiki. Me being the developer, I'm not very good with any of the arts, so anybody who can contribute textures, models or sounds is much appreciated. Vitrix still has much development to go, so anybody who helps will be welcomed. ​ Want to see one of your ideas in Vitrix someday? Recommend me ideas: [https://github.com/ShadityZ/Vitrix/discussions/24](https://github.com/ShadityZ/Vitrix/discussions/24) Apply to become a developer: [https://github.com/ShadityZ/Vitrix/discussions/26](https://github.com/ShadityZ/Vitrix/discussions/26) ​ You can find the Vitrix github repository here: [https://github.com/ShadityZ/Vitrix](https://github.com/ShadityZ/Vitrix) Here at some images: [https://user-images.githubusercontent.com/543577/163570397-c4736068-199e-4527-a998-e18309e9c49c.png](https://user-images.githubusercontent.com/543577/163570397-c4736068-199e-4527-a998-e18309e9c49c.png) [https://imgur.com/a/PLKDG4L](https://imgur.com/a/PLKDG4L) ​ Contributions open, ShadityZ
0.9
t3_u43oxi
1,650,012,550
Python
Python custom formatting
0.83
t3_u43mf5
1,650,012,218
Python
Good GUI builder for Python similar to Java’s Eclipse Windowbuilder
Hi guys! I’m a Java developer migrating to Python, and I’m trying to find a good GUI builder that is similar to Java’s Eclipse windowbuilder. I have tried PyQy5 and it’s Qt Designer which is very good and very close to windowbuilder in terms of interface, but the only problem is that the Qt Designer doesn’t work dynamically with the IDE like the windowbuilder: all Qt Designer’s ui file need to be translated manually to py file and then modified. This is really bad for efficiency since everything added and modified in the Qt Designer need to be saved and translated again and manually copied from the new py file to the main py file, and all objects’ code’s locations need to be manually located (Unlike in windowbuider where you double click the object in the builder and you will be automatically redirected to the related code) Since Python is such a popular language and so many people use it to develop complicated GUI softwares, I guess there has to be a GUI builder that is more efficient and similar to Java’s windowbuilder
0.78
t3_u40lpu
1,649,999,500
Python
Airflow 2.3.0 - Dynamic Tasks
Coming Soon in Airflow 2.3.0 - First-class support for "Dynamic Tasks". This is feature is called "Dynamic Task Mapping" The wait for the most requested feature of Apache Airflow is almost over !! No longer hacking over creating dynamic tasks, with Dynamic Task Mapping, Airflow will allow users to create a number of tasks at runtime based upon current data, rather than having to know in advance how many tasks would be needed. https://twitter.com/kaxil/status/1514745136680419335?s=21&t=suoW11Re4Ew2cooN4FbhEw
0.73
t3_u3vzb1
1,649,983,938
Python
Collection(s) of counter-intuitive Python behaviour
This is kind of a shot in the blue: Some time ago I found a (GitHub?) repo that collected unexpected/surprising Python behaviour. Ofc this depends on ones knowledge but it is stuff that is counter-intuitive if you don't know it or the internals. The first example was [internal caching of -5...256](https://www.reddit.com/r/Python/comments/18leav/python_integer_range_5_256_and_identity_comparison/) and all the consequences of that (ids, is), … If you don't know that particular repo, do you know similar behaviour? I found this [Python oddities talk](https://treyhunner.com/python-oddities/) but that wasn't it. Secondary question: What would be a good source for this (edit: finding oddities/inconsistencies)? I enjoyed to learn what's new by reading the release notes <3. I found looking/searching through [bugs.python.org](https://bugs.python.org/) quite interesting, because you can follow a discussion about aspectes of the language properties/behaviour, same idea why I skimmed PEPs and their discussion. However, there is always something one does not know and I want to learn all of that. For that reason I am keeping a file in which I document parts of the language that I am not that used to, and then I mostly play around with `ptpython` and try stuff which I try to use later on if it seems like a good fit. I guess well fitting flairs are discussion, help, resource, … but since I can't really decide I am choosing help. after all I want help to find a resource which could provide material for a discussion.
0.77
t3_u3vd2g
1,649,981,969
Python
Friday Daily Thread: Free chat Friday! Daily Thread
Use this thread to talk about anything Python related! Questions, news, projects and any relevant discussion around Python is permitted!
0.57
t3_u3uzei
1,649,980,810
Python
Non developer code review
Hello, I am not a developer and barely work with software for my job but have been self taught ever since reading "Automate the boring stuff with python" four years ago. One of the biggest issues that I run into by being self taught and not working with software is I am never really certain if I am doing things correctly or if there are better ways. I have found a bunch of people on fiver to do code reviews but as I don't have a complete project, I'm not sure if that is the best path to take for a code review. For the most part I believe I am past the point of having to following tutorials, but not far enough to really make a full project from start to finish. To summaries my questions: 1. What are the best places/communities for non developer code review? 2. What are the best places/ways to learn how to construct a project from start to finish? Here is my github to assess my level of knowledge (FYI not much lol) [https://github.com/daedalus23/Configuration](https://github.com/daedalus23/Configuration)
0.67
t3_u3u8om
1,649,978,547
Python
For those familiar with SpeechRecognition module, does it collect user data?
I have a question, and it may be dumb but I haven't been able to find an answer online, but does the SpeechRecognition module, specifically CMU Sphinx or Google Speech Recognition collect user data? I am a fan of having privacy and try to leave as minimal of a digital footprint when possible and have been wondering since I started using SpeechRecognition about the data collection. I'd like to avoid having to deploy my own NLP, TTS, and STT models if I can to achieve privacy for the project I am working on that involves this stuff.
0.6
t3_u3tp8v
1,649,976,942
Python
Version 2.1.1 of YFrake library just released!
I'm happy to let you guys know that the YFrake library now implements caching, speeding up consecutive identical requests to the same endpoints even more! If you are into fintech and use stock market data from Yahoo Finance, give YFrake a try! It's easy to use, it's way faster than yfinance, has more data endpoints, is thoroughly tested, is fully documented and can even run as a server to forward data to other applications! You can check it out on GitHub at: [https://github.com/aspenforest/yfrake](https://github.com/aspenforest/yfrake) The docs are available on: [https://yfrake.readthedocs.io/](https://yfrake.readthedocs.io/)
0.6
t3_u3taxa
1,649,975,777
Python
Ready-Made Mobile App UI for Serverless Python
I made a tool for myself to wrap Python code in a mobile app (chat interface) so that I can let my non-technical friends try any programs I write. Curious if you guys would be interested too. I like coding in Python, but I didn't like how my non-technical friends and family couldn't try my python apps. So I made a lightweight frontend for iOS and Android using Flutter and a lightweight web app to fill in a serverless Python function. This is how it works: 1. User uses the mobile app to send a message. Optionally with an attachment, like an image. This message is sent to serverless function as a JSON object. 2. Serverless function starter code is just print(msg) and return empty\_message. But when I want to write an app, I do some operations on msg, and return a JSON in a certain schema. 3. Mobile app gets the JSON back from serverless, and I render it to user according to the JSON schema. I thought I'd try a bunch of consumer app ideas, but I actually ended up mostly making a bunch of other tools for myself. Like when I send a hard-coded message like "redis flushall", I make the backend flush redis cache for another app that I made. I'm not really utilizing my own tool well, so I'm curious whether anyone here would be interested in using it to make some consumer tools. I can't publicly open it, cuz I made it for myself and there's no robust authentication to prevent people from running spam code on the serverless infra. But I'd love to send link and placeholder auth to some people if you are interested and leave a comment! (Would love to know what kind of apps you'd build!). If a lot of people are interested, I'll work on protecting it behind some auth, or let people pay for their own compute cost (for example, log in to their AWS; and automatically set up a VM to run the python code you write using my web IDE)!
0.5
t3_u3s8ji
1,649,972,674
Python
Run Multiple Functions in Parallel in Python3
0.3
t3_u3rxoa
1,649,971,834
Python
I'm organizing a hackathon!
Someone interested in build something next weekend? \-> workby.io/hackathon
0.29
t3_u3r7bu
1,649,969,801
Python
Financial portfolio optimization for scikit-learn enthusiasts
Scikit-portfolio is a Python package designed to introduce **data scientists and machine learning engineers** to the problem of **optimal portfolio allocation in finance**. The main idea of scikit-portfolio is to provide many well-known portfolio optimization methods with an easily accessible **scikit-learn inspired** set of API. You can optimize your portfolio starting from a pandas Dataframe with the prices or returns and simply compute the MinVol vanilla portfolio to get the optimal weights as: `MinimumVolatility().fit(prices).weights_` When your portfolio optimization method depends on a number of hyperparameters you can simply perform a `GridSearchCV` as in machine-learning algorithms, and present the grid of hyperparameters, which for most methods are already encoded in the class. ``` prices_train, prices_test = train_test_split(prices, test_size=0.3, shuffle=False) ptf_model = MaxSharpe() best_model = GridSearchCV( estimator=ptf_model, param_grid=ptf_model.grid_parameters(), cv=KFold(5), scoring=sharpe_ratio_scorer ).fit(prices_train) ``` It implements Omega Ratio and MAD efficient frontier as well as a number of portfolio hyperparameters search methods for the optimization in backtesting settings, using the same methods as in classical machine-learning model selection method. Additionally, I've implemented ensemble portfolios, like the **Michaud Resampled Efficient Frontier** that builds an optimal portfolio based on the average of many efficient frontiers based on random perturbations of the expected returns. We not only support the classical MeanVariance efficient frontier, but many kind of efficient frontiers, with different definitions of risk and satisfaction. This is for example how you build an ensemble of estimators of the maximum Sharpe ratio portfolio: ``` prices = load_tech_stock_prices() # create a Maximum sharpe ratio portfolio estimator to be fed to resampled frontier meta-estimator ptf = MaxSharpe( returns_data=False, risk_free_rate=0.0, frequency=252, rets_estimator=MeanHistoricalLinearReturns() ) ensemble = MichaudResampledFrontier( ptf_estimator=ptf, rets_estimator=MeanHistoricalLinearReturns(), risk_estimator=SampleCovariance(), n_iter=512, n_jobs=-1 ).fit(prices) ``` **Documentation** [https://scikit-portfolio.github.io/scikit-portfolio/](https://scikit-portfolio.github.io/scikit-portfolio/) **Source code** [https://github.com/scikit-portfolio/scikit-portfolio](https://github.com/scikit-portfolio/scikit-portfolio) The project requires some help in the documentation, while it is already pretty stable in the API and bugfix. ![mad_frontier](https://scikit-portfolio.github.io/scikit-portfolio/imgs/mad_efficient_frontier.svg)
0.67
t3_u3qq2x
1,649,968,463
Python
Parts of the Standard Library that are considered to be bad practice / un-Pythonic ?
I had an argument today about the using the `_empty` object from the `inspect` module to denote an item not found in a lookup, rather than just returning None (as None could well be a value in our data), or erroring (as too many try/excepts make code more difficult to read, and failing to find something in our system is not actually an error anyway). Aside from the idea of using a private attribute of another module, the other person says it's "not Pythonic" to use smaller custom types like this, as it's too close to something like `typedef` in c++ (never mind that Python has `namedtuple` for almost the exact same purpose anyway, but I digress). I argued that it's a ready-made and easily legible solution to the problem, and regardless, if it's good enough for the standard library then it should be good enough for us. While I think I'm right in this case, I know the last point is a very dogmatic way of looking at things. It got me thinking - are there any notable parts of the language's standard modules, that would be considered a poor or incorrect use of the language if you were to use them in production?
0.92
t3_u3p62s
1,649,964,161
Python
GUI, CLI and library for remote controlling Philips Android TVs
Some time ago I was trying to find out if there's a way to programmatically control my TV's Ambilight feature. It turns out Philips Android-powered TVs have a pretty extensive API and there's no decent library or program to make use of it! I found this state of affairs unacceptable and decided to be the change I want to see in the world. Then I proceeded to create a library, CLI, and finally GUI utilizing this API: * [PhilipsTV GUI](https://github.com/bcyran/philipstv-gui) \- a GUI, obviously * [philipstv](https://github.com/bcyran/philipstv) \- CLI and a lib The features include emulating pressing TV remote keys, listing and changing channels and applications, and of course controlling Ambilight. [All of PhilipsTV GUI functionality in one image](https://preview.redd.it/vkp8gfnkzit81.png?width=1241&format=png&auto=webp&s=14a40b658da14951ad22c1e59e07ec98074547b4) It would be pretty cool if someone found that useful because I spent quite a lot of time on this and actually... I don't even need this.
0.94
t3_u3m6ar
1,649,955,769
Python
I used a new dataframe library (polars) to wrangle the one of the largest housing price databases. Code in post
0.94
t3_u3m0qp
1,649,955,374
Python
A live 45-minutes session on the fundamentals of observability, OpenTelemetry, and distributed tracing with microservices' messaging systems (Kafka, RabbitMQ, etc)
Hi everyone, we're running another live OpenTelemetry and observability fundamentals session - Wednesday, April 20 at 11 AM PDT. You will learn how to instrument your message brokers and apps to capture traces with OpenTelemetry. This session is at no cost and vendor-neutral. You can expect in this session: 45 minutes of core concepts, how to deploy it yourself hands-on + Q&A. If you are interested in observability, OpenTelemetry, and tracing - join! Register here [https://www.aspecto.io/opentelemetry-fundamentals/messaging-systems/](https://www.aspecto.io/opentelemetry-fundamentals/messaging-systems/?utm_source=post&utm_medium=reddit&utm_campaign=r-python-opentelemetry-fundamentals-messaging-systems)
0.71
t3_u3kzsh
1,649,952,550
Python
Using Python how to connect to multiple Bluetooth LE devices and transfer data between them.
0.59
t3_u3j2d6
1,649,947,229
Python
Running Rich's Inspect in bashrc
I really like [Rich's Inspect method](https://rich.readthedocs.io/en/stable/introduction.html#rich-inspect) such that I want to create a shortcut in my bashrc. I tried thiese and it didn't work. alias rinspect='python -c "from rich import inspect; import '$1'; inspect('$1')"' alias r2inspect='python -c 'import sys; from rich import inspect; import sys.argv[1]; inspect(sys.argv[1])' Basically, I want to run it like this: $ rinspect datetime What am I missing here?
0.81
t3_u3imay
1,649,945,996
Python
how to handle huge amount of data for a web app ?
hey guys, i'm working on a project where i'm importing data from google sheets using sheets API weekly, so that each week a new sheet is added to the spreadsheet and then the data is automatically collected in one new sheet to be used as input for my dashboard that i used streamlit to build, i'm planning now to deploy it on heroku, but i came to ci/cd part which i didnt get tbh, and i,m wondering how my app would perform when the data would be larger maybe after 1 year, whaat to do then , is there any solution to handle that big data from the start ?
0.7
t3_u3gs01
1,649,940,505
Python
mdiff - generating diff with block move detection
[mdiff](https://github.com/m-matelski/mdiff) is a package for comparing and generating diff for input sequences. It can detect sequence elements displacements (i.e. line in text have been moved up or down). # Sequence Matcher Example: from mdiff import HeckelSequenceMatcher a = ['line1', 'line2', 'line3', 'line4', 'line5'] b = ['line1', 'line3', 'line2', 'line4', 'line6'] sm = HeckelSequenceMatcher(a, b) opcodes = sm.get_opcodes() for tag, i1, i2, j1, j2 in opcodes: print('{:7} a[{}:{}] --> b[{}:{}] {!r:>8} --> {!r}'.format(tag, i1, i2, j1, j2, a[i1:i2], b[j1:j2])) Output: equal a[0:1] --> b[0:1] ['line1'] --> ['line1'] move a[1:2] --> b[2:2] ['line2'] --> [] equal a[2:3] --> b[1:2] ['line3'] --> ['line3'] moved a[1:1] --> b[2:3] [] --> ['line2'] equal a[3:4] --> b[3:4] ['line4'] --> ['line4'] replace a[4:5] --> b[4:5] ['line5'] --> ['line6'] # Text Diff Generating diff for input texts with (optional) similar lines changes detection. from mdiff import diff_lines_with_similarities, CompositeOpCode a = 'line1\nline2\nline3\nline4\nline5' b = 'line1\nline3\nline2\nline4\nline6' a_lines, b_lines, opcodes = diff_lines_with_similarities(a, b, cutoff=0.75) # Just printing diff on a line level, and nested diff on a character level for similar lines for opcode in opcodes: tag, i1, i2, j1, j2 = opcode print('{:7} a_lines[{}:{}] --> b_lines[{}:{}] {!r:>10} --> {!r}'. format(tag, i1, i2, j1, j2, a_lines[i1:i2], b_lines[j1:j2])) if isinstance(opcode, CompositeOpCode) and opcode.children_opcodes: for ltag, li1, li2, lj1, lj2 in opcode.children_opcodes: print('\t{:7} a_lines[{}][{}:{}] --> b_lines[{}][{}:{}] {!r:>10} --> {!r}' .format(ltag, i1, li1, li2, j1, lj1, lj2, a_lines[i1][li1:li2], b_lines[j1][lj1:lj2])) Output: equal a_lines[0:1] --> b_lines[0:1] ['line1'] --> ['line1'] move a_lines[1:2] --> b_lines[2:2] ['line2'] --> [] equal a_lines[2:3] --> b_lines[1:2] ['line3'] --> ['line3'] moved a_lines[1:1] --> b_lines[2:3] [] --> ['line2'] equal a_lines[3:4] --> b_lines[3:4] ['line4'] --> ['line4'] replace a_lines[4:5] --> b_lines[4:5] ['line5'] --> ['line6'] equal a_lines[4][0:4] --> b_lines[4][0:4] 'line' --> 'line' replace a_lines[4][4:5] --> b_lines[4][4:5] '5' --> '6' # App **mdiff** provides simple [CLI tool](https://github.com/m-matelski/mdiff#cli-tool) and [GUI app](https://github.com/m-matelski/mdiff#standalone-gui-application) for comparing files and texts. It can be used for visualising and testing different diff algorithms (also Python built-in difflib.SequenceMatcher). https://preview.redd.it/tu88e3lhrgt81.png?width=1211&format=png&auto=webp&s=45b602c8fed5b89d0dfc1228f889c44a1bca397f
0.87
t3_u3glpx
1,649,939,930
Python
HackerRank or Leetcode?
In which one do you guys prefer to practice, and why?
0.85
t3_u3ghm3
1,649,939,555
Python
Running your scheduled Python tasks on Heroku? You can now natively monitor them! 👾👾👾
Hi devs! Do you, like so many others, use one-off dynos to run your scheduled tasks on Heroku? Do you feel like one-off dynos running in the background are kind of invisible? Have a look at the [One-off Dyno Metrics Heroku add-on](https://elements.heroku.com/addons/one-off-metrics)! This Heroku add-on plots the execution times, throughput, concurrency, and dyno events of your one-off dynos. It also provides threshold alerting, allowing you to monitor important stuff. You will know exactly how your one-off dynos behave, and what is going wrong. The add-on is about to become generally available. Last chance to install during the beta and get full access for a month after launch!
0.8
t3_u3gaab
1,649,938,900
Python
DataSpell 2022.1 Released
0.66
t3_u3d9w5
1,649,928,154
Python
Using Python to create large scale SEM campaigns in minutes.
Join our next webinar on Wednesday 20/04/2022 at 12 PM CET. Our next guest will be Elias Dabbas, the creator of advertools. He'll share how he's using Python to create large scale SEM campaigns in minutes using advertools. Topics covered: \- Generating Keywords for SEM Campaigns \- Creating Ads Using Long Descriptive Text \- Creating Ads on a Large Scale Register here: [https://www.linkedin.com/events/usingpythontocreatelargescalese6918192144046338048/about/](https://www.linkedin.com/events/usingpythontocreatelargescalese6918192144046338048/about/) [https://github.com/eliasdabbas/advertools](https://github.com/eliasdabbas/advertools)
0.4
t3_u39d7x
1,649,911,596
Python
Python as a career
I am an Engineer and have a little background in coding using R. Is it possible I can learn Python to make it a side hustle? I welcome your advice. Thanks
0.82
t3_u379ba
1,649,904,315
Python
Thursday Daily Thread: Python Careers, Courses, and Furthering Education!
Discussion of using Python in a professional environment, getting jobs in Python as well as ask questions about courses to further your python education! **This thread is not for recruitment, please see** r/PythonJobs **or the thread in the sidebar for that.**
0.67
t3_u343wx
1,649,894,414
Python
Learn how to write clean Python code with this free ebook
Hi! I wrote [Cleaner Python](https://ezzeddin.gumroad.com/l/cleaner-python) with the intention to help developers who are getting started in writing clean code in Python. I'd love to hear your feedback and please let me know if you have any questions.
0.58
t3_u32r51
1,649,890,439
Python
Chances of getting a job for smb. learned python at home
Hey folks! I hope it’s the place that I can post this question. Let me give you a brief info about my background. I’ve studied economics and worked in international sales. After my gf got a job from a Swedish company we decided to move there. We will be there by August if everything went as we want. So I was thinking of learning software to change my career path. During pandemic I learnt SQL but than didn’t develop myself. So now I started with python which I think easier than many languages. But what I am wondering is if I can get a job or not. I know that it depends on what and how much I learnt and etc. but what you guys think or recommend? Honestly speaking, I think I can get a job as an intern or a junior. Especially after Covid the demand for developers increased rapidly. So I am not pessimistic about this idea. After python I am planning to learn JavaScript too. Anyway. I am waiting for your answers and valuable feedbacks!
0.6
t3_u32l5z
1,649,889,953
Python
What are your most wanted quality indicators for Python code?
Dear, I'm trying to list the good and bad practices regarding Python code to write a document to help the teams to assess progress points. For example in good practices: * Comments * Typing * Docstrings * Sphinx documentation * Readable variable names * Git * CI/CD * Unit Tests * ... For pollutions: * Deprecated code with no warning * Commented code everywhere * Full paths * ... I would like to know what are your own pain points and what you like, or hate, when you inherit from someone else code. Thanks
0.71
t3_u31bkw
1,649,886,437
Python
Alarm-Clock made with Python and Kivy
Hi! I'm here to share with you a little project I developed as a hobby last year: an alarm-clock made with Python and Kivy! I'd appreciate feedbacks :3 [https://github.com/v0di/alarm-clock](https://github.com/v0di/alarm-clock)
0.84
t3_u2zz5r
1,649,882,880
Python
PyCharm 2022.1 released
0.96
t3_u2vp01
1,649,871,165
Python
The fastest tool for querying large JSON files is written in Python! (benchmark)
[spyql](https://github.com/dcmoura/spyql) is a tool (and python lib) for querying and transforming data. It is fully written in Python. In the [latest benchmark](https://colab.research.google.com/github/dcmoura/spyql/blob/master/notebooks/json_benchmark.ipynb), spyql outperformed all other tools, including jq, one of the most popular tools written in C. Here is one example extracted from the benchmark that shows spyql achieving the lowest processing time while keeping memory requirements low when the dataset size is >= 100MB. ​ [Processing time and memory requirements vs size of input JSON data](https://preview.redd.it/ejgy2k0gwbt81.png?width=1315&format=png&auto=webp&s=782958571e0a5a7309484011fbc0d7c1c9da5015) IMO, these results might questions some preconceived opinions about Python’s performance and interpreted languages in general. The benchmark is very easy to reproduce without installing any software since it runs on a [google colab notebook](https://colab.research.google.com/github/dcmoura/spyql/blob/master/notebooks/json_benchmark.ipynb). Happy to hear your thoughts! **UPDATE 2022/04/22** Thank you all for your feedback. The benchmark was updated and the fastest tool is **NOT** written in Python. Here are the highlights: * Added ClickHouse (written in C++) to the benchmark: I was unaware that the clickhouse-local tool would handle these tasks. ClickHouse is now the fastest (together with OctoSQL); * OctoSQL (written in Go) was updated as a response to the benchmark: updates included switching to fastjson, short-circuiting LIMIT, and eagerly printing when outputting JSON and CSV. Now, OctoSQL is one of the fastest and memory is stable; * SPyQL (written in Python) is now third: SPyQL leverages orjson (Rust) to parse JSONs, while the query engine is written in Python. When processing 1GB of input data, SPyQL takes 4x-5x more time than the best, while still achieving up to 2x higher performance than jq (written in C); * I removed Pandas from the benchmark and focused on command-line tools. I am planning a separate benchmark on Python libs where Pandas, Polars and Modin (and eventually others) will be included. This benchmark is a living document. If you are interested in receiving updates, please subscribe to the following issue: [https://github.com/dcmoura/spyql/issues/72](https://github.com/dcmoura/spyql/issues/72) Thank you!
0.92
t3_u2v858
1,649,869,896
Python
Ohio State University Researchers Develop SAT2LoD2: An Open-Source Python Tool For 3D Landscape Modelling Using Satelite Imagery
3D landscape modeling has seen a rise in its popularity and applications in recent years. It has countless applications in the fields of civil engineering, earth sciences, military applications, and many others. Geometric 3D models are typically developed using the city geography markup language (CityGML), and the Level-of-Detail (LoD) building model is the preferred model for building 3D models using CityGML.  The use of Satellite imagery for landscape modeling provides the advantage of covering a wide area and is low cost. However, developing LoD2 models using satellite imagery remains a big challenge. Building models in such a way involves complex steps demanding heuristics-based approaches and ML-based detection paradigms. In a recent paper, researchers at the Ohio State University propose a [SAT2LoD2 ](https://arxiv.org/pdf/2204.04139v1.pdf)to facilitate the development of 3D landscape models. SAT2LoD2 is an open-source, python-based GUI-enabled software that takes the satellite images as inputs and returns LoD2 building models as outputs. The software also has the feature of taking road networks and custom maps as additional inputs for better results. [Continue Reading](https://www.marktechpost.com/2022/04/13/ohio-state-university-researchers-develop-sat2lod2-an-open-source-python-tool-for-3d-landscape-modelling-using-satelite-imagery/) Paper: https://arxiv.org/pdf/2204.04139v1.pdf Github: https://github.com/gdaosu/lod2buildingmodel
1
t3_u2v7m9
1,649,869,856
Python
typeforce: Make mypy more effective
**Typeforce** is a CLI tool that enriches your Python environment with type annotations, empowering [mypy](https://mypy.readthedocs.io/en/stable/). In particular: + Generates `py.typed` for annotated packages. + Installs missed stub files and plugins. https://github.com/orsinium-labs/typeforce
0.81
t3_u2sbgj
1,649,862,123
Python
`nme` - package to simplify data persistence when upgrading data structures
I would like to share my python package `nme`. This package is for simplifying loading data from the older versions of code. It was initially created for [napari](https://napari.org/) plugins for improving science reproducibility, but I think that it may be useful for other projects. Code is here: https://github.com/Czaki/nme Documentation: https://nme.readthedocs.io/en/latest/?badge=latest Currently, it supports `json` and `cbor2` as backends for serialization. I'm open to any improvement suggestions.
0.5
t3_u2s3uy
1,649,861,576
Python
Why does the Development Company use the Python web framework?
0.11
t3_u2rvxb
1,649,860,950
Python
Minimalist dependency injection in Python
1
t3_u2pow9
1,649,854,549
Python
I made a video about Cross Validation using python's sklearn package. An extremely important yet often overlooked topic in machine learning.
0.38
t3_u2pmet
1,649,854,324
Python
Python 3.11 is Coming! Here’s How It Fares Against Python 3.10
0.78
t3_u2orpk
1,649,851,479
Python
Do you have hundreds of old and embarrassing tweets? Here's a script to delete them all.
I made a Python script to delete old tweets. Given a date, it'll delete all the tweets before that date. Personally, I had hundreds of tweets between my friends talking about hot boys in high school that I had forgotten all about but were all so public 🤦🏻‍♀️. Give it a try: [https://github.com/yaylinda/delete-tweets](https://github.com/yaylinda/delete-tweets) Feel free to make suggestions or improvements!
0.91
t3_u2o1al
1,649,848,859
Python
Here is a script that turns your pc off when a download is finished
Here is a script that turns off your computer when a game on steam has finished downloading. import os import time while os.listdir('*insert your own steam downloading folder here*') != []: print('Download in progress..') time.sleep(5) print('Folder empty. Downloads complete.') os.system("shutdown /s /t 1")
0.86
t3_u2ln8f
1,649,838,771
Python
Gotchas of early-bound function argument defaults in Python
0.72
t3_u2iknk
1,649,825,890
Python
Why do some functions have the arguments outside and some inside? e.g: len(example) vs example.upper() ?
This is the case too in other languages right?
0.8
t3_u2gg0a
1,649,818,670
Python
A python framework for unstructured data processing
Unstructured data is information that is not arranged according to a predefined schema or data model. Image, text, video, and nested JSON are the most common types of unstructured data we collected in real-world applications. We have just released [Towhee 0.6](https://github.com/towhee-io/towhee), a framework for doing ML jobs over unstructured data. Our latest release includes [`DataCollection`](https://towhee.readthedocs.io/en/branch0.6/data_collection/get_started.html), a new user-centric method-chaining API that enables rapid development and prototyping of unstructured data applications. `DataCollection` is designed to behave as a python list or generator, with some enhancement features such as `method-chaining coding style`, `parallel execution`, and `exception handling`. Here is a short example of image animation: ```python import towhee towhee.glob['path']('./test.png') \ .image_decode['path', 'origin']() \ .img2img_translation.animegan['origin', 'facepaintv2'](model_name = 'facepaintv2') \ .img2img_translation.animegan['origin', 'hayao'](model_name = 'hayao') \ .img2img_translation.animegan['origin', 'paprika'](model_name = 'paprika') \ .img2img_translation.animegan['origin', 'shinkai'](model_name = 'shinkai') \ .select['origin', 'facepaintv2', 'hayao', 'paprika', 'shinkai']() \ .show() ``` [`image_decode`](https://towhee.io/image-decode/cv2) and [`img2img_translation.animegan`](https://towhee.io/img2img-translation/animegan) are predefined `operator`s from [towhee hub](https://towhee.io). We already have nearly a hundred operators, officially maintained or contributed by our users. You can check the result from [the tutorial](https://github.com/towhee-io/towhee/blob/main/tutorials/anime_style_transformer.ipynb). Documentation for DataCollection is available [here](https://towhee.readthedocs.io/en/branch0.6/data_collection/get_started.html). We will be releasing code examples and tutorials using the new API in the upcoming weeks. Would appreciate some feedback and contribution :)
0.67
t3_u2g5ha
1,649,817,729
Python
Do people generally write Sphinx API documentation using autoapi or manually?
(this might not be the best subreddit, but I didn't see a Sphinx subreddit, if there's a better place, let me know) I'm working on writing my first distributable python package and I'm trying to be very meticulous about the documentation, making a readthedocs page for it. I'm very new to using Sphinx, and I'm confused on the landscape of projects that have autogenerated API documentation vs. those that involve manually written documentation. I have been able to get the `autoapi` extension to work, but the documentation it generates feels very boilerplate, and I want to go in and reformat some of the stuff it does, which I think it's possible to essentially "convert" a project from auto to manual. So maybe I should autogenerate it at first and then convert it for later changes. I have some concerns about that approach though. 1. What if I add more stuff to the API later, or update the way certain functions work? Would I just need to do those small changes by hand? I feel like if I reverted to the autogeneration it would overwrite my manual changes (maybe I'm wrong though). 2. I actually prefer to code at the same time that I am documenting, so that the documentation is not an afterthought, but in that case I would want to do the manual changes at the same time as when I code, so maybe autogeneration is a bad idea for me. But this particular project is collaborative and I think I'm probably the only one in my group who *enjoys* the documentation, so I want to be sure it's super easy for future collaborators. Any thoughts at all would be greatly appreciated! I seem to be unable to find answers to a general best practices question like this
0.81
t3_u2dfzz
1,649,809,416
Python
Wednesday Daily Thread: Beginner questions
New to Python and have questions? Use this thread to ask anything about Python, there are no bad questions! This thread may be fairly low volume in replies, if you don't receive a response we recommend looking at r/LearnPython or joining the Python Discord server at [https://discord.gg/python](https://discord.gg/python) where you stand a better chance of receiving a response.
1
t3_u2cz7f
1,649,808,018
Python
My first working code piece!
print ('What is the temperature today?') import random Temperature = random.randint(10,40) print(Temperature) print ('Degrees') ​ if Temperature > 24: print ('Its a hot day,') print ('Make sure to drink some water!') ​ if Temperature <24: print ('Its not to hot today!') ​ if Temperature == 24: print ('Its a hot day,') print ('Make sure to drink some water!') ​ ​ I am happy that it works!
0.55
t3_u2ccc8
1,649,806,110
Python
Name a better learning resource than Schafer Corey, I'll wait
I am really amazed by Schafer Corey on [YouTube](https://www.youtube.com/c/Coreyms/videos) especially since I am not the the type of guy that enjoys watching videos to learn, I am honestly in awe with his teaching skills and it inspires me to write blogs. I will be very curious to see if you guys have other high quality content. I am well aware that you won't become proficient just by watching his videos but his tutorials get straight to the point and you understand the concept and you can build new things!
0.87
t3_u2b3r9
1,649,802,620
Python
5 months of python, Beginning an AlgoBot, TEAR MY CODE to Shred to make me better.
0.87
t3_u27epy
1,649,792,143
Python
python programming quick look
0.17
t3_u25pul
1,649,787,655
Python
TIL Dropbox started, client and server, with Python and even hired the creator of Python
0.42
t3_u255tq
1,649,786,229
Python
2 Level Security system (Arduino Keypad + Face recognition ) using Python
0.91
t3_u24o2f
1,649,784,906
Python
fstring.help: Python f-string guide
0.5
t3_u21wcl
1,649,777,711
Python
20 Python Interview Questions To Challenge Your Knowledge
0.44
t3_u218g8
1,649,775,942
Python
Announcing Quart-DB
[Quart-DB](https://github.com/pgjones/quart-db) is a Quart extension that provides managed connection(s) to postgresql database(s). Once initialised it will, by default, add a connection on `g` for every request usable via `g.connection`. Alternatively connections (and transactions) can be managed directly and explicitly. The queries can be constructed using named `:name` parameters or `$1` positional parameters. Quart-DB uses [asyncpg](https://github.com/MagicStack/asyncpg) to manage the connections and [buildpg](https://github.com/samuelcolvin/buildpg) to parse the named parameter bindings. from quart import g, Quart, websocket from quart_db import QuartDB app = Quart(__name__) db = QuartDB(app, url="postgresql://user:pass@localhost:5432/db_name") @app.get("/<int:id>") async def get_count(id: int): result = await g.connection.fetch_val( "SELECT COUNT(*) FROM tbl WHERE id = :id", {"id": id}, ) return {"count": result} @app.post("/") async def set_with_transaction(): async with g.connection.transaction(): await db.execute("UPDATE tbl SET done = $1", [True]) ... return {} @app.get("/explicit") async def explicit_usage(): async with db.connection() as connection: ...
0.85
t3_u20nde
1,649,774,365
Python
I wrote a tutorial on how to use pytest to write good Python code. I hope somebody finds it useful!
[https://github.com/rhayes777/workshop](https://github.com/rhayes777/workshop)
0.97
t3_u206vp
1,649,773,093
Python
Shades: a module to make art with python
Over the last year or so, I've been developing a python library to make it easier for me to make maths-ey generative art in python. I shared stuff a while back while I was still developing, and finally got stuff in a state where I'm pretty happy with things, so thought I'd share here just in case any other python fans might like it. [Here's a link if you're interested!](https://github.com/benrutter/Shades) https://preview.redd.it/a9obpj02v3t81.png?width=2000&format=png&auto=webp&s=4cd73bba9cab4e875772a32091c3ef49057372bb
0.98
t3_u1zzlq
1,649,772,545
Python
Minesweeper but without any play-ability
This is the basic layout of a minesweeper field fished ​ import curses from curses import wrapper from random import randint field = [ ["#", "#", "#", "#", "#", "#", "#", "#", "#"], ["#", "#", "#", "#", "#", "#", "#", "#", "#"], ["#", "#", "#", "#", "#", "#", "#", "#", "#"], ["#", "#", "#", "#", "#", "#", "#", "#", "#"], ["#", "#", "#", "#", "#", "#", "#", "#", "#"], ["#", "#", "#", "#", "#", "#", "#", "#", "#"], ["#", "#", "#", "#", "#", "#", "#", "#", "#"], ["#", "#", "#", "#", "#", "#", "#", "#", "#"], ["#", "#", "#", "#", "#", "#", "#", "#", "#"] ] def print_maze(maze, stdscr,): BLUE = curses.color_pair(1) RED = curses.color_pair(2) bomb_Location = bomb_location() for i, row in enumerate(maze): for j, value in enumerate(row): if (i,j) in bomb_Location: stdscr.addstr(i,j*2, 'x', RED) else: amount = find_amount_bomb(field,i,j,bomb_Location) stdscr.addstr(i,j * 2, amount, BLUE) def bomb_location(): bombLocation = [] for x in range(25): bomb_loc = bomb() bombLocation.append(bomb_loc) return bombLocation def find_amount_bomb(field, row, col, bomb_loc=[]): bombs_nearby = 0 neighbours = find_neigbours(field,row,col) for neighbour in neighbours: if neighbour in bomb_loc: bombs_nearby += 1 return str(bombs_nearby) def find_neigbours(field,row,col): neighbors = [] if row > 0 and col < len(field[0]): neighbors.append((row -1, col +1)) if row > 0 and col > 0: neighbors.append((row -1, col -1)) if row < len(field) and col < len(field[0]): neighbors.append((row +1, col +1)) if row < len(field) and col > 0: neighbors.append((row +1, col -1)) if row > 0: # up neighbors.append((row -1, col)) if row < len(field): # down neighbors.append((row + 1, col)) if col > 0: # left neighbors.append((row, col - 1)) if col < len(field[0]): # right neighbors.append((row, col + 1)) return neighbors def bomb(): i = randint(0,8) j = randint(0,8) return i,j def main(stdscr): curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK) stdscr.clear() print_maze(field,stdscr) stdscr.refresh() stdscr.getch() wrapper(main) idk if this is intermediate or beginner sorry if it is beginner
0.5
t3_u1zxp1
1,649,772,396
Python
Python News: What's New From March 2022? – Real Python
0.75
t3_u1yevy
1,649,768,051
Python
Python code guidelines for unified, streamlined development
In Python programming, there are many things that developers have to consider and keep in mind when writing code. Those issues and practices differ from company to company and from team to team. At Evrone, we created our own collection of guidelines for Python, in order to build a common denominator for writing code within the company. [Read the guidelines here!](https://evrone.com/python-guidelines)
0.6
t3_u1xzt3
1,649,766,739
Python
In addition to a properly formatted and stylish data presentation, we will also apply other helpful functionality, such as adding data to the database.
[https://medium.com/codex/how-to-add-new-rows-into-relational-tables-effortlessly-f6685a60eef2](https://medium.com/codex/how-to-add-new-rows-into-relational-tables-effortlessly-f6685a60eef2) ​ https://preview.redd.it/7c47g2x903t81.png?width=875&format=png&auto=webp&s=26f50b234e17feb3a3a269582a59e174016461b3
0.5
t3_u1wky9
1,649,762,014
Python
Scraping Google Finance Ticker in Python
While programming is kinda easier than a stock market, you can do things programmatically, for example scraping Google Finance Ticker data in Python. Here's a working example to do exactly that, plus basic usage of Nasdaq API which Google is using, among [other data providers which Google Finance uses that you can find under Google's Disclaimer](https://www.google.com/intl/en_UA/googlefinance/disclaimer/). A gist to the same code below: https://gist.github.com/dimitryzub/a5e30389e13142b9262f52154cd56092 Full code and [example in the online IDE](https://replit.com/@DimitryZub1/Scrape-Google-Finance-Ticker-Quote-in-Python#main.py): ```python import nasdaqdatalink import requests, json, re from parsel import Selector from itertools import zip_longest def scrape_google_finance(ticker: str): params = { "hl": "en" # language } headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.60 Safari/537.36", } html = requests.get(f"https://www.google.com/finance/quote/{ticker}", params=params, headers=headers, timeout=30) selector = Selector(text=html.text) # where all extracted data will be temporary located ticker_data = { "ticker_data": {}, "about_panel": {}, "news": {"items": []}, "finance_perfomance": {"table": []}, "people_also_search_for": {"items": []}, "interested_in": {"items": []} } # current price, quote, title extraction ticker_data["ticker_data"]["current_price"] = selector.css(".AHmHk .fxKbKc::text").get() ticker_data["ticker_data"]["quote"] = selector.css(".PdOqHc::text").get().replace(" • ",":") ticker_data["ticker_data"]["title"] = selector.css(".zzDege::text").get() # about panel extraction about_panel_keys = selector.css(".gyFHrc .mfs7Fc::text").getall() about_panel_values = selector.css(".gyFHrc .P6K39c").xpath("normalize-space()").getall() for key, value in zip_longest(about_panel_keys, about_panel_values): key_value = key.lower().replace(" ", "_") ticker_data["about_panel"][key_value] = value # description "about" extraction ticker_data["about_panel"]["description"] = selector.css(".bLLb2d::text").get() ticker_data["about_panel"]["extensions"] = selector.css(".w2tnNd::text").getall() # news extraction if selector.css(".yY3Lee").get(): for index, news in enumerate(selector.css(".yY3Lee"), start=1): ticker_data["news"]["items"].append({ "position": index, "title": news.css(".Yfwt5::text").get(), "link": news.css(".z4rs2b a::attr(href)").get(), "source": news.css(".sfyJob::text").get(), "published": news.css(".Adak::text").get(), "thumbnail": news.css("img.Z4idke::attr(src)").get() }) else: ticker_data["news"]["error"] = f"No news result from a {ticker}." # finance perfomance table if selector.css(".slpEwd .roXhBd").get(): fin_perf_col_2 = selector.css(".PFjsMe+ .yNnsfe::text").get() # e.g. Dec 2021 fin_perf_col_3 = selector.css(".PFjsMe~ .yNnsfe+ .yNnsfe::text").get() # e.g. Year/year change for fin_perf in selector.css(".slpEwd .roXhBd"): if fin_perf.css(".J9Jhg::text , .jU4VAc::text").get(): perf_key = fin_perf.css(".J9Jhg::text , .jU4VAc::text").get() # e.g. Revenue, Net Income, Operating Income.. perf_value_col_1 = fin_perf.css(".QXDnM::text").get() # 60.3B, 26.40%.. perf_value_col_2 = fin_perf.css(".gEUVJe .JwB6zf::text").get() # 2.39%, -21.22%.. ticker_data["finance_perfomance"]["table"].append({ perf_key: { fin_perf_col_2: perf_value_col_1, fin_perf_col_3: perf_value_col_2 } }) else: ticker_data["finance_perfomance"]["error"] = f"No 'finence perfomance table' for {ticker}." # "you may be interested in" results if selector.css(".HDXgAf .tOzDHb").get(): for index, other_interests in enumerate(selector.css(".HDXgAf .tOzDHb"), start=1): ticker_data["interested_in"]["items"].append(discover_more_tickers(index, other_interests)) else: ticker_data["interested_in"]["error"] = f"No 'you may be interested in` results for {ticker}" # "people also search for" results if selector.css(".HDXgAf+ div .tOzDHb").get(): for index, other_tickers in enumerate(selector.css(".HDXgAf+ div .tOzDHb"), start=1): ticker_data["people_also_search_for"]["items"].append(discover_more_tickers(index, other_tickers)) else: ticker_data["people_also_search_for"]["error"] = f"No 'people_also_search_for` in results for {ticker}" return ticker_data def discover_more_tickers(index: int, other_data: str): """ if price_change_formatted will start complaining, check beforehand for None values with try/except and set it to 0, in this function. however, re.search(r"\d{1}%|\d{1,10}\.\d{1,2}%" should make the job done. """ return { "position": index, "ticker": other_data.css(".COaKTb::text").get(), "ticker_link": f'https://www.google.com/finance{other_data.attrib["href"].replace("./", "/")}', "title": other_data.css(".RwFyvf::text").get(), "price": other_data.css(".YMlKec::text").get(), "price_change": other_data.css("[jsname=Fe7oBc]::attr(aria-label)").get(), # https://regex101.com/r/BOFBlt/1 # Up by 100.99% -> 100.99% "price_change_formatted": re.search(r"\d{1}%|\d{1,10}\.\d{1,2}%", other_data.css("[jsname=Fe7oBc]::attr(aria-label)").get()).group() } scrape_google_finance(ticker="GOOGL:NASDAQ") # outputs a JSON string ``` A basic example of retrieving time-series data using Nasdaq API: ```python import nasdaqdatalink def nasdaq_get_timeseries_data(): nasdaqdatalink.read_key(filename=".nasdaq_api_key") # print(nasdaqdatalink.ApiConfig.api_key) # prints api key from the .nasdaq_api_key file timeseries_data = nasdaqdatalink.get("WIKI/GOOGL", collapse="monthly") # not sure what "WIKI" stands for print(timeseries_data) nasdaq_get_timeseries_data() ``` Outputs a `pandas` `DataFrame`: ```lang-none Open High Low Close Volume Ex-Dividend Split Ratio Adj. Open Adj. High Adj. Low Adj. Close Adj. Volume Date 2004-08-31 102.320 103.71 102.16 102.37 4917800.0 0.0 1.0 51.318415 52.015567 51.238167 51.343492 4917800.0 2004-09-30 129.899 132.30 129.00 129.60 13758000.0 0.0 1.0 65.150614 66.354831 64.699722 65.000651 13758000.0 2004-10-31 198.870 199.95 190.60 190.64 42282600.0 0.0 1.0 99.742897 100.284569 95.595093 95.615155 42282600.0 2004-11-30 180.700 183.00 180.25 181.98 15384600.0 0.0 1.0 90.629765 91.783326 90.404069 91.271747 15384600.0 2004-12-31 199.230 199.88 192.56 192.79 15321600.0 0.0 1.0 99.923454 100.249460 96.578127 96.693484 15321600.0 ... ... ... ... ... ... ... ... ... ... ... ... ... 2017-11-30 1039.940 1044.14 1030.07 1036.17 2190379.0 0.0 1.0 1039.940000 1044.140000 1030.070000 1036.170000 2190379.0 2017-12-31 1055.490 1058.05 1052.70 1053.40 1156357.0 0.0 1.0 1055.490000 1058.050000 1052.700000 1053.400000 1156357.0 2018-01-31 1183.810 1186.32 1172.10 1182.22 1643877.0 0.0 1.0 1183.810000 1186.320000 1172.100000 1182.220000 1643877.0 2018-02-28 1122.000 1127.65 1103.00 1103.92 2431023.0 0.0 1.0 1122.000000 1127.650000 1103.000000 1103.920000 2431023.0 2018-03-31 1063.900 1064.54 997.62 1006.94 2940957.0 0.0 1.0 1063.900000 1064.540000 997.620000 1006.940000 2940957.0 [164 rows x 12 columns] ``` A line-by-line tutorial: https://serpapi.com/blog/scrape-google-finance-ticker-quote-data-in-python/
0.85
t3_u1vwze
1,649,759,567
Python
Gufo Ping - The Python asyncio Ping library
[Gufo Ping](https://pypi.org/project/gufo-ping/) is the Python asyncio Ping library. Besides the clean and simple interface is the highly-efficient raw sockets manipulation library implemented in the [Rust](https://rust-lang.org/) language with [PyO3](https://pyo3.rs/) wrapper. Pinging is simple: Send one echo request and await for reply: ping = Ping() rtt = await ping.ping("127.0.0.1") Send a series of requests and await replies: ping = Ping() async for rtt in ping.iter_rtt("127.0.0.1", count=5): print(rtt) Gufo Ping is fast, allowing to monitor 100 000+ hosts at once. Gufo Ping is the part of the [Gufo Stack](https://gufolabs.com/products/gufo-stack/) - the battle-proven technologies which drive the [NOC](https://getnoc.com/)
0.84
t3_u1vbxb
1,649,757,278
Python
Create a Bluetooth LE repeater using Python to overcome the range limitation when transferring data
0.84
t3_u1u01z
1,649,751,499
Python
Natural syntax for units in Python
0.88
t3_u1tgt0
1,649,749,144
Python
What the Decorators in Plain Words | Python
What is a decorator in Python? Why and how should I use it? How can I simplify the debugging of decorators? How can I decorate functions with parameters? How can I pass arguments to a decorator? [This article](https://medium.com/@vlad.bashtannyk/what-the-decorators-in-plain-words-python-b600623ea497) will provide you answers to all these questions in plain words with lots of examples! Check it out now!
0.7
t3_u1tglr
1,649,749,121
Python
Instagram likes predi tor using decision tree
0.45
t3_u1qkkd
1,649,738,057
Python
'Python is like a toy programming language compared to C++'
0.14
t3_u1qbdq
1,649,736,750
Python
Porting from Windows to Linux: Python vs. Powershell?
From a search, it looks like this question comes up every couple of months and, like everything else in IT, the answer is "It depends." So, here are my depends... TL;DR - My shop is running database servers on Windows with maintenance and health check scripts written in DOS .BAT files. The company plans to migrate to cloud servers running Linux using the same database software (DB2 LUW). I want to update our scripts to a new scripting language prior to migrating and port to the new platforms when the time comes. In terms of porting between platforms, and getting a team of DBAs used to a new scripting language, would you go with Python or Powershell? Python seems easier to learn and implement, but I think PS might port better. Your thoughts? --- My shop is running database servers on Windows (not SQL Server) with the intent to migrate to cloud servers running Linux at some point in the future yet to be determined. Our database maintenance scripts are DOS .BAT files. That alone is reason enough to rewrite in a better language and, while we're at, we'll build in intelligence, restartability, health checks, logging. Not a lot of activity from the scripts themselves as they mostly run utilities and not many will run in a day or at once. My plan is to convert the DOS .BAT files to PS now and port to Linux when/if we migrate. However, I'm seeing a lot about Python and looked over some code. The pros I see for it is it seems easy to pick up and not too fussy. I also see comments on its speed and low resource consumption. Those same comments also note that speed and resources aren't an issue as long as concurrency is low, as it is in my case. How is Python in porting between OSes? In Powershell, you have to code path names using the .net objects in order to get OS-independent code. Is there a similar mechanism in Python or will things like drive names and path separator characters cause issues? Another example in PS is 'sort'. If you use the 'sort' command, it will invoke the command for that OS which may behave differently. To get OS-independence, you have to use the actual Powershell command Sort-Object. Are there similar work-arounds in Python for path names? Does Python have issues with system commands that are named the same in both OSes? Are there any other porting gotchas? EDIT to answer common questions: The DB software is DB2 from IBM. There's a mainframe version, which we run on z/OS, and an LUW version, where LUW stands for Linux/Unix/Windows. Although it runs on Windows, industry standard for DB2 LUW is to run on Linux or AIX. We're currently running DB2 LUW on Windows Servers. Job scheduling is handled on the mainframe with remote triggers to the servers to run the scripts. The scripts are running utilities like reorgs, backups, restoring backups to other servers and then sending completion or failed status back to the mainframe scheduler.
0.89
t3_u1ogz1
1,649,730,644
Python
Tuesday Daily Thread: Advanced questions
Have some burning questions on advanced Python topics? Use this thread to ask more advanced questions related to Python. **If your question is a beginner question we hold a beginner Daily Thread tomorrow (Wednesday) where you can ask any question! We may remove questions here and ask you to resubmit tomorrow.** This thread may be fairly low volume in replies, if you don't receive a response we recommend looking at r/LearnPython or joining the Python Discord server at [https://discord.gg/python](https://discord.gg/python) where you stand a better chance of receiving a response.
0.6
t3_u1lfq8
1,649,721,611