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 remove(self): ''' a method to remove collection and all records in the collection :return: string with confirmation of deletion ''' title = '%s.remove' % self.__class__.__name__ # request bucket delete self.s3.delete_bucket(self.bucket_na...
<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_uris(self, base_uri, filter_list=None): """Return a set of internal URIs."""
return { re.sub(r'^/', base_uri, link.attrib['href']) for link in self.parsedpage.get_nodes_by_selector('a') if 'href' in link.attrib and ( link.attrib['href'].startswith(base_uri) or link.attrib['href'].startswith('/') ) and ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def TP0(dv, u): '''Demo problem 0 for horsetail matching, takes two input vectors of any size and returns a single output''' return np.linalg.norm(np.array(dv)) + np.linalg.norm(np.array(u))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def TP1(x, u, jac=False): '''Demo problem 1 for horsetail matching, takes two input vectors of size 2 and returns just the qoi if jac is False or the qoi and its gradient if jac is True''' factor = 0.1*(u[0]**2 + 2*u[0]*u[1] + u[1]**2) q = 0 + factor*(x[0]**2 + 2*x[1]*x[0] + x[1]**2) if not jac:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def TP2(dv, u, jac=False): '''Demo problem 2 for horsetail matching, takes two input vectors of size 2 and returns just the qoi if jac is False or the qoi and its gradient if jac is True''' y = dv[0]/2. z = dv[1]/2. + 12 q = 0.25*((y**2 + z**2)/10 + 5*u[0]*u[1] - z*u[1]**2) + 0.2*z*u[1]**3 + 7 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def TP3(x, u, jac=False): '''Demo problem 1 for horsetail matching, takes two input values of size 1''' q = 2 + 0.5*x + 1.5*(1-x)*u if not jac: return q else: grad = 0.5 -1.5*u return q, grad
<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, key, bucket): """ Get a cached item by key If the cached item isn't found the return None. """
try: return self._cache[bucket][key] except (KeyError, TypeError): 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 set(self, key, val, bucket): """ Set a cached item by key WARN: Regardless if the item is already in the cache, it will be udpated with the new value. """
if bucket not in self._cache: self._cache[bucket] = {} self._cache[bucket][key] = val
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(self, project_name, template_name, substitutions): """ Launch the project creation. """
self.project_name = project_name self.template_name = template_name # create substitutions dictionary from user arguments # TODO: check what is given for subs in substitutions: current_sub = subs.split(',') current_key = current_sub[0].strip() ...
<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_directories(self): """ Create the directories of the template. """
# get the directories from the template directories = [] try: directories = self.directories() except AttributeError: self.term.print_info(u"No directory in the template.") working_dir = os.getcwd() # iteratively create the directories f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_files(self): """ Create the files of the template. """
# get the files from the template files = [] try: files = self.files() except AttributeError: self.term.print_info(u"No file in the template. Weird, but why not?") # get the substitutes intersecting the template and the cli try: for ...
<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_posthook(self): """ Run the post hook into the project directory. """
print(id(self.posthook), self.posthook) print(id(super(self.__class__, self).posthook), super(self.__class__, self).posthook) import ipdb;ipdb.set_trace() if self.posthook: os.chdir(self.project_name) # enter the project main directory self.posthook()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def replace_in_file(self, file_path, old_exp, new_exp): """ In the given file, replace all 'old_exp' by 'new_exp'. """
self.term.print_info(u"Making replacement into {}" .format(self.term.text_in_color(file_path, TERM_GREEN))) # write the new version into a temporary file tmp_file = tempfile.NamedTemporaryFile(mode...
<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, si): '''puts `si` into the currently open chunk, which it creates if necessary. If this item causes the chunk to cross chunk_max, then the chunk closed after adding. ''' if self.o_chunk is None: if os.path.exists(self.t_path): os.remove...
<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_if(pred, iterable, default=None): """ Returns a reference to the first element in the ``iterable`` range for which ``pred`` returns ``True``. If no such...
return next((i for i in iterable if pred(i)), 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 visit_root(self, _, children): """The main node holding all the query. Arguments --------- _ (node) : parsimonious.nodes.Node. children : list - 0: for ``WS`...
resource = children[1] resource.is_root = True return resource
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit_named_resource(self, _, children): """A resource in the query with its optional name. Arguments --------- _ (node) : parsimonious.nodes.Node. children ...
name, resource = children if name: resource.name = name return resource
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit_field(self, _, children): """A simple field. Arguments --------- _ (node) : parsimonious.nodes.Node. children : list - 0: for ``FILTERS``: list of inst...
filters = children[0] return self.Field(getattr(filters[0], 'name', None), filters=filters)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit_named_object(self, _, children): """Manage an object, represented by a ``.resources.Object`` instance. This object is populated with data from the resu...
filters, resource = children resource.name = filters[0].name resource.filters = filters return resource
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def visit_named_list(self, _, children): """Manage a list, represented by a ``.resources.List`` instance. This list is populated with data from the result of the...
filters, resource = children resource.name = filters[0].name resource.filters = filters return resource
<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_constants(): """Load physical constants to simulate the earth-sun system"""
# The universal gravitational constant # https://en.wikipedia.org/wiki/Gravitational_constant G: float = 6.67408E-11 # The names of the celestial bodies body_name = \ ['sun', 'moon', 'mercury', 'venus', 'earth', 'mars', 'jupite...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def julian_day(t: date) -> int: """Convert a Python datetime to a Julian day"""
# Compute the number of days from January 1, 2000 to date t dt = t - julian_base_date # Add the julian base number to the number of days from the julian base date to date t return julian_base_number + dt.days
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_mse(q1, q2): """Compare the results of two simulations"""
# Difference in positions between two simulations dq = q2 - q1 # Mean squared error in AUs return np.sqrt(np.mean(dq*dq))/au2m
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flux_v2(v_vars: List[fl.Var], i: int): """Make Fluxion with the speed squared of body i"""
# Index with the base of (v_x, v_y, v_z) for body i k = 3*i # The speed squared of body i return fl.square(v_vars[k+0]) + fl.square(v_vars[k+1]) + fl.square(v_vars[k+2])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def U_ij(q_vars: List[fl.Var], mass: np.ndarray, i: int, j: int): """Make Fluxion with the gratiational potential energy beween body i and j"""
# Check that the lengths are consistent assert len(q_vars) == 3 * len(mass) # Masses of the bodies i and j mi = mass[i] mj = mass[j] # Gravitational potential is -G * m1 * m2 / r U = -(G * mi * mj) / flux_r(q_vars, i, j) return U
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def T_i(v_vars: List[fl.Var], mass: np.ndarray, i: int): """Make Fluxion with the kinetic energy of body i"""
# Check that the lengths are consistent assert len(v_vars) == 3 * len(mass) # Mass of the body i m = mass[i] # kineteic energy = 1/2 * mass * speed^2 T = (0.5 * m) * flux_v2(v_vars, i) return T
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def plot_energy(time, H, T, U): """Plot kinetic and potential energy of system over time"""
# Normalize energy to initial KE T0 = T[0] H = H / T0 T = T / T0 U = U / T0 # Plot fig, ax = plt.subplots(figsize=[16,8]) ax.set_title('System Energy vs. Time') ax.set_xlabel('Time in Days') ax.set_ylabel('Energy (Ratio Initial KE)') ax.plot(time, T, label='T', color='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 sort_seq_records(self, seq_records): """Checks that SeqExpandedRecords are sorted by gene_code and then by voucher code. The dashes in taxon names need to be...
for seq_record in seq_records: seq_record.voucher_code = seq_record.voucher_code.replace("-", "_") unsorted_gene_codes = set([i.gene_code for i in seq_records]) sorted_gene_codes = list(unsorted_gene_codes) sorted_gene_codes.sort(key=lambda x: x.lower()) unsorted_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 _validate_outgroup(self, outgroup): """All voucher codes in our datasets have dashes converted to underscores."""
if outgroup: outgroup = outgroup.replace("-", "_") good_outgroup = False for seq_record in self.seq_records: if seq_record.voucher_code == outgroup: good_outgroup = True break if good_outgroup: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _prepare_data(self): """ Creates named tuple with info needed to create a dataset. :return: named tuple """
self._extract_genes() self._extract_total_number_of_chars() self._extract_number_of_taxa() self._extract_reading_frames() Data = namedtuple('Data', ['gene_codes', 'number_taxa', 'number_chars', 'seq_records', 'gene_codes_and_lengths', ...
<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_total_number_of_chars(self): """ sets `self.number_chars` to the number of characters as string. """
self._get_gene_codes_and_seq_lengths() sum = 0 for seq_length in self._gene_codes_and_lengths.values(): sum += sorted(seq_length, reverse=True)[0] self.number_chars = str(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 _extract_number_of_taxa(self): """ sets `self.number_taxa` to the number of taxa as string """
n_taxa = dict() for i in self.seq_records: if i.gene_code not in n_taxa: n_taxa[i.gene_code] = 0 n_taxa[i.gene_code] += 1 number_taxa = sorted([i for i in n_taxa.values()], reverse=True)[0] self.number_taxa = str(number_taxa)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cli(self): """Read program parameters from command line and configuration files We support both command line arguments and configuration files. The command l...
# first we parse only for a configuration file with an initial parser init_parser = argparse.ArgumentParser( description = __doc__, formatter_class = argparse.RawDescriptionHelpFormatter, add_help = False) # we don't use a file metavar because we...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def detect_config(self): """check in the current working directory for configuration files"""
default_files = ("config.json", "config.yml") for file_ in default_files: if os.path.exists(file_): return file_
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge_with_default_options(self, config_opts): """merge options from configuration file with the default options"""
return dict(list(self.defaults.items()) + list(config_opts.items()))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authorize(): """Authorize to twitter. Use PIN authentification. :returns: Token for authentificate with Twitter. :rtype: :class:`autotweet.twitter.OAuthToken...
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) url = auth.get_authorization_url() print('Open this url on your webbrowser: {0}'.format(url)) webbrowser.open(url) pin = input('Input verification number here: ').strip() token_key, token_secret = auth.get_access_token(verifier=pin) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def expand_url(status): """Expand url on statuses. :param status: A tweepy status to expand urls. :type status: :class:`tweepy.models.Status` :returns: A string ...
try: txt = get_full_text(status) for url in status.entities['urls']: txt = txt.replace(url['url'], url['expanded_url']) except: # Manually replace txt = status tco_pattern = re.compile(r'https://t.co/\S+') urls = tco_pattern.findall(txt) for ...
<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_tweet(text, remove_url=True): """Strip tweet message. This method removes mentions strings and urls(optional). :param text: tweet message :type text: :...
if remove_url: text = url_pattern.sub('', text) else: text = expand_url(text) text = mention_pattern.sub('', text) text = html_parser.unescape(text) text = text.strip() return text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(fname): """Quick way to read a file content."""
content = None with open(os.path.join(here, fname)) as f: content = f.read() return 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 download(self): """ Download the archive from the IRS website. """
url = 'http://forms.irs.gov/app/pod/dataDownload/fullData' r = requests.get(url, stream=True) with open(self.zip_path, 'wb') as f: # This is a big file, so we download in chunks for chunk in r.iter_content(chunk_size=30720): logger.debug('Downloading...')...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unzip(self): """ Unzip the archive. """
logger.info('Unzipping archive') with zipfile.ZipFile(self.zip_path, 'r') as zipped_archive: data_file = zipped_archive.namelist()[0] zipped_archive.extract(data_file, self.extract_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 clean(self): """ Get the .txt file from within the many-layered directory structure, then delete the directories. """
logger.info('Cleaning up archive') shutil.move( os.path.join( self.data_dir, 'var/IRS/data/scripts/pofd/download/FullDataFile.txt' ), self.final_path ) shutil.rmtree(os.path.join(self.data_dir, 'var')) os.remov...
<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_parse_and_errorlist(self): """Get the parselist and human-readable version, errorlist is returned, because it is used in error messages. """
d = self.__class__.__dict__ parselist = d.get('parselist') errorlist = d.get('errorlist') if parselist and not errorlist: errorlist = [] for t in parselist: if t[1] not in errorlist: errorlist.append(t[1]) errorlist = ' or '.join(error...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def text_to_data(self, text, elt, ps): '''convert text into typecode specific data. Encode all strings as UTF-8, which will be type 'str' not 'unicode' ''' if self.strip: text = text.strip() if self.pyclass is not None: return self.pyclass(text.encode(UNICODE_...
<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_prefix(self, elt, pyobj): '''use this method to set the prefix of the QName, method looks in DOM to find prefix or set new prefix. This method must be called before get_formatted_content. ''' if isinstance(pyobj, tuple): namespaceURI,localName = pyobj ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def parse(self, elt, ps, **kw): '''attempt to parse sequentially. No way to know ahead of time what this instance represents. Must be simple type so it can not have attributes nor children, so this isn't too bad. ''' self.setMemberTypeCodes() (nsuri,typeName) = self.che...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def text_to_data(self, text, elt, ps): '''convert text into typecode specific data. items in list are space separated. ''' v = [] items = text.split() for item in items: v.append(self.itemTypeCode.text_to_data(item, elt, ps)) if self.pyclass is not 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 consumer(site, uri): """Consume URI using site config."""
config = load_site_config(site) model = _get_model('consume', config, uri) consumestore = get_consumestore( model=model, method=_config.get('storage', 'file'), bucket=_config.get('s3_data_bucket', None) ) consumestore.save_media() consumestore.save_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 crawler(site, uri=None): """Crawl URI using site config."""
config = load_site_config(site) model = _get_model('crawl', config, uri) visited_set, visited_uri_set, consume_set, crawl_set = get_site_sets( site, config ) if not visited_set.has(model.hash): visited_set.add(model.hash) visited_uri_set.add(model.uri) if ( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def killer(site): """Kill queues and Redis sets."""
config = load_site_config(site) crawl_q.empty() consume_q.empty() for site_set in get_site_sets(site, config): site_set.destroy()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def GetAuth(self): '''Return a tuple containing client authentication data. ''' if self.auth: return self.auth for elt in self.ps.GetMyHeaderElements(): if elt.localName == 'BasicAuth' \ and elt.namespaceURI == ZSI_SCHEMA_URI: d = _auth_tc.parse(el...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def permission_required_with_403(perm, login_url=None): """ Decorator for views that checks whether a user has a particular permission enabled, redirecting to th...
return user_passes_test_with_403(lambda u: u.has_perm(perm), login_url=login_url)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_to_rgb(img): """ Convert an image to RGB if it isn't already RGB or grayscale """
if img.mode == 'CMYK' and HAS_PROFILE_TO_PROFILE: profile_dir = os.path.join(os.path.dirname(__file__), 'profiles') input_profile = os.path.join(profile_dir, "USWebUncoated.icc") output_profile = os.path.join(profile_dir, "sRGB_v4_ICC_preference.icc") return profileToProfile(img, 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 optimize(image, fmt='jpeg', quality=80): """ Optimize the image if the IMAGE_OPTIMIZATION_CMD is set. IMAGE_OPTIMIZATION_CMD must accept piped input """
from io import BytesIO if IMAGE_OPTIMIZATION_CMD and is_tool(IMAGE_OPTIMIZATION_CMD): image_buffer = BytesIO() image.save(image_buffer, format=fmt, quality=quality) image_buffer.seek(0) # If you don't reset the file pointer, the read command returns an empty string p1 = subpro...
<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(filename, default=None): ''' Try to load @filename. If there is no loader for @filename's filetype, return @default. ''' ext = get_ext(filename) if ext in ldict: return ldict[ext](filename) 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 report(self, msg, do_reset=False, file=sys.stdout): """Print to stdout msg followed by the runtime. When true, do_reset will result in a reset of start time....
print >> file, "%s (%s s)" % (msg, time.time() - self.start) if do_reset: self.start = 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 result(self, msg, do_reset=False): """Return log message containing ellapsed time as a string. When true, do_reset will result in a reset of start time. """
result = "%s (%s s)" % (msg, time.time() - self.start) if do_reset: self.start = time.time() 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 runtime(self): """Return ellapsed time and reset start. """
t = time.time() - self.start self.start = time.time() return t
<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_one(self, aws_syncr, amazon, gateway): """Make sure this gateway exists and has only attributes we want it to have"""
gateway_info = amazon.apigateway.gateway_info(gateway.name, gateway.location) if not gateway_info: amazon.apigateway.create_gateway(gateway.name, gateway.location, gateway.stages, gateway.resources, gateway.api_keys, gateway.domain_names) else: amazon.apigateway.modify_g...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def includeme(configurator): """ Add yaml configuration utilities. :param pyramid.config.Configurator configurator: pyramid's app configurator """
settings = configurator.registry.settings # lets default it to running path yaml_locations = settings.get('yaml.location', settings.get('yml.location', os.getcwd())) configurator.add_directive('config_defaults', config_defaults) configurator.config_defaults(yaml...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _translate_config_path(location): """ Translate location into fullpath according asset specification. Might be package:path for package related paths, or sim...
# getting spec path package_name, filename = resolve_asset_spec(location.strip()) if not package_name: path = filename else: package = __import__(package_name) path = os.path.join(package_path(package), filename) return 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 _env_filenames(filenames, env): """ Extend filenames with ennv indication of environments. :param list filenames: list of strings indicating filenames :param...
env_filenames = [] for filename in filenames: filename_parts = filename.split('.') filename_parts.insert(1, env) env_filenames.extend([filename, '.'.join(filename_parts)]) return env_filenames
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _extend_settings(settings, configurator_config, prefix=None): """ Extend settings dictionary with content of yaml's configurator key. .. note:: This methods ...
for key in configurator_config: settings_key = '.'.join([prefix, key]) if prefix else key if hasattr(configurator_config[key], 'keys') and\ hasattr(configurator_config[key], '__getitem__'): _extend_settings( settings, configurator_config[key], prefix=set...
<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(uri): """Return an instance of Page."""
global _instances try: instance = _instances[uri] except KeyError: instance = Page( uri, client.get_instance() ) _instances[uri] = instance return instance
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fetch(self): """Fetch Page.content from client."""
self.content = self.client.get_content( uri=self.uri ) self.hash = hashlib.sha256( self.content ).hexdigest()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def load_objects(self, dirs=[], callwith={}): ''' Call this to load resources from each dir in @dirs. Code resources will receive @callwith as an argument. ''' for d in dirs: contents = ls(d) for t in contents: first = join(d, t) ...
<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_music(self, plylst, force=False): ''' Use to set the playlist to @plylst. If @force is False, the playlist will not be set if it is @plylst already. ''' plylst = plylst.lower() if plylst != self.cur_playlist or force: self.cur_playlist = plylst ...
<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_m_vol(self, vol=None, relative=False): ''' Set the music volume. If @vol != None, It will be changed to it (or by it, if @relative is True.) ''' if vol != None: if relative: vol += self.m_vol self.m_vol = min(max(vol, 0), 1) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def set_s_vol(self, vol=None, relative=False): ''' Set the volume of all sounds. If @vol != None, It will be changed to it (or by it, if @relative is True.) ''' if vol != None: if relative: vol += self.s_vol self.s_vol = min(max(vol, 0), 1...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_channel(self): ''' Used internally when playing sounds. ''' c = pygame.mixer.find_channel(not self.dynamic) while c is None: self.channels += 1 pygame.mixer.set_num_channels(self.channels) c = pygame.mixer.find_channel() 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 event(self, utype, **kw): ''' Make a meta-event with a utype of @type. **@kw works the same as for pygame.event.Event(). ''' d = {'utype': utype} d.update(kw) pygame.event.post(pygame.event.Event(METAEVENT, d))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def loop(self, events=[]): ''' Run the loop. ''' try: for e in events: if e.type == METAEVENT: e = self.MetaEvent(e) for func in self.event_funcs.get(e.type, []): func(self, self.gstate, e) except...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def accumulate(a_generator, cooperator=None): """ Start a Deferred whose callBack arg is a deque of the accumulation of the values yielded from a_generator. :par...
if cooperator: own_cooperate = cooperator.cooperate else: own_cooperate = cooperate spigot = ValueBucket() items = stream_tap((spigot,), a_generator) d = own_cooperate(items).whenDone() d.addCallback(accumulation_handler, spigot) return d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def batch_accumulate(max_batch_size, a_generator, cooperator=None): """ Start a Deferred whose callBack arg is a deque of the accumulation of the values yielded ...
if cooperator: own_cooperate = cooperator.cooperate else: own_cooperate = cooperate spigot = ValueBucket() items = stream_tap((spigot,), a_generator) d = own_cooperate(i_batch(max_batch_size, items)).whenDone() d.addCallback(accumulation_handler, spigot) return d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_connection(): """Return a redis.Redis instance connected to REDIS_URL."""
# REDIS_URL is defined in .env and loaded into the environment by Honcho redis_url = os.getenv('REDIS_URL') # If it's not defined, use the Redis default if not redis_url: redis_url = 'redis://localhost:6379' urlparse.uses_netloc.append('redis') url = urlparse.urlparse(redis_url) 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 work(): """Start an rq worker on the connection provided by create_connection."""
with rq.Connection(create_connection()): worker = rq.Worker(list(map(rq.Queue, listen))) worker.work()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _gen_shuffles(self): ''' Used internally to build a list for mapping between a random number and a song index. ''' # The current metasong index si = 0 # The shuffle mapper list self.shuffles = [] # Go through all our songs... for song...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def _new_song(self): ''' Used internally to get a metasong index. ''' # We'll need this later s = self.song if self.shuffle: # If shuffle is on, we need to (1) get a random song that # (2) accounts for weighting. This line does both. ...
<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_selectable(self): ''' Used internally to get a group of choosable tracks. ''' # Save some typing cursong = self.loop[self.song][0] if self.dif_song and len(cursong) > 1: # Position is relative to the intro of the track, # so we we...
<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_song(self): ''' Used internally to get the current track and make sure it exists. ''' # Try to get the current track from the start metasong if self.at_beginning: # Make sure it exists. if self.pos < len(self.start): # It exists, 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 begin(self): ''' Start over and get a track. ''' # Check for a start metasong if self.start: # We are in the beginning song self.at_beginning = True # And on the first track. self.pos = 0 else: # We aren't 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 _applicationStart(self, data): """ Initializes the database connection pool. :param data: <object> event data object :return: <void> """
checkup = False if "viper.mysql" in self.application.config \ and isinstance(self.application.config["viper.mysql"], dict): if "host" in self.application.config["viper.mysql"] and \ "port" in self.application.config["viper.mysql"] and \ ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _checkIfDatabaseIsEmpty(self, successHandler=None, failHandler=None): """ Check if database contains any tables. :param successHandler: <function(<bool>)> me...
def failCallback(error): errorMessage = str(error) if isinstance(error, Failure): errorMessage = error.getErrorMessage() if failHandler is not None: reactor.callInThread(failHandler, errorMessage) def selectCallback(transaction, succ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _initDatabase(self): """ Initializes the database structure based on application configuration. :return: <void> """
queries = [] if len(self.application.config["viper.mysql"]["init"]["scripts"]) > 0: for scriptFilePath in self.application.config["viper.mysql"]["init"]["scripts"]: sqlFile = open(scriptFilePath, "r") queriesInFile = self.extractFromSQLFile(sqlFile) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extractFromSQLFile(self, filePointer, delimiter=";"): """ Process an SQL file and extract all the queries sorted. :param filePointer: <io.TextIOWrapper> file...
data = filePointer.read() # reading file and splitting it into lines dataLines = [] dataLinesIndex = 0 for c in data: if len(dataLines) - 1 < dataLinesIndex: dataLines.append("") if c == "\r\n" or c == "\r" or c == "\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 runInteraction(self, interaction, *args, **kwargs): """ Interact with the database and return the result. :param interaction: <function> method with first ar...
try: return self._connectionPool.runInteraction( interaction, *args, **kwargs ) except: d = defer.Deferred() d.errback() return d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def runQuery(self, *args, **kwargs): """ Execute an SQL query and return the result. :param args: additional positional arguments to be passed to cursor execute ...
try: return self._connectionPool.runQuery(*args, **kwargs) except: d = defer.Deferred() d.errback() return d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def solve(self, value, resource): """Solve a resource with a value. Arguments --------- value : ? A value to solve in combination with the given resource. The fi...
result = self.solve_value(value, resource) return self.coerce(result, resource)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def solve_value(self, value, resource): """Solve a resource with a value, without coercing. Arguments --------- value : ? A value to solve in combination with th...
# The given value is the starting point on which we apply the first filter. result = value # Apply filters one by one on the previous result. if result is not None: for filter_ in resource.filters: result = self.registry.solve_filter(result, filter_) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def can_solve(cls, resource): """Tells if the solver is able to resolve the given resource. Arguments --------- resource : subclass of ``dataql.resources.Resourc...
for solvable_resource in cls.solvable_resources: if isinstance(resource, solvable_resource): 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 coerce(self, value, resource): """Coerce the value to an acceptable one. Only these kinds of values are returned as is: - str - int - float - True - False - ...
if value in (True, False, None): return value if isinstance(value, (int, float)): return value if isinstance(value, str): return value return self.coerce_default(value, resource)
<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(self, value, resource): """Get a dict with attributes from ``value``. Arguments --------- value : ? The value to get some resources from. resource : d...
return {r.name: self.registry.solve_resource(value, r) for r in resource.resources}
<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(self, value, resource): """Convert a list of objects in a list of dicts. Arguments --------- value : iterable The list (or other iterable) to get valu...
if not isinstance(value, Iterable): raise NotIterable(resource, self.registry[value]) # Case #1: we only have one sub-resource, so we return a list with this item for # each iteration if len(resource.resources) == 1: res = resource.resources[0] retu...
<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_recordings_dictionary(list_selected, pronunciation_dictionary_filename, out_dictionary_filename, htk_trace, additional_dictionary_filenames=[]): """Cr...
temp_words_fd, temp_words_file = tempfile.mkstemp() words = set() for recording in list_selected: words |= set([w.upper() for w in get_words_from_recording(recording)]) with codecs.open(temp_words_file, 'w', 'utf-8') as f: f.writelines([u'{}\n'.format(w) for w in sorted(list(words))])...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def utf8_normalize(input_filename, comment_char='#', to_upper=False): """Normalize UTF-8 characters of a file """
# Prepare the input dictionary file in UTF-8 and NFC temp_dict_fd, output_filename = tempfile.mkstemp() logging.debug('to_nfc from file {} to file {}'.format(input_filename, output_filename)) with codecs.open(output_filename, 'w', 'utf-8') as f: with codecs.open(input_filename, 'r', 'utf-8') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_flat_start_model(feature_filename, state_stay_probabilities, symbol_list, output_model_directory, output_prototype_filename, htk_trace): """ Creates a...
# Create a prototype model create_prototype_model(feature_filename, output_prototype_filename, state_stay_probabilities=state_stay_probabilities) # Compute the global mean and variance config.htk_command("HCompV -A -D -T {} -f 0.01 " ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def recognise_model(feature_filename, symbollist_filename, model_directory, recognition_filename, pronunciation_dictionary_filename, list_words_filename='', cmllr...
# Normalize UTF-8 to avoid Mac problems temp_dictionary_filename = utf8_normalize(pronunciation_dictionary_filename) # Create language word list if list_words_filename: list_words = parse_wordlist(list_words_filename) else: list_words = sorted(parse_dictionary(temp_dictionary_filen...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect(self): """ Construct the psycopg2 connection instance :return: psycopg2.connect instance """
if self._conn: return self._conn self._conn = psycopg2.connect( self.config, cursor_factory=psycopg2.extras.RealDictCursor, ) self._conn.set_session(autocommit=True) psycopg2.extras.register_hstore(self._conn) return self._conn
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pager(parser, token): """ Output pagination links. """
try: tag_name, page_obj = token.split_contents() except ValueError: raise template.TemplateSyntaxError('pager tag requires 1 argument (page_obj), %s given' % (len(token.split_contents()) - 1)) return PagerNode(page_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 view_modifier(parser, token): """ Output view modifier. """
try: tag_name, view_modifier = token.split_contents() except ValueError: raise template.TemplateSyntaxError('view_modifier tag requires 1 argument (view_modifier), %s given' % (len(token.split_contents()) - 1)) return ViewModifierNode(view_modifier)