_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q45200 | UnPublishView.post | train | def post(self, request, *args, **kwargs):
"""
Method for handling POST requests. Unpublishes the
the object by calling the object's unpublish method.
The action is logged, the user is notified with a
message. Returns a 'render redirect' to the result of
the `get_done_url`... | python | {
"resource": ""
} |
q45201 | DeleteView.post | train | def post(self, request, *args, **kwargs):
"""
Method for handling POST requests.
Deletes the object. Successful deletes are logged.
Returns a 'render redirect' to the result of the
`get_done_url` method.
If a ProtectedError is raised, the `render` method
is calle... | python | {
"resource": ""
} |
q45202 | KeyExpander.expand | train | def expand(self, key_array):
"""
Expand the encryption key per AES key schedule specifications
http://en.wikipedia.org/wiki/Rijndael_key_schedule# Key_schedule_description
"""
if len(key_array) != self._n:
raise RuntimeError('expand(): key size ' + str(len(k... | python | {
"resource": ""
} |
q45203 | build_dot_value | train | def build_dot_value(key, value):
"""Build new dictionaries based off of the dot notation key.
For example, if a key were 'x.y.z' and the value was 'foo',
we would expect a return value of: ('x', {'y': {'z': 'foo'}})
Args:
key (str): The key to build a dictionary off of.
value: The valu... | python | {
"resource": ""
} |
q45204 | DotDict.get | train | def get(self, key, default=None):
"""Get a value from the `DotDict`.
The `key` parameter can either be a regular string key,
e.g. "foo", or it can be a string key with dot notation,
e.g. "foo.bar.baz", to signify a nested lookup.
The default value is returned if any level of th... | python | {
"resource": ""
} |
q45205 | DotDict.delete | train | def delete(self, key):
"""Remove a value from the `DotDict`.
The `key` parameter can either be a regular string key,
e.g. "foo", or it can be a string key with dot notation,
e.g. "foo.bar.baz", to signify a nested element.
If the key does not exist in the `DotDict`, it will con... | python | {
"resource": ""
} |
q45206 | make_extractor | train | def make_extractor(non_default):
"""
Return us a function to extract options
Anything not in non_default is wrapped in a "Default" object
"""
def extract_options(template, options):
for option, val in normalise_options(template):
name = option.replace('-', '_')
... | python | {
"resource": ""
} |
q45207 | SpecRegister.set_option | train | def set_option(self, name, val, action=Empty, opts=Empty):
"""Determine which options were specified outside of the defaults"""
if action is Empty and opts is Empty:
self.specified.append(name)
super(SpecRegister, self).set_option(name, val)
else:
super(SpecRe... | python | {
"resource": ""
} |
q45208 | House.from_tibiadata | train | def from_tibiadata(cls, content):
"""
Parses a TibiaData response into a House object.
Parameters
----------
content: :class:`str`
The JSON content of the TibiaData response.
Returns
-------
:class:`House`
The house contained in t... | python | {
"resource": ""
} |
q45209 | House._parse_status | train | def _parse_status(self, status):
"""Parses the house's state description and applies the corresponding values
Parameters
----------
status: :class:`str`
Plain text string containing the current renting state of the house.
"""
m = rented_regex.search(status)
... | python | {
"resource": ""
} |
q45210 | ListedHouse._parse_status | train | def _parse_status(self, status):
"""
Parses the status string found in the table and applies the corresponding values.
Parameters
----------
status: :class:`str`
The string containing the status.
"""
if "rented" in status:
self.status = Ho... | python | {
"resource": ""
} |
q45211 | Bison.config | train | def config(self):
"""Get the complete configuration where the default, config,
environment, and override values are merged together.
Returns:
(DotDict): A dictionary of configuration values that
allows lookups using dot notation.
"""
if self._full_con... | python | {
"resource": ""
} |
q45212 | Bison.set | train | def set(self, key, value):
"""Set a value in the `Bison` configuration.
Args:
key (str): The configuration key to set a new value for.
value: The value to set.
"""
# the configuration changes, so we invalidate the cached config
self._full_config = None
... | python | {
"resource": ""
} |
q45213 | Bison.parse | train | def parse(self, requires_cfg=True):
"""Parse the configuration sources into `Bison`.
Args:
requires_cfg (bool): Specify whether or not parsing should fail
if a config file is not found. (default: True)
"""
self._parse_default()
self._parse_config(requ... | python | {
"resource": ""
} |
q45214 | Bison._find_config | train | def _find_config(self):
"""Searches through the configured `config_paths` for the `config_name`
file.
If there are no `config_paths` defined, this will raise an error, so the
caller should take care to check the value of `config_paths` first.
Returns:
str: The fully... | python | {
"resource": ""
} |
q45215 | Bison._parse_config | train | def _parse_config(self, requires_cfg=True):
"""Parse the configuration file, if one is configured, and add it to
the `Bison` state.
Args:
requires_cfg (bool): Specify whether or not parsing should fail
if a config file is not found. (default: True)
"""
... | python | {
"resource": ""
} |
q45216 | Bison._parse_env | train | def _parse_env(self):
"""Parse the environment variables for any configuration if an `env_prefix`
is set.
"""
env_cfg = DotDict()
# if the env prefix doesn't end with '_', we'll append it here
if self.env_prefix and not self.env_prefix.endswith('_'):
self.env... | python | {
"resource": ""
} |
q45217 | Bison._parse_default | train | def _parse_default(self):
"""Parse the `Schema` for the `Bison` instance to create the set of
default values.
If no defaults are specified in the `Schema`, the default dictionary
will not contain anything.
"""
# the configuration changes, so we invalidate the cached conf... | python | {
"resource": ""
} |
q45218 | Relation_usingList.get_codomain | train | def get_codomain(self, key):
"""
RETURN AN ARRAY OF OBJECTS THAT key MAPS TO
"""
return [v for k, v in self.all if k == key] | python | {
"resource": ""
} |
q45219 | Session.timeout | train | def timeout(self, value):
"""Sets a custom timeout value for this session"""
if value == TIMEOUT_SESSION:
self._config.timeout = None
self._backend_client.expires = None
else:
self._config.timeout = value
self._calculate_expires() | python | {
"resource": ""
} |
q45220 | Session._calculate_expires | train | def _calculate_expires(self):
"""Calculates the session expiry using the timeout"""
self._backend_client.expires = None
now = datetime.utcnow()
self._backend_client.expires = now + timedelta(seconds=self._config.timeout) | python | {
"resource": ""
} |
q45221 | Session._load_cookie | train | def _load_cookie(self):
"""Loads HTTP Cookie from environ"""
cookie = SimpleCookie(self._environ.get('HTTP_COOKIE'))
vishnu_keys = [key for key in cookie.keys() if key == self._config.cookie_name]
# no session was started yet
if not vishnu_keys:
return
mors... | python | {
"resource": ""
} |
q45222 | Session.header | train | def header(self):
"""Generates HTTP header for this cookie."""
if self._send_cookie:
morsel = Morsel()
cookie_value = Session.encode_sid(self._config.secret, self._sid)
if self._config.encrypt_key:
cipher = AESCipher(self._config.encrypt_key)
... | python | {
"resource": ""
} |
q45223 | Session.encode_sid | train | def encode_sid(cls, secret, sid):
"""Computes the HMAC for the given session id."""
secret_bytes = secret.encode("utf-8")
sid_bytes = sid.encode("utf-8")
sig = hmac.new(secret_bytes, sid_bytes, hashlib.sha512).hexdigest()
return "%s%s" % (sig, sid) | python | {
"resource": ""
} |
q45224 | Session.is_signature_equal | train | def is_signature_equal(cls, sig_a, sig_b):
"""Compares two signatures using a constant time algorithm to avoid timing attacks."""
if len(sig_a) != len(sig_b):
return False
invalid_chars = 0
for char_a, char_b in zip(sig_a, sig_b):
if char_a != char_b:
... | python | {
"resource": ""
} |
q45225 | Session.decode_sid | train | def decode_sid(cls, secret, cookie_value):
"""Decodes a cookie value and returns the sid if value or None if invalid."""
if len(cookie_value) > SIG_LENGTH + SID_LENGTH:
logging.warn("cookie value is incorrect length")
return None
cookie_sig = cookie_value[:SIG_LENGTH]
... | python | {
"resource": ""
} |
q45226 | Session.terminate | train | def terminate(self):
"""Terminates an active session"""
self._backend_client.clear()
self._needs_save = False
self._started = False
self._expire_cookie = True
self._send_cookie = True | python | {
"resource": ""
} |
q45227 | Session.get | train | def get(self, key):
"""Retrieve a value from the session dictionary"""
self._started = self._backend_client.load()
self._needs_save = True
return self._backend_client.get(key) | python | {
"resource": ""
} |
q45228 | new_collection_percolator | train | def new_collection_percolator(target):
"""Create new percolator associated with the new collection.
:param target: Collection where the percolator will be atached.
"""
query = IQ(target.dbquery)
for name in current_search.mappings.keys():
if target.name and target.dbquery:
curre... | python | {
"resource": ""
} |
q45229 | delete_collection_percolator | train | def delete_collection_percolator(target):
"""Delete percolator associated with the new collection.
:param target: Collection where the percolator was attached.
"""
for name in current_search.mappings.keys():
if target.name and target.dbquery:
current_search.client.delete(
... | python | {
"resource": ""
} |
q45230 | collection_updated_percolator | train | def collection_updated_percolator(mapper, connection, target):
"""Create percolator when collection is created.
:param mapper: Not used. It keeps the function signature.
:param connection: Not used. It keeps the function signature.
:param target: Collection where the percolator should be updated.
"... | python | {
"resource": ""
} |
q45231 | _find_matching_collections_externally | train | def _find_matching_collections_externally(collections, record):
"""Find matching collections with percolator engine.
:param collections: set of collections where search
:param record: record to match
"""
index, doc_type = RecordIndexer().record_to_index(record)
body = {"doc": record.dumps()}
... | python | {
"resource": ""
} |
q45232 | _str | train | def _str(value, depth):
"""
FOR DEBUGGING POSSIBLY RECURSIVE STRUCTURES
"""
output = []
if depth >0 and _get(value, CLASS) in data_types:
for k, v in value.items():
output.append(str(k) + "=" + _str(v, depth - 1))
return "{" + ",\n".join(output) + "}"
elif depth >0 an... | python | {
"resource": ""
} |
q45233 | _AppState.cache | train | def cache(self):
"""Return a cache instance."""
cache = self._cache or self.app.config.get('COLLECTIONS_CACHE')
return import_string(cache) if isinstance(cache, six.string_types) \
else cache | python | {
"resource": ""
} |
q45234 | _AppState.collections | train | def collections(self):
"""Get list of collections."""
# if cache server is configured, load collection from there
if self.cache:
return self.cache.get(
self.app.config['COLLECTIONS_CACHE_KEY']) | python | {
"resource": ""
} |
q45235 | _AppState.collections | train | def collections(self, values):
"""Set list of collections."""
# if cache server is configured, save collection list
if self.cache:
self.cache.set(
self.app.config['COLLECTIONS_CACHE_KEY'], values) | python | {
"resource": ""
} |
q45236 | _post_vote | train | def _post_vote(user_bingo_board, field, vote):
"""
change vote on a field
@param user_bingo_board: the user's bingo board or None
@param field: the BingoField to vote on
@param vote: the vote property from the HTTP POST
@raises: VoteException: if user_bingo_board is None or
... | python | {
"resource": ""
} |
q45237 | split_qs | train | def split_qs(string, delimiter='&'):
"""Split a string by the specified unquoted, not enclosed delimiter"""
open_list = '[<{('
close_list = ']>})'
quote_chars = '"\''
level = index = last_index = 0
quoted = False
result = []
for index, letter in enumerate(string):
if letter in... | python | {
"resource": ""
} |
q45238 | parse_qs | train | def parse_qs(string):
"""Intelligently parse the query string"""
result = {}
for item in split_qs(string):
# Split the query string by unquotes ampersants ('&')
try:
# Split the item by unquotes equal signs
key, value = split_qs(item, delimiter='=')
except Va... | python | {
"resource": ""
} |
q45239 | ceiling | train | def ceiling(value, mod=1):
"""
RETURN SMALLEST INTEGER GREATER THAN value
"""
if value == None:
return None
mod = int(mod)
v = int(math_floor(value + mod))
return v - (v % mod) | python | {
"resource": ""
} |
q45240 | DataLookup | train | def DataLookup(fieldVal, db, lookupType, fieldName, histObj={}):
"""
Return new field value based on single-value lookup against MongoDB
:param string fieldVal: input value to lookup
:param MongoClient db: MongoClient instance connected to MongoDB
:param string lookupType: Type of lookup to perform... | python | {
"resource": ""
} |
q45241 | IncludesLookup | train | def IncludesLookup(fieldVal, lookupType, db, fieldName, deriveFieldName='',
deriveInput={}, histObj={}, overwrite=False,
blankIfNoMatch=False):
"""
Return new field value based on whether or not original value includes AND
excludes all words in a comma-delimited list qu... | python | {
"resource": ""
} |
q45242 | RegexLookup | train | def RegexLookup(fieldVal, db, fieldName, lookupType, histObj={}):
"""
Return a new field value based on match against regex queried from MongoDB
:param string fieldVal: input value to lookup
:param MongoClient db: MongoClient instance connected to MongoDB
:param string lookupType: Type of lookup to... | python | {
"resource": ""
} |
q45243 | DeriveDataLookup | train | def DeriveDataLookup(fieldName, db, deriveInput, overwrite=True, fieldVal='',
histObj={}, blankIfNoMatch=False):
"""
Return new field value based on single or multi-value lookup against MongoDB
:param string fieldName: Field name to query against
:param MongoClient db: MongoClient ... | python | {
"resource": ""
} |
q45244 | DeriveDataCopyValue | train | def DeriveDataCopyValue(fieldName, deriveInput, overwrite, fieldVal, histObj={}):
"""
Return new value based on value from another field
:param string fieldName: Field name to query against
:param dict deriveInput: Values to perform lookup against:
{"copyField1": "copyVal1"}
:param bool ... | python | {
"resource": ""
} |
q45245 | _normalize_select_no_context | train | def _normalize_select_no_context(select, schema=None):
"""
SAME NORMALIZE, BUT NO SOURCE OF COLUMNS
"""
if not _Column:
_late_import()
if is_text(select):
select = Data(value=select)
else:
select = wrap(select)
output = select.copy()
if not select.value:
... | python | {
"resource": ""
} |
q45246 | _map_term_using_schema | train | def _map_term_using_schema(master, path, term, schema_edges):
"""
IF THE WHERE CLAUSE REFERS TO FIELDS IN THE SCHEMA, THEN EXPAND THEM
"""
output = FlatList()
for k, v in term.items():
dimension = schema_edges[k]
if isinstance(dimension, Dimension):
domain = dimension.get... | python | {
"resource": ""
} |
q45247 | QueryOp.wrap | train | def wrap(query, container, namespace):
"""
NORMALIZE QUERY SO IT CAN STILL BE JSON
"""
if is_op(query, QueryOp) or query == None:
return query
query = wrap(query)
table = container.get_table(query['from'])
schema = table.schema
output = QueryO... | python | {
"resource": ""
} |
q45248 | CacheManager.invalidate_cache | train | def invalidate_cache(self, klass, extra=None, **kwargs):
"""
Invalidate a cache for a specific class.
This will loop through all registered groups that have registered
the given model class and call their invalidate_cache method.
All keyword arguments will be directly passed th... | python | {
"resource": ""
} |
q45249 | create_store_prompt | train | def create_store_prompt(name):
"""Create a prompt which implements the `store` feature.
:param name: name of the generator
:return: prompt
"""
def _prompt(questions, answers=None, **kwargs):
stored_answers = _read_stored_answers(name)
to_store = []
for q in questions:
... | python | {
"resource": ""
} |
q45250 | memoize | train | def memoize(function):
"""Memoizing function. Potentially not thread-safe, since it will return
resuts across threads. Make sure this is okay with callers."""
_cache = {}
@wraps(function)
def wrapper(*args, **kwargs):
key = str(args) + str(kwargs)
if key not in _cache:
... | python | {
"resource": ""
} |
q45251 | dwmAll | train | def dwmAll(data, db, configName='', config={}, udfNamespace=__name__, verbose=False):
"""
Return list of dictionaries after cleaning rules have been applied; optionally with a history record ID appended.
:param list data: list of dictionaries (records) to which cleaning rules should be applied
:param M... | python | {
"resource": ""
} |
q45252 | Signal.wait | train | def wait(self):
"""
PUT THREAD IN WAIT STATE UNTIL SIGNAL IS ACTIVATED
"""
if self._go:
return True
with self.lock:
if self._go:
return True
stopper = _allocate_lock()
stopper.acquire()
if not self.waiti... | python | {
"resource": ""
} |
q45253 | Signal.on_go | train | def on_go(self, target):
"""
RUN target WHEN SIGNALED
"""
if not target:
Log.error("expecting target")
with self.lock:
if not self._go:
DEBUG and self._name and Log.note("Adding target to signal {{name|quote}}", name=self.name)
... | python | {
"resource": ""
} |
q45254 | Signal.remove_go | train | def remove_go(self, target):
"""
FOR SAVING MEMORY
"""
with self.lock:
if not self._go:
try:
self.job_queue.remove(target)
except ValueError:
pass | python | {
"resource": ""
} |
q45255 | _jx_expression | train | def _jx_expression(expr, lang):
"""
WRAP A JSON EXPRESSION WITH OBJECT REPRESENTATION
"""
if is_expression(expr):
# CONVERT TO lang
new_op = lang[expr.id]
if not new_op:
# CAN NOT BE FOUND, TRY SOME PARTIAL EVAL
return language[expr.id].partial_eval()
... | python | {
"resource": ""
} |
q45256 | ElasticsearchMultilingualSearchBackend.setup | train | def setup(self):
"""
Defers loading until needed.
Compares the existing mapping for each language with the current codebase.
If they differ, it automatically updates the index.
"""
# Get the existing mapping & cache it. We'll compare it
# during the ``update`` & i... | python | {
"resource": ""
} |
q45257 | get | train | def get():
"""Returns the current version without importing pymds."""
pkgnames = find_packages()
if len(pkgnames) == 0:
raise ValueError("Can't find any packages")
pkgname = pkgnames[0]
content = open(join(pkgname, '__init__.py')).read()
c = re.compile(r"__version__ *= *('[^']+'|\"[^\... | python | {
"resource": ""
} |
q45258 | store_integers | train | def store_integers(items, allow_zero=True):
"""Store integers from the given list in a storage.
This is an example function to show autodoc style.
Return :class:`Storage` instance with integers from the given list.
Examples::
>>> storage = store_integers([1, 'foo', 2, 'bar', 0])
>>> ... | python | {
"resource": ""
} |
q45259 | Storage.add_item | train | def add_item(self, item):
"""Append item to the list.
:attr:`last_updated` will be set to :py:meth:`datetime.datetime.now`.
:param item:
Something to append to :attr:`items`.
"""
self.items.append(item)
self.last_updated = datetime.datetime.now() | python | {
"resource": ""
} |
q45260 | HttpError.map_http_status_to_exception | train | def map_http_status_to_exception(http_code):
"""
Bind a HTTP status to an HttpError.
:param http_code: The HTTP code
:type http_code: int
:return The HttpError that fits to the http_code or HttpError.
:rtype Any subclass of HttpError or HttpError
"""
htt... | python | {
"resource": ""
} |
q45261 | Ident.to_xml_string | train | def to_xml_string(self):
"""
Exports the element in XML format.
:returns: element in XML format.
:rtype: str
"""
self.update_xml_element()
xml = self.xml_element
return etree.tostring(xml, pretty_print=True).decode('utf-8') | python | {
"resource": ""
} |
q45262 | Draft.fetch | train | def fetch(self):
"""Fetch data corresponding to this draft and store it as ``self.data``."""
if self.message_id is None:
raise Exception(".message_id not set.")
response = self.session.request("find:Message.content", [ self.message_id ])
if response == None:
raise... | python | {
"resource": ""
} |
q45263 | Draft.save | train | def save(self):
"""Save current draft state."""
response = self.session.request("save:Message", [ self.data ])
self.data = response
self.message_id = self.data["id"]
return self | python | {
"resource": ""
} |
q45264 | Draft.send_preview | train | def send_preview(self): # pragma: no cover
"""Send a preview of this draft."""
response = self.session.request("method:queuePreview", [ self.data ])
self.data = response
return self | python | {
"resource": ""
} |
q45265 | Draft.send | train | def send(self): # pragma: no cover
"""Send the draft."""
response = self.session.request("method:queue", [ self.data ])
self.data = response
return self | python | {
"resource": ""
} |
q45266 | Draft.delete | train | def delete(self):
"""Delete the draft."""
response = self.session.request("delete:Message", [ self.message_id ])
self.data = response
return self | python | {
"resource": ""
} |
q45267 | _get_query_sets_for_object | train | def _get_query_sets_for_object(o):
"""
Determines the correct query set based on the object.
If the object is a literal, it will return a query set over LiteralStatements.
If the object is a URIRef or BNode, it will return a query set over Statements.
If the object is unknown, it will return both t... | python | {
"resource": ""
} |
q45268 | _get_named_graph | train | def _get_named_graph(context):
"""
Returns the named graph for this context.
"""
if context is None:
return None
return models.NamedGraph.objects.get_or_create(identifier=context.identifier)[0] | python | {
"resource": ""
} |
q45269 | DjangoStore.destroy | train | def destroy(self, configuration=None):
"""
Completely destroys a store and all the contexts and triples in the store.
>>> store = DjangoStore()
>>> g = rdflib.Graph(store=store)
>>> g.open(configuration=None, create=True) == rdflib.store.VALID_STORE
True
>>> g.op... | python | {
"resource": ""
} |
q45270 | DjangoStore.add | train | def add(self, (s, p, o), context, quoted=False):
"""
Adds a triple to the store.
>>> from rdflib.term import URIRef
>>> from rdflib.namespace import RDF
>>> subject = URIRef('http://zoowizard.org/resource/Artis')
>>> object = URIRef('http://schema.org/Zoo')
>>> ... | python | {
"resource": ""
} |
q45271 | DjangoStore.remove | train | def remove(self, (s, p, o), context=None):
"""
Removes a triple from the store.
"""
named_graph = _get_named_graph(context)
query_sets = _get_query_sets_for_object(o)
filter_parameters = dict()
if named_graph is not None:
filter_parameters['context_id... | python | {
"resource": ""
} |
q45272 | DjangoStore.triples | train | def triples(self, (s, p, o), context=None):
"""
Returns all triples in the current store.
"""
named_graph = _get_named_graph(context)
query_sets = _get_query_sets_for_object(o)
filter_parameters = dict()
if named_graph is not None:
filter_parameters['... | python | {
"resource": ""
} |
q45273 | Handler.load | train | def load(self):
"""load ALL_VERS_DATA from disk"""
basepath = os.path.dirname(os.path.abspath(__file__))
filename = os.sep.join([basepath, c.FOLDER_JSON, c.FILE_GAME_VERSIONS])
Handler.ALL_VERS_DATA = {} # reset known data; do not retain defunct information
with open(filename, "r... | python | {
"resource": ""
} |
q45274 | Handler.save | train | def save(self, new=None, timeout=2):
"""write ALL_VERS_DATA to disk in 'pretty' format"""
if new: self.update(new) # allow two operations (update + save) with a single command
if not self._updated: return # nothing to do
thisPkg = os.path.dirname(__file__)
filename = os.path.join... | python | {
"resource": ""
} |
q45275 | Handler.update | train | def update(self, data):
"""update known data with with newly provided data"""
if not isinstance(data, list): data = [data] # otherwise no conversion is necessary
master = Handler.ALL_VERS_DATA
for record in data:
#print(record)
for k,v in iteritems(record): # ensu... | python | {
"resource": ""
} |
q45276 | getLocalIPaddress | train | def getLocalIPaddress():
"""visible to other machines on LAN"""
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('google.com', 0))
my_local_ip = s.getsockname()[0] # takes ~0.005s
#from netifaces import interfaces, ifaddresses, AF_INET
#full solution i... | python | {
"resource": ""
} |
q45277 | getPublicIPaddress | train | def getPublicIPaddress(timeout=c.DEFAULT_TIMEOUT):
"""visible on public internet"""
start = time.time()
my_public_ip = None
e = Exception
while my_public_ip == None:
if time.time() - start > timeout:
break
try: #httpbin.org -- site is useful to test scripts / applications... | python | {
"resource": ""
} |
q45278 | bits_to_dict | train | def bits_to_dict(bits):
"""Convert a Django template tag's kwargs into a dictionary of Python types.
The only necessary types are number, boolean, list, and string.
http://pygments.org/docs/formatters/#HtmlFormatter
from: ["style='monokai'", "cssclass='cssclass',", "boolean='true',", 'num=0,', "list='... | python | {
"resource": ""
} |
q45279 | pygmentify | train | def pygmentify(value, **kwargs):
"""Return a highlighted code block with Pygments."""
soup = BeautifulSoup(value, 'html.parser')
for pre in soup.find_all('pre'):
# Get code
code = ''.join([to_string(item) for item in pre.contents])
code = code.replace('<', '<')
code = cod... | python | {
"resource": ""
} |
q45280 | _encode_multipart_formdata | train | def _encode_multipart_formdata(fields, files):
"""
Create a multipart encoded form for use in PUTing and POSTing.
fields is a sequence of (name, value) elements for regular form fields.
files is a sequence of (name, filename, value) elements for data to be uploaded as files
Return (content_type, bo... | python | {
"resource": ""
} |
q45281 | _generate_read_callable | train | def _generate_read_callable(name, display_name, arguments, regex, doc, supported):
"""
Returns a callable which conjures the URL for the resource and GETs a response
"""
def f(self, *args, **kwargs):
url = self._generate_url(regex, args)
if 'params' in kwargs:
url += "?" + ur... | python | {
"resource": ""
} |
q45282 | _generate_create_callable | train | def _generate_create_callable(name, display_name, arguments, regex, doc, supported, post_arguments, is_action):
"""
Returns a callable which conjures the URL for the resource and POSTs data
"""
def f(self, *args, **kwargs):
for key, value in args[-1].items():
if type(value) == file:
... | python | {
"resource": ""
} |
q45283 | Client.print_help | train | def print_help(self):
"""
Prints the api method info to stdout for debugging.
"""
keyfunc = lambda x: (x.resource_name, x.__doc__.strip())
resources = groupby(sorted(filter(lambda x: (hasattr(x, 'is_api_call') and
x.is_api_call... | python | {
"resource": ""
} |
q45284 | Client._construct_request | train | def _construct_request(self):
"""
Utility for constructing the request header and connection
"""
if self.parsed_endpoint.scheme == 'https':
conn = httplib.HTTPSConnection(self.parsed_endpoint.netloc)
else:
conn = httplib.HTTPConnection(self.parsed_endpoint... | python | {
"resource": ""
} |
q45285 | Client._delete_resource | train | def _delete_resource(self, url):
"""
DELETEs the resource at url
"""
conn, head = self._construct_request()
conn.request("DELETE", url, "", head)
resp = conn.getresponse()
self._handle_response_errors('DELETE', url, resp) | python | {
"resource": ""
} |
q45286 | Client._get_data | train | def _get_data(self, url, accept=None):
"""
GETs the resource at url and returns the raw response
If the accept parameter is not None, the request passes is as the Accept header
"""
if self.parsed_endpoint.scheme == 'https':
conn = httplib.HTTPSConnection(self.parsed_e... | python | {
"resource": ""
} |
q45287 | Client._put_or_post_multipart | train | def _put_or_post_multipart(self, method, url, data):
"""
encodes the data as a multipart form and PUTs or POSTs to the url
the response is parsed as JSON and the returns the resulting data structure
"""
fields = []
files = []
for key, value in data.items():
... | python | {
"resource": ""
} |
q45288 | Client._put_or_post_json | train | def _put_or_post_json(self, method, url, data):
"""
urlencodes the data and PUTs it to the url
the response is parsed as JSON and the resulting data type is returned
"""
if self.parsed_endpoint.scheme == 'https':
conn = httplib.HTTPSConnection(self.parsed_endpoint.net... | python | {
"resource": ""
} |
q45289 | find_importer_frame | train | def find_importer_frame():
"""Returns the outer frame importing this "end" module.
If this module is being imported by other means than import statement,
None is returned.
Returns:
A frame object or None.
"""
byte = lambda ch: ord(ch) if PY2 else ch
frame = inspect.currentframe()
... | python | {
"resource": ""
} |
q45290 | is_end_node | train | def is_end_node(node):
"""Checks if a node is the "end" keyword.
Args:
node: AST node.
Returns:
True if the node is the "end" keyword, otherwise False.
"""
return (isinstance(node, ast.Expr) and
isinstance(node.value, ast.Name) and
node.value.id == 'end') | python | {
"resource": ""
} |
q45291 | get_compound_bodies | train | def get_compound_bodies(node):
"""Returns a list of bodies of a compound statement node.
Args:
node: AST node.
Returns:
A list of bodies of the node. If the given node does not represent
a compound statement, an empty list is returned.
"""
if isinstance(node, (ast.Module, a... | python | {
"resource": ""
} |
q45292 | check_end_blocks | train | def check_end_blocks(frame):
"""Performs end-block check.
Args:
frame: A frame object of the module to be checked.
Raises:
SyntaxError: If check failed.
"""
try:
try:
module_name = frame.f_globals['__name__']
except KeyError:
warnings.warn(
... | python | {
"resource": ""
} |
q45293 | metadata_to_buffers | train | def metadata_to_buffers(metadata):
"""
Transform a dict of metadata into a sequence of buffers.
:param metadata: The metadata, as a dict.
:returns: A list of buffers.
"""
results = []
for key, value in metadata.items():
assert len(key) < 256
assert len(value) < 2 ** 32
... | python | {
"resource": ""
} |
q45294 | buffer_to_metadata | train | def buffer_to_metadata(buffer):
"""
Transform a buffer to a metadata dictionary.
:param buffer: The buffer, as received in a READY command.
:returns: A metadata dictionary, with its keys normalized (in
lowercase).
"""
offset = 0
size = len(buffer)
metadata = {}
while offset... | python | {
"resource": ""
} |
q45295 | Socket.generate_identity | train | def generate_identity(self):
"""
Generate a unique but random identity.
"""
identity = struct.pack('!BI', 0, self._base_identity)
self._base_identity += 1
if self._base_identity >= 2 ** 32:
self._base_identity = 0
return identity | python | {
"resource": ""
} |
q45296 | Socket._wait_peers | train | async def _wait_peers(self):
"""
Blocks until at least one non-dead peer is available.
"""
# Make sure we remove dead peers.
for p in self._peers[:]:
if p.dead:
self._peers.remove(p)
while not self._peers:
await self._peers.wait_no... | python | {
"resource": ""
} |
q45297 | Socket._fair_get_in_peer | train | async def _fair_get_in_peer(self):
"""
Get the first available available inbound peer in a fair manner.
:returns: A `Peer` inbox, whose inbox is guaranteed not to be
empty (and thus can be read from without blocking).
"""
peer = None
while not peer:
... | python | {
"resource": ""
} |
q45298 | Socket._fair_recv | train | async def _fair_recv(self):
"""
Receive from all the existing peers, rotating the list of peers every
time.
:returns: The frames.
"""
with await self._read_lock:
peer = await self._fair_get_in_peer()
result = peer.inbox.read_nowait()
retu... | python | {
"resource": ""
} |
q45299 | Socket._fair_get_out_peer | train | async def _fair_get_out_peer(self):
"""
Get the first available peer, with non-blocking inbox or wait until one
meets the condition.
:returns: The peer whose outbox is ready to be written to.
"""
peer = None
while not peer:
await self._wait_peers()
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.