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 list_series(self, keys=None, tags=None, attrs=None, limit=1000):
"""Get a list of all series matching the given criteria. **Note:** for the key argument, the... |
params = {
'key': keys,
'tag': tags,
'attr': attrs,
'limit': limit
}
url_args = endpoint.make_url_args(params)
url = '?'.join([endpoint.SERIES_ENDPOINT, url_args])
resp = self.session.get(url)
return resp |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def aggregate_data(self, start, end, aggregation, keys=[], tags=[], attrs={}, rollup=None, period=None, interpolationf=None, interpolation_period=None, tz=None, l... |
url = 'segment'
vstart = check_time_param(start)
vend = check_time_param(end)
params = {
'start': vstart,
'end': vend,
'key': keys,
'tag': tags,
'attr': attrs,
'aggregation.fold': aggregation,
'rollup.... |
<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_data(self, key, data, tags=[], attrs={}):
"""Write a set a datapoints into a series by its key. For now, the tags and attributes arguments are ignored.... |
url = make_series_url(key)
url = urlparse.urljoin(url + '/', 'data')
#revisit later if there are server changes to take these into
#account
#params = {
# 'tag': tag,
# 'attr': attr,
#}
#url_args = endpoint.make_url_args(params)
#ur... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def single_value(self, key, ts=None, direction=None):
"""Return a single value for a series. You can supply a timestamp as the ts argument, otherwise the search ... |
url = make_series_url(key)
url = urlparse.urljoin(url + '/', 'single')
if ts is not None:
vts = check_time_param(ts)
else:
vts = None
params = {
'ts': vts,
'direction': direction
}
url_args = endpoint.make_url_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 multi_series_single_value(self, keys=None, ts=None, direction=None, attrs={}, tags=[]):
"""Return a single value for multiple series. You can supply a timest... |
url = 'single/'
if ts is not None:
vts = check_time_param(ts)
else:
vts = None
params = {
'key': keys,
'tag': tags,
'attr': attrs,
'ts': vts,
'direction': direction
}
url_args = endpoi... |
<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 async_open(self) -> None: """Opens connection to the LifeSOS ethernet interface.""" |
await self._loop.create_connection(
lambda: self,
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 load_abbr(abbr_file=ABBREVIATION_FILE):
""" Load the abbr2long from file """ |
abbr2long = dict()
with open(abbr_file) as f:
lines = f.read().split('\n')
for line in lines:
m = re.match(r'(\w+)\t(.+)', line)
if m:
abbr2long[m.group(1)] = m.group(2)
return abbr2long |
<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_spelling(spell_file=SPELLING_FILE):
""" Load the term_freq from spell_file """ |
with open(spell_file) as f:
tokens = f.read().split('\n')
size = len(tokens)
term_freq = {token: size - i for i, token in enumerate(tokens)}
return term_freq |
<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_search_freq(fp=SEARCH_FREQ_JSON):
""" Load the search_freq from JSON file """ |
try:
with open(fp) as f:
return Counter(json.load(f))
except FileNotFoundError:
return Counter() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tokenize(s):
""" A simple tokneizer """ |
s = re.sub(r'(?a)(\w+)\'s', r'\1', s) # clean the 's from Crohn's disease
#s = re.sub(r'(?a)\b', ' ', s) # split the borders of chinese and english chars
split_pattern = r'[{} ]+'.format(re.escape(STOPCHARS))
tokens = [token for token in re.split(split_pattern, s) if not set(token) <= set(string.punct... |
<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_spelling(token_folder, spelling_file):
""" Generate the spelling correction file form token_folder and save to spelling_file """ |
token_pattern = r'[a-z]{3,}'
tokens = []
for base, dirlist, fnlist in os.walk(token_folder):
for fn in fnlist:
fp = os.path.join(base, fn)
with open(fp) as f:
toks = re.findall(token_pattern, f.read())
tokens.extend(toks)
token_ranked, _ ... |
<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_hints(code_list, k=10, hint_folder=HINT_FOLDER, current_tokens=None):
""" Fetch first k hints for given code_list """ |
def hint_score(v, size):
"""
The formula for hint score
"""
return 1.0 - abs(v / (size + 1) - 0.5)
if len(code_list) <= 1:
return [], []
if current_tokens is None:
current_tokens = []
size = min(len(code_list), MAX_HINT_SMAPLING_SIZE)
sample = ran... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch(index, tokens):
""" Fetch the codes from given tokens """ |
if len(tokens) == 0:
return set()
return set.intersection(*[set(index.get(token, [])) for token in tokens]) |
<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_snippets(code_list, base=SNIPPET_FOLDER):
""" Get the snippets """ |
output = []
for code in code_list:
path = gen_path(base, code)
fp = os.path.join(path, code)
try:
with open(fp) as f:
output.append(f.read())
except FileNotFoundError:
output.append('')
logging.warning("FileNotFoundError: No su... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _ed1(token):
""" Return tokens the edit distance of which is one from the given token """ |
insertion = {letter.join([token[:i], token[i:]]) for letter in string.ascii_lowercase for i in range(1, len(token) + 1)}
deletion = {''.join([token[:i], token[i+1:]]) for i in range(1, len(token) + 1)}
substitution = {letter.join([token[:i], token[i+1:]]) for letter in string.ascii_lowercase for i in range... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _correct(token, term_freq):
""" Correct a single token according to the term_freq """ |
if token.lower() in term_freq:
return token
e1 = [t for t in _ed1(token) if t in term_freq]
if len(e1) > 0:
e1.sort(key=term_freq.get)
return e1[0]
e2 = [t for t in _ed2(token) if t in term_freq]
if len(e2) > 0:
e2.sort(key=term_freq.get)
return e2[0]
ret... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def correct(tokens, term_freq):
""" Correct a list of tokens, according to the term_freq """ |
log = []
output = []
for token in tokens:
corrected = _correct(token, term_freq)
if corrected != token:
log.append((token, corrected))
output.append(corrected)
return output, log |
<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(index, query, snippet_folder=SNIPPET_FOLDER, term_freq=term_freq):
""" The highest level of search function """ |
fallback_log = []
code_list = []
tokens = tokenize(query)
tokens, abbr_log = abbr_expand(tokens)
tokens, correct_log = correct(tokens, term_freq)
tokens = lemmatize(tokens)
tokens = filterout(tokens)
while len(tokens) > 0: # Fallback mechanism
code_list = fetch(index, tokens)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _do_connection(self, wgt, sig, func):
""" Make a connection between a GUI widget and a callable. wgt and sig are strings with widget and signal name func is ... |
#new style (we use this)
#self.btn_name.clicked.connect(self.on_btn_name_clicked)
#old style
#self.connect(self.btn_name, SIGNAL('clicked()'), self.on_btn_name_clicked)
if hasattr(self, wgt):
wgtobj = getattr(self, wgt)
if hasattr(wgtobj, sig):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _process_list(self, l):
""" Processes a list of widget names. If any name is between `` then it is supposed to be a regex. """ |
if hasattr(self, l):
t = getattr(self, l)
def proc(inp):
w = inp.strip()
if w.startswith('`'):
r = re.compile(w[1:-1])
return [u for u in [m.group() for m in [r.match(x) for x in dir(self)] if m] if isinstance(get... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def auto_connect(self):
""" Make a connection between every member function to a GUI signal. Every member function whose name is in format: '_on_' + <widget_name... |
for o in dir(self):
if o.startswith('_on_') and '__' in o:
func = getattr(self, o)
wgt, sig = o.split('__')
if self._do_connection(wgt[4:], sig, func):
print('Failed to connect', o)
if o.startswith('_when_') and '__' 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 print_signals_and_slots(self):
""" List all active Slots and Signal. Credits to: http://visitusers.org/index.php?title=PySide_Recipes#Debugging """ |
for i in xrange(self.metaObject().methodCount()):
m = self.metaObject().method(i)
if m.methodType() == QMetaMethod.MethodType.Signal:
print("SIGNAL: sig=", m.signature(), "hooked to nslots=", self.receivers(SIGNAL(m.signature())))
elif m.methodType() == Q... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_all_signals(self):
""" Prints out every signal available for this widget and childs. """ |
for o in dir(self):
obj= getattr(self, o)
#print o, type(obj)
div = False
for c in dir(obj):
cobj = getattr(obj, c)
if isinstance(cobj, Signal):
print('def _on_{}__{}(self):'.format(o, c))
di... |
<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(self, path, all=False):
'''
Looks for files in the app directories.
'''
found = os.path.join(settings.STATIC_ROOT, path)
if all:
return [found]
else:
return found |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def interrupt(self):
""" Invoked on a write operation into the IR of the RendererDevice. """ |
if(self.device.read(9) & 0x01):
self.handle_request()
self.device.clear_IR() |
<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_char_screen(self):
""" Draws the output buffered in the char_buffer. """ |
self.screen = Image.new("RGB", (self.height, self.width))
self.drawer = ImageDraw.Draw(self.screen)
for sy, line in enumerate(self.char_buffer):
for sx, tinfo in enumerate(line):
self.drawer.text((sx * 6, sy * 9), tinfo[0], fill=tinfo[1:])
self.output_device.interrupt() |
<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_cli(self, prefix, other_cli):
"""Adds the functionality of the other CLI to this one, where all commands to the other CLI are prefixed by the given prefi... |
if prefix not in self.clis and prefix not in self.cmds:
self.clis[prefix] = other_cli
else:
raise ValueError('Attempting to overwrite cmd or extern CLI: %s' % prefix) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _dispatch(self, cmd, args):
"""Attempt to run the given command with the given arguments """ |
if cmd in self.clis:
extern_cmd, args = args[0], args[1:]
self.clis[cmd]._dispatch(extern_cmd, args)
else:
if cmd in self.cmds:
callback, parser = self.cmds[cmd]
try:
p_args = parser.parse_args(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 exec_cmd(self, cmdstr):
"""Parse line from CLI read loop and execute provided command """ |
parts = cmdstr.split()
if len(parts):
cmd, args = parts[0], parts[1:]
self._dispatch(cmd, args)
else:
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 print_help(self):
"""Prints usage of all registered commands, collapsing aliases into one record """ |
seen_aliases = set()
print('-'*80)
for cmd in sorted(self.cmds):
if cmd not in self.builtin_cmds:
if cmd not in seen_aliases:
if cmd in self.aliases:
seen_aliases.update(self.aliases[cmd])
disp = '/'... |
<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, instream=sys.stdin):
"""Runs the CLI, reading from sys.stdin by default """ |
sys.stdout.write(self.prompt)
sys.stdout.flush()
while True:
line = instream.readline()
try:
self.exec_cmd(line)
except Exception as e:
self.errfun(e)
sys.stdout.write(self.prompt)
sys.stdout.flush() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute_finder(self, manager, package_name):
""" Execute finder script within the temporary venv context. """ |
filename = '{env_path}/results.json'.format(env_path=manager.env_path)
subprocess.call([
manager.venv_python, self._finder_path, package_name, filename
])
# Load results into this context
json_str = open(filename, 'r').read()
return json.loads(json_str) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def urltool(classqname, filt, reverse):
""" Dump all urls branching from a class as OpenAPI 3 documentation The class must be given as a FQPN which points to a K... |
filt = re.compile(filt or '.*')
rootCls = namedAny(classqname)
rules = list(_iterClass(rootCls))
arr = []
for item in sorted(rules):
if item.subKlein:
continue
matched = filt.search(item.rulePath)
matched = not matched if reverse else matched
if matched... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def literal_unicode_representer(dumper, data):
""" Use |- literal syntax for long strings """ |
if '\n' in data:
return dumper.represent_scalar(u'tag:yaml.org,2002:str', data, style='|')
else:
return dumper.represent_scalar(u'tag:yaml.org,2002:str', 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 wrap_job_cursor(func_, *args, **kwargs):
""" wraps a filter generator. Types should be appropriate before passed to rethinkdb somewhat specific to the _jobs_... |
assert isinstance(args[0], str)
assert isinstance(args[1], (str, type(None)))
assert isinstance(args[2], (str, type(None)))
if args[2] and not args[1]:
raise ValueError("Must specify location if using port.")
return func_(*args, **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 qurl(url, add=None, exclude=None, remove=None):
""" Returns the url with changed parameters """ |
urlp = list(urlparse(url))
qp = parse_qsl(urlp[4])
# Add parameters
add = add if add else {}
for name, value in add.items():
if isinstance(value, (list, tuple)):
# Append mode
value = [smart_str(v) for v in value]
qp = [p for p in qp if p[0] != name or 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 clip_adaptor(read, adaptor):
""" Clip an adaptor sequence from this sequence. We assume it's in the 3' end. This is basically a convenience wrapper for clipT... |
missmatches = 2
adaptor = adaptor.truncate(10)
read.clip_end(adaptor, len(adaptor) - missmatches) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def contains_adaptor(read, adaptor):
""" Check whether this sequence contains adaptor contamination. If it exists, we assume it's in the 3' end. This function re... |
origSeq = read.sequenceData
clip_adaptor(read, adaptor)
res = False
if read.sequenceData != origSeq:
res = True
read.sequenceData = origSeq
return 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 reverse_complement(self, is_RNA=None):
""" Reverse complement this read in-place. """ |
Sequence.reverseComplement(self, is_RNA)
self.seq_qual = self.seq_qual[::-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 split(self, point=None):
""" Split this read into two halves. Original sequence is left unaltered. The name of the resultant reads will have '.1' and '.2' ap... |
if point is None:
point = len(self) / 2
if point < 0:
raise NGSReadError("Cannot split read at index less than 0 " +
"(index provided: " + str(point) + ")")
if point > len(self):
raise NGSReadError("Cannot split read at index greater than 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 show_slug_with_level(context, page, lang=None, fallback=True):
"""Display slug with level by language.""" |
if not lang:
lang = context.get('lang', pages_settings.PAGE_DEFAULT_LANGUAGE)
page = get_page_from_string_or_id(page, lang)
if not page:
return ''
return {'content': page.slug_with_level(lang)} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_get_pages_with_tag(parser, token):
""" Return Pages with given tag Syntax:: {% get_pages_with_tag <tag name> as <varname> %} Example use: {% get_pages_wit... |
bits = token.split_contents()
if 4 != len(bits):
raise TemplateSyntaxError('%r expects 2 arguments' % bits[0])
if bits[-2] != 'as':
raise TemplateSyntaxError(
'%r expects "as" as the second last argument' % bits[0])
varname = bits[-1]
tag = parser.compile_filter(bits[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 remove_year(name):
"""Removes year from input :param name: path to edit :return: inputs with no years """ |
for i in range(len(
name) - 3): # last index is length - 3 - 1 = length - 4
if name[i: i + 4].isdigit():
name = name[:i] + name[i + 4:]
return remove_year(
name) # if there is a removal, start again
return 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 remove_brackets(name):
"""Removes brackets form input :param name: path to fix :return: inputs with no brackets """ |
name = re.sub(
r"([(\[]).*?([)\]])",
r"\g<1>\g<2>",
name
) # remove anything in between brackets
brackets = "()[]{}" # list of brackets
for bracket in brackets:
name = name.replace(bracket, "")
return 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 extract_name_max_chars(name, max_chars=64, blank=" "):
"""Extracts max chars in name truncated to nearest word :param name: path to edit :param max_chars: ma... |
new_name = name.strip()
if len(new_name) > max_chars:
new_name = new_name[:max_chars] # get at most 64 chars
if new_name.rfind(blank) > 0:
new_name = new_name[:new_name.rfind(blank)] # nearest word
return new_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 get_parent_folder_name(file_path):
"""Finds parent folder of file :param file_path: path :return: Name of folder container """ |
return os.path.split(os.path.split(os.path.abspath(file_path))[0])[-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 ls_dir(path, include_hidden=False):
"""Finds content of folder :param path: directory to get list of files and folders :param include_hidden: True iff includ... |
lst = []
for file in os.listdir(path):
hidden_file = FileSystem(file).is_hidden()
if (hidden_file and include_hidden) or (not hidden_file):
lst.append(os.path.join(path, file))
return list(set(lst)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ls_recurse(path, include_hidden=False):
"""Finds content of folder recursively :param path: directory to get list of files and folders :param include_hidden:... |
lst = []
for file in os.listdir(path):
hidden_file = FileSystem(file).is_hidden()
if (hidden_file and include_hidden) or (not hidden_file):
lst.append(os.path.join(path, file))
if is_folder(os.path.join(path, file)):
lst += ls_recurse(
... |
<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_russian(self):
"""Checks if file path is russian :return: True iff document has a russian name """ |
russian_chars = 0
for char in RUSSIAN_CHARS:
if char in self.name:
russian_chars += 1 # found a russian char
return russian_chars > len(RUSSIAN_CHARS) / 2.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 rename(self, new_path):
"""Renames to new path :param new_path: new path to use """ |
rename_path = fix_raw_path(new_path)
if is_folder(self.path):
os.rename(self.path, rename_path)
else:
os.renames(self.path, rename_path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setClass(self, factoryclass):
"""Sets the constructor for the component type this label is to represent :param factoryclass: a class that, when called, resul... |
self.factoryclass = factoryclass
self.setText(str(factoryclass.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 getLabel(self, key):
"""Gets the label assigned to an axes :param key:??? :type key: str """ |
axisItem = self.getPlotItem().axes[key]['item']
return axisItem.label.toPlainText() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def updateData(self, axeskey, x, y):
"""Replaces the currently displayed data :param axeskey: name of data plot to update. Valid options are 'stim' or 'response'... |
if axeskey == 'stim':
self.stimPlot.setData(x,y)
# call manually to ajust placement of signal
ranges = self.viewRange()
self.rangeChange(self, ranges)
if axeskey == 'response':
self.clearTraces()
if self._traceUnit == '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 appendData(self, axeskey, bins, ypoints):
"""Appends data to existing plotted data :param axeskey: name of data plot to update. Valid options are 'stim' or '... |
if axeskey == 'raster' and len(bins) > 0:
x, y = self.rasterPlot.getData()
# don't plot overlapping points
bins = np.unique(bins)
# adjust repetition number to response scale
ypoints = np.ones_like(bins)*self.rasterYslots[ypoints[0]]
x = 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 setThreshold(self, threshold):
"""Sets the current threshold :param threshold: the y value to set the threshold line at :type threshold: float """ |
self.threshLine.setValue(threshold)
self.threshold_field.setValue(threshold) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setRasterBounds(self, lims):
"""Sets the raster plot y-axis bounds, where in the plot the raster will appear between :param lims: the (min, max) y-values for... |
self.rasterBottom = lims[0]
self.rasterTop = lims[1]
self.updateRasterBounds() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def updateRasterBounds(self):
"""Updates the y-coordinate slots where the raster points are plotted, according to the current limits of the y-axis""" |
yrange = self.viewRange()[1]
yrange_size = yrange[1] - yrange[0]
rmax = self.rasterTop*yrange_size + yrange[0]
rmin = self.rasterBottom*yrange_size + yrange[0]
self.rasterYslots = np.linspace(rmin, rmax, self.nreps)
self.rasterBoundsUpdated.emit((self.rasterBottom, self.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def askRasterBounds(self):
"""Prompts the user to provide the raster bounds with a dialog. Saves the bounds to be applied to the plot""" |
dlg = RasterBoundsDialog(bounds= (self.rasterBottom, self.rasterTop))
if dlg.exec_():
bounds = dlg.values()
self.setRasterBounds(bounds) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rangeChange(self, pw, ranges):
"""Adjusts the stimulus signal to keep it at the top of a plot, after any ajustment to the axes ranges takes place. This is a ... |
if hasattr(ranges, '__iter__'):
# adjust the stim signal so that it falls in the correct range
yrange_size = ranges[1][1] - ranges[1][0]
stim_x, stim_y = self.stimPlot.getData()
if stim_y is not None:
stim_height = yrange_size*STIM_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 update_thresh(self):
"""Emits a Qt signal thresholdUpdated with the current threshold value""" |
thresh_val = self.threshLine.value()
self.threshold_field.setValue(thresh_val)
self.thresholdUpdated.emit(thresh_val, self.getTitle()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def updateImage(self, imgdata, xaxis=None, yaxis=None):
"""Updates the Widget image directly. :type imgdata: numpy.ndarray, see :meth:`pyqtgraph:pyqtgraph.ImageI... |
imgdata = imgdata.T
self.img.setImage(imgdata)
if xaxis is not None and yaxis is not None:
xscale = 1.0/(imgdata.shape[0]/xaxis[-1])
yscale = 1.0/(imgdata.shape[1]/yaxis[-1])
self.resetScale()
self.img.scale(xscale, yscale)
sel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resetScale(self):
"""Resets the scale on this image. Correctly aligns time scale, undoes manual scaling""" |
self.img.scale(1./self.imgScale[0], 1./self.imgScale[1])
self.imgScale = (1.,1.) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def updateData(self, signal, fs):
"""Displays a spectrogram of the provided signal :param signal: 1-D signal of audio :type signal: numpy.ndarray :param fs: samp... |
# use a separate thread to calculate spectrogram so UI doesn't lag
t = threading.Thread(target=_doSpectrogram, args=(self.spec_done, (fs, signal),), kwargs=self.specgramArgs)
t.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 setSpecArgs(**kwargs):
"""Sets optional arguments for the spectrogram appearance. Available options: :param nfft: size of FFT window to use :type nfft: int :... |
for key, value in kwargs.items():
if key == 'colormap':
SpecWidget.imgArgs['lut'] = value['lut']
SpecWidget.imgArgs['levels'] = value['levels']
SpecWidget.imgArgs['state'] = value['state']
for w in SpecWidget.instances:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clearImg(self):
"""Clears the current image""" |
self.img.setImage(np.array([[0]]))
self.img.image = 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 editColormap(self):
"""Prompts the user with a dialog to change colormap""" |
self.editor = pg.ImageView()
# remove the ROI and Norm buttons
self.editor.ui.roiBtn.setVisible(False)
self.editor.ui.menuBtn.setVisible(False)
self.editor.setImage(self.imageArray)
if self.imgArgs['state'] is not None:
self.editor.getHistogramWidget().item.g... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def updateColormap(self):
"""Updates the currently colormap accoring to stored settings""" |
if self.imgArgs['lut'] is not None:
self.img.setLookupTable(self.imgArgs['lut'])
self.img.setLevels(self.imgArgs['levels']) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def appendData(self, xdata, ydata, color='b', legendstr=None):
"""Adds the data to the plot :param xdata: index values for data, plotted on x-axis :type xdata: n... |
item = self.plot(xdata, ydata, pen=color)
if legendstr is not None:
self.legend.addItem(item, legendstr)
return item |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setLabels(self, xlabel=None, ylabel=None, title=None, xunits=None, yunits=None):
"""Sets the plot labels :param xlabel: X-axis label (do not include units) :... |
if xlabel is not None:
self.setLabel('bottom', xlabel, units=xunits)
if ylabel is not None:
self.setLabel('left', ylabel, units=yunits)
if title is not None:
self.setTitle(title) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setPoint(self, x, group, y):
"""Sets the given point, connects line to previous point in group :param x: x value of point :type x: float :param group: group ... |
if x == -1:
# silence window
self.plot([0],[y], symbol='o')
else:
yindex = self.groups.index(group)
xdata, ydata = self.lines[yindex].getData()
if ydata is None:
xdata = [x]
ydata = [y]
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 setLabels(self, name):
"""Sets plot labels, according to predefined options :param name: The type of plot to create labels for. Options: calibration, tuning,... |
if name == "calibration":
self.setWindowTitle("Calibration Curve")
self.setTitle("Calibration Curve")
self.setLabel('bottom', "Frequency", units='Hz')
self.setLabel('left', 'Recorded Intensity (dB SPL)')
elif name == "tuning":
self.setWindowTi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loadCurve(data, groups, thresholds, absvals, fs, xlabels):
"""Accepts a data set from a whole test, averages reps and re-creates the progress plot as the sam... |
xlims = (xlabels[0], xlabels[-1])
pw = ProgressWidget(groups, xlims)
spike_counts = []
# skip control
for itrace in range(data.shape[0]):
count = 0
for ichan in range(data.shape[2]):
flat_reps = data[itrace,:,ichan,:].flatten()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def processData(self, times, response, test_num, trace_num, rep_num):
"""Calulate spike times from raw response data""" |
# invert polarity affects spike counting
response = response * self._polarity
if rep_num == 0:
# reset
self.spike_counts = []
self.spike_latencies = []
self.spike_rates = []
fs = 1./(times[1] - times[0])
# process response; calc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setSr(self, fs):
"""Sets the samplerate of the input operation being plotted""" |
self.tracePlot.setSr(fs)
self.stimPlot.setSr(fs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setWindowSize(self, winsz):
"""Sets the size of scroll window""" |
self.tracePlot.setWindowSize(winsz)
self.stimPlot.setWindowSize(winsz) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def addSpectrogram(self, ydata, fs, title=None):
"""Adds a new spectorgram plot for the given image. Generates a SpecWidget :param ydata: 2-D array of the image ... |
p = SpecWidget()
p.updateData(ydata, fs)
if title is not None:
p.setTitle(title)
self.stacker.addWidget(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 nextPlot(self):
"""Moves the displayed plot to the next one""" |
if self.stacker.currentIndex() < self.stacker.count():
self.stacker.setCurrentIndex(self.stacker.currentIndex()+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 prevPlot(self):
"""Moves the displayed plot to the previous one""" |
if self.stacker.currentIndex() > 0:
self.stacker.setCurrentIndex(self.stacker.currentIndex()-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 most_even_chunk(string, group):
"""Divide a string into a list of strings as even as possible.""" |
counts = [0] + most_even(len(string), group)
indices = accumulate(counts)
slices = window(indices, 2)
return [string[slice(*one)] for one in slices] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def most_even(number, group):
"""Divide a number into a list of numbers as even as possible.""" |
count, rest = divmod(number, group)
counts = zip_longest([count] * group, [1] * rest, fillvalue=0)
chunks = [sum(one) for one in counts]
logging.debug('chunks: %s', chunks)
return chunks |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def window(seq, count=2):
"""Slide window.""" |
iseq = iter(seq)
result = tuple(islice(iseq, count))
if len(result) == count:
yield result
for elem in iseq:
result = result[1:] + (elem,)
yield 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_modules(path):
"""Finds modules in folder recursively :param path: directory :return: list of modules """ |
lst = []
folder_contents = os.listdir(path)
is_python_module = "__init__.py" in folder_contents
if is_python_module:
for file in folder_contents:
full_path = os.path.join(path, file)
if is_file(full_path):
lst.append(full_path)
if is_folder... |
<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(self):
"""Parses file contents :return: Tree hierarchy of file """ |
with open(self.path, "rt") as reader:
return ast.parse(reader.read(), filename=self.path) |
<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_package(self, root_package):
"""Finds package name of file :param root_package: root package :return: package name """ |
package = self.path.replace(root_package, "")
if package.endswith(".py"):
package = package[:-3]
package = package.replace(os.path.sep, MODULE_SEP)
root_package = get_folder_name(root_package)
package = root_package + package # add root
return package |
<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_instances(self, instance):
"""Finds all instances of instance in tree :param instance: type of object :return: list of objects in tree of same instance ... |
return [
x
for x in self.tree.body
if isinstance(x, 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 get_classes(self):
"""Finds classes in file :return: list of top-level classes """ |
instances = self._get_instances(ast.ClassDef)
instances = [
PyClass(instance, self.package)
for instance in instances
]
return instances |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def best_assemblyfile(self):
""" Determine whether the contigs.fasta output file from the assembler is present. If not, set the .bestassembly attribute to 'NA' "... |
for sample in self.metadata:
try:
# Set the name of the filtered assembly file
filtered_outputfile = os.path.join(self.path, 'raw_assemblies', '{}.fasta'.format(sample.name))
# Set the name of the unfiltered spades assembly output 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 get(self, group_id=None, **kwargs):
"""Get component groups :param group_id: Component group ID (optional) :return: Component groups data (:class:`dict`) Add... |
path = 'components/groups'
if group_id is not None:
path += '/%s' % group_id
return self.paginate_get(path, data=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 create(self, name, order=None, collapsed=None):
"""Create a new Component Group :param str name: Name of the component group :param int order: Order of the c... |
data = ApiParams()
data['name'] = name
data['order'] = order
data['collapsed'] = collapsed
return self._post('components/groups', data=data)['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 update(self, group_id, name=None, order=None, collapsed=None):
"""Update a Component Group :param int group_id: Component Group ID :param str name: Name of t... |
data = ApiParams()
data['group'] = group_id
data['name'] = name
data['order'] = order
data['collapsed'] = collapsed
return self._put('components/groups/%s' % group_id, data=data)['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 create(self, name, message, status, visible, component_id=None, component_status=None, notify=None, created_at=None, template=None, tplvars=None):
"""Create ... |
data = ApiParams()
data['name'] = name
data['message'] = message
data['status'] = status
data['visible'] = visible
data['component_id'] = component_id
data['component_status'] = component_status
data['notify'] = notify
data['created_at'] = created... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self, incident_id, name=None, message=None, status=None, visible=None, component_id=None, component_status=None, notify=None, created_at=None, template... |
data = ApiParams()
data['name'] = name
data['message'] = message
data['status'] = status
data['visible'] = visible
data['component_id'] = component_id
data['component_status'] = component_status
data['notify'] = notify
data['created_at'] = created... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(self, name, suffix, description, default_value, display=None):
"""Create a new Metric :param str name: Name of metric :param str suffix: Metric unit :... |
data = ApiParams()
data['name'] = name
data['suffix'] = suffix
data['description'] = description
data['default_value'] = default_value
data['display'] = display
return self._post('metrics', data=data)['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 create(self, metric_id, value, timestamp=None):
"""Add a Metric Point to a Metric :param int metric_id: Metric ID :param int value: Value to plot on the metr... |
data = ApiParams()
data['value'] = value
data['timestamp'] = timestamp
return self._post('metrics/%s/points' % metric_id, data=data)['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 create(self, email, verify=None, components=None):
"""Create a new subscriber :param str email: Email address to subscribe :param bool verify: Whether to sen... |
data = ApiParams()
data['email'] = email
data['verify'] = verify
data['components'] = components
return self._post('subscribers', data=data)['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 annotatedcore(self):
""" Calculates the core genome of organisms using custom databases """ |
logging.info('Calculating annotated core')
# Determine the total number of core genes
self.total_core()
# Iterate through all the samples, and process all Escherichia
for sample in self.metadata:
if sample.general.bestassemblyfile != 'NA':
# Create 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 total_core(self):
""" Determine the total number of core genes present """ |
corefile = os.path.join(self.reffilepath, self.analysistype, 'Escherichia', 'core_combined.fasta')
for record in SeqIO.parse(corefile, 'fasta'):
gene_name = record.id.split('-')[0]
if gene_name not in self.coregenomes:
self.coregenomes.append(gene_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 get_simple_output(self, stderr=STDOUT):
"""Executes a simple external command and get its output The command contains no pipes. Error messages are redirected... |
args = shlex.split(self.cmd)
proc = Popen(args, stdout=PIPE, stderr=stderr)
return proc.communicate()[0].decode("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 get_complex_output(self, stderr=STDOUT):
"""Executes a piped command and get the lines of the output in a list :param stderr: where to put stderr :return: ou... |
proc = Popen(self.cmd, shell=True, stdout=PIPE, stderr=stderr)
return proc.stdout.readlines() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def keep_alive(self):
"""Keeps a process alive. If the process terminates, it will restart it The terminated processes become zombies. They die when their parent... |
while True:
pid = self.execute_in_background()
p = psutil.Process(pid)
while p.is_running() and str(p.status) != 'zombie':
os.system('sleep 5') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.