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 streamify(self, state, frame):
"""Prepare frame for output as a COBS-encoded stream.""" |
# Get the encoding table
enc_tab = self._tables[1][:]
# Need the special un-trailed block length and code
untrail_len, untrail_code = enc_tab.pop(0)
# Set up a repository to receive the encoded blocks
result = []
# Break the frame into blocks
blocks =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_conf(self, keys=[]):
"""Parse configuration values from the database. The extension must have been previously initialized. If a key is not found in the... |
confs = self.app.config.get('WAFFLE_CONFS', {})
if not keys:
keys = confs.keys()
result = {}
for key in keys:
# Some things cannot be changed...
if key.startswith('WAFFLE_'):
continue
# No arbitrary keys
if 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 update_db(self, new_values):
"""Update database values and application configuration. The provided keys must be defined in the ``WAFFLE_CONFS`` setting. Argu... |
confs = self.app.config.get('WAFFLE_CONFS', {})
to_update = {}
for key in new_values.keys():
# Some things cannot be changed...
if key.startswith('WAFFLE_'):
continue
# No arbitrary keys
if key not in confs.keys():
... |
<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_conf(self):
"""Update configuration values from database. This method should be called when there is an update notification. """ |
parsed = self.parse_conf()
if not parsed:
return None
# Update app config
self.app.config.update(parsed) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_app(self, app, configstore):
"""Initialize the extension for the given application and store. Parse the configuration values stored in the database obta... |
if not hasattr(app, 'extensions'):
app.extensions = {}
self.state = _WaffleState(app, configstore)
app.extensions['waffleconf'] = self.state |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def isolcss(prefix, css):
""" Returns `css` with all selectors prefixed by `prefix`, or replacing "&" as SASS and LESS both do. Tries to parse strictly then fall... |
try:
# Attempt full strict parse, raise exception on failure.
all(True for m in matchiter(selrule_or_atom_re, css))
except ValueError as e:
logger.warning("Strict parse failed at char {}".format(e.args[0]))
splits = matchiter(selrule_or_any_re, css)
else:
splits = ma... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decrypt_file(filename, set_env=True, override_env=False):
""" Decrypts a JSON file containing encrypted secrets. This file should contain an object mapping t... |
data = json.load(open(filename))
results = {}
for key, v in data.iteritems():
v_decrypt = decrypt_secret(v)
results[key] = v_decrypt
if set_env:
if key in os.environ and not override_env:
break
os.environ[str(key)] = v_decrypt
return 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 decrypt_or_cache(filename, **kwargs):
""" Attempts to load a local version of decrypted secrets before making external api calls. This is useful as it allows... |
clear_fname = enc_to_clear_filename(filename)
if clear_fname:
return json.load(open(clear_fname))
return decrypt_file(filename, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list(self, filterfn=lambda x: True):
"""Return all direct descendands of directory `self` for which `filterfn` returns True. """ |
return [self / p for p in self.listdir() if filterfn(self / p)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rm(self, fname=None):
"""Remove a file, don't raise exception if file does not exist. """ |
if fname is not None:
return (self / fname).rm()
try:
self.remove()
except OSError:
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def chunked(l, n):
"""Chunk one big list into few small lists.""" |
return [l[i:i + n] for i in range(0, len(l), 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 getBids(self, auction_id):
"""Retrieve all bids in given auction.""" |
bids = {}
rc = self.__ask__('doGetBidItem2', itemId=auction_id)
if rc:
for i in rc:
i = i['bidsArray']
bids[long(i['item'][1])] = {
'price': Decimal(i['item'][6]),
'quantity': int(i['item'][5]),
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getBuyerInfo(self, auction_id, buyer_id):
"""Return buyer info.""" |
# TODO: add price from getBids
rc = self.__ask__('doGetPostBuyData', itemsArray=self.ArrayOfLong([auction_id]), buyerFilterArray=self.ArrayOfLong([buyer_id]))
rc = rc[0]['usersPostBuyData']['item'][0]['userData']
return {'allegro_aid': auction_id,
'allegro_uid': rc['user... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getOrders(self, auction_ids):
"""Return orders details.""" |
orders = {}
# chunk list (only 25 auction_ids per request)
for chunk in chunked(auction_ids, 25):
# auctions = [{'item': auction_id} for auction_id in chunk] # TODO?: is it needed?
auctions = self.ArrayOfLong(chunk)
rc = self.__ask__('doGetPostBuyData', item... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getJournalDeals(self, start=None):
"""Return all journal events from start.""" |
# 1 - utworzenie aktu zakupowego (deala), 2 - utworzenie formularza pozakupowego (karta platnosci), 3 - anulowanie formularza pozakupowego (karta platnosci), 4 - zakończenie (opłacenie) transakcji przez PzA
if start is not None:
self.last_event_id = start
events = []
while s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getWaitingFeedbacks(self):
"""Return all waiting feedbacks from buyers.""" |
# TODO: return sorted dictionary (negative/positive/neutral)
feedbacks = []
offset = 0
amount = self.__ask__('doGetWaitingFeedbacksCount')
while amount > 0:
rc = self.__ask__('doGetWaitingFeedbacks',
offset=offset, packageSize=200)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def silent(cmd, **kwargs):
"""Calls the given shell command. Output will not be displayed. Returns the status code. **Examples**: :: auxly.shell.silent("ls") """ |
return call(cmd, shell=True, stdout=NULL, stderr=NULL, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def has(cmd):
"""Returns true if the give shell command is available. **Examples**: :: auxly.shell.has("ls") # True """ |
helps = ["--help", "-h", "--version"]
if "nt" == os.name:
helps.insert(0, "/?")
fakecmd = "fakecmd"
cmderr = strerr(fakecmd).replace(fakecmd, cmd)
for h in helps:
hcmd = "%s %s" % (cmd, h)
if 0 == silent(hcmd):
return True
if len(listout(hcmd)) > 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 csvpretty(csvfile: csvfile=sys.stdin):
""" Pretty print a CSV file. """ |
shellish.tabulate(csv.reader(csvfile)) |
<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_key(self, path, geometry, filters, options):
"""Generates the thumbnail's key from it's arguments. If the arguments doesn't change the key will not chang... |
seed = u' '.join([
str(path),
str(geometry),
str(filters),
str(options),
]).encode('utf8')
return md5(seed).hexdigest() |
<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_source(self, path_or_url):
"""Returns the source image file descriptor. path_or_url: Path to the source image as an absolute path, a path relative to `se... |
if path_or_url.startswith(('http://', 'https://')):
try:
return urlopen(path_or_url)
except IOError:
return None
fullpath = path_or_url
if not os.path.isabs(path_or_url):
fullpath = os.path.join(self.base_path, path_or_url)
... |
<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_thumb(self, path, key, format):
"""Get the stored thumbnail if exists. path: path of the source image key: key of the thumbnail format: thumbnail's file ... |
thumbpath = self.get_thumbpath(path, key, format)
fullpath = os.path.join(self.out_path, thumbpath)
if os.path.isfile(fullpath):
url = self.get_url(thumbpath)
return Thumb(url, key)
return Thumb() |
<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_thumbpath(self, path, key, format):
"""Return the relative path of the thumbnail. path: path of the source image key: key of the thumbnail format: thumbn... |
relpath = os.path.dirname(path)
thumbsdir = self.get_thumbsdir(path)
name, _ = os.path.splitext(os.path.basename(path))
name = '{}.{}.{}'.format(name, key, format.lower())
return os.path.join(relpath, thumbsdir, 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 save(self, path, key, format, data):
"""Save a newly generated thumbnail. path: path of the source image key: key of the thumbnail format: thumbnail's file e... |
thumbpath = self.get_thumbpath(path, key, format)
fullpath = os.path.join(self.out_path, thumbpath)
self.save_thumb(fullpath, data)
url = self.get_url(thumbpath)
thumb = Thumb(url, key, fullpath)
return thumb |
<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_handler(cls, level, fmt, colorful, **kwargs):
"""Add a configured handler to the global logger.""" |
global g_logger
if isinstance(level, str):
level = getattr(logging, level.upper(), logging.DEBUG)
handler = cls(**kwargs)
handler.setLevel(level)
if colorful:
formatter = ColoredFormatter(fmt, datefmt='%Y-%m-%d %H:%M:%S')
else:
formatter = logging.Formatter(fmt, da... |
<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_filehandler(level, fmt, filename, mode, backup_count, limit, when):
"""Add a file handler to the global logger.""" |
kwargs = {}
# If the filename is not set, use the default filename
if filename is None:
filename = getattr(sys.modules['__main__'], '__file__', 'log.py')
filename = os.path.basename(filename.replace('.py', '.log'))
filename = os.path.join('/tmp', filename)
if not os.path.exis... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_logger(name=None):
"""Reload the global logger.""" |
global g_logger
if g_logger is None:
g_logger = logging.getLogger(name=name)
else:
logging.shutdown()
g_logger.handlers = []
g_logger.setLevel(logging.DEBUG) |
<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_logger(name=None, filename=None, mode='a', level='NOTSET:NOTSET', fmt= '%(asctime)s %(filename)s:%(lineno)d [PID:%(process)-5d THD:%(thread)-5d %(levelnam... |
level = level.split(':')
if len(level) == 1: # Both set to the same level
s_level = f_level = level[0]
else:
s_level = level[0] # StreamHandler log level
f_level = level[1] # FileHandler log level
init_logger(name=name)
add_streamhandler(s_level, fmt)
if with_file... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_log_funcs():
"""Import the common log functions from the global logger to the module.""" |
global g_logger
curr_mod = sys.modules[__name__]
for func_name in _logging_funcs:
func = getattr(g_logger, func_name)
setattr(curr_mod, func_name, func) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def powerupIndirector(interface):
""" A decorator for a powerup indirector from a single interface to a single in-memory implementation. The in-memory implementa... |
def decorator(cls):
zi.implementer(iaxiom.IPowerupIndirector)(cls)
cls.powerupInterfaces = [interface]
cls.indirect = _indirect
return cls
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lint(self, dataset=None, col=None, no_header=False, ignore_nfd=False, ignore_ws=False, linewise=False, no_lines=False):
""" Returns a string containi... |
reader = Reader(dataset, has_header=not no_header, ipa_col=col)
recog = Recogniser()
norm = Normaliser(nfc_chars=recog.get_nfc_chars())
for ipa_string, line_num in reader.gen_ipa_data():
ipa_string = norm.normalise(ipa_string, line_num)
recog.recognise(ipa_string, line_num)
rep = Reporter()
norm.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 parse_rune_links(html: str) -> dict: """A function which parses the main Runeforge website into dict format. Parameters html : str The string representation o... |
soup = BeautifulSoup(html, 'lxml')
# Champs with only a single runepage
single_page_raw = soup.find_all('li', class_='champion')
single_page = {re.split('\W+', x.a.div.div['style'])[-3].lower():
[x.a['href']] for x in single_page_raw if x.a is not None}
# Champs with two (o... |
<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_string(regex, s):
"""Find a string using a given regular expression. If the string cannot be found, returns None. The regex should contain one matching ... |
m = re.search(regex, s)
if m is None:
return None
return m.groups()[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 clean_text(s):
"""Removes all cruft from the text.""" |
SPACES_RE = re.compile(r'\s+')
SPECIAL_CHARS_RE = re.compile(r'[^\w\s\.\-\(\)]')
s = SPACES_RE.sub(' ', s)
s = s.strip()
s = SPECIAL_CHARS_RE.sub('', s)
return s |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_immoweb_link(url):
"""Parses an Immoweb estate detail URL and returns the Immoweb estate id. Returns a string with the Immoweb estate id. """ |
IMMOWEB_ID_RE = re.compile(r'.*?IdBien=([0-9]+).*?')
return IMMOWEB_ID_RE.match(url).groups()[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 parse_number(d, key, regex, s):
"""Find a number using a given regular expression. If the number is found, sets it under the key in the given dictionary. d -... |
result = find_number(regex, s)
if result is not None:
d[key] = result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def make_category_filter(categories, blank=True):
'''
Generates a dict representing a Factual filter matching any of the categories
passed.
The resulting filter uses $bw "begins with" operators to return all matching
subcategories. Because of this, passing a top level category removes the need
to pass any of it... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_type(self, value, spec):
""" Some well-educated format guessing. """ |
data_type = spec.get('type', 'string').lower().strip()
if data_type in ['bool', 'boolean']:
return value.lower() in BOOL_TRUISH
elif data_type in ['int', 'integer']:
try:
return int(value)
except (ValueError, TypeError):
return... |
<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_value(self, spec, row):
""" Returns the value or a dict with a 'value' entry plus extra fields. """ |
column = spec.get('column')
default = spec.get('default')
if column is None:
if default is not None:
return self.convert_type(default, spec)
return
value = row.get(column)
if is_empty(value):
if default is not 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_source(self, spec, row):
""" Sources can be specified as plain strings or as a reference to a column. """ |
value = self.get_value({'column': spec.get('source_url_column')}, row)
if value is not None:
return value
return spec.get('source_url') |
<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, data):
""" Load a single row of data and convert it into entities and relations. """ |
objs = {}
for mapper in self.entities:
objs[mapper.name] = mapper.load(self.loader, data)
for mapper in self.relations:
objs[mapper.name] = mapper.load(self.loader, data, objs) |
<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_v3(vec1, m):
"""Return a new Vec3 containing the sum of our x, y, z, and arg. If argument is a float or vec, addt it to our x, y, and z. Otherwise, treat... |
if type(m) in NUMERIC_TYPES:
return Vec3(vec1.x + m, vec1.y + m, vec1.z + m)
else:
return Vec3(vec1.x + m.x, vec1.y + m.y, vec1.z + m.z) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def translate_v3(vec, amount):
"""Return a new Vec3 that is translated version of vec.""" |
return Vec3(vec.x+amount, vec.y+amount, vec.z+amount) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scale_v3(vec, amount):
"""Return a new Vec3 that is a scaled version of vec.""" |
return Vec3(vec.x*amount, vec.y*amount, vec.z*amount) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dot_v3(v, w):
"""Return the dotproduct of two vectors.""" |
return sum([x * y for x, y in zip(v, w)]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def projection_as_vec_v3(v, w):
"""Return the signed length of the projection of vector v on vector w. Returns the full vector result of projection_v3(). """ |
proj_len = projection_v3(v, w)
return scale_v3(v, proj_len) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def point_to_line(point, segment_start, segment_end):
"""Given a point and a line segment, return the vector from the point to the closest point on the segment. ... |
# TODO: Needs unittests.
segment_vec = segment_end - segment_start
# t is distance along line
t = -(segment_start - point).dot(segment_vec) / (
segment_vec.length_squared())
closest_point = segment_start + scale_v3(segment_vec, t)
return point - closest_point |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cross_v3(vec_a, vec_b):
"""Return the crossproduct between vec_a and vec_b.""" |
return Vec3(vec_a.y * vec_b.z - vec_a.z * vec_b.y,
vec_a.z * vec_b.x - vec_a.x * vec_b.z,
vec_a.x * vec_b.y - vec_a.y * vec_b.x) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rotate_around_vector_v3(v, angle_rad, norm_vec):
""" rotate v around norm_vec by angle_rad.""" |
cos_val = math.cos(angle_rad)
sin_val = math.sin(angle_rad)
## (v * cosVal) +
## ((normVec * v) * (1.0 - cosVal)) * normVec +
## (v ^ normVec) * sinVal)
#line1: scaleV3(v,cosVal)
#line2: dotV3( scaleV3( dotV3(normVec,v), 1.0-cosVal), normVec)
#line3: scaleV3( crossV3( v,normVec), sinVal... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ave_list_v3(vec_list):
"""Return the average vector of a list of vectors.""" |
vec = Vec3(0, 0, 0)
for v in vec_list:
vec += v
num_vecs = float(len(vec_list))
vec = Vec3(vec.x / num_vecs, vec.y / num_vecs, vec.z / num_vecs)
return vec |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _float_almost_equal(float1, float2, places=7):
"""Return True if two numbers are equal up to the specified number of "places" after the decimal point. """ |
if round(abs(float2 - float1), places) == 0:
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 almost_equal(self, v2, places=7):
"""When comparing for equality, compare floats up to a limited precision specified by "places". """ |
try:
return (
len(self) == len(v2) and
_float_almost_equal(self.x, v2.x, places) and
_float_almost_equal(self.y, v2.y, places) and
_float_almost_equal(self.z, v2.z, places))
except:
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 dot(self, w):
"""Return the dotproduct between self and another vector.""" |
return sum([x * y for x, y in zip(self, w)]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cross(self, vec):
"""Return the crossproduct between self and vec.""" |
return Vec3(self.y * vec.z - self.z * vec.y,
self.z * vec.x - self.x * vec.z,
self.x * vec.y - self.y * vec.x) |
<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, x, y, z):
"""Set x, y, and z components. Also return self. """ |
self.x = x
self.y = y
self.z = z
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 neg(self):
"""Negative value of all components.""" |
self.x = -self.x
self.y = -self.y
self.z = -self.z |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def put_stream(self, rel_path, metadata=None, cb=None):
"""return a file object to write into the cache. The caller is responsibile for closing the stream """ |
from io import IOBase
if not isinstance(rel_path, basestring):
rel_path = rel_path.cache_key
repo_path = os.path.join(self.cache_dir, rel_path.strip("/"))
if not os.path.isdir(os.path.dirname(repo_path)):
os.makedirs(os.path.dirname(repo_path))
if os.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def size(self):
'''Return the size of all of the files referenced in the database'''
c = self.database.cursor()
r = c.execute("SELECT sum(size) FROM files")
try:
size = int(r.fetchone()[0])
except TypeError:
size = 0
return size |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _free_up_space(self, size, this_rel_path=None):
'''If there are not size bytes of space left, delete files
until there is
Args:
size: size of the current file
this_rel_path: rel_pat to the current file, so we don't delete it.
'''
# Amount of space w... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def verify(self):
'''Check that the database accurately describes the state of the repository'''
c = self.database.cursor()
non_exist = set()
no_db_entry = set(os.listdir(self.cache_dir))
try:
no_db_entry.remove('file_database.db')
no_db_entry.remove('fi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def put_stream(self, rel_path, metadata=None, cb=None):
"""return a file object to write into the cache. The caller is responsibile for closing the stream. Bad t... |
class flo:
def __init__(self, this, sink, upstream, repo_path):
self.this = this
self.sink = sink
self.upstream = upstream
self.repo_path = repo_path
@property
def repo_path(self):
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 create_proxy(self, this, message):
"""Create proxy for an actor. `message` has the form:: {'tag': 'create_proxy', } """ |
actor = message['actor']
proxy = self._create_proxy(this, actor)
message['customer'] << proxy |
<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_caselessly(dictionary, sought):
"""Find the sought key in the given dictionary regardless of case 9 """ |
try:
return dictionary[sought]
except KeyError:
caseless_keys = {k.lower(): k for k in dictionary.keys()}
real_key = caseless_keys[sought.lower()] # allow any KeyError here
return dictionary[real_key] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def append_value(dictionary, key, item):
"""Append those items to the values for that key""" |
items = dictionary.get(key, [])
items.append(item)
dictionary[key] = items |
<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_values(dictionary, key, items):
"""Extend the values for that key with the items""" |
values = dictionary.get(key, [])
try:
values.extend(items)
except TypeError:
raise TypeError('Expected a list, got: %r' % items)
dictionary[key] = 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 run(self):
'''Fetch and dispatch jobs as long as the system is running.
This periodically checks the :class:`rejester.TaskMaster` mode
and asks it for more work. It will normally run forever in a
loop until the mode becomes
:attr:`~rejester.TaskMaster.TERMINATE`, at which p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def run_one(self, set_title=False):
'''Get exactly one job, run it, and return.
Does nothing (but returns :const:`False`) if there is no work
to do. Ignores the global mode; this will do work even
if :func:`rejester.TaskMaster.get_mode` returns
:attr:`~rejester.TaskMaster.TERMI... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def as_child(cls, global_config, parent=None):
'''Run a single job in a child process.
This method never returns; it always calls :func:`sys.exit`
with an error code that says what it did.
'''
try:
setproctitle('rejester worker')
random.seed() # otherwi... |
<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_signal_handlers(self):
'''Set some signal handlers.
These react reasonably to shutdown requests, and keep the
logging child alive.
'''
def handler(f):
def wrapper(signum, backtrace):
return f()
return wrapper
self.old_sig... |
<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, level, message):
'''Write a log message via the child process.
The child process must already exist; call :meth:`live_log_child`
to make sure. If it has died in a way we don't expect then
this will raise :const:`signal.SIGPIPE`.
'''
if self.log_fd 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 debug(self, group, message):
'''Maybe write a debug-level log message.
In particular, this gets written if the hidden `debug_worker`
option contains `group`.
'''
if group in self.debug_worker:
if 'stdout' in self.debug_worker:
print message
... |
<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_spewer(self, gconfig, fd):
'''Child process to manage logging.
This reads pairs of lines from `fd`, which are alternating
priority (Python integer) and message (unformatted string).
'''
setproctitle('rejester fork_worker log task')
yakonfig.set_default_config([y... |
<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_log_child(self):
'''Start the logging child process.'''
self.stop_log_child()
gconfig = yakonfig.get_global_config()
read_end, write_end = os.pipe()
pid = os.fork()
if pid == 0:
# We are the child
self.clear_signal_handlers()
... |
<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_log_child(self):
'''Stop the logging child process.'''
if self.log_fd:
os.close(self.log_fd)
self.log_fd = None
if self.log_child:
try:
self.debug('children', 'stopping log child with pid {0}'
.format(self.lo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def live_log_child(self):
'''Start the logging child process if it died.'''
if not (self.log_child and self.pid_is_alive(self.log_child)):
self.start_log_child() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def do_some_work(self, can_start_more):
'''Run one cycle of the main loop.
If the log child has died, restart it. If any of the worker
children have died, collect their status codes and remove them
from the child set. If there is a worker slot available, start
exactly one chil... |
<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_spinning_children(self):
'''Stop children that are working on overdue jobs.'''
child_jobs = self.task_master.get_child_work_units(self.worker_id)
# We will kill off any jobs that are due before "now". This
# isn't really now now, but now plus a grace period to make
# s... |
<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_gracefully(self):
'''Refuse to start more processes.
This runs in response to SIGINT or SIGTERM; if this isn't a
background process, control-C and a normal ``kill`` command
cause this.
'''
if self.shutting_down:
self.log(logging.INFO,
... |
<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_all_children(self):
'''Kill all workers.'''
# There's an unfortunate race condition if we try to log this
# case: we can't depend on the logging child actually receiving
# the log message before we kill it off. C'est la vie...
self.stop_log_child()
for pid in 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 scram(self):
'''Kill all workers and die ourselves.
This runs in response to SIGABRT, from a specific invocation
of the ``kill`` command. It also runs if
:meth:`stop_gracefully` is called more than once.
'''
self.stop_all_children()
signal.signal(signal.SIG... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def run(self):
'''Run the main loop.
This is fairly invasive: it sets a bunch of signal handlers
and spawns off a bunch of child processes.
'''
setproctitle('rejester fork_worker for namespace {0}'
.format(self.config.get('namespace', None)))
self.s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instance():
""" Creates an EC2 instance from an Ubuntu AMI and configures it as a Django server with nginx + gunicorn """ |
# Record the starting time and print a starting message
start_time = time.time()
print(_green("Started..."))
# Use boto to create an EC2 instance
env.host_string = _create_ec2_instance()
print(_green("Waiting 30 seconds for server to boot..."))
time.sleep(30)
# Configure the insta... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _run_task(task, start_message, finished_message):
""" Tasks a task from tasks.py and runs through the commands on the server """ |
# Get the hosts and record the start time
env.hosts = fabconf['EC2_INSTANCES']
start = time.time()
# Check if any hosts exist
if env.hosts == []:
print("There are EC2 instances defined in project_conf.py, please add some instances and try again")
print("or run 'fab spawn_instance'... |
<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, configurable, config=None, **kwargs):
'''Create a sub-object of this factory.
Instantiates the `configurable` object with the current saved
:attr:`config`. This essentially translates to
``configurable(**config)``, except services defined in the
parent and requ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def from_obj(cls, obj, any_configurable=False):
'''Create a proxy object from a callable.
If `any_configurable` is true, `obj` takes a parameter named
``config``, and `obj` smells like it implements
:class:`yakonfig.Configurable` (it has a
:attr:`~yakonfig.Configurable.config_na... |
<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_config(self, config, name=''):
'''Check that the configuration for this object is valid.
This is a more restrictive check than for most :mod:`yakonfig`
objects. It will raise :exc:`yakonfig.ConfigurationError` if
`config` contains any keys that are not in the underlying
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def inspect_obj(obj):
'''Learn what there is to be learned from our target.
Given an object at `obj`, which must be a function, method or
class, return a configuration *discovered* from the name of
the object and its parameter list. This function is
responsible for doing runtime... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def modulepath(filename):
""" Find the relative path to its module of a python file if existing. filename string, name of a python file """ |
filepath = os.path.abspath(filename)
prepath = filepath[:filepath.rindex('/')]
postpath = '/'
if prepath.count('/') == 0 or not os.path.exists(prepath + '/__init__.py'):
flag = False
else:
flag = True
while True:
if prepath.endswith('/lib') or prepath.endswith('/bin') or... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_message_type(message_type):
""" Get printable version for message type :param message_type: Message type :type message_type: int :return: Printable ve... |
if message_type == MsgType.NOT_SET:
return "NOT_SET"
elif message_type == MsgType.ACK:
return "ACK"
elif message_type == MsgType.JOIN:
return "JOIN"
elif message_type == MsgType.UNJOIN:
return "UNJOIN"
elif message_type == MsgType.CONFIG:
return "CONFIG"
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_data(data):
""" Format bytes for printing :param data: Bytes :type data: None | bytearray | str :return: Printable version :rtype: unicode """ |
if data is None:
return None
return u":".join([u"{:02x}".format(ord(c)) for c 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 guess_message_type(message):
""" Guess the message type based on the class of message :param message: Message to guess the type for :type message: APPMessage... |
if isinstance(message, APPConfigMessage):
return MsgType.CONFIG
elif isinstance(message, APPJoinMessage):
return MsgType.JOIN
elif isinstance(message, APPDataMessage):
# All inheriting from this first !!
return MsgType.DATA
elif isinstance(message, APPUpdateMessage):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def timestamp_localize(value):
""" Save timestamp as utc :param value: Timestamp (in UTC or with tz_info) :type value: float | datetime.datetime :return: Localiz... |
if isinstance(value, datetime.datetime):
if not value.tzinfo:
value = pytz.UTC.localize(value)
else:
value = value.astimezone(pytz.UTC)
# Assumes utc (and add the microsecond part)
value = calendar.timegm(value.timetuple()) + \
... |
<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_timestamp_to_current(self):
""" Set timestamp to current time utc :rtype: None """ |
# Good form to add tzinfo
self.timestamp = pytz.UTC.localize(datetime.datetime.utcnow()) |
<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, obj):
""" Set this instance up based on another instance :param obj: Instance to copy from :type obj: APPMessage :rtype: None """ |
if isinstance(obj, APPMessage):
self._header = obj._header
self._payload = obj._payload |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pack_people(people):
""" Pack people into a network transmittable format :param people: People to pack :type people: list[paps.people.People] :return: The p... |
res = bytearray()
bits = bytearray([1])
for person in people:
bits.extend(person.to_bits())
aByte = 0
for i, bit in enumerate(bits[::-1]):
mod = i % 8
aByte |= bit << mod
if mod == 7 or i == len(bits) - 1:
res.app... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_dynacRepr(cls, pynacRepr):
""" Construct a ``Quad`` instance from the Pynac lattice element """ |
L = float(pynacRepr[1][0][0])
B = float(pynacRepr[1][0][1])
aperRadius = float(pynacRepr[1][0][2])
return cls(L, B, aperRadius) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dynacRepresentation(self):
""" Return the Pynac representation of this quadrupole instance. """ |
return ['QUADRUPO', [[self.L.val, self.B.val, self.aperRadius.val]]] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_dynacRepr(cls, pynacRepr):
""" Construct a ``CavityAnalytic`` instance from the Pynac lattice element """ |
cavID = int(pynacRepr[1][0][0])
xesln = float(pynacRepr[1][1][0])
phase = float(pynacRepr[1][1][1])
fieldReduction = float(pynacRepr[1][1][2])
isec = int(pynacRepr[1][1][3])
return cls(phase, fieldReduction, cavID, xesln, isec) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def adjustPhase(self, adjustment):
""" Adjust the accelerating phase of the cavity by the value of ``adjustment``. The adjustment is additive, so a value of ``sc... |
self.phase = self.phase._replace(val = self.phase.val + adjustment) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scaleField(self, scalingFactor):
""" Adjust the accelerating field of the cavity by the value of ``scalingFactor``. The adjustment is multiplicative, so a va... |
oldField = self.fieldReduction.val
newField = 100.0 * (scalingFactor * (1.0 + oldField/100.0) - 1.0)
self.fieldReduction = self.fieldReduction._replace(val = newField) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.