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 get_active_threads_involving_all_participants(self, *participant_ids):
""" Gets the threads where the specified participants are active and no one has left. """ |
query = Thread.objects.\
exclude(participation__date_left__lte=now()).\
annotate(count_participants=Count('participants')).\
filter(count_participants=len(participant_ids))
for participant_id in participant_ids:
query = query.filter(participants__id=participant_id)
return query.distinct() |
<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_or_create_thread(self, request, name=None, *participant_ids):
""" When a Participant posts a message to other participants without specifying an existing Thread, we must 1. Create a new Thread if they have not yet opened the discussion. 2. If they have already opened the discussion and multiple Threads are not allowed for the same users, we must re-attach this message to the existing thread. 3. If they have already opened the discussion and multiple Threads are allowed, we simply create a new one. """ |
# we get the current participant
# or create him if he does not exit
participant_ids = list(participant_ids)
if request.rest_messaging_participant.id not in participant_ids:
participant_ids.append(request.rest_messaging_participant.id)
# we need at least one other participant
if len(participant_ids) < 2:
raise Exception('At least two participants are required.')
if getattr(settings, "REST_MESSAGING_THREAD_UNIQUE_FOR_ACTIVE_RECIPIENTS", True) is True:
# if we limit the number of threads by active participants
# we ensure a thread is not already running
existing_threads = self.get_active_threads_involving_all_participants(*participant_ids)
if len(list(existing_threads)) > 0:
return existing_threads[0]
# we have no existing Thread or multiple Thread instances are allowed
thread = Thread.objects.create(name=name)
# we add the participants
thread.add_participants(request, *participant_ids)
# we send a signal to say the thread with participants is created
post_save.send(Thread, instance=thread, created=True, created_and_add_participants=True, request_participant_id=request.rest_messaging_participant.id)
return thread |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def return_daily_messages_count(self, sender):
""" Returns the number of messages sent in the last 24 hours so we can ensure the user does not exceed his messaging limits """ |
h24 = now() - timedelta(days=1)
return Message.objects.filter(sender=sender, sent_at__gte=h24).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 check_who_read(self, messages):
""" Check who read each message. """ |
# we get the corresponding Participation objects
for m in messages:
readers = []
for p in m.thread.participation_set.all():
if p.date_last_check is None:
pass
elif p.date_last_check > m.sent_at:
# the message has been read
readers.append(p.participant.id)
setattr(m, "readers", readers)
return messages |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_is_notification(self, participant_id, messages):
""" Check if each message requires a notification for the specified participant. """ |
try:
# we get the last check
last_check = NotificationCheck.objects.filter(participant__id=participant_id).latest('id').date_check
except Exception:
# we have no notification check
# all the messages are considered as new
for m in messages:
m.is_notification = True
return messages
for m in messages:
if m.sent_at > last_check and m.sender.id != participant_id:
setattr(m, "is_notification", True)
else:
setattr(m, "is_notification", False)
return messages |
<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_lasts_messages_of_threads(self, participant_id, check_who_read=True, check_is_notification=True):
""" Returns the last message in each thread """ |
# we get the last message for each thread
# we must query the messages using two queries because only Postgres supports .order_by('thread', '-sent_at').distinct('thread')
threads = Thread.managers.\
get_threads_where_participant_is_active(participant_id).\
annotate(last_message_id=Max('message__id'))
messages = Message.objects.filter(id__in=[thread.last_message_id for thread in threads]).\
order_by('-id').\
distinct().\
select_related('thread', 'sender')
if check_who_read is True:
messages = messages.prefetch_related('thread__participation_set', 'thread__participation_set__participant')
messages = self.check_who_read(messages)
else:
messages = messages.prefetch_related('thread__participants')
if check_is_notification is True:
messages = self.check_is_notification(participant_id, messages)
return messages |
<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_all_messages_in_thread(self, participant_id, thread_id, check_who_read=True):
""" Returns all the messages in a thread. """ |
try:
messages = Message.objects.filter(thread__id=thread_id).\
order_by('-id').\
select_related('thread').\
prefetch_related('thread__participation_set', 'thread__participation_set__participant')
except Exception:
return Message.objects.none()
messages = self.check_who_read(messages)
return messages |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(self, request, *args, **kwargs):
""" We ensure the Thread only involves eligible participants. """ |
serializer = self.get_serializer(data=compat_get_request_data(request))
compat_serializer_check_is_valid(serializer)
self.perform_create(request, serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mark_thread_as_read(self, request, pk=None):
""" Pk is the pk of the Thread to which the messages belong. """ |
# we get the thread and check for permission
thread = Thread.objects.get(id=pk)
self.check_object_permissions(request, thread)
# we save the date
try:
participation = Participation.objects.get(thread=thread, participant=request.rest_messaging_participant)
participation.date_last_check = now()
participation.save()
# we return the thread
serializer = self.get_serializer(thread)
return Response(serializer.data)
except Exception:
return Response(status=status.HTTP_400_BAD_REQUEST) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def process(self, quoted=False):
''' Parse an URL '''
self.p = urlparse(self.raw)
self.scheme = self.p.scheme
self.netloc = self.p.netloc
self.opath = self.p.path if not quoted else quote(self.p.path)
self.path = [x for x in self.opath.split('/') if x]
self.params = self.p.params
self.query = parse_qs(self.p.query, keep_blank_values=True)
self.fragment = self.p.fragment |
<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(self, url, encoding=None, force_refetch=False, nocache=False, quiet=True):
''' Fetch a HTML file as binary'''
try:
if not force_refetch and self.cache is not None and url in self.cache:
# try to look for content in cache
logging.debug('Retrieving content from cache for {}'.format(url))
return self.cache.retrieve_blob(url, encoding)
encoded_url = WebHelper.encode_url(url)
req = Request(encoded_url, headers={'User-Agent': 'Mozilla/5.0'})
# support gzip
req.add_header('Accept-encoding', 'gzip, deflate')
# Open URL
getLogger().info("Fetching: {url} |".format(url=url))
response = urlopen(req)
content = response.read()
# unzip if required
if 'Content-Encoding' in response.info() and response.info().get('Content-Encoding') == 'gzip':
# unzip
with gzip.open(BytesIO(content)) as gzfile:
content = gzfile.read()
# update cache if required
if self.cache is not None and not nocache:
if url not in self.cache:
self.cache.insert_blob(url, content)
return content.decode(encoding) if content and encoding else content
except URLError as e:
if hasattr(e, 'reason'):
getLogger().exception('We failed to reach {}. Reason: {}'.format(url, e.reason))
elif hasattr(e, 'code'):
getLogger().exception('The server couldn\'t fulfill the request. Error code: {}'.format(e.code))
else:
# Other exception ...
getLogger().exception("Fetching error")
if not quiet:
raise
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 _platform(self) -> Optional[str]: """Extract platform.""" |
try:
return str(self.journey.MainStop.BasicStop.Dep.Platform.text)
except AttributeError:
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 _delay(self) -> int: """Extract departure delay.""" |
try:
return int(self.journey.MainStop.BasicStop.Dep.Delay.text)
except AttributeError:
return 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 _departure(self) -> datetime: """Extract departure time.""" |
departure_time = datetime.strptime(
self.journey.MainStop.BasicStop.Dep.Time.text, "%H:%M"
).time()
if departure_time > (self.now - timedelta(hours=1)).time():
return datetime.combine(self.now.date(), departure_time)
return datetime.combine(self.now.date() + timedelta(days=1), departure_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 _extract(self, attribute) -> str: """Extract train information.""" |
attr_data = self.journey.JourneyAttributeList.JourneyAttribute[
self.attr_types.index(attribute)
].Attribute
attr_variants = attr_data.xpath("AttributeVariant/@type")
data = attr_data.AttributeVariant[attr_variants.index("NORMAL")].Text.pyval
return str(data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pass_list(self) -> List[Dict[str, Any]]: """Extract next stops along the journey.""" |
stops: List[Dict[str, Any]] = []
for stop in self.journey.PassList.BasicStop:
index = stop.get("index")
station = stop.Location.Station.HafasName.Text.text
station_id = stop.Location.Station.ExternalId.text
stops.append({"index": index, "stationId": station_id, "station": station})
return stops |
<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(style):
"""Check `style` against pyout.styling.schema. Parameters style : dict Style object to validate. Raises ------ StyleValidationError if `style` is not valid. """ |
try:
import jsonschema
except ImportError:
return
try:
jsonschema.validate(style, schema)
except jsonschema.ValidationError as exc:
new_exc = StyleValidationError(exc)
# Don't dump the original jsonschema exception because it is already
# included in the StyleValidationError's message.
new_exc.__cause__ = None
raise new_exc |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def value_type(value):
"""Classify `value` of bold, color, and underline keys. Parameters value : style value Returns ------- str, {"simple", "lookup", "re_lookup", "interval"} """ |
try:
keys = list(value.keys())
except AttributeError:
return "simple"
if keys in [["lookup"], ["re_lookup"], ["interval"]]:
return keys[0]
raise ValueError("Type of `value` could not be determined") |
<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_mecab_loc(location):
''' Set MeCab binary location '''
global MECAB_LOC
if not os.path.isfile(location):
logging.getLogger(__name__).warning("Provided mecab binary location does not exist {}".format(location))
logging.getLogger(__name__).info("Mecab binary is switched to: {}".format(location))
MECAB_LOC = location |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def run_mecab_process(content, *args, **kwargs):
''' Use subprocess to run mecab '''
encoding = 'utf-8' if 'encoding' not in kwargs else kwargs['encoding']
mecab_loc = kwargs['mecab_loc'] if 'mecab_loc' in kwargs else None
if mecab_loc is None:
mecab_loc = MECAB_LOC
proc_args = [mecab_loc]
if args:
proc_args.extend(args)
output = subprocess.run(proc_args,
input=content.encode(encoding),
stdout=subprocess.PIPE)
output_string = os.linesep.join(output.stdout.decode(encoding).splitlines())
return output_string |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def parse(content, *args, **kwargs):
''' Use mecab-python3 by default to parse JP text. Fall back to mecab binary app if needed '''
global MECAB_PYTHON3
if 'mecab_loc' not in kwargs and MECAB_PYTHON3 and 'MeCab' in globals():
return MeCab.Tagger(*args).parse(content)
else:
return run_mecab_process(content, *args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def voice(self):
"""tuple. contain text and lang code """ |
dbid = self.lldb.dbid
text, lang = self._voiceoverdb.get_text_lang(dbid)
return text, lang |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add(self, src):
""" store an audio file to storage dir :param src: audio file path :return: checksum value """ |
if not audio.get_type(src):
raise TypeError('The type of this file is not supported.')
return super().add(src) |
<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_cmd(command, arguments):
"""Merge command with arguments.""" |
if arguments is None:
arguments = []
if command.endswith(".py") or command.endswith(".pyw"):
return [sys.executable, command] + list(arguments)
else:
return [command] + list(arguments) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def argparse(argv, parser, arguments):
""" A command line argument parser. Parses arguments coming from the argv Observable and outputs them as Argument items in the output observable. Parameters argv : Observable An Observable of strings. parser : Observable An Observable containing one Parser item. arguments : Observable An Observable containing ArgumentDef items. Returns ------- Observable An Observable of Argument items. """ |
def add_arg(parser, arg_spec):
parser.add_argument(arg_spec.name, help=arg_spec.help)
return parser
parse_request = parser \
.map(lambda i: ArgumentParser(description=i.description)) \
.combine_latest(arguments, lambda parser, arg_def: add_arg(parser,arg_def)) \
.last() \
.combine_latest(argv.to_list(), lambda parser, args: (parser,args))
def subscribe(observer):
def on_next(value):
parser, args = value
try:
args = parser.parse_args(args)
for key,value in vars(args).items():
observer.on_next(Argument(key=key, value=value))
except NameError as exc:
observer.on_error("{}\n{}".format(exc, parser.format_help()))
return parse_request.subscribe(on_next, observer.on_error, observer.on_completed)
return AnonymousObservable(subscribe) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def qn(phi, *n):
""" Calculate the complex flow vector `Q_n`. :param array-like phi: Azimuthal angles. :param int n: One or more harmonics to calculate. :returns: A single complex number if only one ``n`` was given or a complex array for multiple ``n``. """ |
phi = np.ravel(phi)
n = np.asarray(n)
i_n_phi = np.zeros((n.size, phi.size), dtype=complex)
np.outer(n, phi, out=i_n_phi.imag)
qn = np.exp(i_n_phi, out=i_n_phi).sum(axis=1)
if qn.size == 1:
qn = qn[0]
return qn |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def correlation(self, n, k, error=False):
r""" Calculate `\langle k \rangle_n`, the `k`-particle correlation function for `n`\ th-order anisotropy. :param int n: Anisotropy order. :param int k: Correlation order. :param bool error: Whether to calculate statistical error (for `\langle 2 \rangle` only). If true, return a tuple ``(corr, corr_error)``. """ |
self._calculate_corr(n, k)
corr_nk = self._corr[n][k]
if error:
self._calculate_corr_err(n, k)
return corr_nk, self._corr_err[n][k]
else:
return corr_nk |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pdf(self, phi):
""" Evaluate the _unnormalized_ flow PDF. """ |
pdf = np.inner(self._vn, np.cos(np.outer(phi, self._n)))
pdf *= 2.
pdf += 1.
return pdf |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _uniform_phi(M):
""" Generate M random numbers in [-pi, pi). """ |
return np.random.uniform(-np.pi, np.pi, 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 sample(self, multiplicity):
r""" Randomly sample azimuthal angles `\phi`. :param int multiplicity: Number to sample. :returns: Array of sampled angles. """ |
if self._n is None:
return self._uniform_phi(multiplicity)
# Since the flow PDF does not have an analytic inverse CDF, I use a
# simple accept-reject sampling algorithm. This is reasonably
# efficient since for normal-sized vn, the PDF is close to flat. Now
# due to the overhead of Python functions, it's desirable to minimize
# the number of calls to the random number generator. Therefore I
# sample numbers in chunks; most of the time only one or two chunks
# should be needed. Eventually, I might rewrite this with Cython, but
# it's fast enough for now.
N = 0 # number of phi that have been sampled
phi = np.empty(multiplicity) # allocate array for phi
pdf_max = 1 + 2*self._vn.sum() # sampling efficiency ~ 1/pdf_max
while N < multiplicity:
n_remaining = multiplicity - N
n_to_sample = int(1.03*pdf_max*n_remaining)
phi_chunk = self._uniform_phi(n_to_sample)
phi_chunk = phi_chunk[self._pdf(phi_chunk) >
np.random.uniform(0, pdf_max, n_to_sample)]
K = min(phi_chunk.size, n_remaining) # number of phi to take
phi[N:N+K] = phi_chunk[:K]
N += K
return phi |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def dumps(obj, *args, **kwargs):
''' Typeless dump an object to json string '''
return json.dumps(obj, *args, cls=TypelessSONEncoder, ensure_ascii=False, **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 txt2mecab(text, **kwargs):
''' Use mecab to parse one sentence '''
mecab_out = _internal_mecab_parse(text, **kwargs).splitlines()
tokens = [MeCabToken.parse(x) for x in mecab_out]
return MeCabSent(text, tokens) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def lines2mecab(lines, **kwargs):
''' Use mecab to parse many lines '''
sents = []
for line in lines:
sent = txt2mecab(line, **kwargs)
sents.append(sent)
return sents |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def pos3(self):
''' Use pos-sc1-sc2 as POS '''
parts = [self.pos]
if self.sc1 and self.sc1 != '*':
parts.append(self.sc1)
if self.sc2 and self.sc2 != '*':
parts.append(self.sc2)
return '-'.join(parts) |
<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_ruby(self):
''' Convert one MeCabToken into HTML '''
if self.need_ruby():
surface = self.surface
reading = self.reading_hira()
return '<ruby><rb>{sur}</rb><rt>{read}</rt></ruby>'.format(sur=surface, read=reading)
elif self.is_eos:
return ''
else:
return self.surface |
<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(self, sentence_text, **kwargs):
''' Parse a text string and add it to this doc '''
sent = MeCabSent.parse(sentence_text, **kwargs)
self.sents.append(sent)
return sent |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def output(self, response, accepts):
""" Formats a response from a view to handle any RDF graphs If a view function returns an RDF graph, serialize it based on Accept header If it's not an RDF graph, return it without any special handling """ |
graph = self.get_graph(response)
if graph is not None:
# decide the format
mimetype, format = self.format_selector.decide(accepts, graph.context_aware)
# requested content couldn't find anything
if mimetype is None:
return self.make_406_response()
# explicitly mark text mimetypes as utf-8
if 'text' in mimetype:
mimetype = mimetype + '; charset=utf-8'
# format the new response
serialized = graph.serialize(format=format)
response = self.make_new_response(response, mimetype, serialized)
return response
else:
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 decorate(self, view):
""" Wraps a view function to return formatted RDF graphs Uses content negotiation to serialize the graph to the client-preferred format Passes other content through unmodified """ |
from functools import wraps
@wraps(view)
def decorated(*args, **kwargs):
response = view(*args, **kwargs)
accept = self.get_accept()
return self.output(response, accept)
return decorated |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ecc(self, n):
r""" Calculate eccentricity harmonic `\varepsilon_n`. :param int n: Eccentricity order. """ |
ny, nx = self._profile.shape
xmax, ymax = self._xymax
xcm, ycm = self._cm
# create (X, Y) grids relative to CM
Y, X = np.mgrid[ymax:-ymax:1j*ny, -xmax:xmax:1j*nx]
X -= xcm
Y -= ycm
# create grid of weights = profile * R^n
Rsq = X*X + Y*Y
if n == 1:
W = np.sqrt(Rsq, out=Rsq)
elif n == 2:
W = Rsq
else:
if n & 1: # odd n
W = np.sqrt(Rsq)
else: # even n
W = np.copy(Rsq)
# multiply by R^2 until W = R^n
for _ in range(int((n-1)/2)):
W *= Rsq
W *= self._profile
# create grid of e^{i*n*phi} * W
i_n_phi = np.zeros_like(X, dtype=complex)
np.arctan2(Y, X, out=i_n_phi.imag)
i_n_phi.imag *= n
exp_phi = np.exp(i_n_phi, out=i_n_phi)
exp_phi *= W
return abs(exp_phi.sum()) / W.sum() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, var, default=None):
"""Return a value from configuration. Safe version which always returns a default value if the value is not found. """ |
try:
return self.__get(var)
except (KeyError, IndexError):
return default |
<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, var, value, index=None):
"""Insert at the index. If the index is not provided appends to the end of the list. """ |
current = self.__get(var)
if not isinstance(current, list):
raise KeyError("%s: is not a list" % var)
if index is None:
current.append(value)
else:
current.insert(index, value)
if self.auto_save:
self.save() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def keys(self):
"""Return a merged set of top level keys from all configurations.""" |
s = set()
for config in self.__configs:
s |= config.keys()
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 split(s, posix=True):
"""Split the string s using shell-like syntax. Args: s (str):
String to split posix (bool):
Use posix split Returns: list of str: List of string parts """ |
if isinstance(s, six.binary_type):
s = s.decode("utf-8")
return shlex.split(s, posix=posix) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search(path, matcher="*", dirs=False, files=True):
"""Recursive search function. Args: path (str):
Path to search recursively matcher (str or callable):
String pattern to search for or function that returns True/False for a file argument dirs (bool):
if True returns directories that match the pattern files(bool):
if True returns files that match the patter Yields: str: Found files and directories """ |
if callable(matcher):
def fnmatcher(items):
return list(filter(matcher, items))
else:
def fnmatcher(items):
return fnmatch.filter(items, matcher)
for root, directories, filenames in os.walk(os.path.abspath(path)):
to_match = []
if dirs:
to_match.extend(directories)
if files:
to_match.extend(filenames)
for item in fnmatcher(to_match):
yield os.path.join(root, item) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def chdir(directory):
"""Change the current working directory. Args: directory (str):
Directory to go to. """ |
directory = os.path.abspath(directory)
logger.info("chdir -> %s" % directory)
try:
if not os.path.isdir(directory):
logger.error(
"chdir -> %s failed! Directory does not exist!", directory
)
return False
os.chdir(directory)
return True
except Exception as e:
logger.error("chdir -> %s failed! %s" % (directory, e))
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 goto(directory, create=False):
"""Context object for changing directory. Args: directory (str):
Directory to go to. create (bool):
Create directory if it doesn't exists. Usage:: """ |
current = os.getcwd()
directory = os.path.abspath(directory)
if os.path.isdir(directory) or (create and mkdir(directory)):
logger.info("goto -> %s", directory)
os.chdir(directory)
try:
yield True
finally:
logger.info("goto <- %s", directory)
os.chdir(current)
else:
logger.info(
"goto(%s) - directory does not exist, or cannot be " "created.",
directory,
)
yield 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 remove(path):
"""Delete a file or directory. Args: path (str):
Path to the file or directory that needs to be deleted. Returns: bool: True if the operation is successful, False otherwise. """ |
if os.path.isdir(path):
return __rmtree(path)
else:
return __rmfile(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 read(path, encoding="utf-8"):
"""Read the content of the file. Args: path (str):
Path to the file encoding (str):
File encoding. Default: utf-8 Returns: str: File content or empty string if there was an error """ |
try:
with io.open(path, encoding=encoding) as f:
return f.read()
except Exception as e:
logger.error("read: %s failed. Error: %s", path, e)
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 touch(path, content="", encoding="utf-8", overwrite=False):
"""Create a file at the given path if it does not already exists. Args: path (str):
Path to the file. content (str):
Optional content that will be written in the file. encoding (str):
Encoding in which to write the content. Default: ``utf-8`` overwrite (bool):
Overwrite the file if exists. Returns: bool: True if the operation is successful, False otherwise. """ |
path = os.path.abspath(path)
if not overwrite and os.path.exists(path):
logger.warning('touch: "%s" already exists', path)
return False
try:
logger.info("touch: %s", path)
with io.open(path, "wb") as f:
if not isinstance(content, six.binary_type):
content = content.encode(encoding)
f.write(content)
return True
except Exception as e:
logger.error("touch: %s failed. Error: %s", path, e)
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_object(path="", obj=None):
"""Return an object from a dot path. Path can either be a full path, in which case the `get_object` function will try to import the modules in the path and follow it to the final object. Or it can be a path relative to the object passed in as the second argument. Args: path (str):
Full or relative dot path to the desired object obj (object):
Starting object. Dot path is calculated relatively to this object. Returns: Object at the end of the path, or list of non hidden objects if we use the star query. Example for full paths:: <function join at 0x1002d9ed8> <module 'tea.process' from 'tea/process/__init__.pyc'> Example for relative paths when an object is passed in:: <function join at 0x1002d9ed8> Example for a star query. (Star query can be used only as the last element of the path:: [] [<class 'tea.dsa.singleton.Singleton'>, <class 'tea.dsa.singleton.SingletonMetaclass'> """ |
if not path:
return obj
path = path.split(".")
if obj is None:
obj = importlib.import_module(path[0])
path = path[1:]
for item in path:
if item == "*":
# This is the star query, returns non hidden objects
return [
getattr(obj, name)
for name in dir(obj)
if not name.startswith("__")
]
if isinstance(obj, types.ModuleType):
submodule = "{}.{}".format(_package(obj), item)
try:
obj = importlib.import_module(submodule)
except Exception as import_error:
try:
obj = getattr(obj, item)
except Exception:
# FIXME: I know I should probably merge the errors, but
# it's easier just to throw the import error since
# it's most probably the one user wants to see.
# Create a new LoadingError and throw a combination
# of the import error and attribute error.
raise import_error
else:
obj = getattr(obj, item)
return 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 load_subclasses(klass, modules=None):
"""Load recursively all all subclasses from a module. Args: klass (str or list of str):
Class whose subclasses we want to load. modules: List of additional modules or module names that should be recursively imported in order to find all the subclasses of the desired class. Default: None FIXME: This function is kept only for backward compatibility reasons, it should not be used. Deprecation warning should be raised and it should be replaces by the ``Loader`` class. """ |
if modules:
if isinstance(modules, six.string_types):
modules = [modules]
loader = Loader()
loader.load(*modules)
return klass.__subclasses__() |
<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_exception():
"""Return full formatted traceback as a string.""" |
trace = ""
exception = ""
exc_list = traceback.format_exception_only(
sys.exc_info()[0], sys.exc_info()[1]
)
for entry in exc_list:
exception += entry
tb_list = traceback.format_tb(sys.exc_info()[2])
for entry in tb_list:
trace += entry
return "%s\n%s" % (exception, trace) |
<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(self, *modules):
"""Load one or more modules. Args: modules: Either a string full path to a module or an actual module object. """ |
for module in modules:
if isinstance(module, six.string_types):
try:
module = get_object(module)
except Exception as e:
self.errors[module] = e
continue
self.modules[module.__package__] = module
for (loader, module_name, is_pkg) in pkgutil.walk_packages(
module.__path__
):
full_name = "{}.{}".format(_package(module), module_name)
try:
self.modules[full_name] = get_object(full_name)
if is_pkg:
self.load(self.modules[full_name])
except Exception as e:
self.errors[full_name] = 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 _product_filter(products) -> str: """Calculate the product filter.""" |
_filter = 0
for product in {PRODUCTS[p] for p in products}:
_filter += product
return format(_filter, "b")[::-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 _base_url() -> str: """Build base url.""" |
_lang: str = "d"
_type: str = "n"
_with_suggestions: str = "?"
return BASE_URI + STBOARD_PATH + _lang + _type + _with_suggestions |
<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 get_departures( self, station_id: str, direction_id: Optional[str] = None, max_journeys: int = 20, products: Optional[List[str]] = None, ) -> Dict[str, Any]: """Fetch data from rmv.de.""" |
self.station_id: str = station_id
self.direction_id: str = direction_id
self.max_journeys: int = max_journeys
self.products_filter: str = _product_filter(products or ALL_PRODUCTS)
base_url: str = _base_url()
params: Dict[str, Union[str, int]] = {
"selectDate": "today",
"time": "now",
"input": self.station_id,
"maxJourneys": self.max_journeys,
"boardType": "dep",
"productsFilter": self.products_filter,
"disableEquivs": "discard_nearby",
"output": "xml",
"start": "yes",
}
if self.direction_id:
params["dirInput"] = self.direction_id
url = base_url + urllib.parse.urlencode(params)
try:
with async_timeout.timeout(self._timeout):
async with self._session.get(url) as response:
_LOGGER.debug(f"Response from RMV API: {response.status}")
xml = await response.read()
_LOGGER.debug(xml)
except (asyncio.TimeoutError, aiohttp.ClientError):
_LOGGER.error("Can not load data from RMV API")
raise RMVtransportApiConnectionError()
# pylint: disable=I1101
try:
self.obj = objectify.fromstring(xml)
except (TypeError, etree.XMLSyntaxError):
_LOGGER.debug(f"Get from string: {xml[:100]}")
print(f"Get from string: {xml}")
raise RMVtransportError()
try:
self.now = self.current_time()
self.station = self._station()
except (TypeError, AttributeError):
_LOGGER.debug(
f"Time/Station TypeError or AttributeError {objectify.dump(self.obj)}"
)
raise RMVtransportError()
self.journeys.clear()
try:
for journey in self.obj.SBRes.JourneyList.Journey:
self.journeys.append(RMVJourney(journey, self.now))
except AttributeError:
_LOGGER.debug(f"Extract journeys: {objectify.dump(self.obj.SBRes)}")
raise RMVtransportError()
return self.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 data(self) -> Dict[str, Any]: """Return travel data.""" |
data: Dict[str, Any] = {}
data["station"] = self.station
data["stationId"] = self.station_id
data["filter"] = self.products_filter
journeys = []
for j in sorted(self.journeys, key=lambda k: k.real_departure)[
: self.max_journeys
]:
journeys.append(
{
"product": j.product,
"number": j.number,
"trainId": j.train_id,
"direction": j.direction,
"departure_time": j.real_departure_time,
"minutes": j.real_departure,
"delay": j.delay,
"stops": [s["station"] for s in j.stops],
"info": j.info,
"info_long": j.info_long,
"icon": j.icon,
}
)
data["journeys"] = journeys
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 _station(self) -> str: """Extract station name.""" |
return str(self.obj.SBRes.SBReq.Start.Station.HafasName.Text.pyval) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def current_time(self) -> datetime: """Extract current time.""" |
_date = datetime.strptime(self.obj.SBRes.SBReq.StartT.get("date"), "%Y%m%d")
_time = datetime.strptime(self.obj.SBRes.SBReq.StartT.get("time"), "%H:%M")
return datetime.combine(_date.date(), _time.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 process_file(path, processor, encoding='utf-8', mode='rt', *args, **kwargs):
''' Process a text file's content. If the file name ends with .gz, read it as gzip file '''
if mode not in ('rU', 'rt', 'rb', 'r'):
raise Exception("Invalid file reading mode")
with open(path, encoding=encoding, mode=mode, *args, **kwargs) as infile:
return processor(infile) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def read_file(path, encoding='utf-8', *args, **kwargs):
''' Read text file content. If the file name ends with .gz, read it as gzip file.
If mode argument is provided as 'rb', content will be read as byte stream.
By default, content is read as string.
'''
if 'mode' in kwargs and kwargs['mode'] == 'rb':
return process_file(path, processor=lambda x: x.read(),
encoding=encoding, *args, **kwargs)
else:
return process_file(path, processor=lambda x: to_string(x.read(), encoding),
encoding=encoding, *args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def write_file(path, content, mode=None, encoding='utf-8'):
''' Write content to a file. If the path ends with .gz, gzip will be used. '''
if not mode:
if isinstance(content, bytes):
mode = 'wb'
else:
mode = 'wt'
if not path:
raise ValueError("Output path is invalid")
else:
getLogger().debug("Writing content to {}".format(path))
# convert content to string when writing text data
if mode in ('w', 'wt') and not isinstance(content, str):
content = to_string(content)
elif mode == 'wb':
# content needs to be encoded as bytes
if not isinstance(content, str):
content = to_string(content).encode(encoding)
else:
content = content.encode(encoding)
if str(path).endswith('.gz'):
with gzip.open(path, mode) as outfile:
outfile.write(content)
else:
with open(path, mode=mode) as outfile:
outfile.write(content) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def forbid_multi_line_headers(name, val):
"""Forbid multi-line headers, to prevent header injection.""" |
val = smart_text(val)
if "\n" in val or "\r" in val:
raise BadHeaderError(
"Header values can't contain newlines "
"(got %r for header %r)" % (val, name)
)
try:
val = val.encode("ascii")
except UnicodeEncodeError:
if name.lower() in ("to", "from", "cc"):
result = []
for item in val.split(", "):
nm, addr = parseaddr(item)
nm = str(Header(nm, DEFAULT_CHARSET))
result.append(formataddr((nm, str(addr))))
val = ", ".join(result)
else:
val = Header(val, DEFAULT_CHARSET)
else:
if name.lower() == "subject":
val = Header(val)
return name, 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 close(self):
"""Close the connection to the email server.""" |
try:
try:
self.connection.quit()
except socket.sslerror:
# This happens when calling quit() on a TLS connection
# sometimes.
self.connection.close()
except Exception as e:
logger.error(
"Error trying to close connection to server " "%s:%s: %s",
self.host,
self.port,
e,
)
if self.fail_silently:
return
raise
finally:
self.connection = 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 _send(self, message):
"""Send an email.
Helper method that does the actual sending.
""" |
if not message.recipients():
return False
try:
self.connection.sendmail(
message.sender,
message.recipients(),
message.message().as_string(),
)
except Exception as e:
logger.error(
"Error sending a message to server %s:%s: %s",
self.host,
self.port,
e,
)
if not self.fail_silently:
raise
return False
return True |
<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_file(self, path, mimetype=None):
"""Attache a file from the filesystem.""" |
filename = os.path.basename(path)
content = open(path, "rb").read()
self.attach(filename, content, mimetype) |
<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_attachment(self, filename, content, mimetype=None):
"""Convert the filename, content, mimetype triple to attachment.""" |
if mimetype is None:
mimetype, _ = mimetypes.guess_type(filename)
if mimetype is None:
mimetype = DEFAULT_ATTACHMENT_MIME_TYPE
basetype, subtype = mimetype.split("/", 1)
if basetype == "text":
attachment = SafeMIMEText(
smart_bytes(content, DEFAULT_CHARSET), subtype, DEFAULT_CHARSET
)
else:
# Encode non-text attachments with base64.
attachment = MIMEBase(basetype, subtype)
attachment.set_payload(content)
encode_base64(attachment)
if filename:
attachment.add_header(
"Content-Disposition", "attachment", filename=filename
)
return attachment |
<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_alternative(self, content, mimetype=None):
"""Attach an alternative content representation.""" |
self.attach(content=content, mimetype=mimetype) |
<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(verbose=False, logger=None):
"""Setup console logging. Info and below go to stdout, others go to stderr. :param bool verbose: Print debug statements. :param str logger: Which logger to set handlers to. Used for testing. """ |
if not verbose:
logging.getLogger('requests').setLevel(logging.WARNING)
format_ = '%(asctime)s %(levelname)-8s %(name)-40s %(message)s' if verbose else '%(message)s'
level = logging.DEBUG if verbose else logging.INFO
handler_stdout = logging.StreamHandler(sys.stdout)
handler_stdout.setFormatter(logging.Formatter(format_))
handler_stdout.setLevel(logging.DEBUG)
handler_stdout.addFilter(InfoFilter())
handler_stderr = logging.StreamHandler(sys.stderr)
handler_stderr.setFormatter(logging.Formatter(format_))
handler_stderr.setLevel(logging.WARNING)
root_logger = logging.getLogger(logger)
root_logger.setLevel(level)
root_logger.addHandler(handler_stdout)
root_logger.addHandler(handler_stderr) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def with_log(func):
"""Automatically adds a named logger to a function upon function call. :param func: Function to decorate. :return: Decorated function. :rtype: function """ |
@functools.wraps(func)
def wrapper(*args, **kwargs):
"""Inject `log` argument into wrapped function.
:param list args: Pass through all positional arguments.
:param dict kwargs: Pass through all keyword arguments.
"""
decorator_logger = logging.getLogger('@with_log')
decorator_logger.debug('Entering %s() function call.', func.__name__)
log = kwargs.get('log', logging.getLogger(func.__name__))
try:
ret = func(log=log, *args, **kwargs)
finally:
decorator_logger.debug('Leaving %s() function call.', func.__name__)
return ret
return 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 get_arguments(argv=None, environ=None):
"""Get command line arguments or values from environment variables. :param list argv: Command line argument list to process. For testing. :param dict environ: Environment variables. For testing. :return: Parsed options. :rtype: dict """ |
name = 'appveyor-artifacts'
environ = environ or os.environ
require = getattr(pkg_resources, 'require') # Stupid linting error.
commit, owner, pull_request, repo, tag = '', '', '', '', ''
# Run docopt.
project = [p for p in require(name) if p.project_name == name][0]
version = project.version
args = docopt(__doc__, argv=argv or sys.argv[1:], version=version)
# Handle Travis environment variables.
if environ.get('TRAVIS') == 'true':
commit = environ.get('TRAVIS_COMMIT', '')
owner = environ.get('TRAVIS_REPO_SLUG', '/').split('/')[0]
pull_request = environ.get('TRAVIS_PULL_REQUEST', '')
if pull_request == 'false':
pull_request = ''
repo = environ.get('TRAVIS_REPO_SLUG', '/').split('/')[1].replace('_', '-')
tag = environ.get('TRAVIS_TAG', '')
# Command line arguments override.
commit = args['--commit'] or commit
owner = args['--owner-name'] or owner
pull_request = args['--pull-request'] or pull_request
repo = args['--repo-name'] or repo
tag = args['--tag-name'] or tag
# Merge env variables and have command line args override.
config = {
'always_job_dirs': args['--always-job-dirs'],
'commit': commit,
'dir': args['--dir'] or '',
'ignore_errors': args['--ignore-errors'],
'job_name': args['--job-name'] or '',
'mangle_coverage': args['--mangle-coverage'],
'no_job_dirs': args['--no-job-dirs'] or '',
'owner': owner,
'pull_request': pull_request,
'raise': args['--raise'],
'repo': repo,
'tag': tag,
'verbose': args['--verbose'],
}
return 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 query_api(endpoint, log):
"""Query the AppVeyor API. :raise HandledError: On non HTTP200 responses or invalid JSON response. :param str endpoint: API endpoint to query (e.g. '/projects/Robpol86/appveyor-artifacts'). :param logging.Logger log: Logger for this function. Populated by with_log() decorator. :return: Parsed JSON response. :rtype: dict """ |
url = API_PREFIX + endpoint
headers = {'content-type': 'application/json'}
response = None
log.debug('Querying %s with headers %s.', url, headers)
for i in range(QUERY_ATTEMPTS):
try:
try:
response = requests.get(url, headers=headers, timeout=10)
except (requests.exceptions.ConnectTimeout, requests.exceptions.ReadTimeout, requests.Timeout):
log.error('Timed out waiting for reply from server.')
raise HandledError
except requests.ConnectionError:
log.error('Unable to connect to server.')
raise HandledError
except HandledError:
if i == QUERY_ATTEMPTS - 1:
raise
log.warning('Network error, retrying in 1 second...')
time.sleep(1)
else:
break
log.debug('Response status: %d', response.status_code)
log.debug('Response headers: %s', str(response.headers))
log.debug('Response text: %s', response.text)
if not response.ok:
message = response.json().get('message')
if message:
log.error('HTTP %d: %s', response.status_code, message)
else:
log.error('HTTP %d: Unknown error: %s', response.status_code, response.text)
raise HandledError
try:
return response.json()
except ValueError:
log.error('Failed to parse JSON: %s', response.text)
raise HandledError |
<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(config, log):
"""Validate config values. :raise HandledError: On invalid config values. :param dict config: Dictionary from get_arguments(). :param logging.Logger log: Logger for this function. Populated by with_log() decorator. """ |
if config['always_job_dirs'] and config['no_job_dirs']:
log.error('Contradiction: --always-job-dirs and --no-job-dirs used.')
raise HandledError
if config['commit'] and not REGEX_COMMIT.match(config['commit']):
log.error('No or invalid git commit obtained.')
raise HandledError
if config['dir'] and not os.path.isdir(config['dir']):
log.error("Not a directory or doesn't exist: %s", config['dir'])
raise HandledError
if config['no_job_dirs'] not in ('', 'rename', 'overwrite', 'skip'):
log.error('--no-job-dirs has invalid value. Check --help for valid values.')
raise HandledError
if not config['owner'] or not REGEX_GENERAL.match(config['owner']):
log.error('No or invalid repo owner name obtained.')
raise HandledError
if config['pull_request'] and not config['pull_request'].isdigit():
log.error('--pull-request is not a digit.')
raise HandledError
if not config['repo'] or not REGEX_GENERAL.match(config['repo']):
log.error('No or invalid repo name obtained.')
raise HandledError
if config['tag'] and not REGEX_GENERAL.match(config['tag']):
log.error('Invalid git tag obtained.')
raise HandledError |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query_build_version(config, log):
"""Find the build version we're looking for. AppVeyor calls build IDs "versions" which is confusing but whatever. Job IDs aren't available in the history query, only on latest, specific version, and deployment queries. Hence we need two queries to get a one-time status update. Returns None if the job isn't queued yet. :raise HandledError: On invalid JSON data. :param dict config: Dictionary from get_arguments(). :param logging.Logger log: Logger for this function. Populated by with_log() decorator. :return: Build version. :rtype: str """ |
url = '/projects/{0}/{1}/history?recordsNumber=10'.format(config['owner'], config['repo'])
# Query history.
log.debug('Querying AppVeyor history API for %s/%s...', config['owner'], config['repo'])
json_data = query_api(url)
if 'builds' not in json_data:
log.error('Bad JSON reply: "builds" key missing.')
raise HandledError
# Find AppVeyor build "version".
for build in json_data['builds']:
if config['tag'] and config['tag'] == build.get('tag'):
log.debug('This is a tag build.')
elif config['pull_request'] and config['pull_request'] == build.get('pullRequestId'):
log.debug('This is a pull request build.')
elif config['commit'] == build['commitId']:
log.debug('This is a branch build.')
else:
continue
log.debug('Build JSON dict: %s', str(build))
return build['version']
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 query_job_ids(build_version, config, log):
"""Get one or more job IDs and their status associated with a build version. Filters jobs by name if --job-name is specified. :raise HandledError: On invalid JSON data or bad job name. :param str build_version: AppVeyor build version from query_build_version(). :param dict config: Dictionary from get_arguments(). :param logging.Logger log: Logger for this function. Populated by with_log() decorator. :return: List of two-item tuples. Job ID (first) and its status (second). :rtype: list """ |
url = '/projects/{0}/{1}/build/{2}'.format(config['owner'], config['repo'], build_version)
# Query version.
log.debug('Querying AppVeyor version API for %s/%s at %s...', config['owner'], config['repo'], build_version)
json_data = query_api(url)
if 'build' not in json_data:
log.error('Bad JSON reply: "build" key missing.')
raise HandledError
if 'jobs' not in json_data['build']:
log.error('Bad JSON reply: "jobs" key missing.')
raise HandledError
# Find AppVeyor job.
all_jobs = list()
for job in json_data['build']['jobs']:
if config['job_name'] and config['job_name'] == job['name']:
log.debug('Filtering by job name: found match!')
return [(job['jobId'], job['status'])]
all_jobs.append((job['jobId'], job['status']))
if config['job_name']:
log.error('Job name "%s" not found.', config['job_name'])
raise HandledError
return all_jobs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query_artifacts(job_ids, log):
"""Query API again for artifacts. :param iter job_ids: List of AppVeyor jobIDs. :param logging.Logger log: Logger for this function. Populated by with_log() decorator. :return: List of tuples: (job ID, artifact file name, artifact file size). :rtype: list """ |
jobs_artifacts = list()
for job in job_ids:
url = '/buildjobs/{0}/artifacts'.format(job)
log.debug('Querying AppVeyor artifact API for %s...', job)
json_data = query_api(url)
for artifact in json_data:
jobs_artifacts.append((job, artifact['fileName'], artifact['size']))
return jobs_artifacts |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def artifacts_urls(config, jobs_artifacts, log):
"""Determine destination file paths for job artifacts. :param dict config: Dictionary from get_arguments(). :param iter jobs_artifacts: List of job artifacts from query_artifacts(). :param logging.Logger log: Logger for this function. Populated by with_log() decorator. :return: Destination file paths (keys), download URLs (value[0]), and expected file size (value[1]). :rtype: dict """ |
artifacts = dict()
# Determine if we should create job ID directories.
if config['always_job_dirs']:
job_dirs = True
elif config['no_job_dirs']:
job_dirs = False
elif len(set(i[0] for i in jobs_artifacts)) == 1:
log.debug('Only one job ID, automatically setting job_dirs = False.')
job_dirs = False
elif len(set(i[1] for i in jobs_artifacts)) == len(jobs_artifacts):
log.debug('No local file conflicts, automatically setting job_dirs = False')
job_dirs = False
else:
log.debug('Multiple job IDs with file conflicts, automatically setting job_dirs = True')
job_dirs = True
# Get final URLs and destination file paths.
root_dir = config['dir'] or os.getcwd()
for job, file_name, size in jobs_artifacts:
artifact_url = '{0}/buildjobs/{1}/artifacts/{2}'.format(API_PREFIX, job, file_name)
artifact_local = os.path.join(root_dir, job if job_dirs else '', file_name)
if artifact_local in artifacts:
if config['no_job_dirs'] == 'skip':
log.debug('Skipping %s from %s', artifact_local, artifact_url)
continue
if config['no_job_dirs'] == 'rename':
new_name = artifact_local
while new_name in artifacts:
path, ext = os.path.splitext(new_name)
new_name = (path + '_' + ext) if ext else (new_name + '_')
log.debug('Renaming %s to %s from %s', artifact_local, new_name, artifact_url)
artifact_local = new_name
elif config['no_job_dirs'] == 'overwrite':
log.debug('Overwriting %s from %s with %s', artifact_local, artifacts[artifact_local][0], artifact_url)
else:
log.error('Collision: %s from %s and %s', artifact_local, artifacts[artifact_local][0], artifact_url)
raise HandledError
artifacts[artifact_local] = (artifact_url, size)
return artifacts |
<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_urls(config, log):
"""Wait for AppVeyor job to finish and get all artifacts' URLs. :param dict config: Dictionary from get_arguments(). :param logging.Logger log: Logger for this function. Populated by with_log() decorator. :return: Paths and URLs from artifacts_urls. :rtype: dict """ |
# Wait for job to be queued. Once it is we'll have the "version".
build_version = None
for _ in range(3):
build_version = query_build_version(config)
if build_version:
break
log.info('Waiting for job to be queued...')
time.sleep(SLEEP_FOR)
if not build_version:
log.error('Timed out waiting for job to be queued or build not found.')
raise HandledError
# Get job IDs. Wait for AppVeyor job to finish.
job_ids = list()
valid_statuses = ['success', 'failed', 'running', 'queued']
while True:
job_ids = query_job_ids(build_version, config)
statuses = set([i[1] for i in job_ids])
if 'failed' in statuses:
job = [i[0] for i in job_ids if i[1] == 'failed'][0]
url = 'https://ci.appveyor.com/project/{0}/{1}/build/job/{2}'.format(config['owner'], config['repo'], job)
log.error('AppVeyor job failed: %s', url)
raise HandledError
if statuses == set(valid_statuses[:1]):
log.info('Build successful. Found %d job%s.', len(job_ids), '' if len(job_ids) == 1 else 's')
break
if 'running' in statuses:
log.info('Waiting for job%s to finish...', '' if len(job_ids) == 1 else 's')
elif 'queued' in statuses:
log.info('Waiting for all jobs to start...')
else:
log.error('Got unknown status from AppVeyor API: %s', ' '.join(statuses - set(valid_statuses)))
raise HandledError
time.sleep(SLEEP_FOR)
# Get artifacts.
artifacts = query_artifacts([i[0] for i in job_ids])
log.info('Found %d artifact%s.', len(artifacts), '' if len(artifacts) == 1 else 's')
return artifacts_urls(config, artifacts) if artifacts else 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 mangle_coverage(local_path, log):
"""Edit .coverage file substituting Windows file paths to Linux paths. :param str local_path: Destination path to save file to. :param logging.Logger log: Logger for this function. Populated by with_log() decorator. """ |
# Read the file, or return if not a .coverage file.
with open(local_path, mode='rb') as handle:
if handle.read(13) != b'!coverage.py:':
log.debug('File %s not a coverage file.', local_path)
return
handle.seek(0)
# I'm lazy, reading all of this into memory. What could possibly go wrong?
file_contents = handle.read(52428800).decode('utf-8') # 50 MiB limit, surely this is enough?
# Substitute paths.
for windows_path in set(REGEX_MANGLE.findall(file_contents)):
unix_relative_path = windows_path.replace(r'\\', '/').split('/', 3)[-1]
unix_absolute_path = os.path.abspath(unix_relative_path)
if not os.path.isfile(unix_absolute_path):
log.debug('Windows path: %s', windows_path)
log.debug('Unix relative path: %s', unix_relative_path)
log.error('No such file: %s', unix_absolute_path)
raise HandledError
file_contents = file_contents.replace(windows_path, unix_absolute_path)
# Write.
with open(local_path, 'w') as handle:
handle.write(file_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 main(config, log):
"""Main function. Runs the program. :param dict config: Dictionary from get_arguments(). :param logging.Logger log: Logger for this function. Populated by with_log() decorator. """ |
validate(config)
paths_and_urls = get_urls(config)
if not paths_and_urls:
log.warning('No artifacts; nothing to download.')
return
# Download files.
total_size = 0
chunk_size = max(min(max(v[1] for v in paths_and_urls.values()) // 50, 1048576), 1024)
log.info('Downloading file%s (1 dot ~ %d KiB):', '' if len(paths_and_urls) == 1 else 's', chunk_size // 1024)
for size, local_path, url in sorted((v[1], k, v[0]) for k, v in paths_and_urls.items()):
download_file(config, local_path, url, size, chunk_size)
total_size += size
if config['mangle_coverage']:
mangle_coverage(local_path)
log.info('Downloaded %d file(s), %d bytes total.', len(paths_and_urls), total_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 entry_point():
"""Entry-point from setuptools.""" |
signal.signal(signal.SIGINT, lambda *_: getattr(os, '_exit')(0)) # Properly handle Control+C
config = get_arguments()
setup_logging(config['verbose'])
try:
main(config)
except HandledError:
if config['raise']:
raise
logging.critical('Failure.')
sys.exit(0 if config['ignore_errors'] else 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 incoming_messages(self) -> t.List[t.Tuple[float, bytes]]: """Consume the receive buffer and return the messages. If there are new messages added to the queue while this funciton is being processed, they will not be returned. This ensures that this terminates in a timely manner. """ |
approximate_messages = self._receive_buffer.qsize()
messages = []
for _ in range(approximate_messages):
try:
messages.append(self._receive_buffer.get_nowait())
except queue.Empty:
break
return messages |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _safe_get(mapping, key, default=None):
"""Helper for accessing style values. It exists to avoid checking whether `mapping` is indeed a mapping before trying to get a key. In the context of style dicts, this eliminates "is this a mapping" checks in two common situations: 1) a style argument is None, and 2) a style key's value (e.g., width) can be either a mapping or a plain value. """ |
try:
return mapping.get(key, default)
except AttributeError:
return default |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def strip_callables(row):
"""Extract callable values from `row`. Replace the callable values with the initial value (if specified) or an empty string. Parameters row : mapping A data row. The keys are either a single column name or a tuple of column names. The values take one of three forms: 1) a non-callable value, 2) a tuple (initial_value, callable), 3) or a single callable (in which case the initial value is set to an empty string). Returns ------- list of (column, callable) """ |
callables = []
to_delete = []
to_add = []
for columns, value in row.items():
if isinstance(value, tuple):
initial, fn = value
else:
initial = NOTHING
# Value could be a normal (non-callable) value or a
# callable with no initial value.
fn = value
if callable(fn) or inspect.isgenerator(fn):
lgr.debug("Using %r as the initial value "
"for columns %r in row %r",
initial, columns, row)
if not isinstance(columns, tuple):
columns = columns,
else:
to_delete.append(columns)
for column in columns:
to_add.append((column, initial))
callables.append((columns, fn))
for column, value in to_add:
row[column] = value
for multi_columns in to_delete:
del row[multi_columns]
return callables |
<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, columns):
"""Build the style and fields. Parameters columns : list of str Column names. """ |
self.columns = columns
default = dict(elements.default("default_"),
**_safe_get(self.init_style, "default_", {}))
self.style = elements.adopt({c: default for c in columns},
self.init_style)
# Store special keys in _style so that they can be validated.
self.style["default_"] = default
self.style["header_"] = self._compose("header_", {"align", "width"})
self.style["aggregate_"] = self._compose("aggregate_",
{"align", "width"})
self.style["separator_"] = _safe_get(self.init_style, "separator_",
elements.default("separator_"))
lgr.debug("Validating style %r", self.style)
self.style["width_"] = _safe_get(self.init_style, "width_",
elements.default("width_"))
elements.validate(self.style)
self._setup_fields()
ngaps = len(self.columns) - 1
self.width_separtor = len(self.style["separator_"]) * ngaps
lgr.debug("Calculated separator width as %d", self.width_separtor) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _compose(self, name, attributes):
"""Construct a style taking `attributes` from the column styles. Parameters name : str Name of main style (e.g., "header_"). attributes : set of str Adopt these elements from the column styles. Returns ------- The composite style for `name`. """ |
name_style = _safe_get(self.init_style, name, elements.default(name))
if self.init_style is not None and name_style is not None:
result = {}
for col in self.columns:
cstyle = {k: v for k, v in self.style[col].items()
if k in attributes}
result[col] = dict(cstyle, **name_style)
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 _set_widths(self, row, proc_group):
"""Update auto-width Fields based on `row`. Parameters row : dict proc_group : {'default', 'override'} Whether to consider 'default' or 'override' key for pre- and post-format processors. Returns ------- True if any widths required adjustment. """ |
width_free = self.style["width_"] - sum(
[sum(self.fields[c].width for c in self.columns),
self.width_separtor])
if width_free < 0:
width_fixed = sum(
[sum(self.fields[c].width for c in self.columns
if c not in self.autowidth_columns),
self.width_separtor])
assert width_fixed > self.style["width_"], "bug in width logic"
raise elements.StyleError(
"Fixed widths specified in style exceed total width")
elif width_free == 0:
lgr.debug("Not checking widths; no free width left")
return False
lgr.debug("Checking width for row %r", row)
adjusted = False
for column in sorted(self.columns, key=lambda c: self.fields[c].width):
# ^ Sorting the columns by increasing widths isn't necessary; we do
# it so that columns that already take up more of the screen don't
# continue to grow and use up free width before smaller columns
# have a chance to claim some.
if width_free < 1:
lgr.debug("Giving up on checking widths; no free width left")
break
if column in self.autowidth_columns:
field = self.fields[column]
lgr.debug("Checking width of column %r "
"(field width: %d, free width: %d)",
column, field.width, width_free)
# If we've added any style transform functions as
# pre-format processors, we want to measure the width
# of their result rather than the raw value.
if field.pre[proc_group]:
value = field(row[column], keys=[proc_group],
exclude_post=True)
else:
value = row[column]
value = six.text_type(value)
value_width = len(value)
wmax = self.autowidth_columns[column]["max"]
if value_width > field.width:
width_old = field.width
width_available = width_free + field.width
width_new = min(value_width,
wmax or width_available,
width_available)
if width_new > width_old:
adjusted = True
field.width = width_new
lgr.debug("Adjusting width of %r column from %d to %d "
"to accommodate value %r",
column, width_old, field.width, value)
self._truncaters[column].length = field.width
width_free -= field.width - width_old
lgr.debug("Free width is %d after processing column %r",
width_free, column)
return adjusted |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _proc_group(self, style, adopt=True):
"""Return whether group is "default" or "override". In the case of "override", the self.fields pre-format and post-format processors will be set under the "override" key. Parameters style : dict A style that follows the schema defined in pyout.elements. adopt : bool, optional Merge `self.style` and `style`, giving priority to the latter's keys when there are conflicts. If False, treat `style` as a standalone style. """ |
fields = self.fields
if style is not None:
if adopt:
style = elements.adopt(self.style, style)
elements.validate(style)
for column in self.columns:
fields[column].add(
"pre", "override",
*(self.procgen.pre_from_style(style[column])))
fields[column].add(
"post", "override",
*(self.procgen.post_from_style(style[column])))
return "override"
else:
return "default" |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render(self, row, style=None, adopt=True):
"""Render fields with values from `row`. Parameters row : dict A normalized row. style : dict, optional A style that follows the schema defined in pyout.elements. If None, `self.style` is used. adopt : bool, optional Merge `self.style` and `style`, using the latter's keys when there are conflicts. If False, treat `style` as a standalone style. Returns ------- A tuple with the rendered value (str) and a flag that indicates whether the field widths required adjustment (bool). """ |
group = self._proc_group(style, adopt=adopt)
if group == "override":
# Override the "default" processor key.
proc_keys = ["width", "override"]
else:
# Use the set of processors defined by _setup_fields.
proc_keys = None
adjusted = self._set_widths(row, group)
proc_fields = [self.fields[c](row[c], keys=proc_keys)
for c in self.columns]
return self.style["separator_"].join(proc_fields) + "\n", adjusted |
<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_config(self):
""" Sets up the basic config from the variables passed in all of these are from what Heroku gives you. """ |
self.create_ssl_certs()
config = {
"bootstrap_servers": self.get_brokers(),
"security_protocol": 'SSL',
"ssl_cafile": self.ssl["ca"]["file"].name,
"ssl_certfile": self.ssl["cert"]["file"].name,
"ssl_keyfile": self.ssl["key"]["file"].name,
"ssl_check_hostname": False,
"ssl_password": None
}
self.config.update(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 create_ssl_certs(self):
""" Creates SSL cert files """ |
for key, file in self.ssl.items():
file["file"] = self.create_temp_file(file["suffix"], file["content"]) |
<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_temp_file(self, suffix, content):
""" Creates file, because environment variables are by default escaped it encodes and then decodes them before write so \n etc. work correctly. """ |
temp = tempfile.NamedTemporaryFile(suffix=suffix)
temp.write(content.encode('latin1').decode('unicode_escape').encode('utf-8'))
temp.seek(0) # Resets the temp file line to 0
return temp |
<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, topic, *args, **kwargs):
""" Appends the prefix to the topic before sendingf """ |
prefix_topic = self.heroku_kafka.prefix_topic(topic)
return super(HerokuKafkaProducer, self).send(prefix_topic, *args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, variable_path: str, default: t.Optional[t.Any] = None, coerce_type: t.Optional[t.Type] = None, coercer: t.Optional[t.Callable] = None, **kwargs):
""" Inherited method should take all specified arguments. :param variable_path: a delimiter-separated path to a nested value :param default: default value if there's no object by specified path :param coerce_type: cast a type of a value to a specified one :param coercer: perform a type casting with specified callback :param kwargs: additional arguments inherited parser may need :return: value or default """ |
raise NotImplementedError |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def coerce(val: t.Any, coerce_type: t.Optional[t.Type] = None, coercer: t.Optional[t.Callable] = None) -> t.Any: """ Casts a type of ``val`` to ``coerce_type`` with ``coercer``. If ``coerce_type`` is bool and no ``coercer`` specified it uses :func:`~django_docker_helpers.utils.coerce_str_to_bool` by default. :param val: a value of any type :param coerce_type: any type :param coercer: provide a callback that takes ``val`` and returns a value with desired type :return: type casted value """ |
if not coerce_type and not coercer:
return val
if coerce_type and type(val) is coerce_type:
return val
if coerce_type and coerce_type is bool and not coercer:
coercer = coerce_str_to_bool
if coercer is None:
coercer = coerce_type
return coercer(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 _splice(value, n):
"""Splice `value` at its center, retaining a total of `n` characters. Parameters value : str n : int The total length of the returned ends will not be greater than this value. Characters will be dropped from the center to reach this limit. Returns ------- A tuple of str: (head, tail). """ |
if n <= 0:
raise ValueError("n must be positive")
value_len = len(value)
center = value_len // 2
left, right = value[:center], value[center:]
if n >= value_len:
return left, right
n_todrop = value_len - n
right_idx = n_todrop // 2
left_idx = right_idx + n_todrop % 2
return left[:-left_idx], right[right_idx:] |
<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(self, kind, key, *values):
"""Add processor functions. Any previous list of processors for `kind` and `key` will be overwritten. Parameters kind : {"pre", "post"} key : str A registered key. Add the functions (in order) to this key's list of processors. *values : callables Processors to add. """ |
if kind == "pre":
procs = self.pre
elif kind == "post":
procs = self.post
else:
raise ValueError("kind is not 'pre' or 'post'")
self._check_if_registered(key)
procs[key] = values |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _format(self, _, result):
"""Wrap format call as a two-argument processor function. """ |
return self._fmt.format(six.text_type(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 transform(function):
"""Return a processor for a style's "transform" function. """ |
def transform_fn(_, result):
if isinstance(result, Nothing):
return result
lgr.debug("Transforming %r with %r", result, function)
try:
return function(result)
except:
exctype, value, tb = sys.exc_info()
try:
new_exc = StyleFunctionError(function, exctype, value)
# Remove the "During handling ..." since we're
# reraising with the traceback.
new_exc.__cause__ = None
six.reraise(StyleFunctionError, new_exc, tb)
finally:
# Remove circular reference.
# https://docs.python.org/2/library/sys.html#sys.exc_info
del tb
return transform_fn |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def by_key(self, style_key, style_value):
"""Return a processor for a "simple" style value. Parameters style_key : str A style key. style_value : bool or str A "simple" style value that is either a style attribute (str) and a boolean flag indicating to use the style attribute named by `style_key`. Returns ------- A function. """ |
if self.style_types[style_key] is bool:
style_attr = style_key
else:
style_attr = style_value
def proc(_, result):
return self.render(style_attr, result)
return proc |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.