Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def deregister(self, event, fn):
if event in self._handler_dict and fn in self._handler_dict[event]:
self._handler_dict[event].remove(fn) | [
"\n Deregister the handler function from the given event.\n "
] |
Please provide a description of the function:def deregister_all(self, *events):
if events:
for event in events:
self._handler_dict[event] = []
else:
self._handler_dict = {} | [
"\n Deregisters all handler functions, or those registered against the given event(s).\n "
] |
Please provide a description of the function:def unpack_scope(cls, scope):
query = {}
projection = {}
options = {}
if isinstance(scope, tuple):
if len(scope) > 3:
raise ValueError("Invalid scope")
if len(scope) >= 1:
query... | [
"Unpacks the response from a scope function. The function should return\n either a query, a query and a projection, or a query a projection and\n an query options hash."
] |
Please provide a description of the function:def register_fn(cls, f):
def inner(self, *args, **kwargs):
try:
query, projection, options = cls.unpack_scope(f(*args, **kwargs))
new_query = deepcopy(self.query)
new_projection = deepcopy(self.proj... | [
"Registers a scope function on this builder."
] |
Please provide a description of the function:def cursor(self):
if not self._active_cursor:
self._active_cursor = self.model.find(self.query,
self.projection or None,
**self.options)
r... | [
"\n Returns a cursor for the currently assembled query, creating it if\n it doesn't already exist.\n "
] |
Please provide a description of the function:def _ensure_object_id(cls, id):
if isinstance(id, ObjectId):
return id
if isinstance(id, basestring) and OBJECTIDEXPR.match(id):
return ObjectId(id)
return id | [
"Checks whether the given id is an ObjectId instance, and if not wraps it."
] |
Please provide a description of the function:def apply_defaults(self):
self.emit('will_apply_defaults')
self.schema.apply_defaults(self)
self.emit('did_apply_defaults') | [
"Apply schema defaults to this document."
] |
Please provide a description of the function:def find_by_id(cls, id):
obj = cls.find_one(cls._id_spec(id))
if not obj:
raise NotFoundException(cls.collection, id)
return obj | [
"\n Finds a single document by its ID. Throws a\n NotFoundException if the document does not exist (the\n assumption being if you've got an id you should be\n pretty certain the thing exists)\n "
] |
Please provide a description of the function:def reload(self):
self.emit('will_reload')
self.populate(self.collection.find_one(type(self)._id_spec(self['_id'])))
self.emit('did_reload') | [
"Reloads the current model's data from the underlying\n database record, updating it in-place."
] |
Please provide a description of the function:def on(cls, event, handler_func=None):
if handler_func:
cls.handler_registrar().register(event, handler_func)
return
def register(fn):
cls.handler_registrar().register(event, fn)
return fn
ret... | [
"\n Registers a handler function whenever an instance of the model\n emits the given event.\n\n This method can either called directly, passing a function reference:\n\n MyModel.on('did_save', my_function)\n\n ...or as a decorator of the function to be registered.\n\n ... |
Please provide a description of the function:def _emit(self, event, document, *args, **kwargs):
self.handler_registrar().apply(event, document, *args, **kwargs) | [
"\n Inner version of emit which passes the given document as the\n primary argument to handler functions.\n "
] |
Please provide a description of the function:def emit(self, event, *args, **kwargs):
self._emit(event, self, *args, **kwargs) | [
"\n Emits an event call to all handler functions registered against\n this model's class and the given event type.\n "
] |
Please provide a description of the function:def static_method(cls, f):
setattr(cls, f.__name__, staticmethod(f))
return f | [
"Decorator which dynamically binds static methods to the model for later use."
] |
Please provide a description of the function:def class_method(cls, f):
setattr(cls, f.__name__, classmethod(f))
return f | [
"Decorator which dynamically binds class methods to the model for later use."
] |
Please provide a description of the function:def scope(cls, f):
if not hasattr(cls, "scopes"):
cls.scopes = copy(STANDARD_SCOPES)
cls.scopes.append(f)
def create_builder(self, *args, **kwargs):
bldr = ScopeBuilder(cls, cls.scopes)
return getattr(bld... | [
"Decorator which can dynamically attach a query scope to the model."
] |
Please provide a description of the function:def _module_name_from_previous_frame(num_frames_back):
frm = inspect.stack()[num_frames_back + 1]
return inspect.getmodule(frm[0]).__name__ | [
"\n Returns the module name associated with a frame `num_frames_back` in the\n call stack. This function adds 1 to account for itself, so `num_frames_back`\n should be given relative to the caller.\n "
] |
Please provide a description of the function:def create_model(schema, collection, class_name=None):
if not class_name:
class_name = camelize(str(collection.name))
model_class = type(class_name,
(Model,),
dict(schema=schema, _collection_factory=staticme... | [
"\n Main entry point to creating a new mongothon model. Both\n schema and Pymongo collection objects must be provided.\n\n Returns a new class which can be used as a model class.\n\n The class name of the model class by default is inferred\n from the provided collection (converted to camel case).\n ... |
Please provide a description of the function:def create_model_offline(schema, collection_factory, class_name):
model_class = type(class_name,
(Model,),
dict(schema=schema, _collection_factory=staticmethod(collection_factory)))
# Since we are dynamically creati... | [
"\n Entry point for creating a new Mongothon model without instantiating\n a database connection. The collection is instead provided through a closure\n that is resolved upon the model's first database access.\n "
] |
Please provide a description of the function:def wrap(value):
if isinstance(value, Document) or isinstance(value, DocumentList):
return value
elif isinstance(value, dict):
return Document(value)
elif isinstance(value, list):
return DocumentList(value)
else:
return va... | [
"\n Wraps the given value in a Document or DocumentList as applicable.\n "
] |
Please provide a description of the function:def unwrap(value):
if isinstance(value, Document):
return value.to_dict()
elif isinstance(value, DocumentList):
return value.to_list()
else:
return value | [
"\n Unwraps the given Document or DocumentList as applicable.\n "
] |
Please provide a description of the function:def note_change(self, key, value):
# If we're changing the value and we haven't done so already, note it.
if value != self._instance[key] and key not in self._previous and key not in self._added:
self._previous[key] = self._instance[key]
... | [
"\n Updates change state to reflect a change to a field. Takes care of ignoring\n no-ops, reversions and takes appropriate steps if the field was previously\n deleted or added to ensure the change state purely reflects the diff since\n last reset.\n "
] |
Please provide a description of the function:def note_addition(self, key, value):
# If we're adding a field we previously deleted, remove the deleted note.
if key in self._deleted:
# If the key we're adding back has a different value, then it's a change
if value != self.... | [
"\n Updates the change state to reflect the addition of a field. Detects previous\n changes and deletions of the field and acts accordingly.\n "
] |
Please provide a description of the function:def note_deletion(self, key):
# If we'rew deleting a key we previously added, then there is no diff
if key in self._added:
self._added.remove(key)
else:
# If the deleted key was previously changed, use the original val... | [
"\n Notes the deletion of a field.\n "
] |
Please provide a description of the function:def changes(self):
return {key: (self._previous[key], self._instance[key])
for key in self._previous} | [
"\n Returns a dict containing just the fields which have changed on this\n Document since it was created or last saved, together with both their\n previous and current values\n\n doc['name'] # => 'bob'\n doc['name'] = 'clive'\n doc.changes ... |
Please provide a description of the function:def reset_all_changes(self):
self.reset_changes()
for value in self.values():
if isinstance(value, Document) or isinstance(value, DocumentList):
value.reset_all_changes() | [
"\n Resets change tracking in this document, recursing into child Documents and\n DocumentLists.\n "
] |
Please provide a description of the function:def populate(self, other):
self.clear()
self.update(other)
self.reset_all_changes() | [
"Like update, but clears the contents first."
] |
Please provide a description of the function:def parse(self, buffer):
log.debug("parsing a %d byte packet" % len(buffer))
(opcode,) = struct.unpack(str("!H"), buffer[:2])
log.debug("opcode is %d" % opcode)
packet = self.__create(opcode)
packet.buffer = buffer
ret... | [
"This method is used to parse an existing datagram into its\n corresponding TftpPacket object. The buffer is the raw bytes off of\n the network."
] |
Please provide a description of the function:def __create(self, opcode):
tftpassert(opcode in self.classes,
"Unsupported opcode: %d" % opcode)
packet = self.classes[opcode]()
return packet | [
"This method returns the appropriate class object corresponding to\n the passed opcode."
] |
Please provide a description of the function:def add_dup(self, pkt):
log.debug("Recording a dup of %s", pkt)
s = str(pkt)
if s in self.dups:
self.dups[s] += 1
else:
self.dups[s] = 1
tftpassert(self.dups[s] < MAX_DUPS, "Max duplicates reached") | [
"This method adds a dup for a packet to the metrics."
] |
Please provide a description of the function:def checkTimeout(self, now):
log.debug("checking for timeout on session %s", self)
if now - self.last_update > self.timeout:
raise TftpTimeout("Timeout waiting for traffic") | [
"Compare current time with last_update time, and raise an exception\n if we're over the timeout time."
] |
Please provide a description of the function:def end(self, close_fileobj=True):
log.debug("in TftpContext.end - closing socket")
self.sock.close()
if close_fileobj and self.fileobj is not None and not self.fileobj.closed:
log.debug("self.fileobj is open - closing")
... | [
"Perform session cleanup, since the end method should always be\n called explicitely by the calling code, this works better than the\n destructor.\n Set close_fileobj to False so fileobj can be returned open."
] |
Please provide a description of the function:def sethost(self, host):
self.__host = host
self.address = socket.gethostbyname(host) | [
"Setter method that also sets the address property as a result\n of the host that is set."
] |
Please provide a description of the function:def cycle(self):
try:
(buffer, (raddress, rport)) = self.sock.recvfrom(MAX_BLKSIZE)
except socket.timeout:
log.warning("Timeout waiting for traffic, retrying...")
raise TftpTimeout("Timed-out waiting for traffic")
... | [
"Here we wait for a response from the server after sending it\n something, and dispatch appropriate action to that response."
] |
Please provide a description of the function:def start(self, buffer):
log.debug("In TftpContextServer.start")
self.metrics.start_time = time.time()
log.debug("Set metrics.start_time to %s", self.metrics.start_time)
# And update our last updated time.
self.last_update = t... | [
"Start the state cycle. Note that the server context receives an\n initial packet in its start method. Also note that the server does not\n loop on cycle(), as it expects the TftpServer object to manage\n that."
] |
Please provide a description of the function:def start(self):
log.info("Sending tftp download request to %s" % self.host)
log.info(" filename -> %s" % self.file_to_transfer)
log.info(" options -> %s" % self.options)
self.metrics.start_time = time.time()
log.debug(... | [
"Initiate the download."
] |
Please provide a description of the function:def end(self):
TftpContext.end(self, not self.filelike_fileobj)
self.metrics.end_time = time.time()
log.debug("Set metrics.end_time to %s" % self.metrics.end_time)
self.metrics.compute() | [
"Finish up the context."
] |
Please provide a description of the function:def upload(self, filename, input, packethook=None, timeout=SOCK_TIMEOUT):
self.context = TftpContextClientUpload(self.host,
self.iport,
filename,
... | [
"This method initiates a tftp upload to the configured remote host,\n uploading the filename passed. It reads the file from input, which\n can be a file-like object or a path to a local file. If a packethook\n is provided, it must be a function that takes a single parameter,\n which will... |
Please provide a description of the function:def decode_options(self, buffer):
fmt = b"!"
options = {}
log.debug("decode_options: buffer is: %s", repr(buffer))
log.debug("size of buffer is %d bytes", len(buffer))
if len(buffer) == 0:
log.debug("size of buffe... | [
"This method decodes the section of the buffer that contains an\n unknown number of options. It returns a dictionary of option names and\n values."
] |
Please provide a description of the function:def encode(self):
tftpassert(self.filename, "filename required in initial packet")
tftpassert(self.mode, "mode required in initial packet")
# Make sure filename and mode are bytestrings.
filename = self.filename
mode = self.mo... | [
"Encode the packet's buffer from the instance variables."
] |
Please provide a description of the function:def encode(self):
if len(self.data) == 0:
log.debug("Encoding an empty DAT packet")
data = self.data
if not isinstance(self.data, bytes):
data = self.data.encode('ascii')
fmt = b"!HH%ds" % len(data)
sel... | [
"Encode the DAT packet. This method populates self.buffer, and\n returns self for easy method chaining."
] |
Please provide a description of the function:def decode(self):
# We know the first 2 bytes are the opcode. The second two are the
# block number.
(self.blocknumber,) = struct.unpack(str("!H"), self.buffer[2:4])
log.debug("decoding DAT packet, block number %d", self.blocknumber)
... | [
"Decode self.buffer into instance variables. It returns self for\n easy method chaining."
] |
Please provide a description of the function:def encode(self):
fmt = b"!HH%dsx" % len(self.errmsgs[self.errorcode])
log.debug("encoding ERR packet with fmt %s", fmt)
self.buffer = struct.pack(fmt,
self.opcode,
self.erro... | [
"Encode the DAT packet based on instance variables, populating\n self.buffer, returning self."
] |
Please provide a description of the function:def decode(self):
"Decode self.buffer, populating instance variables and return self."
buflen = len(self.buffer)
tftpassert(buflen >= 4, "malformed ERR packet, too short")
log.debug("Decoding ERR packet, length %s bytes", buflen)
if bu... | [] |
Please provide a description of the function:def match_options(self, options):
for name in self.options:
if name in options:
if name == 'blksize':
# We can accept anything between the min and max values.
size = int(self.options[name])
... | [
"This method takes a set of options, and tries to match them with\n its own. It can accept some changes in those options from the server as\n part of a negotiation. Changed or unchanged, it will return a dict of\n the options so that the session can update itself to the negotiated\n opti... |
Please provide a description of the function:def handleOACK(self, pkt):
if len(pkt.options.keys()) > 0:
if pkt.match_options(self.context.options):
log.info("Successful negotiation of options")
# Set options to OACK options
self.context.option... | [
"This method handles an OACK from the server, syncing any accepted\n options."
] |
Please provide a description of the function:def returnSupportedOptions(self, options):
# We support the options blksize and tsize right now.
# FIXME - put this somewhere else?
accepted_options = {}
for option in options:
if option == 'blksize':
# Mak... | [
"This method takes a requested options list from a client, and\n returns the ones that are supported."
] |
Please provide a description of the function:def sendDAT(self):
finished = False
blocknumber = self.context.next_block
# Test hook
if DELAY_BLOCK and DELAY_BLOCK == blocknumber:
import time
log.debug("Deliberately delaying 10 seconds...")
time... | [
"This method sends the next DAT packet based on the data in the\n context. It returns a boolean indicating whether the transfer is\n finished."
] |
Please provide a description of the function:def sendACK(self, blocknumber=None):
log.debug("In sendACK, passed blocknumber is %s", blocknumber)
if blocknumber is None:
blocknumber = self.context.next_block
log.info("Sending ack to block %d" % blocknumber)
ackpkt = T... | [
"This method sends an ack packet to the block number specified. If\n none is specified, it defaults to the next_block property in the\n parent context."
] |
Please provide a description of the function:def sendError(self, errorcode):
log.debug("In sendError, being asked to send error %d", errorcode)
errpkt = TftpPacketERR()
errpkt.errorcode = errorcode
if self.context.tidport == None:
log.debug("Error packet received out... | [
"This method uses the socket passed, and uses the errorcode to\n compose and send an error packet."
] |
Please provide a description of the function:def sendOACK(self):
log.debug("In sendOACK with options %s", self.context.options)
pkt = TftpPacketOACK()
pkt.options = self.context.options
self.context.sock.sendto(pkt.encode().buffer,
(self.context.... | [
"This method sends an OACK packet with the options from the current\n context."
] |
Please provide a description of the function:def resendLast(self):
"Resend the last sent packet due to a timeout."
log.warning("Resending packet %s on sessions %s"
% (self.context.last_pkt, self))
self.context.metrics.resent_bytes += len(self.context.last_pkt.buffer)
self.con... | [] |
Please provide a description of the function:def handleDat(self, pkt):
log.info("Handling DAT packet - block %d" % pkt.blocknumber)
log.debug("Expecting block %s", self.context.next_block)
if pkt.blocknumber == self.context.next_block:
log.debug("Good, received block %d in s... | [
"This method handles a DAT packet during a client download, or a\n server upload."
] |
Please provide a description of the function:def serverInitial(self, pkt, raddress, rport):
options = pkt.options
sendoack = False
if not self.context.tidport:
self.context.tidport = rport
log.info("Setting tidport to %s" % rport)
log.debug("Setting defa... | [
"This method performs initial setup for a server context transfer,\n put here to refactor code out of the TftpStateServerRecvRRQ and\n TftpStateServerRecvWRQ classes, since their initial setup is\n identical. The method returns a boolean, sendoack, to indicate whether\n it is required to... |
Please provide a description of the function:def handle(self, pkt, raddress, rport):
"Handle an initial RRQ packet as a server."
log.debug("In TftpStateServerRecvRRQ.handle")
sendoack = self.serverInitial(pkt, raddress, rport)
path = self.full_path
log.info("Opening file %s for r... | [] |
Please provide a description of the function:def make_subdirs(self):
# Pull off everything below the root.
subpath = self.full_path[len(self.context.root):]
log.debug("make_subdirs: subpath is %s", subpath)
# Split on directory separators, but drop the last one, as it should
... | [
"The purpose of this method is to, if necessary, create all of the\n subdirectories leading up to the file to the written."
] |
Please provide a description of the function:def handle(self, pkt, raddress, rport):
"Handle an initial WRQ packet as a server."
log.debug("In TftpStateServerRecvWRQ.handle")
sendoack = self.serverInitial(pkt, raddress, rport)
path = self.full_path
if self.context.upload_open:
... | [] |
Please provide a description of the function:def handle(self, pkt, raddress, rport):
log.debug("In TftpStateServerStart.handle")
if isinstance(pkt, TftpPacketRRQ):
log.debug("Handling an RRQ packet")
return TftpStateServerRecvRRQ(self.context).handle(pkt,
... | [
"Handle a packet we just received."
] |
Please provide a description of the function:def handle(self, pkt, raddress, rport):
"Handle a packet, hopefully an ACK since we just sent a DAT."
if isinstance(pkt, TftpPacketACK):
log.debug("Received ACK for packet %d" % pkt.blocknumber)
# Is this an ack to the one we just sent... | [] |
Please provide a description of the function:def handle(self, pkt, raddress, rport):
if isinstance(pkt, TftpPacketDAT):
return self.handleDat(pkt)
# Every other packet type is a problem.
elif isinstance(pkt, TftpPacketACK):
# Umm, we ACK, you don't.
... | [
"Handle the packet in response to an ACK, which should be a DAT."
] |
Please provide a description of the function:def handle(self, pkt, raddress, rport):
if not self.context.tidport:
self.context.tidport = rport
log.debug("Set remote port for session to %s", rport)
# If we're going to successfully transfer the file, then we should see
... | [
"Handle a packet we just received."
] |
Please provide a description of the function:def handle(self, pkt, raddress, rport):
if not self.context.tidport:
self.context.tidport = rport
log.info("Set remote port for session to %s" % rport)
# Now check the packet type and dispatch it properly.
if isinstan... | [
"Handle the packet in response to an RRQ to the server."
] |
Please provide a description of the function:def listen(self, listenip="", listenport=DEF_TFTP_PORT,
timeout=SOCK_TIMEOUT):
tftp_factory = TftpPacketFactory()
# Don't use new 2.5 ternary operator yet
# listenip = listenip if listenip else '0.0.0.0'
if not listeni... | [
"Start a server listening on the supplied interface and port. This\n defaults to INADDR_ANY (all interfaces) and UDP port 69. You can also\n supply a different socket timeout value, if desired."
] |
Please provide a description of the function:def stop(self, now=False):
if now:
self.shutdown_immediately = True
else:
self.shutdown_gracefully = True | [
"Stop the server gracefully. Do not take any new transfers,\n but complete the existing ones. If force is True, drop everything\n and stop. Note, immediately will not interrupt the select loop, it\n will happen when the server returns on ready data, or a timeout.\n ie. SOCK_TIMEOUT"
] |
Please provide a description of the function:def all_releases(self,response_type=None,params=None):
path='/releases?'
response_type = response_type if response_type else self.response_type
if response_type != 'xml': params['file_type'] = 'json'
response = _get_request(self.url_r... | [
"\n Function to request all releases of economic data.\n `<https://research.stlouisfed.org/docs/api/fred/releases.html>`_\n\n :arg str response_type: File extension of response. Options are 'xml', 'json',\n 'dict','df','numpy','csv','tab,'pipe'. Required.\n :ar... |
Please provide a description of the function:def related_tags(self,release_id=None,tag_names=None,response_type=None,params=None):
path='/release/related_tags?'
params['release_id'], params['tag_names'] = release_id, tag_names
response_type = response_type if response_type else self.res... | [
"\n Function to request FRED related tags for a particular release.\n FRED tags are attributes assigned to series.\n Series are assigned tags and releases. Indirectly through series,\n it is possible to get the tags for a category. No tags exist for a\n release that does not have ... |
Please provide a description of the function:def query_params(*frb_fred_params):
def _wrapper(func):
@wraps(func)
def _wrapped(*args, **kwargs):
params = kwargs.pop('params', {})
for p in frb_fred_params:
if p in kwargs:
params[p] = kw... | [
"\n Decorator that pops all accepted parameters from method's kwargs and puts\n them in the params argument. Modeled after elasticsearch-py client utils strategy.\n See https://github.com/elastic/elasticsearch-py/blob/3400179153cc13b6ae2c26734337202569bdfd80/elasticsearch/client/utils.py\n "
] |
Please provide a description of the function:def vintage_dates(self,series_id=None,response_type=None,params=None):
path = '/series/vintagedates?'
params['series_id'] = series_id
response_type = response_type if response_type else self.response_type
if response_type != 'xml': pa... | [
"\n Function to request the dates in history when a series' data values were\n revised or new data values were released. Vintage dates are the release dates\n for a series excluding release dates when the data for the series did not change.\n `<https://research.stlouisfed.org/docs/api/fr... |
Please provide a description of the function:def search(self,search_text=None,response_type=None,params=None):
path = '/series/search?'
params['search_text'] = search_text
response_type = response_type if response_type else self.response_type
if response_type != 'xml': params['f... | [
"\n Function to request economic data series that match search text.\n `<https://research.stlouisfed.org/docs/api/fred/series_search.html>`_\n\n :arg str search_text: The words to match against economic data series. Required.\n :arg str response_type: File extension of response. Options ... |
Please provide a description of the function:def search_tags(self,series_search_text=None,response_type=None,params=None):
path = '/series/search/tags?'
params['series_search_text'] = series_search_text
response_type = response_type if response_type else self.response_type
if re... | [
"\n Function to request the FRED tags for a series search.\n `<https://research.stlouisfed.org/docs/api/fred/series_search_tags.html>`_\n\n :arg str series_search_text: The words to match against economic data series. Required.\n :arg str response_type: File extension of response. Option... |
Please provide a description of the function:def search_related_tags(self,series_search_text=None,tag_names=None,response_type=None,params=None):
path = '/series/search/related_tags?'
params['series_search_text'], params['tag_names'] = series_search_text, tag_names
response_type = respo... | [
"\n Function to request the related FRED tags for one or more FRED tags matching a series search.\n `<https://research.stlouisfed.org/docs/api/fred/series_search_related_tags.html>`_\n\n :arg str series_search_text: The words to match against economic data series. Required.\n :arg str ta... |
Please provide a description of the function:def _fetch(url, ssl_verify = True):
req = Request(url)
if ssl_verify:
page = urlopen(req)
else:
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
page = urlopen(req, context... | [
"\n Helper funcation to fetch content from a given url.\n "
] |
Please provide a description of the function:def _url_builder(url_root,api_key,path,params):
params['api_key'] = api_key
url_end = urlencode(params)
url = "%s%s%s" % (url_root,path,url_end)
return url | [
"\n Helper funcation to build a parameterized url.\n "
] |
Please provide a description of the function:def _convert(frame):
frame = frame.convert_objects(convert_numeric=True)
for column in frame:
if column in c.dates:
frame[column] = frame[column].astype('datetime64')
return frame | [
"\n Helper funcation to build a parameterized url.\n "
] |
Please provide a description of the function:def _dict(content):
if _has_pandas:
data = _data_frame(content).to_dict(orient='records')
else:
response = loads(content)
key = [x for x in response.keys() if x in c.response_data][0]
data = response[key]
return data | [
"\n Helper funcation that converts text-based get response\n to a python dictionary for additional manipulation.\n "
] |
Please provide a description of the function:def _data_frame(content):
response = loads(content)
key = [x for x in response.keys() if x in c.response_data][0]
frame = DataFrame(response[key])
final_frame = _convert(frame)
return final_frame | [
"\n Helper funcation that converts text-based get response\n to a pandas dataframe for additional manipulation.\n "
] |
Please provide a description of the function:def _tab(content):
response = _data_frame(content).to_csv(index=False,sep='\t')
return response | [
"\n Helper funcation that converts text-based get response\n to tab separated values for additional manipulation.\n "
] |
Please provide a description of the function:def _pipe(content):
response = _data_frame(content).to_csv(index=False,sep='|')
return response | [
"\n Helper funcation that converts text-based get response\n to pipe separated values for additional manipulation.\n "
] |
Please provide a description of the function:def _get_request(url_root,api_key,path,response_type,params, ssl_verify):
url = _url_builder(url_root,api_key,path,params)
content = _fetch(url, ssl_verify)
response = _dispatch(response_type)(content)
return response | [
"\n Helper funcation that requests a get response from FRED.\n "
] |
Please provide a description of the function:def parse_atom_file(filename: str) -> AtomFeed:
root = parse_xml(filename).getroot()
return _parse_atom(root) | [
"Parse an Atom feed from a local XML file."
] |
Please provide a description of the function:def parse_atom_bytes(data: bytes) -> AtomFeed:
root = parse_xml(BytesIO(data)).getroot()
return _parse_atom(root) | [
"Parse an Atom feed from a byte-string containing XML data."
] |
Please provide a description of the function:def _get_link(element: Element) -> Optional[str]:
link = get_text(element, 'link')
if link is not None:
return link
guid = get_child(element, 'guid')
if guid is not None and guid.attrib.get('isPermaLink') == 'true':
return get_text(eleme... | [
"Attempt to retrieve item link.\n\n Use the GUID as a fallback if it is a permalink.\n "
] |
Please provide a description of the function:def parse_rss_file(filename: str) -> RSSChannel:
root = parse_xml(filename).getroot()
return _parse_rss(root) | [
"Parse an RSS feed from a local XML file."
] |
Please provide a description of the function:def parse_rss_bytes(data: bytes) -> RSSChannel:
root = parse_xml(BytesIO(data)).getroot()
return _parse_rss(root) | [
"Parse an RSS feed from a byte-string containing XML data."
] |
Please provide a description of the function:def parse_json_feed_file(filename: str) -> JSONFeed:
with open(filename) as f:
try:
root = json.load(f)
except json.decoder.JSONDecodeError:
raise FeedJSONError('Not a valid JSON document')
return parse_json_feed(root) | [
"Parse a JSON feed from a local json file."
] |
Please provide a description of the function:def parse_json_feed_bytes(data: bytes) -> JSONFeed:
try:
root = json.loads(data)
except json.decoder.JSONDecodeError:
raise FeedJSONError('Not a valid JSON document')
return parse_json_feed(root) | [
"Parse a JSON feed from a byte-string containing JSON data."
] |
Please provide a description of the function:def parse_opml_file(filename: str) -> OPML:
root = parse_xml(filename).getroot()
return _parse_opml(root) | [
"Parse an OPML document from a local XML file."
] |
Please provide a description of the function:def parse_opml_bytes(data: bytes) -> OPML:
root = parse_xml(BytesIO(data)).getroot()
return _parse_opml(root) | [
"Parse an OPML document from a byte-string containing XML data."
] |
Please provide a description of the function:def get_feed_list(opml_obj: OPML) -> List[str]:
rv = list()
def collect(obj):
for outline in obj.outlines:
if outline.type == 'rss' and outline.xml_url:
rv.append(outline.xml_url)
if outline.outlines:
... | [
"Walk an OPML document to extract the list of feed it contains."
] |
Please provide a description of the function:def simple_parse_file(filename: str) -> Feed:
pairs = (
(rss.parse_rss_file, _adapt_rss_channel),
(atom.parse_atom_file, _adapt_atom_feed),
(json_feed.parse_json_feed_file, _adapt_json_feed)
)
return _simple_parse(pairs, filename) | [
"Parse an Atom, RSS or JSON feed from a local file."
] |
Please provide a description of the function:def simple_parse_bytes(data: bytes) -> Feed:
pairs = (
(rss.parse_rss_bytes, _adapt_rss_channel),
(atom.parse_atom_bytes, _adapt_atom_feed),
(json_feed.parse_json_feed_bytes, _adapt_json_feed)
)
return _simple_parse(pairs, data) | [
"Parse an Atom, RSS or JSON feed from a byte-string containing data."
] |
Please provide a description of the function:def read(fn, **kwargs):
ext = fn[fn.rfind('.'):].split('@')
if len(ext) == 1:
if ext[0] == '.out' or ext[0] == '.dat':
dirname = os.path.dirname(fn)
if len(dirname) == 0:
dirname = '.'
cycfn = dirname+'... | [
"\n Convenience function: Detect file extension and read via Atomistica or ASE.\n If reading a NetCDF files, frame numbers can be appended via '@'.\n e.g., a = read('traj.nc@5')\n "
] |
Please provide a description of the function:def write(fn, a, **kwargs):
ext = fn[fn.rfind('.'):].split('@')
if ext[0] == '.out' or ext[0] == '.dat':
return write_atoms(fn, a)
elif ext[0] == '.lammps':
return write_lammps_data(fn, a, velocities=True, **kwargs)
elif ext[0] == '.nc':
... | [
"\n Convenience function: Detect file extension and write via Atomistica or ASE.\n Has support for writing LAMMPS data files.\n "
] |
Please provide a description of the function:def get_shear_distance(a):
cx, cy, cz = a.cell
if 'shear_dx' in a.info:
assert abs(cx[1]) < 1e-12, 'cx[1] = {0}'.format(cx[1])
assert abs(cx[2]) < 1e-12, 'cx[2] = {0}'.format(cx[2])
assert abs(cy[0]) < 1e-12, 'cx[0] = {0}'.format(cy[0])
... | [
"\n Returns the distance a volume has moved during simple shear. Considers\n either Lees-Edwards boundary conditions or sheared cells.\n "
] |
Please provide a description of the function:def get_XIJ(nat, i_now, dr_now, dr_old):
# Do an element-wise outer product
dr_dr = dr_now.reshape(-1,3,1)*dr_old.reshape(-1,1,3)
xij = np.zeros([nat,3,3])
for i in range(3):
for j in range(3):
# For each atom, sum over all neighbors... | [
"\n Calculates the X_{ij} matrix\n "
] |
Please provide a description of the function:def get_YIJ(nat, i_now, dr_old):
# Just do an element-wise outer product
dr_dr = dr_old.reshape(-1,3,1)*dr_old.reshape(-1,1,3)
yij = np.zeros([nat,3,3])
for i in range(3):
for j in range(3):
# For each atom, sum over all neighbors
... | [
"\n Calculates the Y_{ij} matrix\n "
] |
Please provide a description of the function:def array_inverse(A):
A = np.ascontiguousarray(A, dtype=float)
b = np.identity(A.shape[2], dtype=A.dtype)
n_eq = A.shape[1]
n_rhs = A.shape[2]
pivots = np.zeros(n_eq, np.intc)
identity = np.eye(n_eq)
def lapack_inverse(a):
b = np.co... | [
"\n Compute inverse for each matrix in a list of matrices.\n This is faster than calling numpy.linalg.inv for each matrix.\n "
] |
Please provide a description of the function:def get_delta_plus_epsilon(nat, i_now, dr_now, dr_old):
XIJ = get_XIJ(nat, i_now, dr_now, dr_old)
YIJ = get_YIJ(nat, i_now, dr_old)
YIJ_invert = array_inverse(YIJ)
# Perform sum_k X_ik Y_jk^-1
epsilon = np.sum(XIJ.reshape(-1,3,1,3)*YIJ_invert.resha... | [
"\n Calculate delta_ij+epsilon_ij, i.e. the deformation gradient matrix\n "
] |
Please provide a description of the function:def get_D_square_min(atoms_now, atoms_old, i_now, j_now, delta_plus_epsilon=None):
nat = len(atoms_now)
assert len(atoms_now) == len(atoms_old)
pos_now = atoms_now.positions
pos_old = atoms_old.positions
# Compute current and old distance vectors. ... | [
"\n Calculate the D^2_min norm of Falk and Langer\n "
] |
Please provide a description of the function:def dhms(secs):
dhms = [0, 0, 0, 0]
dhms[0] = int(secs // 86400)
s = secs % 86400
dhms[1] = int(s // 3600)
s = secs % 3600
dhms[2] = int(s // 60)
s = secs % 60
dhms[3] = int(s+.5)
return dhms | [
"return days,hours,minutes and seconds"
] |
Please provide a description of the function:def hms(secs):
hms = [0, 0, 0]
hms[0] = int(secs // 3600)
s = secs % 3600
hms[1] = int(s // 60)
s = secs % 60
hms[2] = int(s+.5)
return hms | [
"return hours,minutes and seconds"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.