_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q42100 | GroupsAPI.list_group_s_users | train | def list_group_s_users(self, group_id, include=None, search_term=None):
"""
List group's users.
Returns a list of users in the group.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] =... | python | {
"resource": ""
} |
q42101 | GroupsAPI.preview_processed_html | train | def preview_processed_html(self, group_id, html=None):
"""
Preview processed html.
Preview html content processed for this group
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = grou... | python | {
"resource": ""
} |
q42102 | GroupsAPI.list_group_memberships | train | def list_group_memberships(self, group_id, filter_states=None):
"""
List group memberships.
List the members of a group.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
... | python | {
"resource": ""
} |
q42103 | Clause.from_str | train | def from_str(cls, string):
"""
Creates a clause from a given string.
Parameters
----------
string: str
A string of the form `a+!b` which translates to `a AND NOT b`.
Returns
-------
caspo.core.clause.Clause
Created object instanc... | python | {
"resource": ""
} |
q42104 | Clause.bool | train | def bool(self, state):
"""
Returns the Boolean evaluation of the clause with respect to a given state
Parameters
----------
state : dict
Key-value mapping describing a Boolean state or assignment
Returns
-------
boolean
The evalua... | python | {
"resource": ""
} |
q42105 | Compare.compare_dbs | train | def compare_dbs(self, db_x, db_y, show=True):
"""Compare the tables and row counts of two databases."""
# TODO: Improve method
self._printer("\tComparing database's {0} and {1}".format(db_x, db_y))
# Run compare_dbs_getter to get row counts
x = self._compare_dbs_getter(db_x)
... | python | {
"resource": ""
} |
q42106 | Compare._compare_dbs_getter | train | def _compare_dbs_getter(self, db):
"""Retrieve a dictionary of table_name, row count key value pairs for a DB."""
# Change DB connection if needed
if self.database != db:
self.change_db(db)
return self.count_rows_all() | python | {
"resource": ""
} |
q42107 | Compare.compare_schemas | train | def compare_schemas(self, db_x, db_y, show=True):
"""
Compare the structures of two databases.
Analysis's and compares the column definitions of each table
in both databases's. Identifies differences in column names,
data types and keys.
"""
# TODO: Improve meth... | python | {
"resource": ""
} |
q42108 | Compare._schema_getter | train | def _schema_getter(self, db):
"""Retrieve a dictionary representing a database's data schema."""
# Change DB connection if needed
if self.database != db:
self.change_db(db)
schema_dict = {tbl: self.get_schema(tbl) for tbl in self.tables}
schema_lst = []
for t... | python | {
"resource": ""
} |
q42109 | Memoize.put_cache_results | train | def put_cache_results(self, key, func_akw, set_cache_cb):
"""Put function results into cache."""
args, kwargs = func_akw
# get function results
func_results = self.func(*args, **kwargs)
# optionally add results to cache
if set_cache_cb(func_results):
self[ke... | python | {
"resource": ""
} |
q42110 | service_param_string | train | def service_param_string(params):
"""Takes a param section from a metadata class and returns a param string for the service method"""
p = []
k = []
for param in params:
name = fix_param_name(param['name'])
if 'required' in param and param['required'] is True:
p.append(... | python | {
"resource": ""
} |
q42111 | build_metadata_class | train | def build_metadata_class(specfile):
"""Generate a metadata class for the specified specfile."""
with open(specfile) as f:
spec = json.load(f)
name = os.path.basename(specfile).split('.')[0]
spec['name'] = name
env = get_jinja_env()
metadata_template = env.get_t... | python | {
"resource": ""
} |
q42112 | build_model_classes | train | def build_model_classes(metadata):
"""Generate a model class for any models contained in the specified spec file."""
i = importlib.import_module(metadata)
env = get_jinja_env()
model_template = env.get_template('model.py.jinja2')
for model in i.models:
with open(model_path(model.name.l... | python | {
"resource": ""
} |
q42113 | build_service_class | train | def build_service_class(metadata):
"""Generate a service class for the service contained in the specified metadata class."""
i = importlib.import_module(metadata)
service = i.service
env = get_jinja_env()
service_template = env.get_template('service.py.jinja2')
with open(api_path(service.n... | python | {
"resource": ""
} |
q42114 | AccountReportsAPI.start_report | train | def start_report(self, report, account_id, _parameters=None):
"""
Start a Report.
Generates a report instance for the account.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"] = ac... | python | {
"resource": ""
} |
q42115 | AccountReportsAPI.index_of_reports | train | def index_of_reports(self, report, account_id):
"""
Index of Reports.
Shows all reports that have been run for the account of a specific type.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["a... | python | {
"resource": ""
} |
q42116 | BaseQueryMixin.clean_query | train | def clean_query(self):
"""
Removes any `None` value from an elasticsearch query.
"""
if self.query:
for key, value in self.query.items():
if isinstance(value, list) and None in value:
self.query[key] = [v for v in value if v is not None] | python | {
"resource": ""
} |
q42117 | BaseQueryMixin.get_recirc_content | train | def get_recirc_content(self, published=True, count=3):
"""gets the first 3 content objects in the `included_ids`
"""
query = self.get_query()
# check if query has included_ids & if there are any ids in it,
# in case the ids have been removed from the array
if not query.g... | python | {
"resource": ""
} |
q42118 | BaseQueryMixin.get_full_recirc_content | train | def get_full_recirc_content(self, published=True):
"""performs es search and gets all content objects
"""
q = self.get_query()
search = custom_search_model(Content, q, published=published, field_map={
"feature_type": "feature_type.slug",
"tag": "tags.slug",
... | python | {
"resource": ""
} |
q42119 | Timer.run_later | train | def run_later(self, callable_, timeout, *args, **kwargs):
"""Schedules the specified callable for delayed execution.
Returns a TimerTask instance that can be used to cancel pending
execution.
"""
self.lock.acquire()
try:
if self.die:
raise Ru... | python | {
"resource": ""
} |
q42120 | PagesAPI.show_front_page_groups | train | def show_front_page_groups(self, group_id):
"""
Show front page.
Retrieve the content of the front page
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_id
"""ID"""
path["group_id"] = group_id
self.logg... | python | {
"resource": ""
} |
q42121 | ContentTypeField.to_representation | train | def to_representation(self, value):
"""Convert to natural key."""
content_type = ContentType.objects.get_for_id(value)
return "_".join(content_type.natural_key()) | python | {
"resource": ""
} |
q42122 | ContentTypeField.to_internal_value | train | def to_internal_value(self, value):
"""Convert to integer id."""
natural_key = value.split("_")
content_type = ContentType.objects.get_by_natural_key(*natural_key)
return content_type.id | python | {
"resource": ""
} |
q42123 | DefaultUserSerializer.to_internal_value | train | def to_internal_value(self, data):
"""Basically, each author dict must include either a username or id."""
# model = get_user_model()
model = self.Meta.model
if "id" in data:
author = model.objects.get(id=data["id"])
else:
if "username" not in data:
... | python | {
"resource": ""
} |
q42124 | ChangeHandler.run | train | def run(self):
"""Called when a file is changed to re-run the tests with nose."""
if self.auto_clear:
os.system('cls' if os.name == 'nt' else 'auto_clear')
else:
print
print 'Running unit tests...'
if self.auto_clear:
print
subprocess.c... | python | {
"resource": ""
} |
q42125 | write_tex | train | def write_tex():
"""
Finds all of the output data files, and writes them out to .tex
"""
datadir = livvkit.index_dir
outdir = os.path.join(datadir, "tex")
print(outdir)
# functions.mkdir_p(outdir)
data_files = glob.glob(datadir + "/**/*.json", recursive=True)
for each in data_files... | python | {
"resource": ""
} |
q42126 | Subprocess._invoke | train | def _invoke(self, *params):
"""
Invoke self.exe as a subprocess
"""
cmd = [self.exe] + list(params)
proc = subprocess.Popen(
cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, cwd=self.location, env=self.env)
stdout, stderr = proc.communicate()
if not proc.returncode == 0:
raise RuntimeError(st... | python | {
"resource": ""
} |
q42127 | allow_bare_decorator | train | def allow_bare_decorator(cls):
"""
Wrapper for a class decorator which allows for bare decorator and argument syntax
"""
@wraps(cls)
def wrapper(*args, **kwargs):
""""Wrapper for real decorator"""
# If we weren't only passed a bare class, return class instance
if kwargs or ... | python | {
"resource": ""
} |
q42128 | warp_image_by_corner_points_projection | train | def warp_image_by_corner_points_projection(corner_points, image):
"""Given corner points of a Sudoku, warps original selection to a square image.
:param corner_points:
:type: corner_points: list
:param image:
:type image:
:return:
:rtype:
"""
# Clarify by storing in named variables... | python | {
"resource": ""
} |
q42129 | dict_get_path | train | def dict_get_path(data, path, default=None):
"""
Returns the value inside nested structure of data located
at period delimited path
When traversing a list, as long as that list is containing objects of
type dict, items in that list will have their "name" and "type" values
tested against the cur... | python | {
"resource": ""
} |
q42130 | HyperGraph.to_funset | train | def to_funset(self):
"""
Converts the hypergraph to a set of `gringo.Fun`_ instances
Returns
-------
set
Representation of the hypergraph as a set of `gringo.Fun`_ instances
.. _gringo.Fun: http://potassco.sourceforge.net/gringo.html#Fun
"""
... | python | {
"resource": ""
} |
q42131 | options | train | def options(f):
"""
Shared options, used by all bartender commands
"""
f = click.option('--config', envvar='VODKA_HOME', default=click.get_app_dir('vodka'), help="location of config file")(f)
return f | python | {
"resource": ""
} |
q42132 | check_config | train | def check_config(config):
"""
Check and validate configuration attributes, to help administrators
quickly spot missing required configurations and invalid configuration
values in general
"""
cfg = vodka.config.Config(read=config)
vodka.log.set_loggers(cfg.get("logging"))
vodka.app.loa... | python | {
"resource": ""
} |
q42133 | config | train | def config(config, skip_defaults):
"""
Generates configuration file from config specifications
"""
configurator = ClickConfigurator(
vodka.plugin,
skip_defaults=skip_defaults
)
configurator.configure(vodka.config.instance, vodka.config.InstanceHandler)
try:
dst = m... | python | {
"resource": ""
} |
q42134 | newapp | train | def newapp(path):
"""
Generates all files for a new vodka app at the specified location.
Will generate to current directory if no path is specified
"""
app_path = os.path.join(VODKA_INSTALL_DIR, "resources", "blank_app")
if not os.path.exists(path):
os.makedirs(path)
elif os.path.e... | python | {
"resource": ""
} |
q42135 | is_enabled | train | def is_enabled():
"""Returns ``True`` if bcrypt should be used."""
enabled = getattr(settings, "BCRYPT_ENABLED", True)
if not enabled:
return False
# Are we under a test?
if hasattr(mail, 'outbox'):
return getattr(settings, "BCRYPT_ENABLED_UNDER_TEST", False)
return True | python | {
"resource": ""
} |
q42136 | open_file_with_default_program | train | def open_file_with_default_program(file_path,
background=False, return_cmd=False):
'''Opens a file with the default program for that type.
Open the file with the user's preferred application.
Args:
file_path (str) : Path to the file to be opened.
background (bool): Run the program in the backgrou... | python | {
"resource": ""
} |
q42137 | terminal | train | def terminal(exec_='', background=False, shell_after_cmd_exec=False,
keep_open_after_cmd_exec=False, return_cmd=False):
'''Start the default terminal emulator.
Start the user's preferred terminal emulator, optionally running a command in it.
**Order of starting**
Windows:
Powershell
Mac:
- iTe... | python | {
"resource": ""
} |
q42138 | text_editor | train | def text_editor(file='', background=False, return_cmd=False):
'''Starts the default graphical text editor.
Start the user's preferred graphical text editor, optionally with a file.
Args:
file (str) : The file to be opened with the editor. Defaults to an empty string (i.e. no file).
background (bool): Runs... | python | {
"resource": ""
} |
q42139 | run | train | def run(run_type, module, config):
"""
Collects the analyses cases to be run and launches processes for each of
them.
Args:
run_type: A string representation of the run type (eg. verification)
module: The module corresponding to the run. Must have a run_suite function
config: T... | python | {
"resource": ""
} |
q42140 | launch_processes | train | def launch_processes(tests, run_module, group=True, **config):
""" Helper method to launch processes and sync output """
manager = multiprocessing.Manager()
test_summaries = manager.dict()
process_handles = [multiprocessing.Process(target=run_module.run_suite,
args=(test, config[t... | python | {
"resource": ""
} |
q42141 | on_resize | train | def on_resize(width, height):
"""Setup 3D projection"""
glViewport(0, 0, width, height)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(30, 1.0*width/height, 0.1, 1000.0)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity() | python | {
"resource": ""
} |
q42142 | Sanji.register | train | def register(self, reg_data, retry=True, interval=1, timeout=3):
"""
register function
retry
True, infinity retries
False, no retries
Number, retries times
interval
time period for retry
return
False if no success
... | python | {
"resource": ""
} |
q42143 | MailListView.get_context | train | def get_context(self):
"""Add mails to the context
"""
context = super(MailListView, self).get_context()
mail_list = registered_mails_names()
context['mail_map'] = mail_list
return context | python | {
"resource": ""
} |
q42144 | open | train | def open(s3_url, mode='r', s3_connection=None, **kwargs):
"""Open S3 url, returning a File Object.
S3 connection:
1. Can be specified directly by `s3_connection`.
2. `boto.connect_s3` will be used supplying all `kwargs`.
- `aws_access_key_id` and `aws_secret_access_key`.
-... | python | {
"resource": ""
} |
q42145 | Numeric.is_decimal | train | def is_decimal(self):
"""Determine if a data record is of the type float."""
dt = DATA_TYPES['decimal']
if type(self.data) in dt['type']:
self.type = 'DECIMAL'
num_split = str(self.data).split('.', 1)
self.len = len(num_split[0])
self.len_decimal =... | python | {
"resource": ""
} |
q42146 | EnrollmentTermsAPI.create_enrollment_term | train | def create_enrollment_term(self, account_id, enrollment_term_end_at=None, enrollment_term_name=None, enrollment_term_sis_term_id=None, enrollment_term_start_at=None):
"""
Create enrollment term.
Create a new enrollment term for the specified account.
"""
path = {}
... | python | {
"resource": ""
} |
q42147 | EnrollmentTermsAPI.list_enrollment_terms | train | def list_enrollment_terms(self, account_id, workflow_state=None):
"""
List enrollment terms.
Return all of the terms in the account.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - account_id
"""ID"""
path["account_id"... | python | {
"resource": ""
} |
q42148 | AttributeFilter.from_model | train | def from_model(cls, model_instance, default_value=False, **kwargs):
"""
wrapper for Model's get_attribute_filter
"""
if not isinstance(model_instance, DataCollection):
raise TypeError("model_instance must be a subclass of \
prestans.types.DataCollection, %s g... | python | {
"resource": ""
} |
q42149 | AttributeFilter.conforms_to_template_filter | train | def conforms_to_template_filter(self, template_filter):
"""
Check AttributeFilter conforms to the rules set by the template
- If self, has attributes that template_filter does not contain, throw Exception
- If sub list found, perform the first check
- If self has a value for ... | python | {
"resource": ""
} |
q42150 | AttributeFilter.is_filter_at_key | train | def is_filter_at_key(self, key):
"""
return True if attribute is a sub filter
"""
if key in self:
attribute_status = getattr(self, key)
if isinstance(attribute_status, self.__class__):
return True
return False | python | {
"resource": ""
} |
q42151 | AttributeFilter.is_attribute_visible | train | def is_attribute_visible(self, key):
"""
Returns True if an attribute is visible
If attribute is an instance of AttributeFilter, it returns True if all attributes
of the sub filter are visible.
:param key: name of attribute to check
:type key: str
:return: whethe... | python | {
"resource": ""
} |
q42152 | AttributeFilter.are_any_attributes_visible | train | def are_any_attributes_visible(self):
"""
checks to see if any attributes are set to true
"""
for attribute_name, type_instance in inspect.getmembers(self):
if attribute_name.startswith('__') or inspect.ismethod(type_instance):
continue
if isins... | python | {
"resource": ""
} |
q42153 | AttributeFilter.set_all_attribute_values | train | def set_all_attribute_values(self, value):
"""
sets all the attribute values to the value and propagate to any children
"""
for attribute_name, type_instance in inspect.getmembers(self):
if attribute_name.startswith('__') or inspect.ismethod(type_instance):
... | python | {
"resource": ""
} |
q42154 | AttributeFilter._init_from_dictionary | train | def _init_from_dictionary(self, from_dictionary, template_model=None):
"""
Private helper to init values from a dictionary, wraps children into
AttributeFilter objects
:param from_dictionary: dictionary to get attribute names and visibility from
:type from_dictionary: dict
... | python | {
"resource": ""
} |
q42155 | Predictor.predict | train | def predict(self):
"""
Computes all possible weighted average predictions and their variances
Example::
>>> from caspo import core, predict
>>> networks = core.LogicalNetworkList.from_csv('behaviors.csv')
>>> setup = core.Setup.from_json('setup.json')
... | python | {
"resource": ""
} |
q42156 | LogFile.content | train | def content(self):
"""
Returns raw CSV content of the log file.
"""
raw_content = self._manager.api.session.get(self.download_link).content
data = BytesIO(raw_content)
archive = ZipFile(data)
filename = archive.filelist[0] # Always 1 file in the archive
r... | python | {
"resource": ""
} |
q42157 | Validator.validate | train | def validate(self, read_tuple_name):
"""Check RNF validity of a read tuple.
Args:
read_tuple_name (str): Read tuple name to be checked.s
"""
if reg_lrn.match(read_tuple_name) is None:
self.report_error(
read_tuple_name=read_tuple_name,
error_name="wron... | python | {
"resource": ""
} |
q42158 | Validator.report_error | train | def report_error(self, read_tuple_name, error_name, wrong="", message="", warning=False):
"""Report an error.
Args:
read_tuple_name (): Name of the read tuple.
error_name (): Name of the error.
wrong (str): What is wrong.
message (str): Additional msessage to be printed.
warning (bool): Warni... | python | {
"resource": ""
} |
q42159 | TraceSlowRequestsMiddleware._is_exempt | train | def _is_exempt(self, environ):
"""
Returns True if this request's URL starts with one of the
excluded paths.
"""
exemptions = self.exclude_paths
if exemptions:
path = environ.get('PATH_INFO')
for excluded_p in self.exclude_paths:
i... | python | {
"resource": ""
} |
q42160 | load_network_model | train | def load_network_model(model):
'''
Loads metabolic network models in metabolitics.
:param str model: model name
'''
if type(model) == str:
if model in ['ecoli', 'textbook', 'salmonella']:
return cb.test.create_test_model(model)
elif model == 'recon2':
return ... | python | {
"resource": ""
} |
q42161 | TokenQueryset.bulk_refresh | train | def bulk_refresh(self):
"""
Refreshes all refreshable tokens in the queryset.
Deletes any tokens which fail to refresh.
Deletes any tokens which are expired and cannot refresh.
Excludes tokens for which the refresh was incomplete for other reasons.
"""
session = O... | python | {
"resource": ""
} |
q42162 | ibatch | train | def ibatch(iterable, size):
"""Yield a series of batches from iterable, each size elements long."""
source = iter(iterable)
while True:
batch = itertools.islice(source, size)
yield itertools.chain([next(batch)], batch) | python | {
"resource": ""
} |
q42163 | KVStore.put_many | train | def put_many(self, items): # pragma: no cover
"""Put many key-value pairs.
This method may take advantage of performance or atomicity
features of the underlying store. It does not guarantee that
all items will be set in the same transaction, only that
transactions may be used f... | python | {
"resource": ""
} |
q42164 | KVStore.prefix_keys | train | def prefix_keys(self, prefix, strip_prefix=False):
"""Get all keys that begin with ``prefix``.
:param prefix: Lexical prefix for keys to search.
:type prefix: bytes
:param strip_prefix: True to strip the prefix from yielded items.
:type strip_prefix: bool
:yields: All ... | python | {
"resource": ""
} |
q42165 | GradebookHistoryAPI.details_for_given_date_in_gradebook_history_for_this_course | train | def details_for_given_date_in_gradebook_history_for_this_course(self, date, course_id):
"""
Details for a given date in gradebook history for this course.
Returns the graders who worked on this day, along with the assignments they worked on.
More details can be obtained by selectin... | python | {
"resource": ""
} |
q42166 | GradebookHistoryAPI.lists_submissions | train | def lists_submissions(self, date, course_id, grader_id, assignment_id):
"""
Lists submissions.
Gives a nested list of submission versions
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""The id of the contextual cou... | python | {
"resource": ""
} |
q42167 | GradebookHistoryAPI.list_uncollated_submission_versions | train | def list_uncollated_submission_versions(self, course_id, ascending=None, assignment_id=None, user_id=None):
"""
List uncollated submission versions.
Gives a paginated, uncollated list of submission versions for all matching
submissions in the context. This SubmissionVersion objects... | python | {
"resource": ""
} |
q42168 | Section._save_percolator | train | def _save_percolator(self):
"""saves the query field as an elasticsearch percolator
"""
index = Content.search_objects.mapping.index
query_filter = self.get_content().to_dict()
q = {}
if "query" in query_filter:
q = {"query": query_filter.get("query", {})}
... | python | {
"resource": ""
} |
q42169 | Section.get_content | train | def get_content(self):
"""performs es search and gets content objects
"""
if "query" in self.query:
q = self.query["query"]
else:
q = self.query
search = custom_search_model(Content, q, field_map={
"feature-type": "feature_type.slug",
... | python | {
"resource": ""
} |
q42170 | sample | train | def sample(name, reads_in_tuple):
""" Create a new sample.
"""
if name in [sample_x.get_name() for sample_x in __SAMPLES__]:
rnftools.utils.error(
"Multiple samples have the same name. Each sample must have a unique name.",
program="RNFtools",
subprogram="MIShmash",
... | python | {
"resource": ""
} |
q42171 | get_schema_model | train | def get_schema_model():
"""
Returns the schema model that is active in this project.
"""
try:
return django_apps.get_model(settings.POSTGRES_SCHEMA_MODEL, require_ready=False)
except ValueError:
raise ImproperlyConfigured("POSTGRES_SCHEMA_MODEL must be of the form 'app_label.model_na... | python | {
"resource": ""
} |
q42172 | SSLSocket.read | train | def read(self, len=1024):
"""Read up to LEN bytes and return them.
Return zero-length string on EOF."""
while True:
try:
return self._sslobj.read(len)
except SSLError:
ex = sys.exc_info()[1]
if ex.args[0] == SSL_ERROR_EOF an... | python | {
"resource": ""
} |
q42173 | SSLSocket.write | train | def write(self, data):
"""Write DATA to the underlying SSL channel. Returns
number of bytes of DATA actually transmitted."""
while True:
try:
return self._sslobj.write(data)
except SSLError:
ex = sys.exc_info()[1]
if ex.arg... | python | {
"resource": ""
} |
q42174 | SSLSocket.connect | train | def connect(self, addr):
"""Connects to remote ADDR, and then wraps the connection in
an SSL channel."""
# Here we assume that the socket is client-side, and not
# connected at the time of the call. We connect it, then wrap it.
if self._sslobj:
raise ValueError("atte... | python | {
"resource": ""
} |
q42175 | SSLSocket.accept | train | def accept(self):
"""Accepts a new connection from a remote client, and returns
a tuple containing that new connection wrapped with a server-side
SSL channel, and the address of the remote client."""
newsock, addr = socket.accept(self)
ssl_sock = SSLSocket(newsock._sock,
... | python | {
"resource": ""
} |
q42176 | sclient.send_request | train | def send_request(self, url):
""" Send a request to given url. """
while True:
try:
return urllib.request.urlopen(url)
except urllib.error.HTTPError as e:
raise serror(
"Request `%s` failed (%s:%s)." %
(url, e... | python | {
"resource": ""
} |
q42177 | sclient.get | train | def get(self, uri):
""" Send a request to given uri. """
return self.send_request(
"{0}://{1}:{2}{3}{4}".format(
self.get_protocol(),
self.host,
self.port,
uri,
self.client_id
)
) | python | {
"resource": ""
} |
q42178 | sclient.get_client_id | train | def get_client_id(self):
""" Attempt to get client_id from soundcloud homepage. """
# FIXME: This method doesn't works
id = re.search(
"\"clientID\":\"([a-z0-9]*)\"",
self.send_request(self.SC_HOME).read().decode("utf-8"))
if not id:
raise serror("Can... | python | {
"resource": ""
} |
q42179 | error_handler | train | def error_handler(task):
"""Handle and log RPC errors."""
@wraps(task)
def wrapper(self, *args, **kwargs):
try:
return task(self, *args, **kwargs)
except Exception as e:
self.connected = False
if not self.testing:
exc_type, exc_obj, exc_tb ... | python | {
"resource": ""
} |
q42180 | Bridge.payment | train | def payment(self, origin, destination, amount):
"""Convenience method for sending Bitcoins.
Send coins from origin to destination. Calls record_tx to log the
transaction to database. Uses free, instant "move" transfers
if addresses are both local (in the same wallet), and standard
... | python | {
"resource": ""
} |
q42181 | Bridge.record_tx | train | def record_tx(self, origin, destination, amount,
outcome, destination_id=None):
"""Records a transaction in the database.
Args:
origin (str): user_id of the sender
destination (str): coin address or user_id of the recipient
amount (str, Decimal, number): ... | python | {
"resource": ""
} |
q42182 | Bridge.rpc_connect | train | def rpc_connect(self):
"""Connect to a coin daemon's JSON RPC interface.
Returns:
bool: True if successfully connected, False otherwise.
"""
if self.coin in COINS:
rpc_url = COINS[self.coin]["rpc-url"] + ":"
if self.testnet:
rpc_url += ... | python | {
"resource": ""
} |
q42183 | Bridge.getaccountaddress | train | def getaccountaddress(self, user_id=""):
"""Get the coin address associated with a user id.
If the specified user id does not yet have an address for this
coin, then generate one.
Args:
user_id (str): this user's unique identifier
Returns:
str: Base58Check ... | python | {
"resource": ""
} |
q42184 | Bridge.getbalance | train | def getbalance(self, user_id="", as_decimal=True):
"""Calculate the total balance in all addresses belonging to this user.
Args:
user_id (str): this user's unique identifier
as_decimal (bool): balance is returned as a Decimal if True (default)
or a strin... | python | {
"resource": ""
} |
q42185 | Bridge.listtransactions | train | def listtransactions(self, user_id="", count=10, start_at=0):
"""List all transactions associated with this account.
Args:
user_id (str): this user's unique identifier
count (int): number of transactions to return (default=10)
start_at (int): start the list at this transac... | python | {
"resource": ""
} |
q42186 | Bridge.move | train | def move(self, fromaccount, toaccount, amount, minconf=1):
"""Send coins between accounts in the same wallet.
If the receiving account does not exist, it is automatically
created (but not automatically assigned an address).
Args:
fromaccount (str): origin account
to... | python | {
"resource": ""
} |
q42187 | Bridge.sendfrom | train | def sendfrom(self, user_id, dest_address, amount, minconf=1):
"""
Send coins from user's account.
Args:
user_id (str): this user's unique identifier
dest_address (str): address which is to receive coins
amount (str or Decimal): amount to send (eight decimal points)... | python | {
"resource": ""
} |
q42188 | Bridge.signmessage | train | def signmessage(self, address, message):
"""Sign a message with the private key of an address.
Cryptographically signs a message using ECDSA. Since this requires
an address's private key, the wallet must be unlocked first.
Args:
address (str): address used to sign the messag... | python | {
"resource": ""
} |
q42189 | Bridge.verifymessage | train | def verifymessage(self, address, signature, message):
"""
Verifies that a message has been signed by an address.
Args:
address (str): address claiming to have signed the message
signature (str): ECDSA signature
message (str): plaintext message which was signed
... | python | {
"resource": ""
} |
q42190 | Bridge.call | train | def call(self, command, *args):
"""
Passes an arbitrary command to the coin daemon.
Args:
command (str): command to be sent to the coin daemon
"""
return self.rpc.call(str(command), *args) | python | {
"resource": ""
} |
q42191 | update_feature_type_rates | train | def update_feature_type_rates(sender, instance, created, *args, **kwargs):
"""
Creates a default FeatureTypeRate for each role after the creation of a FeatureTypeRate.
"""
if created:
for role in ContributorRole.objects.all():
FeatureTypeRate.objects.create(role=role, feature_type=in... | python | {
"resource": ""
} |
q42192 | update_contributions | train | def update_contributions(sender, instance, action, model, pk_set, **kwargs):
"""Creates a contribution for each author added to an article.
"""
if action != 'pre_add':
return
else:
for author in model.objects.filter(pk__in=pk_set):
update_content_contributions(instance, autho... | python | {
"resource": ""
} |
q42193 | CalendarEventsAPI.create_calendar_event | train | def create_calendar_event(self, calendar_event_context_code, calendar_event_child_event_data_X_context_code=None, calendar_event_child_event_data_X_end_at=None, calendar_event_child_event_data_X_start_at=None, calendar_event_description=None, calendar_event_duplicate_append_iterator=None, calendar_event_duplicate_count... | python | {
"resource": ""
} |
q42194 | CalendarEventsAPI.reserve_time_slot | train | def reserve_time_slot(self, id, cancel_existing=None, comments=None, participant_id=None):
"""
Reserve a time slot.
Reserves a particular time slot and return the new reservation
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - id
... | python | {
"resource": ""
} |
q42195 | CalendarEventsAPI.update_calendar_event | train | def update_calendar_event(self, id, calendar_event_child_event_data_X_context_code=None, calendar_event_child_event_data_X_end_at=None, calendar_event_child_event_data_X_start_at=None, calendar_event_context_code=None, calendar_event_description=None, calendar_event_end_at=None, calendar_event_location_address=None, ca... | python | {
"resource": ""
} |
q42196 | CalendarEventsAPI.delete_calendar_event | train | def delete_calendar_event(self, id, cancel_reason=None):
"""
Delete a calendar event.
Delete an event from the calendar and return the deleted event
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - id
"""ID"""
path["id"... | python | {
"resource": ""
} |
q42197 | tokens_required | train | def tokens_required(scopes='', new=False):
"""
Decorator for views to request an ESI Token.
Accepts required scopes as a space-delimited string
or list of strings of scope names.
Can require a new token to be retrieved by SSO.
Returns a QueryDict of Tokens.
"""
def decorator(view_func):... | python | {
"resource": ""
} |
q42198 | token_required | train | def token_required(scopes='', new=False):
"""
Decorator for views which supplies a single, user-selected token for the view to process.
Same parameters as tokens_required.
"""
def decorator(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request,... | python | {
"resource": ""
} |
q42199 | ContactFinder.find | train | def find(self, ip):
'''
Find the abuse contact for a IP address
:param ip: IPv4 or IPv6 address to check
:type ip: string
:returns: emails associated with IP
:rtype: list
:returns: none if no contact could be found
:rtype: None
:raises: :py:clas... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.