Join devRant
Do all the things like
++ or -- rants, post your own rants, comment on others' rants and build your customized dev avatar
Sign Up
Pipeless API
From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple API
Learn More
Search - "def ()"
-
!Rant
Thought this was kind of funny for us lady devs/programmers, and something we can relate to.
The lady in the image is an engineer/programmer and is getting married but doesn't have any girlfriends (since she works in a mostly male oriented field, like us). So instead of having female bridesmaids she had her close brogrammers / college classmates stand up in her wedding with her. I mean, it was probably less drama, anyways! 😂
I'm the only girl on my team so I def relate!
*not my pic*26 -
Started being a Teaching Assistant for Intro to Programming at the uni I study at a while ago and, although it's not entirely my piece of cake, here are some "highlights":
* students were asked to use functions, so someone was ingenious (laughed my ass off for this one):
def all_lines(input):
all_lines =input
return all_lines
* "you need to use functions" part 2
*moves the whole code from main to a function*
* for Math-related coding assignments, someone was always reading the input as a string and parsing it, instead of reading it as numbers, and was incredibly surprised that he can do the latter "I always thought you can't read numbers! Technology has gone so far!"
* for an assignment requiring a class with 3 private variables, someone actually declared each variable needed as a vector and was handling all these 3 vectors as 3D matrices
* because the lecturer specified that the length of the program does not matter, as long as it does its job and is well-written, someone wrote a 100-lines program on one single line
* someone was spamming me with emails to tell me that the grade I gave them was unfair (on the reason that it was directly crashing when run), because it was running on their machine (they included pictures), but was not running on mine, because "my Python version was expired". They sent at least 20 emails in less than 2h
* "But if it works, why do I still have to make it look better and more understandable?"
* "can't we assume the input is always going to be correct? Who'd want to type in garbage?"
* *writes 10 if-statements that could be basically replaced by one for-loop*
"okay, here, you can use a for-loop"
*writes the for loop, includes all the if-statements from before, one for each of the 10 values the for-loop variable gets*
* this picture
N.B.: depending on how many others I remember, I may include them in the comments afterwards19 -
Python is so ridiculously easy and fast to write, I'm just waiting for the release where you just say:
def main():
make_program("RegExParser", "fast", "fancy")
And that's it...15 -
First rant, so here goes:
def initialize
@rant = 'when the contractor your boss brought in to help, whose weekly rate exceeds your monthly salary, doesn't know the difference between server side and client side technologies.'
end5 -
I wrote a database migration to add a column to a table and populated that column upon record creation.
But the code is so freaking convoluted that it took me four days of clawing my eyes out to manage this.
BUT IT'S FINALLY DONE.
FREAKING YAY.
Why so long, you ask? Just how convoluted could this possibly be? Follow my lead ~
There's an API to create a gift. (Possibly more; I have no bloody clue.)
I needed the mobile dev contractor to tell me which APIs he uses because there are lots of unused ones, and no reasoning to their naming, nor comments telling me what they do.
This API takes the supplied gift params, cherry-picks a few bits of useful data out (by passing both hashes by reference to several methods), replaces a couple of them with lookups / class instances (more pass-by-reference nonsense). After all of this, it logs the resulting (and very different) mess, and happily declares it the original supplied params. Utterly useless for basically everything, and so very wrong.
It then uses this data to call GiftSale#create, which returns an instance of GiftSale (that's actually a Gift; more on that soon).
GiftSale inherits from Gift, and redefines three of its methods.
GiftSale#create performs a lot of validations / data massaging, some by reference, some not. It uses `super` to call Gift#create which actually maps to the constructor Gift#initialize.
Gift#initialize calls Gift#pre_init (passing the data by reference again), which does nothing and returns null. But remember: GiftSale inherits from Gift, meaning GiftSale#pre_init supersedes Gift#pre_init, so that one is called instead. GiftSale#pre_init returns a Stripe charge object upon success, or a Gift (and a log entry containing '500 Internal') upon failure. But this is irrelevant because the return value is never actually used. Pass by reference, remember? I didn't.
We're now back at Gift#initialize, Rails finally creates a Gift object using the args modified [mostly] in-place by all of the above.
Another step back and we're at GiftSale#create again. This method returns either the shiny new Gift object or an error string (???), and the API logic branches on its type. For further confusion: not all of the method's returns are explicit, and those implicit return values are nested three levels deep. (In Ruby, a method will return the last executed line's return value automatically, allowing e.g. `def add(a,b); a+b; end`)
So, to summarize: GiftSale#create jumps back and forth between Gift five times before finally creating a Gift instance, and each jump further modifies the supplied params in-place.
Also. There are no rescue/catch blocks, meaning any issue with any of the above results in a 500. (A real 500, not a fake 500 like last time. A real 500, with tragic consequences.)
If you're having trouble following the above... yep! That's why it took FOUR FREAKING DAYS! I had no tests, no documentation, no already-built way of testing the API, and no idea what data to send it. especially considering it requires data from Stripe. It also requires an active session token + user data, and I likewise had no login API tests, documentation, logging, no idea how to create a user ... fucking hell, it's a mess.)
Also, and quite confusingly:
There's a class for GiftSale, but there's no table for it.
Gift and GiftSale are completely interchangeable except for their #create methods.
So, why does GiftSale exist?
I have no bloody idea.
All it seems to do is make everything far more complicated than it needs to be.
Anyway. My total commit?
Six lines.
IN FOUR FUCKING DAYS!
AHSKJGHALSKHGLKAHDSGJKASGH.7 -
ARGH. I wrote a long rant containing a bunch of gems from the codebase at @work, and lost it.
I'll summarize the few I remember.
First, the cliche:
if (x == true) { return true; } else { return false; };
Seriously written (more than once) by the "legendary" devs themselves.
Then, lots of typos in constants (and methods, and comments, and ...) like:
SMD_AGENT_SHCEDULE_XYZ = '5-year-old-typo'
and gems like:
def hot_garbage
magic = [nil, '']
magic = [0, nil] if something_something
success = other_method_that_returns_nothing(magic)
if success == true
return true # signal success
end
end
^ That one is from our glorious self-proclaimed leader / "engineering director" / the junior dev thundercunt on a power trip. Good stuff.
Next up are a few of my personal favorites:
Report.run_every 4.hours # Every 6 hours
Daemon.run_at_hour 6 # Daily at 8am
LANG_ENGLISH = :en
LANG_SPANISH = :sp # because fuck standards, right?
And for design decisions...
The code was supposed to support multiple currencies, but just disregards them and sets a hardcoded 'usd' instead -- and the system stores that string on literally hundreds of millions of records, often multiple times too (e.g. for payment, display fees, etc). and! AND! IT'S ALWAYS A FUCKING VARCHAR(255)! So a single payment record uses 768 bytes to store 'usd' 'usd' 'usd'
I'd mention the design decisions that led to the 35 second minimum pay API response time (often 55 sec), but i don't remember the details well enough.
Also:
The senior devs can get pretty much anything through code review. So can the dev accountants. and ... well, pretty much everyone else. Seriously, i have absolutely no idea how all of this shit managed to get published.
But speaking of code reviews: Some security holes are allowed through because (and i quote) "they already exist elsewhere in the codebase." You can't make this up.
Oh, and another!
In a feature that merges two user objects and all their data, there's a method to generate a unique ID. It concatenates 12 random numbers (one at a time, ofc) then checks the database to see if that id already exists. It tries this 20 times, and uses the first unique one... or falls through and uses its last attempt. This ofc leads to collisions, and those collisions are messy and require a db rollback to fix. gg. This was written by the "legendary" dev himself, replete with his signature single-letter variable names. I brought it up and he laughed it off, saying the collisions have been rare enough it doesn't really matter so he won't fix it.
Yep, it's garbage all the way down.16 -
@dfox
!rant, it's the Feature request
Possibility to post `a code snippet with monospaced font` would be usefull.
Or even
```
def multiline_code():
from 2 to Inf:
"Lines of code"
```
Sth like in markdown.9 -
If you haven't seen the video instructions for how to factory reset GE's smart light bulbs.
STOP WHAT YOU ARE DOING AND WATCH: https://youtube.com/watch/...
Theres also a twitter thread about this which includes screenshots of their instructions on how to count 2 seconds: https://twitter.com/NumbersMuncher/...
This is what happens when you hire a product manager with no experience and put them in charge of engineering, design, UX (who we kidding they def don't have one of these) etc. This is just magical16 -
define every function like this:
def function ( arg ) :
instead of
def function(arg):
bit of a nitpick I know. but when I asked her about it she said "convention" and when I asked which convention she replied with "the only one in existence"
so I was triggered by that for sure28 -
What's up with guys and girls using the 'def' word? It's like they're speaking Python.
guy: "sup babe. Wanna grab coffee later?"
girl: "def baby"8 -
class devRant_member:
def __init__(self, name):
self.name = name
def say_hi(self):
print( "Hello world, I'm ", self.name)
p = devRant_member("Blacksteel")
p.say_hi()6 -
"We use WSDL and SOAP to provide data APIs"
- Old-fashioned but ok, gimme the service def file
(The WSDL services definition file describes like 20 services)
- Cool, I see several services. In need those X data entities.
"Those will all be available through the Data service endpoint"
- What you mean "all entities in the same endpoint"? It is a WSDL, the whole point is having self-documented APIs for each entity format!
"No, you have a parameter to set the name of the data entity you want, and each entity will have its own format when the service return it"
- WTF you need the WSDL for if you will have a single service for everything?!?
"It is the way we have always done things"
Certain companies are some outdated-ass backwater tech wannabees.
Usually those that have dominated the market of an entire country since the fucking Perestroika.
The moment I turn on the data pipeline, those fuckers are gonna be overloaded into oblivion. I brought popcorn.7 -
Everyone talks about their hate of js but like python is honestly just as bad.
- shitty package manager,
* need to recreate python environments to keep workflows seperate as oppose to just mapping dependencies like in maven, npm, cargo, go-get
* Can't fix python version number to project I.e specify it in requirements
- dynamic typing that gets fixed with shitty duck typing too many times
- no first class functions
- limited lambda expressions
- def def def
- overly archaic error messages, rarely have I gotten a good error message and didn't have to dive into package code to figure it out
- people still use 2.7 ... Honestly I blame the difficulty of changing versions for this. It's just not trivial to even specify another python version
- inconsistent import system. When in module use . When outside don't.
- SLOW so SLOW
- BLOCKING making things concurrent has only recently got easier, but it still needs lots of work. Like it would be nice to do
runasync some_async_fcn()
Or just running asynchronous functions on the global scope will make it know to go to some default runtime. Or heck. Just let me run it like that...
- private methods aren't really private. They just hide them in intelisense but you can still override them....
I know my username is ironic :P11 -
I have this one chick on Twitter that she used to be a fellow classmate of mine while I was going for my Bachelors degree.
She would always bitch and complain about how the teachers we had were horrible at teaching. I had to interact with her because of one assignment and EVERYONE in the team was good and well with the items, we finished it rather quick (build a terminal emulator) and we were just thinking about ways to make it look cooler. It was challenging to be honest, but everyone was so interested in it and had all the materials requires plus a very nice instructor to go with that would be overly happy to answer questions and provide additional content, the instructor in question made no book requirement for the class and provided instead free resources, be it video content or his own code on the matter to make sure that everyone got it.
Dude was amazing (most of my university instructors were truly fascinating or people that had worked for very interesting projects) and so when she complain that the guy "had no idea how to teach" I decided to investigate a little.
You see, she had NEVER taken any consideration that maybe you should advance your studies in the field, particularly in programming, by doing your own fucking research. No, the professor is not supposed to hold your fucking hand while you are trying to understand how a fucking function IN FUCKING PYTHON works, dude gave a full length lecture and the only retard that did not understood the topic: was you. He went to you to help you and instead you gave the man an attitude because for some fucking reason he was accounted for your own fucking stupidity. Motherfucker was there for more than 30 minutes trying to explain to this dumb chick the nuances of def hello(): return "hey there" and for some fucking reason you were too daft to understand that.......
The chick complained to us in the team how because of work she had NO time whatsoever to dedicate to reading programming or general software engineering materials......yet her twitter was FULL of book reviews concerning novels and self help books and bullshit like that.
If you are like that, and blame it on your teachers: fuck-you.
To this day she still bitches about the teachers from time to time, I legit told her once that she had no business attending a C.S degree.
Do you think you can get into Julliard without ever touching a fucking instrument? no. Do you think you can tell some Terence Fletcher-throwing-a-chair-at-your motherfucker to show you how to position your hands on a drumstick or what keys to press on a piano? FUCK NO.
If you were being DAFT on a ProGraMmiNg101 for which they picked Python to be the language to use and blamed your fucking stupidity to a teacher then yet again: FUCK-YOU6 -
Ok might as well share my misadventure on a phone screen:
It started pretty normal, the guy talks about his background, the position, and asked me about my background.
Move on to the language trivia; I’m not good at memorizing language features, but I guess it’s what people want, so I’ll be working on that down the road… Anyways it didn’t go well, and the guy somehow made me feel like an idiot even on the questions I got right.
It’s really awkward at this point… but let me tell you I was not prepared for what I can only describe as the fucking coding portion of the phone screen…
No computer. No pencil or paper. No whiteboard. Over the phone I’m saying: “class Dog with a capital ‘D’ colon newline tab def space bark open parentheses close parentheses….”
what the actual fuck4 -
Hey everyone. I decided to rewrite python's abs() function, as it's really slow. Here is my new and improved version. It's up to 500% faster!!!
def abs(int=None):
if not int is None:
try:
lnt = math.sqrt(int);
lnt = math.pow(lnt, 2);
return lnt;
except Exception as E:
lnt = int/-1;
return lnt;
else:
raise ValueError("oopsie whoopsie! uwu we made a fucky wucky!!1 a wittle fucko boingo! the code monkies at our headquarters are working VEWY HAWD to fix dis!!");
Edit: devrant fucked up the indention.
Here is a hastebin instead:
https://hastebin.com/iyajuyoxuq.pl7 -
TIL that Python's "everything is an object" mentality allows you to do
def some_function():
some_function.variable = "abc"
print(some_function.variable)
> abc9 -
A new mathematical constant was discovered recently: Bruce's constant
I took some code from the paper and adapted it in python.
def bruce(n):
J = log(n, 1.333333333333333) / log(n, 2)
K = log(n, 1.333333333333333) / log(n, 3)
return ((J+K)-e)+1
gives e everytime for ((J+K)-bruce)+1, regardless of the value of n.
bruce can always be aproximated with the decimal 4.5, telling you how close n can be used to aproximate e (usually to two digits).
Bruce's constant is equal to 4.5099806905005
It is named after that famous mathematician, bruce lee.
You'll start with four limbs and end up with two in a wheelchair!6 -
Want maximum efficiency in python?
def say(text):
print(text)
You save 2 keypresses everytime you print16 -
An interesting python function I just made. Probably not the first to do so.
def printf(fmt, *args):
print(fmt, args, end="")9 -
I wrote this code last month...
def func(is_admin, user):
is_admin = is_admin or False
user = user # so pro much wow
return is_admin ^ user4 -
require "universe"
require "bioDan"
class ProductManager
def initialize(person_type)
@ideas = Universe.import_random_ideas({ mostly_shitty: true, association: person_type })
life_purpose
end
def life_purpose
@ideas.find_each do |idea|
bioDan.interrupt! unless bioDan.bad_mood?
bioDan.queue << idea
end
end
end
ProductManager.create "enthusiastic prick"
%x[crontab -e "0 09 * * * ruby this_script.rb > /dev/null"]
# 😥7 -
Ever wanted to have undefined behavior in Python? Do this in Python 2 (yes this was supposed to be a fibonacci number calculator with a limit but one of my classmates forgot the conversion just as seen below):
#Begin
def fib(n):
a,b=0,1
while a<n:
print a
a,b=b,a+b
fib(raw_input)
#End3 -
been a couple of years since I was last active here.
Source Engine still has its claws on me today - but Nii broke free and properly got into other engines and made some cool projects! We both study different stuff now.
I tried to get into Unity a couple of times now, even made a small VR grappling hook prototype once (def not nauseating). But it's hell. It's kinda sad that modern engines don't understand the needs of level designers as well as Source's Hammer. Even though Source is outdated af.
Thing is, I am more and more starting to doubt that this is what I wanna do in life. Game industry sucks. Ad industry sucks even more. I might just become a tree and produce oxygen.2 -
Just found this awesome function in the old commits.
def clean_cache():
'''
This function cleans the stored cache in every update. Make sure to call it before every feature addition.
'''
print 'Cache is cleared. '
return2 -
I got my dirty fingers on this leak of an AMAZING ML model capable of pondering EVERY PARAMETER IN THE UNIVERSE and saying if your business idea needs improvement or is good to go.
BEHOLD THIS 100% PURE PYTHON SOLUTION:
```python
import random
def magic(*args, **kwargs):
if random.random() > 0.5:
return "Good to go!"
else:
return "Requires improvement on value proposition"
```
This LEAK is from a startup that just received 4 BILLION USD IN VENTURE CAPITAL to improve their AI SYSTEMS.
Literally enough money to solve world hunger forever.
Who else is gonna invest in NEW THERANOS ADVANCED A.I. RESEARCH INTERNATIONAL INC?8 -
!rant && 'suggestion'
What if we write cook book in pseudo code (or official development languages) instead of plain english so dumb fuck that can't follow a simple instruction like me could actually make something nice?
def mayonnaise:
mayonnaise = random.shuffle(['yolk', 'salt', 'pepper', 'mustard', 'vinegar'])
while(mayonnaise not "thick"):
mayonnaise.whip()
mayonnaise.append('olive oil')
mayonnaise.append('seasoning' || 'lemon juice')6 -
Here’s how my Friday night is going:
def signin
if should_not_sign_user_in?(stuff)
return redirect_to :nope
end
# signin logic
end
The guard says I shouldn’t sign the user in. It logs the details of why. I read the logs; they’re all correct. It logs the return value, which is false, and the user gets signed in anyway.
Wat.
There’s a return and a redirect there!
This is only happening on the QA server, too, so something fishy is going on.5 -
def sayHiToColleagues():
for colleague in colleagues:
if colleague.roomNr > me.roomNr:
break
sayHi(colleague.name)6 -
# source_code.py
crawler.do_abstracted_operation_on_a_count_variable_in_crawler_for_when_new_page_is_added_and_ready_to_be_parsed_i_love_abstraction()
# crawler.py
def do_abstracted_operation_on_a_count_variable_in_crawler_for_when_new_page_is_added_and_ready_to_be_parsed_i_love_abstraction(self):
self.count += 18 -
!dev
So, here I am browsing steam for something new to play.
Thanks kwilliams for a solid 30 hours of gameplay 🤘
But anyway, I was just scrolling through and came across and old gem.
https://store.steampowered.com/app/...
And it got me thinking, if anyone else used to play this old bad boi around here.
It's not High Def or modern, although it does 1920x1080, but damn it's a trip down nostalgic lane.2 -
python machine learning tutorials:
- import preprocessed dataset in perfect format specially crafted to match the model instead of reading from file like an actual real life would work
- use images data for recurrent neural network and see no problem
- use Conv1D for 2d input data like images
- use two letter variable names that only tutorial creator knows what they mean.
- do 10 data transformation in 1 line with no explanation of what is going on
- just enter these magic words
- okey guys thanks for watching make sure to hit that subscribe button
ehh, the machine learning ecosystem is burning pile of shit let me give you some examples:
- thanks to years of object oriented programming research and most wonderful abstractions we have "loss.backward()" which have no apparent connection to model but it affects the model, good to know
- cannot install the python packages because python must be >= 3.9 and at the same time < 3.9
- runtime error with bullshit cryptic message
- python having no data types but pytorch forces you to specify float32
- lets throw away the module name of a function with these simple tricks:
"import torch.nn.functional as F"
"import torch_geometric.transforms as T"
- tensor.detach().cpu().numpy() ???
- class NeuralNetwork(torch.nn.Module):
def __init__(self):
super(NeuralNetwork, self).__init__() ????
- lets call a function that switches on the tracking of math operations on tensors "model.train()" instead of something more indicative of the function actual effect like "model.set_mode_to_train()"
- what the fuck is ".iloc" ?
- solving environment -/- brings back memories when you could make a breakfast while the computer was turning on
- hey lets choose the slowest, most sloppy and inconsistent language ever created for high performance computing task called "data sCieNcE". but.. but. you can use numpy! I DONT GIVE A SHIT about numpy why don't you motherfuckers create a language that is inherently performant instead of calling some convoluted c++ library that requires 10s of dependencies? Why don't you create a package management system that works without me having to try random bullshit for 3 hours???
- lets set as industry standard a jupyter notebook which is not git compatible and have either 2 second latency of tab completion, no tab completion, no documentation on hover or useless documentation on hover, no way to easily redo the changes, no autosave, no error highlighting and possibility to use variable defined in a cell below in the cell above it
- lets use inconsistent variable names like "read_csv" and "isfile"
- lets pass a boolean variable as a string "true"
- lets contribute to tech enabled authoritarianism and create a face recognition and object detection models that china uses to destroy uyghur minority
- lets create a license plate computer vision system that will help government surveillance everyone, guys what a great idea
I don't want to deal with this bullshit language, bullshit ecosystem and bullshit unethical tech anymore.11 -
I've spent many years in a bubble of 1 backend lang.. but when i started checking out other langs, I got very annoyed that each one has same basic stuff but with different syntax... Can we just agree on something? Ffs!
We really couldnt come up with unified syntax for -
false, False FALSE
OR or ||
def func function
And dont get me started on all the variations of for loops... Its like we are trying make our life hard
Looking at new versions of some langs, looks like they are copying new stuff from one another.. with different syntax.. thanks!
Nodejs trying to look more like she doesnt have callbacks.. while other langs adding callback functionality... Why why why?!2 -
#on a mission ;)
def vacations_started_yay():
devrant.uninstall()
for i in range(60):
if(i%7==0):
devrant.install()
elif(i%8==0 ):
devrant.uninstall()3 -
When you are helping another dev on their machine and they don't have caps lock set to <esc>
def replace
5DD:WQ
end -
Def not dev oriented.
I am a huge fan of trading card games. It started with Yu Gi Oh, moved on to Magic, even tried, LoTR when it was a thing, tried algo Star Wars the original CCG (loved it), Duel Masters (when it was still in the U.S) Pokemon (of fucking course) and other more uncommon ones like Cardfight Vanguard, tried latino only games (Mitos y leyendas, Myths & Legends, this one is king on my list) and Flesh & Blood. But as a mexican kid, I was always a fan of fucking dragon ball, like most mexican kids.
SO I bought some cards from the newest game expansion. the owner of the TCG/anime store told me that if I was willing to play that I should hang out on tuesdays.
So, learning the rules of the game, and wanting to play with other people, I went there on a tuesday.
The MTG people were there fighting amongst themselves for some reason. the Pokemon people were there also, just opening packs without playing. A rather large table was there with a bunch of people playing a game that I did not recognize. And then there was me. I was chilling on my phone thinking that the DB dudes would show up eventually. nothing, so I just sat there waiting.
Suddenly a dude comes to the large table and starts pairing people for a "tournament" and once they are all sited he notices that 1 is missing, he walks up to me holding a store app and asks me "sorry bro, are you here to play with us by any chance?" to which I say "I do not think so, I came here for DB but I don't know what you guys are playing"
The dude looks down on his app, somehow actually sad and says "man I do play DB, but I don't think I have my cards with me, maybe, let me see" and he goes on to see if he brought something.
This was green flag n 1. the dude wanted to just play something with someone. And was doing something to not LEAVE someone behind. then quick as hell another says "well, why don't we give him a deck and he can play with us! we can teach him!" and I say "well what are you lads playing?" and he says "digimon man you like the anime? a new release came about! it's sick man it would be awesome if you play!"
Second green flag, another member of that community was happy for the idea of increasing the membership and actively did something to increase the population.
So, I hanged out with them. Close knit group, all friends from a long time, but willing to take an unfamiliar (and rather handsome) face with them.
My face when (MFW) the DB dudes where not there, so the digimon group adopted me.
I know have over.....2000 cards, most of them were gifted to me by them after they saw my chops and tough me how to play, by graciously lending me their decks.
This my lads, is what humanity is about. We got close fast, it has been 2 weeks of just chilling with them at the game lounge, just nice people, all of them really. Not a single angry moment or anything, you pull a crazy combo on them and they legit sheeeeeeeesh and applaud them, they don't care about loosing, they just want to have a good time, and this, this is a good crowd to be at.
Strive to make people feel welcomed. Being nice to others, taking a chance on people you deem to be ok, is fine really. It is rather cool. Anyone can be a salty asshole, but it takes a real king to be nice to others just for the sake of having a good time.
These dudes, they are gold. And I finally have something to take my mind away from work and other things that increase my anxiety and stress. I would much rather be there shooting the shit with the lads and playing games than at home, drinking the night away to relieve stress.
Kings3 -
class Bug():
def __init__():
self._fix = random.randint(1, 6)
def fix():
if self.is_feature :
return Feature(self)
else:
if random.randint(1, 6) == self._fix:
Bug()
del self
else:
return Bug() -
++ if you've ever had to type something along these lines:
def main(args):
do = some
stuff = here
if __name__ == '__main__':
main()
trying to figure out the best way to write a driver script for a processing pipeline and the choices have boiled down to;
a) define "new" main functions where necessary
b) learn subprocess module
c) write a bash script to do it instead
still not sure what I'm going with... -
Class constantEnergyStruggle():
def energyLevel(self):
while work.working():
drainEnergy()
while work.dayOff:
thinkAboutWork()
drainEnergy()
while dreaming:
thinkAboutWork()
drainEnergy() -
heres something interesting:
The golden ratio is 1.618...
If you're not familiar with it, doing 1/goldenratio
the result is 0.618...
It gives you back the float component exactly.
Discovered that it is actually part of a series.
First of all:
2-(((5-sqrt(5))/2)-1) =
1.618033988749895 -> thats our golden ratio
In other words:
(2%gold) =
0.381966011250106
While:
((5-sqrt(5))/2) =
1.381966011250105
Ok, now we're getting somewhere. We can turn these into variables
First of all, lets see if we can get the golden ratio back out:
2-(((5-sqrt(5))/2)-1) = 1.618033988749895
Okay good.
The formula looks something like
j-(((i-sqrt(i))/2)-1)
Where j = (i*2)+1
That means we can easily figure out what j we need from our i value. (i-1)/2 = j
We run it back far enough we get
1-(((3-sqrt(3))/2)-1) =
1.3660254037844386
Thats the golden ratios little brother. Doesn't look anything like it, but it is part of the series.
And I found a boat load of research documents scattered *all* over the net, where this number and others in the series inexplicably crop up in power series, in chemistry, and elsewhere. Just looks like random floats if you don't know better.
We can actually go lower in the series:
0.5-(((2-sqrt(2))/2)-1)
1.2071067811865475
At the lowest positive value for j, we get
0-(((1-sqrt(1))/2)-1) = 1
It's kinda elegant.
I even wrote a little script to do the conversions:
def gr(k):
....i = k
....j = (i-1)/2
....return j-(((i-sqrt(abs(i)))/2)-1)
The dots are so devrant doesn't break pythons formatting.3 -
InitiativeQ is a new currency built by ex-PayPal guys and they're currently giving it away free...Unlike the cryptos you've lost a bunch of money on! If you play the lotto or buy cryptos, you should def. get on board with this. All you need to provide is name and email and they promise not to sell your email address or bug you with spam emails.
By invite only: https://lnkd.in/ei5HBhZ27 -
I am working on an AoK bot. It worked before but now it fails on me. It says: {'success': False, 'error': 'Invalid comment.'}
I don't know why.
This is the comment: "@retoor debugsemiss everything and nave the and resorts they're not paying much to clean a fucking roomic lolg creating of my phoprooting such is the quoting this kidle... Noh ot inuforian times fined the apposivy suistlondlan't by imprymarbygind. Metwary nate ?"
Call method:
```
async def post_comment(self, rant_id, text):
payload = dict(
rant_id=rant_id,
comment=text
)
payload.update(self.auth_params)
async with self.session.post(f'/api/devrant/rants/{rant_id}/comments',data=payload, params=self.auth_params) as resp:
print(await resp.json())
```
Someone has an idea why it's failing? Also tried it with hardcored rant_id and message.23 -
StackOverflow locked my account. I'm hoping someone here might be kind enough to help me with a bash script I'm "bashing" my head with. Actually, it's zsh on MacOS if it makes any difference.
I have an input file. Four lines. No blank lines. Each of the four lines has two strings of text delimited by a tab. Each string on either side of the tab is either one word with no spaces or a bunch of words with spaces. Like this (using <tab> as a placeholder here on Devrant for where the tab actually is)
ABC<tab>DEF
GHI<tab>jkl mno pq
RST<tab>UV
wx<tab>Yz
I need to open and read the file, separate them into key-value pairs, and put them into an array for processing. I have this script to do that:
# Get input arguments
search_string_file="$1"
file_path="$2"
# Read search strings and corresponding names from the file and store in arrays
search_strings=()
search_names=()
# Read search strings and corresponding names from the file and store in arrays
while IFS= read -r line || [[ -n "$line" ]]; do
echo "Line: $line"
search_string=$(echo "$line" | awk -F'\t' '{print $1}')
name=$(echo "$line" | awk -F'\t' '{print $2}')
search_strings+=("$search_string")
search_names+=("$name")
done < "$search_string_file"
# Debug: Print the entire array of search strings
echo "Search strings array:"
for (( i=0; i<${#search_strings[@]}; i++ )); do
echo "[$i] ${search_strings[$i]} -- ${search_names[$i]}"
done
However, in the output, I get the following:
Line: ABC<tab>DEF
Line: GHI<tab>jkl mno pq
Line: RST<tab>UV
Line: wx<tab>Yz
Search strings array:
[0] --
[1] ABC -- DEF
[2] GHI -- jkl mno pq
[3] RST -- UV
That's it. I seem to be off by one because that last line...
Line: wx<tab>Yz
never gets added to the array. What I need it to be is:
[0] ABC -- DEF
[1] GHI -- jkl mno pq
[2] RST -- UV
[3] wx -- Yz
What am I doing wrong here?
Thanks.17 -
class test:
def __init__(self, x):
self.x=x
def printer (self):
print self.x
class new(test):
def __init__(self, y, z):
test.__init__(self, y)
self.y=z
def printer (self):
test.printer(self)
print self.x
super(new, self).printer()
print self.y
N1=new(1,2)
N1.printer()
Is this correct in all respects ??
If erroneous, where ??3 -
class Rant(Speech):
def __init__(self, topic, audience):
self.topic = topic
self.audience = [x for x in audience if x.mood = moods[bored]]
devRant = Rant("wtf?", devs)3 -
My boss writes code like this:
def someFunction (someArg: String) = ...
Who does that?! A space? Da fuck?! And it's all over the code base. Whenever another dev touches any of his stuff, we correct it:
def someFunction(someArg: String) = ...
The way god intended it!8 -
def best and worst dev experience from 2016 was a 4 week advanced dev boot camp for work. it was a smaller classroom with about 20 experienced devs in it. it was bright in there. a lot of strong minds backed by strong opinions and even loud voices at times, these are devs after all(so picture that for 1 month straight, 8 hr days). first 2 weeks was all new stuff. it was like a waterfall on head. I kept getting paired with weakest person in the camp for the weekly clone projects which didn't help matters for me or her. after the second week I started to grasp what we were doing and they started mixing up the groups. by the last week most everyone in the camp had learned so much, we had come so far we all kinda bonded through the experience. the final projects Imo were all very impressive. we were all pretty proud of ourselves I'd say. I never learned so much in such a short period of time. immersive training is the only way to go. those week long standard lecture lab workbook tech training courses are weak!! u wanna learn something, u gotta get in there and get dirty with it.1
-
Day 3 as the Junior Dev.
Co worker fucks every time on defining functions in python
What my asshole teammate does is:
def someShitFunc():
print(shit)
And he was clearly instruct to return value not print the value what a jerk he is.
I have to fix his all problems and in meeting he brags how his code worked. What a sucker.4 -
def haveNiceDay(){
while code.works():
if frustration == true:
game.play()
food.eat()
keepCoding()
if error.notResolved():
while giveup!= false:
screen.stare()
} -
class Me(Person):
def day(self, mood):
self.morning()
self.job.start()
while True:
if self.job.time > 28800:
break
self.job.work()
self.job.end()
self.afternoon()
self.evening()
def morning(self):
self.say("Hello World!")
if mood == bad:
self.be_grumpy()
self.__super__.morning()5 -
AHH!!! PM talk is melting my brain...nodes are...collapsing...
"We need to post-mortem our lessons learned and level set our expectations so we can define quick resolutions and set tollgate approvals, at a very high level."
# clear my head of beastly things
def cls():
print ('\n' * 666)
cls()1 -
Class normal people:
Def good day:
"Manager was out, had great lunch, got a. special someone's number, successfully avoided traffic, got in special someone's pants"
Def bad day:
"Stubbed toe this morning, rained all day, broke up w. special someone, sat in traffic for 2 hrs"
Class software dev:
Def good day:
"Wrote lots of working code, little to no bugs, checked in no-probs, ahead od schedule for ship, extra time for ping-pong!"
Def bad day:
"Somone fucked up the latest build, coffee machine's broken, ran out of adderall, manager on everyone's @$$ for a fix, 5 hrs later...no fix, no blames, no coffee, board meeting; fml" -
The recent USB C/ no headphone-jack rant inspired me a bit and I noticed that two USB C ports might be a solution for me in regards to the headphone debate.
I'd still need a dongle for my headphones, but I can still charge.
Maybe I could get a audiophile grade dongle make myself def, that be great.
It would also be kind of useful for other stuff, you can't have enough usb ports on any device.
And then I started looking into that topic.
WTF one plus! Why did you make my op 3T USB 2.0 in type C !!!????
I'm not that stupid though. I know there are reasons, but this just upsets me, 3.0 at least please!
What is missing for you that you could use your phone instead of a PC for the most workloads of use-cases?
For me it's two high speed usb C ports with display connect capabilities + periferals.
I currently think that it would be a great thing to move most Noob users off their pcs onto their smartphones for that purpose.1 -
Since I started the process has been something like this:
def new_project():
Have an idea;
for implementation in idea:
search("how to/
{implementation}");
if idea.works():
me.celebrate()
else:
me.die_a_bit_inside() -
So I applied for a Cloud Architect position. The process was very intensive. Roughly 6 interviews, 2 practical assignments and a written exam. In total it took me 3 weeks to go through the screening process. I aced everything, and was told they were going to send me an offer. I received an email on the 21st of April asking me if I was still interested. I replied back immediately saying I was most def interested. The next morning I get an email back from the hiring manager, who happened to CC the client as well, saying I took too long to reply to the offer, and the job was filled. I was perplexed as to how I took too long to reply. I went through the email chain that the client also received, and saw the hiring manager changed the email headers in the reply chain from the 21st of April, to the 12th of April. So it made out that I did indeed take too long and the client went with someone else! WTF! Very unprofessional, but very little I could do.. I wasted a lot of time and energy and heartache with this!4
-
So I needed a break from all the straight computer logic for days... so i figured i had 2 options, argue with chatGPT or go back to a dating app.
I chose the latter.
Im ocd with notifs... i NEED the bubble to be gone.
Found this gem...
"Hey beautiful Sara ;) my names is James king it very nice 2 meet u wow u look like a angel that fall from heaven 😘u mind me of a rose because how beautiful you are am how beautiful the rose is am I the best guy on badoo that u would ever talk with on badoo I actually look for Friendship and relationship ;) how are u today am wyd"
So... because im curious, esp when it comes to perplexing linguistics... im def gonna ask if English is his 1st language.
Normally i can tell within a sentence or 2... even tend to know their native tongue by then... this one has me stumped.
Anyone wanna guess if hes a native English speaker???
Maybe ill make a modest prize poolif there's a few entrants.
(he has plenty of pics so ill be able to legally find out in a few min... but ill wait til i dont get a response for a week)
Ill probably make a script to strip out the auto-messages... replying with an auto ofc... and the mundane crap that shows they definitely didnt go beyond the pics.13 -
I'm working with an xml schema that effectively emulates xml... inside xml...
It looks like this
<child>
<tag>ABC</tag>
<value>DEF</value>
</child>
I don't event want to get started on how it handles child elements.
This is some next level abstraction hell.
And it's not like it can't use normal XML tags. In other parts of the project it uses a slightly more sane schema.5 -
Def processCurrentDay(work):
If work.field == "retail":
While work.status == "unsatisfactory":
Work.do_work_things()
If work.status
=="exceptional":
Society.bioengineerFlyPigs()
else:
processCurrentDay(work) -
If got this code with the 20second sleep statement. And I am not really sure if it is a good idea to have it ...
def start_instance(self):
instance=self.ec2.Instance(self.iId)
instance.start()
while instance.state['Name'] != 'running':
sleep(5)
instance=self.ec2.Instance(self.iId)
sleep(20) #Let's sleep another 20 for the server to be really up
return instance.state
Can I have some advice regarding best practices?3 -
Change the main backbone of an application (2 - 3 weeks) in order to facilitate the upgrade of the application from AngularJS to Angular (which they tell us is going to happen...eventually) or, rewrite the application (~4 months) in Angular. What arguments should we be using to get the rewrite? Our pleas are falling upon def ears.3
-
(I'm not completely sure of what I'm saying here, so don't take this too seriously)
Settling on a language to write the api for ranterix is hard.
I'm finding a lot of things about elixir to be insanely good for a stable api.
But I'm having a lot of gripes with the most important elixir web framework, phoenix.
Take a look at this piece of code from the phoenix docs:
defmodule Hello.Repo.Migrations.CreateUsers do
use Ecto.Migration
def change do
create table(:users) do
add :name, :string
add :email, :string add :bio, :string
add :number_of_pets, :integer
timestamps()
end
end
end
Jesus christ, I hate this shit.
Wtf are create, add and timestamps. Add is somehow valid inside the create, how the fuck is that considered good code? What happens if you call timestamps twice? It's all obscure "trust me, it works" code.
It appears to be written by a child.
js may have a million problems. But one thing I like about CJS (require) or ESM (import) is that there's nothing unexplained. You know where the fuck most things come from.
You default export an eatShit() function on one file and import it from another, and what do you get?
The goddamn actual eatShit function.
require is a function the same way toString is a function and it returns whatever the fuck you had exported in the target file.
Meanwhile some dynamic langs are like "oh, I'll just export only some lang construct that i expect you to specify and put that shit in fucking global of the importing file".
Js is about the fucking freedom. It won't decide for you what things will files export, you can export whatever the fuck you want, strings, functions, classes, objects or even nothing at all, thanks to module.exports object or export statement.
And in js, you can spy on anything external, for example with (...args) => debugger; fnToSpyOn(...args)
You can spoof console.log this way to see what the fuck is calling it (note: monkey patching for debugging = GOOD, for actual programming = DOGSHIT)
To be fair though, that is possible because of being a dynamic lang and elixir is kind of a hybrid typed lang, fair enough.
But here's where i drop the shit.
Phoenix takes it one step further by following the braindead ruby style of code and pretty DSLs.
I fucking hate DSLs, I fucking hate abstraction addiction.
Get this, we're not writing fucking poetry here. We're writing programs for machines for them to execute.
Machines are not humans with emotions or creativity, nor feel.
We need some level of abstraction to save time understanding source code, sure.
But there has to be a balance. Languages can be ergonomic for humans, but they also need to be ergonomic for algorithms and machines.
Some of the people that write "beautiful" "zen" code are the folks that think that everyone who doesn't push the pretty code agenda is a code elitist that doesn't want "normal" people to get into programming.
Programming is hard, man, there's no fucking way around it.
Sometimes operating system or even hardware details bleed into code.
DSLs are one easy way to make code really really easy to understand, but also make it really fucking hard to debug or to lose "programming meaning".7 -
Once in school, a teammate couldn't contribute real work, and is wiring the report. I asked him to write about how ABC should be like DEF, and those exact words appeared on the report draft.
-
Before you tell me shit is real, kindly provide the variables.
```
def real_shit(shit, real):
return shit is real
```2 -
Well i managed to finish a pet project after a very very long time while drunk coding for the first time. Def gonna do it again 12/104
-
def devRantPostAction(post : DevRantPost) = {
If ((post.contains("fuck") && ContradictsItself(post)) || ContainsBrilliantGif(post) || ReferencesPornSite(post))
PlusOne
else if (ContainsSqlInjection(post)
MinusOne
else
Ignore
} -
!rant
This is what I do every time I feel like garbage.
class Main:
def feelsgood():
x = input("Type your name")
print(x + " is awesome!")
Main.feelsgood() -
After trying to print colored text to the console using a portable Python 3 interpreter on Windows I came up with a "solution". I tried pretty much everything possible (I could think of): curses couldn't be loaded, ansi didn't work and installing libraries wasn't really an option, because it's not my device. Fuck portable interpreters and have fun with the "solution".
Def color_print(text, color):
text = text.replace("\n", "\\\" \\\"")
os.system ("powershell \"$host.ui.RawUi.ForegroundColor = \\\"" + color + "\\\"; echo \\\"" + test + "\\\"; $host.ui.RawUi.ForegroundColor = \\\"Gray\\\"")
It's slow, unreadable, only works for on Windows and requires powershell and is probably the worst piece of code I ever wrote, but it works 👍.2 -
If anyone has a moment.
curious if i'm fucking something up.
model:
self.linear_relu_stack = nn.Sequential(
nn.Linear(11, 13),
nn.ReLU(),
# nn.Linear(20, 20),
# nn.ReLU(),
nn.Linear(13,13),
nn.ReLU(),
nn.Linear(13,8),
nn.Sigmoid()
)
Inputs:
def __init__(self, targetx, targety, velocityx, velocityy, reloadtime, theta, phi, exitvelocity, maxtrackx, maxtracky,splashradius) -> None:
# map to 1 and 2
self.Target: XY = XY(targetx, targety)
# map to 3 and 4
self.TargetVel: XY = XY(velocityx, velocityy)
# TODO: this may never be necessary as targeting and firing is the primary objective
# map to 5, probably not yet needed may never be.
self.ReloadTime:float = reloadtime
# map to 6 and 7
self.TurretOrientation: Orientation = Orientation(theta, phi)
# map tp 8
self.MuzzleVelocity:float = exitvelocity
# map to 9 and 10, see i don't remember the outcome of this
# but i feel it should work. after countless bits of training data added.
# i can see how this would fuck up if exact values were off or there was a precision error
# maybe firing should be controlled by something else ?
self.MaxTrackSpeed: Orientation = Orientation(maxtrackx, maxtracky)
# these are for sigmoid output, any positive value of x will produce between 0.5 and 1.0 as return value
# from the sigmoid function.
self.OutMin = 0.5
self.OutMax = 1.0
# this is the number of meters radius that damage still occurs when a projectile lands.
# to be used for calculating where a hit will occur.
self.SplashRadius:float = splashradius
Outputs:
def __init__(self, firenow, clockwise,cclockwise,up,down,oor, hspeed, vspeed) -> None:
self.FireNow = float(firenow)
self.RotateClockWise = float(clockwise)
self.RotateCClockWise = float(cclockwise)
self.MoveUp = float(up)
self.Down = float(down)
self.OutOfRange = float(oor)
self.vspeed = float(vspeed)
self.hspeed = float(hspeed)9 -
Alright so this is just me throwing my thoughts down from today cause I need some outlet.
Gonna start programming a lot more than I do now cause I want to improve and I enjoy it.
I started my JavaScript course and that's going well so far. I need to figure out a way to make the info stick. I'm gonna def use the projects from each day as resources though.
I need to practice python (which I'm good with) occasionally so I dont lose my magic touch. I was thinking of doing a project on a raspberry pi that uses a camera for object/facial recognition and picking projects like that and occasional small ones I do in js.
Although theres still a lot I have to learn on the DOM side of js. I dont want to be a front end dev cause I dont have that artistic eye so I'm mostly gonna use it for node and small front end stuff
But mostly I need to be able to grasp more from tutorials, examples, courses, etc. And understand how and when and why I should use whatever it is.
Also I wanna use someones code to learn but it's never documented well enough for me to know what's happening I'm mostly referring to when theres a library or api I'm unfamiliar with.
Also JS is getting a little boring so hopefully python will help dull that feel6 -
Oh china, you always know how to snap me out of long stints of mundane and/or annoying, chore-esq work.
//...and letting me excuse a 10min, otherwise purely wrong procrastination down a current political rabbit hole
I gotta say, at least in china they are bold enough to put their image and identity on whatever they make... but in that 'im selling pseudo-sex, not because im sexy--just the opposite, so you know I relate' way.
Side note: i got an automated spam call survey yesterday*... it ot got to the 1st (of claimed 3) question.. which had a surprising amount of actual reiterations before looping... it was determined to get opinions(and totally incept the lemmings, soccer moms and politically ignorant into their stance, plus intense rage/disgust/dreams of standing on a soap box and fighting about this new issue they were totally unaware of.)... about this actively serving, politician's demand that china sell tiktok or totally stop allowing any operations/use on american soil... because of the heavily implied heinous nature of controlling and twisting society via media to it's explicitly declared communism... even directly called china, as a whole, communists, with impressive dramatics (and i coached public speaking hs and college kids then over a decade of business consulting, typically involving coaching vocals and implicit vocab)
I actually listened to it because it's what a typical subject, brought out of the koolaid fog, would view as ridiculously ironic(assuming they knew the actual, and therefore inherently ironic, def if irony... most dont. It's disturbing)... but it you have decent common sense, and dont emotionally view your entirety as wrong/broken/needing to be fixed in a cult-like manner, it's the oposite of irony. History of/and politics pull this crap all the time. It still works.
It reminds me of how my moniker, awesomeest, came about. In 3rd grade i realised that even adults, knowing they were chatting with an 8yr old, even if they knew/used the correct spelling of a, less common, term... if i misspelled it as if i thought it was right, theyd actually change their spelling to match (in perpetuity) albeit my vocab was easily high school level by then...likely at least in part to my flawless(aka blind/ignorant) demeanor of confidence that whatever i said/thought was totally correct, as a matter of fact. Not like the insecure ppl trying to prove something
I used to find it so comical... now it's just sad.
This bs automated political spam/manipulation is the modern version of i remember of kids farting in the late 90s... the culprit quickly accusing someone else of their offense, but even extra immature kids 25+ yrs ago figured that out... and even made the retort a catchy rhyme..."the one who smelt it, dealt it"
*i basically programmed in a counter attack/something akin to immature passive aggressive ' who"s really the one wasting the other's time and resources now?!? Ha!' ...odd numbers automatically go into a sort of echo chamber instead of ringing, with a manual escape to actually ringing/calling prompt built in.
I can listen in at any time without it having any effecf/sound too.
I'm curious if anyone participates in these minor acts of terrorism to complete an unrequested, intrusive, and human-less format of a proclaimed opinion poll? And if you do, are you honest? Why do you do it?
Annoyance at spam aside... the real victim I mentally mourn, and view it's method of demise akin to a cardinal sin (assuming religion...blah blah)... is the data! I <3 data... good, unobscured, not contrived, simple, pure, raw data... killed before its birth :'(5 -
Holy shit, finally had the time to look into tmux and also accidentally discovered you can resize the panes via ctrl+b then hold ctrl+[arrow-key] to resize it to any side, but I can't find any use for it all myself yet, since I just use some terminal emulator that has tabs or use the inbuilt virtual-desktop, still an exciting and cool thing to have played with, though I would def. change most of the hotkeys to something less capslock heavy, since it's rather awkward to first press ctrl+b then shift+2 etc.
-
Unicorn Themed day at code club ^_^
``` """ unicorn finder """
from random import randint
class UnicornFinder:
""" UnicornFinder class finds uncorns """
def __init__(self):
pass
def find_unicorn(self):
""" find a unicorn """
unicorn = True
for i in range(0, 31):
if randint(0, 7) != 7:
unicorn = False
break
if unicorn:
print("u200 unicorn found")
else:
print("u404:: unicorn not found")
if __name__ == '__main__':
UnicornFinder().find_unicorn()
```1 -
Maven simplejavamail dependency import, build email, try send it: jakarta.mail.messageexception whatever, not class def found. After some googling: Depends on jakarta-mail. Find jakarta-mail dependency, include it in pom, start again: jakarta.mail.someotherclassexception, no class def found.
Yeah fuck you, too...2 -
The devRant avatar builder should mos def offer loot boxes. I am nearly able to blow my first century on a new shirt or the duck. If a random loot box at 500 gave me the 1/1000 chance to get the white tiger, I would do it. Yes statistically if the model was driven like a slot game I would get the shirt or the duck anyway. But imagine the excitement, the fists slamming down on tables, the expletives. Passion like that leads to love. There is no love in choosing between the shirt and the duck.4
-
Anybody like to rip up CTF (or similar)? I've honestly never done a CTF before, I'd like to give jt a shot. I'll get my ass handed to me because I'm not back up to par on OpSec yet, but I adapt well and when I get into a nice groove I can make shit happen! (I like to think so, anyways haha!!)
I've been in full on dev mode lately and haven't had any time to Hulk Smash for a while... I went to fire up a new Kali live USB today and I couldn't run through the updates like I always have- they changed sooo much and I was pissed because I didn't have ethernet with me. That'll be another day for sure, but I still have my machine with Manjaro armed to the nutsack and back with the BlackArch rep. I def could use a break from the chaos, and getting my ass handed right to me sounds like an awesome time because learning is my favorite thing next to a possible chance at getting to destroy shit.
It's weird, because I'm sort of a n00b but also at the same time I've had computers ripped apart/jammed in my face since every day since I was 9 and Y2K was about to hit the fan lmao!! My hardware/network/layering knowledge is fuckin mint titties, I just can't code like a fuckin madman on the fly. I don't have a "primary" language, because I've been having to work with little bits of several languages for extended periods of time... I can at least find my way around all the dox without much of an issue and have no issue solving the probs I come across which is neat, but until the day comes where I can fuck a gaping hole through my keyboard on the fly like George Hotz during one of his lazy Sunday OpenCV SLAM/Python code streams all jacked up on Herba Mate hahahahaha!!!!
The dude uses fucking VIM and codes faster than anyone I've ever seen on levels of science/math so challenging I almost shit myself inside out when I catch one!!!! The level of respect I have for all my fellow red pills in here is as high as it gets, and that's one of the best parts about being a code junkie- sometimes ya get to cross paths with beastly, out of this world people that teach you so much without even having to explain shit.
If anyone's down, or maybe has some resources for me to check out so I can get my chops up let's make it happen -
Informal python poll:
Do you put your __init__ functions at the top or bottom of your classes?
AKA:
class myClass:
def mymethod(self, arg):
pass
def __init__(self):
pass
or...
class myClass:
def __init__(self):
pass
def mymethod(self, arg):
pass5 -
Behold, the code submitted by user Hecker:
(Quote) > writing html like a pro:
from typing import List
class MissmatchedRowsAndCols(Exception):
pass
class HtmlTableBuilder:
classes: List[str] = []
identifier: str = ""
rows: List[str] = []
cols: List[list] = []
def add_row(self, name: str):
self.rows.append(name)
return self
def add_col(self, fields: list):
if len(self.rows) != len(fields):
raise MissmatchedRowsAndCols(
"The given fields are not matched 1:1 with the rows.")
self.cols.append(fields)
return self
def build(self, indent: int = 4) -> str:
html = "<table border=\"2px\""
if len(self.identifier) > 0:
html += ' id="' + self.identifier + '"'
if len(self.classes) > 0:
html += ' class"' + (" ".join(self.classes)) + '"'
html += ">\n"
html += (" "*indent) + "<thead>\n"
for row in self.rows:
html += (" "*(indent*2)) + "<th>" + row + "</th>\n"
html += (" "*indent) + "</thead>\n"
html += (" "*indent) + "<tbody>\n"
for col in self.cols:
html += (" "*(indent*2)) + "<tr>\n"
for field in col:
html += (" "*(indent*3)) + "<td>\n"
html += (" "*(indent*4)) + str(field) + "\n"
html += (" "*(indent*3)) + "</td>\n"
html += (" "*(indent*2)) + "</tr>\n"
html += (" "*indent) + "</tbody>\n"
html += "</table>"
return html
builder = HtmlTableBuilder()
builder.add_row("index").add_row("language")
builder.add_col([0, "Python"]).add_col([1, "Kotlin"])
print(builder.build())6 -
class Bio:
def __init__(self,likes,dislikes):
self.likes=likes
self.dislikes=dislikes
Sabyasachi=Bio('Python','!Python')
print ('Hello devRant Community. I'm new here')
print ('I don't know why I am writing like this')
while True:
Lets_Rant('😠')5 -
I feel like the world, and my life has been so crazy lately that I needed something reassuring.
```ruby
def test_true_is_true
assert_equal true, true
end
```2 -
can you please help me with this.
I'm creating dataset of [Leet words][1].
This code is for generating [Leet words][1]. it is working fine with less number of strings but I've nearly 3,800+ strings and my pc is not capable to do so. I've Tried to run this on cloud(30gb RAM) not worked for me. but I think possible solution is to convert this code into numpy but I don't know how. if you know any other efficient way to do this it will be helpful.
Thanks!
from itertools import product
import pandas as pd
REPLACE = {'a': '@', 'i': '*', 'o': '*', 'u': '*', 'v': '*',
'l': '1', 'e': '*', 's': '$', 't': '7'}
def Leet2Combos(word):
possibles = []
for l in word.lower():
ll = REPLACE.get(l, l)
possibles.append( (l,) if ll == l else (l, ll) )
return [ ''.join(t) for t in product(*possibles) ]
s="""india
love
USA"""
words = s.split('\n')
print(words)
lst=[]
# ['india', 'love', 'USA']
for word in words:
lst.append(Leet2Combos(word))
k = pd.DataFrame(lst)
k.head()3 -
There's two types of developer.
Type 1 :
def function() {
// code
}
Type 2 :
def function()
{
//code
}
So, which one are you? I won't judge if you're not type 1.4 -
Hey Devrant fam!, well i'm basically trying to see if i can change up this A* algo we need to implement for an assessment, and from what i know basically most people have copy and pasted it, but not me!, so there is this one called Easy A* (star) Pathfinding By Nicholas Swift and my goal is such that i would like to make it input friendly!, here is the code in my main function
def main():
start1,start2 = input('Enter co-ordinates').split(',')
end1,end2 = input('Enter co-ordinates').split(',')
drive_mount()
open_map()
# test1 = (start1, start2)
# test2 = (end1, end2)
start = (start1, start2)
end = (end1, end2)
print(f'start co-ordinates:{start} \n end co-ordinates:{end}')
our_path = astar(our_maze, start, end)
print(f'starting co-ordinates:{start} \n ending co-ordinates:{end} \n Your shortest-path:{our_path}')
if __name__ == '__main__':
main()
however i am then greeted by this error, on line 62 specifically it says "TypeError: must be str, not int" and my original thought was to put str() around all of them, but that does not seem to work :-) any advice? thank you!3 -
Hey DevRant Fam!, hope everyone is very well,I just started using exercism with python inside my chosen editor Emacs, and well... the first problem i'm doing is the Hello World problem...
So the code i have is here:
def hello(name='world!'):
return "Hello, {0}".format(name)
hello()
and it prints out the output "Hello,World!"
but i'm getting a strange error in my command prompt saying something like this '1 Failed Assertion error None != 'Hello, World!'
anyone have some advice its my first time working with Exercism :-) cheers!
Thank you :-)13 -
Code comments are good and all, but there's a time and a place for them. They're more or less an opinionated free-form version of what code is doing.
In a library, they're good for documentation. However in a platform, it makes less sense. Especially one which is changing at quite a fast rate (though it has matured in recent months).
Dont get me wrong, we aren't doing wades of horrible, unintelligible code. We need to be sure of what happens when we call a function, so we make sure the signature is always correct.
def do_good_things(puppies): # "good things" is opinionated. Say what you're doing
"""give treats to puppies""" # doc string is wrong
pet(puppies)5 -
def examMonth():
for exam in exams:
while days:
if time ≥ week:
pass
elif time == days_3 or time == days_2:
book = open_book()
study(book)
else:
panic_and_devRant()
days = days - 1
def study(book):
see_open_book()
delay(minutes_10)
devRant() -
I am that kind of a person who writes the function of each function() in comments above the def.
I hat people who do not do that properly :/
If you are working as a part of a team or wanting to distribute your code, you should do that. :)2 -
I'm working on a simple Flask project. But when I try to work with the database I got an error called "No module named MySQLdb". I also got error when I try to install "mysql clint" with this command:-pip install mysqlclient. So I searched for the solution of this problem but every time I find someone told to download "MySQL client" from this website:-
https://lfd.uci.edu/~gohlke/...
But the "MySQL client" file is no longer available on that website.
please help me by giving that file or any other way. You can also check my project from here:-
https://drive.google.com/file/d/...
unfortunately, my operating system is Android 6.0
Here is the code:-
from flask import Flask,render_template, request
from flask_sqlalchemy import SQLAlchemy
app= Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = "mysql://localhost/codingthunder/"
db = SQLAlchemy(app)
class Contacts(db.Model):
sno = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), nullable=False)
phone_num = db.Column(db.String(14), nullable=False)
mes = db.Column(db.String(120), nullable=False)
date = db.Column(db.String(12), nullable=False)
email = db.Column(db.String(20), nullable=False)
@app.route("/home")
def home():
return render_template("index.html")
@app.route("/about")
def about():
return render_template("about.html")
@app.route("/contact", methods=['GET','POST'])
def contact():
if(request.method=='POST'):
name=request.form.get('name')
email=request.form.get('email')
phone=request.form.get('phone')
message=request.form.get('message')
entry=Contacts(name=name,phone_num=phone,mes=message, date="2019-09-01 12:06:20", email=email)
db.session.add(entry)
db.session.commit()
return render_template("contact.html")
@app.route("/post")
def post():
return render_template("post.html")
app.run(debug=True)3 -
Help wanted, im having troubles with my boot order, for school i need to keep some windows program but i want my def boot order to be linux, its both showing in uefi but wen i select parrot to be first and safe it, reboot boom windows back on top, any thoughts how to fix this????2
-
Me [as Android guy for years] getting an iPad and navigating on the internet.
*Finds an interesting PDF file* Wow let's download it for later.
WHAAAAAT DEF... it's just a PDF download, why it should take all of this???1 -
I can't count likes form my database for an specific post. I made a function that will count all the like by "post.id". It shows the like on the web page when I clicked on like button and it disappears when I refresh the browser. but likes are still remaining in the database but it won't appear on the webpage.
Here are the flask code:
def like_count(post_id):
if request.form.get('like') != None:
if (Like.query.filter_by(post_id=post_id).all())==[]:
return 0
else:
return Like.query.filter_by(post_id=post_id).count()
else:
return 0
def dislike_count(post_id):
if request.form.get('dislike') != None:
if (Dislike.query.filter_by(post_id=post_id).all())==[]:
return 0
else:
return Dislike.query.filter_by(post_id=post_id).count()
else:
return 0
Here are the html code:
<!--dislike-->
<form method="POST" action="">
<input name="dislike" value="1" class="input-style" >
<input value="{{post.id}}" name="post_id" class="input-style">
<button class="fas fa-thumbs-down" class="like-button" >
<div class="like-count" >
{{dislike_count(post.id)}}
</div>
</button>
</form>
<!--like-->
<form method="POST" action="" >
<input name="like" value="1" class="input-style" >
<input name="post_id" value="{{post.id}}" class="input-style" >
<button class="fas fa-thumbs-up" class="like-button" >
<div class="like-count" >
{{like_count(post.id)}}
</div>
</button>
</form>8 -
I want to print the first number in the Fibonacci sequence to contain over 1000 digits. I got fibbonaci to work but I cannot seem to figure out how to implement the "Contain over 1000 digits".
Do I make a list to store the fibbonaci numbers in then do a statement?
My Python 3 Code:
def fibonacci(num):
if num == 2 or num ==1:
return 1
return sum([fibonacci(num - 2), fibonacci(num - 1)])
print(fibonacci(7))7 -
So… I’m on that fun side of autism spectrum where you’d swear I’m just an ass… and my entire fam/friend network has always picked the latter; so, proceed to read as you will, but I swear my ADD is largely manufactured by the misaligned mental connection of the “inspector and inspected”… to say, smart is as smart does… and I ain’t doin spit if you watchin(but then i know everyone watching 😂🤡)
class Clown(self)
Def _init_(self, name)
Clown.name = “me”
Print(clown)2 -
Another company another offer downplayed from role I wanted. tbh probably implies I'm def not to that level yet haha but the feedback seemed to have negatives when I believe I gave examples to imply the reverse. Either way another offer refused I guess. Got a good raise which makes things better I guess.
-
Please give me code snippet to create windows ec2 instance using boto3 within aws free tier limit.
import boto3
# Create an AWS session and EC2 client
aws_management_console = boto3.session.Session(profile_name='....')
ec2_console = aws_management_console.client(service_name='ec2')
def create_ec2_instance():
try:
print("Creating EC2 instance")
ec2_console.run_instances(
ImageId="....",
MinCount=1,
MaxCount=1,
InstanceType="t3.micro",
KeyName="...",
SecurityGroupIds=['...1'] # Specify your security group ID(s) as a list
)
except Exception as e:
print(e)
# Call the function to create the EC2 instance
create_ec2_instance()
Have i missed anything in this code?
It's running fine not creating any instance.4 -
Help. Has Python changed in version 3.6.5, or is there something wrong with my code?!
The following doesn't work:
import os
def main():
console = input("...")
rom = input("...")
The following does work:
import os
console = input("...")
rom = input("...")
def main() :12 -
def list = ['Stark', 'Bolton', 'Lennister', 'Tyrell']
def map = list.collectEntries ({[(list.indexOf(it)): it]}) -
def longVariableNamesEverywhere(*args):
"""
Not a substitute for docstrings and code comments.
"""
#TODO: insert witty and legible code.
#TODO: learn to read code.
return "Rant and self-deprecation complete."4 -
I am trying to extract data from the PubSub subscription and finally, once the data is extracted I want to do some transformation. Currently, it's in bytes format. I have tried multiple ways to extract the data in JSON format using custom schema it fails with an error
TypeError: __main__.MySchema() argument after ** must be a mapping, not str [while running 'Map to MySchema']
**readPubSub.py**
import apache_beam as beam
from apache_beam.options.pipeline_options import PipelineOptions
import json
import typing
class MySchema(typing.NamedTuple):
user_id:str
event_ts:str
create_ts:str
event_id:str
ifa:str
ifv:str
country:str
chip_balance:str
game:str
user_group:str
user_condition:str
device_type:str
device_model:str
user_name:str
fb_connect:bool
is_active_event:bool
event_payload:str
TOPIC_PATH = "projects/nectar-259905/topics/events"
def run(pubsub_topic):
options = PipelineOptions(
streaming=True
)
runner = 'DirectRunner'
print("I reached before pipeline")
with beam.Pipeline(runner, options=options) as pipeline:
message=(
pipeline
| "Read from Pub/Sub topic" >> beam.io.ReadFromPubSub(subscription='projects/triple-nectar-259905/subscriptions/bq_subscribe')#.with_output_types(bytes)
| 'UTF-8 bytes to string' >> beam.Map(lambda msg: msg.decode('utf-8'))
| 'Map to MySchema' >> beam.Map(lambda msg: MySchema(**msg)).with_output_types(MySchema)
| "Writing to console" >> beam.Map(print))
print("I reached after pipeline")
result = message.run()
result.wait_until_finish()
run(TOPIC_PATH)
If I use it directly below
message=(
pipeline
| "Read from Pub/Sub topic" >> beam.io.ReadFromPubSub(subscription='projects/triple-nectar-259905/subscriptions/bq_subscribe')#.with_output_types(bytes)
| 'UTF-8 bytes to string' >> beam.Map(lambda msg: msg.decode('utf-8'))
| "Writing to console" >> beam.Map(print))
I get output as
{
'user_id': '102105290400258488',
'event_ts': '2021-05-29 20:42:52.283 UTC',
'event_id': 'Game_Request_Declined',
'ifa': '6090a6c7-4422-49b5-8757-ccfdbad',
'ifv': '3fc6eb8b4d0cf096c47e2252f41',
'country': 'US',
'chip_balance': '9140',
'game': 'gru',
'user_group': '[1, 36, 529702]',
'user_condition': '[1, 36]',
'device_type': 'phone',
'device_model': 'TCL 5007Z',
'user_name': 'Minnie',
'fb_connect': True,
'event_payload': '{"competition_type":"normal","game_started_from":"result_flow_rematch","variant":"target"}',
'is_active_event': True
}
{
'user_id': '102105290400258488',
'event_ts': '2021-05-29 20:54:38.297 UTC',
'event_id': 'Decline_Game_Request',
'ifa': '6090a6c7-4422-49b5-8757-ccfdbad',
'ifv': '3fc6eb8b4d0cf096c47e2252f41',
'country': 'US',
'chip_balance': '9905',
'game': 'gru',
'user_group': '[1, 36, 529702]',
'user_condition': '[1, 36]',
'device_type': 'phone',
'device_model': 'TCL 5007Z',
'user_name': 'Minnie',
'fb_connect': True,
'event_payload': '{"competition_type":"normal","game_started_from":"result_flow_rematch","variant":"target"}',
'is_active_event': True
}
Please let me know if I m doing something wrong while parsing the data to JSON. Also, I am looking for examples to do data masking and run some SQL within Apache Beam4