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 simple_filter(self, key, value):
"Search keys whose values match with the searched values"
searched = {key: value}
return set([k for k, v in self.data.items() if
intersect(searched, v) == searched]) |
<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(self, **kwargs):
""" Filter data according to the given arguments. """ |
keys = self.filter_keys(**kwargs)
return self.keys_to_values(keys) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_index(self, name, recreate=False, _type='default'):
""" Create an index. If recreate is True, recreate even if already there. """ |
if name not in self.indexes or recreate:
self.build_index(name, _type) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def build_index(self, idx_name, _type='default'):
"Build the index related to the `name`."
indexes = {}
has_non_string_values = False
for key, item in self.data.items():
if idx_name in item:
value = item[idx_name]
# A non-string index value swi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _clean_index(self):
"Clean index values after loading."
for idx_name, idx_def in self.index_defs.items():
if idx_def['type'] == 'lazy':
self.build_index(idx_name)
for index_name, values in self.indexes.items():
for value in values:
if 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 make_command(tasks, *args, **kwargs):
""" Create a TaskCommand with defined tasks. This is a helper function to avoid boiletplate when dealing with simple ca... |
command = TaskCommand(tasks=tasks, *args, **kwargs)
return 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 execute_command(command, args):
""" Runs the provided command with the given args. Exceptions, if any, are propogated to the caller. Arguments: command - som... |
if args is None:
args = sys.argv[1:]
try:
command.execute(args)
except IOError as failure:
if failure.errno == errno.EPIPE:
# This probably means we were piped into something that terminated
# (e.g., head). Might be a better way to handle this, but for now
... |
<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(self, *args, **kwargs):
""" Initializes and runs the tool. This is shorhand to parse command line arguments, then calling: self.setup(parsed_argument... |
args = self.parser.parse_args(*args, **kwargs)
self.process(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 process_targets(self, targets, full_config, arguments):
""" Calls the tasks with the appropriate options for each of the targets. """ |
executor = _get_executor(arguments)
resolver = _get_resolver(arguments)
dep_manager = resolver(targets, full_config, self._task_order)
task_queue = dep_manager.get_queue()
config_info = devpipeline_core.configinfo.ConfigInfo(executor)
try:
failed = []
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _user_input() -> str: """ A helper function which waits for user multi-line input. :return: A string input by user, separated by ``'\\n'``. """ |
lines = []
try:
while True:
line = input()
if line != '':
lines.append(line)
else:
break
except (EOFError, KeyboardInterrupt):
return '\n'.join(lines) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def infile_path(self) -> Optional[PurePath]: """ Read-only property. :return: A ``pathlib.PurePath`` object or ``None``. """ |
if not self.__infile_path:
return Path(self.__infile_path).expanduser()
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generator(self) -> Iterator[str]: """ Create a generate that iterates the whole content of the file or string. :return: An iterator iterating the lines of the... |
stream = self.stream # In case that ``self.stream`` is changed.
stream.seek(0)
for line in stream:
yield line |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generator_telling_position(self) -> Iterator[Tuple[str, int]]: """ Create a generate that iterates the whole content of the file or string, and also tells whi... |
stream = self.stream # In case that ``self.stream`` is changed.
stream.seek(0)
for line in stream:
yield line, stream.tell() |
<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_value(self, string, key, inline_code=True):
"""Extract strings from the docstrings .. code-block:: text * synopsis: ``%shorten{text, max_size}`` * ex... |
regex = r'\* ' + key + ': '
if inline_code:
regex = regex + '``(.*)``'
else:
regex = regex + '(.*)'
value = re.findall(regex, string)
if value:
return value[0].replace('``', '')
else:
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 underline(self, text, indent=4):
"""Underline a given text""" |
length = len(text)
indentation = (' ' * indent)
return indentation + text + '\n' + indentation + ('-' * length) |
<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(self, text, width=78, indent=4):
"""Apply textwrap to a given text string""" |
return textwrap.fill(
text,
width=width,
initial_indent=' ' * indent,
subsequent_indent=' ' * indent,
) |
<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):
"""Retrieve a formated text string""" |
output = ''
for f in self.functions:
output += self.underline(f) + '\n\n'
if f in self.synopsises and isinstance(self.synopsises[f], str):
output += self.format(self.synopsises[f]) + '\n'
if f in self.descriptions and isinstance(
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 propagate(w, b, X, Y):
""" Implement the cost function and its gradient for the propagation Arguments: w weights, a numpy array of size (dim, 1) b bias, a sc... |
m = X.shape[1]
A = sigmoid(np.dot(w.T, X) + b)
cost = -1 / m * np.sum(Y * np.log(A) + (1 - Y) * np.log(1 - A))
# BACKWARD PROPAGATION (TO FIND GRAD)
dw = 1.0 / m * np.dot(X, (A - Y).T)
db = 1.0 / m * np.sum(A - Y)
assert (dw.shape == w.shape)
assert (db.dtype == float)
cost = np.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 LR_train(w, b, X, Y, num_iterations, learning_rate, print_cost=True):
""" This function optimizes w and b by running a gradient descent algorithm Arguments: ... |
costs = []
for i in range(num_iterations):
# Cost and gradient calculation
grads, cost = propagate(w, b, X, Y)
# Retrieve derivatives from grads
dw = grads["dw"]
db = grads["db"]
# update rule
w = w - learning_rate * dw
b = b - learning_rate ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def model(X_train, Y_train, X_test, Y_test, num_iterations=2000, learning_rate=0.5, print_cost=True):
""" Builds the logistic regression model by calling the fun... |
print('X_train shape:', X_train.shape)
# initialize parameters with zeros
w, b = initialize_with_zeros(X_train.shape[0])
print('w shape:', w.shape)
# Gradient descent
parameters, grads, costs = LR_train(w, b, X_train, Y_train, num_iterations,
learning_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 plot_lc(d):
"""plot learning curve Arguments: d Returned by model function. Dictionary containing information about the model. """ |
costs = np.squeeze(d['costs'])
plt.plot(costs)
plt.ylabel('cost')
plt.xlabel('iterations (per hundreds)')
plt.title("Learning rate =" + str(d["learning_rate"]))
plt.show() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getLogLevelNo(level):
"""Return numerical log level or raise ValueError. A valid level is either an integer or a string such as WARNING etc.""" |
if isinstance(level,(int,long)):
return level
try:
return(int(logging.getLevelName(level.upper())))
except:
raise ValueError('illegal loglevel %s' % level) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cmdLine(useBasename=False):
"""Return full command line with any necessary quoting.""" |
qargv = []
cmdwords = list(sys.argv)
if useBasename:
cmdwords[0] = os.path.basename(cmdwords[0])
for s in cmdwords:
# any white space or special characters in word so we need quoting?
if re.search(r'\s|\*|\?', s):
if "'" in s:
qargv.append('"%s"' % re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handleError(exception, debugFlag=False, abortFlag=True):
"""Error handling utility. Print more or less error information depending on debug flag. Unless abor... |
if isinstance(exception, CmdError) or not debugFlag:
error(str(exception))
else:
import traceback
traceback.print_exc()
error(str(exception)) # or log complete traceback as well?
if abortFlag:
sys.exit(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 confirm(msg, acceptByDefault=False, exitCodeOnAbort=1, batch=False):
"""Get user confirmation or abort execution. confirm returns True (if user confirms) or ... |
if batch:
return
if acceptByDefault:
msg += ' - are you sure [y] ? '
else:
msg += ' - are you sure [n] ? '
while True:
reply = raw_input(msg).lower()
print
if reply == '':
reply = 'y' if acceptByDefault else 'n'
if reply == 'y':
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write(self, text):
"""Write text. An additional attribute terminator with a value of None is added to the logging record to indicate that StreamHandler shoul... |
self.logger.log(self.loglevel, text, extra={'terminator': 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 emit(self, record):
"""Emit a record. Unless record.terminator is set, a trailing newline will be written to the output stream.""" |
try:
msg = self.format(record)
if isinstance(msg,unicode):
if hasattr(self.stream, "encoding") and self.stream.encoding:
# Stream should take care of encoding, but do it explicitly to
# prevent bug in Python 2.6 - see
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flush(self):
"""Flush the stream. In contrast to StreamHandler, errors are not caught so the program doesn't iterate through tons of logging errors e.g. in c... |
# See /usr/lib64/python2.7/logging/__init__.py, StreamHander.flush()
self.acquire()
try:
if self.stream and hasattr(self.stream, "flush"):
self.stream.flush()
except IOError as e:
if self.abortOnIOError:
sys.exit('IOError: %s' % e)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def emit(self, record):
"""Emit record after checking if message triggers later sending of e-mail.""" |
if self.triggerLevelNo is not None and record.levelno>=self.triggerLevelNo:
self.triggered = True
logging.handlers.BufferingHandler.emit(self,record) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flush(self):
"""Send messages by e-mail. The sending of messages is suppressed if a trigger severity level has been set and none of the received messages was... |
if self.triggered and len(self.buffer) > 0:
# Do not send empty e-mails
text = []
for record in self.buffer:
terminator = getattr(record, 'terminator', '\n')
s = self.format(record)
if terminator is not None:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_option(self, *args, **kwargs):
"""Add optparse or argparse option depending on CmdHelper initialization.""" |
if self.parseTool == 'argparse':
if args and args[0] == '': # no short option
args = args[1:]
return self.parser.add_argument(*args, **kwargs)
else:
return self.parser.add_option(*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 make_string(seq):
""" Don't throw an exception when given an out of range character. """ |
string = ''
for c in seq:
# Screen out non-printing characters
try:
if 32 <= c and c < 256:
string += chr(c)
except TypeError:
pass
# If no printing chars
if not string:
return str(seq)
return string |
<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_file(file_path_name):
""" Read the content of the specified file. @param file_path_name: path and name of the file to read. @return: content of the spec... |
with io.open(os.path.join(os.path.dirname(__file__), file_path_name), mode='rt', encoding='utf-8') as fd:
return fd.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 run(self, react=True, strict=True, roles=1):
"""Select a cast and perform the next scene. :param bool react: If `True`, then Property directives are executed... |
try:
folder, index, self.script, self.selection, interlude = self.next(
self.folders, self.ensemble,
strict=strict, roles=roles
)
except TypeError:
raise GeneratorExit
with self.script as dialogue:
model = dialogue.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def md5(self):
""" Returns the md5-sum of this file. This is of course potentially expensive! """ |
hash_ = hashlib.md5()
with self.open("rb") as inf:
block = inf.read(4096)
while block:
hash_.update(block)
block = inf.read(4096)
return hash_.hexdigest() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lock(self, fail_on_lock=False, cleanup=False):
""" Allows to lock a file via abl.util.LockFile, with the same parameters there. Returns an opened, writable f... |
return self.connection.lock(self, fail_on_lock, cleanup) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _manipulate(self, *args, **kwargs):
""" This is a semi-private method. It's current use is to manipulate memory file system objects so that you can create ce... |
self.connection._manipulate(self, *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 move(self, source, destination):
""" the semantic should be like unix 'mv' command """ |
if source.isfile():
source.copy(destination)
source.remove()
else:
source.copy(destination, recursive=True)
source.remove('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 parser(self):
""" Instantiates the argparse parser """ |
if self._parser is None:
apkw = {
'description': self.description,
'epilog': self.epilog,
}
self._parser = argparse.ArgumentParser(**apkw)
# For Python 3 add version as a default command
if self.version:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def subparsers(self):
""" Insantiates the subparsers for all commands """ |
if self._subparsers is None:
apkw = {
'title': 'commands',
'description': 'Commands for the %s program' % self.parser.prog,
}
self._subparsers = self.parser.add_subparsers(**apkw)
return self._subparsers |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register(self, command):
""" Registers a command with the program """ |
command = command()
if command.name in self.commands:
raise ConsoleError(
"Command %s already registered!" % command.name
)
command.create_parser(self.subparsers)
self.commands[command.name] = 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 exit(self, code=0, message=None):
""" Exit the console program sanely. """ |
## If we have a parser, use it to exit
if self._parser:
if code > 0:
self.parser.error(message)
else:
self.parser.exit(code, message)
## Else we are exiting before parser creation
else:
if message is not None:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute(self):
""" Entry point to the execution of the program. """ |
# Ensure that we have commands registered
if not self.commands or self._parser is None:
raise NotImplementedError(
"No commands registered with this program!"
)
# Handle input from the command line
args = self.parser.parse_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 get_lang_array(self):
"""gets supported langs as an array""" |
r = self.yandex_translate_request("getLangs", "")
self.handle_errors(r)
return r.json()["dirs"] |
<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_lang_dict(self):
"""gets supported langs as an dictionary""" |
r = self.yandex_translate_request("getLangs")
self.handle_errors(r)
return r.json()["langs"] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _browser_init(self):
""" Init the browsing instance if not setup :rtype: None """ |
if self.session:
return
self.session = requests.Session()
headers = {}
if self.user_agent:
headers['User-agent'] = self.user_agent
self.session.headers.update(headers)
if self._auth_method in [None, "", "HTTPBasicAuth"]:
if self._au... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_scrap(self, path):
""" Load scraper settings from file :param path: Path to file :type path: str :rtype: None :raises WEBFileException: Failed to load s... |
try:
conf = self.load_settings(path)
except:
# Should only be IOError
self.exception("Failed to load file")
raise WEBFileException("Failed to load from {}".format(path))
if "scheme" not in conf:
raise WEBParameterException("Missing sc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def request( self, method, url, timeout=None, headers=None, data=None, params=None ):
""" Make a request using the requests library :param method: Which http met... |
if headers is None:
headers = {}
if not self.session:
self._browser_init()
try:
response = self.session.request(
method,
url,
timeout=timeout,
allow_redirects=self._handle_redirect,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scrap(self, url=None, scheme=None, timeout=None, html_parser=None, cache_ext=None ):
""" Scrap a url and parse the content according to scheme :param url: Ur... |
if not url:
url = self.url
if not scheme:
scheme = self.scheme
if not timeout:
timeout = self.timeout
if not html_parser:
html_parser = self.html_parser
if not scheme:
raise WEBParameterException("Missing scheme definit... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _shrink_list(self, shrink):
""" Shrink list down to essentials :param shrink: List to shrink :type shrink: list :return: Shrunk list :rtype: list """ |
res = []
if len(shrink) == 1:
return self.shrink(shrink[0])
else:
for a in shrink:
temp = self.shrink(a)
if temp:
res.append(temp)
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 _shrink_dict(self, shrink):
""" Shrink dict down to essentials :param shrink: Dict to shrink :type shrink: dict :return: Shrunk dict :rtype: dict """ |
res = {}
if len(shrink.keys()) == 1 and "value" in shrink:
return self.shrink(shrink['value'])
else:
for a in shrink:
res[a] = self.shrink(shrink[a])
if not res[a]:
del res[a]
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 shrink(self, shrink):
""" Remove unnecessary parts :param shrink: Object to shringk :type shrink: dict | list :return: Shrunk object :rtype: dict | list """ |
if isinstance(shrink, list):
return self._shrink_list(shrink)
if isinstance(shrink, dict):
return self._shrink_dict(shrink)
return shrink |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def mode_name(mode):
'''Tries best-effortly to get the right mode name'''
if mode:
l = mode.lower()
if l in ('java', ):
return ('clike', 'text/x-java')
if l in ('c', ):
return ('clike', 'text/x-csrc')
if l in ('c++', 'cxx'):
return ('clike', ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def simulate(radius=5e-6, sphere_index=1.339, medium_index=1.333, wavelength=550e-9, grid_size=(80, 80), model="projection", pixel_size=None, center=None):
"""Si... |
if isinstance(grid_size, numbers.Integral):
# default to square-shape grid
grid_size = (grid_size, grid_size)
if pixel_size is None:
# select simulation automatically
rl = radius / wavelength
if rl < 5:
# a lot of diffraction artifacts may occur;
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def params(self):
"""Current interpolation parameter dictionary""" |
par = {"radius": self.radius,
"sphere_index": self.sphere_index,
"pha_offset": self.pha_offset,
"center": [self.posx_offset, self.posy_offset]
}
return par |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def range_n(self):
"""Current interpolation range of refractive index""" |
return self.sphere_index - self.dn, self.sphere_index + self.dn |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def range_r(self):
"""Current interpolation range of radius""" |
return self.radius - self.dr, self.radius + self.dr |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compute_qpi(self):
"""Compute model data with current parameters Returns ------- qpi: qpimage.QPImage Modeled phase data Notes ----- The model image might de... |
kwargs = self.model_kwargs.copy()
kwargs["radius"] = self.radius
kwargs["sphere_index"] = self.sphere_index
kwargs["center"] = [self.posx_offset, self.posy_offset]
qpi = self.sphere_method(**kwargs)
# apply phase offset
bg_data = np.ones(qpi.shape) * -self.pha_of... |
<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_border_phase(self, idn=0, idr=0):
"""Return one of nine border fields Parameters idn: int Index for refractive index. One of -1 (left), 0 (center), 1 (ri... |
assert idn in [-1, 0, 1]
assert idr in [-1, 0, 1]
n = self.sphere_index + self.dn * idn
r = self.radius + self.dr * idr
# convert to array indices
idn += 1
idr += 1
# find out whether we need to compute a new border field
if self._n_border[idn, ... |
<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_phase(self, nintp=None, rintp=None, delta_offset_x=0, delta_offset_y=0):
"""Interpolate from the border fields to new coordinates Parameters nintp: float... |
if nintp is None:
nintp = self.sphere_index
if rintp is None:
rintp = self.radius
assert (rintp == self.radius or nintp ==
self.sphere_index), "Only r or n can be changed at a time."
assert rintp >= self.radius - self.dr
assert rintp <= ... |
<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_empty_text(self):
"""Display the empty text """ |
self.buffer.insert_with_tags_by_name(
self.buffer.get_start_iter(),
self.empty_text, 'empty-text') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def buildMessage(headers, parts):
""" Builds a message from some headers and MIME parts. """ |
message = multipart.MIMEMultipart('alternative')
for name, value in headers.iteritems():
name = name.title()
if name == "From":
multipart[name] = _encodeAddress(value)
elif name in ["To", "Cc", "Bcc"]:
multipart[name] = _encodeAddresses(value)
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 _encodeHeader(headerValue):
""" Encodes a header value. Returns ASCII if possible, else returns an UTF-8 encoded e-mail header. """ |
try:
return headerValue.encode('ascii', 'strict')
except UnicodeError:
encoded = headerValue.encode("utf-8")
return header.Header(encoded, "UTF-8").encode() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def messageToFile(message):
""" Flattens a message into a file-like object. """ |
outFile = StringIO()
messageGenerator = generator.Generator(outFile, False)
messageGenerator.flatten(message)
outFile.seek(0, 0)
return outFile |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def analyze(qpi, r0, edgekw={}, ret_center=False, ret_edge=False):
"""Determine refractive index and radius using Canny edge detection Compute the refractive ind... |
nmed = qpi["medium index"]
px_m = qpi["pixel size"]
wl_m = qpi["wavelength"]
px_wl = px_m / wl_m
phase = qpi.pha
# determine edge
edge = contour_canny(image=phase,
radius=r0 / px_m,
verbose=False,
**edgekw,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def average_sphere(image, center, radius, weighted=True, ret_crop=False):
"""Compute the weighted average phase from a phase image of a sphere Parameters image: ... |
sx, sy = image.shape
x = np.arange(sx).reshape(-1, 1)
y = np.arange(sy).reshape(1, -1)
discsq = ((x - center[0])**2 + (y - center[1])**2)
root = radius**2 - discsq
# height of the cell for each x and y
h = 2 * np.sqrt(root * (root > 0))
# compute phase density
rho = np.zeros(image.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 circle_fit(edge, ret_dev=False):
"""Fit a circle to a boolean edge image Parameters edge: 2d boolean ndarray Edge image ret_dev: bool Return the average devi... |
sx, sy = edge.shape
x = np.linspace(0, sx, sx, endpoint=False).reshape(-1, 1)
y = np.linspace(0, sy, sy, endpoint=False).reshape(1, -1)
params = lmfit.Parameters()
# initial parameters
sum_edge = np.sum(edge)
params.add("cx", np.sum(x * edge) / sum_edge)
params.add("cy", np.sum(y * edge... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def circle_radii(params, xedge, yedge):
"""Compute the distance to the center from cartesian coordinates This method is used for fitting a circle to a set of con... |
cx = params["cx"].value
cy = params["cy"].value
radii = np.sqrt((cx - xedge)**2 + (cy - yedge)**2)
return radii |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def circle_residual(params, xedge, yedge):
"""Residuals for circle fitting Parameters params: lmfit.Parameters Must contain the keys: - "cx": origin of x coordin... |
radii = circle_radii(params, xedge, yedge)
return radii - np.mean(radii) |
<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_run_command_dialog(command, shell=False, title='', data_callback=None,
parent=None, **kwargs):
'''
Launch command in a subprocess and create a dialog window to monitor the
output of the process.
Parameters
----------
command : list or str
Subprocess co... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def api_key_from_file(url):
""" Check bugzillarc for an API key for this Bugzilla URL. """ |
path = os.path.expanduser('~/.config/python-bugzilla/bugzillarc')
cfg = SafeConfigParser()
cfg.read(path)
domain = urlparse(url)[1]
if domain not in cfg.sections():
return None
if not cfg.has_option(domain, 'api_key'):
return None
return cfg.get(domain, 'api_key') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call(self, action, payload):
""" Make an XML-RPC call to the server. This method will automatically authenticate the call with self.api_key, if that is set. ... |
if self.api_key:
payload['Bugzilla_api_key'] = self.api_key
d = self.proxy.callRemote(action, payload)
d.addErrback(self._parse_errback)
return d |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def assign(self, bugids, user):
""" Assign a bug to a user. param bugid: ``int``, bug ID number. param user: ``str``, the login name of the user to whom the bug ... |
payload = {'ids': (bugids,), 'assigned_to': user}
d = self.call('Bug.update', payload)
d.addCallback(self._parse_bug_assigned_callback)
return d |
<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_by_external_tracker(self, url, id_):
""" Find a list of bugs by searching an external tracker URL and ID. param url: ``str``, the external ticket URL, e... |
payload = {
'include_fields': ['id', 'summary', 'status'],
'f1': 'external_bugzilla.url',
'o1': 'substring',
'v1': url,
'f2': 'ext_bz_bug_map.ext_bz_bug_id',
'o2': 'equals',
'v2': id_,
}
d = self.call('Bug.searc... |
<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_bugs_callback(self, value):
""" Fires when we get bug information back from the XML-RPC server. param value: dict of data from XML-RPC server. The "bu... |
return list(map(lambda x: self._parse_bug(x), value['bugs'])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def onSettingsChange(self, plugin_name, data):
""" The plugin has been changed by the frontend :param plugin_name: Name of plugin that changed :type plugin_name:... |
logger.info(u"onSettingsChange: {}".format(data))
if not plugin_name:
logger.error("Missing plugin name")
return
if not data:
logger.error("Missing data")
return
logger.info(u"Sending data {}".format(data))
reactor.callFromThread(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 onRefreshPluginData(self, plugin_name, data):
""" Frontend requests a data refresh :param plugin_name: Name of plugin that changed :type plugin_name: str :pa... |
logger.info(u"onRefreshPluginData: {}".format(plugin_name))
if not plugin_name:
logger.error("Missing plugin name")
return
reactor.callFromThread(self._sendJSON, {
'msg': "plugin_data_get",
'plugin_name': plugin_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 connect(self,soft_reset=False,**options):
""" This just creates the websocket connection """ |
self._state = STATE_CONNECTING
logger.debug("About to connect to {}".format(self.url))
m = re.search('(ws+)://([\w\.]+)(:?:(\d+))?',self.url)
options['subprotocols'] = ['wamp.2.json']
options['enable_multithread'] = True
options.setdefault('timeout',self._loop_timeout)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hello(self,details=None):
""" Say hello to the server and wait for the welcome message before proceeding """ |
self._welcome_queue = queue.Queue()
if details is None:
details = {}
if self.authid:
details.setdefault('authid', self.authid)
details.setdefault('agent', u'swampyer-1.0')
details.setdefault('authmethods', self.authmethods or [u'anonymous'])
deta... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call(self, uri, *args, **kwargs ):
""" Sends a RPC request to the WAMP server """ |
if self._state == STATE_DISCONNECTED:
raise Exception("WAMP is currently disconnected!")
options = {
'disclose_me': True
}
uri = self.get_full_uri(uri)
message = self.send_and_await_response(CALL(
options=options,
... |
<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_message(self,message):
""" Send awamp message to the server. We don't wait for a response here. Just fire out a message """ |
if self._state == STATE_DISCONNECTED:
raise Exception("WAMP is currently disconnected!")
message = message.as_str()
logger.debug("SND>: {}".format(message))
if not self.ws:
raise Exception("WAMP is currently disconnected!")
self.ws.send(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 send_and_await_response(self,request):
""" Used by most things. Sends out a request then awaits a response keyed by the request_id """ |
if self._state == STATE_DISCONNECTED:
raise Exception("WAMP is currently disconnected!")
wait_queue = queue.Queue()
request_id = request.request_id
self._requests_pending[request_id] = wait_queue;
self.send_message(request)
try:
return wait_queue.... |
<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_to_awaiting(self,result):
""" Send dat ato the appropriate queues """ |
# If we are awaiting to login, then we might also get
# an abort message. Handle that here....
if self._state == STATE_AUTHENTICATING:
# If the authentication message is something unexpected,
# we'll just ignore it for now
if result == WAMP_ABORT \
... |
<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_abort(self, reason):
""" We're out? """ |
self._welcome_queue.put(reason)
self.close()
self.disconnect() |
<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_invocation(self, message):
""" Passes the invocation request to the appropriate callback. """ |
req_id = message.request_id
reg_id = message.registration_id
if reg_id in self._registered_calls:
handler = self._registered_calls[reg_id][REGISTERED_CALL_CALLBACK]
invoke = WampInvokeWrapper(self,handler,message)
invoke.start()
else:
erro... |
<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_event(self, event):
""" Send the event to the subclass or simply reject """ |
subscription_id = event.subscription_id
if subscription_id in self._subscriptions:
# FIXME: [1] should be a constant
handler = self._subscriptions[subscription_id][SUBSCRIPTION_CALLBACK]
WampSubscriptionWrapper(self,handler,event).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 subscribe(self,topic,callback=None,options=None):
""" Subscribe to a uri for events from a publisher """ |
full_topic = self.get_full_uri(topic)
result = self.send_and_await_response(SUBSCRIBE(
options=options or {},
topic=full_topic
))
if result == WAMP_SUBSCRIBED:
if not callback:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def publish(self,topic,options=None,args=None,kwargs=None):
""" Publishes a messages to the server """ |
topic = self.get_full_uri(topic)
if options is None:
options = {'acknowledge':True}
if options.get('acknowledge'):
request = PUBLISH(
options=options or {},
topic=topic,
args=args or [],
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disconnect(self):
""" Disconnect from the websocket and pause the process till we reconnect """ |
logger.debug("Disconnecting")
# Close off the websocket
if self.ws:
try:
if self._state == STATE_CONNECTED:
self.handle_leave()
self.send_message(GOODBYE(
details={},
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 shutdown(self):
""" Request the system to shutdown the main loop and shutdown the system This is a one-way trip! Reconnecting requires a new connection to be... |
self._request_shutdown = True
for i in range(100):
if self._state == STATE_DISCONNECTED:
break
time.sleep(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 start(self):
""" Initialize websockets, say hello, and start listening for events """ |
self.connect()
if not self.isAlive():
super(WAMPClient,self).start()
self.hello()
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self):
""" Waits and receives messages from the server. This function somewhat needs to block so is executed in its own thread until self._request_shutdo... |
while not self._request_shutdown:
# Find out if we have any data pending from the
# server
try:
# If we've been asked to stop running the
# request loop. We'll just sit and wait
# till we get asked to run again
... |
<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_challenge(self,data):
""" Executed when the server requests additional authentication """ |
# Send challenge response
self.send_message(AUTHENTICATE(
signature = self.password,
extra = {}
)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def icevol_correction(age, proxyvalue, proxytype='d18o', timeunit='ya', benthic_stack=None):
"""Correct isotopic proxy data for ice-volume contribution This func... |
age = np.array(age)
proxyvalue = np.array(proxyvalue)
assert len(age) == len(proxyvalue)
proxytype = proxytype.lower()
timeunit = timeunit.lower()
assert proxytype in ['d18o', 'dd']
assert timeunit in ['ya', 'ka', 'ma']
if benthic_stack is None:
benthic_stack = stacks.lr04
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rehearse( folders, references, handler, repeat=0, roles=1, strict=False, loop=None ):
"""Cast a set of objects into a sequence of scene scripts. Deliver the ... |
if isinstance(folders, SceneScript.Folder):
folders = [folders]
yield from handler(references, loop=loop)
matcher = Matcher(folders)
performer = Performer(folders, references)
while True:
folder, index, script, selection, interlude = performer.next(
folders, references... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def can_add_new_content(self, block, file_info):
""" new content from file_info can be added into block iff - file count limit hasn't been reached for the block ... |
return ((self._max_files_per_container == 0 or self._max_files_per_container > len(block.content_file_infos))
and (self.does_content_fit(file_info, block)
or
# check if we can fit some content by splitting the file
# Note: if max si... |
<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_init(self, fs_settings, global_quota):
fs_settings = deepcopy(fs_settings) # because we store some of the info, we need a deep copy
'''
If the same restrictions are applied for many destinations, we use the same job to avoid processing
files twice
'''
for sender_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_last_nonce(app, key, nonce):
""" Get the last_nonce used by the given key from the SQLAlchemy database. Update the last_nonce to nonce at the same time. ... |
uk = ses.query(um.UserKey).filter(um.UserKey.key==key)\
.filter(um.UserKey.last_nonce<nonce * 1000).first()
if not uk:
return None
lastnonce = copy.copy(uk.last_nonce)
# TODO Update DB record in same query as above, if possible
uk.last_nonce = nonce * 1000
try:
ses.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_user_by_key(app, key):
""" An SQLAlchemy User getting function. Get a user by public key. :param str key: the public key the user belongs to """ |
user = ses.query(um.User).join(um.UserKey).filter(um.UserKey.key==key).first()
return user |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_user():
""" Get your user object. Users may only get their own info, not others'. --- responses: '200': description: user response schema: $ref: '#/defin... |
userdict = json.loads(jsonify2(current_user.dbuser, 'User'))
return current_app.bitjws.create_response(userdict) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.