id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
171,552 |
def MCI_MSF_SECOND(msf):
return (BYTE)(((WORD)(msf)) >> 8) | null |
171,553 |
def MCI_MSF_FRAME(msf):
return (BYTE)((msf) >> 16) | null |
171,554 |
def MCI_TMSF_TRACK(tmsf):
return (BYTE)(tmsf) | null |
171,555 |
def MCI_TMSF_MINUTE(tmsf):
return (BYTE)(((WORD)(tmsf)) >> 8) | null |
171,556 |
def MCI_TMSF_SECOND(tmsf):
return (BYTE)((tmsf) >> 16) | null |
171,557 |
def MCI_TMSF_FRAME(tmsf):
return (BYTE)((tmsf) >> 24) | null |
171,558 |
def MCI_HMS_HOUR(hms):
return (BYTE)(hms) | null |
171,559 |
def MCI_HMS_MINUTE(hms):
return (BYTE)(((WORD)(hms)) >> 8) | null |
171,560 |
def MCI_HMS_SECOND(hms):
return (BYTE)((hms) >> 16) | null |
171,561 |
def DIBINDEX(n):
return MAKELONG((n), 0x10FF) | null |
171,562 | AFX_IDW_CONTROLBAR_FIRST = 0xE800
def AFX_CONTROLBAR_MASK(nIDC):
return 1 << (nIDC - AFX_IDW_CONTROLBAR_FIRST) | null |
171,563 |
def PRIMARYLANGID(lgid):
return (WORD)(lgid) & 1023 | null |
171,564 |
def SUBLANGID(lgid):
return (WORD)(lgid) >> 10 | null |
171,565 |
def LANGIDFROMLCID(lcid):
return (WORD)(lcid) | null |
171,566 | NLS_VALID_LOCALE_MASK = 1048575
def SORTIDFROMLCID(lcid):
return (WORD)((((DWORD)(lcid)) & NLS_VALID_LOCALE_MASK) >> 16) | null |
171,567 |
def UNREFERENCED_PARAMETER(P):
return P | null |
171,568 |
def DBG_UNREFERENCED_PARAMETER(P):
return P | null |
171,569 |
def DBG_UNREFERENCED_LOCAL_VARIABLE(V):
return V | null |
171,570 | N_BTMASK = 15
def BTYPE(x):
return (x) & N_BTMASK | null |
171,571 | IMAGE_SYM_DTYPE_POINTER = 1
N_TMASK = 48
N_BTSHFT = 4
def ISPTR(x):
return ((x) & N_TMASK) == (IMAGE_SYM_DTYPE_POINTER << N_BTSHFT) | null |
171,572 | IMAGE_SYM_DTYPE_FUNCTION = 2
N_TMASK = 48
N_BTSHFT = 4
def ISFCN(x):
return ((x) & N_TMASK) == (IMAGE_SYM_DTYPE_FUNCTION << N_BTSHFT) | null |
171,573 | IMAGE_SYM_DTYPE_ARRAY = 3
N_TMASK = 48
N_BTSHFT = 4
def ISARY(x):
return ((x) & N_TMASK) == (IMAGE_SYM_DTYPE_ARRAY << N_BTSHFT) | null |
171,574 | IMAGE_SYM_DTYPE_POINTER = 1
N_BTMASK = 15
N_BTSHFT = 4
N_TSHIFT = 2
def INCREF(x):
return (
(((x) & ~N_BTMASK) << N_TSHIFT)
| (IMAGE_SYM_DTYPE_POINTER << N_BTSHFT)
| ((x) & N_BTMASK)
) | null |
171,575 | N_BTMASK = 15
N_TSHIFT = 2
def DECREF(x):
return (((x) >> N_TSHIFT) & ~N_BTMASK) | ((x) & N_BTMASK) | null |
171,576 | IMAGE_ORDINAL_FLAG = -2147483648
def IMAGE_SNAP_BY_ORDINAL(Ordina):
return (Ordinal & IMAGE_ORDINAL_FLAG) != 0 | null |
171,577 |
def IMAGE_ORDINAL(Ordina):
return Ordinal & 65535 | null |
171,578 |
def PRIMARYLANGID(lgid):
return (lgid) & 1023 | null |
171,579 |
def SUBLANGID(lgid):
return (lgid) >> 10 | null |
171,580 | IMAGE_ORDINAL_FLAG = -2147483648
def IMAGE_SNAP_BY_ORDINAL(Ordinal):
return (Ordinal & IMAGE_ORDINAL_FLAG) != 0 | null |
171,581 |
def IMAGE_ORDINAL(Ordinal):
return Ordinal & 65535 | null |
171,582 |
def PALETTEINDEX(i):
return 16777216 | (i) | null |
171,583 |
def GetRValue(rgb):
return rgb & 0xFF | null |
171,584 |
def GetGValue(rgb):
return (rgb >> 8) & 0xFF | null |
171,585 |
def GetBValue(rgb):
return (rgb >> 16) & 0xFF | null |
171,586 | import array
import struct
import sys
import commctrl
import pywintypes
import win32con
import win32gui
try:
from collections import namedtuple
def _MakeResult(names_str, values):
names = names_str.split()
nt = namedtuple(names[0], names[1:])
return nt(*values)
except ImportError:
# no namedtuple support - just return the values as a normal tuple.
def _MakeResult(names_str, values):
return values
if win32gui.UNICODE:
else:
def UnpackWMNOTIFY(lparam):
format = "PPi"
buf = win32gui.PyGetMemory(lparam, struct.calcsize(format))
return _MakeResult("WMNOTIFY hwndFrom idFrom code", struct.unpack(format, buf)) | null |
171,587 | import array
import struct
import sys
import commctrl
import pywintypes
import win32con
import win32gui
is64bit = "64 bit" in sys.version
try:
from collections import namedtuple
def _MakeResult(names_str, values):
names = names_str.split()
nt = namedtuple(names[0], names[1:])
return nt(*values)
except ImportError:
# no namedtuple support - just return the values as a normal tuple.
def _MakeResult(names_str, values):
return values
_nmhdr_fmt = "PPi"
if is64bit:
# When the item past the NMHDR gets aligned (eg, when it is a struct)
# we need this many bytes padding.
_nmhdr_align_padding = "xxxx"
else:
_nmhdr_align_padding = ""
if win32gui.UNICODE:
else:
def UnpackNMITEMACTIVATE(lparam):
format = _nmhdr_fmt + _nmhdr_align_padding
if is64bit:
# the struct module doesn't handle this correctly as some of the items
# are actually structs in structs, which get individually aligned.
format = format + "iiiiiiixxxxP"
else:
format = format + "iiiiiiiP"
buf = win32gui.PyMakeBuffer(struct.calcsize(format), lparam)
return _MakeResult(
"NMITEMACTIVATE hwndFrom idFrom code iItem iSubItem uNewState uOldState uChanged actionx actiony lParam",
struct.unpack(format, buf),
) | null |
171,588 | import array
import struct
import sys
import commctrl
import pywintypes
import win32con
import win32gui
if win32gui.UNICODE:
def _make_text_buffer(text):
# XXX - at this stage win32gui.UNICODE is only True in py3k,
# and in py3k is makes sense to reject bytes.
if not isinstance(text, str):
raise TypeError("MENUITEMINFO text must be unicode")
data = (text + "\0").encode("utf-16le")
return array.array("b", data)
else:
def _make_text_buffer(text):
if isinstance(text, str):
text = text.encode("mbcs")
return array.array("b", text + "\0")
_menuiteminfo_fmt = "5i5PiP"
def PackMENUITEMINFO(
fType=None,
fState=None,
wID=None,
hSubMenu=None,
hbmpChecked=None,
hbmpUnchecked=None,
dwItemData=None,
text=None,
hbmpItem=None,
dwTypeData=None,
):
# 'extras' are objects the caller must keep a reference to (as their
# memory is used) for the lifetime of the INFO item.
extras = []
# ack - dwItemData and dwTypeData were confused for a while...
assert (
dwItemData is None or dwTypeData is None
), "sorry - these were confused - you probably want dwItemData"
# if we are a long way past 209, then we can nuke the above...
if dwTypeData is not None:
import warnings
warnings.warn("PackMENUITEMINFO: please use dwItemData instead of dwTypeData")
if dwItemData is None:
dwItemData = dwTypeData or 0
fMask = 0
if fType is None:
fType = 0
else:
fMask |= win32con.MIIM_FTYPE
if fState is None:
fState = 0
else:
fMask |= win32con.MIIM_STATE
if wID is None:
wID = 0
else:
fMask |= win32con.MIIM_ID
if hSubMenu is None:
hSubMenu = 0
else:
fMask |= win32con.MIIM_SUBMENU
if hbmpChecked is None:
assert hbmpUnchecked is None, "neither or both checkmark bmps must be given"
hbmpChecked = hbmpUnchecked = 0
else:
assert hbmpUnchecked is not None, "neither or both checkmark bmps must be given"
fMask |= win32con.MIIM_CHECKMARKS
if dwItemData is None:
dwItemData = 0
else:
fMask |= win32con.MIIM_DATA
if hbmpItem is None:
hbmpItem = 0
else:
fMask |= win32con.MIIM_BITMAP
if text is not None:
fMask |= win32con.MIIM_STRING
str_buf = _make_text_buffer(text)
cch = len(text)
# We are taking address of strbuf - it must not die until windows
# has finished with our structure.
lptext = str_buf.buffer_info()[0]
extras.append(str_buf)
else:
lptext = 0
cch = 0
# Create the struct.
# 'P' format does not accept PyHANDLE's !
item = struct.pack(
_menuiteminfo_fmt,
struct.calcsize(_menuiteminfo_fmt), # cbSize
fMask,
fType,
fState,
wID,
int(hSubMenu),
int(hbmpChecked),
int(hbmpUnchecked),
dwItemData,
lptext,
cch,
int(hbmpItem),
)
# Now copy the string to a writable buffer, so that the result
# could be passed to a 'Get' function
return array.array("b", item), extras | null |
171,589 | import array
import struct
import sys
import commctrl
import pywintypes
import win32con
import win32gui
try:
from collections import namedtuple
def _MakeResult(names_str, values):
names = names_str.split()
nt = namedtuple(names[0], names[1:])
return nt(*values)
except ImportError:
# no namedtuple support - just return the values as a normal tuple.
def _MakeResult(names_str, values):
return values
if win32gui.UNICODE:
else:
_menuiteminfo_fmt = "5i5PiP"
def UnpackMENUITEMINFO(s):
(
cb,
fMask,
fType,
fState,
wID,
hSubMenu,
hbmpChecked,
hbmpUnchecked,
dwItemData,
lptext,
cch,
hbmpItem,
) = struct.unpack(_menuiteminfo_fmt, s)
assert cb == len(s)
if fMask & win32con.MIIM_FTYPE == 0:
fType = None
if fMask & win32con.MIIM_STATE == 0:
fState = None
if fMask & win32con.MIIM_ID == 0:
wID = None
if fMask & win32con.MIIM_SUBMENU == 0:
hSubMenu = None
if fMask & win32con.MIIM_CHECKMARKS == 0:
hbmpChecked = hbmpUnchecked = None
if fMask & win32con.MIIM_DATA == 0:
dwItemData = None
if fMask & win32con.MIIM_BITMAP == 0:
hbmpItem = None
if fMask & win32con.MIIM_STRING:
text = win32gui.PyGetString(lptext, cch)
else:
text = None
return _MakeResult(
"MENUITEMINFO fType fState wID hSubMenu hbmpChecked "
"hbmpUnchecked dwItemData text hbmpItem",
(
fType,
fState,
wID,
hSubMenu,
hbmpChecked,
hbmpUnchecked,
dwItemData,
text,
hbmpItem,
),
) | null |
171,590 | import array
import struct
import sys
import commctrl
import pywintypes
import win32con
import win32gui
def _make_empty_text_buffer(cch):
return _make_text_buffer("\0" * cch)
_menuiteminfo_fmt = "5i5PiP"
def EmptyMENUITEMINFO(mask=None, text_buf_size=512):
# text_buf_size is number of *characters* - not necessarily no of bytes.
extra = []
if mask is None:
mask = (
win32con.MIIM_BITMAP
| win32con.MIIM_CHECKMARKS
| win32con.MIIM_DATA
| win32con.MIIM_FTYPE
| win32con.MIIM_ID
| win32con.MIIM_STATE
| win32con.MIIM_STRING
| win32con.MIIM_SUBMENU
)
# Note: No MIIM_TYPE - this screws win2k/98.
if mask & win32con.MIIM_STRING:
text_buffer = _make_empty_text_buffer(text_buf_size)
extra.append(text_buffer)
text_addr, _ = text_buffer.buffer_info()
else:
text_addr = text_buf_size = 0
# Now copy the string to a writable buffer, so that the result
# could be passed to a 'Get' function
buf = struct.pack(
_menuiteminfo_fmt,
struct.calcsize(_menuiteminfo_fmt), # cbSize
mask,
0, # fType,
0, # fState,
0, # wID,
0, # hSubMenu,
0, # hbmpChecked,
0, # hbmpUnchecked,
0, # dwItemData,
text_addr,
text_buf_size,
0, # hbmpItem
)
return array.array("b", buf), extra | null |
171,591 | import array
import struct
import sys
import commctrl
import pywintypes
import win32con
import win32gui
_menuinfo_fmt = "iiiiPiP"
def PackMENUINFO(
dwStyle=None,
cyMax=None,
hbrBack=None,
dwContextHelpID=None,
dwMenuData=None,
fMask=0,
):
if dwStyle is None:
dwStyle = 0
else:
fMask |= win32con.MIM_STYLE
if cyMax is None:
cyMax = 0
else:
fMask |= win32con.MIM_MAXHEIGHT
if hbrBack is None:
hbrBack = 0
else:
fMask |= win32con.MIM_BACKGROUND
if dwContextHelpID is None:
dwContextHelpID = 0
else:
fMask |= win32con.MIM_HELPID
if dwMenuData is None:
dwMenuData = 0
else:
fMask |= win32con.MIM_MENUDATA
# Create the struct.
item = struct.pack(
_menuinfo_fmt,
struct.calcsize(_menuinfo_fmt), # cbSize
fMask,
dwStyle,
cyMax,
hbrBack,
dwContextHelpID,
dwMenuData,
)
return array.array("b", item) | null |
171,592 | import array
import struct
import sys
import commctrl
import pywintypes
import win32con
import win32gui
try:
from collections import namedtuple
def _MakeResult(names_str, values):
names = names_str.split()
nt = namedtuple(names[0], names[1:])
return nt(*values)
except ImportError:
# no namedtuple support - just return the values as a normal tuple.
def _MakeResult(names_str, values):
return values
_menuinfo_fmt = "iiiiPiP"
def UnpackMENUINFO(s):
(cb, fMask, dwStyle, cyMax, hbrBack, dwContextHelpID, dwMenuData) = struct.unpack(
_menuinfo_fmt, s
)
assert cb == len(s)
if fMask & win32con.MIM_STYLE == 0:
dwStyle = None
if fMask & win32con.MIM_MAXHEIGHT == 0:
cyMax = None
if fMask & win32con.MIM_BACKGROUND == 0:
hbrBack = None
if fMask & win32con.MIM_HELPID == 0:
dwContextHelpID = None
if fMask & win32con.MIM_MENUDATA == 0:
dwMenuData = None
return _MakeResult(
"MENUINFO dwStyle cyMax hbrBack dwContextHelpID dwMenuData",
(dwStyle, cyMax, hbrBack, dwContextHelpID, dwMenuData),
) | null |
171,593 | import array
import struct
import sys
import commctrl
import pywintypes
import win32con
import win32gui
_menuinfo_fmt = "iiiiPiP"
def EmptyMENUINFO(mask=None):
if mask is None:
mask = (
win32con.MIM_STYLE
| win32con.MIM_MAXHEIGHT
| win32con.MIM_BACKGROUND
| win32con.MIM_HELPID
| win32con.MIM_MENUDATA
)
buf = struct.pack(
_menuinfo_fmt,
struct.calcsize(_menuinfo_fmt), # cbSize
mask,
0, # dwStyle
0, # cyMax
0, # hbrBack,
0, # dwContextHelpID,
0, # dwMenuData,
)
return array.array("b", buf) | null |
171,594 | import array
import struct
import sys
import commctrl
import pywintypes
import win32con
import win32gui
def PackTVITEM(hitem, state, stateMask, text, image, selimage, citems, param):
extra = [] # objects we must keep references to
mask = 0
mask, hitem = _GetMaskAndVal(hitem, 0, mask, commctrl.TVIF_HANDLE)
mask, state = _GetMaskAndVal(state, 0, mask, commctrl.TVIF_STATE)
if not mask & commctrl.TVIF_STATE:
stateMask = 0
mask, text = _GetMaskAndVal(text, None, mask, commctrl.TVIF_TEXT)
mask, image = _GetMaskAndVal(image, 0, mask, commctrl.TVIF_IMAGE)
mask, selimage = _GetMaskAndVal(selimage, 0, mask, commctrl.TVIF_SELECTEDIMAGE)
mask, citems = _GetMaskAndVal(citems, 0, mask, commctrl.TVIF_CHILDREN)
mask, param = _GetMaskAndVal(param, 0, mask, commctrl.TVIF_PARAM)
if text is None:
text_addr = text_len = 0
else:
text_buffer = _make_text_buffer(text)
text_len = len(text)
extra.append(text_buffer)
text_addr, _ = text_buffer.buffer_info()
buf = struct.pack(
_tvitem_fmt,
mask,
hitem,
state,
stateMask,
text_addr,
text_len, # text
image,
selimage,
citems,
param,
)
return array.array("b", buf), extra
def PackTVINSERTSTRUCT(parent, insertAfter, tvitem):
tvitem_buf, extra = PackTVITEM(*tvitem)
tvitem_buf = tvitem_buf.tobytes()
format = "PP%ds" % len(tvitem_buf)
return struct.pack(format, parent, insertAfter, tvitem_buf), extra | null |
171,595 | import array
import struct
import sys
import commctrl
import pywintypes
import win32con
import win32gui
def _make_empty_text_buffer(cch):
return _make_text_buffer("\0" * cch)
_tvitem_fmt = "iPiiPiiiiP"
def EmptyTVITEM(hitem, mask=None, text_buf_size=512):
extra = [] # objects we must keep references to
if mask is None:
mask = (
commctrl.TVIF_HANDLE
| commctrl.TVIF_STATE
| commctrl.TVIF_TEXT
| commctrl.TVIF_IMAGE
| commctrl.TVIF_SELECTEDIMAGE
| commctrl.TVIF_CHILDREN
| commctrl.TVIF_PARAM
)
if mask & commctrl.TVIF_TEXT:
text_buffer = _make_empty_text_buffer(text_buf_size)
extra.append(text_buffer)
text_addr, _ = text_buffer.buffer_info()
else:
text_addr = text_buf_size = 0
buf = struct.pack(
_tvitem_fmt, mask, hitem, 0, 0, text_addr, text_buf_size, 0, 0, 0, 0 # text
)
return array.array("b", buf), extra | null |
171,596 | import array
import struct
import sys
import commctrl
import pywintypes
import win32con
import win32gui
is64bit = "64 bit" in sys.version
try:
from collections import namedtuple
def _MakeResult(names_str, values):
names = names_str.split()
nt = namedtuple(names[0], names[1:])
return nt(*values)
except ImportError:
# no namedtuple support - just return the values as a normal tuple.
def _MakeResult(names_str, values):
return values
_nmhdr_fmt = "PPi"
if is64bit:
# When the item past the NMHDR gets aligned (eg, when it is a struct)
# we need this many bytes padding.
_nmhdr_align_padding = "xxxx"
else:
_nmhdr_align_padding = ""
if win32gui.UNICODE:
else:
_tvitem_fmt = "iPiiPiiiiP"
def UnpackTVITEM(buffer):
(
item_mask,
item_hItem,
item_state,
item_stateMask,
item_textptr,
item_cchText,
item_image,
item_selimage,
item_cChildren,
item_param,
) = struct.unpack(_tvitem_fmt, buffer)
# ensure only items listed by the mask are valid (except we assume the
# handle is always valid - some notifications (eg, TVN_ENDLABELEDIT) set a
# mask that doesn't include the handle, but the docs explicity say it is.)
if not (item_mask & commctrl.TVIF_TEXT):
item_textptr = item_cchText = None
if not (item_mask & commctrl.TVIF_CHILDREN):
item_cChildren = None
if not (item_mask & commctrl.TVIF_IMAGE):
item_image = None
if not (item_mask & commctrl.TVIF_PARAM):
item_param = None
if not (item_mask & commctrl.TVIF_SELECTEDIMAGE):
item_selimage = None
if not (item_mask & commctrl.TVIF_STATE):
item_state = item_stateMask = None
if item_textptr:
text = win32gui.PyGetString(item_textptr)
else:
text = None
return _MakeResult(
"TVITEM item_hItem item_state item_stateMask "
"text item_image item_selimage item_cChildren item_param",
(
item_hItem,
item_state,
item_stateMask,
text,
item_image,
item_selimage,
item_cChildren,
item_param,
),
)
def UnpackTVNOTIFY(lparam):
item_size = struct.calcsize(_tvitem_fmt)
format = _nmhdr_fmt + _nmhdr_align_padding
if is64bit:
format = format + "ixxxx"
else:
format = format + "i"
format = format + "%ds%ds" % (item_size, item_size)
buf = win32gui.PyGetMemory(lparam, struct.calcsize(format))
hwndFrom, id, code, action, buf_old, buf_new = struct.unpack(format, buf)
item_old = UnpackTVITEM(buf_old)
item_new = UnpackTVITEM(buf_new)
return _MakeResult(
"TVNOTIFY hwndFrom id code action item_old item_new",
(hwndFrom, id, code, action, item_old, item_new),
) | null |
171,597 | import array
import struct
import sys
import commctrl
import pywintypes
import win32con
import win32gui
try:
from collections import namedtuple
def _MakeResult(names_str, values):
names = names_str.split()
nt = namedtuple(names[0], names[1:])
return nt(*values)
except ImportError:
# no namedtuple support - just return the values as a normal tuple.
def _MakeResult(names_str, values):
return values
if win32gui.UNICODE:
else:
_tvitem_fmt = "iPiiPiiiiP"
def UnpackTVITEM(buffer):
(
item_mask,
item_hItem,
item_state,
item_stateMask,
item_textptr,
item_cchText,
item_image,
item_selimage,
item_cChildren,
item_param,
) = struct.unpack(_tvitem_fmt, buffer)
# ensure only items listed by the mask are valid (except we assume the
# handle is always valid - some notifications (eg, TVN_ENDLABELEDIT) set a
# mask that doesn't include the handle, but the docs explicity say it is.)
if not (item_mask & commctrl.TVIF_TEXT):
item_textptr = item_cchText = None
if not (item_mask & commctrl.TVIF_CHILDREN):
item_cChildren = None
if not (item_mask & commctrl.TVIF_IMAGE):
item_image = None
if not (item_mask & commctrl.TVIF_PARAM):
item_param = None
if not (item_mask & commctrl.TVIF_SELECTEDIMAGE):
item_selimage = None
if not (item_mask & commctrl.TVIF_STATE):
item_state = item_stateMask = None
if item_textptr:
text = win32gui.PyGetString(item_textptr)
else:
text = None
return _MakeResult(
"TVITEM item_hItem item_state item_stateMask "
"text item_image item_selimage item_cChildren item_param",
(
item_hItem,
item_state,
item_stateMask,
text,
item_image,
item_selimage,
item_cChildren,
item_param,
),
)
def UnpackTVDISPINFO(lparam):
item_size = struct.calcsize(_tvitem_fmt)
format = "PPi%ds" % (item_size,)
buf = win32gui.PyGetMemory(lparam, struct.calcsize(format))
hwndFrom, id, code, buf_item = struct.unpack(format, buf)
item = UnpackTVITEM(buf_item)
return _MakeResult("TVDISPINFO hwndFrom id code item", (hwndFrom, id, code, item)) | null |
171,598 | import array
import struct
import sys
import commctrl
import pywintypes
import win32con
import win32gui
if win32gui.UNICODE:
def _make_text_buffer(text):
else:
def _make_text_buffer(text):
_lvitem_fmt = "iiiiiPiiPi"
def PackLVITEM(
item=None,
subItem=None,
state=None,
stateMask=None,
text=None,
image=None,
param=None,
indent=None,
):
extra = [] # objects we must keep references to
mask = 0
# _GetMaskAndVal adds quite a bit of overhead to this function.
if item is None:
item = 0 # No mask for item
if subItem is None:
subItem = 0 # No mask for sibItem
if state is None:
state = 0
stateMask = 0
else:
mask |= commctrl.LVIF_STATE
if stateMask is None:
stateMask = state
if image is None:
image = 0
else:
mask |= commctrl.LVIF_IMAGE
if param is None:
param = 0
else:
mask |= commctrl.LVIF_PARAM
if indent is None:
indent = 0
else:
mask |= commctrl.LVIF_INDENT
if text is None:
text_addr = text_len = 0
else:
mask |= commctrl.LVIF_TEXT
text_buffer = _make_text_buffer(text)
text_len = len(text)
extra.append(text_buffer)
text_addr, _ = text_buffer.buffer_info()
buf = struct.pack(
_lvitem_fmt,
mask,
item,
subItem,
state,
stateMask,
text_addr,
text_len, # text
image,
param,
indent,
)
return array.array("b", buf), extra | null |
171,599 | import array
import struct
import sys
import commctrl
import pywintypes
import win32con
import win32gui
try:
from collections import namedtuple
def _MakeResult(names_str, values):
names = names_str.split()
nt = namedtuple(names[0], names[1:])
return nt(*values)
except ImportError:
# no namedtuple support - just return the values as a normal tuple.
def _MakeResult(names_str, values):
return values
_nmhdr_fmt = "PPi"
if win32gui.UNICODE:
else:
_lvitem_fmt = "iiiiiPiiPi"
def UnpackLVITEM(buffer):
(
item_mask,
item_item,
item_subItem,
item_state,
item_stateMask,
item_textptr,
item_cchText,
item_image,
item_param,
item_indent,
) = struct.unpack(_lvitem_fmt, buffer)
# ensure only items listed by the mask are valid
if not (item_mask & commctrl.LVIF_TEXT):
item_textptr = item_cchText = None
if not (item_mask & commctrl.LVIF_IMAGE):
item_image = None
if not (item_mask & commctrl.LVIF_PARAM):
item_param = None
if not (item_mask & commctrl.LVIF_INDENT):
item_indent = None
if not (item_mask & commctrl.LVIF_STATE):
item_state = item_stateMask = None
if item_textptr:
text = win32gui.PyGetString(item_textptr)
else:
text = None
return _MakeResult(
"LVITEM item_item item_subItem item_state "
"item_stateMask text item_image item_param item_indent",
(
item_item,
item_subItem,
item_state,
item_stateMask,
text,
item_image,
item_param,
item_indent,
),
)
def UnpackLVDISPINFO(lparam):
item_size = struct.calcsize(_lvitem_fmt)
format = _nmhdr_fmt + _nmhdr_align_padding + ("%ds" % (item_size,))
buf = win32gui.PyGetMemory(lparam, struct.calcsize(format))
hwndFrom, id, code, buf_item = struct.unpack(format, buf)
item = UnpackLVITEM(buf_item)
return _MakeResult("LVDISPINFO hwndFrom id code item", (hwndFrom, id, code, item)) | null |
171,600 | import array
import struct
import sys
import commctrl
import pywintypes
import win32con
import win32gui
is64bit = "64 bit" in sys.version
try:
from collections import namedtuple
def _MakeResult(names_str, values):
except ImportError:
# no namedtuple support - just return the values as a normal tuple.
def _MakeResult(names_str, values):
_nmhdr_fmt = "PPi"
if is64bit:
# When the item past the NMHDR gets aligned (eg, when it is a struct)
# we need this many bytes padding.
_nmhdr_align_padding = "xxxx"
else:
_nmhdr_align_padding = ""
if win32gui.UNICODE:
else:
def UnpackLVNOTIFY(lparam):
format = _nmhdr_fmt + _nmhdr_align_padding + "7i"
if is64bit:
format = format + "xxxx" # point needs padding.
format = format + "P"
buf = win32gui.PyGetMemory(lparam, struct.calcsize(format))
(
hwndFrom,
id,
code,
item,
subitem,
newstate,
oldstate,
changed,
pt_x,
pt_y,
lparam,
) = struct.unpack(format, buf)
return _MakeResult(
"UnpackLVNOTIFY hwndFrom id code item subitem "
"newstate oldstate changed pt lparam",
(
hwndFrom,
id,
code,
item,
subitem,
newstate,
oldstate,
changed,
(pt_x, pt_y),
lparam,
),
) | null |
171,601 | import array
import struct
import sys
import commctrl
import pywintypes
import win32con
import win32gui
def _make_empty_text_buffer(cch):
_lvitem_fmt = "iiiiiPiiPi"
def EmptyLVITEM(item, subitem, mask=None, text_buf_size=512):
extra = [] # objects we must keep references to
if mask is None:
mask = (
commctrl.LVIF_IMAGE
| commctrl.LVIF_INDENT
| commctrl.LVIF_TEXT
| commctrl.LVIF_PARAM
| commctrl.LVIF_STATE
)
if mask & commctrl.LVIF_TEXT:
text_buffer = _make_empty_text_buffer(text_buf_size)
extra.append(text_buffer)
text_addr, _ = text_buffer.buffer_info()
else:
text_addr = text_buf_size = 0
buf = struct.pack(
_lvitem_fmt,
mask,
item,
subitem,
0,
0,
text_addr,
text_buf_size, # text
0,
0,
0,
)
return array.array("b", buf), extra | null |
171,602 | import array
import struct
import sys
import commctrl
import pywintypes
import win32con
import win32gui
if win32gui.UNICODE:
def _make_text_buffer(text):
# XXX - at this stage win32gui.UNICODE is only True in py3k,
# and in py3k is makes sense to reject bytes.
if not isinstance(text, str):
raise TypeError("MENUITEMINFO text must be unicode")
data = (text + "\0").encode("utf-16le")
return array.array("b", data)
else:
def _make_text_buffer(text):
if isinstance(text, str):
text = text.encode("mbcs")
return array.array("b", text + "\0")
def _GetMaskAndVal(val, default, mask, flag):
if val is None:
return mask, default
else:
if flag is not None:
mask |= flag
return mask, val
_lvcolumn_fmt = "iiiPiiii"
def PackLVCOLUMN(fmt=None, cx=None, text=None, subItem=None, image=None, order=None):
extra = [] # objects we must keep references to
mask = 0
mask, fmt = _GetMaskAndVal(fmt, 0, mask, commctrl.LVCF_FMT)
mask, cx = _GetMaskAndVal(cx, 0, mask, commctrl.LVCF_WIDTH)
mask, text = _GetMaskAndVal(text, None, mask, commctrl.LVCF_TEXT)
mask, subItem = _GetMaskAndVal(subItem, 0, mask, commctrl.LVCF_SUBITEM)
mask, image = _GetMaskAndVal(image, 0, mask, commctrl.LVCF_IMAGE)
mask, order = _GetMaskAndVal(order, 0, mask, commctrl.LVCF_ORDER)
if text is None:
text_addr = text_len = 0
else:
text_buffer = _make_text_buffer(text)
extra.append(text_buffer)
text_addr, _ = text_buffer.buffer_info()
text_len = len(text)
buf = struct.pack(
_lvcolumn_fmt, mask, fmt, cx, text_addr, text_len, subItem, image, order # text
)
return array.array("b", buf), extra | null |
171,603 | import array
import struct
import sys
import commctrl
import pywintypes
import win32con
import win32gui
try:
from collections import namedtuple
def _MakeResult(names_str, values):
names = names_str.split()
nt = namedtuple(names[0], names[1:])
return nt(*values)
except ImportError:
# no namedtuple support - just return the values as a normal tuple.
def _MakeResult(names_str, values):
return values
if win32gui.UNICODE:
else:
_lvcolumn_fmt = "iiiPiiii"
def UnpackLVCOLUMN(lparam):
mask, fmt, cx, text_addr, text_size, subItem, image, order = struct.unpack(
_lvcolumn_fmt, lparam
)
# ensure only items listed by the mask are valid
if not (mask & commctrl.LVCF_FMT):
fmt = None
if not (mask & commctrl.LVCF_WIDTH):
cx = None
if not (mask & commctrl.LVCF_TEXT):
text_addr = text_size = None
if not (mask & commctrl.LVCF_SUBITEM):
subItem = None
if not (mask & commctrl.LVCF_IMAGE):
image = None
if not (mask & commctrl.LVCF_ORDER):
order = None
if text_addr:
text = win32gui.PyGetString(text_addr)
else:
text = None
return _MakeResult(
"LVCOLUMN fmt cx text subItem image order",
(fmt, cx, text, subItem, image, order),
) | null |
171,604 | import array
import struct
import sys
import commctrl
import pywintypes
import win32con
import win32gui
def _make_empty_text_buffer(cch):
_lvcolumn_fmt = "iiiPiiii"
def EmptyLVCOLUMN(mask=None, text_buf_size=512):
extra = [] # objects we must keep references to
if mask is None:
mask = (
commctrl.LVCF_FMT
| commctrl.LVCF_WIDTH
| commctrl.LVCF_TEXT
| commctrl.LVCF_SUBITEM
| commctrl.LVCF_IMAGE
| commctrl.LVCF_ORDER
)
if mask & commctrl.LVCF_TEXT:
text_buffer = _make_empty_text_buffer(text_buf_size)
extra.append(text_buffer)
text_addr, _ = text_buffer.buffer_info()
else:
text_addr = text_buf_size = 0
buf = struct.pack(
_lvcolumn_fmt, mask, 0, 0, text_addr, text_buf_size, 0, 0, 0 # text
)
return array.array("b", buf), extra | null |
171,605 | import array
import struct
import sys
import commctrl
import pywintypes
import win32con
import win32gui
def PackLVHITTEST(pt):
format = "iiiii"
buf = struct.pack(format, pt[0], pt[1], 0, 0, 0)
return array.array("b", buf), None | null |
171,606 | import array
import struct
import sys
import commctrl
import pywintypes
import win32con
import win32gui
try:
from collections import namedtuple
def _MakeResult(names_str, values):
except ImportError:
# no namedtuple support - just return the values as a normal tuple.
def _MakeResult(names_str, values):
def UnpackLVHITTEST(buf):
format = "iiiii"
x, y, flags, item, subitem = struct.unpack(format, buf)
return _MakeResult(
"LVHITTEST pt flags item subitem", ((x, y), flags, item, subitem)
) | null |
171,607 | import array
import struct
import sys
import commctrl
import pywintypes
import win32con
import win32gui
if win32gui.UNICODE:
def _make_text_buffer(text):
# XXX - at this stage win32gui.UNICODE is only True in py3k,
# and in py3k is makes sense to reject bytes.
if not isinstance(text, str):
raise TypeError("MENUITEMINFO text must be unicode")
data = (text + "\0").encode("utf-16le")
return array.array("b", data)
else:
def _make_text_buffer(text):
if isinstance(text, str):
text = text.encode("mbcs")
return array.array("b", text + "\0")
def _GetMaskAndVal(val, default, mask, flag):
if val is None:
return mask, default
else:
if flag is not None:
mask |= flag
return mask, val
def PackHDITEM(
cxy=None, text=None, hbm=None, fmt=None, param=None, image=None, order=None
):
extra = [] # objects we must keep references to
mask = 0
mask, cxy = _GetMaskAndVal(cxy, 0, mask, commctrl.HDI_HEIGHT)
mask, text = _GetMaskAndVal(text, None, mask, commctrl.LVCF_TEXT)
mask, hbm = _GetMaskAndVal(hbm, 0, mask, commctrl.HDI_BITMAP)
mask, fmt = _GetMaskAndVal(fmt, 0, mask, commctrl.HDI_FORMAT)
mask, param = _GetMaskAndVal(param, 0, mask, commctrl.HDI_LPARAM)
mask, image = _GetMaskAndVal(image, 0, mask, commctrl.HDI_IMAGE)
mask, order = _GetMaskAndVal(order, 0, mask, commctrl.HDI_ORDER)
if text is None:
text_addr = text_len = 0
else:
text_buffer = _make_text_buffer(text)
extra.append(text_buffer)
text_addr, _ = text_buffer.buffer_info()
text_len = len(text)
format = "iiPPiiPiiii"
buf = struct.pack(
format, mask, cxy, text_addr, hbm, text_len, fmt, param, image, order, 0, 0
)
return array.array("b", buf), extra | null |
171,608 | import array
import struct
import sys
import commctrl
import pywintypes
import win32con
import win32gui
if sys.version_info < (3, 0):
def _make_memory(ob):
return str(buffer(ob))
def _make_bytes(sval):
return sval
else:
def _make_memory(ob):
return bytes(memoryview(ob))
def _make_bytes(sval):
return sval.encode("ascii")
def PackDEV_BROADCAST(devicetype, rest_fmt, rest_data, extra_data=_make_bytes("")):
# It seems a requirement is 4 byte alignment, even for the 'BYTE data[1]'
# field (eg, that would make DEV_BROADCAST_HANDLE 41 bytes, but we must
# be 44.
extra_data += _make_bytes("\0" * (4 - len(extra_data) % 4))
format = "iii" + rest_fmt
full_size = struct.calcsize(format) + len(extra_data)
data = (full_size, devicetype, 0) + rest_data
return struct.pack(format, *data) + extra_data
def PackDEV_BROADCAST_HANDLE(
handle,
hdevnotify=0,
guid=_make_bytes("\0" * 16),
name_offset=0,
data=_make_bytes("\0"),
):
return PackDEV_BROADCAST(
win32con.DBT_DEVTYP_HANDLE,
"PP16sl",
(int(handle), int(hdevnotify), _make_memory(guid), name_offset),
data,
) | null |
171,609 | import array
import struct
import sys
import commctrl
import pywintypes
import win32con
import win32gui
def PackDEV_BROADCAST(devicetype, rest_fmt, rest_data, extra_data=_make_bytes("")):
def PackDEV_BROADCAST_VOLUME(unitmask, flags):
return PackDEV_BROADCAST(win32con.DBT_DEVTYP_VOLUME, "II", (unitmask, flags)) | null |
171,610 | import array
import struct
import sys
import commctrl
import pywintypes
import win32con
import win32gui
if win32gui.UNICODE:
else:
if sys.version_info < (3, 0):
def _make_memory(ob):
return str(buffer(ob))
else:
def _make_memory(ob):
return bytes(memoryview(ob))
def PackDEV_BROADCAST(devicetype, rest_fmt, rest_data, extra_data=_make_bytes("")):
# It seems a requirement is 4 byte alignment, even for the 'BYTE data[1]'
# field (eg, that would make DEV_BROADCAST_HANDLE 41 bytes, but we must
# be 44.
extra_data += _make_bytes("\0" * (4 - len(extra_data) % 4))
format = "iii" + rest_fmt
full_size = struct.calcsize(format) + len(extra_data)
data = (full_size, devicetype, 0) + rest_data
return struct.pack(format, *data) + extra_data
def PackDEV_BROADCAST_DEVICEINTERFACE(classguid, name=""):
if win32gui.UNICODE:
# This really means "is py3k?" - so not accepting bytes is OK
if not isinstance(name, str):
raise TypeError("Must provide unicode for the name")
name = name.encode("utf-16le")
else:
# py2k was passed a unicode object - encode as mbcs.
if isinstance(name, str):
name = name.encode("mbcs")
# 16 bytes for the IID followed by \0 term'd string.
rest_fmt = "16s%ds" % len(name)
# _make_memory(iid) hoops necessary to get the raw IID bytes.
rest_data = (_make_memory(pywintypes.IID(classguid)), name)
return PackDEV_BROADCAST(win32con.DBT_DEVTYP_DEVICEINTERFACE, rest_fmt, rest_data) | null |
171,611 | import array
import struct
import sys
import commctrl
import pywintypes
import win32con
import win32gui
if win32gui.UNICODE:
else:
class DEV_BROADCAST_INFO:
def __init__(self, devicetype, **kw):
def __str__(self):
def UnpackDEV_BROADCAST(lparam):
if lparam == 0:
return None
hdr_format = "iii"
hdr_size = struct.calcsize(hdr_format)
hdr_buf = win32gui.PyGetMemory(lparam, hdr_size)
size, devtype, reserved = struct.unpack("iii", hdr_buf)
# Due to x64 alignment issues, we need to use the full format string over
# the entire buffer. ie, on x64:
# calcsize('iiiP') != calcsize('iii')+calcsize('P')
buf = win32gui.PyGetMemory(lparam, size)
extra = x = {}
if devtype == win32con.DBT_DEVTYP_HANDLE:
# 2 handles, a GUID, a LONG and possibly an array following...
fmt = hdr_format + "PP16sl"
(
_,
_,
_,
x["handle"],
x["hdevnotify"],
guid_bytes,
x["nameoffset"],
) = struct.unpack(fmt, buf[: struct.calcsize(fmt)])
x["eventguid"] = pywintypes.IID(guid_bytes, True)
elif devtype == win32con.DBT_DEVTYP_DEVICEINTERFACE:
fmt = hdr_format + "16s"
_, _, _, guid_bytes = struct.unpack(fmt, buf[: struct.calcsize(fmt)])
x["classguid"] = pywintypes.IID(guid_bytes, True)
x["name"] = win32gui.PyGetString(lparam + struct.calcsize(fmt))
elif devtype == win32con.DBT_DEVTYP_VOLUME:
# int mask and flags
fmt = hdr_format + "II"
_, _, _, x["unitmask"], x["flags"] = struct.unpack(
fmt, buf[: struct.calcsize(fmt)]
)
else:
raise NotImplementedError("unknown device type %d" % (devtype,))
return DEV_BROADCAST_INFO(devtype, **extra) | null |
171,612 | import win32api
import win32con
import win32evtlog
import winerror
The provided code snippet includes necessary dependencies for implementing the `AddSourceToRegistry` function. Write a Python function `def AddSourceToRegistry( appName, msgDLL=None, eventLogType="Application", eventLogFlags=None, categoryDLL=None, categoryCount=0, )` to solve the following problem:
Add a source of messages to the event log. Allows Python program to register a custom source of messages in the registry. You must also provide the DLL name that has the message table, so the full message text appears in the event log. Note that the win32evtlog.pyd file has a number of string entries with just "%1" built in, so many Python programs can simply use this DLL. Disadvantages are that you do not get language translation, and the full text is stored in the event log, blowing the size of the log up.
Here is the function:
def AddSourceToRegistry(
appName,
msgDLL=None,
eventLogType="Application",
eventLogFlags=None,
categoryDLL=None,
categoryCount=0,
):
"""Add a source of messages to the event log.
Allows Python program to register a custom source of messages in the
registry. You must also provide the DLL name that has the message table, so the
full message text appears in the event log.
Note that the win32evtlog.pyd file has a number of string entries with just "%1"
built in, so many Python programs can simply use this DLL. Disadvantages are that
you do not get language translation, and the full text is stored in the event log,
blowing the size of the log up.
"""
# When an application uses the RegisterEventSource or OpenEventLog
# function to get a handle of an event log, the event logging service
# searches for the specified source name in the registry. You can add a
# new source name to the registry by opening a new registry subkey
# under the Application key and adding registry values to the new
# subkey.
if msgDLL is None:
msgDLL = win32evtlog.__file__
# Create a new key for our application
hkey = win32api.RegCreateKey(
win32con.HKEY_LOCAL_MACHINE,
"SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s"
% (eventLogType, appName),
)
# Add the Event-ID message-file name to the subkey.
win32api.RegSetValueEx(
hkey,
"EventMessageFile", # value name \
0, # reserved \
win32con.REG_EXPAND_SZ, # value type \
msgDLL,
)
# Set the supported types flags and add it to the subkey.
if eventLogFlags is None:
eventLogFlags = (
win32evtlog.EVENTLOG_ERROR_TYPE
| win32evtlog.EVENTLOG_WARNING_TYPE
| win32evtlog.EVENTLOG_INFORMATION_TYPE
)
win32api.RegSetValueEx(
hkey, # subkey handle \
"TypesSupported", # value name \
0, # reserved \
win32con.REG_DWORD, # value type \
eventLogFlags,
)
if categoryCount > 0:
# Optionally, you can specify a message file that contains the categories
if categoryDLL is None:
categoryDLL = win32evtlog.__file__
win32api.RegSetValueEx(
hkey, # subkey handle \
"CategoryMessageFile", # value name \
0, # reserved \
win32con.REG_EXPAND_SZ, # value type \
categoryDLL,
)
win32api.RegSetValueEx(
hkey, # subkey handle \
"CategoryCount", # value name \
0, # reserved \
win32con.REG_DWORD, # value type \
categoryCount,
)
win32api.RegCloseKey(hkey) | Add a source of messages to the event log. Allows Python program to register a custom source of messages in the registry. You must also provide the DLL name that has the message table, so the full message text appears in the event log. Note that the win32evtlog.pyd file has a number of string entries with just "%1" built in, so many Python programs can simply use this DLL. Disadvantages are that you do not get language translation, and the full text is stored in the event log, blowing the size of the log up. |
171,613 | import win32api
import win32con
import win32evtlog
import winerror
The provided code snippet includes necessary dependencies for implementing the `ReportEvent` function. Write a Python function `def ReportEvent( appName, eventID, eventCategory=0, eventType=win32evtlog.EVENTLOG_ERROR_TYPE, strings=None, data=None, sid=None, )` to solve the following problem:
Report an event for a previously added event source.
Here is the function:
def ReportEvent(
appName,
eventID,
eventCategory=0,
eventType=win32evtlog.EVENTLOG_ERROR_TYPE,
strings=None,
data=None,
sid=None,
):
"""Report an event for a previously added event source."""
# Get a handle to the Application event log
hAppLog = win32evtlog.RegisterEventSource(None, appName)
# Now report the event, which will add this event to the event log */
win32evtlog.ReportEvent(
hAppLog, # event-log handle \
eventType,
eventCategory,
eventID,
sid,
strings,
data,
)
win32evtlog.DeregisterEventSource(hAppLog) | Report an event for a previously added event source. |
171,614 | import win32api
import win32con
import win32evtlog
import winerror
error = win32api.error
def FormatMessage(eventLogRecord, logType="Application"):
"""Given a tuple from ReadEventLog, and optionally where the event
record came from, load the message, and process message inserts.
Note that this function may raise win32api.error. See also the
function SafeFormatMessage which will return None if the message can
not be processed.
"""
# From the event log source name, we know the name of the registry
# key to look under for the name of the message DLL that contains
# the messages we need to extract with FormatMessage. So first get
# the event log source name...
keyName = "SYSTEM\\CurrentControlSet\\Services\\EventLog\\%s\\%s" % (
logType,
eventLogRecord.SourceName,
)
# Now open this key and get the EventMessageFile value, which is
# the name of the message DLL.
handle = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, keyName)
try:
dllNames = win32api.RegQueryValueEx(handle, "EventMessageFile")[0].split(";")
# Win2k etc appear to allow multiple DLL names
data = None
for dllName in dllNames:
try:
# Expand environment variable strings in the message DLL path name,
# in case any are there.
dllName = win32api.ExpandEnvironmentStrings(dllName)
dllHandle = win32api.LoadLibraryEx(
dllName, 0, win32con.LOAD_LIBRARY_AS_DATAFILE
)
try:
data = win32api.FormatMessageW(
win32con.FORMAT_MESSAGE_FROM_HMODULE,
dllHandle,
eventLogRecord.EventID,
langid,
eventLogRecord.StringInserts,
)
finally:
win32api.FreeLibrary(dllHandle)
except win32api.error:
pass # Not in this DLL - try the next
if data is not None:
break
finally:
win32api.RegCloseKey(handle)
return data or "" # Don't want "None" ever being returned.
The provided code snippet includes necessary dependencies for implementing the `SafeFormatMessage` function. Write a Python function `def SafeFormatMessage(eventLogRecord, logType=None)` to solve the following problem:
As for FormatMessage, except returns an error message if the message can not be processed.
Here is the function:
def SafeFormatMessage(eventLogRecord, logType=None):
"""As for FormatMessage, except returns an error message if
the message can not be processed.
"""
if logType is None:
logType = "Application"
try:
return FormatMessage(eventLogRecord, logType)
except win32api.error:
if eventLogRecord.StringInserts is None:
desc = ""
else:
desc = ", ".join(eventLogRecord.StringInserts)
return (
"<The description for Event ID ( %d ) in Source ( %r ) could not be found. It contains the following insertion string(s):%r.>"
% (
winerror.HRESULT_CODE(eventLogRecord.EventID),
eventLogRecord.SourceName,
desc,
)
) | As for FormatMessage, except returns an error message if the message can not be processed. |
171,615 | import win32api
import win32con
import win32evtlog
import winerror
def FeedEventLogRecords(
feeder, machineName=None, logName="Application", readFlags=None
):
if readFlags is None:
readFlags = (
win32evtlog.EVENTLOG_BACKWARDS_READ | win32evtlog.EVENTLOG_SEQUENTIAL_READ
)
h = win32evtlog.OpenEventLog(machineName, logName)
try:
while 1:
objects = win32evtlog.ReadEventLog(h, readFlags, 0)
if not objects:
break
map(lambda item, feeder=feeder: feeder(*(item,)), objects)
finally:
win32evtlog.CloseEventLog(h) | null |
171,616 | __version__ = "0.11"
import os
import pprint
import shlex
import stat
import sys
import commctrl
import win32con
def Parse(rc_name, h_name=None):
if h_name:
h_file = open(h_name, "r")
else:
# See if same basename as the .rc
h_name = rc_name[:-2] + "h"
try:
h_file = open(h_name, "r")
except IOError:
# See if MSVC default of 'resource.h' in the same dir.
h_name = os.path.join(os.path.dirname(rc_name), "resource.h")
try:
h_file = open(h_name, "r")
except IOError:
# .h files are optional anyway
h_file = None
rc_file = open(rc_name, "r")
try:
return ParseStreams(rc_file, h_file)
finally:
if h_file is not None:
h_file.close()
rc_file.close()
return rcp
The provided code snippet includes necessary dependencies for implementing the `GenerateFrozenResource` function. Write a Python function `def GenerateFrozenResource(rc_name, output_name, h_name=None)` to solve the following problem:
Converts an .rc windows resource source file into a python source file with the same basic public interface as the rest of this module. Particularly useful for py2exe or other 'freeze' type solutions, where a frozen .py file can be used inplace of a real .rc file.
Here is the function:
def GenerateFrozenResource(rc_name, output_name, h_name=None):
"""Converts an .rc windows resource source file into a python source file
with the same basic public interface as the rest of this module.
Particularly useful for py2exe or other 'freeze' type solutions,
where a frozen .py file can be used inplace of a real .rc file.
"""
rcp = Parse(rc_name, h_name)
in_stat = os.stat(rc_name)
out = open(output_name, "wt")
out.write("#%s\n" % output_name)
out.write("#This is a generated file. Please edit %s instead.\n" % rc_name)
out.write("__version__=%r\n" % __version__)
out.write(
"_rc_size_=%d\n_rc_mtime_=%d\n"
% (in_stat[stat.ST_SIZE], in_stat[stat.ST_MTIME])
)
out.write("class StringDef:\n")
out.write("\tdef __init__(self, id, idNum, value):\n")
out.write("\t\tself.id = id\n")
out.write("\t\tself.idNum = idNum\n")
out.write("\t\tself.value = value\n")
out.write("\tdef __repr__(self):\n")
out.write(
'\t\treturn "StringDef(%r, %r, %r)" % (self.id, self.idNum, self.value)\n'
)
out.write("class FakeParser:\n")
for name in "dialogs", "ids", "names", "bitmaps", "icons", "stringTable":
out.write("\t%s = \\\n" % (name,))
pprint.pprint(getattr(rcp, name), out)
out.write("\n")
out.write("def Parse(s):\n")
out.write("\treturn FakeParser()\n")
out.close() | Converts an .rc windows resource source file into a python source file with the same basic public interface as the rest of this module. Particularly useful for py2exe or other 'freeze' type solutions, where a frozen .py file can be used inplace of a real .rc file. |
171,617 | import win32ras
stateStrings = {
win32ras.RASCS_OpenPort: "OpenPort",
win32ras.RASCS_PortOpened: "PortOpened",
win32ras.RASCS_ConnectDevice: "ConnectDevice",
win32ras.RASCS_DeviceConnected: "DeviceConnected",
win32ras.RASCS_AllDevicesConnected: "AllDevicesConnected",
win32ras.RASCS_Authenticate: "Authenticate",
win32ras.RASCS_AuthNotify: "AuthNotify",
win32ras.RASCS_AuthRetry: "AuthRetry",
win32ras.RASCS_AuthCallback: "AuthCallback",
win32ras.RASCS_AuthChangePassword: "AuthChangePassword",
win32ras.RASCS_AuthProject: "AuthProject",
win32ras.RASCS_AuthLinkSpeed: "AuthLinkSpeed",
win32ras.RASCS_AuthAck: "AuthAck",
win32ras.RASCS_ReAuthenticate: "ReAuthenticate",
win32ras.RASCS_Authenticated: "Authenticated",
win32ras.RASCS_PrepareForCallback: "PrepareForCallback",
win32ras.RASCS_WaitForModemReset: "WaitForModemReset",
win32ras.RASCS_WaitForCallback: "WaitForCallback",
win32ras.RASCS_Projected: "Projected",
win32ras.RASCS_StartAuthentication: "StartAuthentication",
win32ras.RASCS_CallbackComplete: "CallbackComplete",
win32ras.RASCS_LogonNetwork: "LogonNetwork",
win32ras.RASCS_Interactive: "Interactive",
win32ras.RASCS_RetryAuthentication: "RetryAuthentication",
win32ras.RASCS_CallbackSetByCaller: "CallbackSetByCaller",
win32ras.RASCS_PasswordExpired: "PasswordExpired",
win32ras.RASCS_Connected: "Connected",
win32ras.RASCS_Disconnected: "Disconnected",
}
def TestCallback(hras, msg, state, error, exterror):
print("Callback called with ", hras, msg, stateStrings[state], error, exterror) | null |
171,618 | import win32trace
def RunAsCollector():
import sys
try:
import win32api
win32api.SetConsoleTitle("Python Trace Collector")
except:
pass # Oh well!
win32trace.InitRead()
print("Collecting Python Trace Output...")
try:
while 1:
# a short timeout means ctrl+c works next time we wake...
sys.stdout.write(win32trace.blockingread(500))
except KeyboardInterrupt:
print("Ctrl+C") | null |
171,619 | import win32trace
def SetupForPrint():
win32trace.InitWrite()
try: # Under certain servers, sys.stdout may be invalid.
print("Redirecting output to win32trace remote collector")
except:
pass
win32trace.setprint() # this works in an rexec environment. | null |
171,620 | import os
import sys
import win32api
import win32con
def GetRootKey():
"""Retrieves the Registry root in use by Python."""
keyname = BuildDefaultPythonKey()
try:
k = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, keyname)
k.close()
return win32con.HKEY_CURRENT_USER
except win32api.error:
return win32con.HKEY_LOCAL_MACHINE
The provided code snippet includes necessary dependencies for implementing the `SetRegistryDefaultValue` function. Write a Python function `def SetRegistryDefaultValue(subKey, value, rootkey=None)` to solve the following problem:
A helper to set the default value for a key in the registry
Here is the function:
def SetRegistryDefaultValue(subKey, value, rootkey=None):
"""A helper to set the default value for a key in the registry"""
if rootkey is None:
rootkey = GetRootKey()
if type(value) == str:
typeId = win32con.REG_SZ
elif type(value) == int:
typeId = win32con.REG_DWORD
else:
raise TypeError("Value must be string or integer - was passed " + repr(value))
win32api.RegSetValue(rootkey, subKey, typeId, value) | A helper to set the default value for a key in the registry |
171,621 | import os
import sys
import win32api
import win32con
error = "Registry utility error"
def GetRootKey():
"""Retrieves the Registry root in use by Python."""
keyname = BuildDefaultPythonKey()
try:
k = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, keyname)
k.close()
return win32con.HKEY_CURRENT_USER
except win32api.error:
return win32con.HKEY_LOCAL_MACHINE
def GetAppPathsKey():
return "Software\\Microsoft\\Windows\\CurrentVersion\\App Paths"
The provided code snippet includes necessary dependencies for implementing the `RegisterPythonExe` function. Write a Python function `def RegisterPythonExe(exeFullPath, exeAlias=None, exeAppPath=None)` to solve the following problem:
Register a .exe file that uses Python. Registers the .exe with the OS. This allows the specified .exe to be run from the command-line or start button without using the full path, and also to setup application specific path (ie, os.environ['PATH']). Currently the exeAppPath is not supported, so this function is general purpose, and not specific to Python at all. Later, exeAppPath may provide a reasonable default that is used. exeFullPath -- The full path to the .exe exeAlias = None -- An alias for the exe - if none, the base portion of the filename is used. exeAppPath -- Not supported.
Here is the function:
def RegisterPythonExe(exeFullPath, exeAlias=None, exeAppPath=None):
"""Register a .exe file that uses Python.
Registers the .exe with the OS. This allows the specified .exe to
be run from the command-line or start button without using the full path,
and also to setup application specific path (ie, os.environ['PATH']).
Currently the exeAppPath is not supported, so this function is general
purpose, and not specific to Python at all. Later, exeAppPath may provide
a reasonable default that is used.
exeFullPath -- The full path to the .exe
exeAlias = None -- An alias for the exe - if none, the base portion
of the filename is used.
exeAppPath -- Not supported.
"""
# Note - Dont work on win32s (but we dont care anymore!)
if exeAppPath:
raise error("Do not support exeAppPath argument currently")
if exeAlias is None:
exeAlias = os.path.basename(exeFullPath)
win32api.RegSetValue(
GetRootKey(), GetAppPathsKey() + "\\" + exeAlias, win32con.REG_SZ, exeFullPath
) | Register a .exe file that uses Python. Registers the .exe with the OS. This allows the specified .exe to be run from the command-line or start button without using the full path, and also to setup application specific path (ie, os.environ['PATH']). Currently the exeAppPath is not supported, so this function is general purpose, and not specific to Python at all. Later, exeAppPath may provide a reasonable default that is used. exeFullPath -- The full path to the .exe exeAlias = None -- An alias for the exe - if none, the base portion of the filename is used. exeAppPath -- Not supported. |
171,622 | import os
import sys
import win32api
import win32con
def GetRootKey():
"""Retrieves the Registry root in use by Python."""
keyname = BuildDefaultPythonKey()
try:
k = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, keyname)
k.close()
return win32con.HKEY_CURRENT_USER
except win32api.error:
return win32con.HKEY_LOCAL_MACHINE
def GetAppPathsKey():
return "Software\\Microsoft\\Windows\\CurrentVersion\\App Paths"
The provided code snippet includes necessary dependencies for implementing the `GetRegisteredExe` function. Write a Python function `def GetRegisteredExe(exeAlias)` to solve the following problem:
Get a registered .exe
Here is the function:
def GetRegisteredExe(exeAlias):
"""Get a registered .exe"""
return win32api.RegQueryValue(GetRootKey(), GetAppPathsKey() + "\\" + exeAlias) | Get a registered .exe |
171,623 | import os
import sys
import win32api
import win32con
error = "Registry utility error"
def GetRootKey():
"""Retrieves the Registry root in use by Python."""
keyname = BuildDefaultPythonKey()
try:
k = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, keyname)
k.close()
return win32con.HKEY_CURRENT_USER
except win32api.error:
return win32con.HKEY_LOCAL_MACHINE
def GetAppPathsKey():
return "Software\\Microsoft\\Windows\\CurrentVersion\\App Paths"
The provided code snippet includes necessary dependencies for implementing the `UnregisterPythonExe` function. Write a Python function `def UnregisterPythonExe(exeAlias)` to solve the following problem:
Unregister a .exe file that uses Python.
Here is the function:
def UnregisterPythonExe(exeAlias):
"""Unregister a .exe file that uses Python."""
try:
win32api.RegDeleteKey(GetRootKey(), GetAppPathsKey() + "\\" + exeAlias)
except win32api.error as exc:
import winerror
if exc.winerror != winerror.ERROR_FILE_NOT_FOUND:
raise
return | Unregister a .exe file that uses Python. |
171,624 | import os
import sys
import win32api
import win32con
def BuildDefaultPythonKey():
"""Builds a string containing the path to the current registry key.
The Python registry key contains the Python version. This function
uses the version of the DLL used by the current process to get the
registry key currently in use.
"""
return "Software\\Python\\PythonCore\\" + sys.winver
def GetRootKey():
"""Retrieves the Registry root in use by Python."""
keyname = BuildDefaultPythonKey()
try:
k = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, keyname)
k.close()
return win32con.HKEY_CURRENT_USER
except win32api.error:
return win32con.HKEY_LOCAL_MACHINE
The provided code snippet includes necessary dependencies for implementing the `RegisterNamedPath` function. Write a Python function `def RegisterNamedPath(name, path)` to solve the following problem:
Register a named path - ie, a named PythonPath entry.
Here is the function:
def RegisterNamedPath(name, path):
"""Register a named path - ie, a named PythonPath entry."""
keyStr = BuildDefaultPythonKey() + "\\PythonPath"
if name:
keyStr = keyStr + "\\" + name
win32api.RegSetValue(GetRootKey(), keyStr, win32con.REG_SZ, path) | Register a named path - ie, a named PythonPath entry. |
171,625 | import os
import sys
import win32api
import win32con
error = "Registry utility error"
def BuildDefaultPythonKey():
"""Builds a string containing the path to the current registry key.
The Python registry key contains the Python version. This function
uses the version of the DLL used by the current process to get the
registry key currently in use.
"""
return "Software\\Python\\PythonCore\\" + sys.winver
def GetRootKey():
"""Retrieves the Registry root in use by Python."""
keyname = BuildDefaultPythonKey()
try:
k = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, keyname)
k.close()
return win32con.HKEY_CURRENT_USER
except win32api.error:
return win32con.HKEY_LOCAL_MACHINE
The provided code snippet includes necessary dependencies for implementing the `UnregisterNamedPath` function. Write a Python function `def UnregisterNamedPath(name)` to solve the following problem:
Unregister a named path - ie, a named PythonPath entry.
Here is the function:
def UnregisterNamedPath(name):
"""Unregister a named path - ie, a named PythonPath entry."""
keyStr = BuildDefaultPythonKey() + "\\PythonPath\\" + name
try:
win32api.RegDeleteKey(GetRootKey(), keyStr)
except win32api.error as exc:
import winerror
if exc.winerror != winerror.ERROR_FILE_NOT_FOUND:
raise
return | Unregister a named path - ie, a named PythonPath entry. |
171,626 | import os
import sys
import win32api
import win32con
error = "Registry utility error"
def BuildDefaultPythonKey():
"""Builds a string containing the path to the current registry key.
The Python registry key contains the Python version. This function
uses the version of the DLL used by the current process to get the
registry key currently in use.
"""
return "Software\\Python\\PythonCore\\" + sys.winver
def GetRootKey():
"""Retrieves the Registry root in use by Python."""
keyname = BuildDefaultPythonKey()
try:
k = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, keyname)
k.close()
return win32con.HKEY_CURRENT_USER
except win32api.error:
return win32con.HKEY_LOCAL_MACHINE
The provided code snippet includes necessary dependencies for implementing the `GetRegisteredNamedPath` function. Write a Python function `def GetRegisteredNamedPath(name)` to solve the following problem:
Get a registered named path, or None if it doesnt exist.
Here is the function:
def GetRegisteredNamedPath(name):
"""Get a registered named path, or None if it doesnt exist."""
keyStr = BuildDefaultPythonKey() + "\\PythonPath"
if name:
keyStr = keyStr + "\\" + name
try:
return win32api.RegQueryValue(GetRootKey(), keyStr)
except win32api.error as exc:
import winerror
if exc.winerror != winerror.ERROR_FILE_NOT_FOUND:
raise
return None | Get a registered named path, or None if it doesnt exist. |
171,627 | import os
import sys
import win32api
import win32con
error = "Registry utility error"
def BuildDefaultPythonKey():
"""Builds a string containing the path to the current registry key.
The Python registry key contains the Python version. This function
uses the version of the DLL used by the current process to get the
registry key currently in use.
"""
return "Software\\Python\\PythonCore\\" + sys.winver
def GetRootKey():
"""Retrieves the Registry root in use by Python."""
keyname = BuildDefaultPythonKey()
try:
k = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, keyname)
k.close()
return win32con.HKEY_CURRENT_USER
except win32api.error:
return win32con.HKEY_LOCAL_MACHINE
The provided code snippet includes necessary dependencies for implementing the `RegisterModule` function. Write a Python function `def RegisterModule(modName, modPath)` to solve the following problem:
Register an explicit module in the registry. This forces the Python import mechanism to locate this module directly, without a sys.path search. Thus a registered module need not appear in sys.path at all. modName -- The name of the module, as used by import. modPath -- The full path and file name of the module.
Here is the function:
def RegisterModule(modName, modPath):
"""Register an explicit module in the registry. This forces the Python import
mechanism to locate this module directly, without a sys.path search. Thus
a registered module need not appear in sys.path at all.
modName -- The name of the module, as used by import.
modPath -- The full path and file name of the module.
"""
try:
import os
os.stat(modPath)
except os.error:
print("Warning: Registering non-existant module %s" % modPath)
win32api.RegSetValue(
GetRootKey(),
BuildDefaultPythonKey() + "\\Modules\\%s" % modName,
win32con.REG_SZ,
modPath,
) | Register an explicit module in the registry. This forces the Python import mechanism to locate this module directly, without a sys.path search. Thus a registered module need not appear in sys.path at all. modName -- The name of the module, as used by import. modPath -- The full path and file name of the module. |
171,628 | import os
import sys
import win32api
import win32con
error = "Registry utility error"
def BuildDefaultPythonKey():
"""Builds a string containing the path to the current registry key.
The Python registry key contains the Python version. This function
uses the version of the DLL used by the current process to get the
registry key currently in use.
"""
return "Software\\Python\\PythonCore\\" + sys.winver
def GetRootKey():
"""Retrieves the Registry root in use by Python."""
keyname = BuildDefaultPythonKey()
try:
k = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, keyname)
k.close()
return win32con.HKEY_CURRENT_USER
except win32api.error:
return win32con.HKEY_LOCAL_MACHINE
The provided code snippet includes necessary dependencies for implementing the `UnregisterModule` function. Write a Python function `def UnregisterModule(modName)` to solve the following problem:
Unregister an explicit module in the registry. modName -- The name of the module, as used by import.
Here is the function:
def UnregisterModule(modName):
"""Unregister an explicit module in the registry.
modName -- The name of the module, as used by import.
"""
try:
win32api.RegDeleteKey(
GetRootKey(), BuildDefaultPythonKey() + "\\Modules\\%s" % modName
)
except win32api.error as exc:
import winerror
if exc.winerror != winerror.ERROR_FILE_NOT_FOUND:
raise | Unregister an explicit module in the registry. modName -- The name of the module, as used by import. |
171,629 | import os
import sys
import win32api
import win32con
error = "Registry utility error"
def BuildDefaultPythonKey():
"""Builds a string containing the path to the current registry key.
The Python registry key contains the Python version. This function
uses the version of the DLL used by the current process to get the
registry key currently in use.
"""
return "Software\\Python\\PythonCore\\" + sys.winver
def GetRegistryDefaultValue(subkey, rootkey=None):
"""A helper to return the default value for a key in the registry."""
if rootkey is None:
rootkey = GetRootKey()
return win32api.RegQueryValue(rootkey, subkey)
The provided code snippet includes necessary dependencies for implementing the `GetRegisteredHelpFile` function. Write a Python function `def GetRegisteredHelpFile(helpDesc)` to solve the following problem:
Given a description, return the registered entry.
Here is the function:
def GetRegisteredHelpFile(helpDesc):
"""Given a description, return the registered entry."""
try:
return GetRegistryDefaultValue(BuildDefaultPythonKey() + "\\Help\\" + helpDesc)
except win32api.error:
try:
return GetRegistryDefaultValue(
BuildDefaultPythonKey() + "\\Help\\" + helpDesc,
win32con.HKEY_CURRENT_USER,
)
except win32api.error:
pass
return None | Given a description, return the registered entry. |
171,630 | import os
import sys
import win32api
import win32con
error = "Registry utility error"
def BuildDefaultPythonKey():
"""Builds a string containing the path to the current registry key.
The Python registry key contains the Python version. This function
uses the version of the DLL used by the current process to get the
registry key currently in use.
"""
return "Software\\Python\\PythonCore\\" + sys.winver
def GetRootKey():
"""Retrieves the Registry root in use by Python."""
keyname = BuildDefaultPythonKey()
try:
k = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, keyname)
k.close()
return win32con.HKEY_CURRENT_USER
except win32api.error:
return win32con.HKEY_LOCAL_MACHINE
The provided code snippet includes necessary dependencies for implementing the `RegisterHelpFile` function. Write a Python function `def RegisterHelpFile(helpFile, helpPath, helpDesc=None, bCheckFile=1)` to solve the following problem:
Register a help file in the registry. Note that this used to support writing to the Windows Help key, however this is no longer done, as it seems to be incompatible. helpFile -- the base name of the help file. helpPath -- the path to the help file helpDesc -- A description for the help file. If None, the helpFile param is used. bCheckFile -- A flag indicating if the file existence should be checked.
Here is the function:
def RegisterHelpFile(helpFile, helpPath, helpDesc=None, bCheckFile=1):
"""Register a help file in the registry.
Note that this used to support writing to the Windows Help
key, however this is no longer done, as it seems to be incompatible.
helpFile -- the base name of the help file.
helpPath -- the path to the help file
helpDesc -- A description for the help file. If None, the helpFile param is used.
bCheckFile -- A flag indicating if the file existence should be checked.
"""
if helpDesc is None:
helpDesc = helpFile
fullHelpFile = os.path.join(helpPath, helpFile)
try:
if bCheckFile:
os.stat(fullHelpFile)
except os.error:
raise ValueError("Help file does not exist")
# Now register with Python itself.
win32api.RegSetValue(
GetRootKey(),
BuildDefaultPythonKey() + "\\Help\\%s" % helpDesc,
win32con.REG_SZ,
fullHelpFile,
) | Register a help file in the registry. Note that this used to support writing to the Windows Help key, however this is no longer done, as it seems to be incompatible. helpFile -- the base name of the help file. helpPath -- the path to the help file helpDesc -- A description for the help file. If None, the helpFile param is used. bCheckFile -- A flag indicating if the file existence should be checked. |
171,631 | import os
import sys
import win32api
import win32con
error = "Registry utility error"
def BuildDefaultPythonKey():
"""Builds a string containing the path to the current registry key.
The Python registry key contains the Python version. This function
uses the version of the DLL used by the current process to get the
registry key currently in use.
"""
return "Software\\Python\\PythonCore\\" + sys.winver
def GetRootKey():
"""Retrieves the Registry root in use by Python."""
keyname = BuildDefaultPythonKey()
try:
k = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, keyname)
k.close()
return win32con.HKEY_CURRENT_USER
except win32api.error:
return win32con.HKEY_LOCAL_MACHINE
The provided code snippet includes necessary dependencies for implementing the `UnregisterHelpFile` function. Write a Python function `def UnregisterHelpFile(helpFile, helpDesc=None)` to solve the following problem:
Unregister a help file in the registry. helpFile -- the base name of the help file. helpDesc -- A description for the help file. If None, the helpFile param is used.
Here is the function:
def UnregisterHelpFile(helpFile, helpDesc=None):
"""Unregister a help file in the registry.
helpFile -- the base name of the help file.
helpDesc -- A description for the help file. If None, the helpFile param is used.
"""
key = win32api.RegOpenKey(
win32con.HKEY_LOCAL_MACHINE,
"Software\\Microsoft\\Windows\\Help",
0,
win32con.KEY_ALL_ACCESS,
)
try:
try:
win32api.RegDeleteValue(key, helpFile)
except win32api.error as exc:
import winerror
if exc.winerror != winerror.ERROR_FILE_NOT_FOUND:
raise
finally:
win32api.RegCloseKey(key)
# Now de-register with Python itself.
if helpDesc is None:
helpDesc = helpFile
try:
win32api.RegDeleteKey(
GetRootKey(), BuildDefaultPythonKey() + "\\Help\\%s" % helpDesc
)
except win32api.error as exc:
import winerror
if exc.winerror != winerror.ERROR_FILE_NOT_FOUND:
raise | Unregister a help file in the registry. helpFile -- the base name of the help file. helpDesc -- A description for the help file. If None, the helpFile param is used. |
171,632 | import os
import sys
import win32api
import win32con
error = "Registry utility error"
def BuildDefaultPythonKey():
"""Builds a string containing the path to the current registry key.
The Python registry key contains the Python version. This function
uses the version of the DLL used by the current process to get the
registry key currently in use.
"""
return "Software\\Python\\PythonCore\\" + sys.winver
def GetRootKey():
"""Retrieves the Registry root in use by Python."""
keyname = BuildDefaultPythonKey()
try:
k = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, keyname)
k.close()
return win32con.HKEY_CURRENT_USER
except win32api.error:
return win32con.HKEY_LOCAL_MACHINE
The provided code snippet includes necessary dependencies for implementing the `RegisterCoreDLL` function. Write a Python function `def RegisterCoreDLL(coredllName=None)` to solve the following problem:
Registers the core DLL in the registry. If no params are passed, the name of the Python DLL used in the current process is used and registered.
Here is the function:
def RegisterCoreDLL(coredllName=None):
"""Registers the core DLL in the registry.
If no params are passed, the name of the Python DLL used in
the current process is used and registered.
"""
if coredllName is None:
coredllName = win32api.GetModuleFileName(sys.dllhandle)
# must exist!
else:
try:
os.stat(coredllName)
except os.error:
print("Warning: Registering non-existant core DLL %s" % coredllName)
hKey = win32api.RegCreateKey(GetRootKey(), BuildDefaultPythonKey())
try:
win32api.RegSetValue(hKey, "Dll", win32con.REG_SZ, coredllName)
finally:
win32api.RegCloseKey(hKey)
# Lastly, setup the current version to point to me.
win32api.RegSetValue(
GetRootKey(),
"Software\\Python\\PythonCore\\CurrentVersion",
win32con.REG_SZ,
sys.winver,
) | Registers the core DLL in the registry. If no params are passed, the name of the Python DLL used in the current process is used and registered. |
171,633 | import os
import sys
import win32api
import win32con
CLSIDPyFile = "{b51df050-06ae-11cf-ad3b-524153480001}"
RegistryIDPyFile = "Python.File"
RegistryIDPycFile = "Python.CompiledFile"
The provided code snippet includes necessary dependencies for implementing the `RegisterFileExtensions` function. Write a Python function `def RegisterFileExtensions(defPyIcon, defPycIcon, runCommand)` to solve the following problem:
Register the core Python file extensions. defPyIcon -- The default icon to use for .py files, in 'fname,offset' format. defPycIcon -- The default icon to use for .pyc files, in 'fname,offset' format. runCommand -- The command line to use for running .py files
Here is the function:
def RegisterFileExtensions(defPyIcon, defPycIcon, runCommand):
"""Register the core Python file extensions.
defPyIcon -- The default icon to use for .py files, in 'fname,offset' format.
defPycIcon -- The default icon to use for .pyc files, in 'fname,offset' format.
runCommand -- The command line to use for running .py files
"""
# Register the file extensions.
pythonFileId = RegistryIDPyFile
win32api.RegSetValue(
win32con.HKEY_CLASSES_ROOT, ".py", win32con.REG_SZ, pythonFileId
)
win32api.RegSetValue(
win32con.HKEY_CLASSES_ROOT, pythonFileId, win32con.REG_SZ, "Python File"
)
win32api.RegSetValue(
win32con.HKEY_CLASSES_ROOT,
"%s\\CLSID" % pythonFileId,
win32con.REG_SZ,
CLSIDPyFile,
)
win32api.RegSetValue(
win32con.HKEY_CLASSES_ROOT,
"%s\\DefaultIcon" % pythonFileId,
win32con.REG_SZ,
defPyIcon,
)
base = "%s\\Shell" % RegistryIDPyFile
win32api.RegSetValue(
win32con.HKEY_CLASSES_ROOT, base + "\\Open", win32con.REG_SZ, "Run"
)
win32api.RegSetValue(
win32con.HKEY_CLASSES_ROOT,
base + "\\Open\\Command",
win32con.REG_SZ,
runCommand,
)
# Register the .PYC.
pythonFileId = RegistryIDPycFile
win32api.RegSetValue(
win32con.HKEY_CLASSES_ROOT, ".pyc", win32con.REG_SZ, pythonFileId
)
win32api.RegSetValue(
win32con.HKEY_CLASSES_ROOT,
pythonFileId,
win32con.REG_SZ,
"Compiled Python File",
)
win32api.RegSetValue(
win32con.HKEY_CLASSES_ROOT,
"%s\\DefaultIcon" % pythonFileId,
win32con.REG_SZ,
defPycIcon,
)
base = "%s\\Shell" % pythonFileId
win32api.RegSetValue(
win32con.HKEY_CLASSES_ROOT, base + "\\Open", win32con.REG_SZ, "Run"
)
win32api.RegSetValue(
win32con.HKEY_CLASSES_ROOT,
base + "\\Open\\Command",
win32con.REG_SZ,
runCommand,
) | Register the core Python file extensions. defPyIcon -- The default icon to use for .py files, in 'fname,offset' format. defPycIcon -- The default icon to use for .pyc files, in 'fname,offset' format. runCommand -- The command line to use for running .py files |
171,634 | import os
import sys
import win32api
import win32con
RegistryIDPyFile = "Python.File"
def RegisterShellCommand(shellCommand, exeCommand, shellUserCommand=None):
# Last param for "Open" - for a .py file to be executed by the command line
# or shell execute (eg, just entering "foo.py"), the Command must be "Open",
# but you may associate a different name for the right-click menu.
# In our case, normally we have "Open=Run"
base = "%s\\Shell" % RegistryIDPyFile
if shellUserCommand:
win32api.RegSetValue(
win32con.HKEY_CLASSES_ROOT,
base + "\\%s" % (shellCommand),
win32con.REG_SZ,
shellUserCommand,
)
win32api.RegSetValue(
win32con.HKEY_CLASSES_ROOT,
base + "\\%s\\Command" % (shellCommand),
win32con.REG_SZ,
exeCommand,
) | null |
171,635 | import os
import sys
import win32api
import win32con
RegistryIDPyFile = "Python.File"
def RegisterDDECommand(shellCommand, ddeApp, ddeTopic, ddeCommand):
base = "%s\\Shell" % RegistryIDPyFile
win32api.RegSetValue(
win32con.HKEY_CLASSES_ROOT,
base + "\\%s\\ddeexec" % (shellCommand),
win32con.REG_SZ,
ddeCommand,
)
win32api.RegSetValue(
win32con.HKEY_CLASSES_ROOT,
base + "\\%s\\ddeexec\\Application" % (shellCommand),
win32con.REG_SZ,
ddeApp,
)
win32api.RegSetValue(
win32con.HKEY_CLASSES_ROOT,
base + "\\%s\\ddeexec\\Topic" % (shellCommand),
win32con.REG_SZ,
ddeTopic,
) | null |
171,636 | import datetime
import logging
import operator
import re
import struct
import winreg
from itertools import count
import win32api
class TimeZoneInfo(datetime.tzinfo):
"""
Main class for handling Windows time zones.
Usage:
TimeZoneInfo(<Time Zone Standard Name>, [<Fix Standard Time>])
If <Fix Standard Time> evaluates to True, daylight savings time is
calculated in the same way as standard time.
>>> tzi = TimeZoneInfo('Pacific Standard Time')
>>> march31 = datetime.datetime(2000,3,31)
We know that time zone definitions haven't changed from 2007
to 2012, so regardless of whether dynamic info is available,
there should be consistent results for these years.
>>> subsequent_years = [march31.replace(year=year)
... for year in range(2007, 2013)]
>>> offsets = set(tzi.utcoffset(year) for year in subsequent_years)
>>> len(offsets)
1
"""
# this key works for WinNT+, but not for the Win95 line.
tzRegKey = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones"
def __init__(self, param=None, fix_standard_time=False):
if isinstance(param, TimeZoneDefinition):
self._LoadFromTZI(param)
if isinstance(param, str):
self.timeZoneName = param
self._LoadInfoFromKey()
self.fixedStandardTime = fix_standard_time
def _FindTimeZoneKey(self):
"""Find the registry key for the time zone name (self.timeZoneName)."""
# for multi-language compatability, match the time zone name in the
# "Std" key of the time zone key.
zoneNames = dict(self._get_indexed_time_zone_keys("Std"))
# Also match the time zone key name itself, to be compatible with
# English-based hard-coded time zones.
timeZoneName = zoneNames.get(self.timeZoneName, self.timeZoneName)
key = _RegKeyDict.open(winreg.HKEY_LOCAL_MACHINE, self.tzRegKey)
try:
result = key.subkey(timeZoneName)
except Exception:
raise ValueError("Timezone Name %s not found." % timeZoneName)
return result
def _LoadInfoFromKey(self):
"""Loads the information from an opened time zone registry key
into relevant fields of this TZI object"""
key = self._FindTimeZoneKey()
self.displayName = key["Display"]
self.standardName = key["Std"]
self.daylightName = key["Dlt"]
self.staticInfo = TimeZoneDefinition(key["TZI"])
self._LoadDynamicInfoFromKey(key)
def _LoadFromTZI(self, tzi):
self.timeZoneName = tzi.standard_name
self.displayName = "Unknown"
self.standardName = tzi.standard_name
self.daylightName = tzi.daylight_name
self.staticInfo = tzi
def _LoadDynamicInfoFromKey(self, key):
"""
>>> tzi = TimeZoneInfo('Central Standard Time')
Here's how the RangeMap is supposed to work:
>>> m = RangeMap(zip([2006,2007], 'BC'),
... sort_params = dict(reverse=True),
... key_match_comparator=operator.ge)
>>> m.get(2000, 'A')
'A'
>>> m[2006]
'B'
>>> m[2007]
'C'
>>> m[2008]
'C'
>>> m[RangeMap.last_item]
'B'
>>> m.get(2008, m[RangeMap.last_item])
'C'
Now test the dynamic info (but fallback to our simple RangeMap
on systems that don't have dynamicInfo).
>>> dinfo = getattr(tzi, 'dynamicInfo', m)
>>> 2007 in dinfo
True
>>> 2008 in dinfo
False
>>> dinfo[2007] == dinfo[2008] == dinfo[2012]
True
"""
try:
info = key.subkey("Dynamic DST")
except WindowsError:
return
del info["FirstEntry"]
del info["LastEntry"]
years = map(int, list(info.keys()))
values = map(TimeZoneDefinition, list(info.values()))
# create a range mapping that searches by descending year and matches
# if the target year is greater or equal.
self.dynamicInfo = RangeMap(
zip(years, values),
sort_params=dict(reverse=True),
key_match_comparator=operator.ge,
)
def __repr__(self):
result = "%s(%s" % (self.__class__.__name__, repr(self.timeZoneName))
if self.fixedStandardTime:
result += ", True"
result += ")"
return result
def __str__(self):
return self.displayName
def tzname(self, dt):
winInfo = self.getWinInfo(dt)
if self.dst(dt) == winInfo.daylight_bias:
result = self.daylightName
elif self.dst(dt) == winInfo.standard_bias:
result = self.standardName
return result
def getWinInfo(self, targetYear):
"""
Return the most relevant "info" for this time zone
in the target year.
"""
if not hasattr(self, "dynamicInfo") or not self.dynamicInfo:
return self.staticInfo
# Find the greatest year entry in self.dynamicInfo which is for
# a year greater than or equal to our targetYear. If not found,
# default to the earliest year.
return self.dynamicInfo.get(targetYear, self.dynamicInfo[RangeMap.last_item])
def _getStandardBias(self, dt):
winInfo = self.getWinInfo(dt.year)
return winInfo.bias + winInfo.standard_bias
def _getDaylightBias(self, dt):
winInfo = self.getWinInfo(dt.year)
return winInfo.bias + winInfo.daylight_bias
def utcoffset(self, dt):
"Calculates the utcoffset according to the datetime.tzinfo spec"
if dt is None:
return
winInfo = self.getWinInfo(dt.year)
return -winInfo.bias + self.dst(dt)
def dst(self, dt):
"""
Calculate the daylight savings offset according to the
datetime.tzinfo spec.
"""
if dt is None:
return
winInfo = self.getWinInfo(dt.year)
if not self.fixedStandardTime and self._inDaylightSavings(dt):
result = winInfo.daylight_bias
else:
result = winInfo.standard_bias
return -result
def _inDaylightSavings(self, dt):
dt = dt.replace(tzinfo=None)
winInfo = self.getWinInfo(dt.year)
try:
dstStart = self.GetDSTStartTime(dt.year)
dstEnd = self.GetDSTEndTime(dt.year)
# at the end of DST, when clocks are moved back, there's a period
# of daylight_bias where it's ambiguous whether we're in DST or
# not.
dstEndAdj = dstEnd + winInfo.daylight_bias
# the same thing could theoretically happen at the start of DST
# if there's a standard_bias (which I suspect is always 0).
dstStartAdj = dstStart + winInfo.standard_bias
if dstStart < dstEnd:
in_dst = dstStartAdj <= dt < dstEndAdj
else:
# in the southern hemisphere, daylight savings time
# typically ends before it begins in a given year.
in_dst = not (dstEndAdj < dt <= dstStartAdj)
except ValueError:
# there was an error parsing the time zone, which is normal when a
# start and end time are not specified.
in_dst = False
return in_dst
def GetDSTStartTime(self, year):
"Given a year, determines the time when daylight savings time starts"
return self.getWinInfo(year).locate_daylight_start(year)
def GetDSTEndTime(self, year):
"Given a year, determines the time when daylight savings ends."
return self.getWinInfo(year).locate_standard_start(year)
def __cmp__(self, other):
return cmp(self.__dict__, other.__dict__)
def __eq__(self, other):
return self.__dict__ == other.__dict__
def __ne__(self, other):
return self.__dict__ != other.__dict__
def local(class_):
"""Returns the local time zone as defined by the operating system in the
registry.
>>> localTZ = TimeZoneInfo.local()
>>> now_local = datetime.datetime.now(localTZ)
>>> now_UTC = datetime.datetime.utcnow()
>>> (now_UTC - now_local) < datetime.timedelta(seconds = 5)
Traceback (most recent call last):
...
TypeError: can't subtract offset-naive and offset-aware datetimes
>>> now_UTC = now_UTC.replace(tzinfo = TimeZoneInfo('GMT Standard Time', True))
Now one can compare the results of the two offset aware values
>>> (now_UTC - now_local) < datetime.timedelta(seconds = 5)
True
"""
code, info = TimeZoneDefinition.current()
# code is 0 if daylight savings is disabled or not defined
# code is 1 or 2 if daylight savings is enabled, 2 if currently active
fix_standard_time = not code
# note that although the given information is sufficient
# to construct a WinTZI object, it's
# not sufficient to represent the time zone in which
# the current user is operating due
# to dynamic time zones.
return class_(info, fix_standard_time)
def utc(class_):
"""Returns a time-zone representing UTC.
Same as TimeZoneInfo('GMT Standard Time', True) but caches the result
for performance.
>>> isinstance(TimeZoneInfo.utc(), TimeZoneInfo)
True
"""
if "_tzutc" not in class_.__dict__:
setattr(class_, "_tzutc", class_("GMT Standard Time", True))
return class_._tzutc
# helper methods for accessing the timezone info from the registry
def _get_time_zone_key(subkey=None):
"Return the registry key that stores time zone details"
key = _RegKeyDict.open(winreg.HKEY_LOCAL_MACHINE, TimeZoneInfo.tzRegKey)
if subkey:
key = key.subkey(subkey)
return key
def _get_time_zone_key_names():
"Returns the names of the (registry keys of the) time zones"
return TimeZoneInfo._get_time_zone_key().subkeys()
def _get_indexed_time_zone_keys(index_key="Index"):
"""
Get the names of the registry keys indexed by a value in that key,
ignoring any keys for which that value is empty or missing.
"""
key_names = list(TimeZoneInfo._get_time_zone_key_names())
def get_index_value(key_name):
key = TimeZoneInfo._get_time_zone_key(key_name)
return key.get(index_key)
values = map(get_index_value, key_names)
return (
(value, key_name) for value, key_name in zip(values, key_names) if value
)
def get_sorted_time_zone_names():
"""
Return a list of time zone names that can
be used to initialize TimeZoneInfo instances.
"""
tzs = TimeZoneInfo.get_sorted_time_zones()
return [tz.standardName for tz in tzs]
def get_all_time_zones():
return [TimeZoneInfo(n) for n in TimeZoneInfo._get_time_zone_key_names()]
def get_sorted_time_zones(key=None):
"""
Return the time zones sorted by some key.
key must be a function that takes a TimeZoneInfo object and returns
a value suitable for sorting on.
The key defaults to the bias (descending), as is done in Windows
(see http://blogs.msdn.com/michkap/archive/2006/12/22/1350684.aspx)
"""
key = key or (lambda tzi: -tzi.staticInfo.bias)
zones = TimeZoneInfo.get_all_time_zones()
zones.sort(key=key)
return zones
def now():
"""
Return the local time now with timezone awareness as enabled
by this module
>>> now_local = now()
"""
return datetime.datetime.now(TimeZoneInfo.local())
The provided code snippet includes necessary dependencies for implementing the `utcnow` function. Write a Python function `def utcnow()` to solve the following problem:
Return the UTC time now with timezone awareness as enabled by this module >>> now = utcnow()
Here is the function:
def utcnow():
"""
Return the UTC time now with timezone awareness as enabled
by this module
>>> now = utcnow()
"""
now = datetime.datetime.utcnow()
now = now.replace(tzinfo=TimeZoneInfo.utc())
return now | Return the UTC time now with timezone awareness as enabled by this module >>> now = utcnow() |
171,637 | import datetime
import logging
import operator
import re
import struct
import winreg
from itertools import count
import win32api
class TimeZoneInfo(datetime.tzinfo):
"""
Main class for handling Windows time zones.
Usage:
TimeZoneInfo(<Time Zone Standard Name>, [<Fix Standard Time>])
If <Fix Standard Time> evaluates to True, daylight savings time is
calculated in the same way as standard time.
>>> tzi = TimeZoneInfo('Pacific Standard Time')
>>> march31 = datetime.datetime(2000,3,31)
We know that time zone definitions haven't changed from 2007
to 2012, so regardless of whether dynamic info is available,
there should be consistent results for these years.
>>> subsequent_years = [march31.replace(year=year)
... for year in range(2007, 2013)]
>>> offsets = set(tzi.utcoffset(year) for year in subsequent_years)
>>> len(offsets)
1
"""
# this key works for WinNT+, but not for the Win95 line.
tzRegKey = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones"
def __init__(self, param=None, fix_standard_time=False):
if isinstance(param, TimeZoneDefinition):
self._LoadFromTZI(param)
if isinstance(param, str):
self.timeZoneName = param
self._LoadInfoFromKey()
self.fixedStandardTime = fix_standard_time
def _FindTimeZoneKey(self):
"""Find the registry key for the time zone name (self.timeZoneName)."""
# for multi-language compatability, match the time zone name in the
# "Std" key of the time zone key.
zoneNames = dict(self._get_indexed_time_zone_keys("Std"))
# Also match the time zone key name itself, to be compatible with
# English-based hard-coded time zones.
timeZoneName = zoneNames.get(self.timeZoneName, self.timeZoneName)
key = _RegKeyDict.open(winreg.HKEY_LOCAL_MACHINE, self.tzRegKey)
try:
result = key.subkey(timeZoneName)
except Exception:
raise ValueError("Timezone Name %s not found." % timeZoneName)
return result
def _LoadInfoFromKey(self):
"""Loads the information from an opened time zone registry key
into relevant fields of this TZI object"""
key = self._FindTimeZoneKey()
self.displayName = key["Display"]
self.standardName = key["Std"]
self.daylightName = key["Dlt"]
self.staticInfo = TimeZoneDefinition(key["TZI"])
self._LoadDynamicInfoFromKey(key)
def _LoadFromTZI(self, tzi):
self.timeZoneName = tzi.standard_name
self.displayName = "Unknown"
self.standardName = tzi.standard_name
self.daylightName = tzi.daylight_name
self.staticInfo = tzi
def _LoadDynamicInfoFromKey(self, key):
"""
>>> tzi = TimeZoneInfo('Central Standard Time')
Here's how the RangeMap is supposed to work:
>>> m = RangeMap(zip([2006,2007], 'BC'),
... sort_params = dict(reverse=True),
... key_match_comparator=operator.ge)
>>> m.get(2000, 'A')
'A'
>>> m[2006]
'B'
>>> m[2007]
'C'
>>> m[2008]
'C'
>>> m[RangeMap.last_item]
'B'
>>> m.get(2008, m[RangeMap.last_item])
'C'
Now test the dynamic info (but fallback to our simple RangeMap
on systems that don't have dynamicInfo).
>>> dinfo = getattr(tzi, 'dynamicInfo', m)
>>> 2007 in dinfo
True
>>> 2008 in dinfo
False
>>> dinfo[2007] == dinfo[2008] == dinfo[2012]
True
"""
try:
info = key.subkey("Dynamic DST")
except WindowsError:
return
del info["FirstEntry"]
del info["LastEntry"]
years = map(int, list(info.keys()))
values = map(TimeZoneDefinition, list(info.values()))
# create a range mapping that searches by descending year and matches
# if the target year is greater or equal.
self.dynamicInfo = RangeMap(
zip(years, values),
sort_params=dict(reverse=True),
key_match_comparator=operator.ge,
)
def __repr__(self):
result = "%s(%s" % (self.__class__.__name__, repr(self.timeZoneName))
if self.fixedStandardTime:
result += ", True"
result += ")"
return result
def __str__(self):
return self.displayName
def tzname(self, dt):
winInfo = self.getWinInfo(dt)
if self.dst(dt) == winInfo.daylight_bias:
result = self.daylightName
elif self.dst(dt) == winInfo.standard_bias:
result = self.standardName
return result
def getWinInfo(self, targetYear):
"""
Return the most relevant "info" for this time zone
in the target year.
"""
if not hasattr(self, "dynamicInfo") or not self.dynamicInfo:
return self.staticInfo
# Find the greatest year entry in self.dynamicInfo which is for
# a year greater than or equal to our targetYear. If not found,
# default to the earliest year.
return self.dynamicInfo.get(targetYear, self.dynamicInfo[RangeMap.last_item])
def _getStandardBias(self, dt):
winInfo = self.getWinInfo(dt.year)
return winInfo.bias + winInfo.standard_bias
def _getDaylightBias(self, dt):
winInfo = self.getWinInfo(dt.year)
return winInfo.bias + winInfo.daylight_bias
def utcoffset(self, dt):
"Calculates the utcoffset according to the datetime.tzinfo spec"
if dt is None:
return
winInfo = self.getWinInfo(dt.year)
return -winInfo.bias + self.dst(dt)
def dst(self, dt):
"""
Calculate the daylight savings offset according to the
datetime.tzinfo spec.
"""
if dt is None:
return
winInfo = self.getWinInfo(dt.year)
if not self.fixedStandardTime and self._inDaylightSavings(dt):
result = winInfo.daylight_bias
else:
result = winInfo.standard_bias
return -result
def _inDaylightSavings(self, dt):
dt = dt.replace(tzinfo=None)
winInfo = self.getWinInfo(dt.year)
try:
dstStart = self.GetDSTStartTime(dt.year)
dstEnd = self.GetDSTEndTime(dt.year)
# at the end of DST, when clocks are moved back, there's a period
# of daylight_bias where it's ambiguous whether we're in DST or
# not.
dstEndAdj = dstEnd + winInfo.daylight_bias
# the same thing could theoretically happen at the start of DST
# if there's a standard_bias (which I suspect is always 0).
dstStartAdj = dstStart + winInfo.standard_bias
if dstStart < dstEnd:
in_dst = dstStartAdj <= dt < dstEndAdj
else:
# in the southern hemisphere, daylight savings time
# typically ends before it begins in a given year.
in_dst = not (dstEndAdj < dt <= dstStartAdj)
except ValueError:
# there was an error parsing the time zone, which is normal when a
# start and end time are not specified.
in_dst = False
return in_dst
def GetDSTStartTime(self, year):
"Given a year, determines the time when daylight savings time starts"
return self.getWinInfo(year).locate_daylight_start(year)
def GetDSTEndTime(self, year):
"Given a year, determines the time when daylight savings ends."
return self.getWinInfo(year).locate_standard_start(year)
def __cmp__(self, other):
return cmp(self.__dict__, other.__dict__)
def __eq__(self, other):
return self.__dict__ == other.__dict__
def __ne__(self, other):
return self.__dict__ != other.__dict__
def local(class_):
"""Returns the local time zone as defined by the operating system in the
registry.
>>> localTZ = TimeZoneInfo.local()
>>> now_local = datetime.datetime.now(localTZ)
>>> now_UTC = datetime.datetime.utcnow()
>>> (now_UTC - now_local) < datetime.timedelta(seconds = 5)
Traceback (most recent call last):
...
TypeError: can't subtract offset-naive and offset-aware datetimes
>>> now_UTC = now_UTC.replace(tzinfo = TimeZoneInfo('GMT Standard Time', True))
Now one can compare the results of the two offset aware values
>>> (now_UTC - now_local) < datetime.timedelta(seconds = 5)
True
"""
code, info = TimeZoneDefinition.current()
# code is 0 if daylight savings is disabled or not defined
# code is 1 or 2 if daylight savings is enabled, 2 if currently active
fix_standard_time = not code
# note that although the given information is sufficient
# to construct a WinTZI object, it's
# not sufficient to represent the time zone in which
# the current user is operating due
# to dynamic time zones.
return class_(info, fix_standard_time)
def utc(class_):
"""Returns a time-zone representing UTC.
Same as TimeZoneInfo('GMT Standard Time', True) but caches the result
for performance.
>>> isinstance(TimeZoneInfo.utc(), TimeZoneInfo)
True
"""
if "_tzutc" not in class_.__dict__:
setattr(class_, "_tzutc", class_("GMT Standard Time", True))
return class_._tzutc
# helper methods for accessing the timezone info from the registry
def _get_time_zone_key(subkey=None):
"Return the registry key that stores time zone details"
key = _RegKeyDict.open(winreg.HKEY_LOCAL_MACHINE, TimeZoneInfo.tzRegKey)
if subkey:
key = key.subkey(subkey)
return key
def _get_time_zone_key_names():
"Returns the names of the (registry keys of the) time zones"
return TimeZoneInfo._get_time_zone_key().subkeys()
def _get_indexed_time_zone_keys(index_key="Index"):
"""
Get the names of the registry keys indexed by a value in that key,
ignoring any keys for which that value is empty or missing.
"""
key_names = list(TimeZoneInfo._get_time_zone_key_names())
def get_index_value(key_name):
key = TimeZoneInfo._get_time_zone_key(key_name)
return key.get(index_key)
values = map(get_index_value, key_names)
return (
(value, key_name) for value, key_name in zip(values, key_names) if value
)
def get_sorted_time_zone_names():
"""
Return a list of time zone names that can
be used to initialize TimeZoneInfo instances.
"""
tzs = TimeZoneInfo.get_sorted_time_zones()
return [tz.standardName for tz in tzs]
def get_all_time_zones():
return [TimeZoneInfo(n) for n in TimeZoneInfo._get_time_zone_key_names()]
def get_sorted_time_zones(key=None):
"""
Return the time zones sorted by some key.
key must be a function that takes a TimeZoneInfo object and returns
a value suitable for sorting on.
The key defaults to the bias (descending), as is done in Windows
(see http://blogs.msdn.com/michkap/archive/2006/12/22/1350684.aspx)
"""
key = key or (lambda tzi: -tzi.staticInfo.bias)
zones = TimeZoneInfo.get_all_time_zones()
zones.sort(key=key)
return zones
The provided code snippet includes necessary dependencies for implementing the `GetTZCapabilities` function. Write a Python function `def GetTZCapabilities()` to solve the following problem:
Run a few known tests to determine the capabilities of the time zone database on this machine. Note Dynamic Time Zone support is not available on any platform at this time; this is a limitation of this library, not the platform.
Here is the function:
def GetTZCapabilities():
"""
Run a few known tests to determine the capabilities of
the time zone database on this machine.
Note Dynamic Time Zone support is not available on any
platform at this time; this
is a limitation of this library, not the platform."""
tzi = TimeZoneInfo("Mountain Standard Time")
MissingTZPatch = datetime.datetime(2007, 11, 2, tzinfo=tzi).utctimetuple() != (
2007,
11,
2,
6,
0,
0,
4,
306,
0,
)
DynamicTZSupport = not MissingTZPatch and datetime.datetime(
2003, 11, 2, tzinfo=tzi
).utctimetuple() == (2003, 11, 2, 7, 0, 0, 6, 306, 0)
del tzi
return locals() | Run a few known tests to determine the capabilities of the time zone database on this machine. Note Dynamic Time Zone support is not available on any platform at this time; this is a limitation of this library, not the platform. |
171,638 | import datetime
import logging
import operator
import re
import struct
import winreg
from itertools import count
import win32api
DLLCache = DLLHandleCache()
The provided code snippet includes necessary dependencies for implementing the `resolveMUITimeZone` function. Write a Python function `def resolveMUITimeZone(spec)` to solve the following problem:
Resolve a multilingual user interface resource for the time zone name >>> #some pre-amble for the doc-tests to be py2k and py3k aware) >>> try: unicode and None ... except NameError: unicode=str ... >>> import sys >>> result = resolveMUITimeZone('@tzres.dll,-110') >>> expectedResultType = [type(None),unicode][sys.getwindowsversion() >= (6,)] >>> type(result) is expectedResultType True spec should be of the format @path,-stringID[;comment] see http://msdn2.microsoft.com/en-us/library/ms725481.aspx for details
Here is the function:
def resolveMUITimeZone(spec):
"""Resolve a multilingual user interface resource for the time zone name
>>> #some pre-amble for the doc-tests to be py2k and py3k aware)
>>> try: unicode and None
... except NameError: unicode=str
...
>>> import sys
>>> result = resolveMUITimeZone('@tzres.dll,-110')
>>> expectedResultType = [type(None),unicode][sys.getwindowsversion() >= (6,)]
>>> type(result) is expectedResultType
True
spec should be of the format @path,-stringID[;comment]
see http://msdn2.microsoft.com/en-us/library/ms725481.aspx for details
"""
pattern = re.compile(r"@(?P<dllname>.*),-(?P<index>\d+)(?:;(?P<comment>.*))?")
matcher = pattern.match(spec)
assert matcher, "Could not parse MUI spec"
try:
handle = DLLCache[matcher.groupdict()["dllname"]]
result = win32api.LoadString(handle, int(matcher.groupdict()["index"]))
except win32api.error:
result = None
return result | Resolve a multilingual user interface resource for the time zone name >>> #some pre-amble for the doc-tests to be py2k and py3k aware) >>> try: unicode and None ... except NameError: unicode=str ... >>> import sys >>> result = resolveMUITimeZone('@tzres.dll,-110') >>> expectedResultType = [type(None),unicode][sys.getwindowsversion() >= (6,)] >>> type(result) is expectedResultType True spec should be of the format @path,-stringID[;comment] see http://msdn2.microsoft.com/en-us/library/ms725481.aspx for details |
171,639 | import struct
import sys
import win32wnet
def Netbios(ncb):
ob = ncb.Buffer
is_ours = hasattr(ob, "_pack")
if is_ours:
ob._pack()
try:
return win32wnet.Netbios(ncb)
finally:
if is_ours:
ob._unpack() | null |
171,640 | import struct
import sys
import win32wnet
ADAPTER_STATUS_ITEMS = [
("6s", "adapter_address"),
(UCHAR, "rev_major"),
(UCHAR, "reserved0"),
(UCHAR, "adapter_type"),
(UCHAR, "rev_minor"),
(WORD, "duration"),
(WORD, "frmr_recv"),
(WORD, "frmr_xmit"),
(WORD, "iframe_recv_err"),
(WORD, "xmit_aborts"),
(DWORD, "xmit_success"),
(DWORD, "recv_success"),
(WORD, "iframe_xmit_err"),
(WORD, "recv_buff_unavail"),
(WORD, "t1_timeouts"),
(WORD, "ti_timeouts"),
(DWORD, "reserved1"),
(WORD, "free_ncbs"),
(WORD, "max_cfg_ncbs"),
(WORD, "max_ncbs"),
(WORD, "xmit_buf_unavail"),
(WORD, "max_dgram_size"),
(WORD, "pending_sess"),
(WORD, "max_cfg_sess"),
(WORD, "max_sess"),
(WORD, "max_sess_pkt_size"),
(WORD, "name_count"),
]
class NCBStruct:
def __init__(self, items):
self._format = "".join([item[0] for item in items])
self._items = items
self._buffer_ = win32wnet.NCBBuffer(struct.calcsize(self._format))
for format, name in self._items:
if len(format) == 1:
if format == "c":
val = "\0"
else:
val = 0
else:
l = int(format[:-1])
val = "\0" * l
self.__dict__[name] = val
def _pack(self):
vals = []
for format, name in self._items:
try:
vals.append(self.__dict__[name])
except KeyError:
vals.append(None)
self._buffer_[:] = struct.pack(*(self._format,) + tuple(vals))
def _unpack(self):
items = struct.unpack(self._format, self._buffer_)
assert len(items) == len(self._items), "unexpected number of items to unpack!"
for (format, name), val in zip(self._items, items):
self.__dict__[name] = val
def __setattr__(self, attr, val):
if attr not in self.__dict__ and attr[0] != "_":
for format, attr_name in self._items:
if attr == attr_name:
break
else:
raise AttributeError(attr)
self.__dict__[attr] = val
def ADAPTER_STATUS():
return NCBStruct(ADAPTER_STATUS_ITEMS) | null |
171,641 | import struct
import sys
import win32wnet
NAME_BUFFER_ITEMS = [
(str(NCBNAMSZ) + "s", "name"),
(UCHAR, "name_num"),
(UCHAR, "name_flags"),
]
class NCBStruct:
def __init__(self, items):
self._format = "".join([item[0] for item in items])
self._items = items
self._buffer_ = win32wnet.NCBBuffer(struct.calcsize(self._format))
for format, name in self._items:
if len(format) == 1:
if format == "c":
val = "\0"
else:
val = 0
else:
l = int(format[:-1])
val = "\0" * l
self.__dict__[name] = val
def _pack(self):
vals = []
for format, name in self._items:
try:
vals.append(self.__dict__[name])
except KeyError:
vals.append(None)
self._buffer_[:] = struct.pack(*(self._format,) + tuple(vals))
def _unpack(self):
items = struct.unpack(self._format, self._buffer_)
assert len(items) == len(self._items), "unexpected number of items to unpack!"
for (format, name), val in zip(self._items, items):
self.__dict__[name] = val
def __setattr__(self, attr, val):
if attr not in self.__dict__ and attr[0] != "_":
for format, attr_name in self._items:
if attr == attr_name:
break
else:
raise AttributeError(attr)
self.__dict__[attr] = val
def NAME_BUFFER():
return NCBStruct(NAME_BUFFER_ITEMS) | null |
171,642 | import struct
import sys
import win32wnet
SESSION_HEADER_ITEMS = [
(UCHAR, "sess_name"),
(UCHAR, "num_sess"),
(UCHAR, "rcv_dg_outstanding"),
(UCHAR, "rcv_any_outstanding"),
]
class NCBStruct:
def __init__(self, items):
self._format = "".join([item[0] for item in items])
self._items = items
self._buffer_ = win32wnet.NCBBuffer(struct.calcsize(self._format))
for format, name in self._items:
if len(format) == 1:
if format == "c":
val = "\0"
else:
val = 0
else:
l = int(format[:-1])
val = "\0" * l
self.__dict__[name] = val
def _pack(self):
vals = []
for format, name in self._items:
try:
vals.append(self.__dict__[name])
except KeyError:
vals.append(None)
self._buffer_[:] = struct.pack(*(self._format,) + tuple(vals))
def _unpack(self):
items = struct.unpack(self._format, self._buffer_)
assert len(items) == len(self._items), "unexpected number of items to unpack!"
for (format, name), val in zip(self._items, items):
self.__dict__[name] = val
def __setattr__(self, attr, val):
if attr not in self.__dict__ and attr[0] != "_":
for format, attr_name in self._items:
if attr == attr_name:
break
else:
raise AttributeError(attr)
self.__dict__[attr] = val
def SESSION_HEADER():
return NCBStruct(SESSION_HEADER_ITEMS) | null |
171,643 | import struct
import sys
import win32wnet
SESSION_BUFFER_ITEMS = [
(UCHAR, "lsn"),
(UCHAR, "state"),
(str(NCBNAMSZ) + "s", "local_name"),
(str(NCBNAMSZ) + "s", "remote_name"),
(UCHAR, "rcvs_outstanding"),
(UCHAR, "sends_outstanding"),
]
class NCBStruct:
def __init__(self, items):
self._format = "".join([item[0] for item in items])
self._items = items
self._buffer_ = win32wnet.NCBBuffer(struct.calcsize(self._format))
for format, name in self._items:
if len(format) == 1:
if format == "c":
val = "\0"
else:
val = 0
else:
l = int(format[:-1])
val = "\0" * l
self.__dict__[name] = val
def _pack(self):
vals = []
for format, name in self._items:
try:
vals.append(self.__dict__[name])
except KeyError:
vals.append(None)
self._buffer_[:] = struct.pack(*(self._format,) + tuple(vals))
def _unpack(self):
items = struct.unpack(self._format, self._buffer_)
assert len(items) == len(self._items), "unexpected number of items to unpack!"
for (format, name), val in zip(self._items, items):
self.__dict__[name] = val
def __setattr__(self, attr, val):
if attr not in self.__dict__ and attr[0] != "_":
for format, attr_name in self._items:
if attr == attr_name:
break
else:
raise AttributeError(attr)
self.__dict__[attr] = val
def SESSION_BUFFER():
return NCBStruct(SESSION_BUFFER_ITEMS) | null |
171,644 | import struct
import sys
import win32wnet
LANA_ENUM_ITEMS = [
("B", "length"), # Number of valid entries in lana[]
(str(MAX_LANA + 1) + "s", "lana"),
]
class NCBStruct:
def __init__(self, items):
def _pack(self):
def _unpack(self):
def __setattr__(self, attr, val):
def LANA_ENUM():
return NCBStruct(LANA_ENUM_ITEMS) | null |
171,645 | import struct
import sys
import win32wnet
FIND_NAME_HEADER_ITEMS = [
(WORD, "node_count"),
(UCHAR, "reserved"),
(UCHAR, "unique_group"),
]
class NCBStruct:
def __init__(self, items):
self._format = "".join([item[0] for item in items])
self._items = items
self._buffer_ = win32wnet.NCBBuffer(struct.calcsize(self._format))
for format, name in self._items:
if len(format) == 1:
if format == "c":
val = "\0"
else:
val = 0
else:
l = int(format[:-1])
val = "\0" * l
self.__dict__[name] = val
def _pack(self):
vals = []
for format, name in self._items:
try:
vals.append(self.__dict__[name])
except KeyError:
vals.append(None)
self._buffer_[:] = struct.pack(*(self._format,) + tuple(vals))
def _unpack(self):
items = struct.unpack(self._format, self._buffer_)
assert len(items) == len(self._items), "unexpected number of items to unpack!"
for (format, name), val in zip(self._items, items):
self.__dict__[name] = val
def __setattr__(self, attr, val):
if attr not in self.__dict__ and attr[0] != "_":
for format, attr_name in self._items:
if attr == attr_name:
break
else:
raise AttributeError(attr)
self.__dict__[attr] = val
def FIND_NAME_HEADER():
return NCBStruct(FIND_NAME_HEADER_ITEMS) | null |
171,646 | import struct
import sys
import win32wnet
FIND_NAME_BUFFER_ITEMS = [
(UCHAR, "length"),
(UCHAR, "access_control"),
(UCHAR, "frame_control"),
("6s", "destination_addr"),
("6s", "source_addr"),
("18s", "routing_info"),
]
class NCBStruct:
def __init__(self, items):
self._format = "".join([item[0] for item in items])
self._items = items
self._buffer_ = win32wnet.NCBBuffer(struct.calcsize(self._format))
for format, name in self._items:
if len(format) == 1:
if format == "c":
val = "\0"
else:
val = 0
else:
l = int(format[:-1])
val = "\0" * l
self.__dict__[name] = val
def _pack(self):
vals = []
for format, name in self._items:
try:
vals.append(self.__dict__[name])
except KeyError:
vals.append(None)
self._buffer_[:] = struct.pack(*(self._format,) + tuple(vals))
def _unpack(self):
items = struct.unpack(self._format, self._buffer_)
assert len(items) == len(self._items), "unexpected number of items to unpack!"
for (format, name), val in zip(self._items, items):
self.__dict__[name] = val
def __setattr__(self, attr, val):
if attr not in self.__dict__ and attr[0] != "_":
for format, attr_name in self._items:
if attr == attr_name:
break
else:
raise AttributeError(attr)
self.__dict__[attr] = val
def FIND_NAME_BUFFER():
return NCBStruct(FIND_NAME_BUFFER_ITEMS) | null |
171,647 | import struct
import sys
import win32wnet
ACTION_HEADER_ITEMS = [
(ULONG, "transport_id"),
(USHORT, "action_code"),
(USHORT, "reserved"),
]
class NCBStruct:
def __init__(self, items):
self._format = "".join([item[0] for item in items])
self._items = items
self._buffer_ = win32wnet.NCBBuffer(struct.calcsize(self._format))
for format, name in self._items:
if len(format) == 1:
if format == "c":
val = "\0"
else:
val = 0
else:
l = int(format[:-1])
val = "\0" * l
self.__dict__[name] = val
def _pack(self):
vals = []
for format, name in self._items:
try:
vals.append(self.__dict__[name])
except KeyError:
vals.append(None)
self._buffer_[:] = struct.pack(*(self._format,) + tuple(vals))
def _unpack(self):
items = struct.unpack(self._format, self._buffer_)
assert len(items) == len(self._items), "unexpected number of items to unpack!"
for (format, name), val in zip(self._items, items):
self.__dict__[name] = val
def __setattr__(self, attr, val):
if attr not in self.__dict__ and attr[0] != "_":
for format, attr_name in self._items:
if attr == attr_name:
break
else:
raise AttributeError(attr)
self.__dict__[attr] = val
def ACTION_HEADER():
return NCBStruct(ACTION_HEADER_ITEMS) | null |
171,648 | import struct
import sys
import win32wnet
The provided code snippet includes necessary dependencies for implementing the `byte_to_int` function. Write a Python function `def byte_to_int(b)` to solve the following problem:
Given an element in a binary buffer, return its integer value
Here is the function:
def byte_to_int(b):
"""Given an element in a binary buffer, return its integer value"""
if sys.version_info >= (3, 0):
# a byte is already an int in py3k
return b
return ord(b) # its a char from a string in py2k. | Given an element in a binary buffer, return its integer value |
171,649 | import importlib
import os
import sys
import warnings
import pywintypes
import win32api
import win32con
import win32service
import winerror
error = RuntimeError
def _GetServiceShortName(longName):
# looks up a services name
# from the display name
# Thanks to Andy McKay for this code.
access = (
win32con.KEY_READ | win32con.KEY_ENUMERATE_SUB_KEYS | win32con.KEY_QUERY_VALUE
)
hkey = win32api.RegOpenKey(
win32con.HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services", 0, access
)
num = win32api.RegQueryInfoKey(hkey)[0]
longName = longName.lower()
# loop through number of subkeys
for x in range(0, num):
# find service name, open subkey
svc = win32api.RegEnumKey(hkey, x)
skey = win32api.RegOpenKey(hkey, svc, 0, access)
try:
# find display name
thisName = str(win32api.RegQueryValueEx(skey, "DisplayName")[0])
if thisName.lower() == longName:
return svc
except win32api.error:
# in case there is no key called DisplayName
pass
return None | null |
171,650 | import importlib
import os
import sys
import warnings
import pywintypes
import win32api
import win32con
import win32service
import winerror
def SetServiceCustomOption(serviceName, option, value):
try:
serviceName = serviceName._svc_name_
except AttributeError:
pass
key = win32api.RegCreateKey(
win32con.HKEY_LOCAL_MACHINE,
"System\\CurrentControlSet\\Services\\%s\\Parameters" % serviceName,
)
try:
if type(value) == type(0):
win32api.RegSetValueEx(key, option, 0, win32con.REG_DWORD, value)
else:
win32api.RegSetValueEx(key, option, 0, win32con.REG_SZ, value)
finally:
win32api.RegCloseKey(key) | null |
171,651 | import importlib
import os
import sys
import warnings
import pywintypes
import win32api
import win32con
import win32service
import winerror
error = RuntimeError
def GetServiceCustomOption(serviceName, option, defaultValue=None):
# First param may also be a service class/instance.
# This allows services to pass "self"
try:
serviceName = serviceName._svc_name_
except AttributeError:
pass
key = win32api.RegCreateKey(
win32con.HKEY_LOCAL_MACHINE,
"System\\CurrentControlSet\\Services\\%s\\Parameters" % serviceName,
)
try:
try:
return win32api.RegQueryValueEx(key, option)[0]
except win32api.error: # No value.
return defaultValue
finally:
win32api.RegCloseKey(key) | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.