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 clean(self):
"""Verifies that beginning date is before ending date.""" |
cleaned_data = super(DatasetUploadForm, self).clean()
date_begin = self.cleaned_data.get('date_begin')
date_end = self.cleaned_data.get('date_end')
if date_end < date_begin:
msg = u'End date should be after start date.'
self.add_error('date_begin', msg)
self.add_error('date_end', msg)
return cleaned_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 _kwargs_to_attributes(self, kwargs):
""" Put keys from `kwargs` to `self`, if the keys are already there. """ |
for key, val in kwargs.iteritems():
if key not in self.__dict__:
raise ValueError(
"Can't set %s parameter - it is not defined here!" % key
)
self.__dict__[key] = val |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def assist(self, project_path, source, position, filename):
"""Return completion match and list of completion proposals :param project_path: absolute project path :param source: unicode or byte string code source :param position: character or byte cursor position :param filename: absolute path of file with source code :returns: tuple (completion match, sorted list of proposals) """ |
return self._call('assist', project_path, source, position, filename) |
<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_location(self, project_path, source, position, filename):
"""Return line number and file path where name under cursor is defined If line is None location wasn't finded. If file path is None, defenition is located in the same source. :param project_path: absolute project path :param source: unicode or byte string code source :param position: character or byte cursor position :param filename: absolute path of file with source code :returns: tuple (lineno, file path) """ |
return self._call('get_location', project_path, source, position, filename) |
<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_docstring(self, project_path, source, position, filename):
"""Return signature and docstring for current cursor call context Some examples of call context:: func(| func(arg| func(arg,| func(arg, func2(| # call context is func2 Signature and docstring can be None :param project_path: absolute project path :param source: unicode or byte string code source :param position: character or byte cursor position :param filename: absolute path of file with source code :returns: tuple (signarure, docstring) """ |
return self._call('get_docstring', project_path, source, position, filename) |
<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_scope(self, project_path, source, lineno, filename, continous=True):
""" Return scope name at cursor position For example:: class Foo: def foo(self):
pass | def bar(self):
pass get_scope return Foo.foo if continuous is True and Foo otherwise. :param project_path: absolute project path :param source: unicode or byte string code source :param position: character or byte cursor position :param filename: absolute path of file with source code :param continous: allow parent scope beetween children if False """ |
return self._call('get_scope', project_path, source, lineno, filename, continous=continous) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _masquerade(origin: str, orig: ServiceDefn, new: ServiceDefn, **map: str) -> str: """build an origin URL such that the orig has all of the mappings to new defined by map""" |
origin: ParseResult = urlparse(origin)
prev_maps = {}
if origin.query:
prev_maps = {k: v for k, v in parse_qsl(origin.query)}
r_args = {}
for new_k, orig_k in map.items():
assert new_k in new.rpcs, [new_k, new.rpcs]
assert orig_k in orig.rpcs, [orig_k, orig.rpcs]
# todo: check if the definitions are the same
new_v = new.rpcs[new_k]
orig_v = orig.rpcs[orig_k]
if orig_k in prev_maps:
orig_k = prev_maps[orig_k]
assert new_v.res == orig_v.res, [new_v.res, orig_v.res]
assert new_v.req == orig_v.req, [new_v.req, orig_v.req]
r_args[new_k] = orig_k
return urlunparse(origin._replace(query=urlencode(r_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 masquerade(origin: str, orig: Type[TA], new: Type[TB], **map: str) -> str: """Make ``orig`` appear as new""" |
return _masquerade(origin, cache_get(orig), cache_get(new), **map) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sendStatusPing(self):
""" Sends a status ping to Redunda with the instance key specified while constructing the object. """ |
data = parse.urlencode({"key": self.key, "version": self.version}).encode()
req = request.Request("https://redunda.sobotics.org/status.json", data)
response = request.urlopen(req)
jsonReturned = json.loads(response.read().decode("utf-8"))
self.location = jsonReturned["location"]
self.shouldStandby = jsonReturned["should_standby"]
self.eventCount = jsonReturned["event_count"] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def uploadFile(self, filename, ispickle=False, athome=False):
""" Uploads a single file to Redunda. :param str filename: The name of the file to upload :param bool ispickle: Optional variable to be set to True is the file is a pickle; default is False. :returns: returns nothing """ |
print("Uploading file {} to Redunda.".format(filename))
_, tail = os.path.split(filename)
url = "https://redunda.sobotics.org/bots/data/{}?key={}".format(tail, self.key)
#Set the content type to 'application/octet-stream'
header = {"Content-type": "application/octet-stream"}
filedata = ""
if athome:
filename = str(os.path.expanduser("~")) + filename
#Read the data from a file to a string.
if filename.endswith(".pickle") or ispickle:
try:
with open(filename, "rb") as fileToRead:
data = pickle.load(fileToRead)
except pickle.PickleError as perr:
print("Pickling error occurred: {}".format(perr))
return
filedata = json.dumps(data)
else:
try:
with open(filename, "r") as fileToRead:
filedata = fileToRead.read()
except IOError as ioerr:
print("IOError occurred: {}".format(ioerr))
return
requestToMake = request.Request(url, data=filedata.encode("utf-8"), headers=header)
#Make the request.
response = request.urlopen(requestToMake)
if response.code >= 400:
print("Error occurred while uploading file '{}' with error code {}.".format(filename,response.code)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def downloadFile(self, filename, ispickle=False, athome=False):
""" Downloads a single file from Redunda. :param str filename: The name of the file you want to download :param bool ispickle: Optional variable which tells if the file to be downloaded is a pickle; default is False. :returns: returns nothing """ |
print("Downloading file {} from Redunda.".format(filename))
_, tail = os.path.split(filename)
url = "https://redunda.sobotics.org/bots/data/{}?key={}".format(tail, self.key)
requestToMake = request.Request(url)
#Make the request.
response = request.urlopen(requestToMake)
if response.code != 200:
print("Error occured while downloading file '{}' with error code {}.".format(filename,response.code))
if athome:
filename = str(os.path.expanduser("~")) + filename
filedata = response.read().decode("utf-8")
try:
if filename.endswith (".pickle") or ispickle:
data = json.loads(filedata)
try:
with open(filename, "wb") as fileToWrite:
pickle.dump (data, fileToWrite)
except pickle.PickleError as perr:
print("Pickling error occurred: {}".format(perr))
return
else:
with open (filename, "w") as fileToWrite:
fileToWrite.write(filedata)
except IOError as ioerr:
print("IOError occurred: {}".format(ioerr))
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def uploadFiles(self):
""" Uploads all the files in 'filesToSync' """ |
for each_file in self.filesToSync:
self.uploadFile(each_file["name"], each_file["ispickle"], each_file["at_home"]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def downloadFiles(self):
""" Downloads all the files in 'filesToSync' """ |
for each_file in self.filesToSync:
self.downloadFile(each_file["name"], each_file["ispickle"], each_file["at_home"]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getEvents(self):
""" Gets all events from Redunda and returns them. :returns: Returns a dictionary of the events which were fetched. """ |
url = "https://redunda.sobotics.org/events.json"
data = parse.urlencode({"key": self.key}).encode()
req = request.Request(url, data)
response = request.urlopen(req)
return json.loads(response.read().decode("utf-8")) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def configure_client(cls, host: str = 'localhost', port: int = 11211, **client_args):
""" Configure a Memcached client. :param host: host name or ip address to connect to :param port: port number to connect to :param client_args: extra keyword arguments passed to :class:`aiomcache.Client` """ |
assert check_argument_types()
client = Client(host, port, **client_args)
return client |
<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_features(self):
""" Extracts and sets the feature data from the log file necessary for a reduction """ |
for parsed_line in self.parsed_lines:
# If it's ssh, we can handle it
if parsed_line.get('program') == 'sshd':
result = self._parse_auth_message(parsed_line['message'])
# Add the ip if we have it
if 'ip' in result:
self.features['ips'].append(result['ip'])
# If we haven't seen the ip, add it
if result['ip'] not in self.ips_to_pids:
# Make the value a list of pids
self.ips_to_pids[result['ip']] = [parsed_line['processid']]
else:
# If we have seen the ip before, add the pid if it's a new one
if parsed_line['processid'] not in self.ips_to_pids[result['ip']]:
self.ips_to_pids[result['ip']].append(parsed_line['processid']) |
<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(self):
""" Decide which lines should be filtered out """ |
pids = []
for ip in self.filter['ips']:
if ip in self.ips_to_pids:
for pid in self.ips_to_pids[ip]:
pids.append(pid)
for line in self.parsed_lines:
if 'processid' in line and line['processid'] in pids:
self.noisy_logs.append(line)
else:
self.quiet_logs.append(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 _to_epoch(self, ts):
""" Adds a year to the syslog timestamp because syslog doesn't use years :param ts: The timestamp to add a year to :return: Date/time string that includes a year """ |
year = self.year
tmpts = "%s %s" % (ts, str(self.year))
new_time = int(calendar.timegm(time.strptime(tmpts, "%b %d %H:%M:%S %Y")))
# If adding the year puts it in the future, this log must be from last year
if new_time > int(time.time()):
year -= 1
tmpts = "%s %s" % (ts, str(year))
new_time = int(calendar.timegm(time.strptime(tmpts, "%b %d %H:%M:%S %Y")))
return new_time |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parse_auth_message(self, auth_message):
""" Parse a message to see if we have ip addresses or users that we care about :param auth_message: The auth message to parse :return: Result """ |
result = {}
has_matched = False
for regex in REGEXES_INVALID_USER:
# Check for the invalid user/ip messages
m = re.search(regex, auth_message)
if m and not has_matched:
has_matched = True
# Save the username and IP
result['username'] = m.group('user')
result['ip'] = m.group('ip')
for regex in REGEXES_INVALID_IP:
# Check for the invalid ip messages
m = re.search(regex, auth_message)
if m and not has_matched:
has_matched = True
# Save the IP
result['ip'] = m.group('ip')
for regex in REGEXES_IGNORE:
# Check for messages we want to ignore
m = re.search(regex, auth_message)
if m and not has_matched:
has_matched = True
# If it's an ssh log and we don't know what it is, handle that
if not has_matched:
sys.stderr.write("Unhandled auth message: %s\n" % auth_message)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_until(data: bytes, *, return_tail: bool = True, from_=None) -> bytes: """ read until some bytes appear """ |
return (yield (Traps._read_until, data, return_tail, from_)) |
<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_int(nbytes: int, *, byteorder: str = "big", from_=None) -> int: """ read some bytes as integer """ |
return (yield (Traps._read_int, nbytes, byteorder, from_)) |
<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(self, data: bytes = b""):
""" send data for parsing """ |
self.input.extend(data)
self._process() |
<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_bokeh_server(io_loop, files, argvs, host, port):
'''Start bokeh server with applications paths'''
from bokeh.server.server import Server
from bokeh.command.util import build_single_handler_applications
# Turn file paths into bokeh apps
apps = build_single_handler_applications(files, argvs)
# kwargs lifted from bokeh serve call to Server, with created io_loop
kwargs = {
'io_loop':io_loop,
'generate_session_ids':True,
'redirect_root':True,
'use_x_headers':False,
'secret_key':None,
'num_procs':1,
'host': host,
'sign_sessions':False,
'develop':False,
'port':port,
'use_index':True
}
server = Server(apps,**kwargs)
return server |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _generate_request_handler_proxy(handler_class, handler_args, name):
"""When a tornado.web.RequestHandler gets mounted we create a launcher function""" |
@scope.inject
def request_handler_wrapper(app, handler, **kwargs):
handler = handler_class(app, handler.request, **handler_args)
handler._execute([], **kwargs)
request_handler_wrapper.__name__ = name
request_handler_wrapper.handler_class = handler_class
request_handler_wrapper.handler_args = handler_args
return request_handler_wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setup(self):
"""setup routing table""" |
# get all routes from submodules
for prefix, routes in self.sub_rt:
routes.prefix = self.prefix + prefix
routes.setup()
fn_name_prefixes = {}
for fn_key, fn in routes.fn_namespace.items():
self.fn_namespace[routes.name + '.' + fn_key] = fn
fn_prefix = routes.name
if '.' in fn_key:
fn_prefix += '.' + fn_key.rsplit('.', 1)[0]
fn_name_prefixes[fn] = fn_prefix
for key in self:
funcs = set(rule[1] for rule in self[key])
for route, route_module, module, fn in routes.get(key, []):
if fn not in funcs:
new_route = Route(prefix + route.path)
fn.rw_route = new_route
fn_name_prefix = fn_name_prefixes[fn]
data = (new_route, fn_name_prefix, module, fn)
self[key].append(data)
# sort all rules
for key in self:
self[key].sort(key=lambda rule: rule[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 get_version():
""" Loads the current module version from version.py and returns it. :returns: module version identifier. :rtype: str """ |
local_results = {}
version_file_path = os.path.join('pytextql', 'version.py')
# This is compatible with py3k which removed execfile.
with open(version_file_path, 'rb') as fin:
# Compiling instead of passing the text straight to exec
# associates any errors with the correct file name.
code = compile(fin.read(), version_file_path, 'exec')
exec(code, {}, local_results)
return local_results['__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 update(self, **args):
""" Updates a Clip. Parameters: - args Dictionary of other fields Accepted fields can be found here: https://github.com/kippt/api-documentation/blob/master/objects/clip.md """ |
# JSONify our data.
data = json.dumps(args)
r = requests.put(
"https://kippt.com/api/clips/%s" % (self.id),
headers=self.kippt.header,
data=data)
return (r.json()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def like(self):
""" Like a clip. """ |
r = requests.post(
"https://kippt.com/api/clips/%s/likes" % (self.id),
headers=self.kippt.header
)
return (r.json()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def comment(self, body):
""" Comment on a clip. Parameters: - body (Required) """ |
# Merge our url as a parameter and JSONify it.
data = json.dumps({'body': body})
r = requests.post(
"https://kippt.com/api/clips/%s/comments" (self.id),
headers=self.kippt.header,
data=data
)
return (r.json()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unlike(self):
""" Unlike a clip. """ |
r = requests.delete(
"https://kippt.com/api/clips/%s/likes" % (self.id),
headers=self.kippt.header)
return (r.json()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_json(value, pretty=False):
""" Serializes the given value to JSON. :param value: the value to serialize :param pretty: whether or not to format the output in a more human-readable way; if not specified, defaults to ``False`` :type pretty: bool :rtype: str """ |
options = {
'sort_keys': False,
'cls': BasicJSONEncoder,
}
if pretty:
options['indent'] = 2
options['separators'] = (',', ': ')
return json.dumps(value, **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 from_json(value, native_datetimes=True):
""" Deserializes the given value from JSON. :param value: the value to deserialize :type value: str :param native_datetimes: whether or not strings that look like dates/times should be automatically cast to the native objects, or left as strings; if not specified, defaults to ``True`` :type native_datetimes: bool """ |
hook = BasicJsonDecoder(native_datetimes=native_datetimes)
result = json.loads(value, object_hook=hook)
if native_datetimes and isinstance(result, string_types):
return get_date_or_string(result)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_yaml(value, pretty=False):
""" Serializes the given value to YAML. :param value: the value to serialize :param pretty: whether or not to format the output in a more human-readable way; if not specified, defaults to ``False`` :type pretty: bool :rtype: str """ |
if not yaml:
raise NotImplementedError('No supported YAML library available')
options = {
'Dumper': BasicYamlDumper,
'allow_unicode': True,
}
options['default_flow_style'] = not pretty
return yaml.dump(value, **options).rstrip() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_yaml(value, native_datetimes=True):
""" Deserializes the given value from YAML. :param value: the value to deserialize :type value: str :param native_datetimes: whether or not strings that look like dates/times should be automatically cast to the native objects, or left as strings; if not specified, defaults to ``True`` :type native_datetimes: bool """ |
if not yaml:
raise NotImplementedError('No supported YAML library available')
if native_datetimes:
loader = NativeDatesYamlLoader
else:
loader = StringedDatesYamlLoader
return yaml.load(value, Loader=loader) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_toml(value, pretty=False):
# noqa: unused-argument """ Serializes the given value to TOML. :param value: the value to serialize :param pretty: this argument is ignored, as no TOML libraries support this type of operation :type pretty: bool :rtype: str """ |
if not toml:
raise NotImplementedError('No supported TOML library available')
return toml.dumps(make_toml_friendly(value)).rstrip() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_toml(value, native_datetimes=True):
""" Deserializes the given value from TOML. :param value: the value to deserialize :type value: str :param native_datetimes: whether or not strings that look like dates/times should be automatically cast to the native objects, or left as strings; if not specified, defaults to ``True`` :type native_datetimes: bool """ |
if not toml:
raise NotImplementedError('No supported TOML library available')
result = toml.loads(value)
if native_datetimes:
result = convert_datetimes(result)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge_true_table():
"""Merge all true table into single excel file. """ |
writer = pd.ExcelWriter("True Table.xlsx")
for p in Path(__file__).parent.select_by_ext(".csv"):
df = pd.read_csv(p.abspath, index_col=0)
df.to_excel(writer, p.fname, index=True)
writer.save() |
<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 send(self, *args, **kwargs):
"""Send args and kwargs to all registered callbacks""" |
for callback in self:
res = callback(*args, **kwargs)
if asyncio.iscoroutine(res) or isinstance(res, asyncio.Future):
await 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 setup_logging(config=None):
"""Setup logging configuration.""" |
# TODO: integrate in general config file
print(__name__)
if config and config.get('logging'):
logging.config.dictConfig(config.get('logging'))
else:
logging.basicConfig(format='%(asctime)s %(levelname)s:%(message)s',
level=logging.DEBUG) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _create_all_recommendations(cores, ip_views=False, config=None):
"""Calculate all recommendations in multiple processes.""" |
global _reco, _store
_reco = GraphRecommender(_store)
_reco.load_profile('Profiles')
if ip_views:
_reco.load_profile('Profiles_IP')
manager = Manager()
record_list = manager.list(_reco.all_records.keys())
# record_list = manager.list(list(_reco.all_records.keys())[:10])
num_records = len(_reco.all_records.keys())
logger.info("Recommendations to build: {}".format(num_records))
start = time.time()
reco_version = config.get('recommendation_version', 0)
done_records = num_records
if cores <= 1:
_create_recommendations(0, record_list, reco_version)
else:
try:
pool = Pool(cores)
multiple_results = [pool.apply_async(_create_recommendations,
(i, record_list, reco_version))
for i in range(cores)]
# Wait for all processes to exit
[res.get() for res in multiple_results]
except KeyboardInterrupt:
print("Caught KeyboardInterrupt, terminating workers")
# TODO: Update done_records.
pool.terminate()
pool.join()
duration = time.time() - start
logger.info("Time {} for {} recommendations".format(duration,
done_records)) |
<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_weeks(self, weeks, overwrite=False):
"""Fetch and cache the requested weeks.""" |
esf = ElasticsearchFetcher(self.store, self.config)
for year, week in weeks:
print("Fetch {}-{}".format(year, week))
esf.fetch(year, week, overwrite) |
<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_all_recommendations(self, cores, ip_views=False):
"""Calculate the recommendations for all records.""" |
global _store
_store = self.store
_create_all_recommendations(cores, ip_views, self.config) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def table_dataset_database_table( table = None, include_attributes = None, rows_limit = None, print_progress = False, ):
""" Create a pyprel table contents list from a database table of the module dataset. Attributes to be included in the table can be specified; by default, all attributes are included. A limit on the number of rows included can be specified. Progress on building the table can be reported. """ |
if print_progress:
import shijian
progress = shijian.Progress()
progress.engage_quick_calculation_mode()
number_of_rows = len(table)
if include_attributes:
columns = include_attributes
else:
columns = table.columns
table_contents = [columns]
for index_row, row in enumerate(table):
if rows_limit is not None:
if index_row >= rows_limit:
break
row_contents = []
for column in columns:
try:
string_representation = str(row[column])
except:
string_representation = str(row[column].encode("utf-8"))
row_contents.append(string_representation)
table_contents.append(row_contents)
if print_progress:
print(progress.add_datum(
fraction = float(index_row) / float(number_of_rows))
)
return table_contents |
<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_nearest_indices(xs,res):
'''
Simple nearest interpolator that interpolates based on
the minima and maxima of points based on the passed
resolution in res.
Parameters:
-----------
xs -- A collection of `ndim` arrays of points.
res -- List of resolutions.
'''
maxs = [max(a) for a in xs]
mins = [min(a) for a in xs]
XS = [np.linspace(mn, mx, r) for mn,mx,r in zip(mins,maxs,res)];
XS = tuple(np.meshgrid(*XS,indexing='ij'));
if type(xs) != tuple:
xs = tuple(xs);
return nearest_indices(xs,XS); |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clear(self):
""" Clears all of the build variables. """ |
for variable in self._project.variables.list(all=True):
variable.delete() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _resolved_type(self):
"""Return the type for the columns, and a flag to indicate that the column has codes.""" |
import datetime
self.type_ratios = {test: (float(self.type_counts[test]) / float(self.count)) if self.count else None
for test, testf in tests + [(None, None)]}
# If it is more than 5% str, it's a str
try:
if self.type_ratios.get(text_type,0) + self.type_ratios.get(binary_type,0) > .05:
if self.type_counts[text_type] > 0:
return text_type, False
elif self.type_counts[binary_type] > 0:
return binary_type, False
except TypeError as e:
# This is probably the result of the type being unknown
pass
if self.type_counts[datetime.datetime] > 0:
num_type = datetime.datetime
elif self.type_counts[datetime.date] > 0:
num_type = datetime.date
elif self.type_counts[datetime.time] > 0:
num_type = datetime.time
elif self.type_counts[float] > 0:
num_type = float
elif self.type_counts[int] > 0:
num_type = int
elif self.type_counts[text_type] > 0:
num_type = text_type
elif self.type_counts[binary_type] > 0:
num_type = binary_type
else:
num_type = unknown
if self.type_counts[binary_type] > 0 and num_type != binary_type:
has_codes = True
else:
has_codes = False
return num_type, has_codes |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def promote_type(orig_type, new_type):
"""Given a table with an original type, decide whether a new determination of a new applicable type should overide the existing one""" |
if not new_type:
return orig_type
if not orig_type:
return new_type
try:
orig_type = orig_type.__name__
except AttributeError:
pass
try:
new_type = new_type.__name__
except AttributeError:
pass
type_precidence = ['unknown', 'int', 'float', 'date', 'time', 'datetime', 'str', 'bytes', 'unicode']
# TODO This will fail for dates and times.
if type_precidence.index(new_type) > type_precidence.index(orig_type):
return new_type
else:
return orig_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 data_from_repaircafe_org():
"""Gets data from repaircafe_org.""" |
# Use Chrome as a browser
browser = webdriver.Chrome()
# Use PhantomJS as a browser
# browser = webdriver.PhantomJS('phantomjs')
browser.get("https://repaircafe.org/en/?s=Contact+the+local+organisers")
browser.maximize_window()
# Iterate over results (the #viewmore_link button)
viewmore_button = True
while viewmore_button:
try:
viewmore = browser.find_element_by_id("viewmore_link")
# Scroll to the link in order to make it visible
browser.execute_script("arguments[0].scrollIntoView();", viewmore)
# Keep searching
viewmore.click()
except:
# If there's an error, we have reached the end of the search
viewmore_button = False
# Give a bit of time for loading the search results
sleep(2)
# Load the source code
page_source = BeautifulSoup(browser.page_source, "lxml")
# Close the browser
browser.quit()
# Parse the source code in order to find all the links under H4s
data = []
for h4 in page_source.find_all("h4"):
for a in h4.find_all('a', href=True):
data.append({"name": a.contents[0], "url": a['href']})
return 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 get_labs(format):
"""Gets Repair Cafe data from repairecafe.org.""" |
data = data_from_repaircafe_org()
repaircafes = {}
# Load all the Repair Cafes
for i in data:
# Create a lab
current_lab = RepairCafe()
# Add existing data from first scraping
current_lab.name = i["name"]
slug = i["url"].replace("https://repaircafe.org/locations/", "")
if slug.endswith("/"):
slug.replace("/", "")
current_lab.slug = slug
current_lab.url = i["url"]
# Scrape for more data
page_request = requests.get(i["url"])
if page_request.status_code == 200:
page_source = BeautifulSoup(page_request.text, "lxml")
else:
output = "There was an error while accessing data on repaircafe.org."
# Find Facebook and Twitter links, add also the other ones
current_lab.links = {"facebook": "", "twitter": ""}
column = page_source.find_all("div", class_="sc_column_item_2")
for j in column:
for p in j.find_all('p'):
for a in p.find_all('a', href=True):
if "facebook" in a['href']:
current_lab.links["facebook"] = a['href']
elif "twitter" in a['href']:
current_lab.links["twitter"] = a['href']
else:
current_lab.links[a['href']] = a['href']
# Find address
column = page_source.find_all("div", class_="sc_column_item_1")
for x in column:
if x.string:
print x.string.strip()
exit()
# current_lab.address_1 = i["address_1"]
# current_lab.address_2 = i["address_2"]
# current_lab.address_notes = i["address_notes"]
# current_lab.blurb = i["blurb"]
# current_lab.city = i["city"]
# current_lab.country_code = i["country_code"]
# current_lab.county = i["county"]
# current_lab.description = i["description"]
# current_lab.email = i["email"]
# current_lab.id = i["id"]
# current_lab.phone = i["phone"]
# current_lab.postal_code = i["postal_code"]
#
#
# current_lab.continent = country_alpha2_to_continent_code(i[
# "country_code"].upper())
# current_country = pycountry.countries.get(
# alpha_2=i["country_code"].upper())
# current_lab.country_code = current_country.alpha_3
# current_lab.country = current_country.name
# if i["longitude"] is None or i["latitude"] is None:
# # Be nice with the geocoder API limit
# errorsb += 1
# # sleep(10)
# # location = geolocator.geocode(
# # {"city": i["city"],
# # "country": i["country_code"].upper()},
# # addressdetails=True,
# # language="en")
# # if location is not None:
# # current_lab.latitude = location.latitude
# # current_lab.longitude = location.longitude
# # if "county" in location.raw["address"]:
# # current_lab.county = location.raw["address"][
# # "county"].encode('utf-8')
# # if "state" in location.raw["address"]:
# # current_lab.state = location.raw["address"][
# # "state"].encode('utf-8')
# else:
# # Be nice with the geocoder API limit
# sleep(10)
# errorsa += 1
# # location = geolocator.reverse((i["latitude"], i["longitude"]))
# # if location is not None:
# # if "county" in location.raw["address"]:
# # current_lab.county = location.raw["address"][
# # "county"].encode('utf-8')
# # if "state" in location.raw["address"]:
# # current_lab.state = location.raw["address"][
# # "state"].encode('utf-8')
# Add the lab to the list
repaircafes[slug] = current_lab
# Return a dictiornary / json
if format.lower() == "dict" or format.lower() == "json":
output = {}
for j in repaircafes:
output[j] = repaircafes[j].__dict__
# Return a geojson
elif format.lower() == "geojson" or format.lower() == "geo":
labs_list = []
for l in repaircafes:
single = repaircafes[l].__dict__
single_lab = Feature(
type="Feature",
geometry=Point((single["latitude"], single["longitude"])),
properties=single)
labs_list.append(single_lab)
output = dumps(FeatureCollection(labs_list))
# Return a Pandas DataFrame
elif format.lower() == "pandas" or format.lower() == "dataframe":
output = {}
for j in repaircafes:
output[j] = repaircafes[j].__dict__
# Transform the dict into a Pandas DataFrame
output = pd.DataFrame.from_dict(output)
output = output.transpose()
# Return an object
elif format.lower() == "object" or format.lower() == "obj":
output = repaircafes
# Default: return an oject
else:
output = repaircafes
# Return a proper json
if format.lower() == "json":
output = json.dumps(output)
return output |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def archive_if_exists(filename):
""" Move `filename` out of the way, archiving it by appending the current datetime Can be a file or a directory """ |
if os.path.exists(filename):
current_time = datetime.datetime.now()
dt_format = '%Y-%m-%dT%H:%M:%S%z'
timestamp = current_time.strftime(dt_format)
dst = filename + '_' + timestamp
shutil.move(filename, dst) |
<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_files(dirname, extension=None):
""" List all files in directory `dirname`, option to filter on file extension """ |
f = []
for (dirpath, dirnames, filenames) in os.walk(dirname):
f.extend(filenames)
break
if extension is not None:
# Filter on extension
filtered = []
for filename in f:
fn, ext = os.path.splitext(filename)
if ext.lower() == '.' + extension.lower():
filtered.append(filename)
f = filtered
return f |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filename_addstring(filename, text):
""" Add `text` to filename, keeping the extension in place For example when adding a timestamp to the filename """ |
fn, ext = os.path.splitext(filename)
return fn + text + ext |
<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_file_contents(filename):
""" Read file contents from file `filename` """ |
data = None
try:
with open(filename) as pf:
data = pf.read()
except IOError:
# File not found, return None
pass
return 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 parse_name(cls, name):
""" Parses a name into a dictionary of identified subsections with accompanying information to correctly identify and replace if necessary :param name: str, string to be parsed :return: dict, dictionary with relevant parsed information """ |
parse_dict = dict.fromkeys(cls.PARSABLE, None)
parse_dict['date'] = cls.get_date(name)
parse_dict['version'] = cls.get_version(name)
parse_dict['udim'] = cls.get_udim(name)
parse_dict['side'] = cls.get_side(name)
parse_dict['basename'] = cls.get_base_naive(cls._reduce_name(name, parse_dict))
return parse_dict |
<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_side(cls, name, ignore=''):
""" Checks a string for a possible side string token, this assumes its on its own and is not part of or camel cased and combined with a word. Returns first found side to reduce duplicates. We can be safe to assume the abbreviation for the side does not have camel casing within its own word. :param name: str, string that represents a possible name of an object :param name: str, string that represents a possible name of an object :return: (None, str), either the found permutation of the side found in name or None """ |
for side in cls.CONFIG_SIDES:
""" Tried using a regex, however it would've taken too long to debug
side_regex = cls._build_abbreviation_regex(side)
result = cls._generic_search(name, side_regex, metadata={'side': side}, ignore=ignore)
if result:
return result
"""
for permutations in cls.get_string_camel_patterns(side):
for permutation in permutations:
result = cls._generic_search(name, permutation, metadata={'side': side}, ignore=ignore)
if result:
return result
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 get_discipline(cls, name, ignore='', min_length=3):
""" Checks a string for a possible discipline string token, this assumes its on its own and is not part of or camel cased and combined with a word. Returns first found match to reduce duplicates. We can be safe to assume the abbreviation for the discipline does not have camel casing within its own word. :param name: str, the string based object name :param ignore: str, specific ignore string for the search to avoid :param min_length: int, minimum length for possible abbreviations of disciplines. Lower = more wrong guesses. :return: dict, match dictionary """ |
for discipline in cls.CONFIG_DISCIPLINES:
re_abbr = '({RECURSE}(?=[0-9]|[A-Z]|{SEPARATORS}))'.format(
RECURSE=cls._build_abbreviation_regex(discipline),
SEPARATORS=cls.REGEX_SEPARATORS)
matches = cls._get_regex_search(name, re_abbr, ignore=ignore)
if matches:
matches = [m for m in matches if
re.findall('([a-z]{%d,})' % min_length, m['match'], flags=re.IGNORECASE)]
if matches:
return matches[-1]
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 get_string_camel_patterns(cls, name, min_length=0):
""" Finds all permutations of possible camel casing of the given name :param name: str, the name we need to get all possible permutations and abbreviations for :param min_length: int, minimum length we want for abbreviations :return: list(list(str)), list casing permutations of list of abbreviations """ |
# Have to check for longest first and remove duplicates
patterns = []
abbreviations = list(set(cls._get_abbreviations(name, output_length=min_length)))
abbreviations.sort(key=len, reverse=True)
for abbr in abbreviations:
# We won't check for abbreviations that are stupid eg something with apparent camel casing within
# the word itself like LeF, sorting from:
# http://stackoverflow.com/questions/13954841/python-sort-upper-case-and-lower-case
casing_permutations = list(set(cls._get_casing_permutations(abbr)))
casing_permutations.sort(key=lambda v: (v.upper(), v[0].islower(), len(v)))
permutations = [permutation for permutation in casing_permutations if
cls.is_valid_camel(permutation) or len(permutation) <= 2]
if permutations:
patterns.append(permutations)
return patterns |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _reduce_name(cls, name, parse_dict):
""" Reduces a name against matches found in a parse dictionary :param name: str, name to be reduced :param parse_dict: dict, dictionary of matches to reduce against :return: str, reduced string """ |
# Now remove all found entries to make basename regex have an easier time
removal_indices = []
for section, match in iteritems(parse_dict):
try:
matches = []
if isinstance(match, dict) and 'compound_matches' in match:
matches = match.get('compound_matches')
elif not isinstance(match, list) and match is not None:
matches = [match]
for m in matches:
valid_slice = True
slice_a, slice_b = m.get('position')
# Adjust slice positions from previous slices
if removal_indices is []:
removal_indices.append((slice_a, slice_b))
for r_slice_a, r_slice_b in removal_indices:
if slice_a == r_slice_a and slice_b == r_slice_b:
valid_slice = False
if slice_a > r_slice_a or slice_a > r_slice_b or slice_b > r_slice_b or slice_b > r_slice_a:
slice_delta = r_slice_b - r_slice_a
slice_a -= slice_delta
slice_b -= slice_delta
if valid_slice:
name = cls._string_remove_slice(name, slice_a, slice_b)
removal_indices.append((slice_a, slice_b))
except (IndexError, TypeError):
pass
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 _get_regex_search(input_string, regex, metadata={}, match_index=None, ignore='', flags=0):
""" Using this so that all results from the functions return similar results :param input_string: str, input string to be checked :param regex: str, input regex to be compiled and searched with :param match_index: (int, None), whether to get a specific match, if None returns all matches as list :param metadata: dict, dictionary of extra meta tags needed to identify information :return: list(dict), list of dictionaries if multiple hits or a specific entry or None """ |
generator = re.compile(regex, flags=flags).finditer(input_string)
matches = []
for obj in generator:
try:
span_a = obj.span(1)
group_a = obj.group(1)
except IndexError:
span_a = obj.span()
group_a = obj.group()
if obj.groups() == ('',):
# Not sure how to account for this situation yet, weird regex.
return True
if group_a not in ignore:
matches.append({'pattern': regex,
'input': input_string,
'position': span_a,
'position_full': obj.span(),
'match': group_a,
'match_full': obj.group()})
if matches:
for match in matches:
match.update(metadata)
if match_index is not None:
return matches[match_index]
return matches
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 _generic_search(cls, name, search_string, metadata={}, ignore=''):
""" Searches for a specific string given three types of regex search types. Also auto-checks for camel casing. :param name: str, name of object in question :param search_string: str, string to find and insert into the search regexes :param metadata: dict, metadata to add to the result if we find a match :param ignore: str, ignore specific string for the search :return: dict, dictionary of search results """ |
patterns = [cls.REGEX_ABBR_SEOS,
cls.REGEX_ABBR_ISLAND,
cls.REGEX_ABBR_CAMEL]
if not search_string[0].isupper():
patterns.remove(cls.REGEX_ABBR_CAMEL)
for pattern in patterns:
search_result = cls._get_regex_search(name,
pattern.format(ABBR=search_string, SEP=cls.REGEX_SEPARATORS),
metadata=metadata,
match_index=0,
ignore=ignore)
if search_result is not None:
if cls.is_valid_camel(search_result.get('match_full'), strcmp=search_result.get('match')):
return search_result
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 _get_abbreviations(input_string, output_length=0):
""" Generates abbreviations for input_string :param input_string: str, name of object :param output_length: int, optional specific length of abbreviations, default is off :return: list(str), list of all combinations that include the first letter (possible abbreviations) """ |
for i, j in itertools.combinations(range(len(input_string[1:]) + 1), 2):
abbr = input_string[0] + input_string[1:][i:j]
if len(abbr) >= output_length:
yield abbr
elif output_length == 0:
yield abbr
# Have to add the solitary letter as well
if not output_length or output_length == 1:
yield input_string[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 _get_casing_permutations(cls, input_string):
""" Takes a string and gives all possible permutations of casing for comparative purposes :param input_string: str, name of object :return: Generator(str), iterator of all possible permutations of casing for the input_string """ |
if not input_string:
yield ""
else:
first = input_string[:1]
for sub_casing in cls._get_casing_permutations(input_string[1:]):
yield first.lower() + sub_casing
yield first.upper() + sub_casing |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _string_remove_slice(input_str, start, end):
""" Removes portions of a string :param input_str: str, input string :param start: int, end search index :param end: int, start search index :return: str, the cut string """ |
if 0 <= start < end <= len(input_str):
return input_str[:start] + input_str[end:]
return input_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 getvector(d,s):
'''
Get a vector flds data.
Parameters:
-----------
d -- flds data.
s -- key for the data.
'''
return np.array([d[s+"x"],d[s+"y"],d[s+"z"]]); |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def restrict(d,restrict):
'''
Restrict data by indices.
Parameters:
----------
d -- the flds/sclr data
restrict -- a tuple of [xmin,xmax,...] etx
'''
notqs = ['t','xs','ys','zs','fd','sd']
keys = [k for k in d if k not in notqs];
if len(restrict) == 2:
for k in keys:
d[k] = d[k][restrict[0]:restrict[1]]
elif len(restrict) == 4:
for k in keys:
d[k] = d[k][
restrict[0]:restrict[1],
restrict[2]:restrict[3]
];
elif len(restrict) == 6:
for k in keys:
d[k] = d[k][
restrict[0]:restrict[1],
restrict[2]:restrict[3],
restrict[4]:restrict[5]
];
else:
raise ValueError("restrict of length {} is not valid".format(
len(restrict))); |
<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_logger(name, level='INFO'):
""" Creates a new ready-to-use logger. :param name: new logger's name :type name: str :param level: default logging level. :type level: :class:`str` or :class:`int` :return: new logger. :rtype: :class:`logging.Logger` """ |
formatter = ColorFormatter(LOG_FORMAT, DATE_FORMAT)
if not isinstance(logging.getLevelName(level), int):
level = 'INFO'
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger = logging.getLogger(name)
logger.setLevel(level)
logger.addHandler(handler)
return logger |
<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_contributors(authors, contrib_type, competing_interests=None):
""" Given a list of authors from the parser, instantiate contributors objects and build them """ |
contributors = []
for author in authors:
contributor = None
author_contrib_type = contrib_type
surname = author.get("surname")
given_name = author.get("given-names")
collab = author.get("collab")
# Small hack for on-behalf-of type when building authors
# use on-behalf-of as the contrib_type
if author.get("type") and author.get("type") == "on-behalf-of":
collab = author.get("on-behalf-of")
author_contrib_type = "on-behalf-of"
if surname or collab:
contributor = ea.Contributor(author_contrib_type, surname, given_name, collab)
utils.set_attr_if_value(contributor, 'suffix', author.get('suffix'))
contributor.group_author_key = author.get("group-author-key")
contributor.orcid = author.get("orcid")
contributor.corresp = bool(author.get("corresp"))
if author.get("equal-contrib") == "yes":
contributor.equal_contrib = True
# Add contributor affiliations
for aff in author.get("affiliations", []):
affiliation = ea.Affiliation()
affiliation.text = utils.text_from_affiliation_elements(
aff.get("dept"),
aff.get("institution"),
aff.get("city"),
aff.get("country"))
# fall back if no other fields are set take the text content
if affiliation.text == '':
affiliation.text = aff.get("text")
contributor.set_affiliation(affiliation)
# competing interests / conflicts
if (competing_interests and author.get("references")
and "competing-interest" in author.get("references")):
for ref_id in author["references"]["competing-interest"]:
for competing_interest in competing_interests:
if competing_interest.get("text") and competing_interest.get("id") == ref_id:
clean_text = utils.remove_tag('p', competing_interest.get("text"))
contributor.set_conflict(clean_text)
# Finally add the contributor to the list
if contributor:
contributors.append(contributor)
return contributors |
<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_funding(award_groups):
""" Given a funding data, format it """ |
if not award_groups:
return []
funding_awards = []
for award_groups_item in award_groups:
for award_group_id, award_group in iteritems(award_groups_item):
award = ea.FundingAward()
award.award_group_id = award_group_id
if award_group.get('id-type') == "FundRef":
award.institution_id = award_group.get('id')
award.institution_name = award_group.get('institution')
# TODO !!! Check for multiple award_id, if exists
if award_group.get('award-id'):
award.add_award_id(award_group.get('award-id'))
funding_awards.append(award)
return funding_awards |
<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_datasets(datasets_json):
""" Given datasets in JSON format, build and return a list of dataset objects """ |
if not datasets_json:
return []
datasets = []
dataset_type_map = OrderedDict([
('generated', 'datasets'),
('used', 'prev_published_datasets')
])
dataset_type_map_found = []
# First look for the types of datasets present
for dataset_key, dataset_type in iteritems(dataset_type_map):
if datasets_json.get(dataset_key):
dataset_type_map_found.append(dataset_key)
# Continue with the found dataset types
for dataset_key in dataset_type_map_found:
dataset_type = dataset_type_map.get(dataset_key)
for dataset_values in datasets_json.get(dataset_key):
dataset = ea.Dataset()
utils.set_attr_if_value(dataset, 'dataset_type', dataset_type)
utils.set_attr_if_value(dataset, 'year', dataset_values.get('date'))
utils.set_attr_if_value(dataset, 'title', dataset_values.get('title'))
utils.set_attr_if_value(dataset, 'comment', dataset_values.get('details'))
utils.set_attr_if_value(dataset, 'doi', dataset_values.get('doi'))
utils.set_attr_if_value(dataset, 'uri', dataset_values.get('uri'))
utils.set_attr_if_value(dataset, 'accession_id', dataset_values.get('dataId'))
utils.set_attr_if_value(dataset, 'assigning_authority',
dataset_values.get('assigningAuthority'))
# authors
if dataset_values.get('authors'):
# parse JSON format authors into author objects
for author_json in dataset_values.get('authors'):
if utils.author_name_from_json(author_json):
dataset.add_author(utils.author_name_from_json(author_json))
# Try to populate the doi attribute if the uri is a doi
if not dataset.doi and dataset.uri:
if dataset.uri != eautils.doi_uri_to_doi(dataset.uri):
dataset.doi = eautils.doi_uri_to_doi(dataset.uri)
datasets.append(dataset)
return datasets |
<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_data_availability(datasets_json):
""" Given datasets in JSON format, get the data availability from it if present """ |
data_availability = None
if 'availability' in datasets_json and datasets_json.get('availability'):
# only expect one paragraph of text
data_availability = datasets_json.get('availability')[0].get('text')
return data_availability |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def component_title(component):
""" Label, title and caption Title is the label text plus the title text Title may contain italic tag, etc. """ |
title = u''
label_text = u''
title_text = u''
if component.get('label'):
label_text = component.get('label')
if component.get('title'):
title_text = component.get('title')
title = unicode_value(label_text)
if label_text != '' and title_text != '':
title += ' '
title += unicode_value(title_text)
if component.get('type') == 'abstract' and title == '':
title = 'Abstract'
return 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 build_components(components):
""" Given parsed components build a list of component objects """ |
component_list = []
for comp in components:
component = ea.Component()
# id
component.id = comp.get('id')
# type
component.type = comp.get('type')
# asset, if available
component.asset = comp.get('asset')
# DOI
component.doi = comp.get('doi')
if component_title(comp) != '':
component.title = component_title(comp)
# Subtitle
if comp.get('type') in ['supplementary-material', 'fig']:
if comp.get('full_caption'):
subtitle = comp.get('full_caption')
subtitle = clean_abstract(subtitle)
component.subtitle = subtitle
# Mime type
if comp.get('type') in ['abstract', 'table-wrap', 'sub-article',
'chem-struct-wrap', 'boxed-text']:
component.mime_type = 'text/plain'
if comp.get('type') in ['fig']:
component.mime_type = 'image/tiff'
elif comp.get('type') in ['media', 'supplementary-material']:
if comp.get('mimetype') and comp.get('mime-subtype'):
component.mime_type = (comp.get('mimetype') + '/'
+ comp.get('mime-subtype'))
# Permissions
component.permissions = comp.get('permissions')
# Append it to our list of components
component_list.append(component)
return component_list |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_related_articles(related_articles):
""" Given parsed data build a list of related article objects """ |
article_list = []
for related_article in related_articles:
article = ea.RelatedArticle()
if related_article.get('xlink_href'):
article.xlink_href = related_article.get('xlink_href')
if related_article.get('related_article_type'):
article.related_article_type = related_article.get('related_article_type')
if related_article.get('ext_link_type'):
article.ext_link_type = related_article.get('ext_link_type')
# Append it to our list
article_list.append(article)
return article_list |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def build_pub_dates(article, pub_dates):
"convert pub_dates into ArticleDate objects and add them to article"
for pub_date in pub_dates:
# always want a date type, take it from pub-type if must
if pub_date.get('date-type'):
date_instance = ea.ArticleDate(pub_date.get('date-type'),
pub_date.get('date'))
elif pub_date.get('pub-type'):
date_instance = ea.ArticleDate(pub_date.get('pub-type'),
pub_date.get('date'))
# Set more values
utils.set_attr_if_value(date_instance, 'pub_type', pub_date.get('pub-type'))
utils.set_attr_if_value(date_instance, 'publication_format',
pub_date.get('publication-format'))
utils.set_attr_if_value(date_instance, 'day', pub_date.get('day'))
utils.set_attr_if_value(date_instance, 'month', pub_date.get('month'))
utils.set_attr_if_value(date_instance, 'year', pub_date.get('year'))
article.add_date(date_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 build_self_uri_list(self_uri_list):
"parse the self-uri tags, build Uri objects"
uri_list = []
for self_uri in self_uri_list:
uri = ea.Uri()
utils.set_attr_if_value(uri, 'xlink_href', self_uri.get('xlink_href'))
utils.set_attr_if_value(uri, 'content_type', self_uri.get('content-type'))
uri_list.append(uri)
return uri_list |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clean_abstract(abstract, remove_tags=['xref', 'ext-link', 'inline-formula', 'mml:*']):
""" Remove unwanted tags from abstract string, parsing it as HTML, then only keep the body paragraph contents """ |
if remove_tags:
for tag_name in remove_tags:
abstract = utils.remove_tag(tag_name, abstract)
return abstract |
<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_articles_from_article_xmls(article_xmls, detail="full", build_parts=None, remove_tags=None):
""" Given a list of article XML filenames, convert to article objects """ |
poa_articles = []
for article_xml in article_xmls:
print("working on ", article_xml)
article, error_count = build_article_from_xml(article_xml, detail,
build_parts, remove_tags)
if error_count == 0:
poa_articles.append(article)
return poa_articles |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def accounts():
"""Load the accounts YAML file and return a dict """ |
import yaml
for path in account_files:
try:
c_dir = os.path.dirname(path)
if not os.path.exists(c_dir):
os.makedirs(c_dir)
with open(path, 'rb') as f:
return yaml.load(f)['accounts']
except (OSError, IOError) as e:
pass
return {} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_logger( name, file_name=None, stream=None, template=None, propagate=False):
"""Get a logger by name if file_name is specified, and the dirname() of the file_name exists, it will write to that file. If the dirname dies not exist, it will silently ignre it. """ |
logger = logging.getLogger(name)
if propagate is not None:
logger.propagate = propagate
for handler in logger.handlers:
logger.removeHandler(handler)
if not template:
template = "%(name)s %(process)s %(levelname)s %(message)s"
formatter = logging.Formatter(template)
if not file_name and not stream:
stream = sys.stdout
handlers = []
if stream is not None:
handlers.append(logging.StreamHandler(stream=stream))
if file_name is not None:
if os.path.isdir(os.path.dirname(file_name)):
handlers.append(logging.FileHandler(file_name))
else:
print("ERROR: Can't open log file {}".format(file_name))
for ch in handlers:
ch.setFormatter(formatter)
logger.addHandler(ch)
logger.setLevel(logging.INFO)
return logger |
<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_for_file(f, block_size=2 ** 20):
"""Generate an MD5 has for a possibly large file by breaking it into chunks""" |
import hashlib
md5 = hashlib.md5()
try:
# Guess that f is a FLO.
f.seek(0)
while True:
data = f.read(block_size)
if not data:
break
md5.update(data)
return md5.hexdigest()
except AttributeError as e:
# Nope, not a FLO. Maybe string?
file_name = f
with open(file_name, 'rb') as f:
return md5_for_file(f, block_size) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def subcache(self, path):
"""Clone this case, and extend the prefix""" |
cache = self.clone()
cache.prefix = os.path.join(cache.prefix if cache.prefix else '', path)
return cache |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def store_list(self, cb=None):
"""List the cache and store it as metadata. This allows for getting the list from HTTP caches and other types where it is not possible to traverse the tree""" |
from StringIO import StringIO
import json
d = {}
for k, v in self.list().items():
if 'caches' in v:
del v['caches']
d[k] = v
strio = StringIO(json.dumps(d))
sink = self.put_stream('meta/_list.json')
copy_file_or_flo(strio, sink, cb=cb)
sink.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def attach(self, upstream):
"""Attach an upstream to the last upstream. Can be removed with detach""" |
if upstream == self.last_upstream():
raise Exception("Can't attach a cache to itself")
self._prior_upstreams.append(self.last_upstream())
self.last_upstream().upstream = upstream |
<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_upstream(self, type_):
'''Return self, or an upstream, that has the given class type.
This is typically used to find upstream s that impoement the RemoteInterface
'''
if isinstance(self, type_):
return self
elif self.upstream and isinstance(self.upstream, type_):
return self.upstream
elif self.upstream:
return self.upstream.get_upstream(type_)
else:
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 decode(self, a_bytes, encoding):
"""A 'try as much as we can' strategy decoding method. 'try as much as we can' feature: Some time most of byte are encoded correctly. So chardet is able to detect the encoding. But, sometime some bytes in the middle are not encoded correctly. So it is still unable to apply bytes.decode("encoding-method") Example:: b"82347912350898143059043958290345" # 3059 is not right. # [-----Good----][-Bad][---Good---] What we do is to drop those bad encoded bytes, and try to recovery text as much as possible. So this method is to recursively call it self, and try to decode good bytes chunk, and finally concatenate them together. :param a_bytes: the bytes that encoding is unknown. :type a_bytes: bytes :param encoding: how you gonna decode a_bytes :type encoding: str """ |
try:
return (a_bytes.decode(encoding), encoding)
except Exception as e:
ind = self.catch_position_in_UnicodeDecodeError_message(str(e))
return (a_bytes[:ind].decode(encoding) + self.decode(a_bytes[(ind + 2):], encoding)[0],
encoding) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def autodecode(self, a_bytes):
"""Automatically detect encoding, and decode bytes. """ |
try: # 如果装了chardet
analysis = chardet.detect(a_bytes)
if analysis["confidence"] >= 0.75: # 如果可信
return (self.decode(a_bytes, analysis["encoding"])[0],
analysis["encoding"])
else: # 如果不可信, 打印异常
raise Exception("Failed to detect encoding. (%s, %s)" % (
analysis["confidence"],
analysis["encoding"]))
except NameError: # 如果没有装chardet
print(
"Warning! chardet not found. Use utf-8 as default encoding instead.")
return (a_bytes.decode("utf-8")[0],
"utf-8") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def login(self, url, payload):
"""Performe log in. url is the login page url, for example: https://login.secureserver.net/index.php? payload includes the account and password for example: ``{"loginlist": "YourAccount", "password": "YourPassword"}`` """ |
self.auth = requests.Session()
try:
self.auth.post(url, data=payload, timeout=self.default_timeout)
print("successfully logged in to %s" % url)
return True
except:
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_response(self, url, timeout=None):
"""Return http request response. """ |
if not timeout:
timeout = self.default_timeout
if self.default_sleeptime:
time.sleep(self.default_sleeptime)
try:
return self.auth.get(url, headers=self.default_header, timeout=self.default_timeout)
except:
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 html_with_encoding(self, url, timeout=None, encoding="utf-8"):
"""Manually get html with user encoding setting. """ |
response = self.get_response(url, timeout=timeout)
if response:
return self.decoder.decode(response.content, encoding)[0]
else:
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 html(self, url, timeout=None):
"""High level method to get http request response in text. smartly handle the encoding problem. """ |
response = self.get_response(url, timeout=timeout)
if response:
domain = self.get_domain(url)
if domain in self.domain_encoding_map: # domain have been visited
try: # apply extreme decoding
html = self.decoder.decode(response.content,
self.domain_encoding_map[domain])[0]
return html
except Exception as e:
print(e)
return None
else: # never visit this domain
try:
html, encoding = self.decoder.autodecode(response.content)
# save chardet analysis result
self.domain_encoding_map[domain] = encoding
return html
except Exception as e:
print(e)
return None
else:
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 binary(self, url, timeout=None):
"""High level method to get http request response in bytes. """ |
response = self.get_response(url, timeout=timeout)
if response:
return response.content
else:
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 download(self, url, dst, timeout=None):
"""Download the binary file at url to distination path. """ |
response = self.get_response(url, timeout=timeout)
if response:
with open(dst, "wb") as f:
for block in response.iter_content(1024):
if not block:
break
f.write(block) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def changed(self, src, path, dest):
"""Called whenever `path` is changed in the source folder `src`. `dest` is the output folder. The default implementation calls `build` after determining that the input file is newer than any of the outputs, or any of the outputs does not exist.""" |
try:
mtime = os.path.getmtime(os.path.join(src, path))
self._build(src, path, dest, mtime)
except EnvironmentError as e:
logging.error("{0} is inaccessible: {1}".format(
termcolor.colored(path, "yellow", attrs=["bold"]),
e.args[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 build(self, input_path, output_paths):
"""Should be extended by subclasses to actually do stuff. By default this will copy `input` over every file in the `outputs` list.""" |
for output in output_paths:
shutil.copy(input_path, output_paths) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rebuild_references(self, src, path, reject=None):
"""Updates `parents` and `children` to be in sync with the changes to `src` if any.""" |
if reject is None:
reject = set()
reject.add(path)
try:
filename = os.path.join(src, path)
mtime = os.path.getmtime(filename)
contents = open(filename)
except EnvironmentError:
raise ValueError("Unable to open '{0}'".format(path))
if \
path in self.parents and \
self.parents[path].updated == mtime:
# cache hit; no need to update
return
# drop existing references
if path in self.parents:
self.deleted(src, path)
# build a list of parents
parents = TimedSet(mtime)
current = os.path.dirname(path)
for line in contents:
match = self.line_regex.search(line)
if match:
parent = match.group(1)
relative = os.path.normpath(os.path.join(current, parent))
if relative.startswith(".."):
raise ValueError("Parent reference '{0}' outside of "
"watched folder in '{1}'".format(parent,
path))
parent = os.path.normcase(relative)
if parent in reject:
raise ValueError("Circular reference to '{0}' "
"detected in '{1}'".format(parent,
path))
parents.add(parent)
for parent in parents:
# recursively build references for all parents; this will
# usually be a cache hit and no-op
self.rebuild_references(src, parent, reject)
self.parents[path] = parents
for parent in parents:
# add this node to each of its parents' children
if parent not in self.children:
self.children[parent] = set()
self.children[parent].add(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 deleted(self, src, path):
"""Update the reference tree when a handled file is deleted.""" |
if self.parents[path] is not None:
for parent in self.parents[path]:
self.children[parent].remove(path)
if not self.children[parent]:
del self.children[parent]
del self.parents[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 clearScreen(cls):
"""Clear the screen""" |
if "win32" in sys.platform:
os.system('cls')
elif "linux" in sys.platform:
os.system('clear')
elif 'darwin' in sys.platform:
os.system('clear')
else:
cit.err("No clearScreen for " + sys.platform) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getPyCmd(cls):
"""get OS's python command""" |
if "win32" in sys.platform:
return 'py'
elif "linux" in sys.platform:
return 'python3'
elif 'darwin' in sys.platform:
return 'python3'
else:
cit.err("No python3 command for " + sys.platform) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def runCmd(cls, cmd):
"""run command and show if success or failed Args: cmd: string Returns: bool: if this command run successfully """ |
cit.echo(cmd, "command")
result = os.system(cmd)
cls.checkResult(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 readCmd(cls, cmd):
"""run command and return the str format stdout Args: cmd: string Returns: str: what the command's echo """ |
args = shlex.split(cmd)
proc = subprocess.Popen(args, stdout=subprocess.PIPE)
(proc_stdout, proc_stderr) = proc.communicate(input=None) # proc_stdin
return proc_stdout.decode() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.