text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def trending(params):
"""gets trending content values """ |
# get params
try:
series = params.get("site", [DEFAULT_SERIES])[0]
offset = params.get("offset", [DEFAULT_GROUP_BY])[0]
limit = params.get("limit", [20])[0]
except Exception as e:
LOGGER.exception(e)
return json.dumps({"error": e.message}), "500 Internal Error"
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def maha_dist(df):
"""Compute the squared Mahalanobis Distance for each row in the dataframe Given a list of rows `x`, each with `p` elements, a vector :math:\mu... |
mean = df.mean()
S_1 = np.linalg.inv(df.cov())
def fun(row):
A = np.dot((row.T - mean), S_1)
return np.dot(A, (row-mean))
return df.apply(fun, axis=1) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def within_n_sds(n, series):
"""Return true if all values in sequence are within n SDs""" |
z_score = (series - series.mean()) / series.std()
return (z_score.abs() <= n).all() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def within_n_mads(n, series):
"""Return true if all values in sequence are within n MADs""" |
mad_score = (series - series.mean()) / series.mad()
return (mad_score.abs() <= n).all() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def open(filename, flag='c', protocol=None, writeback=False, maxsize=DEFAULT_MAXSIZE, timeout=DEFAULT_TIMEOUT):
"""Open a database file as a persistent dictionar... |
import dbm
dict = dbm.open(filename, flag)
if maxsize is None and timeout is None:
return Shelf(dict, protocol, writeback)
elif maxsize is None:
return TimeoutShelf(dict, protocol, writeback, timeout=timeout)
elif timeout is None:
return LRUShelf(dict, protocol, writeback, m... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _remove_add_key(self, key):
"""Move a key to the end of the linked list and discard old entries.""" |
if not hasattr(self, '_queue'):
return # haven't initialized yet, so don't bother
if key in self._queue:
self._queue.remove(key)
self._queue.append(key)
if self.maxsize == 0:
return
while len(self._queue) > self.maxsize:
del self[... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _is_expired(self, key):
"""Check if a key is expired. If so, delete the key.""" |
if not hasattr(self, '_index'):
return False # haven't initalized yet, so don't bother
try:
timeout = self._index[key]
except KeyError:
if self.timeout:
self._index[key] = int(time() + self.timeout)
else:
self._ind... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set(self, key, func, *args, **kwargs):
"""Return key's value if it exists, otherwise call given function. :param key: The key to lookup/set. :param func: A f... |
if key in self:
return self[key]
self[key] = value = func(*args, **kwargs)
return value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sync(self):
"""Sync the timeout index entry with the shelf.""" |
if self.writeback and self.cache:
super(_TimeoutMixin, self).__delitem__(self._INDEX)
super(_TimeoutMixin, self).sync()
self.writeback = False
super(_TimeoutMixin, self).__setitem__(self._INDEX, self._index)
self.writeback = True
if hasattr(se... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_model(self, request, obj, form, change):
""" Save model for every language so that field auto-population is done for every each of it. """ |
super(DisplayableAdmin, self).save_model(request, obj, form, change)
if settings.USE_MODELTRANSLATION:
lang = get_language()
for code in OrderedDict(settings.LANGUAGES):
if code != lang: # Already done
try:
activate(co... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_fields(self, request, obj=None):
""" For subclasses of ``Orderable``, the ``_order`` field must always be present and be the last field. """ |
fields = super(BaseDynamicInlineAdmin, self).get_fields(request, obj)
if issubclass(self.model, Orderable):
fields = list(fields)
try:
fields.remove("_order")
except ValueError:
pass
fields.append("_order")
return f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_fieldsets(self, request, obj=None):
""" Same as above, but for fieldsets. """ |
fieldsets = super(BaseDynamicInlineAdmin, self).get_fieldsets(
request, obj)
if issubclass(self.model, Orderable):
for fieldset in fieldsets:
fields = [f for f in list(fieldset[1]["fields"])
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_form(self, request, form, change):
""" Set the object's owner as the logged in user. """ |
obj = form.save(commit=False)
if obj.user_id is None:
obj.user = request.user
return super(OwnableAdmin, self).save_form(request, form, change) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def base_concrete_modeladmin(self):
""" The class inheriting directly from ContentModelAdmin. """ |
candidates = [self.__class__]
while candidates:
candidate = candidates.pop()
if ContentTypedAdmin in candidate.__bases__:
return candidate
candidates.extend(candidate.__bases__)
raise Exception("Can't find base concrete ModelAdmin class.") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def changelist_view(self, request, extra_context=None):
""" Redirect to the changelist view for subclasses. """ |
if self.model is not self.concrete_model:
return HttpResponseRedirect(
admin_url(self.concrete_model, "changelist"))
extra_context = extra_context or {}
extra_context["content_models"] = self.get_content_models()
return super(ContentTypedAdmin, self).change... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_content_models(self):
""" Return all subclasses that are admin registered. """ |
models = []
for model in self.concrete_model.get_content_models():
try:
admin_url(model, "add")
except NoReverseMatch:
continue
else:
setattr(model, "meta_verbose_name", model._meta.verbose_name)
setatt... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_model(self, request, obj, form, change):
""" Provides a warning if the user is an active admin with no admin access. """ |
super(SitePermissionUserAdmin, self).save_model(
request, obj, form, change)
user = self.model.objects.get(id=obj.id)
has_perms = len(user.get_all_permissions()) > 0
has_sites = SitePermission.objects.filter(user=user).count() > 0
if user.is_active and user.is_staff ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bind(self, args, kwargs):
""" Bind arguments and keyword arguments to the encapsulated function. Returns a dictionary of parameters (named according to funct... |
spec = self._spec
resolution = self.resolve(args, kwargs)
params = dict(zip(spec.args, resolution.slots))
if spec.varargs:
params[spec.varargs] = resolution.varargs
if spec.varkw:
params[spec.varkw] = resolution.varkw
if spec.kwonlyargs:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply(self, args, kwargs):
""" Replicate a call to the encapsulated function. Unlike func(*args, **kwargs) the call is deterministic in the order kwargs are ... |
# Construct helper locals that only contain the function to call as
# 'func', all positional arguments as 'argX' and all keyword arguments
# as 'kwX'
_locals = {'func': self._func}
if args is not None:
_locals.update({
"arg{}".format(index): args[inde... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self, **kwargs):
""" Add, remove or modify a share's title. Input: * ``title`` The share title, if any (optional) **NOTE**: Passing ``None`` or callin... |
if 'title' in kwargs:
params = {"title": kwargs['title']}
else:
params = {"title": None}
response = GettRequest().post("/shares/%s/update?accesstoken=%s" % (self.sharename, self.user.access_token()), params)
if response.http_status == 200:
self.__in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def destroy(self):
""" This method removes this share and all of its associated files. There is no way to recover a share or its contents once this method has be... |
response = GettRequest().post("/shares/%s/destroy?accesstoken=%s" % (self.sharename, self.user.access_token()), None)
if response.http_status == 200:
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def refresh(self):
""" This method refreshes the object with current metadata from the Gett service. Input: * None Output: * None Example:: share = client.get_sh... |
response = GettRequest().get("/shares/%s" % self.sharename)
if response.http_status == 200:
self.__init__(self.user, **response.response) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def code_timer(reset=False):
'''Sets a global variable for tracking the timer accross multiple
files '''
global CODE_TIMER
if reset:
CODE_TIMER = CodeTimer()
else:
if CODE_TIMER is None:
return CodeTimer()
else:
return CODE_TIMER |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def log(self, timer_name, node):
''' logs a event in the timer '''
timestamp = time.time()
if hasattr(self, timer_name):
getattr(self, timer_name).append({
"node":node,
"time":timestamp})
else:
setattr(self, timer_name, [{"node":nod... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def print_timer(self, timer_name, **kwargs):
''' prints the timer to the terminal
keyword args:
delete -> True/False -deletes the timer after printing
'''
if hasattr(self, timer_name):
_delete_timer = kwargs.get("delete", False)
print("|-----... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_cluster_exists(self, name):
"""Check if cluster exists. If it does not, raise exception.""" |
self.kubeconf.open()
clusters = self.kubeconf.get_clusters()
names = [c['name'] for c in clusters]
if name in names:
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, name=None, provider='AwsEKS', print_output=True):
"""List all cluster. """ |
# Create cluster object
Cluster = getattr(providers, provider)
cluster = Cluster(name)
self.kubeconf.open()
if name is None:
clusters = self.kubeconf.get_clusters()
print("Running Clusters:")
for cluster in clusters:
print(f" ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(self, name, provider='AwsEKS'):
"""Create a Kubernetes cluster on a given provider. """ |
# ----- Create K8s cluster on provider -------
# Create cluster object
Cluster = getattr(providers, provider)
cluster = Cluster(name=name, ssh_key_name='zsailer')
cluster.create()
# -------- Add cluster to kubeconf -----------
# Add cluster to kubeconf
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self, name, provider='AwsEKS'):
"""Delete a Kubernetes cluster. """ |
# if self.check_cluster_exists(name) is False:
# raise JhubctlError("Cluster name not found in availabe clusters.")
# Create cluster object
Cluster = getattr(providers, provider)
cluster = Cluster(name)
cluster.delete()
# Remove from kubeconf
self.k... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def random_string(length=8, charset=None):
'''
Generates a string with random characters. If no charset is specified, only
letters and digits are used.
Args:
length (int) length of the returned string
charset (string) list of characters to choose from
Returns:
(str) with ran... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def str2dict(str_in):
'''
Extracts a dict from a string.
Args:
str_in (string) that contains python dict
Returns:
(dict) or None if no valid dict was found
Raises:
-
'''
dict_out = safe_eval(str_in)
if not isinstance(dict_out, dict):
dict_out = None
r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def str2tuple(str_in):
'''
Extracts a tuple from a string.
Args:
str_in (string) that contains python tuple
Returns:
(dict) or None if no valid tuple was found
Raises:
-
'''
tuple_out = safe_eval(str_in)
if not isinstance(tuple_out, tuple):
tuple_out = No... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def str2dict_keys(str_in):
'''
Extracts the keys from a string that represents a dict and returns them
sorted by key.
Args:
str_in (string) that contains python dict
Returns:
(list) with keys or None if no valid dict was found
Raises:
-
'''
tmp_dict = str2dict(st... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def str2dict_values(str_in):
'''
Extracts the values from a string that represents a dict and returns them
sorted by key.
Args:
str_in (string) that contains python dict
Returns:
(list) with values or None if no valid dict was found
Raises:
-
'''
tmp_dict = str2d... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expr_to_str(n, l=None):
""" construct SQL string from expression node """ |
op = n[0]
if op.startswith('_') and op.endswith('_'):
op = op.strip('_')
if op == 'var':
return n[1]
elif op == 'literal':
if isinstance(n[1], basestring):
return "'%s'" % n[1]
return str(n[1])
elif op == 'cast':
re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def construct_func_expr(n):
""" construct the function expression """ |
op = n[0]
if op.startswith('_') and op.endswith('_'):
op = op.strip('_')
if op == 'var':
return Var(str(n[1]))
elif op == 'literal':
if isinstance(n[1], basestring):
raise "not implemented"
return Constant(n[1])
elif op == 'cas... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_api_by_name(api_name):
""" Fetch an api record by its name """ |
api_records = console.get_rest_apis()['items']
matches = filter(lambda x: x['name'] == api_name, api_records)
if not matches:
return None
return matches[0] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_method(api_id, resource_id, verb):
""" Fetch extra metadata for this particular method """ |
return console.get_method(
restApiId=api_id,
resourceId=resource_id,
httpMethod=verb) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def battery_voltage(self):
""" Returns voltage in mV """ |
msb = self.bus.read_byte_data(AXP209_ADDRESS, BATTERY_VOLTAGE_MSB_REG)
lsb = self.bus.read_byte_data(AXP209_ADDRESS, BATTERY_VOLTAGE_LSB_REG)
voltage_bin = msb << 4 | lsb & 0x0f
return voltage_bin * 1.1 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def internal_temperature(self):
""" Returns temperature in celsius C """ |
temp_msb = self.bus.read_byte_data(AXP209_ADDRESS, INTERNAL_TEMPERATURE_MSB_REG)
temp_lsb = self.bus.read_byte_data(AXP209_ADDRESS, INTERNAL_TEMPERATURE_LSB_REG)
# MSB is 8 bits, LSB is lower 4 bits
temp = temp_msb << 4 | temp_lsb & 0x0f
# -144.7c -> 000h, 0.1c/bit FFFh -> 264.8... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copen(fileobj, mode='rb', **kwargs):
"""Detects and opens compressed file for reading and writing. Args: fileobj (File):
any File-like object supported by a... |
algo = io.open # Only used as io.open in write mode
mode = mode.lower().strip()
modules = {} # Later populated by compression algorithms
write_mode = False if mode.lstrip('U')[0] == 'r' else True
kwargs['mode'] = mode
# Currently supported compression algorithms
modules_to_import = {
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_sg_name_dict(self, data, page_size, no_nameconv):
"""Get names of security groups referred in the retrieved rules. :return: a dict from secgroup ID to s... |
if no_nameconv:
return {}
neutron_client = self.get_client()
search_opts = {'fields': ['id', 'name']}
if self.pagination_support:
if page_size:
search_opts.update({'limit': page_size})
sec_group_ids = set()
for rule in data:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load(self):
""" Loads the user's account details and Raises parseException """ |
pg = self.usr.getPage("http://www.neopets.com/bank.phtml")
# Verifies account exists
if not "great to see you again" in pg.content:
logging.getLogger("neolib.user").info("Could not load user's bank. Most likely does not have an account.", {'pg': pg})
raise noBan... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def collectInterest(self):
""" Collects user's daily interest, returns result Returns bool - True if successful, False otherwise """ |
if self.collectedInterest:
return False
pg = self.usr.getPage("http://www.neopets.com/bank.phtml")
form = pg.form(action="process_bank.phtml")
form['type'] = "interest"
pg = form.submit()
# Success redirects to bank page
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connected_components(G):
"""
Check if G is connected and return list of sets. Every
set contains all vertices in one connected component.
""" |
result = []
vertices = set(G.vertices)
while vertices:
n = vertices.pop()
group = {n}
queue = Queue()
queue.put(n)
while not queue.empty():
n = queue.get()
neighbors = set(G.vertices[n])
neighbors.difference_update(group... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prim(G, start, weight='weight'):
"""
Algorithm for finding a minimum spanning
tree for a weighted undirected graph.
""" |
if len(connected_components(G)) != 1:
raise GraphInsertError("Prim algorithm work with connected graph only")
if start not in G.vertices:
raise GraphInsertError("Vertex %s doesn't exist." % (start,))
pred = {}
key = {}
pqueue = {}
lowest = 0
for edge in G.edges:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find(cls, api_name):
""" Find or create an API model object by name """ |
if api_name in cls.apis_by_name:
return cls.apis_by_name[api_name]
api = cls(api_name)
api._fetch_from_aws()
if api.exists_in_aws:
api._fetch_resources()
cls.apis_by_name[api_name] = api
return api |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _load_from_configs(self, filename):
""" Return content of file which located in configuration directory """ |
config_filename = os.path.join(self._config_path, filename)
if os.path.exists(config_filename):
try:
f = open(config_filename, 'r')
content = ''.join(f.readlines())
f.close()
return content
except Exception as err:
raise err
else:
raise IOError("Fil... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load(self):
""" Load application configuration """ |
try:
if not self.__in_memory:
self._json = json.loads(self._load_from_configs(self._main_config))
# ToDo: make this via extension for root logger
# self._log = aLogger.getLogger(__name__, cfg=self) # reload logger using loaded configuration
self._load_modules()
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, path, default=None, check_type=None, module_name=None):
""" Get option property :param path: full path to the property with name :param default: de... |
if self._json is not None:
# process whole json or just concrete module
node = self._json if module_name is None else self.get_module_config(module_name)
path_data = path.split('.')
try:
while len(path_data) > 0:
node = node[path_data.pop(0)]
if check_type is not ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_module_config(self, name):
""" Return module configuration loaded from separate file or None """ |
if self.exists("modules"):
if name in self._json["modules"] and not isinstance(self._json["modules"][name], str):
return self._json["modules"][name]
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_hook(hook_name):
"""Returns the specified hook. Args: hook_name (str) Returns: str - (the content of) the hook Raises: HookNotFoundError """ |
if not pkg_resources.resource_exists(__name__, hook_name):
raise HookNotFoundError
return pkg_resources.resource_string(__name__, hook_name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def end(self, s=None, post=None, noraise=False):
""" Prints the end banner and raises ``ProgressOK`` exception When ``noraise`` flag is set to ``True``, then the... |
s = s or self.end_msg
self.printer(self.color.green(s))
if post:
post()
if noraise:
return
raise ProgressOK() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def abrt(self, s=None, post=None, noraise=False):
""" Prints the abrt banner and raises ``ProgressAbrt`` exception When ``noraise`` flag is set to ``True``, then... |
s = s or self.abrt_msg
self.printer(self.color.red(s))
if post:
post()
if noraise:
return
raise ProgressAbrt() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prog(self, s=None):
""" Prints the progress indicator """ |
s = s or self.prog_msg
self.printer(s, end='') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def where(self, custom_restrictions=[], **restrictions):
""" Analog to SQL "WHERE". Does not perform a query until `select` is called. Returns a repo object. Opt... |
# Generate the SQL pieces and the relevant values
standard_names, standard_values = self._standard_items(restrictions)
custom_names, custom_values = self._custom_items(custom_restrictions)
in_names, in_values = self._in_items(restrictions)
query_names = standard_names + custom_n... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def order_by(self, **kwargs):
""" Analog to SQL "ORDER BY". +kwargs+ should only contain one item. examples) NO: repo.order_by() NO: repo.order_by(id="desc", nam... |
if kwargs:
col, order = kwargs.popitem()
self.order_clause = "order by {col} {order} ".format(
col=col, order=order)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def select(self, *attributes):
""" Select the passed +attributes+ from the table, subject to the restrictions provided by the other methods in this class. ex) SE... |
namespaced_attributes = [
"{table}.{attr}".format(table=self.table_name, attr=attr)
for attr in attributes
]
cmd = ('select {attrs} from {table} '
'{join_clause}{where_clause}{order_clause}'
'{group_clause}{having_clause}{limit_clause}').for... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def count(self):
""" Count the number of records in the table, subject to the query. """ |
cmd = ("select COUNT(*) from {table} "
"{join_clause}{where_clause}{order_clause}").format(
table=self.table_name,
where_clause=self.where_clause,
join_clause=self.join_clause,
order_clause=self.order_clause).rstrip(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self, **data):
""" Update records in the table with +data+. Often combined with `where`, as it acts on all records in the table unless restricted. ex)... |
data = data.items()
update_command_arg = ", ".join("{} = ?".format(entry[0])
for entry in data)
cmd = "update {table} set {update_command_arg} {where_clause}".format(
update_command_arg=update_command_arg,
where_clause=self.where_cl... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self):
""" Remove entries from the table. Often combined with `where`, as it acts on all records in the table unless restricted. """ |
cmd = "delete from {table} {where_clause}".format(
table=self.table_name,
where_clause=self.where_clause
).rstrip()
Repo.db.execute(cmd, self.where_values) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect_db(Repo, database=":memory:"):
""" Connect Repo to a database with path +database+ so all instances can interact with the database. """ |
Repo.db = sqlite3.connect(database,
detect_types=sqlite3.PARSE_DECLTYPES)
return Repo.db |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _trace(self, frame, event, arg_unused):
""" The trace function passed to sys.settrace. """ |
cur_time = time.time()
lineno = frame.f_lineno
depth = self.depth
filename = inspect.getfile(frame)
if self.last_exc_back:
if frame == self.last_exc_back:
self.data['time_spent'] += (cur_time - self.start_time)
self.depth -= 1
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start(self, origin):
""" Start this Tracer. Return a Python function suitable for use with sys.settrace(). """ |
self.start_time = time.time()
self.pause_until = None
self.data.update(self._get_struct(origin, 'origin'))
self.data_stack.append(self.data)
sys.settrace(self._trace)
return self._trace |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop(self):
""" Stop this Tracer. """ |
if hasattr(sys, "gettrace") and self.log:
if sys.gettrace() != self._trace:
msg = "Trace function changed, measurement is likely wrong: %r"
print >> sys.stdout, msg % sys.gettrace()
sys.settrace(None) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resolver(*for_resolve, attr_package='__package_for_resolve_deco__'):
""" Resolve dotted names in function arguments Usage: """ |
def decorator(func):
spec = inspect.getargspec(func).args
if set(for_resolve) - set(spec):
raise ValueError('bad arguments')
@wraps(func)
def wrapper(*args, **kwargs):
args = list(args)
if args and attr_package:
package = getattr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def relateObjectLocs(obj, entities, selectF):
"""calculate the minimum distance to reach any iterable of entities with a loc""" |
#if obj in entities: return 0 # is already one of the entities
try: obj = obj.loc # get object's location, if it has one
except AttributeError: pass # assume obj is already a MapPoint
try: func = obj.direct2dDistance # assume obj is a MapPoint
except Attribute... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convertToMapPic(byteString, mapWidth):
"""convert a bytestring into a 2D row x column array, representing an existing map of fog-of-war, creep, etc.""" |
data = []
line = ""
for idx,char in enumerate(byteString):
line += str(ord(char))
if ((idx+1)%mapWidth)==0:
data.append(line)
line = ""
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_component_definition(self, definition):
""" Add a ComponentDefinition to the document """ |
# definition.identity = self._to_uri_from_namespace(definition.identity)
if definition.identity not in self._components.keys():
self._components[definition.identity] = definition
else:
raise ValueError("{} has already been defined".format(definition.identity)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def assemble_component(self, into_component, using_components):
""" Assemble a list of already defined components into a structual hirearchy """ |
if not isinstance(using_components, list) or len(using_components) == 0:
raise Exception('Must supply list of ComponentDefinitions')
components = []
sequence_annotations = []
seq_elements = ''
for k, c in enumerate(using_components):
try:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _add_sequence(self, sequence):
""" Add a Sequence to the document """ |
if sequence.identity not in self._sequences.keys():
self._sequences[sequence.identity] = sequence
else:
raise ValueError("{} has already been defined".format(sequence.identity)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_model(self, model):
""" Add a model to the document """ |
if model.identity not in self._models.keys():
self._models[model.identity] = model
else:
raise ValueError("{} has already been defined".format(model.identity)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_module_definition(self, module_definition):
""" Add a ModuleDefinition to the document """ |
if module_definition.identity not in self._module_definitions.keys():
self._module_definitions[module_definition.identity] = module_definition
else:
raise ValueError("{} has already been defined".format(module_definition.identity)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_components(self, uri):
""" Get components from a component definition in order """ |
try:
component_definition = self._components[uri]
except KeyError:
return False
sorted_sequences = sorted(component_definition.sequence_annotations,
key=attrgetter('first_location'))
return [c.component for c in sorted_sequences... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clear_document(self):
""" Clears ALL items from document, reseting it to clean """ |
self._components.clear()
self._sequences.clear()
self._namespaces.clear()
self._models.clear()
self._modules.clear()
self._collections.clear()
self._annotations.clear()
self._functional_component_store.clear()
self._collection_store.clear() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_triplet_value(self, graph, identity, rdf_type):
""" Get a value from an RDF triple """ |
value = graph.value(subject=identity, predicate=rdf_type)
return value.toPython() if value is not None else value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_triplet_value_list(self, graph, identity, rdf_type):
""" Get a list of values from RDF triples when more than one may be present """ |
values = []
for elem in graph.objects(identity, rdf_type):
values.append(elem.toPython())
return values |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _read_sequences(self, graph):
""" Read graph and add sequences to document """ |
for e in self._get_elements(graph, SBOL.Sequence):
identity = e[0]
c = self._get_rdf_identified(graph, identity)
c['elements'] = self._get_triplet_value(graph, identity, SBOL.elements)
c['encoding'] = self._get_triplet_value(graph, identity, SBOL.encoding)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _read_component_definitions(self, graph):
""" Read graph and add component defintions to document """ |
for e in self._get_elements(graph, SBOL.ComponentDefinition):
identity = e[0]
# Store component values in dict
c = self._get_rdf_identified(graph, identity)
c['roles'] = self._get_triplet_value_list(graph, identity, SBOL.role)
c['types'] = self._get_t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _read_models(self, graph):
""" Read graph and add models to document """ |
for e in self._get_elements(graph, SBOL.Model):
identity = e[0]
m = self._get_rdf_identified(graph, identity)
m['source'] = self._get_triplet_value(graph, identity, SBOL.source)
m['language'] = self._get_triplet_value(graph, identity, SBOL.language)
m... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _read_module_definitions(self, graph):
""" Read graph and add module defintions to document """ |
for e in self._get_elements(graph, SBOL.ModuleDefinition):
identity = e[0]
m = self._get_rdf_identified(graph, identity)
m['roles'] = self._get_triplet_value_list(graph, identity, SBOL.role)
functional_components = {}
for func_comp in graph.triples((i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _extend_module_definitions(self, graph):
""" Using collected module definitions extend linkages """ |
for mod_id in self._modules:
mod_identity = self._get_triplet_value(graph, URIRef(mod_id), SBOL.module)
modules = []
for mod in graph.triples((mod_identity, SBOL.module, None)):
md = self._get_rdf_identified(graph, mod[2])
definition_id = self... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _read_annotations(self, graph):
""" Find any non-defined elements at TopLevel and create annotations """ |
flipped_namespaces = {v: k for k, v in self._namespaces.items()}
for triple in graph.triples((None, RDF.type, None)):
namespace, obj = split_uri(triple[2])
prefix = flipped_namespaces[namespace]
as_string = '{}:{}'.format(prefix, obj)
if as_string not in ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _read_collections(self, graph):
""" Read graph and add collections to document """ |
for e in self._get_elements(graph, SBOL.Collection):
identity = e[0]
c = self._get_rdf_identified(graph, identity)
members = []
# Need to handle other non-standard TopLevel objects first
for m in graph.triples((identity, SBOL.member, None)):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read(self, f):
""" Read in an SBOL file, replacing current document contents """ |
self.clear_document()
g = Graph()
g.parse(f, format='xml')
for n in g.namespaces():
ns = n[1].toPython()
if not ns.endswith(('#', '/', ':')):
ns = ns + '/'
self._namespaces[n[0]] = ns
# Extend the existing namespaces avai... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write(self, f):
""" Write an SBOL file from current document contents """ |
rdf = ET.Element(NS('rdf', 'RDF'), nsmap=XML_NS)
# TODO: TopLevel Annotations
sequence_values = sorted(self._sequences.values(), key=lambda x: x.identity)
self._add_to_root(rdf, sequence_values)
component_values = sorted(self._components.values(), key=lambda x: x.identity)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(cls, dname):
""" Get the requested domain @param dname: Domain name @type dname: str @rtype: Domain or None """ |
Domain = cls
dname = dname.hostname if hasattr(dname, 'hostname') else dname.lower()
return Session.query(Domain).filter(Domain.name == dname).first() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_or_create(cls, dname):
""" Get the requested domain, or create it if it doesn't exist already @param dname: Domain name @type dname: str @rtype: Domain "... |
Domain = cls
dname = dname.hostname if hasattr(dname, 'hostname') else dname
extras = 'www.{dn}'.format(dn=dname) if dname not in ('localhost', ) and not \
re.match('^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$', dname) else None
# Fetch the domain entry if it already exists
logg... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all(cls, domain=None):
""" Return all sites @param domain: The domain to filter by @type domain: Domain @rtype: list of Site """ |
Site = cls
site = Session.query(Site)
if domain:
site.filter(Site.domain == domain)
return site.all() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(cls, domain, name):
""" Get the requested site entry @param domain: Domain name @type domain: Domain @param name: Site name @type name: str @rtype: Domai... |
Site = cls
return Session.query(Site).filter(Site.domain == domain).filter(collate(Site.name, 'NOCASE') == name).first() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self, drop_database=True):
""" Delete the site entry @param drop_database: Drop the sites associated MySQL database @type drop_database: bool """ |
self.disable()
Session.delete(self)
if drop_database and self.db_name:
mysql = create_engine('mysql://root:secret@localhost')
mysql.execute('DROP DATABASE IF EXISTS `{db}`'.format(db=self.db_name))
try:
mysql.execute('DROP USER `{u}`'.format(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def version(self, value):
""" Save the Site's version from a string or version tuple @type value: tuple or str """ |
if isinstance(value, tuple):
value = unparse_version(value)
self._version = value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enable(self, force=False):
""" Enable this site """ |
log = logging.getLogger('ipsv.models.sites.site')
log.debug('Disabling all other sites under the domain %s', self.domain.name)
Session.query(Site).filter(Site.id != self.id).filter(Site.domain == self.domain).update({'enabled': 0})
sites_enabled_path = _cfg.get('Paths', 'NginxSitesEnab... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disable(self):
""" Disable this site """ |
log = logging.getLogger('ipsv.models.sites.site')
sites_enabled_path = _cfg.get('Paths', 'NginxSitesEnabled')
symlink_path = os.path.join(sites_enabled_path, '{domain}-{fn}.conf'.format(domain=self.domain.name,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_nginx_config(self):
""" Write the Nginx configuration file for this Site """ |
log = logging.getLogger('ipsv.models.sites.site')
if not os.path.exists(self.root):
log.debug('Creating HTTP root directory: %s', self.root)
os.makedirs(self.root, 0o755)
# Generate our server block configuration
server_block = ServerBlock(self)
server_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extend_list(self, data, parsed_args):
"""Add subnet information to a network list.""" |
neutron_client = self.get_client()
search_opts = {'fields': ['id', 'cidr']}
if self.pagination_support:
page_size = parsed_args.page_size
if page_size:
search_opts.update({'limit': page_size})
subnet_ids = []
for n in data:
if ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bump(self, bump_part):
"""Return a new bumped version instance.""" |
major, minor, patch, stage, n = tuple(self)
# stage bump
if bump_part not in {"major", "minor", "patch"}:
if bump_part not in self.stages:
raise ValueError(f"Unknown {bump_part} stage")
# We can not bump from final stage to final again.
if... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
-> asyncio.tasks.Task: """Create task and add to our collection of pending tasks.""" |
if asyncio.iscoroutine(target):
task = self._loop.create_task(target)
elif asyncio.iscoroutinefunction(target):
task = self._loop.create_task(target(*args))
else:
raise ValueError("Expected coroutine as target")
self._pending_tasks.append(task)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cancel_pending_tasks(self):
"""Cancel all pending tasks.""" |
for task in self._pending_tasks:
task.cancel()
if not self._loop.is_running():
try:
self._loop.run_until_complete(task)
except asyncio.CancelledError:
pass
except Exception: # pylint: disable=broad-e... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start(self, fork=True):
"""Starts the registry aggregator. :param fork: whether to fork a process; if ``False``, blocks and stays in the existing process """ |
if not fork:
distributed_logger.info('Starting metrics aggregator, not forking')
_registry_aggregator(self.reporter, self.socket_addr)
else:
distributed_logger.info('Starting metrics aggregator, forking')
p = Process(target=_registry_aggregator, args=(sel... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.