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 render_homepage(config, env): """Render the homepage.jinja template."""
template = env.get_template('homepage.jinja') rendered_page = template.render( config=config) return rendered_page
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def d_cal(calibcurve, rcmean, w2, cutoff=0.0001, normal_distr=False, t_a=3, t_b=4): """Get calendar date probabilities Parameters calibcurve : CalibCurve Calibra...
assert t_b - 1 == t_a if normal_distr: # TODO(brews): Test this. Line 946 of Bacon.R. std = np.sqrt(calibcurve.error ** 2 + w2) dens = stats.norm(loc=rcmean, scale=std).pdf(calibcurve.c14age) else: # TODO(brews): Test this. Line 947 of Bacon.R. dens = (t_b + ((rcmean...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calibrate_dates(chron, calib_curve, d_r, d_std, cutoff=0.0001, normal_distr=False, t_a=[3], t_b=[4]): """Get density of calendar dates for chron date segment...
# Python version of .bacon.calib() on line 908 in Bacon.R # .bacon.calib - line 908 # rcmean = 4128; w2 = 4225; t_a=3; t_b=4 # test = d_cal(cc = calib_curve.rename(columns = {0:'a', 1:'b', 2:'c'}), rcmean = 4128, w2 = 4225, t_a=t_a, # t_b=t_b, cutoff=cutoff, normal = normal) # Line 959 of Ba...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _init_browser(self): """Overide in appropriate way to prepare a logged in browser."""
self.browser = splinter.Browser('phantomjs') self.browser.visit(self.server_url + "/youraccount/login") try: self.browser.fill('nickname', self.user) self.browser.fill('password', self.password) except: self.browser.fill('p_un', self.user) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upload_marcxml(self, marcxml, mode): """Upload a record to the server. :param marcxml: the XML to upload. :param mode: the mode to use for the upload. - "-i"...
if mode not in ["-i", "-r", "-c", "-a", "-ir"]: raise NameError("Incorrect mode " + str(mode)) return requests.post(self.server_url + "/batchuploader/robotupload", data={'file': marcxml, 'mode': mode}, headers={'User-Agent': CFG_USE...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def url(self): """ Returns the URL to this record. Returns None if not known """
if self.server_url is not None and \ self.recid is not None: return '/'.join( [self.server_url, CFG_SITE_RECORD, str(self.recid)]) else: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clean_list_of_twitter_list(list_of_twitter_lists, sent_tokenize, _treebank_word_tokenize, tagger, lemmatizer, lemmatize, stopset, first_cap_re, all_cap_re, di...
list_of_keyword_sets = list() append_keyword_set = list_of_keyword_sets.append list_of_lemma_to_keywordbags = list() append_lemma_to_keywordbag = list_of_lemma_to_keywordbags.append if list_of_twitter_lists is not None: for twitter_list in list_of_twitter_lists: if twitter_lis...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def user_twitter_list_bag_of_words(twitter_list_corpus, sent_tokenize, _treebank_word_tokenize, tagger, lemmatizer, lemmatize, stopset, first_cap_re, all_cap_re, ...
# Extract a bag-of-words from a list of Twitter lists. # May result in empty sets list_of_keyword_sets, list_of_lemma_to_keywordbags = clean_list_of_twitter_list(twitter_list_corpus, sent_tokenize, _treebank_word_tokenize, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def grouper(iterable, n, pad_value=None): """ Returns a generator of n-length chunks of an input iterable, with appropriate padding at the end. Example: grouper(...
chunk_gen = (chunk for chunk in zip_longest(*[iter(iterable)]*n, fillvalue=pad_value)) return chunk_gen
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def chunks(iterable, n): """ A python generator that yields 100-length sub-list chunks. Input: - full_list: The input list that is to be separated in chunks of 1...
for i in np.arange(0, len(iterable), n): yield iterable[i:i+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 split_every(iterable, n): # TODO: Remove this, or make it return a generator. """ A generator of n-length chunks of an input iterable """
i = iter(iterable) piece = list(islice(i, n)) while piece: yield piece piece = list(islice(i, 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 merge_properties(item_properties, prop_name, merge_value): """ Tries to figure out which type of property value that should be merged and invoke the right fu...
existing_value = item_properties.get(prop_name, None) if not existing_value: # A node without existing values for the property item_properties[prop_name] = merge_value else: if type(merge_value) is int or type(merge_value) is str: item_properties[prop_name] = existing_value + 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 generate_id(self, element): """ Generate a id for a element. :param element: The element. :type element: hatemile.util.html.HTMLDOMElement """
if not element.has_attribute('id'): element.set_attribute('id', self.prefix_id + str(self.count)) self.count = self.count + 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 fetch_state_data(self, states): """ Fetch census estimates from table. """
print("Fetching census data") for table in CensusTable.objects.all(): api = self.get_series(table.series) for variable in table.variables.all(): estimate = "{}_{}".format(table.code, variable.code) print( ">> Fetching {} {} {}"...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has(self, name): """ Returns True if there is atleast one annotation by a given name, otherwise False. """
for a in self.all_annotations: if a.name == name: 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 get_first(self, name): """ Get the first annotation by a given name. """
for a in self.all_annotations: if a.name == name: return a return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_all(self, name): """ Get all the annotation by a given name. """
return [annot for annot in self.all_annotations if annot.name == name]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def first_value_of(self, name, default_value = None): """ Return the first value of a particular param by name if it exists otherwise false. """
vals = self.values_of(name) if vals is not None: return vals if type(vals) is not list else vals[0] return default_value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_long_description(): """ Returns the long description of HaTeMiLe for Python. :return: The long description of HaTeMiLe for Python. :rtype: str """
with open( os.path.join(BASE_DIRECTORY, 'README.md'), 'r', encoding='utf-8' ) as readme_file: return readme_file.read()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_packages(): """ Returns the packages used for HaTeMiLe for Python. :return: The packages used for HaTeMiLe for Python. :rtype: list(str) """
packages = find_packages(exclude=['tests']) packages.append('') packages.append('js') packages.append(LOCALES_DIRECTORY) for directory in os.listdir(LOCALES_DIRECTORY): packages.append(LOCALES_DIRECTORY + '.' + directory) return packages
<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_package_data(): """ Returns the packages with static files of HaTeMiLe for Python. :return: The packages with static files of HaTeMiLe for Python. :rtype...
package_data = { '': ['*.xml'], 'js': ['*.js'], LOCALES_DIRECTORY: ['*'] } for directory in os.listdir(LOCALES_DIRECTORY): package_data[LOCALES_DIRECTORY + '.' + directory] = ['*.json'] return package_data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_requirements(): """ Returns the content of 'requirements.txt' in a list. :return: The content of 'requirements.txt'. :rtype: list(str) """
requirements = [] with open( os.path.join(BASE_DIRECTORY, 'requirements.txt'), 'r', encoding='utf-8' ) as requirements_file: lines = requirements_file.readlines() for line in lines: requirements.append(line.strip()) return requirements
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def where_session_id(cls, session_id): """ Easy way to query by session id """
try: session = cls.query.filter_by(session_id=session_id).one() return session except (NoResultFound, MultipleResultsFound): 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 count(cls, user_id): """ Count sessions with user_id """
return cls.query.with_entities( cls.user_id).filter_by(user_id=user_id).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 get_branch(): """ Returns the current code branch """
if os.getenv('GIT_BRANCH'): # Travis branch = os.getenv('GIT_BRANCH') elif os.getenv('BRANCH_NAME'): # Jenkins 2 branch = os.getenv('BRANCH_NAME') else: branch = check_output( "git rev-parse --abbrev-ref HEAD".split(" "...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_version(): """ Returns the current code version """
try: return check_output( "git describe --tags".split(" ") ).decode('utf-8').strip() except CalledProcessError: return check_output( "git rev-parse --short HEAD".split(" ") ).decode('utf-8').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 jenkins_last_build_sha(): """ Returns the sha of the last completed jenkins build for this project. Expects JOB_URL in environment """
job_url = os.getenv('JOB_URL') job_json_url = "{0}/api/json".format(job_url) response = urllib.urlopen(job_json_url) job_data = json.loads(response.read()) last_completed_build_url = job_data['lastCompletedBuild']['url'] last_complete_build_json_url = "{0}/api/json".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 get_changed_files_from(old_commit_sha, new_commit_sha): """ Returns a list of the files changed between two commits """
return check_output( "git diff-tree --no-commit-id --name-only -r {0}..{1}".format( old_commit_sha, new_commit_sha ).split(" ") ).decode('utf-8').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 extract_snow_tweets_from_file_generator(json_file_path): """ A generator that opens a file containing many json tweets and yields all the tweets contained in...
with open(json_file_path, "r", encoding="utf-8") as fp: for file_line in fp: tweet = json.loads(file_line) yield tweet
<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_all_snow_tweets_from_disk_generator(json_folder_path): """ A generator that returns all SNOW tweets stored in disk. Input: - json_file_path: The path...
# Get a generator with all file paths in the folder json_file_path_generator = (json_folder_path + "/" + name for name in os.listdir(json_folder_path)) for path in json_file_path_generator: for tweet in extract_snow_tweets_from_file_generator(path): yield tweet
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def store_snow_tweets_from_disk_to_mongodb(snow_tweets_folder): """ Store all SNOW tweets in a mongodb collection. """
client = pymongo.MongoClient("localhost", 27017) db = client["snow_tweet_storage"] collection = db["tweets"] for tweet in extract_all_snow_tweets_from_disk_generator(snow_tweets_folder): collection.insert(tweet)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_file(f, full_path): """ Saves file f to full_path and set rules. """
make_dirs_for_file_path(full_path, mode=dju_settings.DJU_IMG_CHMOD_DIR) with open(full_path, 'wb') as t: f.seek(0) while True: buf = f.read(dju_settings.DJU_IMG_RW_FILE_BUFFER_SIZE) if not buf: break t.write(buf) os.chmod(full_path, dju_se...
<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_profile_configs(profile=None, use_cache=True): """ Returns upload configs for profile. """
if use_cache and profile in _profile_configs_cache: return _profile_configs_cache[profile] profile_conf = None if profile is not None: try: profile_conf = dju_settings.DJU_IMG_UPLOAD_PROFILES[profile] except KeyError: if profile != '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 generate_img_id(profile, ext=None, label=None, tmp=False): """ Generates img_id. """
if ext and not ext.startswith('.'): ext = '.' + ext if label: label = re.sub(r'[^a-z0-9_\-]', '', label, flags=re.I) label = re.sub(r'_+', '_', label) label = label[:60] return '{profile}:{tmp}{dtstr}_{rand}{label}{ext}'.format( profile=profile, tmp=(dju_sett...
<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_relative_path_from_img_id(img_id, variant_label=None, ext=None, create_dirs=False): """ Returns path to file relative MEDIA_URL. """
profile, base_name = img_id.split(':', 1) conf = get_profile_configs(profile) if not variant_label: status_suffix = dju_settings.DJU_IMG_UPLOAD_MAIN_SUFFIX else: status_suffix = dju_settings.DJU_IMG_UPLOAD_VARIANT_SUFFIX name, file_ext = os.path.splitext(base_name) prefix = '' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_img_id_exists(img_id): """ Checks if img_id has real file on filesystem. """
main_rel_path = get_relative_path_from_img_id(img_id) main_path = media_path(main_rel_path) return os.path.isfile(main_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 is_img_id_valid(img_id): """ Checks if img_id is valid. """
t = re.sub(r'[^a-z0-9_:\-\.]', '', img_id, re.IGNORECASE) t = re.sub(r'\.+', '.', t) if img_id != t or img_id.count(':') != 1: return False profile, base_name = img_id.split(':', 1) if not profile or not base_name: return False try: get_profile_configs(profile) excep...
<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_all_files_of_img_id(img_id): """ Removes all img_id's files. """
files = get_files_by_img_id(img_id, check_hash=False) if files: os.remove(media_path(files['main'])) for fn in files['variants'].values(): os.remove(media_path(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 remove_tmp_prefix_from_filename(filename): """ Remove tmp prefix from filename. """
if not filename.startswith(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX): raise RuntimeError(ERROR_MESSAGES['filename_hasnt_tmp_prefix'] % {'filename': filename}) return filename[len(dju_settings.DJU_IMG_UPLOAD_TMP_PREFIX):]
<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_tmp_prefix_from_file_path(file_path): """ Remove tmp prefix from file path or url. """
path, filename = os.path.split(file_path) return os.path.join(path, remove_tmp_prefix_from_filename(filename)).replace('\\', '/')
<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_permalink(img_id): """ Removes tmp prefix from filename and rename main and variant files. Returns img_id without tmp prefix. """
profile, filename = img_id.split(':', 1) new_img_id = profile + ':' + remove_tmp_prefix_from_filename(filename) urls = get_files_by_img_id(img_id) if urls is None: return urls move_list = {(urls['main'], remove_tmp_prefix_from_file_path(urls['main']))} for var_label, var_file_path in ur...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upload_from_fs(fn, profile=None, label=None): """ Saves image from fn with TMP prefix and returns img_id. """
if not os.path.isfile(fn): raise ValueError('File is not exists: {}'.format(fn)) if profile is None: profile = 'default' conf = get_profile_configs(profile) with open(fn, 'rb') as f: if not is_image(f, types=conf['TYPES']): msg = (('Format of uploaded file "%(name)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 upload_from_fileobject(f, profile=None, label=None): """ Saves image from f with TMP prefix and returns img_id. """
if profile is None: profile = 'default' conf = get_profile_configs(profile) f.seek(0) if not is_image(f, types=conf['TYPES']): msg = (('Format of uploaded file is not allowed. ' 'Allowed formats is: %(formats)s.') % {'formats': ', '.join(map(lambda t: t.up...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def request(self, method, url, **kwargs): """ Unified method to make request to the Github API :param method: HTTP Method to use :param url: URL to reach :param ...
if "data" in kwargs: kwargs["data"] = json.dumps(kwargs["data"]) kwargs["headers"] = { 'Content-Type': 'application/json', 'Authorization': 'token %s' % self.__token__, } req = make_request( method, url, **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 default_branch(self, file): """ Decide the name of the default branch given the file and the configuration :param file: File with informations about it :retu...
if isinstance(self.__default_branch__, str): return self.__default_branch__ elif self.__default_branch__ == GithubProxy.DEFAULT_BRANCH.NO: return self.master_upstream else: return file.sha[: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 init_app(self, app): """ Initialize the application and register the blueprint :param app: Flask Application :return: Blueprint of the current nemo app :rtyp...
self.app = app self.__blueprint__ = Blueprint( self.__name__, self.__name__, url_prefix=self.__prefix__, ) for url, name, methods in self.__urls__: self.blueprint.add_url_rule( url, view_func=getattr(self, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def put(self, file): """ Create a new file on github :param file: File to create :return: File or self.ProxyError """
input_ = { "message": file.logs, "author": file.author.dict(), "content": file.base64, "branch": file.branch } uri = "{api}/repos/{origin}/contents/{path}".format( api=self.github_api_url, origin=self.origin, pa...
<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, file): """ Check on github if a file exists :param file: File to check status of :return: File with new information, including blob, or Error :rtyp...
uri = "{api}/repos/{origin}/contents/{path}".format( api=self.github_api_url, origin=self.origin, path=file.path ) params = { "ref": file.branch } data = self.request("GET", uri, params=params) # We update the file blob bec...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, file): """ Make an update query on Github API for given file :param file: File to update, with its content :return: File with new information, i...
params = { "message": file.logs, "author": file.author.dict(), "content": file.base64, "sha": file.blob, "branch": file.branch } uri = "{api}/repos/{origin}/contents/{path}".format( api=self.github_api_url, orig...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pull_request(self, file): """ Create a pull request :param file: File to push through pull request :return: URL of the PullRequest or Proxy Error """
uri = "{api}/repos/{upstream}/pulls".format( api=self.github_api_url, upstream=self.upstream, path=file.path ) params = { "title": "[Proxy] {message}".format(message=file.logs), "body": "", "head": "{origin}:{branch}".format(orig...
<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_ref(self, branch, origin=None): """ Check if a reference exists :param branch: The branch to check if it exists :return: Sha of the branch if it exists, ...
if not origin: origin = self.origin uri = "{api}/repos/{origin}/git/refs/heads/{branch}".format( api=self.github_api_url, origin=origin, branch=branch ) data = self.request("GET", uri) if data.status_code == 200: 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 make_ref(self, branch): """ Make a branch on github :param branch: Name of the branch to create :return: Sha of the branch or self.ProxyError """
master_sha = self.get_ref(self.master_upstream) if not isinstance(master_sha, str): return self.ProxyError( 404, "The default branch from which to checkout is either not available or does not exist", step="make_ref" ) para...
<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_sha(self, sha, content): """ Check sent sha against the salted hash of the content :param sha: SHA sent through fproxy-secure-hash header :param conten...
rightful_sha = sha256(bytes("{}{}".format(content, self.secret), "utf-8")).hexdigest() return sha == rightful_sha
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def patch_ref(self, sha): """ Patch reference on the origin master branch :param sha: Sha to use for the branch :return: Status of success :rtype: str or self.Pr...
uri = "{api}/repos/{origin}/git/refs/heads/{branch}".format( api=self.github_api_url, origin=self.origin, branch=self.master_fork ) data = { "sha": sha, "force": True } reply = self.request( "PATCH", ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def r_receive(self, filename): """ Function which receives the data from Perseids - Check the branch does not exist - Make the branch if needed - Receive PUT fro...
########################################### # Retrieving data ########################################### content = request.data.decode("utf-8") # Content checking if not content: error = self.ProxyError(300, "Content is missing") return error.res...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def r_update(self): """ Updates a fork Master - Check the ref of the origin repository - Patch reference of fork repository - Return status to Perseids :return: ...
# Getting Master Branch upstream = self.get_ref(self.master_upstream, origin=self.upstream) if isinstance(upstream, bool): return (ProxyError( 404, "Upstream Master branch '{0}' does not exist".format(self.master_upstream), step="get_upstream_ref" ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_where_user_id(cls, user_id): """ delete by email """
result = cls.where_user_id(user_id) if result is None: return None result.delete() 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 int_filter(text): """Extract integer from text. **中文文档** 摘除文本内的整数。 """
res = list() for char in text: if char.isdigit(): res.append(char) return int("".join(res))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def float_filter(text): """Extract float from text. **中文文档** 摘除文本内的小数。 """
res = list() for char in text: if (char.isdigit() or (char == ".")): res.append(char) return float("".join(res))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(self, filename, offset): """Will eventually load information for Apple_Boot volume. Not yet implemented"""
try: self.offset = offset # self.fd = open(filename, 'rb') # self.fd.close() except IOError as e: print(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 resolve(accessor: hexdi.core.clstype) -> __gentype__.T: """ shortcut for resolving from root container :param accessor: accessor for resolving object :return:...
return hexdi.core.get_root_container().resolve(accessor=accessor)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bind_type(type_to_bind: hexdi.core.restype, accessor: hexdi.core.clstype, lifetime_manager: hexdi.core.ltype): """ shortcut for bind_type on root container :...
hexdi.core.get_root_container().bind_type(type_to_bind, accessor, lifetime_manager)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bind_permanent(type_to_bind: hexdi.core.restype, accessor: hexdi.core.clstype): """ shortcut for bind_type with PermanentLifeTimeManager on root container :p...
hexdi.core.get_root_container().bind_type(type_to_bind, accessor, lifetime.PermanentLifeTimeManager)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bind_transient(type_to_bind: hexdi.core.restype, accessor: hexdi.core.clstype): """ shortcut for bind_type with PerResolveLifeTimeManager on root container :...
hexdi.core.get_root_container().bind_type(type_to_bind, accessor, lifetime.PerResolveLifeTimeManager)
<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_series(self, series): """ Returns a census series API handler. """
if series == "acs1": return self.census.acs1dp elif series == "acs5": return self.census.acs5 elif series == "sf1": return self.census.sf1 elif series == "sf3": return self.census.sf3 else: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup_system_repository(self, repository_type, reset_on_start, repository_class=None): """ Sets up the system repository with the given repository type. :par...
# Set up the system entity repository (this does not join the # transaction and is in autocommit mode). cnf = dict(messaging_enable=True, messaging_reset_on_start=reset_on_start) system_repo = self.new(repository_type, name=REPOSITORY_DO...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def initialize_all(self): """ Convenience method to initialize all repositories that have not been initialized yet. """
for repo in itervalues_(self.__repositories): if not repo.is_initialized: repo.initialize()
<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 file(location, mime_type=None, headers=None, _range=None): '''Return a response object with file data. :param location: Location of file on system. :param mime_type: Specific mime_type. :param headers: Custom Headers. :param _range: ''' filename = path.split(location)[-1] asy...
<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_bundles(): """ Used to cache the bundle definitions rather than loading from config every time they're used """
global _cached_bundles if not _cached_bundles: _cached_bundles = BundleManager() for bundle_conf in bundles_settings.BUNDLES: _cached_bundles[bundle_conf[0]] = Bundle(bundle_conf) return _cached_bundles
<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_bundle_versions(): """ Used to cache the bundle versions rather than loading them from the bundle versions file every time they're used """
global _cached_versions if not bundles_settings.BUNDLES_VERSION_FILE: _cached_versions = {} if _cached_versions is None: locs = {} try: execfile(bundles_settings.BUNDLES_VERSION_FILE, locs) _cached_versions = locs['BUNDLES_VERSIONS'] except IOError: ...
<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_url(self, version=None): """ Return the filename of the bundled bundle """
if self.fixed_bundle_url: return self.fixed_bundle_url return '%s.%s.%s' % (os.path.join(self.bundle_url_root, self.bundle_filename), version or self.get_version(), self.bundle_type)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_file_urls(self): """ Return a list of file urls - will return a single item if settings.USE_BUNDLES is True """
if self.use_bundle: return [self.get_url()] return [bundle_file.file_url for bundle_file in self.files]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def export_batch(self): """Returns a batch instance after exporting a batch of txs. """
batch = self.batch_cls( model=self.model, history_model=self.history_model, using=self.using ) if batch.items: try: json_file = self.json_file_cls(batch=batch, path=self.path) json_file.write() except JSONDumpFileError as 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 _check_key(self, key): """ Ensure key is either in schema's attributes or already set on self. """
self.setup_schema() if key not in self._attrs and key not in self: raise KeyError(key)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hirise_edr(self, pid, chunk_size=1024*1024): """ Download a HiRISE EDR set of .IMG files to the CWD You must know the full id to specifiy the filter to use, ...
productid = "{}*".format(pid) query = {"target" : "mars", "query" : "product", "results" : "f", "output" : "j", "pt" : "EDR", "iid" : "HiRISE", "ihid" : "MRO", ...
<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(self, filename, offset, standalone=False): """Verifies NTFS filesystem signature. Returns: bool: True if filesystem signature at offset 0x03 \ matches...
r = RawStruct( filename=filename, offset=offset + SIG_OFFSET, length=SIG_SIZE) oem_id = r.data if oem_id == b"NTFS ": 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 load(cls, v): """Load the action from configuration"""
if v is None: return [] if isinstance(v, list): return [ Action(s) for s in v ] elif isinstance(v, str): return [Action(v)] else: raise ParseError("Couldn't parse action: %r" % 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 load_stream(cls, st): """Load Automatons from a stream"""
y = yaml.load(st) return [ Automaton(k, v) for k, v in y.iteritems() ]
<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_dot(self, filename_or_stream, auts): """Create a graphviz .dot representation of the automaton."""
if isinstance(filename_or_stream, str): stream = file(filename_or_stream, 'w') else: stream = filename_or_stream dot = DotFile(stream) for aut in auts: dot.start(aut.name) dot.node('shape=Mrecord width=1.5') ...
<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, url): """Create a bucket, directory, or empty file."""
bucket, obj_key = _parse_url(url) if not bucket: raise InvalidURL(url, "You must specify a bucket and (optional) path") if obj_key: target = "/".join((bucket, obj_key)) else: target = bucket return self.call("Cr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def destroy(self, url, recursive=False): """Destroy a bucket, directory, or file. Specifying recursive=True recursively deletes all subdirectories and files."""
bucket, obj_key = _parse_url(url) if not bucket: raise InvalidURL(url, "You must specify a bucket and (optional) path") if obj_key: target = "/".join((bucket, obj_key)) else: target = bucket if recursive: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upload(self, local_path, remote_url): """Copy a local file to an S3 location."""
bucket, key = _parse_url(remote_url) with open(local_path, 'rb') as fp: return self.call("PutObject", bucket=bucket, key=key, body=fp)
<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, remote_url, local_path, buffer_size=8 * 1024): """Copy S3 data to a local file."""
bucket, key = _parse_url(remote_url) response_file = self.call("GetObject", bucket=bucket, key=key)['Body'] with open(local_path, 'wb') as fp: buf = response_file.read(buffer_size) while buf: fp.write(buf) buf = response_file.read(buffer_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy(self, src_url, dst_url): """Copy an S3 object to another S3 location."""
src_bucket, src_key = _parse_url(src_url) dst_bucket, dst_key = _parse_url(dst_url) if not dst_bucket: dst_bucket = src_bucket params = { 'copy_source': '/'.join((src_bucket, src_key)), 'bucket': dst_bucket, 'key': dst_key, } ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def move(self, src_url, dst_url): """Copy a single S3 object to another S3 location, then delete the original object."""
self.copy(src_url, dst_url) self.destroy(src_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 get_shard_names(self): """ get_shard_names returns an array containing the names of the shards in the cluster. This is determined with num_shards and shard_n...
results = [] for shard_num in range(0, self.num_shards()): shard_name = self.get_shard_name(shard_num) results.append(shard_name) return results
<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_canonical_key_id(self, key_id): """ get_canonical_key_id is used by get_canonical_key, see the comment for that method for more explanation. Keyword argu...
shard_num = self.get_shard_num_by_key_id(key_id) return self._canonical_keys[shard_num]
<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_shard_by_num(self, shard_num): """ get_shard_by_num returns the shard at index shard_num. Keyword arguments: shard_num -- The shard index Returns a redis...
if shard_num < 0 or shard_num >= self.num_shards(): raise ValueError("requested invalid shard# {0}".format(shard_num)) return self._shards[shard_num]
<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_key_id_from_key(self, key): """ _get_key_id_from_key returns the key id from a key, if found. otherwise it just returns the key to be used as the key id...
key_id = key regex = '{0}([^{1}]*){2}'.format(self._hash_start, self._hash_stop, self._hash_stop) m = re.search(regex, key) if m is not None: # Use what's inside the hash tags as the key id, if present. # Otherwise the wh...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compute_canonical_key_ids(self, search_amplifier=100): """ A canonical key id is the lowest integer key id that maps to a particular shard. The mapping to ca...
canonical_keys = {} num_shards = self.num_shards() # Guarantees enough to find all keys without running forever num_iterations = (num_shards**2) * search_amplifier for key_id in range(1, num_iterations): shard_num = self.get_shard_num_by_key(str(key_id)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def keys(self, args): """ keys wrapper that queries every shard. This is an expensive operation. This method should be invoked on a TwemRedis instance as if it w...
results = {} # TODO: parallelize for shard_num in range(0, self.num_shards()): shard = self.get_shard_by_num(shard_num) results[shard_num] = shard.keys(args) return results
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mget(self, args): """ mget wrapper that batches keys per shard and execute as few mgets as necessary to fetch the keys from all the shards involved. This met...
key_map = collections.defaultdict(list) results = {} for key in args: shard_num = self.get_shard_num_by_key(key) key_map[shard_num].append(key) # TODO: parallelize for shard_num in key_map.keys(): shard = self.get_shard_by_num(shard_num) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mset(self, args): """ mset wrapper that batches keys per shard and execute as few msets as necessary to set the keys in all the shards involved. This method ...
key_map = collections.defaultdict(dict) result_count = 0 for key in args.keys(): value = args[key] shard_num = self.get_shard_num_by_key(key) key_map[shard_num][key] = value # TODO: parallelize for shard_num in key_map.keys(): sha...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def id_generator(start=0): """ Generator for sequential numeric numbers. """
count = start while True: send_value = (yield count) if not send_value is None: if send_value < count: raise ValueError('Values from ID generator must increase ' 'monotonically (current value: %d; value ' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def generative(func): """ Marks an instance method as generative. """
def wrap(inst, *args, **kw): clone = type(inst).__new__(type(inst)) clone.__dict__ = inst.__dict__.copy() return func(clone, *args, **kw) return update_wrapper(wrap, func)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def truncate(message, limit=500): """ Truncates the message to the given limit length. The beginning and the end of the message are left untouched. """
if len(message) > limit: trc_msg = ''.join([message[:limit // 2 - 2], ' .. ', message[len(message) - limit // 2 + 2:]]) else: trc_msg = message return trc_msg
<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_board(board_id): """remove board. :param board_id: board id (e.g. 'diecimila') :rtype: None """
log.debug('remove %s', board_id) lines = boards_txt().lines() lines = filter(lambda x: not x.strip().startswith(board_id + '.'), lines) boards_txt().write_lines(lines)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_route(self, route) -> dict: """ Construct a route to be parsed into flask App """
middleware = route['middleware'] if 'middleware' in route else None # added to ALL requests to support xhr cross-site requests route['methods'].append('OPTIONS') return { 'url': route['url'], 'name': route['name'], 'methods': route['methods'], ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def diffusion_driver(self): """ diffusion driver are the underlying `dW` of each process `X` in a SDE like `dX = m dt + s dW` :return list(StochasticProcess): "...
if self._diffusion_driver is None: return self, if isinstance(self._diffusion_driver, list): return tuple(self._diffusion_driver) if isinstance(self._diffusion_driver, tuple): return self._diffusion_driver return self._diffusion_driver,
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset_codenames(self, dry_run=None, clear_existing=None): """Ensures all historical model codenames exist in Django's Permission model. """
self.created_codenames = [] self.updated_names = [] actions = ["add", "change", "delete", "view"] if django.VERSION >= (2, 1): actions.append("view") for app in django_apps.get_app_configs(): for model in app.get_models(): try: ...