Today I tested with a simple LaTeX examples in the Colab notebook.
If you open my notebook colab then you will see some issues and how can be fixed.
You can find this on my notebook - catafest_056.ipynb on colab repo.
Is a blog about python programming language. You can see my work with python programming language, tutorials and news.
import winreg
# Open the CLSID key under HKEY_CLASSES_ROOT
clsid_key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, "CLSID")
# Iterate through all the subkeys
for i in range(winreg.QueryInfoKey(clsid_key)[0]):
# Get the name of the subkey
subkey_name = winreg.EnumKey(clsid_key, i)
# Open the subkey
subkey = winreg.OpenKey(clsid_key, subkey_name, 0, winreg.KEY_READ)
try:
# Read the default value of the subkey
value, type = winreg.QueryValueEx(subkey, "")
# Print the subkey name and the value
print(subkey_name, value)
except:
# Skip the subkeys that cannot be read
pass
# Close the subkey
winreg.CloseKey(subkey)
# Close the CLSID key
winreg.CloseKey(clsid_key)
import winreg
# Open the CLSID key under HKEY_CLASSES_ROOT
clsid_key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, "CLSID")
# Open the file for writing
with open("clsid_info.txt", "w") as f:
# Iterate through all the subkeys
for i in range(winreg.QueryInfoKey(clsid_key)[0]):
# Get the name of the subkey
subkey_name = winreg.EnumKey(clsid_key, i)
# Open the subkey
subkey = winreg.OpenKey(clsid_key, subkey_name, 0, winreg.KEY_READ)
try:
# Read the default value of the subkey
value, type = winreg.QueryValueEx(subkey, "")
# Write the subkey name and the value to the file
f.write(subkey_name + " " + value + "\n")
except:
# Skip the subkeys that cannot be read
pass
# Close the subkey
winreg.CloseKey(subkey)
# Close the CLSID key
winreg.CloseKey(clsid_key)
example-project-tensorflow-keras
import glob
import hashlib
import matplotlib.pyplot as plt
import neptune.new as neptune
import numpy as np
import pandas as pd
import tensorflow as tf
from neptune.new.integrations.tensorflow_keras import NeptuneCallback
from scikitplot.metrics import plot_roc, plot_precision_recall
# Select project
run = neptune.init(project='common/example-project-tensorflow-keras',
tags=['keras', 'fashion-mnist'],
name='keras-training')
# Prepare params
parameters = {'dense_units': 128,
'activation': 'relu',
'dropout': 0.23,
'learning_rate': 0.15,
'batch_size': 64,
'n_epochs': 30}
run['model/params'] = parameters
# Prepare dataset
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.fashion_mnist.load_data()
x_train = x_train / 255.0
x_test = x_test / 255.0
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
# Log data version
run['data/version/x_train'] = hashlib.md5(x_train).hexdigest()
run['data/version/y_train'] = hashlib.md5(y_train).hexdigest()
run['data/version/x_test'] = hashlib.md5(x_test).hexdigest()
run['data/version/y_test'] = hashlib.md5(y_test).hexdigest()
run['data/class_names'] = class_names
# Log example images
for j, class_name in enumerate(class_names):
plt.figure(figsize=(10, 10))
label_ = np.where(y_train == j)
for i in range(9):
plt.subplot(3, 3, i + 1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(x_train[label_[0][i]], cmap=plt.cm.binary)
plt.xlabel(class_names[j])
run['data/train_sample'].log(neptune.types.File.as_image(plt.gcf()))
plt.close('all')
# Prepare model
model = tf.keras.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(parameters['dense_units'], activation=parameters['activation']),
tf.keras.layers.Dropout(parameters['dropout']),
tf.keras.layers.Dense(parameters['dense_units'], activation=parameters['activation']),
tf.keras.layers.Dropout(parameters['dropout']),
tf.keras.layers.Dense(10, activation='softmax')
])
optimizer = tf.keras.optimizers.SGD(learning_rate=parameters['learning_rate'])
model.compile(optimizer=optimizer,
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# Log model summary
model.summary(print_fn=lambda x: run['model/summary'].log(x))
# Train model
neptune_cbk = NeptuneCallback(run=run, base_namespace='metrics')
model.fit(x_train, y_train,
batch_size=parameters['batch_size'],
epochs=parameters['n_epochs'],
validation_split=0.2,
callbacks=[neptune_cbk])
# Log model weights
model.save('trained_model')
run['model/weights/saved_model'].upload('trained_model/saved_model.pb')
for name in glob.glob('trained_model/variables/*'):
run[name].upload(name)
# Evaluate model
eval_metrics = model.evaluate(x_test, y_test, verbose=0)
for j, metric in enumerate(eval_metrics):
run['test/scores/{}'.format(model.metrics_names[j])] = metric
# Log predictions as table
y_pred_proba = model.predict(x_test)
y_pred = np.argmax(y_pred_proba, axis=1)
y_pred = y_pred
df = pd.DataFrame(data={'y_test': y_test, 'y_pred': y_pred, 'y_pred_probability': y_pred_proba.max(axis=1)})
run['test/predictions'] = neptune.types.File.as_html(df)
# Log model performance visualizations
fig, ax = plt.subplots()
plot_roc(y_test, y_pred_proba, ax=ax)
run['charts/ROC'] = neptune.types.File.as_image(fig)
fig, ax = plt.subplots()
plot_precision_recall(y_test, y_pred_proba, ax=ax)
run['charts/precision-recall'] = neptune.types.File.as_image(fig)
plt.close('all')
run.wait()
!python
Python 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
from cartopy.io import shapereader
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
import cartopy.io.img_tiles as cimgt
extent = [15, 25, 55, 35]
request = cimgt.OSM()
fig = plt.figure(figsize=(9, 13))
ax = plt.axes(projection=request.crs)
gl = ax.gridlines(draw_labels=True, alpha=0.2)
gl.top_labels = gl.right_labels = False
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
ax.set_extent(extent)
ax.add_image(request, 11)
plt.show()
C:\PythonProjects\scapy_001>pip install scapy
Collecting scapy
Downloading scapy-2.5.0.tar.gz (1.3 MB)
---------------------------------------- 1.3/1.3 MB 3.5 MB/s eta 0:00:00
Installing build dependencies ... done
...
Successfully built scapy
Installing collected packages: scapy
Successfully installed scapy-2.5.0
from scapy.all import Dot11,Dot11Beacon,Dot11Elt,RadioTap,sendp,hexdump
netSSID = 'testSSID' #Network name here
iface = 'Realtek PCIe GbE Family Controller' #Interface name here
dot11 = Dot11(type=0, subtype=8, addr1='ff:ff:ff:ff:ff:ff',
addr2='22:22:22:22:22:22', addr3='33:33:33:33:33:33')
beacon = Dot11Beacon(cap='ESS+privacy')
essid = Dot11Elt(ID='SSID',info=netSSID, len=len(netSSID))
rsn = Dot11Elt(ID='RSNinfo', info=(
'\x01\x00' #RSN Version 1
'\x00\x0f\xac\x02' #Group Cipher Suite : 00-0f-ac TKIP
'\x02\x00' #2 Pairwise Cipher Suites (next two lines)
'\x00\x0f\xac\x04' #AES Cipher
'\x00\x0f\xac\x02' #TKIP Cipher
'\x01\x00' #1 Authentication Key Managment Suite (line below)
'\x00\x0f\xac\x02' #Pre-Shared Key
'\x00\x00')) #RSN Capabilities (no extra capabilities)
frame = RadioTap()/dot11/beacon/essid/rsn
frame.show()
print("\nHexdump of frame:")
hexdump(frame)
input("\nPress enter to start\n")
sendp(frame, iface=iface, inter=0.100, loop=1)
python scapy_network_001.py
###[ RadioTap ]###
version = 0
pad = 0
len = None
present = None
notdecoded= ''
###[ 802.11 ]###
subtype = Beacon
type = Management
proto = 0
FCfield =
ID = 0
addr1 = ff:ff:ff:ff:ff:ff (RA=DA)
addr2 = 22:22:22:22:22:22 (TA=SA)
addr3 = 33:33:33:33:33:33 (BSSID/STA)
SC = 0
###[ 802.11 Beacon ]###
timestamp = 0
beacon_interval= 100
cap = ESS+privpython scapy_network_001.py
###[ RadioTap ]### tion Element ]###
version = 0 = SSID
pad = 0 = 8
len = None = 'testSSID'
present = Noneation Element ]###
notdecoded= '' = RSN
###[ 802.11 ]### = None
subtype = Beacon'\x01\x00\x00\x0f¬\x02\x02\x00\x00\x0f¬\x04\x00\x0f¬\x02\x01\x00\x00\x
type = Management
proto = 0
FCfield =
ID = 0
addr1 = ff:ff:ff:ff:ff:ff (RA=DA)FF FF FF FF ................
addr2 = 22:22:22:22:22:22 (TA=SA)33 33 00 00 ..""""""333333..
addr3 = 33:33:33:33:33:33 (BSSID/STA)8 74 65 ........d.....te
SC = 049 44 30 1C 01 00 00 0F C2 AC 02 02 stSSID0.........
###[ 802.11 Beacon ]### 00 0F C2 AC 02 01 00 00 0F C2 ................
timestamp = 0 ....
beacon_interval= 100
cap = ESS+privacy
###[ 802.11 Information Element ]###
ID = SSID..................................................................
len = 8.....................................................................
info = 'testSSID'
###[ 802.11 Information Element ]###
ID = RSN
len = None>
info = '\x01\x00\x00\x0f¬\x02\x02\x00\x00\x0f¬\x04\x00\x0f¬\x02\x01\x00\x00\x0f¬\x02\x00\x00'
Hexdump of frame:
0000 00 00 08 00 00 00 00 00 80 00 00 00 FF FF FF FF ................
0010 FF FF 22 22 22 22 22 22 33 33 33 33 33 33 00 00 ..""""""333333..
0020 00 00 00 00 00 00 00 00 64 00 11 00 00 08 74 65 ........d.....te
0030 73 74 53 53 49 44 30 1C 01 00 00 0F C2 AC 02 02 stSSID0.........
0040 00 00 0F C2 AC 04 00 0F C2 AC 02 01 00 00 0F C2 ................
0050 AC 02 00 00 ....
Press enter to start
.................................................................
Sent 130 packets.
import pyotp
# Generare secret pentru utilizator
secret = pyotp.random_base32()
# Generare URL pentru codul QR
uri = pyotp.totp.TOTP(secret).provisioning_uri(name="UtilizatorExemplu", issuer_name="NumeServer")
# Exemplu de folosire a URI-ului într-o aplicație web sau pentru a genera un cod QR
print("Scanati urmatorul QR code in aplicatia Microsoft Authenticator:")
print(uri)
python test_001.py
Scanati urmatorul QR code in aplicatia Microsoft Authenticator:
otpauth://totp/NumeServer:UtilizatorExemplu?secret=SPZICPQHAMWOIYCAZEHXZTPQDXEXZSWL&issuer=NumeServer
from google.colab import auth
auth.authenticate_user()
import gspread
from google.auth import default
creds, _ = default()
gc = gspread.authorize(creds)
# Open the spreadsheet by name
spreadsheet = gc.open('fiecare_saptamana')
# Choose a worksheet from the spreadsheet
worksheet = spreadsheet.get_worksheet(0) # 0 represents the index of the first worksheet
# Get and print the data
data = worksheet.get_all_values()
#uncoment this line to print data sau add more source code to parse data
#print(data)
#the result will be
#[['noreply@projects.blender.org', '437', 'notifications@github.com', ...
python
Python 3.13.0a1 (tags/v3.13.0a1:ad056f0, Oct 13 2023, 09:51:17) [MSC v.1935 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> help()
Welcome to Python 3.13's help utility!
If this is your first time using Python, you should definitely check out
the tutorial on the internet at https://docs.python.org/3.13/tutorial/.
Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit".
To get a list of available modules, keywords, symbols, or topics, type
"modules", "keywords", "symbols", or "topics". Each module also comes
with a one-line summary of what it does; to list the modules whose name
or summary contain a given string such as "spam", type "modules spam".
help> modules
Please wait a moment while I gather a list of all available modules...
test_sqlite3: testing with SQLite version 3.43.1
__future__ _testcapi fractions runpy
__hello__ _testclinic ftplib sched
__phello__ _testclinic_limited functools secrets
_abc _testconsole gc select
_aix_support _testimportmultiple genericpath selectors
_ast _testinternalcapi getopt shelve
_asyncio _testmultiphase getpass shlex
_bisect _testsinglephase gettext shutil
_blake2 _thread glob signal
_bz2 _threading_local graphlib site
_codecs _tkinter gzip smtplib
_codecs_cn _tokenize hashlib socket
_codecs_hk _tracemalloc heapq socketserver
_codecs_iso2022 _typing hmac sqlite3
_codecs_jp _uuid html sre_compile
_codecs_kr _warnings http sre_constants
_codecs_tw _weakref idlelib sre_parse
_collections _weakrefset imaplib ssl
_collections_abc _winapi importlib stat
_compat_pickle _wmi inspect statistics
_compression _xxinterpchannels io string
_contextvars _xxsubinterpreters ipaddress stringprep
_csv _zoneinfo itertools struct
_ctypes abc json subprocess
_ctypes_test antigravity keyword symtable
_datetime argparse linecache sys
_decimal array locale sysconfig
_elementtree ast logging tabnanny
_functools asyncio lzma tarfile
_hashlib atexit mailbox tempfile
_heapq base64 marshal test
_imp bdb math textwrap
_io binascii mimetypes this
_json bisect mmap threading
_locale builtins modulefinder time
_lsprof bz2 msvcrt timeit
_lzma cProfile multiprocessing tkinter
_markupbase calendar netrc token
_md5 cmath nt tokenize
_multibytecodec cmd ntpath tomllib
_multiprocessing code nturl2path trace
_opcode codecs numbers traceback
_opcode_metadata codeop opcode tracemalloc
_operator collections operator tty
_osx_support colorsys optparse turtle
_overlapped compileall os turtledemo
_pickle concurrent pathlib types
_py_abc configparser pdb typing
_pydatetime contextlib pickle unicodedata
_pydecimal contextvars pickletools unittest
_pyio copy pip urllib
_pylong copyreg pkgutil uuid
_queue csv platform venv
_random ctypes plistlib warnings
_sha1 curses poplib wave
_sha2 dataclasses posixpath weakref
_sha3 datetime pprint webbrowser
_signal dbm profile winreg
_sitebuiltins decimal pstats winsound
_socket difflib pty wsgiref
_sqlite3 dis py_compile xml
_sre doctest pyclbr xmlrpc
_ssl email pydoc xxsubtype
_stat encodings pydoc_data zipapp
_statistics ensurepip pyexpat zipfile
_string enum queue zipimport
_strptime errno quopri zlib
_struct faulthandler random zoneinfo
_symtable filecmp re
_sysconfig fileinput reprlib
_testbuffer fnmatch rlcompleter
Enter any module name to get more help. Or, type "modules spam" to search
for modules whose name or summary contain the string "spam".
help> ^Z
>>>
python.exe -m pip install --upgrade pip
~/Django001$ python
Python 3.8.12 (default, Aug 30 2021, 16:42:10)
[GCC 10.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import secrets
>>> secrets.token_urlsafe(32)
'yIXPv6u4uCt4AUWlkU4NCuoyJiZlLx5IFm8kG6h8RtA'
~/Django001$ python manage.py startapp catafest001
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'catafest001',
]
~/Django001$ python manage.py createsuperuser
Username (leave blank to use 'runner'):
Email address: catafest@yahoo.com
Password:
Password (again):
The password is too similar to the username.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.
import time
from plyer import notification
if __name__ == "__main__":
while True:
notification.notify(title="Test",message="Text message",timeout=10)
time.sleep(3000)
import pyautogui
import time
# Display a short notification to prompt the user to activate the modal dialog window
print("Please activate the modal dialog window.")
# Wait for the user to activate the modal dialog window (you can click in the dialog window)
time.sleep(10) # Wait 10 seconds or enough time to activate the window
# Get the coordinates where you want to read the text on the label
x_label = 200 # Replace with the correct x coordinates
y_label = 300 # Replace with the correct y coordinates
# Move the mouse cursor to the coordinates of the label
pyautogui.moveTo(x_label, y_label)
# Select the text in the label using the mouse
pyautogui.dragTo(x_label + 200, y_label, duration=1) # Substitute the appropriate coordinates and duration
# Copies the selected text to the clipboard
pyautogui.hotkey("ctrl", "c")
# You can use the clipboard to access the read text
import clipboard
text_copied = clipboard.paste()
NameError: name 'sys' is not defined. Did you forget to import 'sys'?
$ pip install PyGobject
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
win = Gtk.Window()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()
$ whereis sway
$ env/bin/pytest --sway=/usr/bin/sway
$ sudo env/bin/pytest --sway=/usr/bin/sway
mkdir rsconnect-python-001
cd rsconnect-python-001
pip install rsconnect-python --user
Collecting rsconnect-python
rsconnect add --account catafest --name catafest --token YOUR_TOKEN --secret YOUR_SECRET
Detected the following inputs:
name: COMMANDLINE
insecure: DEFAULT
account: COMMANDLINE
token: COMMANDLINE
secret: COMMANDLINE
Checking shinyapps.io credential... [OK]
Added shinyapps.io credential "catafest".
library(shiny)
# Definirea interfeței utilizatorului
ui <- fluidPage(
titlePanel("Aplicație Shiny Simplă"),
sidebarLayout(
sidebarPanel(
numericInput("num", "Introduceți un număr:", value = 1),
actionButton("goButton", "Generează")
),
mainPanel(
textOutput("rezultat")
)
)
)
# Definirea serverului
server <- function(input, output) {
observeEvent(input$goButton, {
num <- input$num
output$rezultat <- renderText({
paste("Numărul introdus este:", num)
})
})
}
# Crearea aplicației Shiny
shinyApp(ui, server)
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
# Creați o aplicație Dash
app = dash.Dash(__name__)
# Definiți aspectul și structura aplicației
app.layout = html.Div([
html.H1("Aplicație Dash Simplă"),
dcc.Graph(id='grafic'),
dcc.Input(id='input-numar', type='number', value=1),
html.Div(id='rezultat')
])
# Definiți funcția callback pentru actualizarea graficului
@app.callback(
Output('grafic', 'figure'),
Input('input-numar', 'value')
)
def actualizare_grafic(numar):
# Implementați logica de actualizare a graficului aici
# Exemplu simplu: Un grafic cu o linie dreaptă cu panta egală cu numărul introdus
import plotly.express as px
import pandas as pd
data = pd.DataFrame({'x': range(10), 'y': [numar * x for x in range(10)]})
fig = px.line(data, x='x', y='y', title='Graficul personalizat')
return fig
# Rulează aplicația
if __name__ == '__main__':
app.run_server(debug=True)
shiny::runApp("C:/PythonProjects/rsconnect-python-001/")
Listening on http://127.0.0.1:7036
>rsconnect deploy shiny . --name catafest --title test
[WARNING] 2023-09-01T22:28:10+0300 Can't determine entrypoint; defaulting to 'app'
Warning: Capturing the environment using 'pip freeze'.
Consider creating a requirements.txt file instead.
...
Task done: Stopping old instances
Application successfully deployed to https://catafest.shinyapps.io/test/
...
deploying - Starting instances
Task done: Stopping old instances
Application successfully deployed to https://catafest.shinyapps.io/rsconnect-python-001/
←[32;20m [OK]
←[0m←[0mSaving deployed information...←[0m←[32;20m [OK]
←[0m
[notice] A new release of pip is available: 23.1.2 -> 23.2.1
[notice] To update, run: /srv/connect/venv/bin/python3 -m pip install --upgrade pip
[2023-09-01T22:43:31.378864990+0000] Copying file manifest.json
←[31;20m [ERROR]: Application deployment failed with error: Unhandled Exception: Child Task 1332185768 error:
Unhandled Exception: 599
←[0mError: Application deployment failed with error: Unhandled Exception: Child Task 1332185768 error:
Unhandled Exception: 599
pip install capstone --user
Collecting capstone
Obtaining dependency information for capstone from https://files.pythonhosted.org/packages/d0/dd/b28df50316ca193
dd1275a4c47115a720796d
9e1501c1888c4bfa5dc2260/capstone-5.0.1-py3-none-win_amd64.whl.metadata
Downloading capstone-5.0.1-py3-none-win_amd64.whl.metadata (3.5 kB)
Downloading capstone-5.0.1-py3-none-win_amd64.whl (1.3 MB)
---------------------------------------- 1.3/1.3 MB 1.6 MB/s eta 0:00:00
Installing collected packages: capstone
Successfully installed capstone-5.0.1
pip install pefile --user
Collecting pefile
Downloading pefile-2023.2.7-py3-none-any.whl (71 kB)
---------------------------------------- 71.8/71.8 kB 564.7 kB/s eta 0:00:00
Installing collected packages: pefile
Successfully installed pefile-2023.2.7
format PE64 GUI 5.0
entry start
include 'INCLUDE\win64a.inc'
section '.text' code readable executable
start:
push rbp
invoke GetModuleHandle,0
invoke DialogBoxParam,rax,37,HWND_DESKTOP,DialogProc,0
invoke ExitProcess,0
proc DialogProc uses rbx rsi rdi,hWnd,wMsg,wParam,lParam
mov [hWnd],rcx
mov [wMsg],rdx
mov [wParam],r8
mov [lParam],r9
cmp [wMsg],WM_COMMAND
je wmcommand
cmp [wMsg],WM_CLOSE
je wmclose
cmp [wMsg],WM_SYSCOMMAND
je wmsyscommand
xor rax,rax
jmp finish
wmsyscommand:
cmp [wParam],SC_RESTORE
je sc_restore
invoke DefWindowProc,[hWnd],[wMsg],[wParam],[lParam]
ret
sc_restore:
invoke AnimateWindow,[hWnd],DWORD 1000,0x00040004 ;HERE IT IS
invoke ShowWindow,[hWnd],SW_RESTORE
mov rax,1
ret
wmcommand:
cmp [wParam],BN_CLICKED shl 16 + IDOK
jne processed
invoke ShowWindow,[hWnd],SW_MINIMIZE
ret
wmclose:
invoke EndDialog,[hWnd],0
processed:
mov rax,1
ret ; this no need and use cmp to get error
; cmp rax,0
; je show_error
; show_error:
; invoke GetLastError ;must call this first and save the result before doing anything else
; invoke wsprintf,...
; invoke MessageBox,...
finish:
ret
endp
section '.idata' import data readable writeable
library kernel,'KERNEL32.DLL',\
user,'USER32.DLL'
import kernel,\
GetModuleHandle,'GetModuleHandleA',\
ExitProcess,'ExitProcess'
import user,\
DialogBoxParam,'DialogBoxParamA',\
CheckRadioButton,'CheckRadioButton',\
GetDlgItemText,'GetDlgItemTextA',\
IsDlgButtonChecked,'IsDlgButtonChecked',\
MessageBox,'MessageBoxA',\
DefWindowProc,'DefWindowProcA',\
EndDialog,'EndDialog',\
AnimateWindow,'AnimateWindow',\
ShowWindow,'ShowWindow'
section '.rsrc' resource data readable
directory RT_DIALOG,dialogs
resource dialogs,\
37,LANG_ENGLISH+SUBLANG_DEFAULT,demonstration
dialog demonstration,'Create message box',70,70,190,175,WS_CAPTION+WS_POPUP+WS_SYSMENU+DS_MODALFRAME
dialogitem 'BUTTON','OK',IDOK,85,150,45,15,WS_VISIBLE+WS_TABSTOP+BS_DEFPUSHBUTTON
enddialog
import pefile
from capstone import *
exe_file = 'test_001_no_err_imp.EXE'
pe = pefile.PE(exe_file)
# find text section
offset = False
for section in pe.sections:
if section.Name == b'.text\x00\x00\x00':
offset = section.VirtualAddress
codePtr = section.PointerToRawData
codeEndPtr = codePtr+section.SizeOfRawData
break
code = pe.get_memory_mapped_image()[codePtr:codeEndPtr]
# start disassembling text section
md = Cs(CS_ARCH_X86, CS_MODE_32)
md.detail = True
if offset:
for i in md.disasm(code, offset):
print('0x%x:\t%s\t%s' % (i.address, i.mnemonic, i.op_str))
python capstone_test_001.py
0x1000: push ebp
0x1001: dec eax
0x1002: sub esp, 0x20
0x1005: dec eax
0x1006: mov ecx, 0
0x100c: call dword ptr [0x105e]
0x1012: dec eax
0x1013: add esp, 0x20
0x1016: dec eax
0x1017: sub esp, 0x30
0x101a: dec eax
0x101b: mov ecx, eax
0x101d: dec eax
0x101e: mov edx, 0x25
0x1024: dec ecx
0x1025: mov eax, 0
0x102b: dec ecx
0x102c: mov ecx, 0x40105a
0x1032: dec eax
0x1033: mov dword ptr [esp + 0x20], 0
0x103b: call dword ptr [0x109f]
0x1041: dec eax
0x1042: add esp, 0x30
0x1045: dec eax
0x1046: sub esp, 0x20
0x1049: dec eax
0x104a: mov ecx, 0
0x1050: call dword ptr [0x1022]
0x1056: dec eax
0x1057: add esp, 0x20
0x105a: push ebp
0x105b: dec eax
0x105c: mov ebp, esp
0x105e: dec eax
0x105f: sub esp, 8
0x1062: push ebx
0x1063: push esi
0x1064: push edi
0x1065: dec eax
0x1066: mov dword ptr [ebp + 0x10], ecx
0x1069: dec eax
0x106a: mov dword ptr [ebp + 0x18], edx
0x106d: dec esp
0x106e: mov dword ptr [ebp + 0x20], eax
0x1071: dec esp
0x1072: mov dword ptr [ebp + 0x28], ecx
0x1075: dec eax
0x1076: cmp dword ptr [ebp + 0x18], 0x111
0x107d: je 0x1110
0x1083: dec eax
0x1084: cmp dword ptr [ebp + 0x18], 0x10
0x1088: je 0x1135
0x108e: dec eax
0x108f: cmp dword ptr [ebp + 0x18], 0x112
0x1096: je 0x10a0
0x1098: dec eax
0x1099: xor eax, eax
0x109b: jmp 0x115a
0x10a0: dec eax
0x10a1: cmp dword ptr [ebp + 0x20], 0xf120
0x10a8: je 0x10cd
0x10aa: dec eax
0x10ab: sub esp, 0x20
0x10ae: dec eax
0x10af: mov ecx, dword ptr [ebp + 0x10]
0x10b2: dec eax
0x10b3: mov edx, dword ptr [ebp + 0x18]
0x10b6: dec esp
0x10b7: mov eax, dword ptr [ebp + 0x20]
0x10ba: dec esp
0x10bb: mov ecx, dword ptr [ebp + 0x28]
0x10be: call dword ptr [0x1024]
0x10c4: dec eax
0x10c5: add esp, 0x20
0x10c8: pop edi
0x10c9: pop esi
0x10ca: pop ebx
0x10cb: leave
0x10cc: ret
0x10cd: dec eax
0x10ce: sub esp, 0x20
0x10d1: dec eax
0x10d2: mov ecx, dword ptr [ebp + 0x10]
0x10d5: mov edx, 0x3e8
0x10da: dec ecx
0x10db: mov eax, 0x40004
0x10e1: call dword ptr [0x1011]
0x10e7: dec eax
0x10e8: add esp, 0x20
0x10eb: dec eax
0x10ec: sub esp, 0x20
0x10ef: dec eax
0x10f0: mov ecx, dword ptr [ebp + 0x10]
0x10f3: dec eax
0x10f4: mov edx, 9
0x10fa: call dword ptr [0x1000]
0x1100: dec eax
0x1101: add esp, 0x20
0x1104: dec eax
0x1105: mov eax, 1
0x110b: pop edi
0x110c: pop esi
0x110d: pop ebx
0x110e: leave
0x110f: ret
0x1110: dec eax
0x1111: cmp dword ptr [ebp + 0x20], 1
0x1115: jne 0x114e
0x1117: dec eax
0x1118: sub esp, 0x20
0x111b: dec eax
0x111c: mov ecx, dword ptr [ebp + 0x10]
0x111f: dec eax
0x1120: mov edx, 6
0x1126: call dword ptr [0xfd4]
0x112c: dec eax
0x112d: add esp, 0x20
0x1130: pop edi
0x1131: pop esi
0x1132: pop ebx
0x1133: leave
0x1134: ret
0x1135: dec eax
0x1136: sub esp, 0x20
0x1139: dec eax
0x113a: mov ecx, dword ptr [ebp + 0x10]
0x113d: dec eax
0x113e: mov edx, 0
0x1144: call dword ptr [0xfa6]
0x114a: dec eax
0x114b: add esp, 0x20
0x114e: dec eax
0x114f: mov eax, 1
0x1155: pop edi
0x1156: pop esi
0x1157: pop ebx
0x1158: leave
0x1159: ret
0x115a: pop edi
0x115b: pop esi
0x115c: pop ebx
0x115d: leave
0x115e: ret
0x115f: add byte ptr [eax], al
0x1161: add byte ptr [eax], al
0x1163: add byte ptr [eax], al
0x1165: add byte ptr [eax], al
0x1167: add byte ptr [eax], al
0x1169: add byte ptr [eax], al
0x116b: add byte ptr [eax], al
0x116d: add byte ptr [eax], al
0x116f: add byte ptr [eax], al
0x1171: add byte ptr [eax], al
0x1173: add byte ptr [eax], al
0x1175: add byte ptr [eax], al
0x1177: add byte ptr [eax], al
0x1179: add byte ptr [eax], al
0x117b: add byte ptr [eax], al
0x117d: add byte ptr [eax], al
0x117f: add byte ptr [eax], al
0x1181: add byte ptr [eax], al
0x1183: add byte ptr [eax], al
0x1185: add byte ptr [eax], al
0x1187: add byte ptr [eax], al
0x1189: add byte ptr [eax], al
0x118b: add byte ptr [eax], al
0x118d: add byte ptr [eax], al
0x118f: add byte ptr [eax], al
0x1191: add byte ptr [eax], al
0x1193: add byte ptr [eax], al
0x1195: add byte ptr [eax], al
0x1197: add byte ptr [eax], al
0x1199: add byte ptr [eax], al
0x119b: add byte ptr [eax], al
0x119d: add byte ptr [eax], al
0x119f: add byte ptr [eax], al
0x11a1: add byte ptr [eax], al
0x11a3: add byte ptr [eax], al
0x11a5: add byte ptr [eax], al
0x11a7: add byte ptr [eax], al
0x11a9: add byte ptr [eax], al
0x11ab: add byte ptr [eax], al
0x11ad: add byte ptr [eax], al
0x11af: add byte ptr [eax], al
0x11b1: add byte ptr [eax], al
0x11b3: add byte ptr [eax], al
0x11b5: add byte ptr [eax], al
0x11b7: add byte ptr [eax], al
0x11b9: add byte ptr [eax], al
0x11bb: add byte ptr [eax], al
0x11bd: add byte ptr [eax], al
0x11bf: add byte ptr [eax], al
0x11c1: add byte ptr [eax], al
0x11c3: add byte ptr [eax], al
0x11c5: add byte ptr [eax], al
0x11c7: add byte ptr [eax], al
0x11c9: add byte ptr [eax], al
0x11cb: add byte ptr [eax], al
0x11cd: add byte ptr [eax], al
0x11cf: add byte ptr [eax], al
0x11d1: add byte ptr [eax], al
0x11d3: add byte ptr [eax], al
0x11d5: add byte ptr [eax], al
0x11d7: add byte ptr [eax], al
0x11d9: add byte ptr [eax], al
0x11db: add byte ptr [eax], al
0x11dd: add byte ptr [eax], al
0x11df: add byte ptr [eax], al
0x11e1: add byte ptr [eax], al
0x11e3: add byte ptr [eax], al
0x11e5: add byte ptr [eax], al
0x11e7: add byte ptr [eax], al
0x11e9: add byte ptr [eax], al
0x11eb: add byte ptr [eax], al
0x11ed: add byte ptr [eax], al
0x11ef: add byte ptr [eax], al
0x11f1: add byte ptr [eax], al
0x11f3: add byte ptr [eax], al
0x11f5: add byte ptr [eax], al
0x11f7: add byte ptr [eax], al
0x11f9: add byte ptr [eax], al
0x11fb: add byte ptr [eax], al
0x11fd: add byte ptr [eax], al