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 issueCommand(self, command, *args):
""" Issue the given Assuan command and return a Deferred that will fire with the response. """ |
result = Deferred()
self._dq.append(result)
self.sendLine(b" ".join([command] + list(args)))
return 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 _currentResponse(self, debugInfo):
""" Pull the current response off the queue. """ |
bd = b''.join(self._bufferedData)
self._bufferedData = []
return AssuanResponse(bd, debugInfo) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lineReceived(self, line):
""" A line was received. """ |
if line.startswith(b"#"): # ignore it
return
if line.startswith(b"OK"):
# if no command issued, then just 'ready'
if self._ready:
self._dq.pop(0).callback(self._currentResponse(line))
else:
self._ready = True
if lin... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_chunks(stream, block_size=2**10):
""" Given a byte stream with reader, yield chunks of block_size until the stream is consusmed. """ |
while True:
chunk = stream.read(block_size)
if not chunk:
break
yield chunk |
<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_stream_py3(dc, chunks):
""" Given a decompression stream and chunks, yield chunks of decompressed data until the compression window ends. """ |
while not dc.eof:
res = dc.decompress(dc.unconsumed_tail + next(chunks))
yield res |
<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_streams(chunks):
""" Given a gzipped stream of data, yield streams of decompressed data. """ |
chunks = peekable(chunks)
while chunks:
if six.PY3:
dc = zlib.decompressobj(wbits=zlib.MAX_WBITS | 16)
else:
dc = zlib.decompressobj(zlib.MAX_WBITS | 16)
yield load_stream(dc, chunks)
if dc.unused_data:
chunks = peekable(itertools.chain((dc.un... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lines_from_stream(chunks):
""" Given data in chunks, yield lines of text """ |
buf = buffer.DecodingLineBuffer()
for chunk in chunks:
buf.feed(chunk)
# when Python 3, yield from buf
for _ in buf:
yield _ |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def session_registration(uri, session):
"""Requests-mock registration with a specific Session. :param uri: base URI to match against :param session: Python reque... |
# log the URI that is used to access the Stack-In-A-Box services
logger.debug('Registering Stack-In-A-Box at {0} under Python Requests-Mock'
.format(uri))
logger.debug('Session has id {0}'.format(id(session)))
# tell Stack-In-A-Box what URI to match with
StackInABox.update_uri(uri... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def requests_request(method, url, **kwargs):
"""Requests-mock requests.request wrapper.""" |
session = local_sessions.session
response = session.request(method=method, url=url, **kwargs)
session.close()
return response |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def requests_post(url, data=None, json=None, **kwargs):
"""Requests-mock requests.post wrapper.""" |
return requests_request('post', url, data=data, json=json, **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 get_reason_for_status(status_code):
"""Lookup the HTTP reason text for a given status code. :param status_code: int - HTTP status code :returns: string - HTT... |
if status_code in requests.status_codes.codes:
return requests.status_codes._codes[status_code][0].replace('_',
' ')
else:
return 'Unknown status code - {0}'.format(status_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 split_status(status):
"""Split a HTTP Status and Reason code string into a tuple. :param status string containing the status and reason text or the integer o... |
# If the status is an integer, then lookup the reason text
if isinstance(status, int):
return (status, RequestMockCallable.get_reason_for_status(
status))
# otherwise, ensure it is a string and try to split it based on the
# standard HTTP status and reason ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle(self, request, uri):
"""Request handler interface. :param request: Python requests Request object :param uri: URI of the request """ |
# Convert the call over to Stack-In-A-Box
method = request.method
headers = CaseInsensitiveDict()
request_headers = CaseInsensitiveDict()
request_headers.update(request.headers)
request.headers = request_headers
stackinabox_result = StackInABox.call_into(method,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_tip(self, sender, receiver, message, context_uid, meta):
""" Send a request to the ChangeTip API, to be delivered immediately. """ |
assert self.channel is not None, "channel must be defined"
# Add extra data to meta
meta["mention_bot"] = self.mention_bot()
data = json.dumps({
"channel": self.channel,
"sender": sender,
"receiver": receiver,
"message": 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 discoverEndpoint(domain, endpoint, content=None, look_in={'name': 'link'}, test_urls=True, validateCerts=True):
"""Find the given endpoint for the given doma... |
if test_urls:
ronkyuu.URLValidator(message='invalid domain URL')(domain)
if content:
result = {'status': requests.codes.ok,
'headers': None,
'content': content
}
else:
r = requests.get(domain, verify=validateCerts)
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 discoverMicropubEndpoints(domain, content=None, look_in={'name': 'link'}, test_urls=True, validateCerts=True):
"""Find the micropub for the given domain. Onl... |
return discoverEndpoint(domain, ('micropub',), content, look_in, test_urls, validateCerts) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def discoverTokenEndpoints(domain, content=None, look_in={'name': 'link'}, test_urls=True, validateCerts=True):
"""Find the token for the given domain. Only scan... |
return discoverEndpoint(domain, ('token_endpoint',), content, look_in, test_urls, validateCerts) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def form_node(cls):
"""A class decorator to finalize fully derived FormNode subclasses.""" |
assert issubclass(cls, FormNode)
res = attrs(init=False, slots=True)(cls)
res._args = []
res._required_args = 0
res._rest_arg = None
state = _FormArgMode.REQUIRED
for field in fields(res):
if 'arg_mode' in field.metadata:
if state is _FormArgMode.REST:
ra... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def intercept(aspects):
"""Decorate class to intercept its matching methods and apply advices on them. Advices are the cross-cutting concerns that need to be sep... |
if not isinstance(aspects, dict):
raise TypeError("Aspects must be a dictionary of joint-points and advices")
def get_matching_advices(name):
"""Get all advices matching method name"""
all_advices = dict()
for joint_point, advices in aspects.iteritems():
if re.match... |
<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_diff(environ, label, pop=False):
"""Get previously frozen key-value pairs. :param str label: The name for the frozen environment. :param bool pop: Destr... |
if pop:
blob = environ.pop(_variable_name(label), None)
else:
blob = environ.get(_variable_name(label))
return _loads(blob) if blob 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 _apply_diff(environ, diff):
"""Apply a frozen environment. :param dict diff: key-value pairs to apply to the environment. :returns: A dict of the key-value p... |
original = {}
if diff:
for k, v in diff.iteritems():
if v is None:
log.log(5, 'unset %s', k)
else:
log.log(5, '%s="%s"', k, v)
original[k] = environ.get(k)
if original[k] is None:
log.log(1, '%s was not ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_current():
"""return current Xresources color theme""" |
global current
if exists( SETTINGSFILE ):
f = open( SETTINGSFILE ).read()
current = re.findall('config[^\s]+.+', f)[1].split('/')[-1]
return current
else:
return "** Not Set **" |
<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_colors():
"""return list of available Xresources color themes""" |
if exists( THEMEDIR ):
contents = os.listdir( THEMEDIR )
themes = [theme for theme in contents if '.' not in theme]
if len(themes) > 0:
themes.sort()
return themes
else:
print "** No themes in themedir **"
print " run:"
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getch_selection(colors, per_page=15):
"""prompt for selection, validate input, return selection""" |
global transparency, prefix, current
get_transparency()
page = 1
length = len(colors)
last_page = length / per_page
if (last_page * per_page) < length:
last_page += 1
getch = _Getch()
valid = False
while valid == False:
menu_pages(colors, page, True, per_page... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_theme(selection):
"""removes any non-color related lines from theme file""" |
global themefile
text = open(THEMEDIR + '/' + selection).read()
if '!dotcolors' in text[:10]:
themefile = text
return
lines = ['!dotcolors auto formatted\n']
for line in text.split('\n'):
lline = line.lower()
background = 'background' in lline
foreground = ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pretty_size(value):
"""Convert a number of bytes into a human-readable string. """ |
exp = int(math.log(value, 1024)) if value > 0 else 0
unit = 'bkMGTPEZY'[exp]
if exp == 0:
return '%d%s' % (value, unit) # value < 1024, result is always without fractions
unit_value = value / (1024.0 ** exp) # value in the relevant units
places = int(math.log(unit_value, 10)) # 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 _on_open(self, _):
"""Joins the hack.chat channel and starts pinging.""" |
nick = self._format_nick(self._nick, self._pwd)
data = {"cmd": "join", "channel": self._channel, "nick": nick}
self._send_packet(data)
self._thread = True
threading.Thread(target=self._ping).start() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def join(self, new_channel, nick, pwd=None):
"""Joins a new channel. Keyword arguments: new_channel: <str>; the channel to connect to nick: <str>; the nickname t... |
self._send_packet({"cmd": "join", "channel": new_channel,
"nick": self._format_nick(nick, pwd)}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upload(client, source_dir):
""" Upload images to play store. The function will iterate through source_dir and upload all matching image_types found in folder... |
print('')
print('upload images')
print('-------------')
base_image_folders = [
os.path.join(source_dir, 'images', x) for x in image_types]
for type_folder in base_image_folders:
if os.path.exists(type_folder):
image_type = os.path.basename(type_folder)
langf... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_and_upload_images(client, image_type, language, base_dir):
""" Delete and upload images with given image_type and language. Function will stage delete... |
print('{0} {1}'.format(image_type, language))
files_in_dir = os.listdir(os.path.join(base_dir, language))
delete_result = client.deleteall(
'images', imageType=image_type, language=language)
deleted = delete_result.get('deleted', list())
for deleted_files in deleted:
print(' delet... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download(client, target_dir):
"""Download images from play store into folder herachy.""" |
print('download image previews')
print(
"Warning! Downloaded images are only previews!"
"They may be to small for upload.")
tree = {}
listings = client.list('listings')
languages = map(lambda listing: listing['language'], listings)
parameters = [{'imageType': image_type, 'langu... |
<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_and_save_image(url, destination):
"""Download image from given url and saves it to destination.""" |
from urllib2 import Request, urlopen, URLError, HTTPError
# create the url and the request
req = Request(url)
# Open the url
try:
f = urlopen(req)
print "downloading " + url
# Open our local file for writing
local_file = open(destination, "wb")
# Write to ... |
<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_qapp():
"""Return an instance of QApplication. Creates one if neccessary. :returns: a QApplication instance :rtype: QApplication :raises: None """ |
global app
app = QtGui.QApplication.instance()
if app is None:
app = QtGui.QApplication([], QtGui.QApplication.GuiClient)
return 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 load_all_resources():
"""Load all resources inside this package When compiling qt resources, the compiled python file will register the resource on import. .... |
pkgname = resources.__name__
for importer, mod_name, _ in pkgutil.iter_modules(resources.__path__):
full_mod_name = '%s.%s' % (pkgname, mod_name)
if full_mod_name not in sys.modules:
module = importer.find_module(mod_name
).load_module(full_mod_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 set_main_style(widget):
"""Load the main.qss and apply it to the application :param widget: The widget to apply the stylesheet to. Can also be a QApplication... |
load_all_resources()
with open(MAIN_STYLESHEET, 'r') as qss:
sheet = qss.read()
widget.setStyleSheet(sheet) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wrap(ptr, base=None):
"""Wrap the given pointer with shiboken and return the appropriate QObject :returns: if ptr is not None returns a QObject that is cast ... |
if ptr is None:
return None
ptr = long(ptr) # Ensure type
if base is None:
qObj = shiboken.wrapInstance(long(ptr), QtCore.QObject)
metaObj = qObj.metaObject()
cls = metaObj.className()
superCls = metaObj.superClass().className()
if hasattr(QtGui, cls):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dt_to_qdatetime(dt):
"""Convert a python datetime.datetime object to QDateTime :param dt: the datetime object :type dt: :class:`datetime.datetime` :returns: ... |
return QtCore.QDateTime(QtCore.QDate(dt.year, dt.month, dt.day),
QtCore.QTime(dt.hour, dt.minute, dt.second)) |
<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_icon(name, aspix=False, asicon=False):
"""Return the real file path to the given icon name If aspix is True return as QtGui.QPixmap, if asicon is True re... |
datapath = os.path.join(ICON_PATH, name)
icon = pkg_resources.resource_filename('jukeboxcore', datapath)
if aspix or asicon:
icon = QtGui.QPixmap(icon)
if asicon:
icon = QtGui.QIcon(icon)
return icon |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def allinstances(cls):
"""Return all instances that inherit from JB_Gui :returns: all instances that inherit from JB_Gui :rtype: list :raises: None """ |
JB_Gui._allinstances = weakref.WeakSet([i for i in cls._allinstances if shiboken.isValid(i)])
return list(cls._allinstances) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def classinstances(cls):
"""Return all instances of the current class JB_Gui will not return the instances of subclasses A subclass will only return the instance... |
l = [i for i in cls.allinstances() if type(i) == cls]
return l |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instances(cls):
"""Return all instances of this class and subclasses :returns: all instances of the current class and subclasses :rtype: list :raises: None "... |
l = [i for i in cls.allinstances() if isinstance(i, cls)]
return l |
<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(self, error_msg):
""" Outputs error message on own logger. Also raises exceptions if need be. Args: error_msg: message to output """ |
if self.logger is not None:
self.logger.error(error_msg)
if self.exc is not None:
raise self.exc(error_msg) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clear_data(self):
"""Clear both ontology and annotation data. Parameters Returns ------- None """ |
self.clear_annotation_data()
self.terms = {}
self._alt_id = {}
self._syn2id = {}
self._name2id = {}
self._flattened = 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 clear_annotation_data(self):
"""Clear annotation data. Parameters Returns ------- None """ |
self.genes = set()
self.annotations = []
self.term_annotations = {}
self.gene_annotations = {} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _flatten_ancestors(self, include_part_of=True):
"""Determines and stores all ancestors of each GO term. Parameters include_part_of: bool, optional Whether to... |
def get_all_ancestors(term):
ancestors = set()
for id_ in term.is_a:
ancestors.add(id_)
ancestors.update(get_all_ancestors(self.terms[id_]))
if include_part_of:
for id_ in term.part_of:
ancestors.add(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 get_gene_goterms(self, gene, ancestors=False):
"""Return all GO terms a particular gene is annotated with. Parameters gene: str The gene symbol of the gene. ... |
annotations = self.gene_annotations[gene]
terms = set(ann.term for ann in annotations)
if ancestors:
assert self._flattened
ancestor_terms = set()
for t in terms:
ancestor_terms.update(self.terms[id_] for id_ in t.ancestors)
terms... |
<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_goterm_genes(self, id_, descendants=True):
"""Return all genes that are annotated with a particular GO term. Parameters id_: str GO term ID of the GO ter... |
# determine which terms to include
main_term = self.terms[id_]
check_terms = {main_term, }
if descendants:
assert self._flattened
check_terms.update([self.terms[id_]
for id_ in main_term.descendants])
# get annotations 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 get_gene_sets(self, min_genes=None, max_genes=None):
"""Return the set of annotated genes for each GO term. Parameters min_genes: int, optional Exclude GO te... |
if not self.terms:
raise ValueError('You need to first parse both an OBO file and '
'a gene association file!')
if not self.annotations:
raise ValueError('You need to first parse a gene association '
'file!')
a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_meta(self, f):
"""Read the headers of a file in file format and place them in the self.meta dictionary. """ |
if not isinstance(f, BacktrackableFile):
f = BacktrackableFile(f)
try:
(name, value) = self.read_meta_line(f)
while name:
name = (name == 'nominal_offset' and 'timestamp_rounding' or
name)
name = (name == 'actu... |
<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_excluded(self, prop, info_dict):
""" Check if the given prop should be excluded from the export """ |
if prop.key in BLACKLISTED_KEYS:
return True
if info_dict.get('exclude', False):
return True
if prop.key in self.excludes:
return True
if self.includes and prop.key not in self.includes:
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_title(self, prop, main_infos, info_dict):
""" Return the title configured as in colanderalchemy """ |
result = main_infos.get('label')
if result is None:
result = info_dict.get('colanderalchemy', {}).get('title')
if result is None:
result = prop.key
return 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 _get_prop_infos(self, prop):
""" Return the infos configured for this specific prop, merging the different configuration level """ |
info_dict = self.get_info_field(prop)
main_infos = info_dict.get('export', {}).copy()
infos = main_infos.get(self.config_key, {})
main_infos['label'] = self._get_title(prop, main_infos, info_dict)
main_infos['name'] = prop.key
main_infos['key'] = prop.key
main_in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _collect_headers(self):
""" Collect headers from the models attribute info col """ |
res = []
for prop in self.get_sorted_columns():
main_infos = self._get_prop_infos(prop)
if self._is_excluded(prop, main_infos):
continue
if isinstance(prop, RelationshipProperty):
main_infos = self._collect_relationship(main_infos,... |
<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_many_to_one_field_from_fkey(self, main_infos, prop, result):
""" Find the relationship associated with this fkey and set the title :param dict main_in... |
if prop.columns[0].foreign_keys and prop.key.endswith('_id'):
# We have a foreign key, we'll try to merge it with the
# associated foreign key
rel_name = prop.key[0:-3]
for val in result:
if val["name"] == rel_name:
val["label"... |
<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_row(self, obj):
""" fill a new row with the given obj obj instance of the exporter's model """ |
row = {}
for column in self.headers:
value = ''
if '__col__' in column:
if isinstance(column['__col__'], ColumnProperty):
value = self._get_column_cell_val(obj, column)
elif isinstance(column['__col__'], RelationshipProperty... |
<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_formatted_val(self, obj, name, column):
""" Format the value of the attribute 'name' from the given object """ |
attr_path = name.split('.')
val = None
tmp_val = obj
for attr in attr_path:
tmp_val = getattr(tmp_val, attr, None)
if tmp_val is None:
break
if tmp_val is not None:
val = tmp_val
return format_value(column, val, self.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_relationship_cell_val(self, obj, column):
""" Return the value to insert in a relationship cell """ |
val = ""
key = column['key']
related_key = column.get('related_key', None)
related_obj = getattr(obj, key, None)
if related_obj is None:
return ""
if column['__col__'].uselist: # OneToMany
# We know how to retrieve a value from the related obj... |
<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_column_cell_val(self, obj, column):
""" Return a value of a "column" cell """ |
name = column['name']
return self._get_formatted_val(obj, name, column) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def join(input_files, output_file):
'''
Join geojsons into one. The spatial reference system of the output file is the same
as the one of the last file in the list.
Args:
input_files (list): List of file name strings.
output_file (str): Output file name.
'''
# get feature 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 split(input_file, file_1, file_2, no_in_first_file):
'''
Split a geojson in two separate files.
Args:
input_file (str): Input filename.
file_1 (str): Output file name 1.
file_2 (str): Output file name 2.
no_features (int): Number of features in input_file to go to file_1... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_from(input_file, property_names):
'''
Reads a geojson and returns a list of value tuples, each value corresponding to a
property in property_names.
Args:
input_file (str): File name.
property_names: List of strings; each string is a property name.
Returns:
List ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def write_properties_to(data, property_names, input_file, output_file, filter=None):
'''
Writes property data to polygon_file for all geometries indicated in the filter, and
creates output file. The length of data must be equal to the number of geometries
in the filter. Existing property 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 find_unique_values(input_file, property_name):
'''
Find unique values of a given property in a geojson file.
Args
input_file (str): File name.
property_name (str): Property name.
Returns
List of distinct values of property. If property does not exist, it returns 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 create_balanced_geojson(input_file, classes, output_file='balanced.geojson',
samples_per_class=None):
'''
Create a geojson comprised of balanced classes from the class_name property in
input_file. Randomly selects polygons from all classes.
Args:
input_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 setup_manage_parser(self, parser):
"""Setup the given parser for manage command :param parser: the argument parser to setup :type parser: :class:`argparse.Ar... |
parser.set_defaults(func=self.manage)
parser.add_argument("args", nargs=argparse.REMAINDER,
help="arguments for django manage command") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def manage(self, namespace, unknown):
"""Execute the manage command for django :param namespace: namespace containing args with django manage.py arguments :type ... |
# first argument is usually manage.py. This will also adapt the help messages
args = ['jukebox manage']
args.extend(namespace.args)
args.extend(unknown)
from django.core.management import execute_from_command_line
execute_from_command_line(args) |
<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_compile_ui_parser(self, parser):
"""Setup the given parser for the compile_ui command :param parser: the argument parser to setup :type parser: :class:... |
parser.set_defaults(func=self.compile_ui)
parser.add_argument('uifile',
nargs="+",
help='the uifile that will be compiled.\
The compiled file will be in the same directory but ends with _ui.py.\
Optional a list of files.',
type=arg... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compile_ui(self, namespace, unknown):
"""Compile qt designer files :param namespace: namespace containing arguments from the launch parser :type namespace: N... |
uifiles = namespace.uifile
for f in uifiles:
qtcompile.compile_ui(f.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 setup_compile_rcc_parser(self, parser):
"""Setup the given parser for the compile_rcc command :param parser: the argument parser to setup :type parser: :clas... |
parser.set_defaults(func=self.compile_rcc)
parser.add_argument('rccfile',
help='the resource file to compile.\
The compiled file will be in the jukeboxcore.gui.resources package and ends with _rc.py',
type=argparse.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 compile_rcc(self, namespace, unknown):
"""Compile qt resource files :param namespace: namespace containing arguments from the launch parser :type namespace: ... |
rccfile = namespace.rccfile.name
qtcompile.compile_rcc(rccfile) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_nullable_array(value):
""" Converts value into array object. Single values are converted into arrays with a single element. :param value: the value to con... |
# Shortcuts
if value == None:
return None
if type(value) == list:
return value
if type(value) in [tuple, set]:
return list(value)
return [value] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_array_with_default(value, default_value):
""" Converts value into array object with specified default. Single values are converted into arrays with single... |
result = ArrayConverter.to_nullable_array(value)
return result if result != None else default_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 list_to_array(value):
""" Converts value into array object with empty array as default. Strings with comma-delimited values are split into array of strings. ... |
if value == None:
return []
elif type(value) in [list, tuple, set]:
return list(value)
elif type(value) in [str]:
return value.split(',')
else:
return [value] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_server_sock():
"Get a server socket"
s = _socket.socket()
s.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, True)
s.setblocking(False)
s.bind(('0.0.0.0', _config.server_listen_port))
s.listen(5)
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 get_client_sock(addr):
"Get a client socket"
s = _socket.create_connection(addr)
s.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, True)
s.setblocking(False)
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 get_beacon():
"Get a beacon socket"
s = _socket.socket(_socket.AF_INET, _socket.SOCK_DGRAM)
s.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, True)
s.setsockopt(_socket.SOL_SOCKET, _socket.SO_BROADCAST, True)
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 message(self):
''' Override this to provide failure message'''
name = self.__class__.__name__
return "{0} {1}".format(humanize(name),
pp(*self.expectedArgs, **self.expectedKwArgs)) |
<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_results_info(self):
""" Returns the search results info for this command invocation or None. The search results info object is created from the search... |
if self._search_results_info is not None:
return self._search_results_info
try:
info_path = self.input_header['infoPath']
except KeyError:
return None
def convert_field(field):
return (field[1:] if field[0] == '_' else field).replace('.'... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process(self, args=argv, input_file=stdin, output_file=stdout):
""" Processes search results as specified by command arguments. :param args: Sequence of comm... |
self.logger.debug(u'%s arguments: %s', type(self).__name__, args)
self._configuration = None
self._output_file = output_file
try:
if len(args) >= 2 and args[1] == '__GETINFO__':
ConfigurationSettings, operation, args, reader = self._prepare(args, input_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 check_contract_allowed(func):
"""Check if Contract is allowed by token """ |
@wraps(func)
def decorator(*args, **kwargs):
contract = kwargs.get('contract')
if (contract and current_user.is_authenticated()
and not current_user.allowed(contract)):
return current_app.login_manager.unauthorized()
return func(*args, **kwargs)
return de... |
<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_cups_allowed(func):
"""Check if CUPS is allowd by token """ |
@wraps(func)
def decorator(*args, **kwargs):
cups = kwargs.get('cups')
if (cups and current_user.is_authenticated()
and not current_user.allowed(cups, 'cups')):
return current_app.login_manager.unauthorized()
return func(*args, **kwargs)
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 format_py3o_val(value):
""" format a value to fit py3o's context * Handle linebreaks """ |
value = force_unicode(value)
value = escape(value)
value = value.replace(u'\n', u'<text:line-break/>')
return Markup(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_compilation_context(instance):
""" Return the compilation context for py3o templating Build a deep dict representation of the given instance and add conf... |
context_builder = SqlaContext(instance.__class__)
py3o_context = context_builder.compile_obj(instance)
return py3o_context |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compile_template(instance, template, additionnal_context=None):
""" Fill the given template with the instance's datas and return the odt file For every insta... |
py3o_context = get_compilation_context(instance)
if additionnal_context is not None:
py3o_context.update(additionnal_context)
output_doc = StringIO()
odt_builder = Template(template, output_doc)
odt_builder.render(py3o_context)
return output_doc |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def collect_columns(self):
""" Collect columns information from a given model. a column info contains the py3 informations exclude Should the column be excluded ... |
res = []
for prop in self.get_sorted_columns():
info_dict = self.get_info_field(prop)
export_infos = info_dict.get('export', {}).copy()
main_infos = export_infos.get(self.config_key, {}).copy()
if export_infos.get('exclude'):
if main_in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gen_xml_doc(self):
""" Generate the text tags that should be inserted in the content.xml of a full model """ |
res = self.make_doc()
var_tag = """
<text:user-field-decl office:value-type="string"
office:string-value="%s" text:name="py3o.%s"/>"""
text_tag = """<text:p text:style-name="P1">
<text:user-field-get text:name="py3o.%s">%s</text:user-field-get>
</text: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 _get_formatted_val(self, obj, attribute, column):
""" Return the formatted value of the attribute "attribute" of the obj "obj" regarding the column's descrip... |
attr_path = attribute.split('.')
val = None
tmp_val = obj
for attr in attr_path:
tmp_val = getattr(tmp_val, attr, None)
if tmp_val is None:
break
if tmp_val is not None:
val = tmp_val
value = format_value(column, 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 _get_column_value(self, obj, column):
""" Return a single cell's value :param obj obj: The instance we manage :param dict column: The column description dict... |
return self._get_formatted_val(obj, column['__col__'].key, column) |
<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_to_many_relationship_value(self, obj, column):
""" Get the resulting datas for a One To many or a many to many relationship :param obj obj: The instance... |
related_key = column.get('related_key', None)
related = getattr(obj, column['__col__'].key)
value = {}
if related:
total = len(related)
for index, rel_obj in enumerate(related):
if related_key:
compiled_res = self._get_formatt... |
<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_to_one_relationship_value(self, obj, column):
""" Compute datas produced for a many to one relationship :param obj obj: The instance we manage :param di... |
related_key = column.get('related_key', None)
related = getattr(obj, column['__col__'].key)
if related:
if related_key is not None:
value = self._get_formatted_val(
related, related_key, column
)
else:
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 _get_relationship_value(self, obj, column):
""" Compute datas produced for a given relationship """ |
if column['__col__'].uselist:
value = self._get_to_many_relationship_value(obj, column)
else:
value = self._get_to_one_relationship_value(obj, column)
return value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compile_obj(self, obj):
""" generate a context based on the given obj :param obj: an instance of the model """ |
res = {}
for column in self.columns:
if isinstance(column['__col__'], ColumnProperty):
value = self._get_column_value(obj, column)
elif isinstance(column['__col__'], RelationshipProperty):
value = self._get_relationship_value(obj, column)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write(_filename, _long, enter=True):
"""Write the call info to file""" |
def method(*arg, **kw): # pylint: disable=W0613
"""Reference to the advice in order to facilitate argument support."""
def get_short(_fname):
"""Get basename of the file. If file is __init__.py, get its directory too"""
dir_path, short_fname = os.path.split(_fname)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _addPub(self, stem, source):
"""Enters stem as value for source. """ |
key = re.sub("[^A-Za-z0-9&]+", " ", source).strip().upper()
self.sourceDict[key] = stem
self.bibstemWords.setdefault(stem, set()).update(
key.lower().split()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _loadOneSource(self, sourceFName):
"""handles one authority file including format auto-detection. """ |
sourceLines = open(sourceFName).readlines()
del sourceLines[0]
if len(sourceLines[0].split("\t"))==2:
self._loadTwoPartSource(sourceFName, sourceLines)
elif len(sourceLines[0].split("\t"))==3:
self._loadThreePartSource(sourceFName, sourceLines)
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 _loadSources(self):
"""creates a trigdict and populates it with data from self.autorityFiles """ |
self.confstems = {}
self.sourceDict = newtrigdict.Trigdict()
for fName in self.authorityFiles:
self._loadOneSource(fName)
# We want to allow naked bibstems in references, too
for stem in self.sourceDict.values():
cleanStem = stem.replace(".", "").upper()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def long_description():
""" Build the long description from a README file located in the same directory as this module. """ |
base_path = os.path.dirname(os.path.realpath(__file__))
with io.open(os.path.join(base_path, 'README.md'), encoding='utf-8') as f:
return f.read() |
<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_build_info(api_instance, build_id=None, keys=DEFAULT_BUILD_KEYS, wait=False):
""" print build info about a job """ |
build = (api_instance.get_build(build_id) if build_id
else api_instance.get_last_build())
output = ""
if wait:
build.block_until_complete()
if 'timestamp' in keys:
output += str(build.get_timestamp()) + '\n'
if 'console' in keys:
output += build.get_console()... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _filter_names(names):
""" Given a list of file names, return those names that should be copied. """ |
names = [n for n in names
if n not in EXCLUDE_NAMES]
# This is needed when building a distro from a working
# copy (likely a checkout) rather than a pristine export:
for pattern in EXCLUDE_PATTERNS:
names = [n for n in names
if (not fnmatch.fnmatch(n, pattern))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def relative_to(base, relativee):
""" Gets 'relativee' relative to 'basepath'. i.e., 'radix' 'Projects/Twisted' The 'relativee' must be a child of 'basepath'. ""... |
basepath = os.path.abspath(base)
relativee = os.path.abspath(relativee)
if relativee.startswith(basepath):
relative = relativee[len(basepath):]
if relative.startswith(os.sep):
relative = relative[1:]
return os.path.join(base, relative)
raise ValueError("%s is not a s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.