docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Seeks to an offset within the file-like object.
Args:
offset (int): offset to seek.
whence (Optional[int]): value that indicates whether offset is an
absolute or relative position within the file.
Raises:
IOError: if the seek failed.
OSError: if the seek failed. | def seek(self, offset, whence=os.SEEK_SET):
if not self._is_open:
raise IOError('Not opened.')
if self._current_offset < 0:
raise IOError(
'Invalid current offset: {0:d} value less than zero.'.format(
self._current_offset))
if whence == os.SEEK_CUR:
offset +=... | 391,820 |
Create a configuration from a mapping.
This allows either a mapping to be directly passed or as
keyword arguments, for example,
.. code-block:: python
config = {'keep_alive_timeout': 10}
Config.from_mapping(config)
Config.form_mapping(keep_alive_timeout=10)... | def from_mapping(
cls: Type["Config"], mapping: Optional[Mapping[str, Any]] = None, **kwargs: Any
) -> "Config":
mappings: Dict[str, Any] = {}
if mapping is not None:
mappings.update(mapping)
mappings.update(kwargs)
config = cls()
for key, value i... | 391,995 |
Create a configuration from a Python file.
.. code-block:: python
Config.from_pyfile('hypercorn_config.py')
Arguments:
filename: The filename which gives the path to the file. | def from_pyfile(cls: Type["Config"], filename: FilePath) -> "Config":
file_path = os.fspath(filename)
spec = importlib.util.spec_from_file_location("module.name", file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module) # type: ignore
re... | 391,996 |
Load the configuration values from a TOML formatted file.
This allows configuration to be loaded as so
.. code-block:: python
Config.from_toml('config.toml')
Arguments:
filename: The filename which gives the path to the file. | def from_toml(cls: Type["Config"], filename: FilePath) -> "Config":
file_path = os.fspath(filename)
with open(file_path) as file_:
data = toml.load(file_)
return cls.from_mapping(data) | 391,997 |
Create a configuration from a Python object.
This can be used to reference modules or objects within
modules for example,
.. code-block:: python
Config.from_object('module')
Config.from_object('module.instance')
from module import instance
Confi... | def from_object(cls: Type["Config"], instance: Union[object, str]) -> "Config":
if isinstance(instance, str):
try:
path, config = instance.rsplit(".", 1)
except ValueError:
path = instance
instance = importlib.import_module(instanc... | 391,998 |
Parses mt940 data, expects a string with data
Args:
data (str): The MT940 data
Returns: :py:class:`list` of :py:class:`Transaction` | def parse(self, data):
# Remove extraneous whitespace and such
data = '\n'.join(self.strip(data.split('\n')))
# The pattern is a bit annoying to match by regex, even with a greedy
# match it's difficult to get both the beginning and the end so we're
# working around it ... | 392,450 |
play wav file or raw audio (string or generator)
Args:
wav: wav file path
data: raw audio data, str or iterator
rate: sample rate, only for raw audio
channels: channel number, only for raw data
width: raw audio data width, 16 bit is 2, only for raw dat... | def play(self, wav=None, data=None, rate=16000, channels=1, width=2, block=True, spectrum=None):
if wav:
f = wave.open(wav, 'rb')
rate = f.getframerate()
channels = f.getnchannels()
width = f.getsampwidth()
def gen(w):
d = w.r... | 392,990 |
It supports GeneratorType mp3 stream or mp3 data string
Args:
mp3: mp3 file
data: mp3 generator or data
block: if true, block until audio is played. | def play_mp3(self, mp3=None, data=None, block=True):
if platform.machine() == 'mips':
command = 'madplay -o wave:- - | aplay -M'
else:
command = 'ffplay -autoexit -nodisp -'
if mp3:
def gen(m):
with open(m, 'rb') as f:
... | 392,992 |
Writes ADRs and AEDRs for variables
Parameters:
f : file
The open CDF file
varNum : int
The variable number for adding attributes
var_attrs : dict
A dictionary object full of variable attributes
zVar : bool
... | def _write_var_attrs(self, f, varNum, var_attrs, zVar):
if (not isinstance(var_attrs, dict)):
raise TypeError('Variable attribute(s) should be in dictionary form.')
for attr, entry in var_attrs.items():
if (attr in self.gattrs):
print('Attribute: ', att... | 393,074 |
Gets datatype size
Parameters:
datatype : int
CDF variable data type
numElms : int
number of elements
Returns:
numBytes : int
The number of bytes for the data | def _datatype_size(datatype, numElms): # @NoSelf
sizes = {1: 1,
2: 2,
4: 4,
8: 8,
11: 1,
12: 2,
14: 4,
21: 4,
22: 8,
31: 8,
32: 16... | 393,083 |
Write a CCR to file "g" from file "f" with level "level".
Currently, only handles gzip compression.
Parameters:
f : file
Uncompressed file to read from
g : file
File to read the compressed file into
level : int
The leve... | def _write_ccr(self, f, g, level: int):
f.seek(8)
data = f.read()
uSize = len(data)
section_type = CDF.CCR_
rfuA = 0
cData = gzip.compress(data, level)
block_size = CDF.CCR_BASE_SIZE64 + len(cData)
cprOffset = 0
ccr1 = bytearray(32)
... | 393,093 |
Updates variable aedr links
Parameters:
f : file
The open CDF file
attrNum : int
The number of the attribute to change
zVar : bool
True if we are updating a z variable attribute
varNum : int
The vari... | def _update_aedr_link(self, f, attrNum, zVar, varNum, offset):
# The offset to this AEDR's ADR
adr_offset = self.attrsinfo[attrNum][2]
# Get the number of entries
if zVar:
f.seek(adr_offset+56, 0)
# ADR's NzEntries
entries = int.from_bytes(f... | 393,102 |
loads a datasaet (from in-modules datasets) in a dataframe data structure.
Args:
item (str) : name of the dataset to load.
show_doc (bool) : to show the dataset's documentation.
Examples:
>>> iris = data('iris')
>>> data('titanic', show_doc=True)
: returns the dataset's... | def data(item=None, show_doc=False):
if item:
try:
if show_doc:
__print_item_docs(item)
return
df = __read_csv(item)
return df
except KeyError:
find_similar(item)
else:
return __datasets_desc() | 394,827 |
Helper to create summaries for activations.
Creates a summary that provides a histogram of activations.
Creates a summary that measure the sparsity of activations.
Args:
x: Tensor
Returns:
nothing | def _activation_summary(x):
# Remove 'tower_[0-9]/' from the name in case this is a multi-GPU training
# session. This helps the clarity of presentation on tensorboard.
tf.histogram_summary(x.name + '/activations', x)
tf.scalar_summary(x.name + '/sparsity', tf.nn.zero_fraction(x)) | 395,544 |
Ensure directory exists.
Args:
path(str): dir path | def ensure_dir(path):
dirpath = os.path.dirname(path)
if dirpath and not os.path.exists(dirpath):
os.makedirs(dirpath) | 395,658 |
Checks the key path find specification.
Args:
registry_key (WinRegistryKey): Windows Registry key.
search_depth (int): number of key path segments to compare.
Returns:
bool: True if the Windows Registry key matches the find specification,
False if not. | def _CheckKeyPath(self, registry_key, search_depth):
if self._key_path_segments is None:
return False
if search_depth < 0 or search_depth > self._number_of_key_path_segments:
return False
# Note that the root has no entry in the key path segments and
# no name to match.
if search_... | 395,759 |
Determines if the find specification is at maximum depth.
Args:
search_depth (int): number of key path segments to compare.
Returns:
bool: True if at maximum depth, False if not. | def AtMaximumDepth(self, search_depth):
if self._key_path_segments is not None:
if search_depth >= self._number_of_key_path_segments:
return True
return False | 395,760 |
Determines if the Windows Registry key matches the find specification.
Args:
registry_key (WinRegistryKey): Windows Registry key.
search_depth (int): number of key path segments to compare.
Returns:
tuple: contains:
bool: True if the Windows Registry key matches the find specificati... | def Matches(self, registry_key, search_depth):
if self._key_path_segments is None:
key_path_match = None
else:
key_path_match = self._CheckKeyPath(registry_key, search_depth)
if not key_path_match:
return False, key_path_match
if search_depth != self._number_of_key_path_seg... | 395,761 |
Initializes a Windows Registry searcher.
Args:
win_registry (WinRegistry): Windows Registry.
Raises:
ValueError: when Windows Registry is not set. | def __init__(self, win_registry):
if not win_registry:
raise ValueError('Missing Windows Registry value.')
super(WinRegistrySearcher, self).__init__()
self._win_registry = win_registry | 395,762 |
Searches for matching keys within the Windows Registry key.
Args:
registry_key (WinRegistryKey): Windows Registry key.
find_specs (list[FindSpec]): find specifications.
search_depth (int): number of key path segments to compare.
Yields:
str: key path of a matching Windows Registry key. | def _FindInKey(self, registry_key, find_specs, search_depth):
sub_find_specs = []
for find_spec in find_specs:
match, key_path_match = find_spec.Matches(registry_key, search_depth)
if match:
yield registry_key.path
# pylint: disable=singleton-comparison
if key_path_match !=... | 395,763 |
Searches for matching keys within the Windows Registry.
Args:
find_specs (list[FindSpec]): find specifications. where None
will return all allocated Windows Registry keys.
Yields:
str: key path of a matching Windows Registry key. | def Find(self, find_specs=None):
if not find_specs:
find_specs = [FindSpec()]
registry_key = self._win_registry.GetRootKey()
for matching_path in self._FindInKey(registry_key, find_specs, 0):
yield matching_path | 395,764 |
Initializes a Windows Registry file.
Args:
ascii_codepage (Optional[str]): ASCII string codepage.
key_path_prefix (Optional[str]): Windows Registry key path prefix. | def __init__(self, ascii_codepage='cp1252', key_path_prefix=''):
super(WinRegistryFile, self).__init__()
self._ascii_codepage = ascii_codepage
self._key_path_prefix = key_path_prefix
self._key_path_prefix_length = len(key_path_prefix)
self._key_path_prefix_upper = key_path_prefix.upper() | 395,765 |
Sets the Window Registry key path prefix.
Args:
key_path_prefix (str): Windows Registry key path prefix. | def SetKeyPathPrefix(self, key_path_prefix):
self._key_path_prefix = key_path_prefix
self._key_path_prefix_length = len(key_path_prefix)
self._key_path_prefix_upper = key_path_prefix.upper() | 395,767 |
Initializes a Windows Registry key.
Args:
key_path (Optional[str]): Windows Registry key path. | def __init__(self, key_path=''):
super(WinRegistryKey, self).__init__()
self._key_path = key_paths.JoinKeyPath([key_path]) | 395,768 |
Initializes a Windows Registry file.
Args:
ascii_codepage (str): ASCII string codepage.
key_path_prefix (str): Windows Registry key path prefix. | def __init__(self, ascii_codepage='cp1252', key_path_prefix=''):
super(FakeWinRegistryFile, self).__init__(
ascii_codepage=ascii_codepage, key_path_prefix=key_path_prefix)
self._root_key = None | 395,771 |
Adds a Windows Registry key for a specific key path.
Args:
key_path (str): Windows Registry key path to add the key.
registry_key (WinRegistryKey): Windows Registry key.
Raises:
KeyError: if the subkey already exists.
ValueError: if the Windows Registry key cannot be added. | def AddKeyByPath(self, key_path, registry_key):
if not key_path.startswith(definitions.KEY_PATH_SEPARATOR):
raise ValueError('Key path does not start with: {0:s}'.format(
definitions.KEY_PATH_SEPARATOR))
if not self._root_key:
self._root_key = FakeWinRegistryKey(self._key_path_prefix... | 395,772 |
Retrieves the key for a specific path.
Args:
key_path (str): Windows Registry key path.
Returns:
WinRegistryKey: Windows Registry key or None if not available. | def GetKeyByPath(self, key_path):
key_path_upper = key_path.upper()
if key_path_upper.startswith(self._key_path_prefix_upper):
relative_key_path = key_path[self._key_path_prefix_length:]
elif key_path.startswith(definitions.KEY_PATH_SEPARATOR):
relative_key_path = key_path
key_path = ... | 395,773 |
Builds the Windows Registry key hierarchy.
Args:
subkeys (list[FakeWinRegistryKey]): list of subkeys.
values (list[FakeWinRegistryValue]): list of values. | def _BuildKeyHierarchy(self, subkeys, values):
if subkeys:
for registry_key in subkeys:
name = registry_key.name.upper()
if name in self._subkeys:
continue
self._subkeys[name] = registry_key
# pylint: disable=protected-access
registry_key._key_path = key... | 395,776 |
Adds a subkey.
Args:
registry_key (WinRegistryKey): Windows Registry subkey.
Raises:
KeyError: if the subkey already exists. | def AddSubkey(self, registry_key):
name = registry_key.name.upper()
if name in self._subkeys:
raise KeyError(
'Subkey: {0:s} already exists.'.format(registry_key.name))
self._subkeys[name] = registry_key
key_path = key_paths.JoinKeyPath([self._key_path, registry_key.name])
reg... | 395,777 |
Adds a value.
Args:
registry_value (WinRegistryValue): Windows Registry value.
Raises:
KeyError: if the value already exists. | def AddValue(self, registry_value):
name = registry_value.name.upper()
if name in self._values:
raise KeyError(
'Value: {0:s} already exists.'.format(registry_value.name))
self._values[name] = registry_value | 395,778 |
Retrieves a subkey by index.
Args:
index (int): index of the subkey.
Returns:
WinRegistryKey: Windows Registry subkey or None if not found.
Raises:
IndexError: if the index is out of bounds. | def GetSubkeyByIndex(self, index):
subkeys = list(self._subkeys.values())
if index < 0 or index >= len(subkeys):
raise IndexError('Index out of bounds.')
return subkeys[index] | 395,779 |
Retrieves a subkey by path.
Args:
key_path (str): path of the subkey.
Returns:
WinRegistryKey: Windows Registry subkey or None if not found. | def GetSubkeyByPath(self, key_path):
subkey = self
for path_segment in key_paths.SplitKeyPath(key_path):
subkey = subkey.GetSubkeyByName(path_segment)
if not subkey:
break
return subkey | 395,780 |
Initializes a Windows Registry value.
Args:
name (str): name of the Windows Registry value.
data (Optional[bytes]): value data.
data_type (Optional[int]): value data type.
offset (Optional[int]): offset of the value within the Windows Registry
file. | def __init__(self, name, data=b'', data_type=definitions.REG_NONE, offset=0):
super(FakeWinRegistryValue, self).__init__()
self._data = data
self._data_type = data_type
self._data_size = len(data)
self._name = name
self._offset = offset | 395,781 |
Initializes the Windows Registry file mapping.
Args:
key_path_prefix (str): Windows Registry key path prefix.
windows_path (str): Windows path to the Windows Registry file, such as:
C:\\Windows\\System32\\config\\SYSTEM
unique_key_paths (list[str]): key paths unique to the Windows Regis... | def __init__(self, key_path_prefix, windows_path, unique_key_paths):
super(WinRegistryFileMapping, self).__init__()
self.key_path_prefix = key_path_prefix
self.unique_key_paths = unique_key_paths
self.windows_path = windows_path | 395,783 |
Initializes the Windows Registry.
Args:
ascii_codepage (Optional[str]): ASCII string codepage.
registry_file_reader (Optional[WinRegistryFileReader]): Windows Registry
file reader. | def __init__(self, ascii_codepage='cp1252', registry_file_reader=None):
super(WinRegistry, self).__init__()
self._ascii_codepage = ascii_codepage
self._registry_file_reader = registry_file_reader
self._registry_files = {}
self._user_registry_files = {} | 395,784 |
Retrieves a cached Windows Registry file for a key path.
Args:
key_path_upper (str): Windows Registry key path, in upper case with
a resolved root key alias.
Returns:
tuple: consist:
str: key path prefix
WinRegistryFile: corresponding Windows Registry file or None if not... | def _GetCachedFileByPath(self, key_path_upper):
longest_key_path_prefix_upper = ''
longest_key_path_prefix_length = len(longest_key_path_prefix_upper)
for key_path_prefix_upper in self._registry_files:
if key_path_upper.startswith(key_path_prefix_upper):
key_path_prefix_length = len(key_p... | 395,786 |
Virtual key callback to determine the current control set.
Args:
key_path_suffix (str): current control set Windows Registry key path
suffix with leading path separator.
Returns:
WinRegistryKey: the current control set Windows Registry key or None
if not available. | def _GetCurrentControlSet(self, key_path_suffix):
select_key_path = 'HKEY_LOCAL_MACHINE\\System\\Select'
select_key = self.GetKeyByPath(select_key_path)
if not select_key:
return None
# To determine the current control set check:
# 1. The "Current" value.
# 2. The "Default" value.
... | 395,787 |
Virtual key callback to determine the users sub keys.
Args:
key_path_suffix (str): users Windows Registry key path suffix with
leading path separator.
Returns:
WinRegistryKey: the users Windows Registry key or None if not available. | def _GetUsers(self, key_path_suffix):
user_key_name, _, key_path_suffix = key_path_suffix.partition(
definitions.KEY_PATH_SEPARATOR)
# HKEY_USERS\.DEFAULT is an alias for HKEY_USERS\S-1-5-18 which is
# the Local System account.
if user_key_name == '.DEFAULT':
search_key_name = 'S-1-5... | 395,788 |
Retrieves a Windows Registry file for a specific path.
Args:
key_path_upper (str): Windows Registry key path, in upper case with
a resolved root key alias.
Returns:
tuple: consists:
str: upper case key path prefix
WinRegistryFile: corresponding Windows Registry file or N... | def _GetFileByPath(self, key_path_upper):
# TODO: handle HKEY_USERS in both 9X and NT.
key_path_prefix, registry_file = self._GetCachedFileByPath(key_path_upper)
if not registry_file:
for mapping in self._GetFileMappingsByPath(key_path_upper):
try:
registry_file = self._OpenFil... | 395,789 |
Retrieves the Windows Registry file mappings for a specific path.
Args:
key_path_upper (str): Windows Registry key path, in upper case with
a resolved root key alias.
Yields:
WinRegistryFileMapping: Windows Registry file mapping. | def _GetFileMappingsByPath(self, key_path_upper):
candidate_mappings = []
for mapping in self._REGISTRY_FILE_MAPPINGS_NT:
if key_path_upper.startswith(mapping.key_path_prefix.upper()):
candidate_mappings.append(mapping)
# Sort the candidate mappings by longest (most specific) match first... | 395,790 |
Opens a Windows Registry file.
Args:
path (str): path of the Windows Registry file.
Returns:
WinRegistryFile: Windows Registry file or None if not available. | def _OpenFile(self, path):
if not self._registry_file_reader:
return None
return self._registry_file_reader.Open(
path, ascii_codepage=self._ascii_codepage) | 395,791 |
Retrieves the key for a specific path.
Args:
key_path (str): Windows Registry key path.
Returns:
WinRegistryKey: Windows Registry key or None if not available.
Raises:
RuntimeError: if the root key is not supported. | def GetKeyByPath(self, key_path):
root_key_path, _, key_path = key_path.partition(
definitions.KEY_PATH_SEPARATOR)
# Resolve a root key alias.
root_key_path = root_key_path.upper()
root_key_path = self._ROOT_KEY_ALIASES.get(root_key_path, root_key_path)
if root_key_path not in self._R... | 395,792 |
Determines the Registry file mapping based on the content of the file.
Args:
registry_file (WinRegistyFile): Windows Registry file.
Returns:
str: key path prefix or an empty string.
Raises:
RuntimeError: if there are multiple matching mappings and
the correct mapping cannot be... | def GetRegistryFileMapping(self, registry_file):
if not registry_file:
return ''
candidate_mappings = []
for mapping in self._REGISTRY_FILE_MAPPINGS_NT:
if not mapping.unique_key_paths:
continue
# If all unique key paths are found consider the file to match.
match = Tr... | 395,793 |
Maps the Windows Registry file to a specific key path prefix.
Args:
key_path_prefix (str): key path prefix.
registry_file (WinRegistryFile): Windows Registry file. | def MapFile(self, key_path_prefix, registry_file):
self._registry_files[key_path_prefix.upper()] = registry_file
registry_file.SetKeyPathPrefix(key_path_prefix) | 395,795 |
Initializes the Windows Registry file.
Args:
ascii_codepage (Optional[str]): ASCII string codepage.
key_path_prefix (Optional[str]): Windows Registry key path prefix. | def __init__(self, ascii_codepage='cp1252', key_path_prefix=''):
super(REGFWinRegistryFile, self).__init__(
ascii_codepage=ascii_codepage, key_path_prefix=key_path_prefix)
self._file_object = None
self._regf_file = pyregf.file()
self._regf_file.set_ascii_codepage(ascii_codepage) | 395,796 |
Retrieves the key for a specific path.
Args:
key_path (str): Windows Registry key path.
Returns:
WinRegistryKey: Registry key or None if not available. | def GetKeyByPath(self, key_path):
key_path_upper = key_path.upper()
if key_path_upper.startswith(self._key_path_prefix_upper):
relative_key_path = key_path[self._key_path_prefix_length:]
elif key_path.startswith(definitions.KEY_PATH_SEPARATOR):
relative_key_path = key_path
key_path = ... | 395,797 |
Opens the Windows Registry file using a file-like object.
Args:
file_object (file): file-like object.
Returns:
bool: True if successful or False if not. | def Open(self, file_object):
self._file_object = file_object
self._regf_file.open_file_object(self._file_object)
return True | 395,799 |
Initializes a Windows Registry key object.
Args:
pyregf_key (pyregf.key): pyregf key object.
key_path (Optional[str]): Windows Registry key path. | def __init__(self, pyregf_key, key_path=''):
super(REGFWinRegistryKey, self).__init__(key_path=key_path)
self._pyregf_key = pyregf_key | 395,800 |
Retrieves a subkey by index.
Args:
index (int): index of the subkey.
Returns:
WinRegistryKey: Windows Registry subkey or None if not found.
Raises:
IndexError: if the index is out of bounds. | def GetSubkeyByIndex(self, index):
if index < 0 or index >= self._pyregf_key.number_of_sub_keys:
raise IndexError('Index out of bounds.')
pyregf_key = self._pyregf_key.get_sub_key(index)
if not pyregf_key:
return None
key_path = key_paths.JoinKeyPath([self._key_path, pyregf_key.name])... | 395,802 |
Retrieves a subkey by name.
Args:
name (str): name of the subkey.
Returns:
WinRegistryKey: Windows Registry subkey or None if not found. | def GetSubkeyByName(self, name):
pyregf_key = self._pyregf_key.get_sub_key_by_name(name)
if not pyregf_key:
return None
key_path = key_paths.JoinKeyPath([self._key_path, pyregf_key.name])
return REGFWinRegistryKey(pyregf_key, key_path=key_path) | 395,803 |
Retrieves a subkey by path.
Args:
key_path (str): path of the subkey.
Returns:
WinRegistryKey: Windows Registry subkey or None if not found. | def GetSubkeyByPath(self, key_path):
pyregf_key = self._pyregf_key.get_sub_key_by_path(key_path)
if not pyregf_key:
return None
key_path = key_paths.JoinKeyPath([self._key_path, key_path])
return REGFWinRegistryKey(pyregf_key, key_path=key_path) | 395,804 |
Retrieves a value by name.
Value names are not unique and pyregf provides first match for the value.
Args:
name (str): name of the value or an empty string for the default value.
Returns:
WinRegistryValue: Windows Registry value if a corresponding value was
found or None if not. | def GetValueByName(self, name):
pyregf_value = self._pyregf_key.get_value_by_name(name)
if not pyregf_value:
return None
return REGFWinRegistryValue(pyregf_value) | 395,806 |
Initializes a Windows Registry value.
Args:
pyregf_value (pyregf.value): pyregf value object. | def __init__(self, pyregf_value):
super(REGFWinRegistryValue, self).__init__()
self._pyregf_value = pyregf_value | 395,807 |
Joins the path segments into key path.
Args:
path_segments (list[str]): Windows Registry key path segments.
Returns:
str: key path. | def JoinKeyPath(path_segments):
# This is an optimized way to combine the path segments into a single path
# and combine multiple successive path separators to one.
# Split all the path segments based on the path (segment) separator.
path_segments = [
segment.split(definitions.KEY_PATH_SEPARATOR)
... | 395,810 |
Splits the key path into path segments.
Args:
key_path (str): key path.
path_separator (Optional[str]): path separator.
Returns:
list[str]: key path segments without the root path segment, which is an
empty string. | def SplitKeyPath(key_path, path_separator=definitions.KEY_PATH_SEPARATOR):
# Split the path with the path separator and remove empty path segments.
return list(filter(None, key_path.split(path_separator))) | 395,811 |
Initializes a Windows Registry key.
Args:
name (str): name of the Windows Registry key.
key_path (Optional[str]): Windows Registry key path.
registry (Optional[WinRegistry]): Windows Registry. | def __init__(self, name, key_path='', registry=None):
super(VirtualWinRegistryKey, self).__init__(key_path=key_path)
self._name = name
self._registry = registry
self._registry_key = None
self._subkeys = collections.OrderedDict() | 395,812 |
Joins the path segments into key path.
Args:
path_segments (list[str]): Windows Registry key path segments.
Returns:
str: key path. | def _JoinKeyPath(self, path_segments):
# This is an optimized way to combine the path segments into a single path
# and combine multiple successive path separators to one.
# Split all the path segments based on the path (segment) separator.
path_segments = [
segment.split(definitions.KEY_P... | 395,819 |
Adds a subkey.
Args:
registry_key (WinRegistryKey): Windows Registry subkey.
Raises:
KeyError: if the subkey already exists. | def AddSubkey(self, registry_key):
name = registry_key.name.upper()
if name in self._subkeys:
raise KeyError(
'Subkey: {0:s} already exists.'.format(registry_key.name))
self._subkeys[name] = registry_key
key_path = self._JoinKeyPath([self._key_path, registry_key.name])
registr... | 395,820 |
Retrieves a subkey by index.
Args:
index (int): index of the subkey.
Returns:
WinRegistryKey: Windows Registry subkey or None if not found.
Raises:
IndexError: if the index is out of bounds. | def GetSubkeyByIndex(self, index):
if not self._registry_key and self._registry:
self._GetKeyFromRegistry()
subkeys = list(self._subkeys.values())
if index < 0 or index >= len(subkeys):
raise IndexError('Index out of bounds.')
return subkeys[index] | 395,821 |
Retrieves a subkey by name.
Args:
name (str): name of the subkey.
Returns:
WinRegistryKey: Windows Registry subkey or None if not found. | def GetSubkeyByName(self, name):
if not self._registry_key and self._registry:
self._GetKeyFromRegistry()
return self._subkeys.get(name.upper(), None) | 395,822 |
Retrieves a subkey by path.
Args:
key_path (str): path of the subkey.
Returns:
WinRegistryKey: Windows Registry subkey or None if not found. | def GetSubkeyByPath(self, key_path):
if not self._registry_key and self._registry:
self._GetKeyFromRegistry()
subkey = self
for path_segment in key_paths.SplitKeyPath(key_path):
subkey = subkey.GetSubkeyByName(path_segment)
if not subkey:
break
return subkey | 395,823 |
Retrieves a value by name.
Args:
name (str): name of the value or an empty string for the default value.
Returns:
WinRegistryValue: Windows Registry value or None if not found. | def GetValueByName(self, name):
if not self._registry_key and self._registry:
self._GetKeyFromRegistry()
if not self._registry_key:
return None
return self._registry_key.GetValueByName(name) | 395,825 |
Initializer. Subclass may override.
Args:
options: an dict containing the options passed to RefactoringTool
that could be used to customize the fixer through the command line.
log: a list to append warnings and other messages to. | def __init__(self, options, log):
self.options = options
self.log = log
self.compile_pattern() | 397,577 |
Generator yielding matches for a sequence of patterns and nodes.
Args:
patterns: a sequence of patterns
nodes: a sequence of nodes
Yields:
(count, results) tuples where:
count: the entire sequence of patterns matches nodes[:count];
results: dict containing named submatc... | def generate_matches(patterns, nodes):
if not patterns:
yield 0, {}
else:
p, rest = patterns[0], patterns[1:]
for c0, r0 in p.generate_matches(nodes):
if not rest:
yield c0, r0
else:
for c1, r1 in generate_matches(rest, nodes[c... | 398,393 |
Generator yielding matches for a sequence of nodes.
Args:
nodes: sequence of nodes
Yields:
(count, results) tuples where:
count: the match comprises nodes[:count];
results: dict containing named submatches. | def generate_matches(self, nodes):
if self.content is None:
# Shortcut for special case (see __init__.__doc__)
for count in xrange(self.min, 1 + min(len(nodes), self.max)):
r = {}
if self.name:
r[self.name] = nodes[:count]
... | 398,425 |
Update oldobj, if possible in place, with newobj.
If oldobj is immutable, this simply returns newobj.
Args:
oldobj: the object to be updated
newobj: the object used as the source for the update | def _update(self, namespace, name, oldobj, newobj, is_class_namespace=False):
try:
notify_info2('Updating: ', oldobj)
if oldobj is newobj:
# Probably something imported
return
if type(oldobj) is not type(newobj):
# Cop... | 398,437 |
Follow an attribute chain.
If you have a chain of objects where a.foo -> b, b.foo-> c, etc,
use this to iterate over all objects in the chain. Iteration is
terminated by getattr(x, attr) is None.
Args:
obj: the starting object
attr: the name of the chaining attribute
Yields:
... | def attr_chain(obj, attr):
next = getattr(obj, attr)
while next:
yield next
next = getattr(next, attr) | 398,453 |
Main program.
Args:
fixer_pkg: the name of a package where the fixers are located.
args: optional; a list of command line arguments. If omitted,
sys.argv[1:] is used.
Returns a suggested exit status (0, 1, 2). | def main(fixer_pkg, args=None):
# Set up option parser
parser = optparse.OptionParser(usage="2to3 [options] file|dir ...")
parser.add_option("-d", "--doctests_only", action="store_true",
help="Fix up doctests only")
parser.add_option("-f", "--fix", action="append", default=[],... | 398,574 |
Initializer.
Args:
fixer_names: a list of fixers to import
options: an dict with configuration.
explicit: a list of fixers to run even if they are explicit. | def __init__(self, fixer_names, options=None, explicit=None):
self.fixers = fixer_names
self.explicit = explicit or []
self.options = self._default_options.copy()
if options is not None:
self.options.update(options)
if self.options["print_function"]:
... | 398,846 |
Refactor a given input string.
Args:
data: a string holding the code to be refactored.
name: a human-readable name for use in error/log messages.
Returns:
An AST corresponding to the refactored input stream; None if
there were errors during the parse. | def refactor_string(self, data, name):
features = _detect_future_features(data)
if "print_function" in features:
self.driver.grammar = pygram.python_grammar_no_print_statement
try:
tree = self.driver.parse_string(data)
except Exception as err:
... | 398,854 |
Refactors a parse tree (modifying the tree in place).
For compatible patterns the bottom matcher module is
used. Otherwise the tree is traversed node-to-node for
matches.
Args:
tree: a pytree.Node instance representing the root of the tree
to be refactored... | def refactor_tree(self, tree, name):
for fixer in chain(self.pre_order, self.post_order):
fixer.start_tree(tree, name)
#use traditional matching for the incompatible fixers
self.traverse_by(self.bmi_pre_order_heads, tree.pre_order())
self.traverse_by(self.bmi_post_... | 398,856 |
Traverse an AST, applying a set of fixers to each node.
This is a helper method for refactor_tree().
Args:
fixers: a list of fixer instances.
traversal: a generator that yields AST nodes.
Returns:
None | def traverse_by(self, fixers, traversal):
if not fixers:
return
for node in traversal:
for fixer in fixers[node.type]:
results = fixer.match(node)
if results:
new = fixer.transform(node, results)
if ... | 398,857 |
Overwrite class parameters if passed as keyword arguments.
Args:
model (django.db.models.Model): Model to select choices from.
queryset (django.db.models.query.QuerySet): QuerySet to select choices from.
search_fields (list): List of model lookup strings.
max_res... | def __init__(self, *args, **kwargs):
self.model = kwargs.pop('model', self.model)
self.queryset = kwargs.pop('queryset', self.queryset)
self.search_fields = kwargs.pop('search_fields', self.search_fields)
self.max_results = kwargs.pop('max_results', self.max_results)
def... | 400,123 |
Construct a new PushClient object.
Args:
host: The server protocol, hostname, and port.
api_url: The api url at the host. | def __init__(self, host=None, api_url=None):
self.host = host
if not self.host:
self.host = PushClient.DEFAULT_HOST
self.api_url = api_url
if not self.api_url:
self.api_url = PushClient.DEFAULT_BASE_API_URL | 401,669 |
Send push notifications
The server will validate any type of syntax errors and the client will
raise the proper exceptions for the user to handle.
Each notification is of the form:
{
'to': 'ExponentPushToken[xxx]',
'body': 'This text gets display in the notification... | def _publish_internal(self, push_messages):
# Delayed import because this file is immediately read on install, and
# the requests library may not be installed yet.
import requests
response = requests.post(
self.host + self.api_url + '/push/send',
data=js... | 401,671 |
Update weighted average rate. Param n is generic; it's how many of
whatever the caller is doing (rows, checksums, etc.). Param s is how
long this n took, in seconds (hi-res or not).
Parameters:
n - Number of operations (rows, etc.)
t - Amount of time in seconds that n ... | def update(self, n, t):
if self.avg_n and self.avg_t:
self.avg_n = (self.avg_n * self.weight) + n
self.avg_t = (self.avg_t * self.weight) + t
else:
self.avg_n = n
self.avg_t = t
new_n = int(self.avg_rate * self.target_t)
return ne... | 401,737 |
Cast the specified value to the specified type (returned by func). Currently this
only support int, float, bool. Should be extended if needed.
Parameters:
func (func): Calback function to used cast to type (int, bool, float).
value (any): value to be cast and returned. | def cast(func, value):
if value is not None:
if func == bool:
return bool(int(value))
elif func in (int, float):
try:
return func(value)
except ValueError:
return float('nan')
return func(value)
return value | 402,803 |
Returns a query string (uses for HTTP URLs) where only the value is URL encoded.
Example return value: '?genre=action&type=1337'.
Parameters:
args (dict): Arguments to include in query string. | def joinArgs(args):
if not args:
return ''
arglist = []
for key in sorted(args, key=lambda x: x.lower()):
value = compat.ustr(args[key])
arglist.append('%s=%s' % (key, compat.quote(value)))
return '?%s' % '&'.join(arglist) | 402,804 |
Returns the integer value of the library string type.
Parameters:
libtype (str): LibType to lookup (movie, show, season, episode, artist, album, track,
collection)
Raises:
:class:`plexapi.exceptions.NotFound`: Unknown libtype | def searchType(libtype):
libtype = compat.ustr(libtype)
if libtype in [compat.ustr(v) for v in SEARCHTYPES.values()]:
return libtype
if SEARCHTYPES.get(libtype) is not None:
return SEARCHTYPES[libtype]
raise NotFound('Unknown libtype: %s' % libtype) | 402,806 |
Returns the result of <callback> for each set of \*args in listargs. Each call
to <callback> is called concurrently in their own separate threads.
Parameters:
callback (func): Callback function to apply to each set of \*args.
listargs (list): List of lists; \*args to pass each t... | def threaded(callback, listargs):
threads, results = [], []
job_is_done_event = Event()
for args in listargs:
args += [results, len(results)]
results.append(None)
threads.append(Thread(target=callback, args=args, kwargs=dict(job_is_done_event=job_is_done_event)))
threads... | 402,807 |
Returns a datetime object from the specified value.
Parameters:
value (str): value to return as a datetime
format (str): Format to pass strftime (optional; if value is a str). | def toDatetime(value, format=None):
if value and value is not None:
if format:
value = datetime.strptime(value, format)
else:
# https://bugs.python.org/issue30684
# And platform support for before epoch seems to be flaky.
# TODO check for others e... | 402,808 |
Returns a list of strings from the specified value.
Parameters:
value (str): comma delimited string to convert to list.
itemcast (func): Function to cast each list item to (default str).
delim (str): string delimiter (optional; default ','). | def toList(value, itemcast=None, delim=','):
value = value or ''
itemcast = itemcast or str
return [itemcast(item) for item in value.split(delim) if item != ''] | 402,809 |
Returns the :class:`~plexapi.client.PlexClient` that matches the specified name.
Parameters:
name (str): Name of the client to return.
Raises:
:class:`plexapi.exceptions.NotFound`: Unknown client name | def client(self, name):
for client in self.clients():
if client and client.title == name:
return client
raise NotFound('Unknown client name: %s' % name) | 402,850 |
Creates and returns a new :class:`~plexapi.playlist.Playlist`.
Parameters:
title (str): Title of the playlist to be created.
items (list<Media>): List of media items to include in the playlist. | def createPlaylist(self, title, items=None, section=None, limit=None, smart=None, **kwargs):
return Playlist.create(self, title, items=items, limit=limit, section=section, smart=smart, **kwargs) | 402,851 |
Download databases.
Parameters:
savepath (str): Defaults to current working dir.
unpack (bool): Unpack the zip file. | def downloadDatabases(self, savepath=None, unpack=False):
url = self.url('/diagnostics/databases')
filepath = utils.download(url, self._token, None, savepath, self._session, unpack=unpack)
return filepath | 402,852 |
Returns a :class:`~plexapi.base.Release` object containing release info.
Parameters:
force (bool): Force server to check for new releases
download (bool): Download if a update is available. | def check_for_update(self, force=True, download=False):
part = '/updater/check?download=%s' % (1 if download else 0)
if force:
self.query(part, method=self._session.put)
releases = self.fetchItems('/updater/status')
if len(releases):
return releases[0] | 402,853 |
Returns the URL for a transcoded image from the specified media object.
Returns None if no media specified (needed if user tries to pass thumb
or art directly).
Parameters:
height (int): Height to transcode the image to.
width (int): Width to transcod... | def transcodeImage(self, media, height, width, opacity=100, saturation=100):
if media:
transcode_url = '/photo/:/transcode?height=%s&width=%s&opacity=%s&saturation=%s&url=%s' % (
height, width, opacity, saturation, media)
return self.url(transcode_url, includeTok... | 402,857 |
Returns the specified configuration value or <default> if not found.
Parameters:
key (str): Configuration variable to load in the format '<section>.<variable>'.
default: Default value to use if key not found.
cast (func): Cast the value to the specified type ... | def get(self, key, default=None, cast=None):
try:
# First: check environment variable is set
envkey = 'PLEXAPI_%s' % key.upper().replace('.', '_')
value = os.environ.get(envkey)
if value is None:
# Second: check the config file has attr
... | 402,872 |
Mark the file as downloaded (by the nature of Plex it will be marked as downloaded within
any SyncItem where it presented).
Parameters:
media (base.Playable): the media to be marked as downloaded. | def markDownloaded(self, media):
url = '/sync/%s/item/%s/downloaded' % (self.clientIdentifier, media.ratingKey)
media._server.query(url, method=requests.put) | 402,902 |
Returns a :class:`~plexapi.sync.MediaSettings` object, based on provided video quality value.
Parameters:
videoQuality (int): idx of quality of the video, one of VIDEO_QUALITY_* values defined in this module.
Raises:
:class:`plexapi.exceptions.BadRequest`: when ... | def createVideo(videoQuality):
if videoQuality == VIDEO_QUALITY_ORIGINAL:
return MediaSettings('', '', '')
elif videoQuality < len(VIDEO_QUALITIES['bitrate']):
return MediaSettings(VIDEO_QUALITIES['bitrate'][videoQuality],
VIDEO_QUALITIES... | 402,908 |
Returns a :class:`~plexapi.sync.MediaSettings` object, based on provided photo quality value.
Parameters:
resolution (str): maximum allowed resolution for synchronized photos, see PHOTO_QUALITY_* values in the
module.
Raises:
:c... | def createPhoto(resolution):
if resolution in PHOTO_QUALITIES:
return MediaSettings(photoQuality=PHOTO_QUALITIES[resolution], photoResolution=resolution)
else:
raise BadRequest('Unexpected photo quality') | 402,909 |
Creates a :class:`~plexapi.sync.Policy` object for provided options and automatically sets proper `scope`
value.
Parameters:
limit (int): limit items by count.
unwatched (bool): if True then watched items wouldn't be synced.
Returns:
... | def create(limit=None, unwatched=False):
scope = 'all'
if limit is None:
limit = 0
else:
scope = 'count'
return Policy(scope, unwatched, limit) | 402,911 |
Edit an object.
Parameters:
kwargs (dict): Dict of settings to edit.
Example:
{'type': 1,
'id': movie.ratingKey,
'collection[0].tag.tag': 'Super',
'collection.locked': 0} | def edit(self, **kwargs):
if 'id' not in kwargs:
kwargs['id'] = self.ratingKey
if 'type' not in kwargs:
kwargs['type'] = utils.searchType(self.type)
part = '/library/sections/%s/all?%s' % (self.librarySectionID,
ur... | 402,928 |
Helper to edit and refresh a tags.
Parameters:
tag (str): tag name
items (list): list of tags to add
locked (bool): lock this field.
remove (bool): If this is active remove the tags in items. | def _edit_tags(self, tag, items, locked=True, remove=False):
if not isinstance(items, list):
items = [items]
value = getattr(self, tag + 's')
existing_cols = [t.tag for t in value if t and remove is False]
d = tag_helper(tag, existing_cols + items, locked, remove)
... | 402,929 |
Returns a stream url that may be used by external applications such as VLC.
Parameters:
**params (dict): optional parameters to manipulate the playback when accessing
the stream. A few known parameters include: maxVideoBitrate, videoResolution
offset,... | def getStreamURL(self, **params):
if self.TYPE not in ('movie', 'episode', 'track'):
raise Unsupported('Fetching stream URL for %s is unsupported.' % self.TYPE)
mvb = params.get('maxVideoBitrate')
vr = params.get('videoResolution', '')
params = {
'path': ... | 402,932 |
Set the watched progress for this video.
Note that setting the time to 0 will not work.
Use `markWatched` or `markUnwatched` to achieve
that goal.
Parameters:
time (int): milliseconds watched
state (string): state of the video, default 'stopped' | def updateProgress(self, time, state='stopped'):
key = '/:/progress?key=%s&identifier=com.plexapp.plugins.library&time=%d&state=%s' % (self.ratingKey,
time, state)
self._server.query(key)
self.... | 402,937 |
Set the timeline progress for this video.
Parameters:
time (int): milliseconds watched
state (string): state of the video, default 'stopped'
duration (int): duration of the item | def updateTimeline(self, time, state='stopped', duration=None):
durationStr = '&duration='
if duration is not None:
durationStr = durationStr + str(duration)
else:
durationStr = durationStr + str(self.duration)
key = '/:/timeline?ratingKey=%s&key=%s&ident... | 402,938 |
Returns the :class:`~plexapi.library.LibrarySection` that matches the specified title.
Parameters:
title (str): Title of the section to return. | def section(self, title=None):
for section in self.sections():
if section.title.lower() == title.lower():
return section
raise NotFound('Invalid library section: %s' % title) | 402,941 |
Returns the :class:`~plexapi.library.LibrarySection` that matches the specified sectionID.
Parameters:
sectionID (str): ID of the section to return. | def sectionByID(self, sectionID):
if not self._sectionsByID or sectionID not in self._sectionsByID:
self.sections()
return self._sectionsByID[sectionID] | 402,942 |
Edit a library (Note: agent is required). See :class:`~plexapi.library.Library` for example usage.
Parameters:
kwargs (dict): Dict of settings to edit. | def edit(self, **kwargs):
part = '/library/sections/%s?%s' % (self.key, urlencode(kwargs))
self._server.query(part, method=self._server._session.put)
# Reload this way since the self.key dont have a full path, but is simply a id.
for s in self._server.library.sections():
... | 402,948 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.