Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given snippet: <|code_start|> return fetch_url(url, parser='json')
def full_img_url(img, size='w500'):
return (IMG_BASE + '/' + size + img) if img else None
def movie_item(movie_data):
title = movie_data['title']
poster = full_img_url(movie_data['poster_path'])
url = '/movie/%d?append_to_response... | item_add(ST_SEARCH, _('Search movies'), 'search', action=ACT_SEARCH) |
Given the code snippet: <|code_start|>
SUPPORT: To regenerate thumbnail, just delete the image file under thumbnails folder inside the post directory.
SUPPORT: To remove any link from the blog post, delete the entry after the post is created **in the blog directory**
Note down all the links somewhere then run the follo... | page_html = fetch_html_page(url) |
Next line prediction: <|code_start|> f.mkdir(parents=True, exist_ok=True)
# output
context["hn_post_id"] = hn_post_id
context["target_folder"] = target_folder
context["child_links_folder"] = child_links_folder
context["thumbnails_folder"] = thumbnails_folder
class G... | context["bs"] = html_parser_from(self.page_html) |
Based on the snippet: <|code_start|>#!/usr/bin/env python3
"""
Count number of files by type in a directory
input:
- directory
- file extensions
output:
- total number of files
"""
def main(source_directory: str, extensions: List[str]):
print(f"Source directory: {source_directory}, extensions: {ex... | if p.is_file() and p.suffix.lower() in extensions and valid_file(p) |
Continue the code snippet: <|code_start|>$ cat <filename>.html | pup 'a attr{href}' >> links.txt
3. Run this script
$ EDITOR=/usr/local/bin/idea ./links_to_hugo.py --links-file .temp/links.txt --post-title "Post title" \
--blog-directory "<full-path-to-blog-directory" --open-in-editor
4. Review blog post in the ... | page_html = fetch_html_page(url) |
Given the following code snippet before the placeholder: <|code_start|> known_domains = ["ycombinator", "algolia", "hackernews", "youtube", "twitter", "chrome.google.com", "youtu.be"]
def has_known_domain(post_link):
return any(map(lambda l: l in post_link.lower(), known_domains))
r... | bs = html_parser_from(page_html) |
Using the snippet: <|code_start|>
def parse_args():
parser = ArgumentParser(description=__doc__)
parser.add_argument("-p", "--page-url", type=str, required=True, help="PhpBB Forum Page Url")
return parser.parse_args()
class InitScript(WorkflowBase):
"""Initialise environment"""
def _init_script(s... | create_dir(output_folder, delete_existing=False) |
Using the snippet: <|code_start|>#!/usr/bin/env python3
"""
Telegram bot to convert web page links to PDF
"""
load_dotenv()
OUTPUT_DIR = Path.home().joinpath("OutputDir", "web-to-pdf")
def welcome(update: Update, _):
if update.message:
update.message.reply_text(
"👋 Hi there. ⬇️ I'm a bot ... | page_html = fetch_html_page(web_page_url) |
Here is a snippet: <|code_start|>#!/usr/bin/env python3
"""
Telegram bot to convert web page links to PDF
"""
load_dotenv()
OUTPUT_DIR = Path.home().joinpath("OutputDir", "web-to-pdf")
def welcome(update: Update, _):
if update.message:
update.message.reply_text(
"👋 Hi there. ⬇️ I'm a bot ... | bs = html_parser_from(page_html) |
Based on the snippet: <|code_start|>
load_dotenv()
OUTPUT_DIR = Path.home().joinpath("OutputDir", "web-to-pdf")
def welcome(update: Update, _):
if update.message:
update.message.reply_text(
"👋 Hi there. ⬇️ I'm a bot that converts web pages to PDFs. ⬆️. " "Try sending me a link to a web pag... | @retry(telegram.error.TimedOut, tries=3) |
Next line prediction: <|code_start|> def fix(v):
return v[1:] if v.startswith(os.sep) else v
if len(segments) > 1:
segments = [segments[0]] + [fix(v) for v in segments[1:]]
return os.path.join(*segments)
def join_path_later(*segments):
"""
Like :func:`join_path`, but deferred.
... | path = stringify(path) |
Predict the next line for this snippet: <|code_start|>#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | segments = stringify_list(segments) |
Next line prediction: <|code_start|>
return lambda _: join_path(*segments)
def base_path(path):
"""
Returns the real base path string of a file.
:param path: path; calls :func:`ronin.utils.strings.stringify` on it
:type path: str|FunctionType
:returns: base path of ``path``
:rtype: s... | with current_context() as ctx: |
Predict the next line after this snippet: <|code_start|> """
A list that raises :class:`~exceptions.TypeError` exceptions when objects of the wrong type are
inserted.
:param items: initial list
:type items: list
:param value_type: type(s) required for list values
:type value_type: :obj:`... | raise TypeError('value must be a "{}": {!r}'.format(type_name(self.value_type), value)) |
Next line prediction: <|code_start|> self.key_type = _convert_type(key_type)
self.value_type = _convert_type(value_type)
self.wrapper_function = wrapper_function
self.unwrapper_function = unwrapper_function
if items:
for k, v in items:
self[k] = v
... | the_type = import_symbol(the_type) |
Next line prediction: <|code_start|> self.unwrapper_function = items.unwrapper_function
self.key_type = _convert_type(key_type)
self.value_type = _convert_type(value_type)
self.wrapper_function = wrapper_function
self.unwrapper_function = unwrapper_function
if items:
... | elif isinstance(the_type, string): |
Given the following code snippet before the placeholder: <|code_start|>atexit.register(_restore_terminal)
terminal = Terminal()
def announce(message, prefix='rōnin', color='green'):
"""
Writes a message to the terminal with a colored prefix.
:param message: message
:type message: str
:param ... | message = to_str(message) |
Next line prediction: <|code_start|>
UNESCAPED_STRING_RE = re.compile(r'(?<!\\) ')
def stringify(value):
"""
Casts the value to a Unicode string. If the value is a function, calls it using
:func:`ronin.contexts.current_context` as its only argument, and recurses until a
non-FunctionType value is retur... | return to_str(value) |
Here is a snippet: <|code_start|>
from __future__ import unicode_literals
_ENCODING = 'utf-8'
UNESCAPED_STRING_RE = re.compile(r'(?<!\\) ')
def stringify(value):
"""
Casts the value to a Unicode string. If the value is a function, calls it using
:func:`ronin.contexts.current_context` as its only argume... | with current_context() as ctx: |
Given snippet: <|code_start|>extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ... | version = VERSION |
Here is a snippet: <|code_start|># Copyright 2016-2018 Tal Liron
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | self.extensions = StrictList(value_type=Extension) |
Given the code snippet: <|code_start|>
class Executor(object):
"""
Base class for executors.
:ivar command: command
:vartype command: str or ~types.FunctionType
:ivar command_types: command types supported (used by extensions)
:vartype command_types: [:obj:`str`]
:ivar output_extension:... | f.write(stringify(self.command)) |
Predict the next line for this snippet: <|code_start|> if to_filter and argument_filter:
argument = argument_filter(argument)
if append:
if argument not in arguments:
arguments.append(argument)
else:
arguments.remove(... | value = join_later(value) |
Given the following code snippet before the placeholder: <|code_start|>#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either exp... | self.command_types = StrictList(value_type=str) |
Using the snippet: <|code_start|> Human-readable name of type(s). Built-in types will avoid the "__builtin__" prefix.
Tuples are always handled as a join of "|".
:param the_type: type(s)
:type the_type: type|(type)
:returns: name of type(s)
:rtype: str
"""
if isinstance(the_type, ... | if isinstance(the_type, string): |
Using the snippet: <|code_start|> """
Imports a symbol based on its fully qualified name.
:param name: symbol name
:type name: str
:returns: symbol
:raises ImportError: if could not import the module
:raises AttributeError: if could not find the symbol in the module
"""
if n... | module = to_str(the_type.__module__) |
Using the snippet: <|code_start|>def configure_platform(prefixes=None, which_command=None):
"""
Configures the current context's platform support.
:param prefixes: overrides for the default platform prefixes; unspecified keys will remain
unchanged from their defaults
:type prefixes: {str: str|... | command = stringify(command) |
Next line prediction: <|code_start|># Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
#... | with current_context(False) as ctx: |
Given the following code snippet before the placeholder: <|code_start|>)
RUNTIMES = {
"threading": pytest.param(
Runtime(
name="threading",
actor_class=ThreadingActor,
event_class=threading.Event,
future_class=ThreadingFuture,
sleep_func=time.sle... | log_handler = PykkaTestLogHandler() |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
"""
An x11 bridge provides a secure/firewalled link between a desktop application and the host x11 server. In this case, we use XPRA to do the bridging.
::.
------------- -------------
|desktop app| <--/tmp/.X11-un... | class XpraX11Bridge(Service): |
Predict the next line for this snippet: <|code_start|> self.preArgs = []
self.subuserName = None
self.subuserArgs = []
self.consumedSubuserName = False
def readArg(self,arg):
if not self.consumedSubuserName:
if arg.startswith("-"):
self.preArgs.append(arg)
else:
self.su... | user = User() |
Continue the code snippet: <|code_start|>#!/usr/bin/python3
# -*- coding: utf-8 -*-
#external imports
#internal imports
def parseCliArgs(realArgs):
usage = "usage: subuser version"
description = """Prints subuser's version and other usefull debugging info.
"""
parser = optparse.OptionParser(usage=usage,descripti... | user = User() |
Given snippet: <|code_start|>#!/usr/bin/python3
# -*- coding: utf-8 -*-
#external imports
#internal imports
def parseCliArgs(realArgs):
usage = "usage: subuser ps"
description = """ List running subusers.
"""
parser=optparse.OptionParser(usage=usage,description=description,formatter=subuserlib.commandLineArgu... | user = User() |
Given snippet: <|code_start|> archive.seek(0)
def readAndPrintStreamingBuildStatus(user,response):
jsonSegmentBytes = b''
output = b''
byte = response.read(1)
while byte:
jsonSegmentBytes += byte
output += byte
byte = response.read(1)
try:
lineDict = json.loads(jsonSegmentBytes.decode("u... | class DockerDaemon(UserOwnedObject): |
Continue the code snippet: <|code_start|> user.registry.log(lineDict["stream"])
elif "status" in lineDict:
user.registry.log(lineDict["status"])
elif "errorDetail" in lineDict:
raise exceptions.ImageBuildException("Build error:"+lineDict["errorDetail"]["message"]+"\n"+response.read().... | self.__connection = UHTTPConnection("/var/run/docker.sock") |
Continue the code snippet: <|code_start|> def __init__(self,user):
self.__connection = None
self.__imagePropertiesCache = {}
UserOwnedObject.__init__(self,user)
def getConnection(self):
"""
Get an `HTTPConnection <https://docs.python.org/2/library/httplib.html#httplib.HTTPConnection>`_ to the D... | return Container(self.user,containerId) |
Continue the code snippet: <|code_start|>#internal imports
class Config(userOwnedObject.UserOwnedObject, dict):
def __init__(self,user):
self.__delitem__ = None
self.__setitem__ = None
userOwnedObject.UserOwnedObject.__init__(self,user)
self._loadConfig()
def _getSubuserConfigPaths(self):
""" ... | loadMultiFallbackJsonConfigFile.expandPathsInDict(self.user.homeDir,pathsToExpand,config) |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
"""
The Config class is used to hold user wide settings.
"""
#external imports
#internal imports
class Config(userOwnedObject.UserOwnedObject, dict):
def __init__(self,user):
self.__delitem__ = None
self.__setitem__ = None
use... | configFileInSubuserDir = paths.getSubuserDataFile("config.json") |
Predict the next line after this snippet: <|code_start|>#!/usr/bin/python3
# -*- coding: utf-8 -*-
#external imports
#internal imports
####################################################
def parseCliArgs(realArgs):
usage = "usage: subuser repair [options]"
description = """
Repair your subuser installation.
This... | lockedUser = LockedUser() |
Given the following code snippet before the placeholder: <|code_start|> subuserNamesWithNoImageSource = list(subusersWithNoImageSource.keys())
subuserNamesWithNoImageSource.sort()
registry.log(" ".join(subuserNamesWithNoImageSource))
registry.log("Unregistering any non-existant installed images.",2)
use... | installationTask = InstallationTask(op) |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
#external imports
#internal imports
def parseCliArgs(sysargs):
usage = "usage: subuser repository [options] [add|remove] NAME <URL>"
description = """Add or remove a new named repository.
- EXAMPLE
Add a new repository named foo with the URI https://www.exa... | lockedUser = LockedUser() |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
"""
Runtime environments which are prepared for subusers to run in.
"""
#external imports
#internal imports
def getRecursiveDirectoryContents(directory):
files = []
for (directory,_,fileList) in os.walk(directory):
for fileName in fileList:
fi... | class Runtime(UserOwnedObject): |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Each time you run a command such as `subuser subuser add foo xterm` you are preforming an operation which modifies the subuser registry and which builds images. Many of the steps are repeated for each operation and many of the configuration options are gl... | self.permissionsAccepter = AcceptPermissionsAtCLI(user) |
Based on the snippet: <|code_start|>
subusers
Updates the specified subusers
EXAMPLE:
$ subuser update subusers iceweasel git
lock-subuser-to SUBUSER GIT-COMMIT
Don't want a subuser to be updated? No problem, lock it to a given version with this update sub-command. Use subuser update log to se... | lockedUser = LockedUser() |
Using the snippet: <|code_start|>#!/usr/bin/python3
# -*- coding: utf-8 -*-
#external imports
#internal imports
def parseCliArgs(realArgs):
usage = "usage: subuser remove-old-images"
description = """ Remove old, no longer used, installed images. Note, once you do this, you will no longer be able to return to pre... | lockedUser = LockedUser() |
Here is a snippet: <|code_start|>#external imports
#internal imports
#####################################################################################
def parseCliArgs(realArgs):
usage = "usage: subuser registry [options]"
description = """Interact with the subuser registry.
log
Prints a log of recen... | user = User() |
Given the following code snippet before the placeholder: <|code_start|>#internal imports
#####################################################################################
def parseCliArgs(realArgs):
usage = "usage: subuser registry [options]"
description = """Interact with the subuser registry.
log
P... | lockedUser = LockedUser() |
Predict the next line for this snippet: <|code_start|> ret = func(*args, **kwargs)
elapsedTime = time.time() - startTime
print('function [{}] finished in {} ms'.format(
func.__name__, int(elapsedTime * 1000)))
return ret
return newfunc
class EndUser(UserOwnedObject,objec... | if not test.testing: |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
"""
The ``EndUser`` object the object that represents the user account owned by the human user of the system. It is possible to run subuser using a different user account, in order to isolate root from the end user's user account.
"""
#exter... | class EndUser(UserOwnedObject,object): |
Using the snippet: <|code_start|> feature = self._build_obj(feature)
self.data_store[key] = feature
self.idx.insert(key, feature['geometry'].bounds)
class CachedLookup(SpatialLookup):
""" Cache results of spatial lookups """
geohash_cache = {}
def __init__(self, precision=7, *arg... | proj_point = project([float(lon), float(lat)]) |
Continue the code snippet: <|code_start|>
root = os.path.dirname(inspect.getfile(geotweet))
TEST_STREAM = os.path.join(root, 'data/twitter-api-stream-raw.log')
class GeoFilterStepTests(unittest.TestCase):
def setUp(self):
<|code_end|>
. Use current file imports:
import unittest
import json
import os
import sy... | self.step = GeoFilterStep() |
Predict the next line for this snippet: <|code_start|>
class GeoFilterStepTests(unittest.TestCase):
def setUp(self):
self.step = GeoFilterStep()
def test_invalid_empty(self):
data = dict()
error = "Expected validate_geotweet to return False"
self.assertFalse(self.step.validate_... | self.step = ExtractStep() |
Given snippet: <|code_start|>
root = dirname(dirname(dirname(dirname(os.path.abspath(__file__)))))
sys.path.append(root)
GEOTWEET_DIR = root
DATA_DIR = os.path.join(root, 'data', 'geo')
COUNTIES_GEOJSON_LOCAL = os.path.join(DATA_DIR,'us_counties102005.geojson')
os.environ['COUNTIES_GEOJSON_LOCAL'] = COUNTIES_GEOJSON_... | self.mr = StateCountyWordCountJob() |
Given snippet: <|code_start|>
SCRIPTDIR = dirname(os.path.abspath(__file__))
DEFAULT_STATES = os.path.join(SCRIPTDIR, 'data/states.txt')
US_GEOFABRIK = 'http://download.geofabrik.de/north-america/us/{0}-latest.osm.pbf'
POI_TAGS = ["amenity", "builing", "shop", "office", "tourism"]
class OSMRunner(object):
"""
... | self.s3 = S3Loader(bucket=args.bucket, region=args.region) |
Given the code snippet: <|code_start|> # bb = r2.get(elf, "pdbj")
# r2.gets(elf, "pdb")
# for i in bb:
# if i["type"] == "cjmp":
# jump = i["jump"]
# offset = i["offset"]
# self.bra... | l = LongWriteInfo(elf, start, end, thumb) |
Given the following code snippet before the placeholder: <|code_start|> outf = open(path, "w")
outf.write("(setq substages '(%s))\n" % " ".join([str(i) for i in substage_linenos]))
outf.close()
@classmethod
def get_function_lineno(cls, fn, path, last=False):
if last:
... | pymacs_request.ask_emacs('(create-substage-calltraces "%s" "%s" "%s")' % |
Next line prediction: <|code_start|> # Load pretrained model
if pretrained_model is not None and pretrained_model.find("model") > -1:
logger.info("load pretrained model : "
+ os.path.join(db_model.trained_model_path, pretrained_model))
serializers.load_hdf5(os.path.join(db_mod... | remove_resume_file(db_model.trained_model_path) |
Based on the snippet: <|code_start|>
datadir = os.path.join(os.path.dirname(dividebatur.__file__),
os.pardir, "dividebatur-aec")
class CandidateListTests(unittest.TestCase):
def test_fed2013(self):
all_candidates_csv = os.path.join(
datadir, "fed2013", "common",
... | cl = CandidateList("NSW", all_candidates_csv, senate_candidates_csv) |
Using the snippet: <|code_start|> current_candidates = []
candidate_id = candidate_by_name_party[
c.surname, c.ballot_given_nm, c.party_ballot_nm]
candidate = Candidate(candidate_id,
c.surname,
c.... | for candidate in sorted(named_tuple_iter('AllCandidate', reader, header, ballot_position=int), key=lambda row: (ticket_sort_key(row.ticket), row.ballot_position)): |
Predict the next line after this snippet: <|code_start|> current_candidates = []
candidate_id = candidate_by_name_party[
c.surname, c.ballot_given_nm, c.party_ballot_nm]
candidate = Candidate(candidate_id,
c.surname,
... | for candidate in sorted(named_tuple_iter('AllCandidate', reader, header, ballot_position=int), key=lambda row: (ticket_sort_key(row.ticket), row.ballot_position)): |
Here is a snippet: <|code_start|>
# put some paranoia around exclusion: we want to make sure that
# `candidates` is unique, and that none of these candidates have
# been previously excluded
for candidate_id in candidates:
assert(candidate_id not in self.candidates_excluded)
... | ElectionDistributionPerformed( |
Next line prediction: <|code_start|> transfer_values = list(reversed(sorted(transfers_applicable)))
self.results.candidates_excluded(
CandidatesExcluded(
candidates=candidates,
transfer_values=transfer_values,
reason=reason))
for transf... | ExclusionDistributionPerformed( |
Here is a snippet: <|code_start|> return sorted_candidate_ids[self.election_tie_cb(candidates)]
def determine_quota(self):
self.total_papers = sum(count for _, count in self.papers_for_count)
self.quota = int(self.total_papers / (self.vacancies + 1)) + 1
def determine_elected_candidates... | ActProvision("Multiple candidates elected with %d votes. Tie broken from previous totals." % (votes))) |
Predict the next line for this snippet: <|code_start|> self.candidate_bundle_transactions.transfer_to(candidate_id, bundle_transaction)
candidate_votes[candidate_id] += bundle_transaction.votes
exhausted_votes = int(exhausted_papers * transfer_value)
return exhausted_votes, exhau... | CandidateElected( |
Given the following code snippet before the placeholder: <|code_start|> order=elected_no,
excess_votes=excess_votes,
paper_count=paper_count,
transfer_value=transfer_value))
def exclude_candidates(self, candidates, reason):
"""
mark one... | CandidatesExcluded( |
Predict the next line for this snippet: <|code_start|>
candidates_for_exclusion = []
for candidate_id in candidate_ids:
if candidate_aggregates.get_vote_count(candidate_id) == min_votes:
candidates_for_exclusion.append(candidate_id)
next_to_min_votes = None
c... | return excluded_candidate_id, ExclusionReason("exclusion", { |
Given snippet: <|code_start|>
def json_log(self, candidate_aggregates):
if self.test_log_dir is None:
return
log = []
for candidate_id in self.candidate_ids_display(candidate_aggregates):
log.append((self.get_candidate_title(candidate_id), candidate_aggregates.get_vot... | logger.error("failed to serialise data") |
Continue the code snippet: <|code_start|> prefs = []
for ticket_entry in g:
prefs.append(ticket_entry.CandidateID)
self.gvt[ticket].append(tuple(prefs))
def load_first_preferences(self, state_name, firstprefs_csv):
with open(firstprefs_csv,... | logger.info("GVT split ticket remainder, AEO input needed: %s" % (remainder_pattern)) |
Here is a snippet: <|code_start|> remainder_pattern = [0] * (size - remainder) + [1] * (remainder)
if remainder:
logger.info("GVT split ticket remainder, AEO input needed: %s" % (remainder_pattern))
# remainder_pattern = [0] * (size-remainder) + [1] * remainder
... | Preference=int_or_none, |
Using the snippet: <|code_start|>
class SenateATL:
"parses AEC candidates Senate ATL data file (pre-2015)"
def __init__(self, state_name, gvt_csv, firstprefs_csv):
self.state_name = state_name
self.gvt = defaultdict(list)
self.ticket_votes = []
self.btl_firstprefs = {}
... | named_tuple_iter('GvtRow', reader, header, PreferenceNo=int, TicketNo=int, CandidateID=int, OwnerTicket=lambda t: t.strip()), |
Based on the snippet: <|code_start|>
class SenateATL:
"parses AEC candidates Senate ATL data file (pre-2015)"
def __init__(self, state_name, gvt_csv, firstprefs_csv):
self.state_name = state_name
self.gvt = defaultdict(list)
self.ticket_votes = []
self.btl_firstprefs = {}
... | key=lambda gvt: (gvt.State, ticket_sort_key(gvt.OwnerTicket), gvt.TicketNo, gvt.PreferenceNo)) |
Here is a snippet: <|code_start|>
_logger = logging.getLogger('weixin_pay_notificaiton')
def process_notify(request):
_logger.info('received weixin pay notification.body:{}'.format(request.body))
<|code_end|>
. Write the next line using the current file imports:
import logging
from django.http import Http... | unipay.process_notify(PAY_WAY_WEIXIN, request.body)
|
Here is a snippet: <|code_start|>
_logger = logging.getLogger('weixin_pay_notificaiton')
def process_notify(request):
_logger.info('received weixin pay notification.body:{}'.format(request.body))
<|code_end|>
. Write the next line using the current file imports:
import logging
from django.http import Http... | unipay.process_notify(PAY_WAY_WEIXIN, request.body)
|
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
_SERVICE = 'mobile.securitypay.pay'
_CHARSET = 'utf-8'
_SIGN_TYPE = 'RSA'
_PAYMENT_TYPE = '1'
_ALIPAY_ORDER_FIELD = ('out_trade_no', 'subject', 'body', 'total_fee', 'it_b_pay',)
class AliPayOrder(models.Model):
out_trade_no = models.CharField(ver... | return '{}&sign_type="RSA"&sign="{}"'.format(data, quote_plus(security.sign(data)))
|
Predict the next line for this snippet: <|code_start|> obj.initial_orlder()
admin.ModelAdmin.save_model(self, request, obj, form, change)
########################### product #########################
class ProductResource(resources.ModelResource):
class Meta:
model = OrderItem
... | admin.site.register(Product, ProductAdmin)
|
Given the following code snippet before the placeholder: <|code_start|> 'paied',
'product_desc', )
def save_model(self, request, obj, form, change):
if not obj.orderno:
obj.initial_orlder()
admin.ModelAdmin.save_model(self, request, obj, form, ... | obj.weinxin_qrurl = unipay.generate_qr_pay_url(PAY_WAY_WEIXIN, obj.productid)
|
Given the code snippet: <|code_start|> 'paied',
'product_desc', )
def save_model(self, request, obj, form, change):
if not obj.orderno:
obj.initial_orlder()
admin.ModelAdmin.save_model(self, request, obj, form, change)
####################... | obj.weinxin_qrurl = unipay.generate_qr_pay_url(PAY_WAY_WEIXIN, obj.productid)
|
Based on the snippet: <|code_start|>
_logger = logging.getLogger('openunipay_ali_pay_notificaiton')
def process_notify(request):
_logger.info('received ali pay notification.body:{}'.format(request.body))
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
from django.http... | unipay.process_notify(PAY_WAY_ALI, request)
|
Given the following code snippet before the placeholder: <|code_start|>
_logger = logging.getLogger('openunipay_ali_pay_notificaiton')
def process_notify(request):
_logger.info('received ali pay notification.body:{}'.format(request.body))
<|code_end|>
, predict the next line using imports from the current fil... | unipay.process_notify(PAY_WAY_ALI, request)
|
Given the code snippet: <|code_start|>PAY_WAY_WEIXIN = 'WEIXIN'
PAY_WAY_ALI = 'ALI'
PAY_WAY = ((PAY_WAY_WEIXIN, u'微信支付'),
(PAY_WAY_ALI, u'支付宝支付'), )
class OrderItem(models.Model):
orderno = models.CharField(verbose_name=u'订单号', max_length=50, primary_key=True, editable=False)
user = models.... | self.dt_start = datetime.local_now()
|
Using the snippet: <|code_start|>"""uimbank_server URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r... | url(r'^notify/alipay/$', views_alipay.process_notify), |
Predict the next line for this snippet: <|code_start|>"""uimbank_server URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL t... | url(r'^notify/weixin/$', views_weixin.process_notify), |
Predict the next line for this snippet: <|code_start|>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to ... | test_config = ef_site_config.EFSiteConfig().load_from_local_file() |
Continue the code snippet: <|code_start|>
class TestMarkdown(TestCase):
def test_render_md_to_html(self):
scenarios = (
{'md': 'title\n===', 'expect': '<div class="highlight"><h1>title</h1>\n</div>'},
{'md': '#1\n##2', 'expect': '<div class="highlight"><h1>1</h1>\n\n<h2 id="2">2<... | hashed = generate_passwd(passwd) |
Predict the next line after this snippet: <|code_start|>
class TestMarkdown(TestCase):
def test_render_md_to_html(self):
scenarios = (
{'md': 'title\n===', 'expect': '<div class="highlight"><h1>title</h1>\n</div>'},
{'md': '#1\n##2', 'expect': '<div class="highlight"><h1>1</h1>\n... | self.assertTrue(validate_passwd(passwd, hashed)) |
Here is a snippet: <|code_start|>
class TestMarkdown(TestCase):
def test_render_md_to_html(self):
scenarios = (
{'md': 'title\n===', 'expect': '<div class="highlight"><h1>title</h1>\n</div>'},
{'md': '#1\n##2', 'expect': '<div class="highlight"><h1>1</h1>\n\n<h2 id="2">2</h2>\n</di... | token = generate_token(j, passwd) |
Predict the next line for this snippet: <|code_start|>
class TestMarkdown(TestCase):
def test_render_md_to_html(self):
scenarios = (
{'md': 'title\n===', 'expect': '<div class="highlight"><h1>title</h1>\n</div>'},
{'md': '#1\n##2', 'expect': '<div class="highlight"><h1>1</h1>\n\n<h2... | self.assertTrue(validate_token(token, passwd)) |
Continue the code snippet: <|code_start|>
class TestMarkdown(TestCase):
def test_render_md_to_html(self):
scenarios = (
{'md': 'title\n===', 'expect': '<div class="highlight"><h1>title</h1>\n</div>'},
{'md': '#1\n##2', 'expect': '<div class="highlight"><h1>1</h1>\n\n<h2 id="2">2<... | self.assertEqual(render_md_to_html(scena['md']), scena['expect']) |
Continue the code snippet: <|code_start|>
GA_ID = 'UA-65521906-1'
class GargantuaTestCase(AsyncHTTPTestCase):
def get_app(self):
options.debug = True
options.dbhost = 'localhost'
options.dbport = 27017
<|code_end|>
. Use current file imports:
from urllib.parse import urlparse
from tor... | self.app = Application() |
Using the snippet: <|code_start|>
class MultiAdapter(BankAdapter):
name = 'Multiple adapters'
@property
def adapters(self):
for name in self.config.get('bank_adapters', []):
yield get_bank_adapter(name)(self.config, self.filename)
@property
def fetch_type(self):
for ad... | accounts = update_accounts(accounts, list(adapter.fetch_accounts())) |
Based on the snippet: <|code_start|>
class MultiAdapter(BankAdapter):
name = 'Multiple adapters'
@property
def adapters(self):
for name in self.config.get('bank_adapters', []):
yield get_bank_adapter(name)(self.config, self.filename)
@property
def fetch_type(self):
for... | transactions = update_transactions(transactions, adapter.fetch_transactions(account, start_date, end_date)) |
Continue the code snippet: <|code_start|> new_completed - completed, goal.label, new_save, used[goal.label], target - new_completed))
if total_savings < 0:
_debug(' ! Not enough savings to cover this month (remaining=%s)' % total_savings)
if not r... | income_transactions, _ = split_income_expenses(filter_transactions_period( |
Predict the next line after this snippet: <|code_start|> budgets = BudgetList()
for date in period_to_months(start_date, end_date):
budgets.append(budgetize_month(transactions, date, *args, **kwargs))
return budgets
def budgetize_month(transactions, date, income_sources=None, planned_expenses=None,... | planned_expenses_transactions, expenses_transactions = extract_transactions_by_label( |
Predict the next line for this snippet: <|code_start|> new_completed - completed, goal.label, new_save, used[goal.label], target - new_completed))
if total_savings < 0:
_debug(' ! Not enough savings to cover this month (remaining=%s)' % total_savings)
... | income_transactions, _ = split_income_expenses(filter_transactions_period( |
Next line prediction: <|code_start|> _debug(' ! Not enough savings to cover this month (remaining=%s)' % total_savings)
if not remaining_goals:
break
savings_after_goals = max(total_savings - sum(saved.values()), 0)
_debug('END COMPUTING OF GOALS (savings=%s,... | transactions = sort_transactions(income_transactions + expenses_transactions) |
Continue the code snippet: <|code_start|> saved[goal.label] = new_save
remaining_goals.remove(goal.label)
elif new_completed < completed:
take_back = saved[goal.label] - new_save
saved[goal.label] = new_save
... | for date in period_to_months(start_date, end_date): |
Here is a snippet: <|code_start|> def to_dict(self):
return {
'name': self.name,
'color': self.color,
'keywords': self.keywords,
'warning_threshold': self.warning_threshold
}
class ComputedCategory(namedtuple('ComputedCategory', ['name', 'color', 'key... | for tx in filter_transactions_period(transactions, start_date, end_date): |
Here is a snippet: <|code_start|> def fetch_transactions_from_all_accounts(self, start_date=None, end_date=None):
transactions = []
for account in self.fetch_accounts():
transactions.extend(self.fetch_transactions(account, start_date, end_date))
return sorted(transactions, key=lam... | return Transaction(**kwargs) |
Given snippet: <|code_start|>
def get_bank_adapter(name):
module = import_module('budgettracker.bank_adapters.' + name)
for obj in module.__dict__.values():
if inspect.isclass(obj) and issubclass(obj, BankAdapter) and obj is not BankAdapter:
return obj
class BankAdapter(object):
fetch... | self.__dict__['categories'] = map(Category.from_dict, self.config.get('categories', [])) |
Next line prediction: <|code_start|> return self.__dict__['categories']
def fetch_transactions_from_all_accounts(self, start_date=None, end_date=None):
transactions = []
for account in self.fetch_accounts():
transactions.extend(self.fetch_transactions(account, start_date, end_dat... | kwargs.setdefault('categories', match_categories(self.categories, kwargs['label'])) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.