_E_NUI_NO_MORE_ITEMS: 'No more items', _E_NUI_FRAME_NO_DATA: 'Frame has no data', _E_NUI_STREAM_NOT_ENABLED: 'Stream is not enabled', _E_NUI_IMAGE_STREAM_IN_USE: 'Image stream is already in use', _E_NUI_FRAME_LIMIT_EXCEEDED: 'Frame limit exceeded', _E_NUI_FEATURE_NOT_INITIALIZED: 'Feature not initialized', _E_NUI_DATABASE_NOT_FOUND: 'Database not found', _E_NUI_DATABASE_VERSION_MISMATCH: 'Database version mismatch', } try: c_bool = ctypes.c_bool except: c_bool = ctypes.c_uint _kernel32 = ctypes.WinDLL('kernel32') _CreateEvent = _kernel32.CreateEventW _CreateEvent.argtypes = [ ctypes.c_voidp, ctypes.c_uint, ctypes.c_bool, ctypes.c_wchar_p ] _CreateEvent.restype = ctypes.c_voidp _CloseHandle = _kernel32.CloseHandle _CloseHandle.argtypes = [ctypes.c_voidp] _CloseHandle.restype = c_bool _WaitForSingleObject = _kernel32.WaitForSingleObject _WaitForSingleObject.argtypes = [ctypes.c_voidp, ctypes.c_uint32] _WaitForSingleObject.restype = ctypes.c_uint32 _WaitForMultipleObjects = _kernel32.WaitForMultipleObjects
__versionTime__ = '2013-01-22' __author__ = 'Max Kolosov <*****@*****.**>' __doc__ = ''' pybass_ape.py - is ctypes python module for BASS_APE - extension to the BASS audio library that enables the playback of Monkey's Audio streams. ''' import sys, ctypes, platform, pybass QWORD = pybass.QWORD HSTREAM = pybass.HSTREAM BASS_FILEPROCS = pybass.BASS_FILEPROCS if platform.system().lower() == 'windows': bass_ape_module = ctypes.WinDLL('bass_ape') func_type = ctypes.WINFUNCTYPE else: bass_ape_module = ctypes.CDLL('bass_ape') func_type = ctypes.CFUNCTYPE # Additional tags available from BASS_StreamGetTags BASS_TAG_APE = 6 # APE tags # BASS_CHANNELINFO type BASS_CTYPE_STREAM_APE = 0x10700 #HSTREAM BASSAPEDEF(BASS_APE_StreamCreateFile)(BOOL mem, const void *file, QWORD offset, QWORD length, DWORD flags); BASS_APE_StreamCreateFile = func_type(HSTREAM, ctypes.c_byte, ctypes.c_void_p, QWORD, QWORD, ctypes.c_ulong)( ('BASS_APE_StreamCreateFile',
def __init__(self): #self._root = tk.Tk() #self._root.overrideredirect(1) #self._root.withdraw() user32 = ctypes.WinDLL('user32', use_last_error=True) gdi32 = ctypes.WinDLL('gdi32', use_last_error=True) kernel32 = ctypes.WinDLL('kernel32', use_last_error=True) psapi = ctypes.WinDLL('psapi', use_last_error=True) self._user32 = user32 self._gdi32 = gdi32 self._kernel32 = kernel32 self._psapi = psapi # Pay attention to different screen DPI settings self._user32.SetProcessDPIAware() # Mapping to `keyboard` names self._SPECIAL_KEYCODES = { "BACKSPACE": "backspace", "TAB": "tab", "CLEAR": "clear", "ENTER": "enter", "SHIFT": "shift", "CTRL": "ctrl", "ALT": "alt", "PAUSE": "pause", "CAPS_LOCK": "caps lock", "ESC": "esc", "SPACE": "spacebar", "PAGE_UP": "page up", "PAGE_DOWN": "page down", "END": "end", "HOME": "home", "LEFT": "left arrow", "UP": "up arrow", "RIGHT": "right arrow", "DOWN": "down arrow", "SELECT": "select", "PRINT": "print", "PRINTSCREEN": "print screen", "INSERT": "ins", "DELETE": "del", "WIN": "win", "CMD": "win", "META": "win", "NUM0": "keypad 0", "NUM1": "keypad 1", "NUM2": "keypad 2", "NUM3": "keypad 3", "NUM4": "keypad 4", "NUM5": "keypad 5", "NUM6": "keypad 6", "NUM7": "keypad 7", "NUM8": "keypad 8", "NUM9": "keypad 9", "NUM9": "keypad 9", "SEPARATOR": 83, "ADD": 78, "MINUS": 74, "MULTIPLY": 55, "DIVIDE": 53, "F1": "f1", "F2": "f2", "F3": "f3", "F4": "f4", "F5": "f5", "F6": "f6", "F7": "f7", "F8": "f8", "F9": "f9", "F10": "f10", "F11": "f11", "F12": "f12", "F13": "f13", "F14": "f14", "F15": "f15", "F16": "f16", "NUM_LOCK": "num lock", "SCROLL_LOCK": "scroll lock", } self._REGULAR_KEYCODES = { "0": "0", "1": "1", "2": "2", "3": "3", "4": "4", "5": "5", "6": "6", "7": "7", "8": "8", "9": "9", "a": "a", "b": "b", "c": "c", "d": "d", "e": "e", "f": "f", "g": "g", "h": "h", "i": "i", "j": "j", "k": "k", "l": "l", "m": "m", "n": "n", "o": "o", "p": "p", "q": "q", "r": "r", "s": "s", "t": "t", "u": "u", "v": "v", "w": "w", "x": "x", "y": "y", "z": "z", ";": ";", "=": "=", ",": ",", "-": "-", ".": ".", "/": "/", "`": "`", "[": "[", "\\": "\\", "]": "]", "'": "'", " ": " ", } self._UPPERCASE_KEYCODES = { "~": "`", "+": "=", ")": "0", "!": "1", "@": "2", "#": "3", "$": "4", "%": "5", "^": "6", "&": "7", "*": "8", "(": "9", "A": "a", "B": "b", "C": "c", "D": "d", "E": "e", "F": "f", "G": "g", "H": "h", "I": "i", "J": "j", "K": "k", "L": "l", "M": "m", "N": "n", "O": "o", "P": "p", "Q": "q", "R": "r", "S": "s", "T": "t", "U": "u", "V": "v", "W": "w", "X": "x", "Y": "y", "Z": "z", ":": ";", "<": ",", "_": "-", ">": ".", "?": "/", "|": "\\", "\"": "'", "{": "[", "}": "]", }
import ctypes, ctypes.wintypes from process_handler import ProcessHandler kernel32 = ctypes.WinDLL("Kernel32.dll") psapi = ctypes.WinDLL('Psapi.dll') user32 = ctypes.WinDLL("user32.dll") EnumWindows = user32.EnumWindows EnumWindows.restype = ctypes.wintypes.BOOL GetWindowLength = user32.GetWindowTextLengthA GetWindowLength.restype = ctypes.c_int GetWindowThreadProcessId = user32.GetWindowThreadProcessId GetWindowThreadProcessId.restype = ctypes.wintypes.DWORD IsIconic = user32.IsIconic IsIconic.restype = ctypes.wintypes.BOOL pids = set() def WindowEnumCallback(hwindow, param): length = GetWindowLength(hwindow) if length > 0 and not IsIconic(hwindow): processID = ctypes.c_ulong() a = GetWindowThreadProcessId(hwindow, ctypes.byref(processID)) pids.add(processID.value) return True
class eclib(object): # Constants UNITS_NB = 16 # EC-Lab DLL (private) __dll = ctypes.WinDLL("C:\EC-Lab Development Package\\EClib64.dll") # Device Info Structure class DeviceInfoType(ctypes.Structure): _fields_ = [("DeviceCode", ctypes.c_int32), ("RAMSize", ctypes.c_int32), ("CPU", ctypes.c_int32), ("NumberOfChannels", ctypes.c_int32), ("NumberOfSlots", ctypes.c_int32), ("FirmwareVersion", ctypes.c_int32), ("FirmwareDate_yyyy", ctypes.c_int32), ("FirmwareDate_mm", ctypes.c_int32), ("FirmwareDate_dd", ctypes.c_int32), ("HTdisplayOn", ctypes.c_int32), ("NbOfConnectedPC", ctypes.c_int32)] # Current Values Type class CurrentValuesType(ctypes.Structure): _fields_ = [("State", ctypes.c_int32), ("MemFilled", ctypes.c_int32), ("TimeBase", ctypes.c_float), ("Ewe", ctypes.c_float), ("EweRangeMin", ctypes.c_float), ("EweRangeMax", ctypes.c_float), ("Ece", ctypes.c_float), ("EceRangeMin", ctypes.c_float), ("EceRangeMax", ctypes.c_float), ("Eoverflow", ctypes.c_int32), ("I", ctypes.c_float), ("IRange", ctypes.c_int32), ("Ioverflow", ctypes.c_int32), ("ElapsedTime", ctypes.c_float), ("Freq", ctypes.c_float), ("Rcomp", ctypes.c_float), ("Saturation", ctypes.c_int32), ("OptErr", ctypes.c_int32), ("OptPos", ctypes.c_int32)] # Data Information Type class DataInfosType(ctypes.Structure): _fields_ = [("IRQskipped", ctypes.c_int32), ("NbRows", ctypes.c_int32), ("NbCols", ctypes.c_int32), ("TechniqueIndex", ctypes.c_int32), ("TechniqueID", ctypes.c_int32), ("ProcessIndex", ctypes.c_int32), ("loop", ctypes.c_int32), ("StartTime", ctypes.c_double), ("MuxPad", ctypes.c_int32)] # Data buffer Type DataBufferType = ctypes.c_uint32 * 1000 # ECC parameter structure class EccParamType(ctypes.Structure): _fields_ = [("ParamStr", 64 * ctypes.c_byte), ("ParamType", ctypes.c_int32), ("ParamVal", ctypes.c_uint32), ("ParamIndex", ctypes.c_int32)] # ECC parameters structure class EccParamsType(ctypes.Structure): _fields_ = [("len", ctypes.c_int32), ("pParams", ctypes.c_void_p)] # Array of units UnitsType = ctypes.c_byte * UNITS_NB # Array of results ResultsType = ctypes.c_int32 * UNITS_NB # Error Enumeration class ErrorCodeEnum(object): ERR_NOERROR = 0 # Technique Parameter Type Enumeration class ParamTypeEnum(object): PARAM_INT = 0 PARAM_BOOLEAN = 1 PARAM_SINGLE = 2 # ErrorCode BL_ConvertNumericIntoSingle(int num, ref float psgl) BL_ConvertNumericIntoSingle = __dll["BL_ConvertNumericIntoSingle"] BL_ConvertNumericIntoSingle.restype = ctypes.c_int # ErrorCode BL_Connect(string server, byte timeout, ref int connection_id, ref DeviceInfo pInfos) BL_Connect = __dll["BL_Connect"] BL_Connect.restype = ctypes.c_int # ErrorCode BL_TestConnection(int ID) BL_TestConnection = __dll["BL_TestConnection"] BL_TestConnection.restype = ctypes.c_int # ErrorCode BL_LoadFirmware(int ID, byte[] pChannels, int[] pResults, byte Length, bool ShowGauge, # bool ForceReload, string BinFile, string XlxFile) BL_LoadFirmware = __dll["BL_LoadFirmware"] BL_LoadFirmware.restype = ctypes.c_int # bool BL_IsChannelPlugged(int ID, byte ch) BL_IsChannelPlugged = __dll["BL_IsChannelPlugged"] BL_IsChannelPlugged.restype = ctypes.c_bool # ErrorCode BL_GetChannelsPlugged(int ID, byte[] pChPlugged, byte Size) BL_GetChannelsPlugged = __dll["BL_GetChannelsPlugged"] BL_GetChannelsPlugged.restype = ctypes.c_int # ErrorCode BL_GetMessage(int ID, byte ch, [MarshalAs(UnmanagedType.LPArray)] byte[] msg, ref int size) BL_GetMessage = __dll["BL_GetMessage"] BL_GetMessage.restype = ctypes.c_int # ErrorCode BL_LoadTechnique(int ID, byte channel, string pFName, EccParams pparams, bool FirstTechnique, # bool LastTechnique, bool DisplayParams) BL_LoadTechnique = __dll["BL_LoadTechnique"] BL_LoadTechnique.restype = ctypes.c_int # ErrorCode BL_DefineSglParameter(string lbl, float value, int index, IntPtr pParam) BL_DefineSglParameter = __dll["BL_DefineSglParameter"] BL_DefineSglParameter.restype = ctypes.c_int # ErrorCode BL_TestCommSpeed(int ID, byte channel, ref int spd_rcvt, ref int spd_kernel) BL_TestCommSpeed = __dll["BL_TestCommSpeed"] BL_TestCommSpeed.restype = ctypes.c_int # ErrorCode BL_StartChannel(int ID, byte channel) BL_StartChannel = __dll["BL_StartChannel"] BL_StartChannel.restype = ctypes.c_int # ErrorCode BL_GetData(int ID, byte channel, [MarshalAs(UnmanagedType.LPArray, SizeConst=1000)] int[] buf, # ref DataInfos pInfos, ref CurrentValues pValues) BL_GetData = __dll["BL_GetData"] BL_GetData.restype = ctypes.c_int
def enable_ansi_colors_win10(): import ctypes # Function factory for errcheck callbacks that raise WinError on failure. def raise_if(error_result): def check(result, func, args): if result == error_result: raise ctypes.WinError(ctypes.get_last_error()) return args return check # Windows API types. from ctypes.wintypes import BOOL, DWORD, HANDLE, LPCWSTR, LPVOID LPDWORD = ctypes.POINTER(DWORD) # Generic constants. NULL = ctypes.c_void_p(0).value INVALID_HANDLE_VALUE = ctypes.c_void_p(-1).value ERROR_INVALID_PARAMETER = 87 # CreateFile flags. # yapf: disable GENERIC_READ = 0x80000000 GENERIC_WRITE = 0x40000000 FILE_SHARE_READ = 0x01 FILE_SHARE_WRITE = 0x02 OPEN_EXISTING = 3 # yapf: enable # Get/SetConsoleMode flags. ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x04 kernel32 = ctypes.WinDLL('kernel32', use_last_error=True) # HANDLE CreateFileW(...) CreateFileW = kernel32.CreateFileW CreateFileW.restype = HANDLE CreateFileW.errcheck = raise_if(INVALID_HANDLE_VALUE) # yapf: disable CreateFileW.argtypes = (LPCWSTR, # lpFileName DWORD, # dwDesiredAccess DWORD, # dwShareMode LPVOID, # lpSecurityAttributes DWORD, # dwCreationDisposition DWORD, # dwFlagsAndAttributes HANDLE) # hTemplateFile # yapf: enable # BOOL CloseHandle(HANDLE hObject) CloseHandle = kernel32.CloseHandle CloseHandle.restype = BOOL CloseHandle.errcheck = raise_if(False) CloseHandle.argtypes = (HANDLE, ) # BOOL GetConsoleMode(HANDLE hConsoleHandle, LPDWORD lpMode) GetConsoleMode = kernel32.GetConsoleMode GetConsoleMode.restype = BOOL GetConsoleMode.errcheck = raise_if(False) GetConsoleMode.argtypes = (HANDLE, LPDWORD) # BOOL SetConsoleMode(HANDLE hConsoleHandle, DWORD dwMode) SetConsoleMode = kernel32.SetConsoleMode SetConsoleMode.restype = BOOL SetConsoleMode.errcheck = raise_if(False) SetConsoleMode.argtypes = (HANDLE, DWORD) # Open the console output device. conout = CreateFileW("CONOUT$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0) # Get the current mode. mode = DWORD() GetConsoleMode(conout, ctypes.byref(mode)) # Try to set the flag that controls ANSI escape code support. try: SetConsoleMode(conout, mode.value | ENABLE_VIRTUAL_TERMINAL_PROCESSING) except WindowsError as e: if e.winerror == ERROR_INVALID_PARAMETER: return False # Not supported, likely an older version of Windows. raise finally: CloseHandle(conout) return True
import simplejson as json from flask import render_template, Response, session, request as req, \ url_for, current_app from flask_babelex import gettext from flask_security import login_required from pgadmin.utils import PgAdminModule from pgadmin.utils import get_storage_directory from pgadmin.utils.ajax import make_json_response from pgadmin.utils.preferences import Preferences # Checks if platform is Windows if _platform == "win32": import ctypes oldmode = ctypes.c_uint() kernel32 = ctypes.WinDLL('kernel32') SEM_FAILCRITICALERRORS = 1 SEM_NOOPENFILEERRORBOX = 0x8000 SEM_FAIL = SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS file_root = "" # uppercase supported in py2, ascii_uppercase supported in py3 try: letters = string.uppercase except Exception: letters = string.ascii_uppercase # import unquote from urlib for python2.x and python3.x try: from urllib import unquote except Exception as e:
# Import the required module to handle Windows API Calls import ctypes # Import Python -> Windows Types from ctypes from ctypes.wintypes import DWORD,BOOL,HANDLE,LPWSTR,WORD,LPBYTE # Grab a handle to kernel32.dll & User32.dll & Advapi32.dll k_handle = ctypes.WinDLL("Kernel32.dll") u_handle = ctypes.WinDLL("User32.dll") a_handle = ctypes.WinDLL("Advapi32.dll") # Access Rights PROCESS_ALL_ACCESS = (0x000F0000 | 0x00100000 | 0xFFF) # Token Access Rights STANDARD_RIGHTS_REQUIRED = 0x000F0000 STANDARD_RIGHTS_READ = 0x00020000 TOKEN_ASSIGN_PRIMARY = 0x0001 TOKEN_DUPLICATE = 0x0002 TOKEN_IMPERSONATION = 0x0004 TOKEN_QUERY = 0x0008 TOKEN_QUERY_SOURCE = 0x0010 TOKEN_ADJUST_PRIVILEGES = 0x0020 TOKEN_ADJUST_GROUPS = 0x0040 TOKEN_ADJUST_DEFAULT = 0x0080 TOKEN_ADJUST_SESSIONID = 0x0100 TOKEN_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY) TOKEN_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE |
# Import the required module to handle Windows API Calls. import ctypes # Grab a handle to kernel32.dll k_handle = ctypes.WinDLL("Kernel32.dll") # Win API Call # HANDLE OpenProcess( # DWORD dwDesiredAccess, # BOOL bInheritHandle, # DWAORD dwProcessId # ); # Access Rights PROCESS_ALL_ACCESS = (0x000F0000 | 0x00100000 | 0xFFF) # Access Rights PROCESS_ALL_ACCESS = (0x000F0000 | 0x00100000 | 0xFFF) # Setting Up The Params dwDesiredAccess = PROCESS_ALL_ACCESS bInheritHandle = False dwProcessId = 0x100c # Replace This With Your Own! # Calling the Windows API Call response = k_handle.OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId) # Check For Errors error = k_handle.GetLastError() if error != 0: print("Handle Not Created!")
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Microscope. If not, see <http://www.gnu.org/licenses/>. """Boston Micromachines deformable mirrors SDK. """ import ctypes import os from ctypes import c_char, c_char_p, c_double, c_int, c_uint, c_uint32 if os.name in ("nt", "ce"): # Not actually tested yet SDK = ctypes.WinDLL("BMC2") else: SDK = ctypes.CDLL("libBMC.so.3") # Definitions from BMCDefs.h MAX_PATH = 260 SERIAL_NUMBER_LEN = 11 MAX_DM_SIZE = 4096 class DM_PRIV(ctypes.Structure): pass class DM_DRIVER(ctypes.Structure):
# else: # msvcrt.putwch(b) if termios: Console = ConsolePosix VT_ENABLED = True else: Console = ConsoleWindows # Windows VT mode ( >= win10 only) # https://bugs.python.org/msg291732 import ctypes from ctypes import wintypes kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) ERROR_INVALID_PARAMETER = 0x0057 ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004 def _check_bool(result, func, args): if not result: raise ctypes.WinError(ctypes.get_last_error()) return args LPDWORD = ctypes.POINTER(wintypes.DWORD) kernel32.GetConsoleMode.errcheck = _check_bool kernel32.GetConsoleMode.argtypes = (wintypes.HANDLE, LPDWORD) kernel32.SetConsoleMode.errcheck = _check_bool kernel32.SetConsoleMode.argtypes = (wintypes.HANDLE, wintypes.DWORD)
import ctypes from ctypes import wintypes u_handle = ctypes.WinDLL("User32.dll") k_handle = ctypes.WinDLL("kernel32.dll") ''' Windows API HWND FindWindowA( LPCSTR lpClassName, LPCSTR lpWindowName ); DWORD GetWindowThreadProcessId( HWND hWnd, LPDWORD lpdwProcessId ); HANDLE OpenProcess( DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwProcessId ); BOOL TerminateProcess( HANDLE hProcess, UINT uExitCode ); ''' PROCESS_ALL_ACCESS = (0x00100000 | 0xF0000 | 0xFFF)
def __init_dll(self, nodeid): """ Initialize the API from a Windows DLL. """ # Load the DLL self.Api = ctypes.WinDLL("otnodeapi.dll") if self.Api == None: raise OSError("Failed to load otnodeapi.dll!") # Define the functions self.Api.otNodeLog.argtypes = [ctypes.c_char_p] self.Api.otNodeInit.argtypes = [ctypes.c_uint] self.Api.otNodeInit.restype = ctypes.c_void_p self.Api.otNodeFinalize.argtypes = [ctypes.c_void_p] self.Api.otNodeSetMode.argtypes = [ctypes.c_void_p, ctypes.c_char_p] self.Api.otNodeInterfaceUp.argtypes = [ctypes.c_void_p] self.Api.otNodeInterfaceDown.argtypes = [ctypes.c_void_p] self.Api.otNodeThreadStart.argtypes = [ctypes.c_void_p] self.Api.otNodeThreadStop.argtypes = [ctypes.c_void_p] self.Api.otNodeCommissionerStart.argtypes = [ctypes.c_void_p] self.Api.otNodeCommissionerJoinerAdd.argtypes = [ ctypes.c_void_p, ctypes.c_char_p, ctypes.c_char_p ] self.Api.otNodeCommissionerStop.argtypes = [ctypes.c_void_p] self.Api.otNodeJoinerStart.argtypes = [ ctypes.c_void_p, ctypes.c_char_p, ctypes.c_char_p ] self.Api.otNodeJoinerStop.argtypes = [ctypes.c_void_p] self.Api.otNodeClearWhitelist.argtypes = [ctypes.c_void_p] self.Api.otNodeEnableWhitelist.argtypes = [ctypes.c_void_p] self.Api.otNodeDisableWhitelist.argtypes = [ctypes.c_void_p] self.Api.otNodeAddWhitelist.argtypes = [ ctypes.c_void_p, ctypes.c_char_p, ctypes.c_byte ] self.Api.otNodeRemoveWhitelist.argtypes = [ ctypes.c_void_p, ctypes.c_char_p ] self.Api.otNodeGetAddr16.argtypes = [ctypes.c_void_p] self.Api.otNodeGetAddr16.restype = ctypes.c_ushort self.Api.otNodeGetAddr64.argtypes = [ctypes.c_void_p] self.Api.otNodeGetAddr64.restype = ctypes.c_char_p self.Api.otNodeGetHashMacAddress.argtypes = [ctypes.c_void_p] self.Api.otNodeGetHashMacAddress.restype = ctypes.c_char_p self.Api.otNodeSetChannel.argtypes = [ctypes.c_void_p, ctypes.c_ubyte] self.Api.otNodeGetChannel.argtypes = [ctypes.c_void_p] self.Api.otNodeGetChannel.restype = ctypes.c_ubyte self.Api.otNodeSetMasterkey.argtypes = [ ctypes.c_void_p, ctypes.c_char_p ] self.Api.otNodeGetMasterkey.argtypes = [ctypes.c_void_p] self.Api.otNodeGetMasterkey.restype = ctypes.c_char_p self.Api.otNodeGetKeySequenceCounter.argtypes = [ctypes.c_void_p] self.Api.otNodeGetKeySequenceCounter.restype = ctypes.c_uint self.Api.otNodeSetKeySequenceCounter.argtypes = [ ctypes.c_void_p, ctypes.c_uint ] self.Api.otNodeSetKeySwitchGuardTime.argtypes = [ ctypes.c_void_p, ctypes.c_uint ] self.Api.otNodeSetNetworkIdTimeout.argtypes = [ ctypes.c_void_p, ctypes.c_ubyte ] self.Api.otNodeGetNetworkName.argtypes = [ctypes.c_void_p] self.Api.otNodeGetNetworkName.restype = ctypes.c_char_p self.Api.otNodeSetNetworkName.argtypes = [ ctypes.c_void_p, ctypes.c_char_p ] self.Api.otNodeGetPanId.argtypes = [ctypes.c_void_p] self.Api.otNodeGetPanId.restype = ctypes.c_ushort self.Api.otNodeSetPanId.argtypes = [ctypes.c_void_p, ctypes.c_ushort] self.Api.otNodeGetPartitionId.argtypes = [ctypes.c_void_p] self.Api.otNodeGetPartitionId.restype = ctypes.c_uint self.Api.otNodeSetPartitionId.argtypes = [ ctypes.c_void_p, ctypes.c_uint ] self.Api.otNodeSetRouterUpgradeThreshold.argtypes = [ ctypes.c_void_p, ctypes.c_ubyte ] self.Api.otNodeSetRouterDowngradeThreshold.argtypes = [ ctypes.c_void_p, ctypes.c_ubyte ] self.Api.otNodeReleaseRouterId.argtypes = [ ctypes.c_void_p, ctypes.c_ubyte ] self.Api.otNodeGetState.argtypes = [ctypes.c_void_p] self.Api.otNodeGetState.restype = ctypes.c_char_p self.Api.otNodeSetState.argtypes = [ctypes.c_void_p, ctypes.c_char_p] self.Api.otNodeGetTimeout.argtypes = [ctypes.c_void_p] self.Api.otNodeGetTimeout.restype = ctypes.c_uint self.Api.otNodeSetTimeout.argtypes = [ctypes.c_void_p, ctypes.c_uint] self.Api.otNodeGetWeight.argtypes = [ctypes.c_void_p] self.Api.otNodeGetWeight.restype = ctypes.c_ubyte self.Api.otNodeSetWeight.argtypes = [ctypes.c_void_p, ctypes.c_ubyte] self.Api.otNodeAddIpAddr.argtypes = [ctypes.c_void_p, ctypes.c_char_p] self.Api.otNodeGetAddrs.argtypes = [ctypes.c_void_p] self.Api.otNodeGetAddrs.restype = ctypes.c_char_p self.Api.otNodeGetContextReuseDelay.argtypes = [ctypes.c_void_p] self.Api.otNodeGetContextReuseDelay.restype = ctypes.c_uint self.Api.otNodeSetContextReuseDelay.argtypes = [ ctypes.c_void_p, ctypes.c_uint ] self.Api.otNodeAddPrefix.argtypes = [ ctypes.c_void_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p ] self.Api.otNodeRemovePrefix.argtypes = [ ctypes.c_void_p, ctypes.c_char_p ] self.Api.otNodeAddRoute.argtypes = [ ctypes.c_void_p, ctypes.c_char_p, ctypes.c_char_p ] self.Api.otNodeRemoveRoute.argtypes = [ ctypes.c_void_p, ctypes.c_char_p ] self.Api.otNodeRegisterNetdata.argtypes = [ctypes.c_void_p] self.Api.otNodeEnergyScan.argtypes = [ ctypes.c_void_p, ctypes.c_uint, ctypes.c_ubyte, ctypes.c_ushort, ctypes.c_ushort, ctypes.c_char_p ] self.Api.otNodePanIdQuery.argtypes = [ ctypes.c_void_p, ctypes.c_ushort, ctypes.c_uint, ctypes.c_char_p ] self.Api.otNodeScan.argtypes = [ctypes.c_void_p] self.Api.otNodeScan.restype = ctypes.c_char_p self.Api.otNodePing.argtypes = [ ctypes.c_void_p, ctypes.c_char_p, ctypes.c_ushort, ctypes.c_uint, ctypes.c_uint16 ] self.Api.otNodePing.restype = ctypes.c_uint self.Api.otNodeSetRouterSelectionJitter.argtypes = [ ctypes.c_void_p, ctypes.c_ubyte ] self.Api.otNodeCommissionerAnnounceBegin.argtypes = [ ctypes.c_void_p, ctypes.c_uint, ctypes.c_ubyte, ctypes.c_ushort, ctypes.c_char_p ] self.Api.otNodeSetActiveDataset.argtypes = [ ctypes.c_void_p, ctypes.c_ulonglong, ctypes.c_ushort, ctypes.c_ushort, ctypes.c_uint, ctypes.c_char_p ] self.Api.otNodeSetPendingDataset.argtypes = [ ctypes.c_void_p, ctypes.c_ulonglong, ctypes.c_ulonglong, ctypes.c_ushort, ctypes.c_ushort ] self.Api.otNodeSendPendingSet.argtypes = [ ctypes.c_void_p, ctypes.c_ulonglong, ctypes.c_ulonglong, ctypes.c_uint, ctypes.c_ushort, ctypes.c_ushort, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p ] self.Api.otNodeSendActiveSet.argtypes = [ ctypes.c_void_p, ctypes.c_ulonglong, ctypes.c_ushort, ctypes.c_ushort, ctypes.c_uint, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p ] self.Api.otNodeSetMaxChildren.argtypes = [ ctypes.c_void_p, ctypes.c_ubyte ] # Initialize a new node self.otNode = self.Api.otNodeInit(ctypes.c_uint(nodeid)) if self.otNode == None: raise OSError("otNodeInit failed!")
import ctypes from ctypes import wintypes import os import time xinput = ctypes.WinDLL('xinput1_3', use_last_error=True) def poll(id): state = XINPUT_STATE() ctypes.memset(ctypes.addressof(state), 0, ctypes.sizeof(state)) xinput.XInputGetState(id, ctypes.byref(state)) return xinput_dict(state.gamepad) def xinput_dict(struct): r = dict((i[0], getattr(struct, i[0])) for i in struct._fields_) r['buttons'] = list(bitmask_iter(r['buttons'], 16)) return r ERROR_SUCCESS = 0x0000 ERROR_DEVICE_NOT_CONNECTED = 0x048F class NoControllerError(Exception): def __init__(self, message): super(NoControllerError, self).__init__(message) class XINPUT_GAMEPAD(ctypes.Structure):
BASS_SFX - An extension allowing the use of Sonique, Winamp, Windows Media Player, and BassBox visual plugins with BASS. ''' import sys, ctypes, platform, pybass #~ from ctypes.wintypes import HINSTANCE #~ from ctypes.wintypes import HWND #~ from ctypes.wintypes import LPCWSTR #~ from ctypes.wintypes import HDC HSTREAM = pybass.HSTREAM BASS_FILEPROCS = pybass.BASS_FILEPROCS HSFX = ctypes.c_long if platform.system().lower() == 'windows': bass_vst_module = ctypes.WinDLL('BASS_SFX') func_type = ctypes.WINFUNCTYPE else: bass_vst_module = ctypes.CDLL('BASS_SFX') func_type = ctypes.CFUNCTYPE # visualization plugin types BASS_SFX_SONIQUE = 0 BASS_SFX_WINAMP = 1 BASS_SFX_WMP = 2 BASS_SFX_BBP = 3 # PluginCreate Flags BASS_SFX_SONIQUE_OPENGL = 1 # render sonique plugins using OpenGL BASS_SFX_SONIQUE_OPENGL_DOUBLEBUFFER = 2 #use OpenGL double buffering
import ctypes from ctypes import * import sys import os import time import limeRFE_H as LH if os.name == 'nt': libLimeSuite = ctypes.WinDLL("C:\\Path\\to\\LimeSuite.dll") else: libLimeSuite = ctypes.cdll.LoadLibrary('./libLimeSuite.so') rfe = c_void_p() # Open port if os.name == 'nt': rfe = libLimeSuite.RFE_Open(c_char_p("COM24"), None) else: rfe = libLimeSuite.RFE_Open(c_char_p("/dev/ttyUSB0"), None) if (rfe == 0): print("Error initializing serial port") exit(1) print "Port opened" #Configure LimeRFE to use channel HAM 2m channel in receive mode. #Transmit output is routed to TX/RX output. Notch is off. Attenuation is 0. result = libLimeSuite.RFE_Configure(rfe, c_int(LH.CID_HAM_0145), c_int(LH.CID_HAM_0145), c_int(LH.PORT_1),
def set_wallpapers(images, imageNumber): print(" ") print(" ") print(" ") print("Setting wallpapers") print("-----------------------------------------------------") print(" ") # Limit the number of images per day. Just to stop the desktop from changing an unreasonable amount. # Just in case a large album is downloaded. # 15 hours. 200 images. 4Mins 30Secs per image if imageNumber > imageNumLimit: imageNumber = imageNumLimit # Get the epoch time for the last image change timeAddDays = datetime.now() + timedelta(days=lastImageDay) timeAddDaysFormatted = timeAddDays.strftime("%Y-%m-%d") timeLastImageString = timeAddDaysFormatted + "T" + lastImageHour + ":" + lastImageMin + ":00Z" timeLastImageEpoch = calendar.timegm( time.strptime(timeLastImageString, "%Y-%m-%dT%H:%M:%SZ")) print( "Last change (GMT +0):", time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timeLastImageEpoch)), " - Epoch:", timeLastImageEpoch) # Get the epoch time for the reset time - aka start the script again. timeAddDays = datetime.now() + timedelta(days=resetDay) timeAddDaysFormatted = timeAddDays.strftime("%Y-%m-%d") timeResetString = timeAddDaysFormatted + "T" + resetHour + ":" + resetMin + ":00Z" timeResetEpoch = calendar.timegm( time.strptime(timeResetString, "%Y-%m-%dT%H:%M:%SZ")) print("Reset time (GMT +0):", time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timeResetEpoch)), " - Epoch:", timeResetEpoch) # Get the time of when this is started timeStartEpoch = calendar.timegm(time.gmtime()) # Calculate the period for all wallpapers timeDiffEpoch = timeLastImageEpoch - timeStartEpoch diffSplit = modf(timeDiffEpoch / 60) diffSplit2 = modf(diffSplit[1] / 60) print('{:d}:{:02d}:{:02d} to display all images - Epoch: {:.0f}'.format( int(diffSplit2[1]), round(60 * diffSplit2[0]), round(60 * diffSplit[0]), timeDiffEpoch)) # Calculate the period for each wallpaper timePerImage = timeDiffEpoch / imageNumber diffSplit = modf(timePerImage / 60) diffSplit2 = modf(diffSplit[1] / 60) print('{:d}:{:02d}:{:02d} time per image - Epoch: {:.0f}'.format( int(diffSplit2[1]), round(60 * diffSplit2[0]), round(60 * diffSplit[0]), timePerImage)) print(" ") print("Start time (GMT +0):", time.strftime('%H:%M:%S', time.localtime(timeStartEpoch)), " - Epoch:", timeStartEpoch) # Update the desktop wallpaper for i, image in enumerate(images): print("Wallpaper: ", i + 1, " of ", imageNumber) # Change wallpaper user32 = ctypes.WinDLL('user32') SystemParametersInfo = user32.SystemParametersInfoW SystemParametersInfo.argtypes = ctypes.c_uint, ctypes.c_uint, ctypes.c_void_p, ctypes.c_uint SystemParametersInfo.restype = wintypes.BOOL SystemParametersInfo(0x0014, 0, imageLocation + image, 0x0001 | 0x0002) timeNowEpoch = calendar.timegm(time.gmtime()) print("Changed at (GMT +0):", time.strftime('%H:%M:%S', time.localtime(timeNowEpoch)), " - Epoch:", timeNowEpoch) print(" ") # Limit the number of images per day. Just to stop the desktop from changing an unreasonable amount. # Just in case a large album is downloaded. # 15 hours. 200 images. 4Mins 30Secs per image if i > imageNumLimit: break # Pause the script for a length of time until it's time to update the wallpaper pause.until(timeStartEpoch + (timePerImage * (i + 1))) # Last image has been set until the reset time print("Final image set") print("Hibernating until (GMT +0):", time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timeResetEpoch)), " - Epoch:", timeResetEpoch) pause.until( timeResetEpoch + 2 ) # Plus 2 seconds to ensure a race condition doesn't happen with the next statment print("Pause until finished") while True: timeNowEpoch = calendar.timegm(time.gmtime()) # Time to restart the script? 9am the following day. if timeNowEpoch > timeResetEpoch: print(" ") print(" ") print("Resetting time...!") print(" ") print(" ") break print("While True") time.sleep( 5 ) # Sleep for 5 seconds if the time to restart hasn't been met yet. return
def findAndKillProcessNT(self, processName, killProcess): """Find (and optionally terminate) processes by the specified name. Returns true if process by that name exists (after attempting to terminate the process). """ import sys, os.path, ctypes, ctypes.wintypes psapi = ctypes.WinDLL('Psapi.dll') enum_processes = psapi.EnumProcesses enum_processes.restype = ctypes.wintypes.BOOL get_process_image_file_name = psapi.GetProcessImageFileNameA get_process_image_file_name.restype = ctypes.wintypes.DWORD kernel32 = ctypes.WinDLL('kernel32.dll') open_process = kernel32.OpenProcess open_process.restype = ctypes.wintypes.HANDLE terminate_process = kernel32.TerminateProcess terminate_process.restype = ctypes.wintypes.BOOL close_handle = kernel32.CloseHandle MAX_PATH = 260 PROCESS_TERMINATE = 0x0001 PROCESS_QUERY_INFORMATION = 0x0400 count = 512 while True: process_ids = (ctypes.wintypes.DWORD * count)() cb = ctypes.sizeof(process_ids) bytes_returned = ctypes.wintypes.DWORD() if enum_processes(ctypes.byref(process_ids), cb, ctypes.byref(bytes_returned)): if bytes_returned.value < cb: break else: count *= 2 else: logging.error("Call to EnumProcesses failed") return False processMayBeStillRunning = False for index in range( int(bytes_returned.value / ctypes.sizeof(ctypes.wintypes.DWORD))): process_id = process_ids[index] h_process = open_process( PROCESS_TERMINATE | PROCESS_QUERY_INFORMATION, False, process_id) if h_process: image_file_name = (ctypes.c_char * MAX_PATH)() if get_process_image_file_name(h_process, image_file_name, MAX_PATH) > 0: filename = os.path.basename(image_file_name.value) if filename.decode() == processName: # Found the process we are looking for if not killProcess: # we don't need to kill the process, just indicate that there is a process to kill res = close_handle(h_process) return True if not terminate_process(h_process, 1): # failed to terminate process, it may be still running processMayBeStillRunning = True res = close_handle(h_process) return processMayBeStillRunning
def detect_fate_sharing_support_win32(): global win32_job, win32_AssignProcessToJobObject if win32_job is None and sys.platform == "win32": import ctypes try: from ctypes.wintypes import BOOL, DWORD, HANDLE, LPVOID, LPCWSTR kernel32 = ctypes.WinDLL("kernel32") kernel32.CreateJobObjectW.argtypes = (LPVOID, LPCWSTR) kernel32.CreateJobObjectW.restype = HANDLE sijo_argtypes = (HANDLE, ctypes.c_int, LPVOID, DWORD) kernel32.SetInformationJobObject.argtypes = sijo_argtypes kernel32.SetInformationJobObject.restype = BOOL kernel32.AssignProcessToJobObject.argtypes = (HANDLE, HANDLE) kernel32.AssignProcessToJobObject.restype = BOOL kernel32.IsDebuggerPresent.argtypes = () kernel32.IsDebuggerPresent.restype = BOOL except (AttributeError, TypeError, ImportError): kernel32 = None job = kernel32.CreateJobObjectW(None, None) if kernel32 else None job = subprocess.Handle(job) if job else job if job: from ctypes.wintypes import DWORD, LARGE_INTEGER, ULARGE_INTEGER class JOBOBJECT_BASIC_LIMIT_INFORMATION(ctypes.Structure): _fields_ = [ ("PerProcessUserTimeLimit", LARGE_INTEGER), ("PerJobUserTimeLimit", LARGE_INTEGER), ("LimitFlags", DWORD), ("MinimumWorkingSetSize", ctypes.c_size_t), ("MaximumWorkingSetSize", ctypes.c_size_t), ("ActiveProcessLimit", DWORD), ("Affinity", ctypes.c_size_t), ("PriorityClass", DWORD), ("SchedulingClass", DWORD), ] class IO_COUNTERS(ctypes.Structure): _fields_ = [ ("ReadOperationCount", ULARGE_INTEGER), ("WriteOperationCount", ULARGE_INTEGER), ("OtherOperationCount", ULARGE_INTEGER), ("ReadTransferCount", ULARGE_INTEGER), ("WriteTransferCount", ULARGE_INTEGER), ("OtherTransferCount", ULARGE_INTEGER), ] class JOBOBJECT_EXTENDED_LIMIT_INFORMATION(ctypes.Structure): _fields_ = [ ("BasicLimitInformation", JOBOBJECT_BASIC_LIMIT_INFORMATION), ("IoInfo", IO_COUNTERS), ("ProcessMemoryLimit", ctypes.c_size_t), ("JobMemoryLimit", ctypes.c_size_t), ("PeakProcessMemoryUsed", ctypes.c_size_t), ("PeakJobMemoryUsed", ctypes.c_size_t), ] debug = kernel32.IsDebuggerPresent() # Defined in <WinNT.h>; also available here: # https://docs.microsoft.com/en-us/windows/win32/api/jobapi2/nf-jobapi2-setinformationjobobject JobObjectExtendedLimitInformation = 9 JOB_OBJECT_LIMIT_BREAKAWAY_OK = 0x00000800 JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION = 0x00000400 JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000 buf = JOBOBJECT_EXTENDED_LIMIT_INFORMATION() buf.BasicLimitInformation.LimitFlags = ( (0 if debug else JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE) | JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION | JOB_OBJECT_LIMIT_BREAKAWAY_OK) infoclass = JobObjectExtendedLimitInformation if not kernel32.SetInformationJobObject( job, infoclass, ctypes.byref(buf), ctypes.sizeof(buf)): job = None win32_AssignProcessToJobObject = (kernel32.AssignProcessToJobObject if kernel32 is not None else False) win32_job = job if job else False return bool(win32_job)
hwPartno = ct.create_string_buffer(b"", 8) hwVersion = ct.create_string_buffer(b"", 8) hwModel = ct.create_string_buffer(b"", 24) errorString = ct.create_string_buffer(b"", 40) numChannels = ct.c_int() resolution = ct.c_double() syncRate = ct.c_int() countRate = ct.c_int() flags = ct.c_int() nRecords = ct.c_int() ctcstatus = ct.c_int() warnings = ct.c_int() warningstext = ct.create_string_buffer(b"", 16384) if os.name == "nt": mhlib = ct.WinDLL("mhlib.dll") else: mhlib = ct.CDLL("libmh150.so") def closeDevices(): for i in range(0, MAXDEVNUM): mhlib.MH_CloseDevice(ct.c_int(i)) exit(0) def stoptttr(): retcode = mhlib.MH_StopMeas(ct.c_int(dev[0])) if retcode < 0: print("MH_StopMeas error %1d. Aborted." % retcode) closeDevices()
import ctypes from ctypes import create_string_buffer, c_int, c_char, c_char_p, c_byte, c_ubyte, c_short, c_double, cdll, pointer, byref, c_uint32 import time import numpy hhlib = ctypes.WinDLL("hhlib.dll") print hhlib class HydraHarp400(object): MODE_HIST = 0 HISTCHAN = 65536 def __init__(self, devnum=0, refsource='internal', debug=False): self.debug = debug self.devnum = int(devnum) self.lib_version = create_string_buffer(8) hhlib.HH_GetLibraryVersion(self.lib_version) if self.debug: print "HHLib Version: '%s'" % self.lib_version.value #% str(self.lib_version.raw).strip() self.lib_version = self.lib_version.value self.hw_serial = create_string_buffer(8) retcode = hhlib.HH_OpenDevice(self.devnum, self.hw_serial) if (retcode == 0): self.hw_serial = self.hw_serial.value if self.debug: print "Device %i Found, serial %s" % (self.devnum, self.hw_serial)
def main(): try: import tensorflow as tf print("TensorFlow successfully installed.") if tf.test.is_built_with_cuda(): print("The installed version of TensorFlow includes GPU support.") else: print("The installed version of TensorFlow does not include GPU support.") sys.exit(0) except ImportError: print("ERROR: Failed to import the TensorFlow module.") print(""" WARNING! This script is no longer maintained! ============================================= Since TensorFlow 1.4, the self-check has been integrated with TensorFlow itself, and any missing DLLs will be reported when you execute the `import tensorflow` statement. The error messages printed below refer to TensorFlow 1.3 and earlier, and are inaccurate for later versions of TensorFlow.""") candidate_explanation = False python_version = sys.version_info.major, sys.version_info.minor print("\n- Python version is %d.%d." % python_version) if not (python_version == (3, 5) or python_version == (3, 6)): candidate_explanation = True print("- The official distribution of TensorFlow for Windows requires " "Python version 3.5 or 3.6.") try: _, pathname, _ = imp.find_module("tensorflow") print("\n- TensorFlow is installed at: %s" % pathname) except ImportError: candidate_explanation = False print(""" - No module named TensorFlow is installed in this Python environment. You may install it using the command `pip install tensorflow`.""") try: msvcp140 = ctypes.WinDLL("msvcp140.dll") except OSError: candidate_explanation = True print(""" - Could not load 'msvcp140.dll'. TensorFlow requires that this DLL be installed in a directory that is named in your %PATH% environment variable. You may install this DLL by downloading Microsoft Visual C++ 2015 Redistributable Update 3 from this URL: https://www.microsoft.com/en-us/download/details.aspx?id=53587""") try: cudart64_80 = ctypes.WinDLL("cudart64_80.dll") except OSError: candidate_explanation = True print(""" - Could not load 'cudart64_80.dll'. The GPU version of TensorFlow requires that this DLL be installed in a directory that is named in your %PATH% environment variable. Download and install CUDA 8.0 from this URL: https://developer.nvidia.com/cuda-toolkit""") try: nvcuda = ctypes.WinDLL("nvcuda.dll") except OSError: candidate_explanation = True print(""" - Could not load 'nvcuda.dll'. The GPU version of TensorFlow requires that this DLL be installed in a directory that is named in your %PATH% environment variable. Typically it is installed in 'C:\Windows\System32'. If it is not present, ensure that you have a CUDA-capable GPU with the correct driver installed.""") cudnn5_found = False try: cudnn5 = ctypes.WinDLL("cudnn64_5.dll") cudnn5_found = True except OSError: candidate_explanation = True print(""" - Could not load 'cudnn64_5.dll'. The GPU version of TensorFlow requires that this DLL be installed in a directory that is named in your %PATH% environment variable. Note that installing cuDNN is a separate step from installing CUDA, and it is often found in a different directory from the CUDA DLLs. You may install the necessary DLL by downloading cuDNN 5.1 from this URL: https://developer.nvidia.com/cudnn""") cudnn6_found = False try: cudnn = ctypes.WinDLL("cudnn64_6.dll") cudnn6_found = True except OSError: candidate_explanation = True if not cudnn5_found or not cudnn6_found: print() if not cudnn5_found and not cudnn6_found: print("- Could not find cuDNN.") elif not cudnn5_found: print("- Could not find cuDNN 5.1.") else: print("- Could not find cuDNN 6.") print(""" The GPU version of TensorFlow requires that the correct cuDNN DLL be installed in a directory that is named in your %PATH% environment variable. Note that installing cuDNN is a separate step from installing CUDA, and it is often found in a different directory from the CUDA DLLs. The correct version of cuDNN depends on your version of TensorFlow: * TensorFlow 1.2.1 or earlier requires cuDNN 5.1. ('cudnn64_5.dll') * TensorFlow 1.3 or later requires cuDNN 6. ('cudnn64_6.dll') You may install the necessary DLL by downloading cuDNN from this URL: https://developer.nvidia.com/cudnn""") if not candidate_explanation: print(""" - All required DLLs appear to be present. Please open an issue on the TensorFlow GitHub page: https://github.com/tensorflow/tensorflow/issues""") sys.exit(-1)
def __enter__(self): QApplication.setOverrideCursor(self.cursor) def __exit__(self, exc_type, exc_val, exc_tb): QApplication.restoreOverrideCursor() return exc_type is None ####################### # IMPORT wrapper if os.name == 'nt' and sys.version_info < (3, 8): import ctypes from ctypes import windll, wintypes kernel32 = ctypes.WinDLL('kernel32', use_last_error=True) _hasAddDllDirectory = hasattr(kernel32, 'AddDllDirectory') if _hasAddDllDirectory: _import_path = os.environ['PATH'] _import_paths = {} def _errcheck_zero(result, func, args): if not result: raise ctypes.WinError(ctypes.get_last_error()) return args DLL_DIRECTORY_COOKIE = wintypes.LPVOID _AddDllDirectory = kernel32.AddDllDirectory _AddDllDirectory.errcheck = _errcheck_zero
gen_dir = os.path.join(basedir, subdir) if not os.path.exists(gen_dir): logger.info("Creating writeable comtypes cache directory: '%s'", gen_dir) os.makedirs(gen_dir) gen.__path__.append(gen_dir) result = os.path.abspath(gen.__path__[-1]) logger.info("Using writeable comtypes cache directory: '%s'", result) return result ################################################################ if os.name == "ce": SHGetSpecialFolderPath = ctypes.OleDLL("coredll").SHGetSpecialFolderPath GetModuleFileName = ctypes.WinDLL("coredll").GetModuleFileNameW else: SHGetSpecialFolderPath = ctypes.OleDLL( "shell32.dll").SHGetSpecialFolderPathW GetModuleFileName = ctypes.WinDLL("kernel32.dll").GetModuleFileNameW SHGetSpecialFolderPath.argtypes = [ ctypes.c_ulong, ctypes.c_wchar_p, ctypes.c_int, ctypes.c_int ] GetModuleFileName.restype = ctypes.c_ulong GetModuleFileName.argtypes = [ctypes.c_ulong, ctypes.c_wchar_p, ctypes.c_ulong] CSIDL_APPDATA = 26 MAX_PATH = 260 def _create_comtypes_gen_package():
import ctypes dll = ctypes.WinDLL("user32.dll") dll.LockWorkStation()
# from __future__ import print_function from distutils.core import setup import ctypes from ctypes import * from ctypes.util import find_library import sys import os.path signalfile = ".sdkwarning" if not os.path.exists(signalfile): name = 'ps2000' try: if sys.platform == 'win32': result = ctypes.WinDLL(find_library(name)) else: result = cdll.LoadLibrary(find_library(name)) except OSError: print("Please install the PicoSDK in order to use this wrapper." "Visit https://www.picotech.com/downloads") exit(1) open(signalfile, 'a').close() setup(name='PicoSDK', version='1.0', description='PicoSDK Python wrapper', author='Pico Technology Ltd', author_email='*****@*****.**', url='https://www.picotech.com', packages=['picosdk'],
# _adslib can be WinDLL or CDLL depending on OS _adsDLL: Union["ctypes.WinDLL", "ctypes.CDLL"] # load dynamic ADS library if platform_is_windows(): # pragma: no cover, skip Windows test dlldir_handle = None if sys.version_info >= (3, 8) and "TWINCAT3DIR" in os.environ: # Starting with version 3.8, CPython does not consider the PATH environment # variable any more when resolving DLL paths. The following works with the default # installation of the Beckhoff TwinCAT ADS DLL. dll_path = os.environ["TWINCAT3DIR"] + "\\..\\AdsApi\\TcAdsDll" if platform.architecture()[0] == "64bit": dll_path += "\\x64" dlldir_handle = os.add_dll_directory(dll_path) try: _adsDLL = ctypes.WinDLL("TcAdsDll.dll") # type: ignore finally: if dlldir_handle: # Do not clobber the load path for other modules dlldir_handle.close() NOTEFUNC = ctypes.WINFUNCTYPE( # type: ignore ctypes.c_void_p, ctypes.POINTER(SAmsAddr), ctypes.POINTER(SAdsNotificationHeader), ctypes.c_ulong, ) elif platform_is_linux(): # try to load local adslib.so in favor to global one local_adslib = os.path.join(os.path.dirname(__file__), "adslib.so") if os.path.isfile(local_adslib):
import ctypes from re import search baseurl = "https://apod.nasa.gov/apod/" pageurl = baseurl + "astropix.html" image_path = "C:\\Users\\kropu\\Pictures\\apod\\imageoftheday.jpg" # download html response = urllib.request.urlopen(pageurl) html = response.read().decode('UTF-8') response.close() # find image url, download and save locally imageurl = baseurl + \ search('<a href="(.*\.jpg)"', html).group(1) image = urllib.request.urlopen(imageurl) with open(image_path, 'wb') as localFile: localFile.write(image.read()) image.close() # magic windows variables SPI_SETDESKWALLPAPER = 0x0014 SPIF_UPDATEINIFILE = 0x0001 SPIF_SENDWININICHANGE = 0x0002 # set wallpaper user32 = ctypes.WinDLL('user32') user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, image_path, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE)
import ctypes from ctypes import wintypes import time import sys user32 = ctypes.WinDLL('user32', use_last_error=True) INPUT_MOUSE = 0 INPUT_KEYBOARD = 1 INPUT_HARDWARE = 2 KEYEVENTF_EXTENDEDKEY = 0x0001 KEYEVENTF_KEYUP = 0x0002 KEYEVENTF_UNICODE = 0x0004 KEYEVENTF_SCANCODE = 0x0008 MAPVK_VK_TO_VSC = 0 # msdn.microsoft.com/en-us/library/dd375731 dict_keystrokes = { ' ': 0x20, 'END': 0x23, 'HOME': 0x24, '\t': 0x09, 'SHIFT': 0x10, 'CTRL': 0x11, 'ALT': 0x12, 'CAPS': 0x14, '0': 0x30, '1': 0x31,
def getcurrentprocess (): k32 = ctypes.WinDLL('kernel32.dll') return k32.GetCurrentProcess()