_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q46100 | invert_dictset | train | def invert_dictset(d):
"""Invert a dictionary with keys matching a set of values, turned into lists."""
# Based on recipe from ASPN
result = {}
for k, c in d.items():
for v in c:
keys = result.setdefault(v, [])
keys.append(k)
return result | python | {
"resource": ""
} |
q46101 | invert_dict | train | def invert_dict(d):
"""Invert a dictionary with keys matching each value turned into a list."""
# Based on recipe from ASPN
result = {}
for k, v in d.items():
keys = result.setdefault(v, [])
keys.append(k)
return result | python | {
"resource": ""
} |
q46102 | defines_to_dict | train | def defines_to_dict(defines):
"""Convert a list of definition strings to a dictionary."""
if defines is None:
return None
result = {}
for define in defines:
kv = define.split('=', 1)
if len(kv) == 1:
result[define.strip()] = 1
else:
result[kv[0].st... | python | {
"resource": ""
} |
q46103 | BaseProcessManager.start | train | def start(self, instance_names):
""" If start is called from the root of a Galaxy source directory with
no args, automatically add this instance.
"""
if not instance_names:
configs = (os.path.join('config', 'galaxy.ini'),
os.path.join('config', 'galaxy.ini... | python | {
"resource": ""
} |
q46104 | VIVOWrapper.setQuery | train | def setQuery(self, query):
"""
Set the SPARQL query text and set the VIVO custom
authentication parameters.
Set here because this is called immediately before
any query is sent to the triple store.
"""
self.queryType = self._parseQueryType(query)
self.que... | python | {
"resource": ""
} |
q46105 | SettingsPostProcessor.post_process | train | def post_process(self, settings):
"""
Perform post processing methods on settings according to their
definition in manifest.
Post process methods are implemented in their own method that have the
same signature:
* Get arguments: Current settings, item name and item valu... | python | {
"resource": ""
} |
q46106 | SettingsPostProcessor._patch_expand_path | train | def _patch_expand_path(self, settings, name, value):
"""
Patch a path to expand home directory and make absolute path.
Args:
settings (dict): Current settings.
name (str): Setting name.
value (str): Path to patch.
Returns:
str: Patched pa... | python | {
"resource": ""
} |
q46107 | SettingsPostProcessor._patch_expand_paths | train | def _patch_expand_paths(self, settings, name, value):
"""
Apply ``SettingsPostProcessor._patch_expand_path`` to each element in
list.
Args:
settings (dict): Current settings.
name (str): Setting name.
value (list): List of paths to patch.
Ret... | python | {
"resource": ""
} |
q46108 | SettingsPostProcessor._validate_path | train | def _validate_path(self, settings, name, value):
"""
Validate path exists
Args:
settings (dict): Current settings.
name (str): Setting name.
value (str): Path to validate.
Raises:
boussole.exceptions.SettingsInvalidError: If path does not... | python | {
"resource": ""
} |
q46109 | SettingsPostProcessor._validate_paths | train | def _validate_paths(self, settings, name, value):
"""
Apply ``SettingsPostProcessor._validate_path`` to each element in
list.
Args:
settings (dict): Current settings.
name (str): Setting name.
value (list): List of paths to patch.
Raises:
... | python | {
"resource": ""
} |
q46110 | summarize | train | def summarize(urls):
"""
Calls extract for each of the URLs,
Returns the list of Extracted instances as summaries,
the result of the process, and the speed.
"""
import time
from summary import Summary
fails = 0
err = lambda e: e.__class__.__name__
summaries = []
... | python | {
"resource": ""
} |
q46111 | initMazeFromJSON | train | def initMazeFromJSON(jsonString, cellClass=Cell, gridClass=Grid):
'''Init a maze from JSON string.'''
jsonObj = json.loads(jsonString)
rows=jsonObj["rows"]
columns=jsonObj["columns"]
grid=gridClass(rows,columns,cellClass)
grid.algorithm=jsonObj["algorithm"]
grid.algorithm_key=jsonObj["a... | python | {
"resource": ""
} |
q46112 | read_json_file | train | def read_json_file(fpath):
"""
Read a JSON file from ``fpath``; raise an exception if it doesn't exist.
:param fpath: path to file to read
:type fpath: str
:return: deserialized JSON
:rtype: dict
"""
if not os.path.exists(fpath):
raise Exception('ERROR: file %s does not exist.' ... | python | {
"resource": ""
} |
q46113 | Summary._load | train | def _load(self, titles=[], descriptions=[], images=[], urls=[], **kwargs):
"""
Loads extracted data into Summary.
Performs validation and filtering on-the-fly, and sets the
non-plural fields to the best specific item so far.
If GET_ALL_DATA is False, it gets only the first valid ... | python | {
"resource": ""
} |
q46114 | Summary._clean_url | train | def _clean_url(self, url):
"""
Canonicalizes the url, as it is done in Scrapy.
And keeps only USEFUL_QUERY_KEYS. It also strips the
trailing slash to help identifying dupes.
"""
# TODO: Turn this into regex
if not url.startswith('http') or url.endswith('}}') or '... | python | {
"resource": ""
} |
q46115 | Summary._filter_image | train | def _filter_image(self, url):
"The param is the image URL, which is returned if it passes all the filters."
return reduce(lambda f, g: f and g(f),
[
filters.AdblockURLFilter()(url),
filters.NoImageFilter(),
filters.SizeImageFilter(),
filters.MonoI... | python | {
"resource": ""
} |
q46116 | Summary._get_tag | train | def _get_tag(self, response, tag_name="html", encoding="utf-8"):
"""
Iterates response content and returns the tag if found.
If not found, the response content is fully consumed so
self._html equals response.content, and it returns None.
"""
def find_tag(tag_name):
... | python | {
"resource": ""
} |
q46117 | Evaluation.of_think | train | def of_think(self, think):
"""
Simulate the worker processing the task for the specified amount of time.
The worker is not released and the task is not paused.
"""
return self._compute(
duration=think.duration,
after=self.continuation) | python | {
"resource": ""
} |
q46118 | Balance.freeze | train | async def freeze(self, *args, **kwargs):
"""
Freeze users balance
Accepts:
- uid [integer] (users id from main server)
- coinid [string] (blockchain type in uppercase)
- amount [integer] (amount for freezing)
Returns:
- uid [integer] (users id from main server)
- coinid [string] (blockchain typ... | python | {
"resource": ""
} |
q46119 | Balance.get_active | train | async def get_active(self, *args, **kwargs):
"""
Get active users balance
Accepts:
- uid [integer] (users id)
- types [list | string] (array with needed types or "all")
Returns:
{
type [string] (blockchain type): amount
}
"""
# Get daya from request
coinids = kwargs.get("coinids")
uid... | python | {
"resource": ""
} |
q46120 | Balance.get_frozen | train | async def get_frozen(self, *args, **kwargs):
"""
Get frozen users balance
Accepts:
- uid [integer] (users id)
- types [list | string] (array with needed types or "all")
Returns:
{
type [string] (blockchain type): amount
}
"""
super().validate(*args, **kwargs)
if kwargs.get("message"):
... | python | {
"resource": ""
} |
q46121 | Balance.get_wallets | train | async def get_wallets(self, *args, **kwargs):
"""
Get users wallets by uid
Accepts:
- uid [integer] (users id)
Returns a list:
- [
{
"address": [string],
"uid": [integer],
"amount_active": [integer],
"amount_frozen": [integer]
},
]
"""
logging.debug("\n [+] -- G... | python | {
"resource": ""
} |
q46122 | Balance.confirmbalance | train | async def confirmbalance(self, *args, **kwargs):
""" Confirm balance after trading
Accepts:
- message (signed dictionary):
- "txid" - str
- "coinid" - str
- "amount" - int
Returns:
- "address" - str
- "coinid" - str
- "amount" - int
- "... | python | {
"resource": ""
} |
q46123 | Config._load_config | train | def _load_config(self, path):
"""
Load configuration from JSON
:param path: path to the JSON config file
:type path: str
:return: config dictionary
:rtype: dict
"""
p = os.path.abspath(os.path.expanduser(path))
logger.debug('Loading configuration ... | python | {
"resource": ""
} |
q46124 | __add_min_max_value | train | def __add_min_max_value(
parser,
basename,
default_min,
default_max,
initial,
help_template):
"""
Generates parser entries for options
with a min, max, and default value.
Args:
parser: the parser to use.
basename: the base option name. Gen... | python | {
"resource": ""
} |
q46125 | copy_default_config_to_user_directory | train | def copy_default_config_to_user_directory(
basename,
clobber=False,
dst_dir='~/.config/scriptabit'):
""" Copies the default configuration file into the user config directory.
Args:
basename (str): The base filename.
clobber (bool): If True, the default will be written ev... | python | {
"resource": ""
} |
q46126 | TokenAuth.authenticate | train | def authenticate(self, token):
""" Authenticate a token
:param token:
"""
if self.verify_token_callback:
# Specified verify function overrides below
return self.verify_token_callback(token)
if not token:
return False
name = self.toke... | python | {
"resource": ""
} |
q46127 | parse_raw | train | def parse_raw(s, lineno=0):
"""Parse a date from a raw string.
The format must be exactly "seconds-since-epoch offset-utc".
See the spec for details.
"""
timestamp_str, timezone_str = s.split(b' ', 1)
timestamp = float(timestamp_str)
try:
timezone = parse_tz(timezone_str)
except... | python | {
"resource": ""
} |
q46128 | Section.get_lines | train | def get_lines(self, config_access, visited_set):
"""
get the lines for this section
visited_set is used to avoid visiting same section
twice, if we've got a diamond in the @is setup
"""
if self in visited_set:
return []
lines = self.lines.copy()
... | python | {
"resource": ""
} |
q46129 | Host.variable_iter | train | def variable_iter(self, base):
"""
returns iterator over the cross product of the variables
for this stanza
"""
base_substs = dict(('<' + t + '>', u) for (t, u) in base.items())
substs = []
vals = []
for with_defn in self.with_exprs:
substs.app... | python | {
"resource": ""
} |
q46130 | Host.host_stanzas | train | def host_stanzas(self, config_access):
"""
returns a list of host definitions
"""
defn_lines = self.resolve_defn(config_access)
for val_dict in self.variable_iter(config_access.get_variables()):
subst = list(self.apply_substitutions(defn_lines, val_dict))
... | python | {
"resource": ""
} |
q46131 | base | train | def base(context, config, database, root, log_level):
"""Housekeeper - Access your files!"""
coloredlogs.install(level=log_level)
context.obj = ruamel.yaml.safe_load(config) if config else {}
context.obj['database'] = database if database else context.obj['database']
context.obj['root'] = root if ro... | python | {
"resource": ""
} |
q46132 | Script.showpath | train | def showpath(path):
"""Return path in form most convenient for user to read.
Return relative path when input path is within the current working
directory, otherwise return same (absolute) path passed in.
:param path: file system path
:type path: str or unicode
:returns:... | python | {
"resource": ""
} |
q46133 | Script.lines | train | def lines(self):
"""List of file lines."""
if self._lines is None:
with io.open(self.path, 'r', encoding='utf-8') as fh:
self._lines = fh.read().split('\n')
return self._lines | python | {
"resource": ""
} |
q46134 | Script.update | train | def update(self):
"""Replace baseline representations previously registered for update."""
for linenum in reversed(sorted(self.updates)):
self.replace_baseline_repr(linenum, self.updates[linenum])
if not self.TEST_MODE:
path = '{}.update{}'.format(*os.path.splitext(self.... | python | {
"resource": ""
} |
q46135 | url_is_from_any_domain | train | def url_is_from_any_domain(url, domains):
"""Return True if the url belongs to any of the given domains"""
host = parse_url(url).netloc.lower()
if host:
return any(((host == d.lower()) or (host.endswith('.%s' % d.lower())) for d in domains))
else:
return False | python | {
"resource": ""
} |
q46136 | _iterable_as_config_list | train | def _iterable_as_config_list(s):
"""Format an iterable as a sequence of comma-separated strings.
To match what ConfigObj expects, a single item list has a trailing comma.
"""
items = sorted(s)
if len(items) == 1:
return "%s," % (items[0],)
else:
return ", ".join(items) | python | {
"resource": ""
} |
q46137 | GoogleSearch.start_search | train | def start_search(self, max_page=1):
"""method to start send query to google. Search start from page 1.
max_page determine how many result expected
hint: 10 result per page for google
"""
for page in range(1, (max_page + 1)):
start = "start={0}".format(str((page - 1) ... | python | {
"resource": ""
} |
q46138 | GoogleSearch.more_search | train | def more_search(self, more_page):
"""Method to add more result to an already exist result.
more_page determine how many result page should be added
to the current result.
"""
next_page = self.current_page + 1
top_page = more_page + self.current_page
for page in r... | python | {
"resource": ""
} |
q46139 | GoogleSearch._execute_search_request | train | def _execute_search_request(self, url):
"""method to execute the query to google.
The specified page and keyword
must already included in the url.
"""
try:
self.request_page = requests.get(url)
except requests.ConnectionError:
print("Connection to... | python | {
"resource": ""
} |
q46140 | GitHubCity.readConfig | train | def readConfig(self, configuration):
"""Read configuration from dict.
Read configuration from a JSON configuration file.
:param configuration: configuration to load.
:type configuration: dict.
"""
self.__logger.debug("Reading configuration")
self.city = configur... | python | {
"resource": ""
} |
q46141 | GitHubCity.readConfigFromJSON | train | def readConfigFromJSON(self, fileName):
"""Read configuration from JSON.
:param fileName: path to the configuration file.
:type fileName: str.
"""
self.__logger.debug("readConfigFromJSON: reading from " + fileName)
with open(fileName) as data_file:
data = loa... | python | {
"resource": ""
} |
q46142 | GitHubCity.configToJson | train | def configToJson(self, fileName):
"""Save the configuration of the city in a JSON.
:param fileName: path to the output file.
:type fileName: str.
"""
config = self.getConfig()
with open(fileName, "w") as outfile:
dump(config, outfile, indent=4, sort_keys=True... | python | {
"resource": ""
} |
q46143 | GitHubCity.getConfig | train | def getConfig(self):
"""Return the configuration of the city.
:return: configuration of the city.
:rtype: dict.
"""
config = {}
config["name"] = self.city
config["intervals"] = self.__intervals
config["last_date"] = self.__lastDay
config["excluded... | python | {
"resource": ""
} |
q46144 | GitHubCity.addFilter | train | def addFilter(self, field, value):
"""Add a filter to the seach.
:param field: what field filter (see GitHub search).
:type field: str.
:param value: value of the filter (see GitHub search).
:type value: str.
"""
if "<" not in value or ">" not in value or ".." no... | python | {
"resource": ""
} |
q46145 | GitHubCity.__processUsers | train | def __processUsers(self):
"""Process users of the queue."""
while self.__usersToProccess.empty() and not self.__end:
pass
while not self.__end or not self.__usersToProccess.empty():
self.__lockGetUser.acquire()
try:
new_user = self.__usersToPr... | python | {
"resource": ""
} |
q46146 | GitHubCity.__addUser | train | def __addUser(self, new_user):
"""Add new users to the list.
:param new_user: name of a GitHub user to include in
the ranking
:type new_user: str.
"""
self.__lockReadAddUser.acquire()
if new_user not in self.__cityUsers and \
new_user not in s... | python | {
"resource": ""
} |
q46147 | GitHubCity.__getPeriodUsers | train | def __getPeriodUsers(self, start_date, final_date):
"""Get all the users given a period.
:param start_date: start date of the range to search
users
:type start_date: time.date.
:param final_date: final date of the range to search
users
:type final_date: t... | python | {
"resource": ""
} |
q46148 | GitHubCity.getCityUsers | train | def getCityUsers(self, numberOfThreads=20):
"""Get all the users from the city.
:param numberOfThreads: number of threads to run.
:type numberOfThreads: int.
"""
if not self.__intervals:
self.__logger.debug("Calculating best intervals")
self.calculateBest... | python | {
"resource": ""
} |
q46149 | GitHubCity.calculateBestIntervals | train | def calculateBestIntervals(self):
"""Calcule valid intervals of a city."""
self.__intervals = []
self.__readAPI(self.__getURL())
today = datetime.datetime.now().date()
self.__validInterval(datetime.date(2008, 1, 1), today)
self.__logger.info("Total number of intervals: "... | python | {
"resource": ""
} |
q46150 | GitHubCity.__validInterval | train | def __validInterval(self, start, finish):
"""Check if the interval is correct.
An interval is correct if it has less than 1001
users. If the interval is correct, it will be added
to '_intervals' attribute. Else, interval will be
split in two news intervals and these intervals
... | python | {
"resource": ""
} |
q46151 | GitHubCity.__exportUsers | train | def __exportUsers(self, sort, limit=0):
"""Export the users to a dictionary.
:param sort: field to sort the users
:type sort: str.
:return: exported users.
:rtype: dict.
"""
position = 1
dataUsers = self.getSortedUsers(sort)
if limit:
... | python | {
"resource": ""
} |
q46152 | GitHubCity.calculeToday | train | def calculeToday(self):
"""Calcule the intervals from the last date."""
self.__logger.debug("Add today")
last = datetime.datetime.strptime(self.__lastDay, "%Y-%m-%d")
today = datetime.datetime.now().date()
self.__validInterval(last, today) | python | {
"resource": ""
} |
q46153 | GitHubCity.__addLocationsToURL | train | def __addLocationsToURL(self, locations):
"""Format all locations to GitHub's URL API.
:param locations: locations where to search users.
:type locations: list(str).
"""
for l in self.__locations:
self.__urlLocations += "+location:\""\
+ str(quote(l)) + ... | python | {
"resource": ""
} |
q46154 | GitHubCity.__launchThreads | train | def __launchThreads(self, numThreads):
"""Launch some threads and start to process users.
:param numThreads: number of thrads to launch.
:type numThreads: int.
"""
i = 0
while i < numThreads:
self.__logger.debug("Launching thread number " +
... | python | {
"resource": ""
} |
q46155 | GitHubCity.__getURL | train | def __getURL(self, page=1, start_date=None,
final_date=None, order="asc"):
"""Get the API's URL to query to get data about users.
:param page: number of the page.
:param start_date: start date of the range to search
users (Y-m-d).
"param final_date: final da... | python | {
"resource": ""
} |
q46156 | Mention.sentence | train | def sentence(self):
"""
The sentence related to this mention
:getter: returns the sentence this mention relates to
:type: corenlp_xml.document.Sentence
"""
if self._sentence is None:
sentences = self._element.xpath('sentence/text()')
if len(sente... | python | {
"resource": ""
} |
q46157 | Mention.head | train | def head(self):
"""
The token serving as the "head" of the mention
:getter: the token corresponding to the head
:type: corenlp_xml.document.Token
"""
if self._head is None:
self._head = self.sentence.tokens[self._head_id-1]
return self._head | python | {
"resource": ""
} |
q46158 | generate_password_hash | train | def generate_password_hash(password, salt, N=1 << 14, r=8, p=1, buflen=64):
"""
Generate password hash givin the password string and salt.
Args:
- ``password``: Password string.
- ``salt`` : Random base64 encoded string.
Optional args:
- ``N`` : the CPU cost, must be a power of... | python | {
"resource": ""
} |
q46159 | write_moc_ascii | train | def write_moc_ascii(moc, filename=None, file=None):
"""Write a MOC to an ASCII file.
Either a filename, or an open file object can be specified.
"""
orders = []
for (order, cells) in moc:
ranges = []
rmin = rmax = None
for cell in sorted(cells):
if rmin is Non... | python | {
"resource": ""
} |
q46160 | read_moc_ascii | train | def read_moc_ascii(moc, filename=None, file=None):
"""Read from an ASCII file into a MOC.
Either a filename, or an open file object can be specified.
"""
if file is not None:
orders = _read_ascii(file)
else:
with open(filename, 'r') as f:
orders = _read_ascii(f)
fo... | python | {
"resource": ""
} |
q46161 | index | train | def index():
""" Base testsuite view. """
# setup_env()
logs = Table('log', metadata, autoload=True)
criticals = logs.select().where(logs.c.log_level == 50).order_by(
'siteconfig', 'date_created')
criticals_count = logs.count(logs.c.log_level == 50)
errors = logs.select().where(logs.... | python | {
"resource": ""
} |
q46162 | Location.timezone | train | def timezone(self, value):
"""Set the timezone."""
self._timezone = (value if isinstance(value, datetime.tzinfo)
else tz.gettz(value)) | python | {
"resource": ""
} |
q46163 | recursive_iterator | train | def recursive_iterator(func):
"""Decorates a function by optimizing it for iterator recursion.
Requires function arguments to be pickleable."""
tee_store = {}
@_coconut.functools.wraps(func)
def recursive_iterator_func(*args, **kwargs):
hashable_args_kwargs = _coconut.pickle.dumps((args, kwa... | python | {
"resource": ""
} |
q46164 | addpattern | train | def addpattern(base_func):
"""Decorator to add a new case to a pattern-matching function, where the new case is checked last."""
def pattern_adder(func):
@_coconut.functools.wraps(func)
@_coconut_tco
def add_pattern_func(*args, **kwargs):
try:
return base_func... | python | {
"resource": ""
} |
q46165 | fmap | train | def fmap(func, obj):
"""Creates a copy of obj with func applied to its contents."""
if _coconut.hasattr(obj, "__fmap__"):
return obj.__fmap__(func)
args = _coconut_map(func, obj)
if _coconut.isinstance(obj, _coconut.dict):
args = _coconut_zip(args, obj.values())
if _coconut.isinstanc... | python | {
"resource": ""
} |
q46166 | reversed.index | train | def index(self, elem):
"""Find the index of elem in the reversed iterator."""
return _coconut.len(self._iter) - self._iter.index(elem) - 1 | python | {
"resource": ""
} |
q46167 | count.index | train | def index(self, elem):
"""Find the index of elem in the count."""
if elem not in self:
raise _coconut.ValueError(_coconut.repr(elem) + " is not in count")
return (elem - self._start) // self._step | python | {
"resource": ""
} |
q46168 | AWSSigV4Verifier.canonical_uri_path | train | def canonical_uri_path(self):
"""
The canonicalized URI path from the request.
"""
result = getattr(self, "_canonical_uri_path", None)
if result is None:
result = self._canonical_uri_path = get_canonical_uri_path(
self.uri_path)
return result | python | {
"resource": ""
} |
q46169 | AWSSigV4Verifier.query_parameters | train | def query_parameters(self):
"""
A key to list of values mapping of the query parameters seen in the
request.
"""
result = getattr(self, "_query_parameters", None)
if result is None:
result = self._query_parameters = normalize_query_parameters(
... | python | {
"resource": ""
} |
q46170 | AWSSigV4Verifier.canonical_query_string | train | def canonical_query_string(self):
"""
The canonical query string from the query parameters.
This takes the query string from the request and orders the parameters
in
"""
results = []
for key, values in iteritems(self.query_parameters):
# Don't includ... | python | {
"resource": ""
} |
q46171 | AWSSigV4Verifier.signed_headers | train | def signed_headers(self):
"""
An ordered dictionary containing the signed header names and values.
"""
# See if the signed headers are listed in the query string
signed_headers = self.query_parameters.get(_x_amz_signedheaders)
if signed_headers is not None:
si... | python | {
"resource": ""
} |
q46172 | AWSSigV4Verifier.request_timestamp | train | def request_timestamp(self):
"""
The timestamp of the request in ISO8601 YYYYMMDD'T'HHMMSS'Z' format.
If this is not available in the query parameters or headers, or the
value is not a valid format for AWS SigV4, an AttributeError exception
is raised.
"""
amz_dat... | python | {
"resource": ""
} |
q46173 | AWSSigV4Verifier.access_key | train | def access_key(self):
"""
The access key id used to sign the request.
If the access key is not in the same credential scope as this request,
an AttributeError exception is raised.
"""
credential = self.query_parameters.get(_x_amz_credential)
if credential is not ... | python | {
"resource": ""
} |
q46174 | AWSSigV4Verifier.request_signature | train | def request_signature(self):
"""
The signature passed in the request.
"""
signature = self.query_parameters.get(_x_amz_signature)
if signature is not None:
signature = signature[0]
else:
signature = self.authorization_header_parameters.get(_signatu... | python | {
"resource": ""
} |
q46175 | AWSSigV4Verifier.string_to_sign | train | def string_to_sign(self):
"""
The AWS SigV4 string being signed.
"""
return (AWS4_HMAC_SHA256 + "\n" +
self.request_timestamp + "\n" +
self.credential_scope + "\n" +
sha256(self.canonical_request.encode("utf-8")).hexdigest()) | python | {
"resource": ""
} |
q46176 | AWSSigV4Verifier.expected_signature | train | def expected_signature(self):
"""
The AWS SigV4 signature expected from the request.
"""
k_secret = b"AWS4" + self.key_mapping[self.access_key].encode("utf-8")
k_date = hmac.new(k_secret, self.request_date.encode("utf-8"),
sha256).digest()
k_regi... | python | {
"resource": ""
} |
q46177 | AWSSigV4Verifier.verify | train | def verify(self):
"""
Verifies that the request timestamp is not beyond our allowable
timestamp mismatch and that the request signature matches our
expectations.
"""
try:
if self.timestamp_mismatch is not None:
m = _iso8601_timestamp_regex.matc... | python | {
"resource": ""
} |
q46178 | moothedata | train | def moothedata(data, key=None):
"""Return an amusing picture containing an item from a dict.
Parameters
----------
data: mapping
A mapping, such as a raster dataset's ``meta`` or ``profile``
property.
key:
A key of the ``data`` mapping.
"""
if not key:
key = ... | python | {
"resource": ""
} |
q46179 | SerializableStructuredNode.resource_collection_response | train | def resource_collection_response(cls, offset=0, limit=20):
"""
This method is deprecated for version 1.1.0. Please use get_collection
"""
request_args = {'page[offset]': offset, 'page[limit]': limit}
return cls.get_collection(request_args) | python | {
"resource": ""
} |
q46180 | SerializableStructuredNode.get_collection | train | def get_collection(cls, request_args):
r"""
Used to fetch a collection of resource object of type 'cls' in response to a GET request\
. get_resource_or_collection should only be invoked on a resource when the client specifies a GET request.
:param request_args: The query parameters supp... | python | {
"resource": ""
} |
q46181 | SerializableStructuredNode.get_resource | train | def get_resource(cls, request_args, id):
r"""
Used to fetch a single resource object with the given id in response to a GET request.\
get_resource should only be invoked on a resource when the client specifies a GET request.
:param request_args:
:return: The query parameters sup... | python | {
"resource": ""
} |
q46182 | SerializableStructuredNode.get_resource_or_collection | train | def get_resource_or_collection(cls, request_args, id=None):
r"""
Deprecated for version 1.1.0. Please use get_resource or get_collection.
This function has multiple behaviors.
With id specified: Used to fetch a single resource object with the given id in response to a GET request.\
... | python | {
"resource": ""
} |
q46183 | SerializableStructuredNode.deactivate_resource | train | def deactivate_resource(cls, id):
r"""
Used to deactivate a node of type 'cls' in response to a DELETE request. deactivate_resource should only \
be invoked on a resource when the client specifies a DELETE request.
:param id: The 'id' field of the node to update in the database. The id... | python | {
"resource": ""
} |
q46184 | SerializableStructuredNode.disconnect_relationship | train | def disconnect_relationship(cls, id, related_collection_name, request_json):
"""
Disconnect one or more relationship in a collection with cardinality 'Many'.
:param id: The 'id' field of the node on the left side of the relationship in the database. The id field must \
be set in the mo... | python | {
"resource": ""
} |
q46185 | SerializableStructuredNode.delete_relationship | train | def delete_relationship(cls, id, related_collection_name, related_resource=None):
"""
Deprecated for version 1.1.0. Please use update_relationship
"""
try:
this_resource = cls.nodes.get(id=id, active=True)
if not related_resource:
r = this_resourc... | python | {
"resource": ""
} |
q46186 | SerializableStructuredNode.update_relationship | train | def update_relationship(cls, id, related_collection_name, request_json):
r"""
Used to completely replace all the existing relationships with new ones.
:param id: The 'id' field of the node on the left side of the relationship in the database. The id field must \
be set in the model -- ... | python | {
"resource": ""
} |
q46187 | StopWordFactory.get_stop_words | train | def get_stop_words(self, language, fail_safe=False):
"""
Returns a StopWord object initialized with the stop words collection
requested by ``language``.
If the requested language is not available a StopWordError is raised.
If ``fail_safe`` is set to True, an empty StopWord object... | python | {
"resource": ""
} |
q46188 | StopWordFactory._get_stop_words | train | def _get_stop_words(self, language):
"""
Internal method for getting the stop words collections
and raising errors.
"""
if language not in self.available_languages:
raise StopWordError(
'Stop words are not available in "%s".\n'
'If poss... | python | {
"resource": ""
} |
q46189 | StopWordFactory.available_languages | train | def available_languages(self):
"""
Returns a list of languages providing collection of stop words.
"""
available_languages = getattr(self, '_available_languages', None)
if available_languages:
return available_languages
try:
languages = os.listdir(... | python | {
"resource": ""
} |
q46190 | StopWordFactory.get_collection_filename | train | def get_collection_filename(self, language):
"""
Returns the filename containing the stop words collection
for a specific language.
"""
filename = os.path.join(self.data_directory, '%s.txt' % language)
return filename | python | {
"resource": ""
} |
q46191 | StopWordFactory.read_collection | train | def read_collection(self, filename):
"""
Reads and returns a collection of stop words into a file.
"""
with open(filename, 'rb') as fd:
lines = fd.read().decode('utf-8-sig').splitlines()
collection = list(filter(bool, [line.strip() for line in lines]))
return ... | python | {
"resource": ""
} |
q46192 | StopWordFactory.write_collection | train | def write_collection(self, filename, collection):
"""
Writes a collection of stop words into a file.
"""
collection = sorted(list(collection))
with open(filename, 'wb+') as fd:
fd.truncate()
fd.write('\n'.join(collection).encode('utf-8')) | python | {
"resource": ""
} |
q46193 | startproject_command | train | def startproject_command(context, basedir, sourcedir, targetdir,
backend, config):
"""
Create a new Sass project
This will prompt you to define your project configuration in a settings
file then create needed directory structure.
Arguments 'basedir', 'config', 'sourcedir',... | python | {
"resource": ""
} |
q46194 | list_example | train | def list_example():
""" Example list pagination.
"""
from uuid import uuid4
from redis import StrictRedis
from zato.redis_paginator import ListPaginator
conn = StrictRedis()
key = 'paginator:{}'.format(uuid4().hex)
for x in range(1, 18):
conn.rpush(key, x)
... | python | {
"resource": ""
} |
q46195 | zset_example | train | def zset_example():
""" Example sorted set pagination.
"""
from uuid import uuid4
from redis import StrictRedis
from zato.redis_paginator import ZSetPaginator
conn = StrictRedis()
key = 'paginator:{}'.format(uuid4().hex)
# 97-114 is 'a' to 'r' in ASCII
for x in range(1, 18)... | python | {
"resource": ""
} |
q46196 | DependencyNode.load | train | def load(cls, graph, element):
"""
Instantiates the node in the graph if it's not already stored in the graph
:param graph: The dependency graph this node is a member of
:type graph: corenlp_xml.dependencies.DependencyGraph
:param element: The lxml element wrapping the node
... | python | {
"resource": ""
} |
q46197 | DependencyNode.governor | train | def governor(self, dep_type, node):
"""
Registers a node as governing this node
:param dep_type: The dependency type
:type dep_type: str
:param node:
:return: self, provides fluent interface
:rtype: corenlp_xml.dependencies.DependencyNode
"""
se... | python | {
"resource": ""
} |
q46198 | DependencyNode.dependent | train | def dependent(self, dep_type, node):
"""
Registers a node as dependent on this node
:param dep_type: The dependency type
:type dep_type: str
:param node: The node to be registered as a dependent
:type node: corenlp_xml.dependencies.DependencyNode
:return: self, ... | python | {
"resource": ""
} |
q46199 | DependencyLink.governor | train | def governor(self):
"""
Accesses the governor node
:getter: Returns the Governor node
:type: corenlp_xml.dependencies.DependencyNode
"""
if self._governor is None:
governors = self._element.xpath('governor')
if len(governors) > 0:
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.