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 average_cq(seq, efficiency=1.0):
"""Given a set of Cq values, return the Cq value that represents the average expression level of the input. The intent is to... |
denominator = sum( [pow(2.0*efficiency, -Ci) for Ci in seq] )
return log(len(seq)/denominator)/log(2.0*efficiency) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_sample_frame(sample_frame):
"""Makes sure that `sample_frame` has the columns we expect. :param DataFrame sample_frame: A sample data frame. :return... |
if not isinstance(sample_frame, pd.core.frame.DataFrame):
raise TypeError("Expected a pandas DataFrame, received {}".format(type(sample_frame)))
for col in ['Sample', 'Target', 'Cq']:
if col not in sample_frame:
raise ValueError("Missing column {} in sample frame".format(col))
i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def censor_background(sample_frame, ntc_samples=['NTC'], margin=log2(10)):
"""Selects rows from the sample data frame that fall `margin` or greater cycles earlie... |
ntcs = sample_frame.loc[ sample_frame['Sample'].apply(lambda x: x in ntc_samples), ]
if ntcs.empty:
return sample_frame
g = ntcs.groupby('Target')
min_ntcs = g['Cq'].min()
# if a target has no NTC, min_ntcs.loc[sample] is NaN
# we should retain all values from targets with no NTC
# ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expression_nf(sample_frame, nf_n, ref_sample):
"""Calculates expression of samples in a sample data frame relative to pre-computed normalization factors. ref... |
ref_sample_df = sample_frame.ix[sample_frame['Sample'] == ref_sample, ['Target', 'Cq']]
ref_sample_cq = ref_sample_df.groupby('Target')['Cq'].aggregate(average_cq)
delta = -sample_frame['Cq'] + asarray(ref_sample_cq.ix[sample_frame['Target']])
rel = power(2, delta) / asarray(nf_n.ix[sample_frame['Samp... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def collect_expression(sample_frame, ref_targets, ref_sample):
"""Calculates the expression of all rows in the sample_frame relative to each of the ref_targets. ... |
by_gene = {'Sample': sample_frame['Sample'], 'Target': sample_frame['Target']}
for target in ref_targets:
by_gene[target] = expression_ddcq(sample_frame, target, ref_sample)
return pd.DataFrame(by_gene) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rank_targets(sample_frame, ref_targets, ref_sample):
"""Uses the geNorm algorithm to determine the most stably expressed genes from amongst ref_targets in yo... |
table = collect_expression(sample_frame, ref_targets, ref_sample)
all_samples = sample_frame['Sample'].unique()
t = table.groupby(['Sample', 'Target']).mean()
logt = log2(t)
ref_targets = set(ref_targets)
worst = []
worst_m = []
while len(ref_targets) - len(worst) > 1:
M = []
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calculate_nf(sample_frame, ref_targets, ref_sample):
"""Calculates a normalization factor from the geometric mean of the expression of all ref_targets, norma... |
grouped = sample_frame.groupby(['Target', 'Sample'])['Cq'].aggregate(average_cq)
samples = sample_frame['Sample'].unique()
nfs = gmean([pow(2, -grouped.ix[zip(repeat(ref_gene), samples)] + grouped.ix[ref_gene, ref_sample]) for ref_gene in ref_targets])
return pd.Series(nfs, index=samples) |
<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_ec2_meta_data():
""" Get meta data about ourselves, if we are on an EC2 instance. In particular, this returns the VPC ID and region of this instance. If ... |
# The timeout is just for the connection attempt, but between retries there
# is an exponential back off in seconds. So, too many retries and it can
# possibly block for a very long time here. Main contributor to waiting
# time here is the number of retries, rather than the timeout time.
try:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect_to_region(region_name):
""" Establish connection to AWS API. """ |
logging.debug("Connecting to AWS region '%s'" % region_name)
con = boto.vpc.connect_to_region(region_name)
if not con:
raise VpcRouteSetError("Could not establish connection to "
"region '%s'." % region_name)
return con |
<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_ip_subnet_lookup(vpc_info):
""" Updates the vpc-info object with a lookup for IP -> subnet. """ |
# We create a reverse lookup from the instances private IP addresses to the
# subnets they are associated with. This is used later on in order to
# determine whether routes should be set in an RT: Is the RT's subnet
# associated with ANY of the IP addresses in the route spec? To make this
# easy, w... |
<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_vpc_overview(con, vpc_id, region_name):
""" Retrieve information for the specified VPC. If no VPC ID was specified then just pick the first VPC we find. ... |
logging.debug("Retrieving information for VPC '%s'" % vpc_id)
d = {}
d['zones'] = con.get_all_zones()
# Find the specified VPC, or just use the first one
all_vpcs = con.get_all_vpcs()
if not all_vpcs:
raise VpcRouteSetError("Cannot find any VPCs.")
if not vpc_id:
# Just... |
<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_instance_and_eni_by_ip(vpc_info, ip):
""" Given a specific IP address, find the EC2 instance and ENI. We need this information for setting the route. Re... |
for instance in vpc_info['instances']:
for eni in instance.interfaces:
for pa in eni.private_ip_addresses:
if pa.private_ip_address == ip:
return instance, eni
raise VpcRouteSetError("Could not find instance/eni for '%s' "
"in V... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_instance_private_ip_from_route(instance, route):
""" Find the private IP and ENI of an instance that's pointed to in a route. Returns (ipaddr, eni) tuple... |
ipaddr = None
for eni in instance.interfaces:
if eni.id == route.interface_id:
ipaddr = eni.private_ip_address
break
return ipaddr, eni if ipaddr else 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 _choose_different_host(old_ip, ip_list, failed_ips, questionable_ips):
""" Randomly choose a different host from a list of hosts. Pick from fully healthy IPs... |
if not ip_list:
# We don't have any hosts to choose from.
return None
ip_set = set(ip_list)
failed_set = set(failed_ips)
# Consider only those questionable IPs that aren't also failed and make
# sure all of the ones in the questionable list are at least also present... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _rt_state_update(route_table_id, dcidr, router_ip="(none)", instance_id="(none)", eni_id="(none)", old_router_ip="(none)", msg="(none)"):
""" Store a message... |
buf = "inst: %s, eni: %s, r_ip: %-15s, o_r_ip: %-15s, msg: %s" % \
(instance_id, eni_id, router_ip, old_router_ip, msg)
CURRENT_STATE.vpc_state.setdefault('route_tables', {}). \
setdefault(route_table_id, {})[dcidr] = buf |
<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_route(dcidr, router_ip, old_router_ip, vpc_info, con, route_table_id, update_reason):
""" Update an existing route entry in the route table. """ |
instance = eni = None
try:
instance, eni = find_instance_and_eni_by_ip(vpc_info, router_ip)
logging.info("--- updating existing route in RT '%s' "
"%s -> %s (%s, %s) (old IP: %s, reason: %s)" %
(route_table_id, dcidr, router_ip,
i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _add_new_route(dcidr, router_ip, vpc_info, con, route_table_id):
""" Add a new route to the route table. """ |
try:
instance, eni = find_instance_and_eni_by_ip(vpc_info, router_ip)
# Only set the route if the RT is associated with any of the subnets
# used for the cluster.
rt_subnets = \
set(vpc_info['rt_subnet_lookup'].get(route_table_id, []))
cluster_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 _get_real_instance_if_mismatch(vpc_info, ipaddr, instance, eni):
""" Return the real instance for the given IP address, if that instance is different than th... |
# Careful! A route may be a black-hole route, which still has instance and
# ENI information for an instance that doesn't exist anymore. If a host was
# terminated and a new host got the same IP then this route won't be
# updated and will keep pointing to a non-existing node. So we find the
# insta... |
<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_host_for_route(vpc_info, route, route_table, dcidr):
""" Given a specific route, return information about the instance to which it points. Returns 3-tup... |
class _CouldNotIdentifyHost(Exception):
# If we can't find both the instance as well as an eni for the route,
# we will raise this exception. In that case, we'll return None/unknown
# values, which indicate to the calling code that a new instance should
# be found.
pass
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _is_cidr_in_ignore_routes(cidr):
""" Checks the CIDR to see if it falls into any CIDRs specified via the ignore_routes parameter. This is used mostly to prot... |
for ignore_cidr in CURRENT_STATE.ignore_routes:
if is_cidr_in_cidr(cidr, ignore_cidr):
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _add_missing_routes(route_spec, failed_ips, questionable_ips, chosen_routers, vpc_info, con, routes_in_rts):
""" Iterate over route spec and add all the rout... |
for dcidr, hosts in route_spec.items():
new_router_ip = chosen_routers.get(dcidr)
# Look at the routes we have seen in each of the route tables.
for rt_id, dcidr_list in routes_in_rts.items():
if dcidr not in dcidr_list:
if not new_router_ip:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_route_spec_config(con, vpc_info, route_spec, failed_ips, questionable_ips):
""" Look through the route spec and update routes accordingly. Idea: Make... |
if CURRENT_STATE._stop_all:
logging.debug("Routespec processing. Stop requested, abort operation")
return
if failed_ips:
logging.debug("Route spec processing. Failed IPs: %s" %
",".join(failed_ips))
else:
logging.debug("Route spec processing. No 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 handle_spec(region_name, vpc_id, route_spec, failed_ips, questionable_ips):
""" Connect to region and update routes according to route spec. """ |
if CURRENT_STATE._stop_all:
logging.debug("handle_spec: Stop requested, abort operation")
return
if not route_spec:
logging.debug("handle_spec: No route spec provided")
return
logging.debug("Handle route spec")
try:
con = connect_to_region(region_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 signature(self, block_size=None):
"Calculates signature for local file."
kwargs = {}
if block_size:
kwargs['block_size'] = block_size
return librsync.signature(open(self.path, 'rb'), **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 patch(self, delta):
"Applies remote delta to local file."
# Create a temp file in which to store our synced copy. We will handle
# deleting it manually, since we may move it instead.
with (tempfile.NamedTemporaryFile(prefix='.sync',
suffix=os.path.basename(self.path),
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def signature(self, block_size=None):
"Requests a signature for remote file via API."
kwargs = {}
if block_size:
kwargs['block_size'] = block_size
return self.api.get('path/sync/signature', self.path, **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 delta(self, signature):
"Generates delta for remote file via API using local file's signature."
return self.api.post('path/sync/delta', self.path, signature=signature) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def patch(self, delta):
"Applies delta for local file to remote file via API."
return self.api.post('path/sync/patch', self.path, delta=delta) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upload(self, local, remote):
""" Performs synchronization from a local file to a remote file. The local path is the source and remote path is the destination... |
self.sync(LocalFile(local), RemoteFile(remote, self.api)) |
<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, local, remote):
""" Performs synchronization from a remote file to a local file. The remote path is the source and the local path is the desti... |
self.sync(RemoteFile(remote, self.api), LocalFile(local)) |
<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_python(self, value):
""" Validates that the input can be converted to a date. Returns a Python datetime.date object. """ |
if value in validators.EMPTY_VALUES:
return None
if isinstance(value, datetime.datetime):
return value.date()
if isinstance(value, datetime.date):
return value
if isinstance(value, list):
# Input comes from a 2 SplitDateWidgets, for exampl... |
<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_python(self, value):
""" Validates that the input can be converted to a datetime. Returns a Python datetime.datetime object. """ |
if value in validators.EMPTY_VALUES:
return None
if isinstance(value, datetime.datetime):
return value
if isinstance(value, datetime.date):
return datetime.datetime(value.year, value.month, value.day)
if isinstance(value, list):
# Input 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 to_python(self, value):
""" Validates that the input can be converted to a time. Returns a Python datetime.time object. """ |
if value in validators.EMPTY_VALUES:
return None
if isinstance(value, datetime.datetime):
return value.time()
if isinstance(value, datetime.time):
return value
if isinstance(value, list):
# Input comes from a 2 SplitTimeWidgets, for exampl... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def docs_client(self):
""" A DocsClient singleton, used to look up spreadsheets by name. """ |
if not hasattr(self, '_docs_client'):
client = DocsClient()
client.ClientLogin(self.google_user, self.google_password,
SOURCE_NAME)
self._docs_client = client
return self._docs_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 sheets_service(self):
""" A SpreadsheetsService singleton, used to perform operations on the actual spreadsheet. """ |
if not hasattr(self, '_sheets_service'):
service = SpreadsheetsService()
service.email = self.google_user
service.password = self.google_password
service.source = SOURCE_NAME
service.ProgrammaticLogin()
self._sheets_service = service
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def recid_fetcher(record_uuid, data):
"""Fetch a record's identifiers. :param record_uuid: The record UUID. :param data: The record metadata. :returns: A :data:`... |
pid_field = current_app.config['PIDSTORE_RECID_FIELD']
return FetchedPID(
provider=RecordIdProvider,
pid_type=RecordIdProvider.pid_type,
pid_value=str(data[pid_field]),
) |
<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_column(self, label, field):
""" Add a new column to the table. It will have the header text ``label``, but for data inserts and queries, the ``field`` n... |
# Don't call this directly.
assert self.headers is not None
cols = 0
if len(self._headers) > 0:
cols = max([int(c.cell.col) for c in self._headers])
new_col = cols + 1
if int(self._ws.col_count.text) < new_col:
self._ws.col_count.text = str(new_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 headers(self):
""" Return the name of all headers currently defined for the table. """ |
if self._headers is None:
query = CellQuery()
query.max_row = '1'
feed = self._service.GetCellsFeed(self._ss.id, self.id,
query=query)
self._headers = feed.entry
return [normalize_header(h.cell.text) for h in ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def insert(self, row):
""" Insert a new row. The row will be added to the end of the spreadsheet. Before inserting, the field names in the given row will be norm... |
data = self._convert_value(row)
self._service.InsertRow(data, self._ss.id, self.id) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove(self, _query=None, **kwargs):
""" Remove all rows matching the current query. If no query is given, this will truncate the entire table. """ |
for entry in self._find_entries(_query=_query, **kwargs):
self._service.DeleteRow(entry) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def normalize_header(name, existing=[]):
""" Try to emulate the way in which Google does normalization on the column names to transform them into headers. """ |
name = re.sub('\W+', '', name, flags=re.UNICODE).lower()
# TODO handle multiple columns with the same name.
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 getAllElementsOfHirarchy(self):
""" returns ALL elements of the complete hirarchy as a flat list """ |
allElements=[]
for element in self.getAllElements():
allElements.append(element)
if isinstance(element, BaseElement):
allElements.extend(element.getAllElementsOfHirarchy())
return allElements |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getElementByID(self, id):
""" returns an element with the specific id and the position of that element within the svg elements array """ |
pos=0
for element in self._subElements:
if element.get_id()==id:
return (element,pos)
pos+=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 getElementsByType(self, type):
""" retrieves all Elements that are of type type @type type: class @param type: type of the element """ |
foundElements=[]
for element in self.getAllElementsOfHirarchy():
if isinstance(element, type):
foundElements.append(element)
return foundElements |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getXML(self):
""" Return a XML representation of the current element. This function can be used for debugging purposes. It is also used by getXML in SVG @ret... |
xml='<'+self._elementName+' '
for key,value in list(self._attributes.items()):
if value != None:
xml+=key+'="'+self.quote_attrib(str(value))+'" '
if len(self._subElements)==0: #self._textContent==None and
xml+=' />\n'
else:
xml+=' >\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 quote_attrib(self, inStr):
""" Transforms characters between xml notation and python notation. """ |
s1 = (isinstance(inStr, str) and inStr or
'%s' % inStr)
s1 = s1.replace('&', '&')
s1 = s1.replace('<', '<')
s1 = s1.replace('>', '>')
if '"' in s1:
# if "'" in s1:
s1 = '%s' % s1.replace('"', """)
# 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 process_status(ctx, param, value):
"""Return status value.""" |
from .models import PIDStatus
# Allow empty status
if value is None:
return None
if not hasattr(PIDStatus, value):
raise click.BadParameter('Status needs to be one of {0}.'.format(
', '.join([s.name for s in PIDStatus])
))
return getattr(PIDStatus, value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(pid_type, pid_value, status, object_type, object_uuid):
"""Create new persistent identifier.""" |
from .models import PersistentIdentifier
if bool(object_type) ^ bool(object_uuid):
raise click.BadParameter('Speficy both or any of --type and --uuid.')
new_pid = PersistentIdentifier.create(
pid_type,
pid_value,
status=status,
object_type=object_type,
obje... |
<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(pid_type, pid_value, status, object_type, object_uuid, overwrite):
"""Assign persistent identifier.""" |
from .models import PersistentIdentifier
obj = PersistentIdentifier.get(pid_type, pid_value)
if status is not None:
obj.status = status
obj.assign(object_type, object_uuid, overwrite=overwrite)
db.session.commit()
click.echo(obj.status) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unassign(pid_type, pid_value):
"""Unassign persistent identifier.""" |
from .models import PersistentIdentifier
obj = PersistentIdentifier.get(pid_type, pid_value)
obj.unassign()
db.session.commit()
click.echo(obj.status) |
<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_object(pid_type, pid_value):
"""Get an object behind persistent identifier.""" |
from .models import PersistentIdentifier
obj = PersistentIdentifier.get(pid_type, pid_value)
if obj.has_object():
click.echo('{0.object_type} {0.object_uuid} {0.status}'.format(obj)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def Deserializer(stream_or_string, **options):
""" Deserialize a stream or string of CSV data. """ |
def process_item(item):
m = _LIST_RE.match(item)
if m:
contents = m.group(1)
if not contents:
item = []
else:
item = process_m2m(contents)
else:
if item == 'TRUE':
item = True
elif it... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def object_formatter(v, c, m, p):
"""Format object view link.""" |
endpoint = current_app.config['PIDSTORE_OBJECT_ENDPOINTS'].get(
m.object_type)
if endpoint and m.object_uuid:
return Markup('<a href="{0}">{1}</a>'.format(
url_for(endpoint, id=m.object_uuid),
_('View')))
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 decode(self, tx):
""" Decodes the given transaction. Args: tx: hex of transaction Returns: decoded transaction .. note:: Only supported for blockr.io at the ... |
if not isinstance(self._service, BitcoinBlockrService):
raise NotImplementedError('Currently only supported for "blockr.io"')
return self._service.decode(tx) |
<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, url, doc):
"""Register a DOI via the DataCite API. :param url: Specify the URL for the API. :param doc: Set metadata for DOI. :returns: `True`... |
try:
self.pid.register()
# Set metadata for DOI
self.api.metadata_post(doc)
# Mint DOI
self.api.doi_post(self.pid.pid_value, url)
except (DataCiteError, HttpError):
logger.exception("Failed to register in DataCite",
... |
<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, url, doc):
"""Update metadata associated with a DOI. This can be called before/after a DOI is registered. :param doc: Set metadata for DOI. :ret... |
if self.pid.is_deleted():
logger.info("Reactivate in DataCite",
extra=dict(pid=self.pid))
try:
# Set metadata
self.api.metadata_post(doc)
self.api.doi_post(self.pid.pid_value, url)
except (DataCiteError, HttpError):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self):
"""Delete a registered DOI. If the PID is new then it's deleted only locally. Otherwise, also it's deleted also remotely. :returns: `True` if i... |
try:
if self.pid.is_new():
self.pid.delete()
else:
self.pid.delete()
self.api.metadata_delete(self.pid.pid_value)
except (DataCiteError, HttpError):
logger.exception("Failed to delete in DataCite",
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sync_status(self):
"""Synchronize DOI status DataCite MDS. :returns: `True` if is sync successfully. """ |
status = None
try:
try:
self.api.doi_get(self.pid.pid_value)
status = PIDStatus.REGISTERED
except DataCiteGoneError:
status = PIDStatus.DELETED
except DataCiteNoContentError:
status = PIDStatus.REGISTER... |
<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(cls, pid_type=None, pid_value=None, object_type=None, object_uuid=None, status=None, **kwargs):
"""Create a new instance for the given type and pid. :... |
assert pid_value
assert pid_type or cls.pid_type
pid = PersistentIdentifier.create(
pid_type or cls.pid_type,
pid_value,
pid_provider=cls.pid_provider,
object_type=object_type,
object_uuid=object_uuid,
status=status or cls... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(cls, pid_value, pid_type=None, **kwargs):
"""Get a persistent identifier for this provider. :param pid_type: Persistent identifier type. (Default: config... |
return cls(
PersistentIdentifier.get(pid_type or cls.pid_type, pid_value,
pid_provider=cls.pid_provider),
**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 init_app(self, app, config_group="flask_keystone"):
""" Iniitialize the Flask_Keystone module in an application factory. :param app: `flask.Flask` applicatio... |
cfg.CONF.register_opts(RAX_OPTS, group=config_group)
self.logger = logging.getLogger(__name__)
try:
logging.register_options(cfg.CONF)
except cfg.ArgsAlreadyParsedError: # pragma: no cover
pass
logging.setup(cfg.CONF, "flask_keystone")
self.con... |
<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_roles(self):
""" Generate a dictionary for configured roles from oslo_config. Due to limitations in ini format, it's necessary to specify roles in a f... |
roles = {}
for keystone_role, flask_role in self.config.roles.items():
roles.setdefault(flask_role, set()).add(keystone_role)
return roles |
<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_before_request(self):
""" Generate the before_request function to be added to the app. Currently this function is static, however it is very likely we ... |
def before_request():
"""
Process invalid identity statuses and attach user to request.
:raises: :exception:`exceptions.FlaskKeystoneUnauthorized`
This function guarantees that a bad token will return a 401
when :mod:`keystonemiddleware` is configur... |
<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_user_model(self):
""" Dynamically generate a User class for use with FlaskKeystone. :returns: a generated User class, inherited from :class:`flask_keys... |
class User(UserBase):
"""
A User as defined by the response from Keystone.
Note: This class is dynamically generated by :class:`FlaskKeystone`
from the :class:`flask_keystone.UserBase` class.
:param request: The incoming `flask.Request` object, afte... |
<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_required(self, f):
""" Require a user to be validated by Identity to access an endpoint. :raises: FlaskKeystoneUnauthorized This method will gate a par... |
@wraps(f)
def wrapped_f(*args, **kwargs):
if current_user.anonymous:
msg = ("Rejected User '%s access to '%s' as user"
" could not be authenticated.")
self.logger.warn(msg % (
current_user.user_id,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pid_exists(value, pidtype=None):
"""Check if a persistent identifier exists. :param value: The PID value. :param pidtype: The pid value (Default: None). :ret... |
try:
PersistentIdentifier.get(pidtype, value)
return True
except PIDDoesNotExistError:
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 register_minter(self, name, minter):
"""Register a minter. :param name: Minter name. :param minter: The new minter. """ |
assert name not in self.minters
self.minters[name] = minter |
<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_fetcher(self, name, fetcher):
"""Register a fetcher. :param name: Fetcher name. :param fetcher: The new fetcher. """ |
assert name not in self.fetchers
self.fetchers[name] = fetcher |
<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_minters_entry_point_group(self, entry_point_group):
"""Load minters from an entry point group. :param entry_point_group: The entrypoint group. """ |
for ep in pkg_resources.iter_entry_points(group=entry_point_group):
self.register_minter(ep.name, ep.load()) |
<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_fetchers_entry_point_group(self, entry_point_group):
"""Load fetchers from an entry point group. :param entry_point_group: The entrypoint group. """ |
for ep in pkg_resources.iter_entry_points(group=entry_point_group):
self.register_fetcher(ep.name, ep.load()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_address(self, address, account="*", rescan=False):
""" param address = address to import param label= account name to use """ |
response = self.make_request("importaddress", [address, account, rescan])
error = response.get('error')
if error is not None:
raise Exception(error)
return response |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getBottomRight(self):
""" Retrieves a tuple with the x,y coordinates of the lower right point of the rect. Requires the coordinates, width, height to be numb... |
return (float(self.get_x()) + float(self.get_width()), float(self.get_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 getTopLeft(self):
""" Retrieves a tuple with the x,y coordinates of the upper left point of the rect. Requires the coordinates, width, height to be numbers "... |
return (float(self.get_x()), float(self.get_y())+ float(self.get_height())) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getTopRight(self):
""" Retrieves a tuple with the x,y coordinates of the upper right point of the rect. Requires the coordinates, width, height to be numbers... |
return (float(self.get_x()) + float(self.get_width()), float(self.get_y()) + float(self.get_height())) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def moveToPoint(self, xxx_todo_changeme):
""" Moves the rect to the point x,y """ |
(x,y) = xxx_todo_changeme
self.set_x(float(self.get_x()) + float(x))
self.set_y(float(self.get_y()) + float(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 getBottomLeft(self):
""" Retrieves a tuple with the x,y coordinates of the lower left point of the circle. Requires the radius and the coordinates to be numb... |
return (float(self.get_cx()) - float(self.get_r()), float(self.get_cy()) - float(self.get_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 getBottomRight(self):
""" Retrieves a tuple with the x,y coordinates of the lower right point of the circle. Requires the radius and the coordinates to be nu... |
return (float(self.get_cx()) + float(self.get_r()), float(self.get_cy()) - float(self.get_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 getTopLeft(self):
""" Retrieves a tuple with the x,y coordinates of the upper left point of the circle. Requires the radius and the coordinates to be numbers... |
return (float(self.get_cx()) - float(self.get_r()), float(self.get_cy()) + float(self.get_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 getTopRight(self):
""" Retrieves a tuple with the x,y coordinates of the upper right point of the circle. Requires the radius and the coordinates to be numbe... |
return (float(self.get_cx()) + float(self.get_r()), float(self.get_cy()) + float(self.get_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 moveToPoint(self, xxx_todo_changeme1):
""" Moves the circle to the point x,y """ |
(x,y) = xxx_todo_changeme1
self.set_cx(float(self.get_cx()) + float(x))
self.set_cy(float(self.get_cy()) + float(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 getBottomLeft(self):
""" Retrieves a tuple with the x,y coordinates of the lower left point of the ellipse. Requires the radius and the coordinates to be num... |
return (float(self.get_cx()) - float(self.get_rx()), float(self.get_cy()) - float(self.get_ry())) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getBottomRight(self):
""" Retrieves a tuple with the x,y coordinates of the lower right point of the ellipse. Requires the radius and the coordinates to be n... |
return (float(self.get_cx()) + float(self.get_rx()), float(self.get_cy()) - float(self.get_ry())) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getTopLeft(self):
""" Retrieves a tuple with the x,y coordinates of the upper left point of the ellipse. Requires the radius and the coordinates to be number... |
return (float(self.get_cx()) - float(self.get_rx()), float(self.get_cy()) + float(self.get_ry())) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getTopRight(self):
""" Retrieves a tuple with the x,y coordinates of the upper right point of the ellipse. Requires the radius and the coordinates to be numb... |
return (float(self.get_cx()) + float(self.get_rx()), float(self.get_cy()) + float(self.get_ry())) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getBottomLeft(self):
""" Retrieves the the bottom left coordinate of the line as tuple. Coordinates must be numbers. """ |
x1 = float(self.get_x1())
x2 = float(self.get_x2())
y1 = float(self.get_y1())
y2 = float(self.get_y2())
if x1 < x2:
if y1 < y2:
return (x1, y1)
else:
return (x1, y2)
else:
if y1 < y2:
ret... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def moveToPoint(self, xxx_todo_changeme2):
""" Moves the line to the point x,y """ |
(x,y) = xxx_todo_changeme2
self.set_x1(float(self.get_x1()) + float(x))
self.set_x2(float(self.get_x2()) + float(x))
self.set_y1(float(self.get_y1()) + float(y))
self.set_y2(float(self.get_y2()) + float(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 createCircle(self, cx, cy, r, strokewidth=1, stroke='black', fill='none'):
""" Creates a circle @type cx: string or int @param cx: starting x-coordinate @typ... |
style_dict = {'fill':fill, 'stroke-width':strokewidth, 'stroke':stroke}
myStyle = StyleBuilder(style_dict)
c = Circle(cx, cy, r)
c.set_style(myStyle.getStyle())
return 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 createEllipse(self, cx, cy, rx, ry, strokewidth=1, stroke='black', fill='none'):
""" Creates an ellipse @type cx: string or int @param cx: starting x-coordin... |
style_dict = {'fill':fill, 'stroke-width':strokewidth, 'stroke':stroke}
myStyle = StyleBuilder(style_dict)
e = Ellipse(cx, cy, rx, ry)
e.set_style(myStyle.getStyle())
return 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 createRect(self, x, y, width, height, rx=None, ry=None, strokewidth=1, stroke='black', fill='none'):
""" Creates a Rectangle @type x: string or int @param x:... |
style_dict = {'fill':fill, 'stroke-width':strokewidth, 'stroke':stroke}
myStyle = StyleBuilder(style_dict)
r = Rect(x, y, width, height, rx, ry)
r.set_style(myStyle.getStyle())
return r |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def createPolygon(self, points, strokewidth=1, stroke='black', fill='none'):
""" Creates a Polygon @type points: string in the form "x1,y1 x2,y2 x3,y3" @param po... |
style_dict = {'fill':fill, 'stroke-width':strokewidth, 'stroke':stroke}
myStyle = StyleBuilder(style_dict)
p = Polygon(points=points)
p.set_style(myStyle.getStyle())
return p |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def createPolyline(self, points, strokewidth=1, stroke='black'):
""" Creates a Polyline @type points: string in the form "x1,y1 x2,y2 x3,y3" @param points: all p... |
style_dict = {'fill':'none', 'stroke-width':strokewidth, 'stroke':stroke}
myStyle = StyleBuilder(style_dict)
p = Polyline(points=points)
p.set_style(myStyle.getStyle())
return p |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def createLine(self, x1, y1, x2, y2, strokewidth=1, stroke="black"):
""" Creates a line @type x1: string or int @param x1: starting x-coordinate @type y1: string... |
style_dict = {'stroke-width':strokewidth, 'stroke':stroke}
myStyle = StyleBuilder(style_dict)
l = Line(x1, y1, x2, y2)
l.set_style(myStyle.getStyle())
return l |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encode_scaled(data, size, version=0, level=QR_ECLEVEL_L, hint=QR_MODE_8, case_sensitive=True):
"""Creates a QR-code from string data, resized to the specifie... |
version, src_size, im = encode(data, version, level, hint, case_sensitive)
if size < src_size:
size = src_size
qr_size = (size / src_size) * src_size
im = im.resize((qr_size, qr_size), Image.NEAREST)
pad = (size - qr_size) / 2
ret = Image.new("L", (size, size), 255)
ret.paste(im, (pad... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def moveTo(self, vector):
""" Moves the turtle to the new position. Orientation is kept as it is. If the pen is lowered it will also add to the currently drawn p... |
self._position = vector
if self.isPenDown():
self._pointsOfPolyline.append(self._position) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def penUp(self):
""" Raises the pen. Any movement will not draw lines till pen is lowered again. """ |
if self._penDown==True:
self._penDown = False
self._addPolylineToElements() |
<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, distance):
""" Moves the turtle by distance in the direction it is facing. If the pen is lowered it will also add to the currently drawn polyline... |
self._position = self._position + self._orient * distance
if self.isPenDown():
x = round(self._position.x, 2)
y = round(self._position.y, 2)
self._pointsOfPolyline.append(Vector(x, 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 getXML(self):
"""Retrieves the pysvg elements that make up the turtles path and returns them as String in an xml representation. """ |
s = ''
for element in self._svgElements:
s += element.getXML()
return s |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def addTurtlePathToSVG(self, svgContainer):
"""Adds the paths of the turtle to an existing svg container. """ |
for element in self.getSVGElements():
svgContainer.addElement(element)
return svgContainer |
<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_content(self, context):
""" Add the csrf_token_value because the mixin use render_to_string and not render. """ |
self._valid_template()
context.update({
"csrf_token_value": get_token(self.request)
})
return render_to_string(self.get_template_names(), context) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def normpath(path, keep_trailing=False):
"""Really normalize the path by adding a missing leading slash.""" |
new_path = k_paths.normpath(path)
if keep_trailing and path.endswith("/") and not new_path.endswith("/"):
new_path = new_path + "/"
if not new_path.startswith('/'):
return '/' + new_path
return new_path |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.