_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q42700 | Alignment.get_id | train | def get_id(self):
"""Returns unique id of an alignment. """
return hash(str(self.title) + str(self.best_score()) + str(self.hit_def)) | python | {
"resource": ""
} |
q42701 | render_template | train | def render_template(template, **context):
"""Renders a given template and context.
:param template: The template name
:param context: the variables that should be available in the
context of the template.
"""
parts = template.split('/')
renderer = _get_renderer(parts[:-1])
... | python | {
"resource": ""
} |
q42702 | open | train | def open(pattern, read_only=False):
"""
Return a root descriptor to work with one or multiple NetCDF files.
Keyword arguments:
pattern -- a list of filenames or a string pattern.
"""
root = NCObject.open(pattern, read_only=read_only)
return root, root.is_new | python | {
"resource": ""
} |
q42703 | getvar | train | def getvar(root, name, vtype='', dimensions=(), digits=0, fill_value=None,
source=None):
"""
Return a variable from a NCFile or NCPackage instance. If the variable
doesn't exists create it.
Keyword arguments:
root -- the root descriptor returned by the 'open' function
name -- the nam... | python | {
"resource": ""
} |
q42704 | loader | train | def loader(pattern, dimensions=None, distributed_dim='time', read_only=False):
"""
It provide a root descriptor to be used inside a with statement. It
automatically close the root when the with statement finish.
Keyword arguments:
root -- the root descriptor returned by the 'open' function
"""
... | python | {
"resource": ""
} |
q42705 | dict_copy | train | def dict_copy(func):
"copy dict args, to avoid modifying caller's copy"
def proxy(*args, **kwargs):
new_args = []
new_kwargs = {}
for var in kwargs:
if isinstance(kwargs[var], dict):
new_kwargs[var] = dict(kwargs[var])
else:
new_kwa... | python | {
"resource": ""
} |
q42706 | is_listish | train | def is_listish(obj):
"""Check if something quacks like a list."""
if isinstance(obj, (list, tuple, set)):
return True
return is_sequence(obj) | python | {
"resource": ""
} |
q42707 | unique_list | train | def unique_list(lst):
"""Make a list unique, retaining order of initial appearance."""
uniq = []
for item in lst:
if item not in uniq:
uniq.append(item)
return uniq | python | {
"resource": ""
} |
q42708 | check_compatibility | train | def check_compatibility(datasets, reqd_num_features=None):
"""
Checks whether the given MLdataset instances are compatible
i.e. with same set of subjects, each beloning to the same class in all instances.
Checks the first dataset in the list against the rest, and returns a boolean array.
Paramete... | python | {
"resource": ""
} |
q42709 | print_info | train | def print_info(ds, ds_path=None):
"Prints basic summary of a given dataset."
if ds_path is None:
bname = ''
else:
bname = basename(ds_path)
dashes = '-' * len(bname)
print('\n{}\n{}\n{:full}'.format(dashes, bname, ds))
return | python | {
"resource": ""
} |
q42710 | print_meta | train | def print_meta(ds, ds_path=None):
"Prints meta data for subjects in given dataset."
print('\n#' + ds_path)
for sub, cls in ds.classes.items():
print('{},{}'.format(sub, cls))
return | python | {
"resource": ""
} |
q42711 | combine_and_save | train | def combine_and_save(add_path_list, out_path):
"""
Combines whatever datasets that can be combined,
and save the bigger dataset to a given location.
"""
add_path_list = list(add_path_list)
# first one!
first_ds_path = add_path_list[0]
print('Starting with {}'.format(first_ds_path))
... | python | {
"resource": ""
} |
q42712 | get_parser | train | def get_parser():
"""Argument specifier.
"""
parser = argparse.ArgumentParser(prog='pyradigm')
parser.add_argument('path_list', nargs='*', action='store',
default=None, help='List of paths to display info about.')
parser.add_argument('-m', '--meta', action='store_true', d... | python | {
"resource": ""
} |
q42713 | parse_args | train | def parse_args():
"""Arg parser.
"""
parser = get_parser()
if len(sys.argv) < 2:
parser.print_help()
logging.warning('Too few arguments!')
parser.exit(1)
# parsing
try:
params = parser.parse_args()
except Exception as exc:
print(exc)
raise ... | python | {
"resource": ""
} |
q42714 | MLDataset.data_and_labels | train | def data_and_labels(self):
"""
Dataset features and labels in a matrix form for learning.
Also returns sample_ids in the same order.
Returns
-------
data_matrix : ndarray
2D array of shape [num_samples, num_features]
with features corresponding r... | python | {
"resource": ""
} |
q42715 | MLDataset.classes | train | def classes(self, values):
"""Classes setter."""
if isinstance(values, dict):
if self.__data is not None and len(self.__data) != len(values):
raise ValueError(
'number of samples do not match the previously assigned data')
elif set(self.keys) !... | python | {
"resource": ""
} |
q42716 | MLDataset.feature_names | train | def feature_names(self, names):
"Stores the text labels for features"
if len(names) != self.num_features:
raise ValueError("Number of names do not match the number of features!")
if not isinstance(names, (Sequence, np.ndarray, np.generic)):
raise ValueError("Input is not... | python | {
"resource": ""
} |
q42717 | MLDataset.glance | train | def glance(self, nitems=5):
"""Quick and partial glance of the data matrix.
Parameters
----------
nitems : int
Number of items to glance from the dataset.
Default : 5
Returns
-------
dict
"""
nitems = max([1, min([nitems,... | python | {
"resource": ""
} |
q42718 | MLDataset.check_features | train | def check_features(self, features):
"""
Method to ensure data to be added is not empty and vectorized.
Parameters
----------
features : iterable
Any data that can be converted to a numpy array.
Returns
-------
features : numpy array
... | python | {
"resource": ""
} |
q42719 | MLDataset.add_sample | train | def add_sample(self, sample_id, features, label,
class_id=None,
overwrite=False,
feature_names=None):
"""Adds a new sample to the dataset with its features, label and class ID.
This is the preferred way to construct the dataset.
Paramete... | python | {
"resource": ""
} |
q42720 | MLDataset.del_sample | train | def del_sample(self, sample_id):
"""
Method to remove a sample from the dataset.
Parameters
----------
sample_id : str
sample id to be removed.
Raises
------
UserWarning
If sample id to delete was not found in the dataset.
... | python | {
"resource": ""
} |
q42721 | MLDataset.get_feature_subset | train | def get_feature_subset(self, subset_idx):
"""
Returns the subset of features indexed numerically.
Parameters
----------
subset_idx : list, ndarray
List of indices to features to be returned
Returns
-------
MLDataset : MLDataset
wi... | python | {
"resource": ""
} |
q42722 | MLDataset.keys_with_value | train | def keys_with_value(dictionary, value):
"Returns a subset of keys from the dict with the value supplied."
subset = [key for key in dictionary if dictionary[key] == value]
return subset | python | {
"resource": ""
} |
q42723 | MLDataset.get_class | train | def get_class(self, class_id):
"""
Returns a smaller dataset belonging to the requested classes.
Parameters
----------
class_id : str or list
identifier(s) of the class(es) to be returned.
Returns
-------
MLDataset
With subset of ... | python | {
"resource": ""
} |
q42724 | MLDataset.transform | train | def transform(self, func, func_description=None):
"""
Applies a given a function to the features of each subject
and returns a new dataset with other info unchanged.
Parameters
----------
func : callable
A valid callable that takes in a single ndarray and... | python | {
"resource": ""
} |
q42725 | MLDataset.random_subset_ids_by_count | train | def random_subset_ids_by_count(self, count_per_class=1):
"""
Returns a random subset of sample ids of specified size by count,
within each class.
Parameters
----------
count_per_class : int
Exact number of samples per each class.
Returns
... | python | {
"resource": ""
} |
q42726 | MLDataset.sample_ids_in_class | train | def sample_ids_in_class(self, class_id):
"""
Returns a list of sample ids belonging to a given class.
Parameters
----------
class_id : str
class id to query.
Returns
-------
subset_ids : list
List of sample ids belonging to a give... | python | {
"resource": ""
} |
q42727 | MLDataset.get_data_matrix_in_order | train | def get_data_matrix_in_order(self, subset_ids):
"""
Returns a numpy array of features, rows in the same order as subset_ids
Parameters
----------
subset_ids : list
List od sample IDs to extracted from the dataset.
Returns
-------
matrix : nda... | python | {
"resource": ""
} |
q42728 | MLDataset.label_set | train | def label_set(self):
"""Set of labels in the dataset corresponding to class_set."""
label_set = list()
for class_ in self.class_set:
samples_in_class = self.sample_ids_in_class(class_)
label_set.append(self.labels[samples_in_class[0]])
return label_set | python | {
"resource": ""
} |
q42729 | MLDataset.add_classes | train | def add_classes(self, classes):
"""
Helper to rename the classes, if provided by a dict keyed in by the orignal keys
Parameters
----------
classes : dict
Dict of class named keyed in by sample IDs.
Raises
------
TypeError
If class... | python | {
"resource": ""
} |
q42730 | MLDataset.__load | train | def __load(self, path):
"""Method to load the serialized dataset from disk."""
try:
path = os.path.abspath(path)
with open(path, 'rb') as df:
# loaded_dataset = pickle.load(df)
self.__data, self.__classes, self.__labels, \
self.__dt... | python | {
"resource": ""
} |
q42731 | MLDataset.__load_arff | train | def __load_arff(self, arff_path, encode_nonnumeric=False):
"""Loads a given dataset saved in Weka's ARFF format. """
try:
from scipy.io.arff import loadarff
arff_data, arff_meta = loadarff(arff_path)
except:
raise ValueError('Error loading the ARFF dataset!')
... | python | {
"resource": ""
} |
q42732 | MLDataset.save | train | def save(self, file_path):
"""
Method to save the dataset to disk.
Parameters
----------
file_path : str
File path to save the current dataset to
Raises
------
IOError
If saving to disk is not successful.
"""
# T... | python | {
"resource": ""
} |
q42733 | MLDataset.__validate | train | def __validate(data, classes, labels):
"Validator of inputs."
if not isinstance(data, dict):
raise TypeError(
'data must be a dict! keys: sample ID or any unique identifier')
if not isinstance(labels, dict):
raise TypeError(
'labels must b... | python | {
"resource": ""
} |
q42734 | get_meta | train | def get_meta(meta, name):
"""Retrieves the metadata variable 'name' from the 'meta' dict."""
assert name in meta
data = meta[name]
if data['t'] in ['MetaString', 'MetaBool']:
return data['c']
elif data['t'] == 'MetaInlines':
# Handle bug in pandoc 2.2.3 and 2.2.3.1: Return boolean v... | python | {
"resource": ""
} |
q42735 | _getel | train | def _getel(key, value):
"""Returns an element given a key and value."""
if key in ['HorizontalRule', 'Null']:
return elt(key, 0)()
elif key in ['Plain', 'Para', 'BlockQuote', 'BulletList',
'DefinitionList', 'HorizontalRule', 'Null']:
return elt(key, 1)(value)
return elt(... | python | {
"resource": ""
} |
q42736 | quotify | train | def quotify(x):
"""Replaces Quoted elements in element list 'x' with quoted strings.
Pandoc uses the Quoted element in its json when --smart is enabled.
Output to TeX/pdf automatically triggers --smart.
stringify() ignores Quoted elements. Use quotify() first to replace
Quoted elements in 'x' wit... | python | {
"resource": ""
} |
q42737 | extract_attrs | train | def extract_attrs(x, n):
"""Extracts attributes from element list 'x' beginning at index 'n'.
The elements encapsulating the attributes (typically a series of Str and
Space elements) are removed from 'x'. Items before index 'n' are left
unchanged.
Returns the attributes in pandoc format. A Value... | python | {
"resource": ""
} |
q42738 | _join_strings | train | def _join_strings(x):
"""Joins adjacent Str elements found in the element list 'x'."""
for i in range(len(x)-1): # Process successive pairs of elements
if x[i]['t'] == 'Str' and x[i+1]['t'] == 'Str':
x[i]['c'] += x[i+1]['c']
del x[i+1] # In-place deletion of element from list
... | python | {
"resource": ""
} |
q42739 | join_strings | train | def join_strings(key, value, fmt, meta): # pylint: disable=unused-argument
"""Joins adjacent Str elements in the 'value' list."""
if key in ['Para', 'Plain']:
_join_strings(value)
elif key == 'Image':
_join_strings(value[-2])
elif key == 'Table':
_join_strings(value[-5]) | python | {
"resource": ""
} |
q42740 | _is_broken_ref | train | def _is_broken_ref(key1, value1, key2, value2):
"""True if this is a broken reference; False otherwise."""
# A link followed by a string may represent a broken reference
if key1 != 'Link' or key2 != 'Str':
return False
# Assemble the parts
n = 0 if _PANDOCVERSION < '1.16' else 1
if isin... | python | {
"resource": ""
} |
q42741 | _repair_refs | train | def _repair_refs(x):
"""Performs the repair on the element list 'x'."""
if _PANDOCVERSION is None:
raise RuntimeError('Module uninitialized. Please call init().')
# Scan the element list x
for i in range(len(x)-1):
# Check for broken references
if _is_broken_ref(x[i]['t'], x[... | python | {
"resource": ""
} |
q42742 | _remove_brackets | train | def _remove_brackets(x, i):
"""Removes curly brackets surrounding the Cite element at index 'i' in
the element list 'x'. It is assumed that the modifier has been
extracted. Empty strings are deleted from 'x'."""
assert x[i]['t'] == 'Cite'
assert i > 0 and i < len(x) - 1
# Check if the surrou... | python | {
"resource": ""
} |
q42743 | Movies.search | train | def search(self, **kwargs):
"""Get movies that match the search query string from the API.
Args:
q (optional): plain text search query; remember to URI encode
page_limit (optional): number of search results to show per page,
default=30
pag... | python | {
"resource": ""
} |
q42744 | Movies.cast | train | def cast(self, **kwargs):
"""Get the cast for a movie specified by id from the API.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_id_path('cast')
response = self._GET(path, kwargs)
self._set_attrs_to_values(response)
... | python | {
"resource": ""
} |
q42745 | Movies.clips | train | def clips(self, **kwargs):
"""Get related clips and trailers for a movie specified by id
from the API.
Returns:
A dict respresentation of the JSON returned from the API.
"""
path = self._get_id_path('clips')
response = self._GET(path, kwargs)
self.... | python | {
"resource": ""
} |
q42746 | debug | train | def debug(value):
"""
Simple tag to debug output a variable;
Usage:
{% debug request %}
"""
print("%s %s: " % (type(value), value))
print(dir(value))
print('\n\n')
return '' | python | {
"resource": ""
} |
q42747 | get_sample_data | train | def get_sample_data(sample_file):
"""Read and returns sample data to fill form with default sample sequence. """
sequence_sample_in_fasta = None
with open(sample_file) as handle:
sequence_sample_in_fasta = handle.read()
return sequence_sample_in_fasta | python | {
"resource": ""
} |
q42748 | blast_records_to_object | train | def blast_records_to_object(blast_records):
"""Transforms biopython's blast record into blast object defined in django-blastplus app. """
# container for transformed objects
blast_objects_list = []
for blast_record in blast_records:
br = BlastRecord(**{'query': blast_record.query,
... | python | {
"resource": ""
} |
q42749 | get_annotation | train | def get_annotation(db_path, db_list):
""" Checks if database is set as annotated. """
annotated = False
for db in db_list:
if db["path"] == db_path:
annotated = db["annotated"]
break
return annotated | python | {
"resource": ""
} |
q42750 | find_usbserial | train | def find_usbserial(vendor, product):
"""Find the tty device for a given usbserial devices identifiers.
Args:
vendor: (int) something like 0x0000
product: (int) something like 0x0000
Returns:
String, like /dev/ttyACM0 or /dev/tty.usb...
"""
if platform.system() == 'Linux':
vendor, product ... | python | {
"resource": ""
} |
q42751 | CustomFieldsBuilder.create_values | train | def create_values(self, base_model=models.Model, base_manager=models.Manager):
"""
This method will create a model which will hold field values for
field types of custom_field_model.
:param base_model:
:param base_manager:
:return:
"""
_builder = self
... | python | {
"resource": ""
} |
q42752 | CustomFieldsBuilder.create_manager | train | def create_manager(self, base_manager=models.Manager):
"""
This will create the custom Manager that will use the fields_model and values_model
respectively.
:param base_manager: the base manager class to inherit from
:return:
"""
_builder = self
class C... | python | {
"resource": ""
} |
q42753 | CustomFieldsBuilder.create_mixin | train | def create_mixin(self):
"""
This will create the custom Model Mixin to attach to your custom field
enabled model.
:return:
"""
_builder = self
class CustomModelMixin(object):
@cached_property
def _content_type(self):
retu... | python | {
"resource": ""
} |
q42754 | bytes_iter | train | def bytes_iter(obj):
"""Turn a complex object into an iterator of byte strings.
The resulting iterator can be used for caching.
"""
if obj is None:
return
elif isinstance(obj, six.binary_type):
yield obj
elif isinstance(obj, six.string_types):
yield obj
elif isinstanc... | python | {
"resource": ""
} |
q42755 | hash_data | train | def hash_data(obj):
"""Generate a SHA1 from a complex object."""
collect = sha1()
for text in bytes_iter(obj):
if isinstance(text, six.text_type):
text = text.encode('utf-8')
collect.update(text)
return collect.hexdigest() | python | {
"resource": ""
} |
q42756 | _ImportsFinder.visit_Import | train | def visit_Import(self, node):
"""callback for 'import' statement"""
self.imports.extend((None, n.name, n.asname, None)
for n in node.names)
ast.NodeVisitor.generic_visit(self, node) | python | {
"resource": ""
} |
q42757 | _ImportsFinder.visit_ImportFrom | train | def visit_ImportFrom(self, node):
"""callback for 'import from' statement"""
self.imports.extend((node.module, n.name, n.asname, node.level)
for n in node.names)
ast.NodeVisitor.generic_visit(self, node) | python | {
"resource": ""
} |
q42758 | ModuleSet._get_imported_module | train | def _get_imported_module(self, module_name):
"""try to get imported module reference by its name"""
# if imported module on module_set add to list
imp_mod = self.by_name.get(module_name)
if imp_mod:
return imp_mod
# last part of import section might not be a module
... | python | {
"resource": ""
} |
q42759 | run_airbnb_demo | train | def run_airbnb_demo(data_dir):
"""HyperTransfomer will transform back and forth data airbnb data."""
# Setup
meta_file = os.path.join(data_dir, 'Airbnb_demo_meta.json')
transformer_list = ['NumberTransformer', 'DTTransformer', 'CatTransformer']
ht = HyperTransformer(meta_file)
# Run
transf... | python | {
"resource": ""
} |
q42760 | WinEventLog.eventlog | train | def eventlog(self, path):
"""Iterates over the Events contained within the log at the given path.
For each Event, yields a XML string.
"""
self.logger.debug("Parsing Event log file %s.", path)
with NamedTemporaryFile(buffering=0) as tempfile:
self._filesystem.downl... | python | {
"resource": ""
} |
q42761 | publish_message_to_centrifugo | train | def publish_message_to_centrifugo(sender, instance, created, **kwargs):
""" Publishes each saved message to Centrifugo. """
if created is True:
client = Client("{0}api/".format(getattr(settings, "CENTRIFUGE_ADDRESS")), getattr(settings, "CENTRIFUGE_SECRET"))
# we ensure the client is still in th... | python | {
"resource": ""
} |
q42762 | publish_participation_to_thread | train | def publish_participation_to_thread(sender, instance, created, **kwargs):
""" Warns users everytime a thread including them is published. This is done via channel subscription. """
if kwargs.get('created_and_add_participants') is True:
request_participant_id = kwargs.get('request_participant_id')
... | python | {
"resource": ""
} |
q42763 | WebGetRobust.__pre_check | train | def __pre_check(self, requestedUrl):
'''
Allow the pre-emptive fetching of sites with a full browser if they're known
to be dick hosters.
'''
components = urllib.parse.urlsplit(requestedUrl)
netloc_l = components.netloc.lower()
if netloc_l in Domain_Constants.SUCURI_GARBAGE_SITE_NETLOCS:
self.__check_... | python | {
"resource": ""
} |
q42764 | WebGetRobust.__decompressContent | train | def __decompressContent(self, coding, pgctnt):
"""
This is really obnoxious
"""
#preLen = len(pgctnt)
if coding == 'deflate':
compType = "deflate"
bits_opts = [
-zlib.MAX_WBITS, # deflate
zlib.MAX_WBITS, # zlib
zlib.MAX_WBITS | 16, # gzip
zlib.MAX_WBITS | 32, # "automati... | python | {
"resource": ""
} |
q42765 | WebGetRobust.addSeleniumCookie | train | def addSeleniumCookie(self, cookieDict):
'''
Install a cookie exported from a selenium webdriver into
the active opener
'''
# print cookieDict
cookie = http.cookiejar.Cookie(
version = 0,
name = cookieDict['name'],
value = cookieDict['value'],
port ... | python | {
"resource": ""
} |
q42766 | mail_on_500 | train | def mail_on_500(app, recipients, sender='noreply@localhost'):
'''Main function for setting up Flask-ErrorMail to send e-mails when 500
errors occur.
:param app: Flask Application Object
:type app: flask.Flask
:param recipients: List of recipient email addresses.
:type recipients: list or tuple... | python | {
"resource": ""
} |
q42767 | dependencies | train | def dependencies(dist, recursive=False, info=False):
"""Yield distribution's dependencies."""
def case_sorted(items):
"""Return unique list sorted in case-insensitive order."""
return sorted(set(items), key=lambda i: i.lower())
def requires(distribution):
"""Return the requirements... | python | {
"resource": ""
} |
q42768 | user_group_perms_processor | train | def user_group_perms_processor(request):
"""
return context variables with org permissions to the user.
"""
org = None
group = None
if hasattr(request, "user"):
if request.user.is_anonymous:
group = None
else:
group = request.user.get_org_group()
... | python | {
"resource": ""
} |
q42769 | set_org_processor | train | def set_org_processor(request):
"""
Simple context processor that automatically sets 'org' on the context if it
is present in the request.
"""
if getattr(request, "org", None):
org = request.org
pattern_bg = org.backgrounds.filter(is_active=True, background_type="P")
pattern_... | python | {
"resource": ""
} |
q42770 | TwoCaptchaSolver._submit | train | def _submit(self, pathfile, filedata, filename):
'''
Submit either a file from disk, or a in-memory file to the solver service, and
return the request ID associated with the new captcha task.
'''
if pathfile and os.path.exists(pathfile):
files = {'file': open(pathfile, 'rb')}
elif filedata:
assert fil... | python | {
"resource": ""
} |
q42771 | mine_urls | train | def mine_urls(urls, params=None, callback=None, **kwargs):
"""Concurrently retrieve URLs.
:param urls: A set of URLs to concurrently retrieve.
:type urls: iterable
:param params: (optional) The URL parameters to send with each
request.
:type params: dict
:param callback: (o... | python | {
"resource": ""
} |
q42772 | mine_items | train | def mine_items(identifiers, params=None, callback=None, **kwargs):
"""Concurrently retrieve metadata from Archive.org items.
:param identifiers: A set of Archive.org item identifiers to mine.
:type identifiers: iterable
:param params: (optional) The URL parameters to send with each
... | python | {
"resource": ""
} |
q42773 | configure | train | def configure(username=None, password=None, overwrite=None, config_file=None):
"""Configure IA Mine with your Archive.org credentials."""
username = input('Email address: ') if not username else username
password = getpass('Password: ') if not password else password
_config_file = write_config_file(user... | python | {
"resource": ""
} |
q42774 | StockRetriever.__get_time_range | train | def __get_time_range(self, startDate, endDate):
"""Return time range
"""
today = date.today()
start_date = today - timedelta(days=today.weekday(), weeks=1)
end_date = start_date + timedelta(days=4)
startDate = startDate if startDate else str(start_date)
endDate =... | python | {
"resource": ""
} |
q42775 | StockRetriever.get_industry_index | train | def get_industry_index(self, index_id,items=None):
"""retrieves all symbols that belong to an industry.
"""
response = self.select('yahoo.finance.industry',items).where(['id','=',index_id])
return response | python | {
"resource": ""
} |
q42776 | StockRetriever.get_dividendhistory | train | def get_dividendhistory(self, symbol, startDate, endDate, items=None):
"""Retrieves divident history
"""
startDate, endDate = self.__get_time_range(startDate, endDate)
response = self.select('yahoo.finance.dividendhistory', items).where(['symbol', '=', symbol], ['startDate', '=', startDa... | python | {
"resource": ""
} |
q42777 | StockRetriever.get_symbols | train | def get_symbols(self, name):
"""Retrieves all symbols belonging to a company
"""
url = "http://autoc.finance.yahoo.com/autoc?query={0}&callback=YAHOO.Finance.SymbolSuggest.ssCallback".format(name)
response = requests.get(url)
json_data = re.match("YAHOO\.Finance\.SymbolSuggest.... | python | {
"resource": ""
} |
q42778 | fromJson | train | def fromJson(struct, attributes=None):
"Convert a JSON struct to a Geometry based on its structure"
if isinstance(struct, basestring):
struct = json.loads(struct)
indicative_attributes = {
'x': Point,
'wkid': SpatialReference,
'paths': Polyline,
'rings': Polygon,
... | python | {
"resource": ""
} |
q42779 | fromGeoJson | train | def fromGeoJson(struct, attributes=None):
"Convert a GeoJSON-like struct to a Geometry based on its structure"
if isinstance(struct, basestring):
struct = json.loads(struct)
type_map = {
'Point': Point,
'MultiLineString': Polyline,
'LineString': Polyline,
'Polygon': P... | python | {
"resource": ""
} |
q42780 | Polygon.contains | train | def contains(self, pt):
"Tests if the provided point is in the polygon."
if isinstance(pt, Point):
ptx, pty = pt.x, pt.y
assert (self.spatialReference is None or \
self.spatialReference.wkid is None) or \
(pt.spatialReference is None or \
... | python | {
"resource": ""
} |
q42781 | VulnScanner.scan | train | def scan(self, concurrency=1):
"""Iterates over the applications installed within the disk
and queries the CVE DB to determine whether they are vulnerable.
Concurrency controls the amount of concurrent queries
against the CVE DB.
For each vulnerable application the method yield... | python | {
"resource": ""
} |
q42782 | execute_ping | train | def execute_ping(host_list, remote_user, remote_pass,
sudo=False, sudo_user=None, sudo_pass=None):
'''
Execute ls on some hosts
'''
runner = spam.ansirunner.AnsibleRunner()
result, failed_hosts = runner.ansible_perform_operation(
host_list=host_list,
remote_user=remo... | python | {
"resource": ""
} |
q42783 | execute_ls | train | def execute_ls(host_list, remote_user, remote_pass):
'''
Execute any adhoc command on the hosts.
'''
runner = spam.ansirunner.AnsibleRunner()
result, failed_hosts = runner.ansible_perform_operation(
host_list=host_list,
remote_user=remote_user,
remote_pass=remote_pass,
... | python | {
"resource": ""
} |
q42784 | compiler_preprocessor_verbose | train | def compiler_preprocessor_verbose(compiler, extraflags):
"""Capture the compiler preprocessor stage in verbose mode
"""
lines = []
with open(os.devnull, 'r') as devnull:
cmd = [compiler, '-E']
cmd += extraflags
cmd += ['-', '-v']
p = Popen(cmd, stdin=devnull, stdout=PIPE... | python | {
"resource": ""
} |
q42785 | NumberTransformer.get_val | train | def get_val(self, x):
"""Converts to int."""
try:
if self.subtype == 'integer':
return int(round(x[self.col_name]))
else:
if np.isnan(x[self.col_name]):
return self.default_val
return x[self.col_name]
e... | python | {
"resource": ""
} |
q42786 | NumberTransformer.safe_round | train | def safe_round(self, x):
"""Returns a converter that takes in a value and turns it into an integer, if necessary.
Args:
col_name(str): Name of the column.
subtype(str): Numeric subtype of the values.
Returns:
function
"""
val = x[self.col_nam... | python | {
"resource": ""
} |
q42787 | Rados.rados_df | train | def rados_df(self,
host_list=None,
remote_user=None,
remote_pass=None):
'''
Invoked the rados df command and return output to user
'''
result, failed_hosts = self.runner.ansible_perform_operation(
host_list=host_list,
... | python | {
"resource": ""
} |
q42788 | Rados.rados_parse_df | train | def rados_parse_df(self,
result):
'''
Parse the result from ansirunner module and save it as a json
object
'''
parsed_results = []
HEADING = r".*(pool name) *(category) *(KB) *(objects) *(clones)" + \
" *(degraded) *(unfound) *(rd) *(rd ... | python | {
"resource": ""
} |
q42789 | update_roles_gce | train | def update_roles_gce(use_cache=True, cache_expiration=86400, cache_path="~/.gcetools/instances", group_name=None, region=None, zone=None):
"""
Dynamically update fabric's roles by using assigning the tags associated with
each machine in Google Compute Engine.
use_cache - will store a local cache in ~/.... | python | {
"resource": ""
} |
q42790 | eventsource_connect | train | def eventsource_connect(url, io_loop=None, callback=None, connect_timeout=None):
"""Client-side eventsource support.
Takes a url and returns a Future whose result is a
`EventSourceClient`.
"""
if io_loop is None:
io_loop = IOLoop.current()
if isinstance(url, httpclient.HTTPRequest):
... | python | {
"resource": ""
} |
q42791 | printout | train | def printout(*args, **kwargs):
"""
Print function with extra options for formating text in terminals.
"""
# TODO(Lukas): conflicts with function names
color = kwargs.pop('color', {})
style = kwargs.pop('style', {})
prefx = kwargs.pop('prefix', '')
suffx = kwargs.pop('suffix', '')
in... | python | {
"resource": ""
} |
q42792 | colorize | train | def colorize(txt, fg=None, bg=None):
"""
Print escape codes to set the terminal color.
fg and bg are indices into the color palette for the foreground and
background colors.
"""
setting = ''
setting += _SET_FG.format(fg) if fg else ''
setting += _SET_BG.format(bg) if bg else ''
ret... | python | {
"resource": ""
} |
q42793 | stylize | train | def stylize(txt, bold=False, underline=False):
"""
Changes style of the text.
"""
setting = ''
setting += _SET_BOLD if bold is True else ''
setting += _SET_UNDERLINE if underline is True else ''
return setting + str(txt) + _STYLE_RESET | python | {
"resource": ""
} |
q42794 | indent | train | def indent(txt, spacing=4):
"""
Indent given text using custom spacing, default is set to 4.
"""
return prefix(str(txt), ''.join([' ' for _ in range(spacing)])) | python | {
"resource": ""
} |
q42795 | rgb | train | def rgb(red, green, blue):
"""
Calculate the palette index of a color in the 6x6x6 color cube.
The red, green and blue arguments may range from 0 to 5.
"""
for value in (red, green, blue):
if value not in range(6):
raise ColorError('Value must be within 0-5, was {}.'.format(valu... | python | {
"resource": ""
} |
q42796 | isUTF8Strict | train | def isUTF8Strict(data): # pragma: no cover - Only used when cchardet is missing.
'''
Check if all characters in a bytearray are decodable
using UTF-8.
'''
try:
decoded = data.decode('UTF-8')
except UnicodeDecodeError:
return False
else:
for ch in decoded:
if 0xD800 <= ord(ch) <= 0xDFFF:
return F... | python | {
"resource": ""
} |
q42797 | decode_headers | train | def decode_headers(header_list):
'''
Decode a list of headers.
Takes a list of bytestrings, returns a list of unicode strings.
The character set for each bytestring is individually decoded.
'''
decoded_headers = []
for header in header_list:
if cchardet:
inferred = cchardet.detect(header)
if inferred a... | python | {
"resource": ""
} |
q42798 | cd | train | def cd(dest):
""" Temporarily cd into a directory"""
origin = os.getcwd()
try:
os.chdir(dest)
yield dest
finally:
os.chdir(origin) | python | {
"resource": ""
} |
q42799 | files | train | def files(patterns,
require_tags=("require",),
include_tags=("include",),
exclude_tags=("exclude",),
root=".",
always_exclude=("**/.git*", "**/.lfs*", "**/.c9*", "**/.~c9*")):
"""
Takes a list of lib50._config.TaggedValue returns which files should be included a... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.