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 __audiorender_thread(self):
""" Thread that takes care of the audio rendering. Do not call directly, but only as the target of a thread. """ |
new_audioframe = None
logger.debug("Started audio rendering thread.")
while self.status in [PLAYING,PAUSED]:
# Retrieve audiochunk
if self.status == PLAYING:
if new_audioframe is None:
# Get a new frame from the audiostream, skip to the next one
# if the current one gives a problem
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 search(self, keyword):
'''Get search results for a specific keyword'''
if type(keyword) != unicode: q = keyword.decode('utf-8')
req = self.fetch(self.search_url, {'q':q.encode('gbk')})
if not req: return None
html = req.content.decode('gbk').encode('utf-8')
soup = Bea... |
<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_top_keywords(self, up=True):
'''Get top keywords for all the categories'''
engine = models.postgres_engine()
session = models.create_session(engine)
#threadPool = ThreadPool(5)
for cat in session.query(models.Category):
if not cat.level: continue
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 cat_top_keywords(self, session, cat, up=True, offset=0, offsets=[]):
'''Get top keywords in a specific category'''
print 'CAT:%s, level:%s'%(str(cat), str(cat.level))
print 'OFFSET: %d'%offset
response = []
if not offsets or offset==0:
url = 'http://top.taobao.c... |
<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_cats(self):
'''Get top keywords categories'''
start_url = 'http://top.taobao.com/index.php?from=tbsy'
rs = self.fetch(start_url)
if not rs: return None
soup = BeautifulSoup(rs.content, convertEntities=BeautifulSoup.HTML_ENTITIES, markupMassage=hexentityMassage)
ca... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render_to_cairo_context(cairo_context, papersize_tuple, layout):
"""Renders the given layout manager on a page of the given context. Assumes the given contex... |
try:
cairo_context.save()
cairo_context.translate(0, papersize_tuple[1])
cairo_context.scale(1, -1)
layout.render(
Rectangle(0, 0, *papersize_tuple),
dict(output=CairoOutput(cairo_context))
)
finally:
cairo_context.restore() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prompt(self):
"""Returns the UTF-8 encoded prompt string.""" |
if self.prompt_string is not None:
return self.prompt_string
if not self.color_enabled:
return (' '.join(self.command) + '>> ').encode('utf8')
color = '34'
sub_color = '37'
prompt_cmd = [
self.colorize('1;' + color, part) if part != self.cm... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def title(self):
"""Returns the UTF-8 encoded title""" |
return (u'[{}] {}>>'.format(
os.path.split(os.path.abspath('.'))[-1],
u' '.join(self.command))).encode('utf8') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query_relative(self, query, event_time=None, relative_duration_before=None, relative_duration_after=None):
"""Perform the query and calculate the time range ... |
assert event_time is None or isinstance(event_time, datetime.datetime)
assert relative_duration_before is None or isinstance(relative_duration_before, str)
assert relative_duration_after is None or isinstance(relative_duration_after, str)
if event_time is None:
# use now as... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def json(self):
"""Returns the search results as a list of JSON objects.""" |
if self.search_results is None:
return None
result = []
for row in self.search_results['rows']:
obj = {}
for index in range(0, len(self.search_results['fields'])):
obj[self.search_results['fields'][index]] = row[index]
result.appe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def draw_text(self, text:str, x:float, y:float, *, font_name:str, font_size:float, fill:Color) -> None: """Draws the given text at x,y.""" |
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 draw_line( self, x0:float, y0:float, x1:float, y1:float, *, stroke:Color, stroke_width:float=1, stroke_dash:typing.Sequence=None ) -> None: """Draws the given... |
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 draw_rect( self, x:float, y:float, w:float, h:float, *, stroke:Color=None, stroke_width:float=1, stroke_dash:typing.Sequence=None, fill:Color=None ) -> None: ... |
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 draw_image( self, img_filename:str, x:float, y:float, w:float, h:float ) -> None: """Draws the given image.""" |
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 draw_polygon( self, *pts, close_path:bool=True, stroke:Color=None, stroke_width:float=1, stroke_dash:typing.Sequence=None, fill:Color=None ) -> None: """Draws... |
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 clip_rect(self, x:float, y:float, w:float, h:float) -> None: """Clip further output to this rect.""" |
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 parse_manifest(template_lines):
"""List of file names included by the MANIFEST.in template lines.""" |
manifest_files = distutils.filelist.FileList()
for line in template_lines:
if line.strip():
manifest_files.process_template_line(line)
return manifest_files.files |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _wx_two_step_creation_on_classic(cls):
""" Patch the wxPython Classic class to behave like a wxPython Phoenix class on a 2-step creation process. On wxPython... |
cls_init = cls.__init__
cls_create = cls.Create
@functools.wraps(cls_init)
def __init__(self, *args, **kwargs):
if args or kwargs:
cls_init(self, *args, **kwargs)
else: # 2-step creation
new_self = getattr(wx, "Pre" + cls.__name__)()
for pair in vars... |
<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_pipeline(url, pipeline_id, auth, verify_ssl, runtime_parameters={}):
"""Start a running pipeline. The API waits for the pipeline to be fully started. A... |
start_result = requests.post(url + '/' + pipeline_id + '/start',
headers=X_REQ_BY, auth=auth, verify=verify_ssl, json=runtime_parameters)
start_result.raise_for_status()
logging.info('Pipeline start requested.')
poll_pipeline_status(STATUS_RUNNING, url, pipeline_id, au... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def export_pipeline(url, pipeline_id, auth, verify_ssl):
"""Export the config and rules for a pipeline. Args: url (str):
the host url in the form 'http://host:p... |
export_result = requests.get(url + '/' + pipeline_id + '/export', headers=X_REQ_BY, auth=auth, verify=verify_ssl)
if export_result.status_code == 404:
logging.error('Pipeline not found: ' + pipeline_id)
export_result.raise_for_status()
return export_result.json() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pipeline_status(url, pipeline_id, auth, verify_ssl):
"""Retrieve the current status for a pipeline. Args: url (str):
the host url in the form 'http://host:p... |
status_result = requests.get(url + '/' + pipeline_id + '/status', headers=X_REQ_BY, auth=auth, verify=verify_ssl)
status_result.raise_for_status()
logging.debug('Status request: ' + url + '/status')
logging.debug(status_result.json())
return status_result.json() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def preview_status(url, pipeline_id, previewer_id, auth, verify_ssl):
"""Retrieve the current status for a preview. Args: url (str):
the host url in the form 'h... |
preview_status = requests.get(url + '/' + pipeline_id + '/preview/' + previewer_id + "/status", headers=X_REQ_BY, auth=auth, verify=verify_ssl)
preview_status.raise_for_status()
logging.debug(preview_status.json())
return preview_status.json() |
<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_pipeline(url, pipeline_id, auth, verify_ssl):
"""Stop a running pipeline. The API waits for the pipeline to be 'STOPPED' before returning. Args: url (st... |
stop_result = requests.post(url + '/' + pipeline_id + '/stop', headers=X_REQ_BY, auth=auth, verify=verify_ssl)
stop_result.raise_for_status()
logging.info("Pipeline stop requested.")
poll_pipeline_status(STATUS_STOPPED, url, pipeline_id, auth, verify_ssl)
logging.info('Pipeline stopped.')
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 validate_pipeline(url, pipeline_id, auth, verify_ssl):
"""Validate a pipeline and show issues. Args: url (str):
the host url in the form 'http://host:port/'... |
validate_result = requests.get(url + '/' + pipeline_id + '/validate', headers=X_REQ_BY, auth=auth, verify=verify_ssl)
validate_result.raise_for_status()
previewer_id = validate_result.json()['previewerId']
poll_validation_status(url, pipeline_id, previewer_id, auth, verify_ssl)
preview_result = 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 import_pipeline(url, pipeline_id, auth, json_payload, verify_ssl, overwrite = False):
"""Import a pipeline. This will completely overwrite the existing pipel... |
parameters = { 'overwrite' : overwrite }
import_result = requests.post(url + '/' + pipeline_id + '/import', params=parameters,
headers=X_REQ_BY, auth=auth, verify=verify_ssl, json=json_payload)
if import_result.status_code != 200:
logging.error('Import error respo... |
<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_pipeline(url, auth, json_payload, verify_ssl):
"""Create a new pipeline. Args: url (str):
the host url in the form 'http://host:port/'. auth (tuple):... |
title = json_payload['pipelineConfig']['title']
description = json_payload['pipelineConfig']['description']
params = {'description':description, 'autoGeneratePipelineId':True}
logging.info('No destination pipeline ID provided. Creating a new pipeline: ' + title)
put_result = requests.put(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 system_info(url, auth, verify_ssl):
"""Retrieve SDC system information. Args: url (str):
the host url. auth (tuple):
a tuple of username, and password. """ |
sysinfo_response = requests.get(url + '/info', headers=X_REQ_BY, auth=auth, verify=verify_ssl)
sysinfo_response.raise_for_status()
return sysinfo_response.json() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def export_pipeline(conf, args):
"""Export a pipeline to json.""" |
# Export the source pipeline and save it to file
src = conf.config['instances'][args.src_instance]
src_url = api.build_pipeline_url(build_instance_url(src))
src_auth = tuple([conf.creds['instances'][args.src_instance]['user'],
conf.creds['instances'][args.src_instance]['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 import_pipeline(conf, args):
"""Import a pipeline from json.""" |
with open(args.pipeline_json) as pipeline_json:
dst = conf.config['instances'][args.dst_instance]
dst_url = api.build_pipeline_url(build_instance_url(dst))
dst_auth = tuple([conf.creds['instances'][args.dst_instance]['user'],
conf.creds['instances'][args.dst_instan... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def promote_pipeline(conf, args):
"""Export a pipeline from a lower environment and import into higher environment.""" |
src = conf.config['instances'][args.src_instance]
src_url = api.build_pipeline_url(build_instance_url(src))
src_auth = tuple([conf.creds['instances'][args.src_instance]['user'], conf.creds['instances'][args.src_instance]['pass']])
verify_ssl = src.get('verify_ssl', True)
export_json = api.export_pi... |
<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_pipeline(conf, args):
"""Start a pipeline""" |
host = conf.config['instances'][args.host_instance]
url = api.build_pipeline_url(build_instance_url(host))
auth = tuple([conf.creds['instances'][args.host_instance]['user'], conf.creds['instances'][args.host_instance]['pass']])
runtime_parameters = {}
verify_ssl = host.get('verify_ssl', True)
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 system_info(conf, args):
"""Retieve SDC system information.""" |
src = conf.config['instances'][args.src]
src_url = api.build_system_url(build_instance_url(src))
src_auth = tuple([conf.creds['instances'][args.src]['user'],
conf.creds['instances'][args.src]['pass']])
verify_ssl = src.get('verify_ssl', True)
sysinfo_json = api.system_info(src... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_pipeline(conf, args):
"""Validate a pipeline configuration.""" |
host = conf.config['instances'][args.host_instance]
host_url = api.build_pipeline_url(build_instance_url(host))
host_auth = tuple([conf.creds['instances'][args.host_instance]['user'],
conf.creds['instances'][args.host_instance]['pass']])
verify_ssl = host.get('verify_ssl', 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 extractGlobalParameters(self, dna, bp, frames=None, paxis='Z', masked=False):
"""Extract the parameters for calculations .. currentmodule:: dnaMD Parameters ... |
frames = self._validateFrames(frames)
if frames[1] == -1:
frames[1] = None
if (len(bp) != 2):
raise ValueError("bp should be a list containing first and last bp of a segment. See, documentation!!!")
if bp[0] > bp[1]:
raise ValueError("bp should be ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getStretchTwistBendModulus(self, bp, frames=None, paxis='Z', masked=True, matrix=False):
r"""Calculate Bending-Stretching-Twisting matrix It calculate elasti... |
if self.esType == 'ST':
raise KeyError(' Use dnaEY.getStretchTwistModulus for Stretching-Twisting modulus.')
frames = self._validateFrames(frames)
name = '{0}-{1}-{2}-{3}'.format(bp[0], bp[1], frames[0], frames[1])
if name not in self.esMatrix:
time, array =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getModulusByTime(self, bp, frameGap, masked=False, paxis='Z', outFile=None):
r"""Calculate moduli as a function of time for convergence check It can be used ... |
if self.esType == 'BST':
props_name = [ 'bend-1', 'bend-2', 'stretch', 'twist', 'bend-1-bend-2',
'bend-2-stretch', 'stretch-twist', 'bend-1-stretch',
'bend-2-twist', 'bend-1-twist']
else:
props_name = ['stretch', 'twist', '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 getGlobalDeformationEnergy(self, bp, complexDna, freeDnaFrames=None, boundDnaFrames=None, paxis='Z', which='all', masked=False, outFile=None):
r"""Deformatio... |
if self.esType == 'BST':
energyTerms = self.enGlobalTypes
else:
energyTerms = self.enGlobalTypes[:5]
if isinstance(which, str):
if which != 'all':
raise ValueError('Either use "all" or use list of terms from this {0} list \n.'.format(energyTe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _calcEnergyStretchTwist(self, diff, es, which):
r"""Calculate energy for ``estype='ST'`` using a difference vector. It is called in :meth:`dnaEY.getGlobalDef... |
if which not in self.enGlobalTypes[:5]:
raise ValueError('{0} is not a supported energy keywords.\n Use any of the following: \n {1}'.format(
which, self.enGlobalTypes[:5]))
energy = None
if which == 'full':
temp = np.matrix(diff)
energy = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calculateLocalElasticity(self, bp, frames=None, helical=False, unit='kT'):
r"""Calculate local elastic matrix or stiffness matrix for local DNA segment .. no... |
acceptedUnit = ['kT', 'kJ/mol', 'kcal/mol']
if unit not in acceptedUnit:
raise ValueError(" {0} not accepted. Use any of the following: {1} ".format(unit, acceptedUnit))
frames = self._validateFrames(frames)
name = '{0}-{1}-{2}-{3}-local-{4}'.format(bp[0], bp[1], frames[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 getLocalElasticityByTime(self, bp, frameGap, helical=False, unit='kT', outFile=None):
r"""Calculate local elastic properties as a function of time for conver... |
if helical:
props_name = helical_local_props_vector
else:
props_name = local_props_vector
time, elasticity = [], OrderedDict()
for name in props_name:
elasticity[name] = []
length = len(self.dna.time[:])
for i in range(frameGap, leng... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calculateLocalElasticitySegments(self, bp, span=2, frameGap=None, helical=False, unit='kT', err_type='block', tool='gmx analyze', outFile=None):
"""Calculate... |
if helical:
props_name = helical_local_props_vector
else:
props_name = local_props_vector
segments, errors, elasticities = [], OrderedDict(), OrderedDict()
for name in props_name:
elasticities[name] = []
errors[name] = []
for s 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 getLocalDeformationEnergy(self, bp, complexDna, freeDnaFrames=None, boundDnaFrames=None, helical=False, unit='kT', which='all', outFile=None):
r"""Deformatio... |
if helical:
energyTerms = ['full', 'diag', 'x-disp', 'y-disp', 'h-rise', 'inclination', 'tip', 'h-twist']
else:
energyTerms = ['full', 'diag', 'shift', 'slide', 'rise', 'tilt', 'roll', 'twist']
if isinstance(which, str):
if which != 'all':
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 _calcLocalEnergy(self, diff, es, which):
r"""Calculate local deformation energy using a difference vector. It is called in :meth:`dnaEY.getLocalDeformationEn... |
if which not in self.enLocalTypes:
raise ValueError('{0} is not a supported energy keywords.\n Use any of the following: \n {1}'.format(
which, self.enLocalTypes))
energy = None
if which == 'full':
temp = np.matrix(diff)
energy = 0.5 * ((te... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_variables(href):
"""Return a list of variable names used in a URI template.""" |
patterns = [re.sub(r'\*|:\d+', '', pattern)
for pattern in re.findall(r'{[\+#\./;\?&]?([^}]+)*}', href)]
variables = []
for pattern in patterns:
for part in pattern.split(","):
if not part in variables:
variables.append(part)
return variables |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def url(self, **kwargs):
"""Returns a URL for the link with optional template expansion. If the link is marked as templated, the href will be expanded according ... |
if self.is_templated:
return uritemplate.expand(self.template, kwargs)
else:
return self.template |
<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_object(cls, o, base_uri):
"""Returns a new ``Link`` based on a JSON object or array. Arguments: - ``o``: a dictionary holding the deserializated JSON fo... |
if isinstance(o, list):
if len(o) == 1:
return cls.from_object(o[0], base_uri)
return [cls.from_object(x, base_uri) for x in o]
return cls(o, base_uri) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def install_mediaroom_protocol(responses_callback, box_ip=None):
"""Install an asyncio protocol to process NOTIFY messages.""" |
from . import version
_LOGGER.debug(version)
loop = asyncio.get_event_loop()
mediaroom_protocol = MediaroomProtocol(responses_callback, box_ip)
sock = create_socket()
await loop.create_datagram_endpoint(lambda: mediaroom_protocol, sock=sock)
return mediaroom_protocol |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tune(self):
"""XML node representing tune.""" |
if self._node.get('activities'):
tune = self._node['activities'].get('tune')
if type(tune) is collections.OrderedDict:
return tune
elif type(tune) is list:
return tune[0]
return tune
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 stopped(self):
"""Return if the stream is stopped.""" |
if self.tune and self.tune.get('@stopped'):
return True if self.tune.get('@stopped') == 'true' else False
else:
raise PyMediaroomError("No information in <node> about @stopped") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def timeshift(self):
"""Return if the stream is a timeshift.""" |
if self.tune and self.tune.get('@src'):
return True if self.tune.get('@src').startswith('timeshift') else False
else:
raise PyMediaroomError("No information in <node> about @src") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def recorded(self):
"""Return if the stream is a recording.""" |
if self.tune and self.tune.get('@src'):
return True if self.tune.get('@src').startswith('mbr') else False
else:
raise PyMediaroomError("No information in <node> about @src") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def device_uuid(self):
"""Return device UUID.""" |
if self._device:
return self._device
return GEN_ID_FORMAT.format(self.src_ip) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def datagram_received(self, data, addr):
"""Datagram received callback.""" |
#_LOGGER.debug(data)
if not self.box_ip or self.box_ip == addr[0]:
self.responses(MediaroomNotify(addr, 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 error_received(self, exception):
"""Datagram error callback.""" |
if exception is None:
pass
else:
import pprint
pprint.pprint(exception)
_LOGGER.error('Error received: %s', exception) |
<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_session(self, sessionkey, refresh_token=None):
'''
Refresh Session Token
'''
if not refresh_token:
refresh_token = sessionkey
params = {
'appkey' : self.API_KEY,
'sessionkey' : sessionkey,
'refresh_token': refresh_token... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pause(self):
""" Pauses the clock to continue running later. Saves the duration of the current interval in the previous_intervals list.""" |
if self.status == RUNNING:
self.status = PAUSED
self.previous_intervals.append(time.time() - self.interval_start)
self.current_interval_duration = 0.0
elif self.status == PAUSED:
self.interval_start = time.time()
self.status = RUNNING |
<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):
""" Starts the clock from 0. Uses a separate thread to handle the timing functionalities. """ |
if not hasattr(self,"thread") or not self.thread.isAlive():
self.thread = threading.Thread(target=self.__run)
self.status = RUNNING
self.reset()
self.thread.start()
else:
print("Clock already running!") |
<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):
""" Internal function that is run in a separate thread. Do not call directly. """ |
self.interval_start = time.time()
while self.status != STOPPED:
if self.status == RUNNING:
self.current_interval_duration = time.time() - self.interval_start
# If max_duration is set, stop the clock if it is reached
if self.max_duration and self.time > self.max_duration:
self.status == STOPPED
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def current_frame(self):
""" The current frame number that should be displayed.""" |
if not self.__fps:
raise RuntimeError("fps not set so current frame number cannot be"
" calculated")
else:
return int(self.__fps * self.time) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fps(self,value):
""" Sets the frames per second of the current movie the clock is used for. Parameters value : float The fps value. """ |
if not value is None:
if not type(value) == float:
raise ValueError("fps needs to be specified as a float")
if value<1.0:
raise ValueError("fps needs to be greater than 1.0")
self.__fps = 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 max_duration(self,value):
""" Sets the value of max duration Parameters value : float The value for max_duration Raises ------ TypeError If... |
if not value is None:
if not type(value) in [float, int]:
raise TypeError("max_duration needs to be specified as a number")
if value<1.0:
raise ValueError("max_duration needs to be greater than 1.0")
value = float(value)
self.__max_duration = 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_shared(fname, encoding="utf-8"):
""" Loads the string data from a text file that was packaged as a data file in the distribution. Uses the setuptools ``p... |
relative_path = "share/dose/v{0}/{1}".format(__version__, fname)
prefixed_path = os.path.join(sys.prefix, *relative_path.split("/"))
# Look for the file directly on sys.prefix
try:
return "\n".join(read_plain_text(prefixed_path, encoding=encoding))
except IOError:
pass
# Homeb... |
<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_agents(self, state_id=None, limit_neighbors=False):
"""Returns list of agents based on their state and connectedness Parameters state_id : int, str, or a... |
if limit_neighbors:
agents = self.global_topology.neighbors(self.id)
else:
agents = self.get_all_nodes()
if state_id is None:
return [self.global_topology.node[_]['agent'] for _ in agents] # return all regardless of state
else:
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 add_node(self, agent_type=None, state=None, name='network_process', **state_params):
"""Add a new node to the current network Parameters agent_type : Network... |
agent_id = int(len(self.global_topology.nodes()))
agent = agent_type(self.env, agent_id=agent_id, state=state, name=name, **state_params)
self.global_topology.add_node(agent_id, {'agent': agent})
return agent_id |
<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_edge(self, agent_id1, agent_id2, edge_attr_dict=None, *edge_attrs):
""" Add an edge between agent_id1 and agent_id2. agent_id1 and agent_id2 correspond t... |
if agent_id1 in self.global_topology.nodes(data=False):
if agent_id2 in self.global_topology.nodes(data=False):
self.global_topology.add_edge(agent_id1, agent_id2, edge_attr_dict=edge_attr_dict, *edge_attrs)
else:
raise ValueError('\'agent_id2\'[{}] not 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 _make_request(self, conn, method, url, timeout=_Default, **httplib_request_kw):
""" Perform a request on a given httplib connection object taken from our poo... |
self.num_requests += 1
if timeout is _Default:
timeout = self.timeout
conn.request(method, url, **httplib_request_kw)
conn.sock.settimeout(timeout)
httplib_response = conn.getresponse()
log.debug("\"%s %s %s\" %s %s" %
(method, 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 is_same_host(self, url):
""" Check if the given ``url`` is a member of the same host as this conncetion pool. """ |
# TODO: Add optional support for socket.gethostbyname checking.
return (url.startswith('/') or
get_host(url) == (self.scheme, self.host, self.port)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def can_document_member(cls, member, membername, isattr, parent):
"""Called to see if a member can be documented by this documenter.""" |
if not super().can_document_member(member, membername, isattr, parent):
return False
return iscoroutinefunction(member) |
<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(context, request, key=None):
"""Return all registry items if key is None, otherwise try to fetch the registry key """ |
registry_records = api.get_registry_records_by_keyword(key)
# Prepare batch
size = req.get_batch_size()
start = req.get_batch_start()
batch = api.make_batch(registry_records, size, start)
return {
"pagesize": batch.get_pagesize(),
"next": batch.make_next_url(),
"previo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge_kwargs(local_kwarg, default_kwarg):
"""Merges kwarg dictionaries. If a local key in the dictionary is set to None, it will be removed. """ |
if default_kwarg is None:
return local_kwarg
if isinstance(local_kwarg, basestring):
return local_kwarg
if local_kwarg is None:
return default_kwarg
# Bypass if not a dictionary (e.g. timeout)
if not hasattr(default_kwarg, 'items'):
return local_kwarg
# Upda... |
<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_simulation(self):
"""Runs the complete simulation""" |
print('Starting simulations...')
for i in range(self.num_trials):
print('---Trial {}---'.format(i))
self.run_trial(i)
print('Simulation completed.') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setup_network_agents(self):
"""Initializes agents on nodes of graph and registers them to the SimPy environment""" |
for i in self.env.G.nodes():
self.env.G.node[i]['agent'] = self.agent_type(environment=self.env, agent_id=i,
state=deepcopy(self.initial_states[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 maxchord(A, ve = None):
""" Maximal chordal subgraph of sparsity graph. Returns a lower triangular sparse matrix which is the projection of :math:`A` on a ma... |
n = A.size[0]
assert A.size[1] == n, "A must be a square matrix"
assert type(A) is spmatrix, "A must be a sparse matrix"
if ve is None:
ve = n-1
else:
assert type(ve) is int and 0<=ve<n,\
"ve must be an integer between 0 and A.size[0]-1"
As = symmetrize(A)
cp,ri,v... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cli(config, in_file, out_file, verbose):
"""Main Interface to generate xml documents from custom dictionaries using legal xsd files complying with legal docu... |
config.out_file = out_file
config.verbose = verbose
config.in_file = in_file
config.out_file = out_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 cfdv32mx(config):
"""Format cfdi v3.2 for Mexico. \b File where the files will be written document.xml. cfdicli --in_file /path/to/yout/json/documnt.json cfd... |
# TODO: look for a secure option for eval.
# Or simply the CLI only should manage json?
# TODO: Implement json option also.
dict_input = eval(config.in_file.read())
invoice = cfdv32.get_invoice(dict_input)
if invoice.valid:
config.out_file.write(invoice.document)
config.ou... |
<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_cache_key(key_prefix):
"""Make cache key from prefix Borrowed from Flask-Cache extension """ |
if callable(key_prefix):
cache_key = key_prefix()
elif '%s' in key_prefix:
cache_key = key_prefix % request.path
else:
cache_key = key_prefix
cache_key = cache_key.encode('utf-8')
return cache_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 get_frame(self, in_data, frame_count, time_info, status):
""" Callback function for the pyaudio stream. Don't use directly. """ |
while self.keep_listening:
try:
frame = self.queue.get(False, timeout=queue_timeout)
return (frame, pyaudio.paContinue)
except Empty:
pass
return (None, pyaudio.paComplete) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def sort_dict(self, data, key):
'''Sort a list of dictionaries by dictionary key'''
return sorted(data, key=itemgetter(key)) if data 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 _push_entry(self, key):
"Push entry onto our access log, invalidate the old entry if exists."
self._invalidate_entry(key)
new_entry = AccessEntry(key)
self.access_lookup[key] = new_entry
self.access_log_lock.acquire()
self.access_log.appendleft(new_entry)
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 _prune_entries(self, num):
"Pop entries from our access log until we popped ``num`` valid ones."
while num > 0:
self.access_log_lock.acquire()
p = self.access_log.pop()
self.access_log_lock.release()
if not p.is_valid:
continue # Inval... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _prune_invalidated_entries(self):
"Rebuild our access_log without the invalidated entries."
self.access_log_lock.acquire()
self.access_log = deque(e for e in self.access_log if e.is_valid)
self.access_log_lock.release() |
<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_ordered_access_keys(self):
"Return ordered access keys for inspection. Used for testing."
self.access_log_lock.acquire()
r = [e.key for e in self.access_log if e.is_valid]
self.access_log_lock.release()
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 calc_scaled_res(self, screen_res, image_res):
"""Calculate appropriate texture size. Calculate size or required texture so that it will fill the window, ... |
rs = screen_res[0]/float(screen_res[1])
ri = image_res[0]/float(image_res[1])
if rs > ri:
return (int(image_res[0] * screen_res[1]/image_res[1]), screen_res[1])
else:
return (screen_res[0], int(image_res[1]*screen_res[0]/image_res[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 load_media(self, vidSource):
""" Loads a video. Parameters vidSource : str The path to the video file """ |
if not os.path.exists(vidSource):
print("File not found: " + vidSource)
pygame.display.quit()
pygame.quit()
sys.exit(1)
self.decoder.load_media(vidSource)
self.decoder.loop = self.loop
pygame.display.set_caption(os.path.split(vidSource)[1])
self.vidsize = self.decoder.clip.size
self.destsize ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __texUpdate(self, frame):
""" Update the texture with the newly supplied frame. """ |
# Retrieve buffer from videosink
if self.texture_locked:
return
self.buffer = frame
self.texUpdated = 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 play(self):
""" Starts playback. """ |
# Signal player to start video playback
self.paused = False
# Start listening for incoming audio frames
if self.decoder.audioformat:
self.audio.start()
self.decoder.play()
# While video is playing, render frames
while self.decoder.status in [mediadecoder.PLAYING, mediadecoder.PAUSED]:
texture_up... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pause(self):
""" Pauses playback. """ |
if self.decoder.status == mediadecoder.PAUSED:
self.decoder.pause()
self.paused = False
elif self.decoder.status == mediadecoder.PLAYING:
self.decoder.pause()
self.paused = True
else:
print("Player not in pausable 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 fg(color):
""" Foreground color formatter function factory. Each function casts from a unicode string to a colored bytestring with the respective foreground ... |
ansi_code = [getattr(colorama.Fore, color.upper()), colorama.Fore.RESET]
return lambda msg: msg.join(ansi_code) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clog(color):
"""Same to ``log``, but this one centralizes the message first.""" |
logger = log(color)
return lambda msg: logger(centralize(msg).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 retrieve_width(self, signum=None, frame=None):
""" Stores the terminal width into ``self.width``, if possible. This function is also the SIGWINCH event handl... |
for method_name, args in self.strategies:
method = getattr(self, "from_" + method_name)
width = method(*args)
if width and width > 0:
self.width = width
break # Found!
os.environ["COLUMNS"] = str(self.width) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dump_part(part, total_segments=None):
""" 'part' may be the hash_key if we are dumping just a few hash_keys - else it will be the segment number """ |
try:
connection = Connection(host=config['host'], region=config['region'])
filename = ".".join([config['table_name'], str(part), "dump"])
if config['compress']:
opener = gzip.GzipFile
filename += ".gz"
else:
opener = open
dumper = BatchD... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hessian(L, Y, U, adj = False, inv = False, factored_updates = False):
""" Supernodal multifrontal Hessian mapping. The mapping .. math:: \mathcal H_X(U) = P(... |
assert L.symb == Y.symb, "Symbolic factorization mismatch"
assert isinstance(L, cspmatrix) and L.is_factor is True, "L must be a cspmatrix factor"
assert isinstance(Y, cspmatrix) and Y.is_factor is False, "Y must be a cspmatrix"
if isinstance(U, cspmatrix):
assert U.is_factor is 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 frame_size(self):
"""The byte size of a single frame of this format.""" |
if self.sample_type == SampleType.S16NativeEndian:
# Sample size is 2 bytes
return self.sample_size * self.channels
else:
raise ValueError('Unknown sample type: %d', self.sample_type) |
<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_fields(store_name, field_names):
""" A class-decorator that creates layout managers with a set of named fields. """ |
def decorate(cls):
def _add(index, name):
def _set_dir(self, value): getattr(self, store_name)[index] = value
def _get_dir(self): return getattr(self, store_name)[index]
setattr(cls, name, property(_get_dir, _set_dir))
for index, field_name in enumerate(field_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 _get_smallest_dimensions(self, data):
"""A utility method to return the minimum size needed to fit all the elements in.""" |
min_width = 0
min_height = 0
for element in self.elements:
if not element: continue
size = element.get_minimum_size(data)
min_width = max(min_width, size.x)
min_height = max(min_height, size.y)
return datatypes.Point(min_width, min_height) |
<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, instance, value, **kw):
"""Converts the value into a DateTime object before setting. """ |
if value:
try:
value = DateTime(value)
except SyntaxError:
logger.warn("Value '{}' is not a valid DateTime string"
.format(value))
return False
self._set(instance, value, **kw) |
<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_filename(self, instance):
"""Get the filename """ |
filename = self.field.getFilename(instance)
if filename:
return filename
fieldname = self.get_field_name()
content_type = self.get_content_type(instance)
extension = mimetypes.guess_extension(content_type)
return fieldname + extension |
<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, instance, value, **kw):
"""Decodes base64 value and set the file object """ |
value = str(value).decode("base64")
# handle the filename
if "filename" not in kw:
logger.debug("FielFieldManager::set: No Filename detected "
"-> using title or id")
kw["filename"] = kw.get("id") or kw.get("title")
self._set(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 set(self, instance, value, **kw):
# noqa """Set the value of the refernce field """ |
ref = []
# The value is an UID
if api.is_uid(value):
ref.append(api.get_object_by_uid(value))
# The value is already an object
if api.is_at_content(value):
ref.append(value)
# The value is a dictionary
# -> handle it like a catalog quer... |
<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_proxy_field(self, instance):
"""Get the proxied field of this field """ |
proxy_object = self.get_proxy_object(instance)
if not proxy_object:
return None
return proxy_object.getField(self.name) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.