_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q40800 | Socket.connect | train | def connect(self):
"""Connect to the given socket"""
if not self.connected:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.connect(self.address)
self.connected = True | python | {
"resource": ""
} |
q40801 | Socket.send | train | def send(self, data):
"""Send a formatted message to the ADB server"""
self._send_data(int_to_hex(len(data)))
self._send_data(data) | python | {
"resource": ""
} |
q40802 | Socket._send_data | train | def _send_data(self, data):
"""Send data to the ADB server"""
total_sent = 0
while total_sent < len(data):
# Send only the bytes that haven't been
# sent yet
sent = self.socket.send(data[total_sent:].encode("ascii"))
if sent == 0:
... | python | {
"resource": ""
} |
q40803 | Socket.receive_until_end | train | def receive_until_end(self, timeout=None):
"""
Reads and blocks until the socket closes
Used for the "shell" command, where STDOUT and STDERR
are just redirected to the terminal with no length
"""
if self.receive_fixed_length(4) != "OKAY":
raise SocketError("... | python | {
"resource": ""
} |
q40804 | defaults | train | def defaults(f, self, *args, **kwargs):
"""
For ``PARAMETERS`` keys, replace None ``kwargs`` with ``self`` attr values.
Should be applied on the top of any decorator stack so other decorators see
the "right" kwargs.
Will also apply transformations found in ``TRANSFORMS``.
"""
for name, dat... | python | {
"resource": ""
} |
q40805 | requires | train | def requires(*params):
"""
Raise ValueError if any ``params`` are omitted from the decorated kwargs.
None values are considered omissions.
Example usage on an AWS() method:
@requires('zone', 'security_groups')
def my_aws_method(self, custom_args, **kwargs):
# We'll only ge... | python | {
"resource": ""
} |
q40806 | AWS.get_security_group_id | train | def get_security_group_id(self, name):
"""
Take name string, give back security group ID.
To get around VPC's API being stupid.
"""
# Memoize entire list of groups
if not hasattr(self, '_security_groups'):
self._security_groups = {}
for group in s... | python | {
"resource": ""
} |
q40807 | AWS.get_instance_subnet_name | train | def get_instance_subnet_name(self, instance):
"""
Return a human readable name for given instance's subnet, or None.
Uses stored config mapping of subnet IDs to names.
"""
# TODO: we have to do this here since we are monkeypatching Instance.
# If we switch to custom Inst... | python | {
"resource": ""
} |
q40808 | AWS.get_subnet_id | train | def get_subnet_id(self, name):
"""
Return subnet ID for given ``name``, if it exists.
E.g. with a subnet mapping of ``{'abc123': 'ops', '67fd56': 'prod'}``,
``get_subnet_id('ops')`` would return ``'abc123'``. If the map has
non-unique values, the first matching key will be retur... | python | {
"resource": ""
} |
q40809 | AWS.create | train | def create(self, hostname, **kwargs):
"""
Create new EC2 instance named ``hostname``.
You may specify keyword arguments matching those of ``__init__`` (e.g.
``size``, ``ami``) to override any defaults given when the object was
created, or to fill in parameters not given at initi... | python | {
"resource": ""
} |
q40810 | AWS.get | train | def get(self, arg):
"""
Return instance object with given EC2 ID or nametag.
"""
try:
reservations = self.get_all_instances(filters={'tag:Name': [arg]})
instance = reservations[0].instances[0]
except IndexError:
try:
instance = ... | python | {
"resource": ""
} |
q40811 | AWS.get_volumes_for_instance | train | def get_volumes_for_instance(self, arg, device=None):
"""
Return all EC2 Volume objects attached to ``arg`` instance name or ID.
May specify ``device`` to limit to the (single) volume attached as that
device.
"""
instance = self.get(arg)
filters = {'attachment.in... | python | {
"resource": ""
} |
q40812 | AWS.terminate | train | def terminate(self, arg):
"""
Terminate instance with given EC2 ID or nametag.
"""
instance = self.get(arg)
with self.msg("Terminating %s (%s): " % (instance.name, instance.id)):
instance.rename("old-%s" % instance.name)
instance.terminate()
wh... | python | {
"resource": ""
} |
q40813 | ZNodeMap._set | train | def _set(self, data, version):
"""serialize and set data to self.path."""
self.zk.set(self.path, json.dumps(data), version) | python | {
"resource": ""
} |
q40814 | Jones.get_config | train | def get_config(self, hostname):
"""
Returns a configuration for hostname.
"""
version, config = self._get(
self.associations.get(hostname)
)
return config | python | {
"resource": ""
} |
q40815 | Jones.get_view_by_env | train | def get_view_by_env(self, env):
"""
Returns the view of `env`.
"""
version, data = self._get(self._get_view_path(env))
return data | python | {
"resource": ""
} |
q40816 | Jones.assoc_host | train | def assoc_host(self, hostname, env):
"""
Associate a host with an environment.
hostname is opaque to Jones.
Any string which uniquely identifies a host is acceptable.
"""
dest = self._get_view_path(env)
self.associations.set(hostname, dest) | python | {
"resource": ""
} |
q40817 | Jones.get_associations | train | def get_associations(self, env):
"""
Get all the associations for this env.
Root cannot have associations, so return None for root.
returns a map of hostnames to environments.
"""
if env.is_root:
return None
associations = self.associations.get_all... | python | {
"resource": ""
} |
q40818 | Jones._flatten_from_root | train | def _flatten_from_root(self, env):
"""
Flatten values from root down in to new view.
"""
nodes = env.components
# Path through the znode graph from root ('') to env
path = [nodes[:n] for n in xrange(len(nodes) + 1)]
# Expand path and map it to the root
... | python | {
"resource": ""
} |
q40819 | Serializer.encode | train | def encode(self, value):
"""Encode value."""
value = self.serialize(value)
if self.encoding:
value = value.encode(self.encoding)
return value | python | {
"resource": ""
} |
q40820 | Serializer.decode | train | def decode(self, value):
"""Decode value."""
if self.encoding:
value = value.decode(self.encoding)
return self.deserialize(value) | python | {
"resource": ""
} |
q40821 | install | train | def install(packagename, save, save_dev, save_test, filename):
"""
Install the package via pip, pin the package only to requirements file.
Use option to decide which file the package will be pinned to.
"""
print('Installing ', packagename)
print(sh_pip.install(packagename))
if not filename:
... | python | {
"resource": ""
} |
q40822 | remove | train | def remove(packagename, save, save_dev, save_test, filename):
"""
Uninstall the package and remove it from requirements file.
"""
print(sh_pip.uninstall(packagename, "-y"))
if not filename:
filename = get_filename(save, save_dev, save_test)
remove_requirements(packagename, filename) | python | {
"resource": ""
} |
q40823 | DKCloudCommandRunner.is_subdirectory | train | def is_subdirectory(potential_subdirectory, expected_parent_directory):
"""
Is the first argument a sub-directory of the second argument?
:param potential_subdirectory:
:param expected_parent_directory:
:return: True if the potential_subdirectory is a child of the expected paren... | python | {
"resource": ""
} |
q40824 | DKCloudCommandRunner._split_one_end | train | def _split_one_end(path):
"""
Utility function for splitting off the very end part of a path.
"""
s = path.rsplit('/', 1)
if len(s) == 1:
return s[0], ''
else:
return tuple(s) | python | {
"resource": ""
} |
q40825 | get_system_config_directory | train | def get_system_config_directory():
"""
Return platform specific config directory.
"""
if platform.system().lower() == 'windows':
_cfg_directory = Path(os.getenv('APPDATA') or '~')
elif platform.system().lower() == 'darwin':
_cfg_directory = Path('~', 'Library', 'Preferences')
... | python | {
"resource": ""
} |
q40826 | get_version_exec_mapping_from_path | train | def get_version_exec_mapping_from_path(path):
"""
Find valid application version from given path object and return
a mapping of version, executable.
"""
version_executable = {}
logger.debug('Getting exes from path: {}'.format(path))
for sub_dir in path.iterdir():
if not sub... | python | {
"resource": ""
} |
q40827 | find_applications_on_system | train | def find_applications_on_system():
"""
Collect maya version from Autodesk PATH if exists, else try looking
for custom executable paths from config file.
"""
# First we collect maya versions from the Autodesk folder we presume
# is addeed to the system environment "PATH"
path_env = os.... | python | {
"resource": ""
} |
q40828 | build_config | train | def build_config(config_file=get_system_config_directory()):
"""
Construct the config object from necessary elements.
"""
config = Config(config_file, allow_no_value=True)
application_versions = find_applications_on_system()
# Add found versions to config if they don't exist. Versions fo... | python | {
"resource": ""
} |
q40829 | get_environment_paths | train | def get_environment_paths(config, env):
"""
Get environment paths from given environment variable.
"""
if env is None:
return config.get(Config.DEFAULTS, 'environment')
# Config option takes precedence over environment key.
if config.has_option(Config.ENVIRONMENTS, env):
... | python | {
"resource": ""
} |
q40830 | build_maya_environment | train | def build_maya_environment(config, env=None, arg_paths=None):
"""
Construct maya environment.
"""
maya_env = MayaEnvironment()
maya_env.exclude_pattern = config.get_list(Config.PATTERNS, 'exclude')
maya_env.icon_extensions = config.get_list(Config.PATTERNS, 'icon_ext')
env = get_env... | python | {
"resource": ""
} |
q40831 | launch | train | def launch(exec_, args):
"""
Launches application.
"""
if not exec_:
raise RuntimeError(
'Mayalauncher could not find a maya executable, please specify'
'a path in the config file (-e) or add the {} directory location'
'to your PATH system environment.... | python | {
"resource": ""
} |
q40832 | Config._create_default_config_file | train | def _create_default_config_file(self):
"""
If config file does not exists create and set default values.
"""
logger.info('Initialize Maya launcher, creating config file...\n')
self.add_section(self.DEFAULTS)
self.add_section(self.PATTERNS)
self.add_section(... | python | {
"resource": ""
} |
q40833 | Config.get_list | train | def get_list(self, section, option):
"""
Convert string value to list object.
"""
if self.has_option(section, option):
return self.get(section, option).replace(' ', '').split(',')
else:
raise KeyError('{} with {} does not exist.'.format(section,
... | python | {
"resource": ""
} |
q40834 | Config.edit | train | def edit(self):
"""
Edit file with default os application.
"""
if platform.system().lower() == 'windows':
os.startfile(str(self.config_file))
else:
if platform.system().lower() == 'darwin':
call = 'open'
else:
... | python | {
"resource": ""
} |
q40835 | MayaEnvironment.is_excluded | train | def is_excluded(self, path, exclude=None):
"""
Return if path is in exclude pattern.
"""
for pattern in (exclude or self.exclude_pattern):
if path.match(pattern):
return True
else:
return False | python | {
"resource": ""
} |
q40836 | MayaEnvironment.put_path | train | def put_path(self, path):
"""
Given path identify in which environment the path belong to and
append it.
"""
if self.is_package(path):
logger.debug('PYTHON PACKAGE: {}'.format(path))
self.python_paths.append(path.parent)
site.addsitedir... | python | {
"resource": ""
} |
q40837 | MayaEnvironment.traverse_path_for_valid_application_paths | train | def traverse_path_for_valid_application_paths(self, top_path):
"""
For every path beneath top path that does not contain the exclude
pattern look for python, mel and images and place them in their
corresponding system environments.
"""
self.put_path(Path(top_path))
... | python | {
"resource": ""
} |
q40838 | ApiClient.get_dataset | train | def get_dataset(self, datasetid):
"""The method is getting information about dataset byt it's id"""
path = '/api/1.0/meta/dataset/{}'
return self._api_get(definition.Dataset, path.format(datasetid)) | python | {
"resource": ""
} |
q40839 | ApiClient.get_dimension | train | def get_dimension(self, dataset, dimension):
"""The method is getting information about dimension with items"""
path = '/api/1.0/meta/dataset/{}/dimension/{}'
return self._api_get(definition.Dimension, path.format(dataset, dimension)) | python | {
"resource": ""
} |
q40840 | ApiClient.get_daterange | train | def get_daterange(self, dataset):
"""The method is getting information about date range of dataset"""
path = '/api/1.0/meta/dataset/{}/daterange'
return self._api_get(definition.DateRange, path.format(dataset)) | python | {
"resource": ""
} |
q40841 | ApiClient.get_data | train | def get_data(self, pivotrequest):
"""The method is getting data by pivot request"""
path = '/api/1.0/data/pivot/'
return self._api_post(definition.PivotResponse, path, pivotrequest) | python | {
"resource": ""
} |
q40842 | ApiClient.get_data_raw | train | def get_data_raw(self, request):
"""The method is getting data by raw request"""
path = '/api/1.0/data/raw/'
res = self._api_post(definition.RawDataResponse, path, request)
token = res.continuation_token
while token is not None:
res2 = self.get_data_raw_with_toke... | python | {
"resource": ""
} |
q40843 | ApiClient.get_mnemonics | train | def get_mnemonics (self, mnemonics):
"""The method get series by mnemonics"""
path = '/api/1.0/data/mnemonics?mnemonics={0}'
return self._api_get(definition.MnemonicsResponseList, path.format(mnemonics)) | python | {
"resource": ""
} |
q40844 | ApiClient.upload_file | train | def upload_file(self, file):
"""The method is posting file to the remote server"""
url = self._get_url('/api/1.0/upload/post')
fcontent = FileContent(file)
binary_data = fcontent.get_binary()
headers = self._get_request_headers()
req = urllib.request.Request(u... | python | {
"resource": ""
} |
q40845 | ApiClient.upload_verify | train | def upload_verify(self, file_location, dataset=None):
"""This method is verifiing posted file on server"""
path = '/api/1.0/upload/verify'
query = 'doNotGenerateAdvanceReport=true&filePath={}'.format(file_location)
if dataset:
query = 'doNotGenerateAdvanceReport=true&f... | python | {
"resource": ""
} |
q40846 | ApiClient.upload_submit | train | def upload_submit(self, upload_request):
"""The method is submitting dataset upload"""
path = '/api/1.0/upload/save'
return self._api_post(definition.DatasetUploadResponse, path, upload_request) | python | {
"resource": ""
} |
q40847 | ApiClient.upload_status | train | def upload_status(self, upload_id):
"""The method is checking status of uploaded dataset"""
path = '/api/1.0/upload/status'
query = 'id={}'.format(upload_id)
return self._api_get(definition.DatasetUploadStatusResponse, path, query) | python | {
"resource": ""
} |
q40848 | ApiClient.delete | train | def delete(self, dataset):
"""The method is deleting dataset by it's id"""
url = self._get_url('/api/1.0/meta/dataset/{}/delete'.format(dataset))
json_data = ''
binary_data = json_data.encode()
headers = self._get_request_headers()
req = urllib.request.Request... | python | {
"resource": ""
} |
q40849 | ApiClient.verify | train | def verify(self, dataset, publication_date, source, refernce_url):
"""The method is verifying dataset by it's id"""
path = '/api/1.0/meta/verifydataset'
req = definition.DatasetVerifyRequest(dataset, publication_date, source, refernce_url)
result = self._api_post(definition.Dataset... | python | {
"resource": ""
} |
q40850 | FileContent.get_binary | train | def get_binary(self):
"""Return a binary buffer containing the file content"""
content_disp = 'Content-Disposition: form-data; name="file"; filename="{}"'
stream = io.BytesIO()
stream.write(_string_to_binary('--{}'.format(self.boundary)))
stream.write(_crlf())
s... | python | {
"resource": ""
} |
q40851 | QueryCache._scratch_stream_name | train | def _scratch_stream_name(self):
"""
A unique cache stream name for this QueryCache.
Hashes the necessary facts about this QueryCache to generate a
unique cache stream name. Different `query_function`
implementations at different `bucket_width` values will be cached
to different streams.
T... | python | {
"resource": ""
} |
q40852 | QueryCache._bucket_time | train | def _bucket_time(self, event_time):
"""
The seconds since epoch that represent a computed bucket.
An event bucket is the time of the earliest possible event for
that `bucket_width`. Example: if `bucket_width =
timedelta(minutes=10)`, bucket times will be the number of seconds
since epoch at 12... | python | {
"resource": ""
} |
q40853 | QueryCache._bucket_events | train | def _bucket_events(self, event_iterable):
"""
Convert an iterable of events into an iterable of lists of events
per bucket.
"""
current_bucket_time = None
current_bucket_events = None
for event in event_iterable:
event_bucket_time = self._bucket_time(event[TIMESTAMP_FIELD])
if c... | python | {
"resource": ""
} |
q40854 | QueryCache._cached_results | train | def _cached_results(self, start_time, end_time):
"""
Retrieves cached results for any bucket that has a single cache entry.
If a bucket has two cache entries, there is a chance that two
different writers previously computed and cached a result since
Kronos has no transaction semantics. While it mi... | python | {
"resource": ""
} |
q40855 | QueryCache.compute_and_cache_missing_buckets | train | def compute_and_cache_missing_buckets(self, start_time, end_time,
untrusted_time, force_recompute=False):
"""
Return the results for `query_function` on every `bucket_width`
time period between `start_time` and `end_time`. Look for
previously cached results to av... | python | {
"resource": ""
} |
q40856 | QueryCache.retrieve_interval | train | def retrieve_interval(self, start_time, end_time, compute_missing=False):
"""
Return the results for `query_function` on every `bucket_width`
time period between `start_time` and `end_time`. Look for
previously cached results to avoid recomputation.
:param start_time: A datetime for the beginning ... | python | {
"resource": ""
} |
q40857 | Scheduler._loop | train | def _loop(self, reader):
"""Main execution loop of the scheduler.
The loop runs every second. Between iterations, the loop listens for
schedule or cancel requests coming from Flask via over the gipc pipe
(reader) and modifies the queue accordingly.
When a task completes, it is rescheduled
"""
... | python | {
"resource": ""
} |
q40858 | token_protected_endpoint | train | def token_protected_endpoint(function):
"""Requires valid auth_token in POST to access
An auth_token is built by sending a dictionary built from a
Werkzeug.Request.form to the scheduler.auth.create_token function.
"""
@wraps(function)
def decorated(*args, **kwargs):
auth_token = request.form.get('auth_... | python | {
"resource": ""
} |
q40859 | molmz | train | def molmz(df, noise=10000):
"""
The mz of the molecular ion.
"""
d = ((df.values > noise) * df.columns).max(axis=1)
return Trace(d, df.index, name='molmz') | python | {
"resource": ""
} |
q40860 | mzminus | train | def mzminus(df, minus=0, noise=10000):
"""
The abundances of ions which are minus below the molecular ion.
"""
mol_ions = ((df.values > noise) * df.columns).max(axis=1) - minus
mol_ions[np.abs(mol_ions) < 0] = 0
d = np.abs(np.ones(df.shape) * df.columns -
(mol_ions[np.newaxis].T *... | python | {
"resource": ""
} |
q40861 | basemz | train | def basemz(df):
"""
The mz of the most abundant ion.
"""
# returns the
d = np.array(df.columns)[df.values.argmax(axis=1)]
return Trace(d, df.index, name='basemz') | python | {
"resource": ""
} |
q40862 | coda | train | def coda(df, window, level):
"""
CODA processing from Windig, Phalp, & Payne 1996 Anal Chem
"""
# pull out the data
d = df.values
# smooth the data and standardize it
smooth_data = movingaverage(d, df.index, window)[0]
stand_data = (smooth_data - smooth_data.mean()) / smooth_data.std()
... | python | {
"resource": ""
} |
q40863 | tfclasses | train | def tfclasses():
"""
A mapping of mimetypes to every class for reading data files.
"""
# automatically find any subclasses of TraceFile in the same
# directory as me
classes = {}
mydir = op.dirname(op.abspath(inspect.getfile(get_mimetype)))
tfcls = {"<class 'aston.tracefile.TraceFile'>",... | python | {
"resource": ""
} |
q40864 | fit | train | def fit(ts, fs=[], all_params=[], fit_vars=None,
alg='leastsq', make_bounded=True):
"""
Use a minimization algorithm to fit a AstonSeries with
analytical functions.
"""
if fit_vars is None:
fit_vars = [f._peakargs for f in fs]
initc = [min(ts.values)]
for f, peak_params, to_f... | python | {
"resource": ""
} |
q40865 | execute_process_async | train | def execute_process_async(func, *args, **kwargs):
"""
Executes `func` in a separate process. Memory and other resources are not
available. This gives true concurrency at the cost of losing access to
these resources. `args` and `kwargs` are
"""
global _GIPC_EXECUTOR
if _GIPC_EXECUTOR is None:
_GIPC_EXE... | python | {
"resource": ""
} |
q40866 | HelpScoutWebHook.receive | train | def receive(self, event_type, signature, data_str):
"""Receive a web hook for the event and signature.
Args:
event_type (str): Name of the event that was received (from the
request ``X-HelpScout-Event`` header).
signature (str): The signature that was received, w... | python | {
"resource": ""
} |
q40867 | HelpScoutWebHook.validate_signature | train | def validate_signature(self, signature, data, encoding='utf8'):
"""Validate the signature for the provided data.
Args:
signature (str or bytes or bytearray): Signature that was provided
for the request.
data (str or bytes or bytearray): Data string to validate ag... | python | {
"resource": ""
} |
q40868 | train_doc2vec | train | def train_doc2vec(paths, out='data/model.d2v', tokenizer=word_tokenize, sentences=False, **kwargs):
"""
Train a doc2vec model on a list of files.
"""
kwargs = {
'size': 400,
'window': 8,
'min_count': 2,
'workers': 8
}.update(kwargs)
n = 0
for path in paths:
... | python | {
"resource": ""
} |
q40869 | _doc2vec_doc_stream | train | def _doc2vec_doc_stream(paths, n, tokenizer=word_tokenize, sentences=True):
"""
Generator to feed sentences to the dov2vec model.
"""
i = 0
p = Progress()
for path in paths:
with open(path, 'r') as f:
for line in f:
i += 1
p.print_progress(i/n)... | python | {
"resource": ""
} |
q40870 | LaCrosse.get_info | train | def get_info(self):
"""Get current configuration info from 'v' command."""
re_info = re.compile(r'\[.*\]')
self._write_cmd('v')
while True:
line = self._serial.readline()
try:
line = line.encode().decode('utf-8')
except AttributeError:... | python | {
"resource": ""
} |
q40871 | LaCrosse.set_frequency | train | def set_frequency(self, frequency, rfm=1):
"""Set frequency in kHz.
The frequency can be set in 5kHz steps.
"""
cmds = {1: 'f', 2: 'F'}
self._write_cmd('{}{}'.format(frequency, cmds[rfm])) | python | {
"resource": ""
} |
q40872 | LaCrosse.set_toggle_interval | train | def set_toggle_interval(self, interval, rfm=1):
"""Set the toggle interval."""
cmds = {1: 't', 2: 'T'}
self._write_cmd('{}{}'.format(interval, cmds[rfm])) | python | {
"resource": ""
} |
q40873 | LaCrosse.set_toggle_mask | train | def set_toggle_mask(self, mode_mask, rfm=1):
"""Set toggle baudrate mask.
The baudrate mask values are:
1: 17.241 kbps
2 : 9.579 kbps
4 : 8.842 kbps
These values can be or'ed.
"""
cmds = {1: 'm', 2: 'M'}
self._write_cmd('{}{}'.format(mode_ma... | python | {
"resource": ""
} |
q40874 | LaCrosse._refresh | train | def _refresh(self):
"""Background refreshing thread."""
while not self._stopevent.isSet():
line = self._serial.readline()
#this is for python2/python3 compatibility. Is there a better way?
try:
line = line.encode().decode('utf-8')
except A... | python | {
"resource": ""
} |
q40875 | LaCrosse.register_callback | train | def register_callback(self, sensorid, callback, user_data=None):
"""Register a callback for the specified sensor id."""
if sensorid not in self._registry:
self._registry[sensorid] = list()
self._registry[sensorid].append((callback, user_data)) | python | {
"resource": ""
} |
q40876 | LaCrosse.register_all | train | def register_all(self, callback, user_data=None):
"""Register a callback for all sensors."""
self._callback = callback
self._callback_data = user_data | python | {
"resource": ""
} |
q40877 | Transfer._initialize | train | def _initialize(self):
"""Initialize transfer."""
payload = {
'apikey': self.session.cookies.get('apikey'),
'source': self.session.cookies.get('source')
}
if self.fm_user.logged_in:
payload['logintoken'] = self.session.cookies.get('logintoken')
... | python | {
"resource": ""
} |
q40878 | Transfer._parse_recipients | train | def _parse_recipients(self, to):
"""Make sure we have a "," separated list of recipients
:param to: Recipient(s)
:type to: (str,
list,
:class:`pyfilemail.Contact`,
:class:`pyfilemail.Group`
)
:rtype: ``str``
... | python | {
"resource": ""
} |
q40879 | Transfer.get_file_specs | train | def get_file_specs(self, filepath, keep_folders=False):
"""Gather information on files needed for valid transfer.
:param filepath: Path to file in question
:param keep_folders: Whether or not to maintain folder structure
:type keep_folders: bool
:type filepath: str, unicode
... | python | {
"resource": ""
} |
q40880 | Transfer.get_files | train | def get_files(self):
"""Get information on file in transfer from Filemail.
:rtype: ``list`` of ``dict`` objects with info on files
"""
method, url = get_URL('get')
payload = {
'apikey': self.session.cookies.get('apikey'),
'logintoken': self.session.cooki... | python | {
"resource": ""
} |
q40881 | Transfer.share | train | def share(self, to, sender=None, message=None):
"""Share transfer with new message to new people.
:param to: receiver(s)
:param sender: Alternate email address as sender
:param message: Meggase to new recipients
:type to: ``list`` or ``str`` or ``unicode``
:type sender: ... | python | {
"resource": ""
} |
q40882 | Transfer.cancel | train | def cancel(self):
"""Cancel the current transfer.
:rtype: ``bool``
"""
method, url = get_URL('cancel')
payload = {
'apikey': self.config.get('apikey'),
'transferid': self.transfer_id,
'transferkey': self.transfer_info.get('transferkey')
... | python | {
"resource": ""
} |
q40883 | Transfer.rename_file | train | def rename_file(self, fmfile, newname):
"""Rename file in transfer.
:param fmfile: file data from filemail containing fileid
:param newname: new file name
:type fmfile: ``dict``
:type newname: ``str`` or ``unicode``
:rtype: ``bool``
"""
if not isinstance... | python | {
"resource": ""
} |
q40884 | Transfer.delete_file | train | def delete_file(self, fmfile):
"""Delete file from transfer.
:param fmfile: file data from filemail containing fileid
:type fmfile: ``dict``
:rtype: ``bool``
"""
if not isinstance(fmfile, dict):
raise FMFileError('fmfile must be a <dict>')
method, u... | python | {
"resource": ""
} |
q40885 | Transfer.update | train | def update(self,
message=None,
subject=None,
days=None,
downloads=None,
notify=None):
"""Update properties for a transfer.
:param message: updated message to recipient(s)
:param subject: updated subject for trasfer
... | python | {
"resource": ""
} |
q40886 | Transfer.download | train | def download(self,
files=None,
destination=None,
overwrite=False,
callback=None):
"""Download file or files.
:param files: file or files to download
:param destination: destination path (defaults to users home directory)
... | python | {
"resource": ""
} |
q40887 | Transfer._download | train | def _download(self, fmfile, destination, overwrite, callback):
"""The actual downloader streaming content from Filemail.
:param fmfile: to download
:param destination: destination path
:param overwrite: replace existing files?
:param callback: callback function that will receive... | python | {
"resource": ""
} |
q40888 | Transfer.compress | train | def compress(self):
"""Compress files on the server side after transfer complete
and make zip available for download.
:rtype: ``bool``
"""
method, url = get_URL('compress')
payload = {
'apikey': self.config.get('apikey'),
'logintoken': self.ses... | python | {
"resource": ""
} |
q40889 | ToSentence.from_pin | train | def from_pin(self, pin, timeout=5):
"""
Generate a sentence from PIN
:param str pin: a string of digits
:param float timeout: total time in seconds
:return dict: {
'sentence': sentence corresponding to the PIN,
'overlap': overlapping positions, starting f... | python | {
"resource": ""
} |
q40890 | ToSentence.from_keywords | train | def from_keywords(self, keyword_list, strictness=2, timeout=3):
"""
Generate a sentence from initial_list.
:param list keyword_list: a list of keywords to be included in the sentence.
:param int | None strictness: None for highest strictness. 2 or 1 for a less strict POS matching
... | python | {
"resource": ""
} |
q40891 | _define_helper | train | def _define_helper(flag_name, default_value, docstring, flagtype, required):
"""Registers 'flag_name' with 'default_value' and 'docstring'."""
option_name = flag_name if required else "--%s" % flag_name
get_context_parser().add_argument(
option_name, default=default_value, help=docstring, type=flagt... | python | {
"resource": ""
} |
q40892 | NamedParser._get_subparsers | train | def _get_subparsers(self, dest):
"""Get named subparsers."""
if not self._subparsers:
self._subparsers = self.parser.add_subparsers(dest=dest)
elif self._subparsers.dest != dest:
raise KeyError(
"Subparser names mismatch. You can only create one subcommand... | python | {
"resource": ""
} |
q40893 | NamedParser.get_subparser | train | def get_subparser(self, name, dest="subcommand", **kwargs):
"""Get or create subparser."""
if name not in self.children:
# Create the subparser.
subparsers = self._get_subparsers(dest)
parser = subparsers.add_parser(name, **kwargs)
self.children[name] = Na... | python | {
"resource": ""
} |
q40894 | build_attr_string | train | def build_attr_string(attrs, supported=True):
'''Build a string that will turn any ANSI shell output the desired
colour.
attrs should be a list of keys into the term_attributes table.
'''
if not supported:
return ''
if type(attrs) == str:
attrs = [attrs]
result =... | python | {
"resource": ""
} |
q40895 | get_terminal_size | train | def get_terminal_size():
'''Finds the width of the terminal, or returns a suitable default value.'''
def read_terminal_size_by_ioctl(fd):
try:
import struct, fcntl, termios
cr = struct.unpack('hh', fcntl.ioctl(1, termios.TIOCGWINSZ,
... | python | {
"resource": ""
} |
q40896 | dict_to_nvlist | train | def dict_to_nvlist(dict):
'''Convert a dictionary into a CORBA namevalue list.'''
result = []
for item in list(dict.keys()):
result.append(SDOPackage.NameValue(item, omniORB.any.to_any(dict[item])))
return result | python | {
"resource": ""
} |
q40897 | nvlist_to_dict | train | def nvlist_to_dict(nvlist):
'''Convert a CORBA namevalue list into a dictionary.'''
result = {}
for item in nvlist :
result[item.name] = item.value.value()
return result | python | {
"resource": ""
} |
q40898 | filtered | train | def filtered(path, filter):
'''Check if a path is removed by a filter.
Check if a path is in the provided set of paths, @ref filter. If
none of the paths in filter begin with @ref path, then True is
returned to indicate that the path is filtered out. If @ref path is
longer than the filter, an... | python | {
"resource": ""
} |
q40899 | Bugsy.get | train | def get(self, bug_number):
"""
Get a bug from Bugzilla. If there is a login token created during
object initialisation it will be part of the query string passed to
Bugzilla
:param bug_number: Bug Number that will be searched. If found will
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.