_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q237100 | validate_path_parameters | train | def validate_path_parameters(target_path, api_path, path_parameters, context):
"""
Helper function for validating a request path
"""
base_path = context.get('basePath', '')
full_api_path = re.sub(NORMALIZE_SLASH_REGEX, '/', base_path + api_path)
parameter_values = get_path_parameter_values(
... | python | {
"resource": ""
} |
q237101 | construct_parameter_validators | train | def construct_parameter_validators(parameter, context):
"""
Constructs a dictionary of validator functions for the provided parameter
definition.
"""
validators = ValidationDict()
if '$ref' in parameter:
validators.add_validator(
'$ref', ParameterReferenceValidator(parameter[... | python | {
"resource": ""
} |
q237102 | construct_multi_parameter_validators | train | def construct_multi_parameter_validators(parameters, context):
"""
Given an iterable of parameters, returns a dictionary of validator
functions for each parameter. Note that this expects the parameters to be
unique in their name value, and throws an error if this is not the case.
"""
validators... | python | {
"resource": ""
} |
q237103 | generate_path_parameters_validator | train | def generate_path_parameters_validator(api_path, path_parameters, context):
"""
Generates a validator function that given a path, validates that it against
the path parameters
"""
path_parameter_validator = functools.partial(
validate_path_parameters,
api_path=api_path,
path_... | python | {
"resource": ""
} |
q237104 | escape_regex_special_chars | train | def escape_regex_special_chars(api_path):
"""
Turns the non prametrized path components into strings subtable for using
as a regex pattern. This primarily involves escaping special characters so
that the actual character is matched in the regex.
"""
def substitute(string, replacements):
... | python | {
"resource": ""
} |
q237105 | construct_parameter_pattern | train | def construct_parameter_pattern(parameter):
"""
Given a parameter definition returns a regex pattern that will match that
part of the path.
"""
name = parameter['name']
type = parameter['type']
repeated = '[^/]'
if type == 'integer':
repeated = '\d'
return "(?P<{name}>{rep... | python | {
"resource": ""
} |
q237106 | path_to_pattern | train | def path_to_pattern(api_path, parameters):
"""
Given an api path, possibly with parameter notation, return a pattern
suitable for turing into a regular expression which will match request
paths that conform to the parameter definitions and the api path.
"""
parts = re.split(PARAMETER_REGEX, api_... | python | {
"resource": ""
} |
q237107 | match_path_to_api_path | train | def match_path_to_api_path(path_definitions, target_path, base_path='',
context=None):
"""
Match a request or response path to one of the api paths.
Anything other than exactly one match is an error condition.
"""
if context is None:
context = {}
assert isinst... | python | {
"resource": ""
} |
q237108 | validate_request | train | def validate_request(request, schema):
"""
Request validation does the following steps.
1. validate that the path matches one of the defined paths in the schema.
2. validate that the request method conforms to a supported methods for the given path.
3. validate that the request parameters ... | python | {
"resource": ""
} |
q237109 | normalize_request | train | def normalize_request(request):
"""
Given a request, normalize it to the internal Request class.
"""
if isinstance(request, Request):
return request
for normalizer in REQUEST_NORMALIZERS:
try:
return normalizer(request)
except TypeError:
continue
... | python | {
"resource": ""
} |
q237110 | normalize_response | train | def normalize_response(response, request=None):
"""
Given a response, normalize it to the internal Response class. This also
involves normalizing the associated request object.
"""
if isinstance(response, Response):
return response
if request is not None and not isinstance(request, Requ... | python | {
"resource": ""
} |
q237111 | generate_header_validator | train | def generate_header_validator(headers, context, **kwargs):
"""
Generates a validation function that will validate a dictionary of headers.
"""
validators = ValidationDict()
for header_definition in headers:
header_processor = generate_value_processor(
context=context,
... | python | {
"resource": ""
} |
q237112 | generate_parameters_validator | train | def generate_parameters_validator(api_path, path_definition, parameters,
context, **kwargs):
"""
Generates a validator function to validate.
- request.path against the path parameters.
- request.query against the query parameters.
- request.headers against the head... | python | {
"resource": ""
} |
q237113 | partial_safe_wraps | train | def partial_safe_wraps(wrapped_func, *args, **kwargs):
"""
A version of `functools.wraps` that is safe to wrap a partial in.
"""
if isinstance(wrapped_func, functools.partial):
return partial_safe_wraps(wrapped_func.func)
else:
return functools.wraps(wrapped_func) | python | {
"resource": ""
} |
q237114 | skip_if_empty | train | def skip_if_empty(func):
"""
Decorator for validation functions which makes them pass if the value
passed in is the EMPTY sentinal value.
"""
@partial_safe_wraps(func)
def inner(value, *args, **kwargs):
if value is EMPTY:
return
else:
return func(value, *a... | python | {
"resource": ""
} |
q237115 | rewrite_reserved_words | train | def rewrite_reserved_words(func):
"""
Given a function whos kwargs need to contain a reserved word such as `in`,
allow calling that function with the keyword as `in_`, such that function
kwargs are rewritten to use the reserved word.
"""
@partial_safe_wraps(func)
def inner(*args, **kwargs):
... | python | {
"resource": ""
} |
q237116 | any_validator | train | def any_validator(obj, validators, **kwargs):
"""
Attempt multiple validators on an object.
- If any pass, then all validation passes.
- Otherwise, raise all of the errors.
"""
if not len(validators) > 1:
raise ValueError(
"any_validator requires at least 2 validator. Only ... | python | {
"resource": ""
} |
q237117 | _extract_to_tempdir | train | def _extract_to_tempdir(archive_filename):
"""extract the given tarball or zipfile to a tempdir and change
the cwd to the new tempdir. Delete the tempdir at the end"""
if not os.path.exists(archive_filename):
raise Exception("Archive '%s' does not exist" % (archive_filename))
tempdir = tempfile... | python | {
"resource": ""
} |
q237118 | _enter_single_subdir | train | def _enter_single_subdir(root_dir):
"""if the given directory has just a single subdir, enter that"""
current_cwd = os.getcwd()
try:
dest_dir = root_dir
dir_list = os.listdir(root_dir)
if len(dir_list) == 1:
first = os.path.join(root_dir, dir_list[0])
if os.pa... | python | {
"resource": ""
} |
q237119 | _set_file_encoding_utf8 | train | def _set_file_encoding_utf8(filename):
"""set a encoding header as suggested in PEP-0263. This
is not entirely correct because we don't know the encoding of the
given file but it's at least a chance to get metadata from the setup.py"""
with open(filename, 'r+') as f:
content = f.read()
f... | python | {
"resource": ""
} |
q237120 | _setup_py_run_from_dir | train | def _setup_py_run_from_dir(root_dir, py_interpreter):
"""run the extractmeta command via the setup.py in the given root_dir.
the output of extractmeta is json and is stored in a tempfile
which is then read in and returned as data"""
data = {}
with _enter_single_subdir(root_dir) as single_subdir:
... | python | {
"resource": ""
} |
q237121 | from_archive | train | def from_archive(archive_filename, py_interpreter=sys.executable):
"""extract metadata from a given sdist archive file
:param archive_filename: a sdist archive file
:param py_interpreter: The full path to the used python interpreter
:returns: a json blob with metadata
"""
with _extract_to_tempdir(... | python | {
"resource": ""
} |
q237122 | xmlns | train | def xmlns(source):
"""
Returns a map of prefix to namespace for the given XML file.
"""
namespaces = {}
events=("end", "start-ns", "end-ns")
for (event, elem) in iterparse(source, events):
if event == "start-ns":
prefix, ns = elem
namespaces[prefix] = ns
... | python | {
"resource": ""
} |
q237123 | create_block | train | def create_block(mc, block_id, subtype=None):
"""Build a block with the specified id and subtype under the player in the
Minecraft world. Subtype is optional and can be specified as None to use
the default subtype for the block.
"""
# Get player tile position and real position.
ptx, pty, ptz = ... | python | {
"resource": ""
} |
q237124 | PN532._busy_wait_ms | train | def _busy_wait_ms(self, ms):
"""Busy wait for the specified number of milliseconds."""
start = time.time()
delta = ms/1000.0
while (time.time() - start) <= delta:
pass | python | {
"resource": ""
} |
q237125 | PN532._write_frame | train | def _write_frame(self, data):
"""Write a frame to the PN532 with the specified data bytearray."""
assert data is not None and 0 < len(data) < 255, 'Data must be array of 1 to 255 bytes.'
# Build frame to send as:
# - SPI data write (0x01)
# - Preamble (0x00)
# - Start cod... | python | {
"resource": ""
} |
q237126 | PN532._read_data | train | def _read_data(self, count):
"""Read a specified count of bytes from the PN532."""
# Build a read request frame.
frame = bytearray(count)
frame[0] = PN532_SPI_DATAREAD
# Send the frame and return the response, ignoring the SPI header byte.
self._gpio.set_low(self._cs)
... | python | {
"resource": ""
} |
q237127 | PN532._read_frame | train | def _read_frame(self, length):
"""Read a response frame from the PN532 of at most length bytes in size.
Returns the data inside the frame if found, otherwise raises an exception
if there is an error parsing the frame. Note that less than length bytes
might be returned!
"""
... | python | {
"resource": ""
} |
q237128 | PN532._wait_ready | train | def _wait_ready(self, timeout_sec=1):
"""Wait until the PN532 is ready to receive commands. At most wait
timeout_sec seconds for the PN532 to be ready. If the PN532 is ready
before the timeout is exceeded then True will be returned, otherwise
False is returned when the timeout is excee... | python | {
"resource": ""
} |
q237129 | PN532.call_function | train | def call_function(self, command, response_length=0, params=[], timeout_sec=1):
"""Send specified command to the PN532 and expect up to response_length
bytes back in a response. Note that less than the expected bytes might
be returned! Params can optionally specify an array of bytes to send as
... | python | {
"resource": ""
} |
q237130 | PN532.begin | train | def begin(self):
"""Initialize communication with the PN532. Must be called before any
other calls are made against the PN532.
"""
# Assert CS pin low for a second for PN532 to be ready.
self._gpio.set_low(self._cs)
time.sleep(1.0)
# Call GetFirmwareVersion to sy... | python | {
"resource": ""
} |
q237131 | PN532.get_firmware_version | train | def get_firmware_version(self):
"""Call PN532 GetFirmwareVersion function and return a tuple with the IC,
Ver, Rev, and Support values.
"""
response = self.call_function(PN532_COMMAND_GETFIRMWAREVERSION, 4)
if response is None:
raise RuntimeError('Failed to detect the... | python | {
"resource": ""
} |
q237132 | PN532.read_passive_target | train | def read_passive_target(self, card_baud=PN532_MIFARE_ISO14443A, timeout_sec=1):
"""Wait for a MiFare card to be available and return its UID when found.
Will wait up to timeout_sec seconds and return None if no card is found,
otherwise a bytearray with the UID of the found card is returned.
... | python | {
"resource": ""
} |
q237133 | PN532.mifare_classic_read_block | train | def mifare_classic_read_block(self, block_number):
"""Read a block of data from the card. Block number should be the block
to read. If the block is successfully read a bytearray of length 16 with
data starting at the specified block will be returned. If the block is
not read then None... | python | {
"resource": ""
} |
q237134 | PN532.mifare_classic_write_block | train | def mifare_classic_write_block(self, block_number, data):
"""Write a block of data to the card. Block number should be the block
to write and data should be a byte array of length 16 with the data to
write. If the data is successfully written then True is returned,
otherwise False is r... | python | {
"resource": ""
} |
q237135 | _dirmatch | train | def _dirmatch(path, matchwith):
"""Check if path is within matchwith's tree.
>>> _dirmatch('/home/foo/bar', '/home/foo/bar')
True
>>> _dirmatch('/home/foo/bar/', '/home/foo/bar')
True
>>> _dirmatch('/home/foo/bar/etc', '/home/foo/bar')
True
>>> _dirmatch('/home/foo/bar2', '/home/foo/bar... | python | {
"resource": ""
} |
q237136 | _virtualenv_sys | train | def _virtualenv_sys(venv_path):
"obtain version and path info from a virtualenv."
executable = os.path.join(venv_path, env_bin_dir, 'python')
# Must use "executable" as the first argument rather than as the
# keyword argument "executable" to get correct value from sys.path
p = subprocess.Popen([exec... | python | {
"resource": ""
} |
q237137 | int_to_ef | train | def int_to_ef(n):
"""This is here for testing support but, in practice, this isn't very
useful as many of the flags are just combinations of other flags. The
relationships are defined by the OS in ways that aren't semantically
intuitive to this project.
"""
flags = {}
for name, value in lib... | python | {
"resource": ""
} |
q237138 | _enumerator | train | def _enumerator(opener, entry_cls, format_code=None, filter_code=None):
"""Return an archive enumerator from a user-defined source, using a user-
defined entry type.
"""
archive_res = _archive_read_new()
try:
r = _set_read_context(archive_res, format_code, filter_code)
opener(archi... | python | {
"resource": ""
} |
q237139 | file_enumerator | train | def file_enumerator(filepath, block_size=10240, *args, **kwargs):
"""Return an enumerator that knows how to read a physical file."""
_LOGGER.debug("Enumerating through archive file: %s", filepath)
def opener(archive_res):
_LOGGER.debug("Opening from file (file_enumerator): %s", filepath)
_... | python | {
"resource": ""
} |
q237140 | memory_enumerator | train | def memory_enumerator(buffer_, *args, **kwargs):
"""Return an enumerator that knows how to read raw memory."""
_LOGGER.debug("Enumerating through (%d) bytes of archive data.",
len(buffer_))
def opener(archive_res):
_LOGGER.debug("Opening from (%d) bytes (memory_enumerator).",
... | python | {
"resource": ""
} |
q237141 | _pour | train | def _pour(opener, flags=0, *args, **kwargs):
"""A flexible pouring facility that knows how to enumerate entry data."""
with _enumerator(opener,
*args,
entry_cls=_ArchiveEntryItState,
**kwargs) as r:
ext = libarchive.calls.archive_write.c_ar... | python | {
"resource": ""
} |
q237142 | file_pour | train | def file_pour(filepath, block_size=10240, *args, **kwargs):
"""Write physical files from entries."""
def opener(archive_res):
_LOGGER.debug("Opening from file (file_pour): %s", filepath)
_archive_read_open_filename(archive_res, filepath, block_size)
return _pour(opener, *args, flags=0, **k... | python | {
"resource": ""
} |
q237143 | memory_pour | train | def memory_pour(buffer_, *args, **kwargs):
"""Yield data from entries."""
def opener(archive_res):
_LOGGER.debug("Opening from (%d) bytes (memory_pour).", len(buffer_))
_archive_read_open_memory(archive_res, buffer_)
return _pour(opener, *args, flags=0, **kwargs) | python | {
"resource": ""
} |
q237144 | _archive_write_data | train | def _archive_write_data(archive, data):
"""Write data to archive. This will only be called with a non-empty string.
"""
n = libarchive.calls.archive_write.c_archive_write_data(
archive,
ctypes.cast(ctypes.c_char_p(data), ctypes.c_void_p),
len(data))
if n == 0:
... | python | {
"resource": ""
} |
q237145 | Adafruit_BME280._write_ctrl_meas | train | def _write_ctrl_meas(self):
"""
Write the values to the ctrl_meas and ctrl_hum registers in the device
ctrl_meas sets the pressure and temperature data acquistion options
ctrl_hum sets the humidty oversampling and must be written to first
"""
self._write_register_byte(_BM... | python | {
"resource": ""
} |
q237146 | Adafruit_BME280._write_config | train | def _write_config(self):
"""Write the value to the config register in the device """
normal_flag = False
if self._mode == MODE_NORMAL:
#Writes to the config register may be ignored while in Normal mode
normal_flag = True
self.mode = MODE_SLEEP #So we switch to... | python | {
"resource": ""
} |
q237147 | Adafruit_BME280._config | train | def _config(self):
"""Value to be written to the device's config register """
config = 0
if self.mode == MODE_NORMAL:
config += (self._t_standby << 5)
if self._iir_filter:
config += (self._iir_filter << 2)
return config | python | {
"resource": ""
} |
q237148 | Adafruit_BME280._ctrl_meas | train | def _ctrl_meas(self):
"""Value to be written to the device's ctrl_meas register """
ctrl_meas = (self.overscan_temperature << 5)
ctrl_meas += (self.overscan_pressure << 2)
ctrl_meas += self.mode
return ctrl_meas | python | {
"resource": ""
} |
q237149 | Adafruit_BME280.measurement_time_typical | train | def measurement_time_typical(self):
"""Typical time in milliseconds required to complete a measurement in normal mode"""
meas_time_ms = 1.0
if self.overscan_temperature != OVERSCAN_DISABLE:
meas_time_ms += (2 * _BME280_OVERSCANS.get(self.overscan_temperature))
if self.oversca... | python | {
"resource": ""
} |
q237150 | Adafruit_BME280.pressure | train | def pressure(self):
"""
The compensated pressure in hectoPascals.
returns None if pressure measurement is disabled
"""
self._read_temperature()
# Algorithm from the BME280 driver
# https://github.com/BoschSensortec/BME280_driver/blob/master/bme280.c
adc =... | python | {
"resource": ""
} |
q237151 | Adafruit_BME280.humidity | train | def humidity(self):
"""
The relative humidity in RH %
returns None if humidity measurement is disabled
"""
self._read_temperature()
hum = self._read_register(_BME280_REGISTER_HUMIDDATA, 2)
#print("Humidity data: ", hum)
adc = float(hum[0] << 8 | hum[1])
... | python | {
"resource": ""
} |
q237152 | Adafruit_BME280._read_coefficients | train | def _read_coefficients(self):
"""Read & save the calibration coefficients"""
coeff = self._read_register(_BME280_REGISTER_DIG_T1, 24)
coeff = list(struct.unpack('<HhhHhhhhhhhh', bytes(coeff)))
coeff = [float(i) for i in coeff]
self._temp_calib = coeff[:3]
self._pressure_c... | python | {
"resource": ""
} |
q237153 | Adafruit_BME280._read24 | train | def _read24(self, register):
"""Read an unsigned 24-bit value as a floating point and return it."""
ret = 0.0
for b in self._read_register(register, 3):
ret *= 256.0
ret += float(b & 0xFF)
return ret | python | {
"resource": ""
} |
q237154 | Index._create | train | def _create(self, postData) :
"""Creates an index of any type according to postData"""
if self.infos is None :
r = self.connection.session.post(self.indexesURL, params = {"collection" : self.collection.name}, data = json.dumps(postData, default=str))
data = r.json()
i... | python | {
"resource": ""
} |
q237155 | Graph.createVertex | train | def createVertex(self, collectionName, docAttributes, waitForSync = False) :
"""adds a vertex to the graph and returns it"""
url = "%s/vertex/%s" % (self.URL, collectionName)
store = DOC.DocumentStore(self.database[collectionName], validators=self.database[collectionName]._fields, initDct=docAt... | python | {
"resource": ""
} |
q237156 | Graph.deleteVertex | train | def deleteVertex(self, document, waitForSync = False) :
"""deletes a vertex from the graph as well as al linked edges"""
url = "%s/vertex/%s" % (self.URL, document._id)
r = self.connection.session.delete(url, params = {'waitForSync' : waitForSync})
data = r.json()
if r.status_co... | python | {
"resource": ""
} |
q237157 | Graph.createEdge | train | def createEdge(self, collectionName, _fromId, _toId, edgeAttributes, waitForSync = False) :
"""creates an edge between two documents"""
if not _fromId :
raise ValueError("Invalid _fromId: %s" % _fromId)
if not _toId :
raise ValueError("Invalid _toId: %s" % _toId)
... | python | {
"resource": ""
} |
q237158 | Graph.link | train | def link(self, definition, doc1, doc2, edgeAttributes, waitForSync = False) :
"A shorthand for createEdge that takes two documents as input"
if type(doc1) is DOC.Document :
if not doc1._id :
doc1.save()
doc1_id = doc1._id
else :
doc1_id = doc1
... | python | {
"resource": ""
} |
q237159 | Graph.unlink | train | def unlink(self, definition, doc1, doc2) :
"deletes all links between doc1 and doc2"
links = self.database[definition].fetchByExample( {"_from": doc1._id,"_to" : doc2._id}, batchSize = 100)
for l in links :
self.deleteEdge(l) | python | {
"resource": ""
} |
q237160 | Graph.deleteEdge | train | def deleteEdge(self, edge, waitForSync = False) :
"""removes an edge from the graph"""
url = "%s/edge/%s" % (self.URL, edge._id)
r = self.connection.session.delete(url, params = {'waitForSync' : waitForSync})
if r.status_code == 200 or r.status_code == 202 :
return True
... | python | {
"resource": ""
} |
q237161 | DocumentCache.delete | train | def delete(self, _key) :
"removes a document from the cache"
try :
doc = self.cacheStore[_key]
doc.prev.nextDoc = doc.nextDoc
doc.nextDoc.prev = doc.prev
del(self.cacheStore[_key])
except KeyError :
raise KeyError("Document with _key %s... | python | {
"resource": ""
} |
q237162 | DocumentCache.getChain | train | def getChain(self) :
"returns a list of keys representing the chain of documents"
l = []
h = self.head
while h :
l.append(h._key)
h = h.nextDoc
return l | python | {
"resource": ""
} |
q237163 | Field.validate | train | def validate(self, value) :
"""checks the validity of 'value' given the lits of validators"""
for v in self.validators :
v.validate(value)
return True | python | {
"resource": ""
} |
q237164 | Collection_metaclass.getCollectionClass | train | def getCollectionClass(cls, name) :
"""Return the class object of a collection given its 'name'"""
try :
return cls.collectionClasses[name]
except KeyError :
raise KeyError( "There is no Collection Class of type: '%s'; currently supported values: [%s]" % (name, ', '.join(... | python | {
"resource": ""
} |
q237165 | Collection_metaclass.isDocumentCollection | train | def isDocumentCollection(cls, name) :
"""return true or false wether 'name' is the name of a document collection."""
try :
col = cls.getCollectionClass(name)
return issubclass(col, Collection)
except KeyError :
return False | python | {
"resource": ""
} |
q237166 | Collection_metaclass.isEdgeCollection | train | def isEdgeCollection(cls, name) :
"""return true or false wether 'name' is the name of an edge collection."""
try :
col = cls.getCollectionClass(name)
return issubclass(col, Edges)
except KeyError :
return False | python | {
"resource": ""
} |
q237167 | Collection.getIndexes | train | def getIndexes(self) :
"""Fills self.indexes with all the indexes associates with the collection and returns it"""
url = "%s/index" % self.database.URL
r = self.connection.session.get(url, params = {"collection": self.name})
data = r.json()
for ind in data["indexes"] :
... | python | {
"resource": ""
} |
q237168 | Collection.delete | train | def delete(self) :
"""deletes the collection from the database"""
r = self.connection.session.delete(self.URL)
data = r.json()
if not r.status_code == 200 or data["error"] :
raise DeletionError(data["errorMessage"], data) | python | {
"resource": ""
} |
q237169 | Collection.createDocument | train | def createDocument(self, initDict = None) :
"""create and returns a document populated with the defaults or with the values in initDict"""
if initDict is not None :
return self.createDocument_(initDict)
else :
if self._validation["on_load"] :
self._validat... | python | {
"resource": ""
} |
q237170 | Collection.createDocument_ | train | def createDocument_(self, initDict = None) :
"create and returns a completely empty document or one populated with initDict"
if initDict is None :
initV = {}
else :
initV = initDict
return self.documentClass(self, initV) | python | {
"resource": ""
} |
q237171 | Collection.ensureHashIndex | train | def ensureHashIndex(self, fields, unique = False, sparse = True, deduplicate = False) :
"""Creates a hash index if it does not already exist, and returns it"""
data = {
"type" : "hash",
"fields" : fields,
"unique" : unique,
"sparse" : sparse,
"... | python | {
"resource": ""
} |
q237172 | Collection.ensureGeoIndex | train | def ensureGeoIndex(self, fields) :
"""Creates a geo index if it does not already exist, and returns it"""
data = {
"type" : "geo",
"fields" : fields,
}
ind = Index(self, creationData = data)
self.indexes["geo"][ind.infos["id"]] = ind
return ind | python | {
"resource": ""
} |
q237173 | Collection.ensureFulltextIndex | train | def ensureFulltextIndex(self, fields, minLength = None) :
"""Creates a fulltext index if it does not already exist, and returns it"""
data = {
"type" : "fulltext",
"fields" : fields,
}
if minLength is not None :
data["minLength"] = minLength
i... | python | {
"resource": ""
} |
q237174 | Collection.validatePrivate | train | def validatePrivate(self, field, value) :
"""validate a private field value"""
if field not in self.arangoPrivates :
raise ValueError("%s is not a private field of collection %s" % (field, self))
if field in self._fields :
self._fields[field].validate(value)
retu... | python | {
"resource": ""
} |
q237175 | Collection.simpleQuery | train | def simpleQuery(self, queryType, rawResults = False, **queryArgs) :
"""General interface for simple queries. queryType can be something like 'all', 'by-example' etc... everything is in the arango doc.
If rawResults, the query will return dictionaries instead of Document objetcs.
"""
retu... | python | {
"resource": ""
} |
q237176 | Collection.action | train | def action(self, method, action, **params) :
"""a generic fct for interacting everything that doesn't have an assigned fct"""
fct = getattr(self.connection.session, method.lower())
r = fct(self.URL + "/" + action, params = params)
return r.json() | python | {
"resource": ""
} |
q237177 | Collection.bulkSave | train | def bulkSave(self, docs, onDuplicate="error", **params) :
"""Parameter docs must be either an iterrable of documents or dictionnaries.
This function will return the number of documents, created and updated, and will raise an UpdateError exception if there's at least one error.
params are any par... | python | {
"resource": ""
} |
q237178 | Edges.getEdges | train | def getEdges(self, vertex, inEdges = True, outEdges = True, rawResults = False) :
"""returns in, out, or both edges liked to a given document. vertex can be either a Document object or a string for an _id.
If rawResults a arango results will be return as fetched, if false, will return a liste of Edge ob... | python | {
"resource": ""
} |
q237179 | Database.reloadCollections | train | def reloadCollections(self) :
"reloads the collection list."
r = self.connection.session.get(self.collectionsURL)
data = r.json()
if r.status_code == 200 :
self.collections = {}
for colData in data["result"] :
colName = colData['name']
... | python | {
"resource": ""
} |
q237180 | Database.reloadGraphs | train | def reloadGraphs(self) :
"reloads the graph list"
r = self.connection.session.get(self.graphsURL)
data = r.json()
if r.status_code == 200 :
self.graphs = {}
for graphData in data["graphs"] :
try :
self.graphs[graphData["_key"]] ... | python | {
"resource": ""
} |
q237181 | Database.createGraph | train | def createGraph(self, name, createCollections = True, isSmart = False, numberOfShards = None, smartGraphAttribute = None) :
"""Creates a graph and returns it. 'name' must be the name of a class inheriting from Graph.
Checks will be performed to make sure that every collection mentionned in the edges def... | python | {
"resource": ""
} |
q237182 | Database.validateAQLQuery | train | def validateAQLQuery(self, query, bindVars = None, options = None) :
"returns the server answer is the query is valid. Raises an AQLQueryError if not"
if bindVars is None :
bindVars = {}
if options is None :
options = {}
payload = {'query' : query, 'bindVars' : bi... | python | {
"resource": ""
} |
q237183 | Database.transaction | train | def transaction(self, collections, action, waitForSync = False, lockTimeout = None, params = None) :
"""Execute a server-side transaction"""
payload = {
"collections": collections,
"action": action,
"waitForSync": waitForSync}
if lockTimeout is not... | python | {
"resource": ""
} |
q237184 | DocumentStore.getPatches | train | def getPatches(self) :
"""get patches as a dictionary"""
if not self.mustValidate :
return self.getStore()
res = {}
res.update(self.patchStore)
for k, v in self.subStores.items() :
res[k] = v.getPatches()
return res | python | {
"resource": ""
} |
q237185 | DocumentStore.getStore | train | def getStore(self) :
"""get the inner store as dictionary"""
res = {}
res.update(self.store)
for k, v in self.subStores.items() :
res[k] = v.getStore()
return res | python | {
"resource": ""
} |
q237186 | DocumentStore.validateField | train | def validateField(self, field) :
"""Validatie a field"""
if field not in self.validators and not self.collection._validation['allow_foreign_fields'] :
raise SchemaViolation(self.collection.__class__, field)
if field in self.store:
if isinstance(self.store[field], Documen... | python | {
"resource": ""
} |
q237187 | DocumentStore.validate | train | def validate(self) :
"""Validate the whole document"""
if not self.mustValidate :
return True
res = {}
for field in self.validators.keys() :
try :
if isinstance(self.validators[field], dict) and field not in self.store :
self.s... | python | {
"resource": ""
} |
q237188 | DocumentStore.set | train | def set(self, dct) :
"""Set the store using a dictionary"""
# if not self.mustValidate :
# self.store = dct
# self.patchStore = dct
# return
for field, value in dct.items() :
if field not in self.collection.arangoPrivates :
if isin... | python | {
"resource": ""
} |
q237189 | Document.reset | train | def reset(self, collection, jsonFieldInit = None) :
if not jsonFieldInit:
jsonFieldInit = {}
"""replaces the current values in the document by those in jsonFieldInit"""
self.collection = collection
self.connection = self.collection.connection
self.documentsURL = self.... | python | {
"resource": ""
} |
q237190 | Document.validate | train | def validate(self) :
"""validate the document"""
self._store.validate()
for pField in self.collection.arangoPrivates :
self.collection.validatePrivate(pField, getattr(self, pField)) | python | {
"resource": ""
} |
q237191 | Document.setPrivates | train | def setPrivates(self, fieldDict) :
"""will set self._id, self._rev and self._key field."""
for priv in self.privates :
if priv in fieldDict :
setattr(self, priv, fieldDict[priv])
else :
setattr(self, priv, None)
if self._i... | python | {
"resource": ""
} |
q237192 | Document.patch | train | def patch(self, keepNull = True, **docArgs) :
"""Saves the document by only updating the modified fields.
The default behaviour concening the keepNull parameter is the opposite of ArangoDB's default, Null values won't be ignored
Use docArgs for things such as waitForSync = True"""
if se... | python | {
"resource": ""
} |
q237193 | Document.delete | train | def delete(self) :
"deletes the document from the database"
if self.URL is None :
raise DeletionError("Can't delete a document that was not saved")
r = self.connection.session.delete(self.URL)
data = r.json()
if (r.status_code != 200 and r.status_code != 202) or 'err... | python | {
"resource": ""
} |
q237194 | Document.getEdges | train | def getEdges(self, edges, inEdges = True, outEdges = True, rawResults = False) :
"""returns in, out, or both edges linked to self belonging the collection 'edges'.
If rawResults a arango results will be return as fetched, if false, will return a liste of Edge objects"""
try :
return ... | python | {
"resource": ""
} |
q237195 | Document.getStore | train | def getStore(self) :
"""return the store in a dict format"""
store = self._store.getStore()
for priv in self.privates :
v = getattr(self, priv)
if v :
store[priv] = v
return store | python | {
"resource": ""
} |
q237196 | Edge.links | train | def links(self, fromVertice, toVertice, **edgeArgs) :
"""
An alias to save that updates the _from and _to attributes.
fromVertice and toVertice, can be either strings or documents. It they are unsaved documents, they will be automatically saved.
"""
if isinstance(fromVertice, Doc... | python | {
"resource": ""
} |
q237197 | User._set | train | def _set(self, jsonData) :
"""Initialize all fields at once. If no password is specified, it will be set as an empty string"""
self["username"] = jsonData["user"]
self["active"] = jsonData["active"]
self["extra"] = jsonData["extra"]
try:
self["changePassword"... | python | {
"resource": ""
} |
q237198 | User.delete | train | def delete(self) :
"""Permanently remove the user"""
if not self.URL :
raise CreationError("Please save user first", None, None)
r = self.connection.session.delete(self.URL)
if r.status_code < 200 or r.status_code > 202 :
raise DeletionError("Unable to delete use... | python | {
"resource": ""
} |
q237199 | Users.fetchAllUsers | train | def fetchAllUsers(self, rawResults = False) :
"""Returns all available users. if rawResults, the result will be a list of python dicts instead of User objects"""
r = self.connection.session.get(self.URL)
if r.status_code == 200 :
data = r.json()
if rawResults :
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.