code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
newIndexer = oldIndexer.upgradeVersion(
oldIndexer.typeName, 2, 3,
indexCount=oldIndexer.indexCount,
installedOn=oldIndexer.installedOn,
indexDirectory=oldIndexer.indexDirectory)
# the 3->4 upgrader for PyLuceneIndexer calls reset(), so don't do it
# here. also, it won'... | def remoteIndexer2to3(oldIndexer) | The documentType keyword was added to all indexable items. Indexes need to
be regenerated for this to take effect. Also, PyLucene no longer stores
the text of messages it indexes, so deleting and re-creating the indexes
will make them much smaller. | 7.699232 | 7.686028 | 1.001718 |
new = old.upgradeVersion(PyLuceneIndexer.typeName, 4, 5,
indexCount=old.indexCount,
installedOn=old.installedOn,
indexDirectory=old.indexDirectory)
new.reset()
new.store.powerUp(new, ixmantissa.IFulltextIndexer)
... | def pyLuceneIndexer4to5(old) | Copy attributes, reset index due because information about deleted
documents has been lost, and power up for IFulltextIndexer so other code
can find this item. | 7.333381 | 6.183435 | 1.185972 |
_IndexerInputSource(store=self.store, indexer=self, source=itemSource)
itemSource.addReliableListener(self, style=iaxiom.REMOTE) | def addSource(self, itemSource) | Add the given L{IBatchProcessor} as a source of input for this indexer. | 28.963694 | 19.469372 | 1.487654 |
self.indexCount = 0
indexDir = self.store.newDirectory(self.indexDirectory)
if indexDir.exists():
indexDir.remove()
for src in self.getSources():
src.removeReliableListener(self)
src.addReliableListener(self, style=iaxiom.REMOTE) | def reset(self) | Process everything all over again. | 10.015908 | 9.370913 | 1.06883 |
remove = self.store.query(_RemoveDocument)
documentIdentifiers = list(remove.getColumn("documentIdentifier"))
if VERBOSE:
log.msg("%s/%d removing %r" % (self.store, self.storeID, documentIdentifiers))
reader = self.openReadIndex()
map(reader.remove, documentI... | def _flush(self) | Deal with pending result-affecting things.
This should always be called before issuing a search. | 8.815181 | 8.255816 | 1.067754 |
RemoteIndexer.reset(self)
if hasattr(self, '_lockfile'):
os.remove(self._lockfile)
del self._lockfile | def reset(self) | In addition to the behavior of the superclass, delete any dangling
lockfiles which may prevent this index from being opened. With the
tested version of PyLucene (something pre-2.0), this appears to not
actually be necessary: deleting the entire index directory but
leaving the lockfile i... | 6.425512 | 3.99042 | 1.610235 |
docid = int(document.uniqueIdentifier())
text = u' '.join(document.textParts())
self.store.executeSQL(self.addSQL, (docid, text)) | def add(self, document) | Add a document to the database. | 10.129359 | 9.495751 | 1.066725 |
docid = int(docid)
self.store.executeSQL(self.removeSQL, (docid,)) | def remove(self, docid) | Remove a document from the database. | 7.336824 | 6.256315 | 1.172707 |
if sortAscending:
direction = 'ASC'
else:
direction = 'DESC'
return [_SQLiteResultWrapper(r[0]) for r in
self.store.querySQL(self.searchSQL % (direction,), (term,))] | def search(self, term, keywords=None, sortAscending=True) | Search the database. | 7.981031 | 7.448387 | 1.071511 |
storeDir = self.store.newDirectory(self.indexDirectory)
if not storeDir.exists():
store = Store(storeDir)
self._initStore(store)
return store
else:
return Store(storeDir) | def _getStore(self) | Get the Store used for FTS.
If it does not exist, it is created and initialised. | 4.752029 | 4.543458 | 1.045906 |
logger = logging.getLogger(__package__)
# TODO (just document prominently)
# assume only one trial can run at once right now
# multi-concurrent-trial support will require complex filter logic
# based on the currently-running trial (maybe we shouldn't allow multiple
# trials on different p... | def init(track_log_handler) | (Re)initialize track's file handler for track package logger.
Adds a stdout-printing handler automatically. | 5.71826 | 5.771816 | 0.990721 |
# Get the path name and line number of the function which called us.
previous_frame = inspect.currentframe().f_back
try:
pathname, lineno, _, _, _ = inspect.getframeinfo(previous_frame)
# if path is in cwd, simplify it
cwd = os.path.abspath(os.getcwd())
pathname = os.pat... | def debug(s, *args) | debug(s, x1, ..., xn) logs s.format(x1, ..., xn). | 3.862913 | 3.713738 | 1.040168 |
value = self.__convert__(value)
self.__validate__(value)
return self.__serialize__(value) | def dump(self, value) | Dumps the value to string.
:returns: Returns the stringified version of the value.
:raises: TypeError, ValueError | 6.10297 | 9.775804 | 0.624293 |
min_ = (-sys.maxsize - 1) if self._min is None else self._min
max_ = sys.maxsize if self._max is None else self._max
return random.randint(min_, max_) | def simulate(self) | Generates a random integer in the available range. | 3.261098 | 2.51546 | 1.296422 |
min_ = 1 if self._min is None else self._min
max_ = 10 if self._max is None else self._max
n = min_ if (min_ >= max_) else random.randint(min_, max_)
chars = string.ascii_letters + string.digits
return ''.join(random.choice(chars) for x in range(n)) | def simulate(self) | Returns a randomly constructed string.
Simulate randomly constructs a string with a length between min and
max. If min is not present, a minimum length of 1 is assumed, if max
is not present a maximum length of 10 is used. | 2.844772 | 2.420575 | 1.175246 |
# Simulates zero to 10 types
return [t.simulate() for t in itertools.islice(self, random.choice(range(10)))] | def simulate(self) | Simulates a stream of types. | 13.546062 | 8.783198 | 1.54227 |
def __findRange(self, excelLib, start, end):
''' return low and high as excel range '''
inc = 1
low = 0
high = 0
dates = excelLib.readCol(0, 1)
for index, date in enumerate(dates):
if int(start) <= int(date):
low = index + inc
... | return low and high as excel range | null | null | null | |
def __readData(self, targetPath, start, end):
''' read data '''
ret = []
if not path.exists(targetPath):
LOG.error("Target file doesn't exist: %s" % path.abspath(targetPath) )
return ret
with ExcelLib(fileName = targetPath, mode = ExcelLib.READ_MODE) as ex... | read data | null | null | null | |
def __writeData(self, targetPath, fields, rows):
''' write data '''
if path.exists(targetPath):
LOG.error("Target file exists: %s" % path.abspath(targetPath) )
raise UfException(Errors.FILE_EXIST, "can't write to a existing file") #because xlwt doesn't support it
w... | write data | null | null | null | |
def readQuotes(self, start, end):
''' read quotes '''
quotes = self.__readData(self.targetPath(ExcelDAM.QUOTE), start, end)
return [Quote(*quote) for quote in quotes] | read quotes | null | null | null | |
def writeQuotes(self, quotes):
''' write quotes '''
self.__writeData(self.targetPath(ExcelDAM.QUOTE),
QUOTE_FIELDS,
[[getattr(quote, field) for field in QUOTE_FIELDS] for quote in quotes]) | write quotes | null | null | null | |
def readTicks(self, start, end):
''' read ticks '''
ticks = self.__readData(self.targetPath(ExcelDAM.TICK), start, end)
return [Tick(*tick) for tick in ticks] | read ticks | null | null | null | |
def writeTicks(self, ticks):
''' read quotes '''
self.__writeData(self.targetPath(ExcelDAM.TICK),
TICK_FIELDS,
[[getattr(tick, field) for field in TICK_FIELDS] for tick in ticks]) | read quotes | null | null | null | |
length = len(args)
if not 2 <= length <= 6:
msg = 'snap takes 2 to 6 arguments, {0} given.'.format(length)
raise TypeError(msg)
# The program data type.
param = Enum(
'x', 'y', 'r', 'theta', 'aux1', 'aux2', 'aux3', 'aux4',
'frequen... | def snap(self, *args) | Records multiple values at once.
It takes two to six arguments specifying which values should be
recorded together. Valid arguments are 'x', 'y', 'r', 'theta',
'aux1', 'aux2', 'aux3', 'aux4', 'frequency', 'trace1', 'trace2',
'trace3' and 'trace4'.
snap is faster since it avoids... | 6.269814 | 4.636605 | 1.352243 |
if mode == 'all':
self._write('SDAT')
elif mode == 'data':
self._write('SASC')
elif mode=='state':
self._write('SSET')
else:
raise ValueError('Invalid save mode.') | def save(self, mode='all') | Saves to the file specified by :attr:`~SR850.filename`.
:param mode: Defines what to save.
======= ================================================
Value Description
======= ================================================
'all' Saves the active display'... | 4.702144 | 3.597831 | 1.306939 |
if mode == 'all':
self._write('RDAT')
elif mode == 'state':
self._write('RSET')
else:
raise ValueError('Invalid recall mode.') | def recall(self, mode='all') | Recalls from the file specified by :attr:`~SR850.filename`.
:param mode: Specifies the recall mode.
======= ==================================================
Value Description
======= ==================================================
'all' Recalls the ... | 5.5457 | 4.278444 | 1.296196 |
if function is not None:
self.fit_function = function
cmd = 'FITT', Integer(min=0, max=100), Integer(min=0, max=100)
self._write(cmd, start, stop) | def fit(self, range, function=None) | Fits a function to the active display's data trace within a
specified range of the time window.
E.g.::
# Fit's a gaussian to the first 30% of the time window.
lockin.fit(range=(0, 30), function='gauss')
:param start: The left limit of the time window in percent.
... | 6.847545 | 6.752742 | 1.014039 |
cmd = 'STAT', Integer, Integer
self._write(cmd, start, stop) | def calculate_statistics(self, start, stop) | Starts the statistics calculation.
:param start: The left limit of the time window in percent.
:param stop: The right limit of the time window in percent.
.. note::
The calculation takes some time. Check the status byte to see when
the operation is done. A running scan... | 30.151005 | 35.325996 | 0.853508 |
if operation is not None:
self.math_operation = operation
if trace is not None:
self.math_trace_argument = trace
type = 'trace'
elif constant is not None:
self.math_constant = constant
type = 'constant'
if type is not N... | def calculate(self, operation=None, trace=None, constant=None, type=None) | Starts the calculation.
The calculation operates on the trace graphed in the active display.
The math operation is defined by the :attr:`~.SR850.math_operation`,
the second argument by the :attr:`~.SR850.math_argument_type`.
For convenience, the operation and the second argument, can b... | 3.157126 | 2.316505 | 1.362884 |
bin = self._query(('MBIN?', Integer, Integer), self.idx)
return None if bin == -1 else bin | def bin(self) | The bin index of this mark.
:returns: An integer bin index or None if the mark is inactive. | 36.357716 | 37.144936 | 0.978807 |
# TODO avoid direct usage of transport object.
marks = tuple(int(x) for x in transport.ask('MACT').split(','))
return marks[1:] | def active(self) | The indices of the active marks. | 32.131855 | 18.632645 | 1.724492 |
if 'format' not in kwargs or kwargs['format'] == 'dataframe':
resp = self.get('/v1/query', data={'q': sql, 'format': 'table'}).json()
if len(resp) == 0:
return pd.DataFrame()
else:
return pd.DataFrame.from_records(resp[1:], columns=res... | def query(self, sql, **kwargs) | Shortcut for GET /v1/query, except with argument format='dataframe'
(the default), in which case it will simply wrap the result of the GET
query to /v1/query (with format='table') in a `pandas.DataFrame`. | 3.431725 | 2.715219 | 1.263885 |
if not url.startswith('/v1/procedures'):
raise Exception("The only supported route is /v1/procedures")
parts = url.split('/')
len_parts = len(parts)
if len_parts not in [4, 6]:
raise Exception(
"You must either PUT a procedure or a procedu... | def put_and_track(self, url, payload, refresh_rate_sec=1) | Put and track progress, displaying progress bars.
May display the wrong progress if 2 things post/put on the same
procedure name at the same time. | 3.594809 | 3.452601 | 1.041188 |
if not url.startswith('/v1/procedures'):
raise Exception("The only supported route is /v1/procedures")
if url.endswith('/runs'):
raise Exception(
"Posting and tracking run is unsupported at the moment")
if len(url.split('/')) != 3:
rai... | def post_and_track(self, url, payload, refresh_rate_sec=1) | Post and track progress, displaying progress bars.
May display the wrong progress if 2 things post/put on the same
procedure name at the same time. | 3.64606 | 3.437522 | 1.060665 |
if self._endpointService is None:
_service = service
else:
_service = self._endpointService
return _service(
self.description.encode('ascii'), self.factory.getFactory()) | def _makeService(self) | Construct a service for the endpoint as described. | 9.104106 | 7.428577 | 1.225552 |
store = self.parent.parent.getStore()
port = None
factories = {}
for portType in [TCPPort, SSLPort, StringEndpointPort]:
for port in store.query(portType):
key = port.factory.storeID
if key not in factories:
factori... | def postOptions(self) | Display details about the ports which already exist. | 2.836036 | 2.764199 | 1.025989 |
for portID in portIDs:
try:
port = store.getItemByID(portID)
except KeyError:
print "%d does not identify an item." % (portID,)
raise SystemExit(1)
if isinstance(port, (TCPPort, SSLPort, StringEndpointPort)):
... | def _delete(self, store, portIDs) | Try to delete the ports with the given store IDs.
@param store: The Axiom store from which to delete items.
@param portIDs: A list of Axiom store IDs for TCPPort or SSLPort items.
@raise L{SystemExit}: If one of the store IDs does not identify a port
item. | 4.104693 | 3.03022 | 1.354586 |
if self.portIdentifiers:
store = self.parent.parent.getStore()
store.transact(self._delete, store, self.portIdentifiers)
print "Deleted."
raise SystemExit(0)
else:
self.opt_help() | def postOptions(self) | Delete the ports specified with the port-identifier option. | 13.634827 | 8.839037 | 1.542569 |
# TODO: need same thing for argparse
flags_dict = flags.FLAGS.flags_by_module_dict()
# only include parameters from modules the user probably cares about
def _relevant_module(module_name):
if __package__ and __package__ in module_name:
return True
if module_name == sys.a... | def absl_flags() | Extracts absl-py flags that the user has specified and outputs their
key-value mapping.
By default, extracts only those flags in the current __package__
and mainfile.
Useful to put into a trial's param_map. | 5.011178 | 4.661279 | 1.075065 |
if pipe is None:
return Pipeline(name=name, autoexec=autoexec,
exit_handler=exit_handler)
try:
if pipe.supports_redpipe_pipeline():
return NestedPipeline(
parent=pipe,
name=name,
autoexec=autoexec,
... | def pipeline(pipe=None, name=None, autoexec=False, exit_handler=None) | This is the foundational function for all of redpipe.
Everything goes through here.
create pipelines, nest pipelines, get pipelines for a specific name.
It all happens here.
Here's a simple example:
.. code:: python
with pipeline() as pipe:
pipe.set('foo', 'bar')
f... | 4.113284 | 3.681356 | 1.117328 |
return pipeline(pipe=pipe, name=name, autoexec=True,
exit_handler=exit_handler) | def autoexec(pipe=None, name=None, exit_handler=None) | create a pipeline with a context that will automatically execute the
pipeline upon leaving the context if no exception was raised.
:param pipe:
:param name:
:return: | 4.352516 | 6.879035 | 0.632722 |
if name == self.connection_name:
return self
try:
return self._pipelines[name]
except KeyError:
pipe = Pipeline(name=name, autoexec=True)
self._pipelines[name] = pipe
return pipe | def _pipeline(self, name) | Don't call this function directly.
Used by the NestedPipeline class when it executes.
:param name:
:return: | 4.004247 | 4.427214 | 0.904462 |
stack = self._stack
callbacks = self._callbacks
promises = []
if stack:
def process():
# get the connection to redis
pipe = ConnectionManager.get(self.connection_name)
# keep track of all the command... | def execute(self) | Invoke the redispy pipeline.execute() method and take all the values
returned in sequential order of commands and map them to the
Future objects we returned when each command was queued inside
the pipeline.
Also invoke all the callback functions queued up.
:param raise_on_error: ... | 5.780617 | 5.248204 | 1.101447 |
self._stack = []
self._callbacks = []
pipes = self._pipelines
self._pipelines = {}
for pipe in pipes.values():
pipe.reset() | def reset(self) | cleanup method. get rid of the stack and callbacks.
:return: | 6.857444 | 4.774704 | 1.436203 |
stack = self._stack
callbacks = self._callbacks
self._stack = []
self._callbacks = []
deferred = []
build = self._nested_future
pipe = self._pipeline(self.connection_name)
for item, args, kwargs, ref in stack:
f = getattr(pipe, item... | def execute(self) | execute the commands inside the nested pipeline.
This causes all queued up commands to be passed upstream to the
parent, including callbacks.
The state of this pipeline object gets cleaned up.
:return: | 7.513348 | 6.913037 | 1.086838 |
output = etree.Element(container_name, nsmap=nsmap, attrib=attrib)
for rule in rules:
if rule not in data:
continue
element = rules[rule](rule, data[rule])
for e in element:
output.append(e)
return output | def dump_etree_helper(container_name, data, rules, nsmap, attrib) | Convert DataCite JSON format to DataCite XML.
JSON should be validated before it is given to to_xml. | 2.829818 | 2.871561 | 0.985463 |
return etree.tostring(
root,
pretty_print=pretty_print,
xml_declaration=xml_declaration,
encoding=encoding,
).decode('utf-8') | def etree_to_string(root, pretty_print=True, xml_declaration=True,
encoding='utf-8') | Dump XML etree as a string. | 1.776019 | 1.83187 | 0.969511 |
def register(f):
self.rules[key] = f
return f
return register | def rule(self, key) | Decorate as a rule for a key in top level JSON. | 4.371086 | 4.187516 | 1.043837 |
# ordered list (column_name, column_type) pairs
column_types = []
# which columns have nullable values
nullable = set()
# tag cached database by dataframe's number of rows and columns
for column_name in df.columns:
values = df[column_name]
... | def from_dataframe(cls, name, df, indices, primary_key=None) | Infer table metadata from a DataFrame | 3.896834 | 3.880593 | 1.004185 |
# Endpoint parameters
date = util.datetime_string(
kwargs.get('day', 1),
kwargs.get('month', 1),
kwargs.get('year', 1970),
kwargs.get('hour', 0),
kwargs.get('minute', 0)
)
params = {
'language': util.langua... | def detail_parking(self, **kwargs) | Obtain detailed info of a given parking.
Args:
lang (str): Language code (*es* or *en*).
day (int): Day of the month in format DD.
The number is automatically padded if it only has one digit.
month (int): Month number in format MM.
The number... | 4.113726 | 3.513336 | 1.170889 |
# Endpoint parameters
params = {
'language': util.language_code(kwargs.get('lang')),
'family': kwargs.get('family')
}
if kwargs.get('id'):
params['id'] = kwargs['id']
# Request
result = self.make_request('detail_poi', {}, **p... | def detail_poi(self, **kwargs) | Obtain detailed info of a given POI.
Args:
family (str): Family code of the POI (3 chars).
lang (str): Language code (*es* or *en*).
id (int): Optional, ID of the POI to query. Passing value -1 will
result in information from all POIs.
Returns:
... | 5.50108 | 5.020519 | 1.095719 |
# Endpoint parameters
params = {'language': util.language_code(kwargs.get('lang'))}
# Request
result = self.make_request('icon_description', {}, **params)
if not util.check_result(result):
return False, result.get('message', 'UNKNOWN ERROR')
# Pars... | def icon_description(self, **kwargs) | Obtain a list of elements that have an associated icon.
Args:
lang (str): Language code (*es* or *en*).
Returns:
Status boolean and parsed response (list[IconDescription]), or
message string in case of error. | 6.9897 | 6.480584 | 1.07856 |
# Endpoint parameters
date = util.datetime_string(
kwargs.get('day', 1),
kwargs.get('month', 1),
kwargs.get('year', 1970),
kwargs.get('hour', 0),
kwargs.get('minute', 0)
)
family_categories = []
for element in ... | def info_parking_poi(self, **kwargs) | Obtain generic information on POIs and parkings.
This returns a list of elements in a given radius from the coordinates.
Args:
radius (int): Radius of the search (in meters).
latitude (double): Latitude in decimal degrees.
longitude (double): Longitude in decimal de... | 3.935901 | 3.327441 | 1.182861 |
# Endpoint parameters
params = {
'language': util.language_code(kwargs.get('lang')),
'publicData': True
}
# Request
result = self.make_request('list_features', {}, **params)
if not util.check_result(result):
return False, res... | def list_features(self, **kwargs) | Obtain a list of parkings.
Args:
lang (str): Language code (*es* or *en*).
Returns:
Status boolean and parsed response (list[Parking]), or message
string in case of error. | 7.471513 | 6.602108 | 1.131686 |
# Endpoint parameters
url_args = {'lang': util.language_code(kwargs.get('lang'))}
# Request
result = self.make_request('list_parking', url_args)
if not util.check_result(result):
return False, result.get('message', 'UNKNOWN ERROR')
# Parse
... | def list_parking(self, **kwargs) | Obtain a list of parkings.
Args:
lang (str): Language code (*es* or *en*).
Returns:
Status boolean and parsed response (list[Parking]), or message
string in case of error. | 6.454146 | 5.98546 | 1.078304 |
# Endpoint parameters
url_args = {
'language': util.language_code(kwargs.get('lang')),
'address': kwargs.get('address', '')
}
# Request
result = self.make_request('list_street_poi_parking', url_args)
if not util.check_result(result):
... | def list_street_poi_parking(self, **kwargs) | Obtain a list of addresses and POIs.
This endpoint uses an address to perform the search
Args:
lang (str): Language code (*es* or *en*).
address (str): Address in which to perform the search.
Returns:
Status boolean and parsed response (list[ParkingPoi]), o... | 5.690942 | 5.010564 | 1.135789 |
# Endpoint parameters
url_args = {'language': util.language_code(kwargs.get('lang'))}
# Request
result = self.make_request('list_poi_types', url_args)
if not util.check_result(result):
return False, result.get('message', 'UNKNOWN ERROR')
# Parse
... | def list_types_poi(self, **kwargs) | Obtain a list of families, types and categories of POI.
Args:
lang (str): Language code (*es* or *en*).
Returns:
Status boolean and parsed response (list[ParkingPoiType]), or message
string in case of error. | 6.760976 | 5.923244 | 1.141431 |
def readQuotes(self, start, end):
''' read quotes from Yahoo Financial'''
if self.symbol is None:
LOG.debug('Symbol is None')
return []
return self.__yf.getQuotes(self.symbol, start, end) | read quotes from Yahoo Financial | null | null | null | |
if not isinstance(value, (dict, list, tuple)):
return value
if isinstance(value, dict):
copy = {}
for k, v in value.items():
copy[k] = deepcopy(v)
if isinstance(value, tuple):
copy = list(range(len(value)))
for k in get_keys(list(value)):
... | def deepcopy(value) | The default copy.deepcopy seems to copy all objects and some are not
`copy-able`.
We only need to make sure the provided data is a copy per key, object does
not need to be copied. | 2.007982 | 1.973145 | 1.017656 |
if confirm is True:
self._write(('DFLT', Integer), 99)
else:
raise ValueError('Reset to factory defaults was not confirmed.') | def _factory_default(self, confirm=False) | Resets the device to factory defaults.
:param confirm: This function should not normally be used, to prevent
accidental resets, a confirm value of `True` must be used. | 20.158934 | 15.682865 | 1.285411 |
username = request.args.get('username', [''])[0]
if '@' not in username:
username = '%s@%s' % (
username, request.getHeader('host').split(':')[0])
return username | def usernameFromRequest(request) | Take an HTTP request and return a username of the form <user>@<domain>.
@type request: L{inevow.IRequest}
@param request: A HTTP request
@return: A C{str} | 3.344927 | 3.605854 | 0.927638 |
PersistentSession(
store=self.store,
sessionKey=key,
authenticatedAs=user) | def createSessionForKey(self, key, user) | Create a persistent session in the database.
@type key: L{bytes}
@param key: The persistent session identifier.
@type user: L{bytes}
@param user: The username the session will belong to. | 16.391308 | 17.340847 | 0.945243 |
session = self.store.findFirst(
PersistentSession, PersistentSession.sessionKey == key)
if session is None:
return None
else:
session.renew()
return session.authenticatedAs | def authenticatedUserForKey(self, key) | Find a persistent session for a user.
@type key: L{bytes}
@param key: The persistent session identifier.
@rtype: L{bytes} or C{None}
@return: The avatar ID the session belongs to, or C{None} if no such
session exists. | 7.418549 | 6.887897 | 1.077041 |
self.store.query(
PersistentSession,
PersistentSession.sessionKey == key).deleteFromStore() | def removeSessionWithKey(self, key) | Remove a persistent session, if it exists.
@type key: L{bytes}
@param key: The persistent session identifier. | 11.34904 | 9.739841 | 1.165218 |
tooOld = extime.Time() - timedelta(seconds=PERSISTENT_SESSION_LIFETIME)
self.store.query(
PersistentSession,
PersistentSession.lastUsed < tooOld).deleteFromStore()
self._lastClean = self._clock.seconds() | def _cleanSessions(self) | Clean expired sesisons. | 8.809495 | 7.536904 | 1.168848 |
sinceLast = self._clock.seconds() - self._lastClean
if sinceLast > self.sessionCleanFrequency:
self._cleanSessions() | def _maybeCleanSessions(self) | Clean expired sessions if it's been long enough since the last clean. | 5.93432 | 4.506307 | 1.316892 |
host = request.getHeader('host')
if host is None:
# This is a malformed request that we cannot possibly handle
# safely, fall back to the default behaviour.
return None
host = host.split(':')[0]
for domain in self._domains:
suffix... | def cookieDomainForRequest(self, request) | Pick a domain to use when setting cookies.
@type request: L{nevow.inevow.IRequest}
@param request: Request to determine cookie domain for
@rtype: C{str} or C{None}
@return: Domain name to use when setting cookies, or C{None} to
indicate that only the domain in the request s... | 4.85002 | 4.983483 | 0.973219 |
cookieValue = request.getSession().uid
request.addCookie(
self.cookieKey, cookieValue, path='/',
max_age=PERSISTENT_SESSION_LIFETIME,
domain=self.cookieDomainForRequest(request)) | def savorSessionCookie(self, request) | Make the session cookie last as long as the persistent session.
@type request: L{nevow.inevow.IRequest}
@param request: The HTTP request object for the guard login URL. | 5.918372 | 6.236571 | 0.948978 |
self._maybeCleanSessions()
if isinstance(creds, credentials.Anonymous):
preauth = self.authenticatedUserForKey(session.uid)
if preauth is not None:
self.savorSessionCookie(request)
creds = userbase.Preauthenticated(preauth)
def c... | def login(self, request, session, creds, segments) | Called to check the credentials of a user.
Here we extend guard's implementation to preauthenticate users if they
have a valid persistent session.
@type request: L{nevow.inevow.IRequest}
@param request: The HTTP request being handled.
@type session: L{nevow.guard.GuardSession}... | 8.11135 | 7.61308 | 1.065449 |
guard.SessionWrapper.explicitLogout(self, session)
self.removeSessionWithKey(session.uid) | def explicitLogout(self, session) | Handle a user-requested logout.
Here we override guard's behaviour for the logout action to delete the
persistent session. In this case the user has explicitly requested a
logout, so the persistent session must be deleted to require the user
to log in on the next request.
@typ... | 14.202285 | 18.517708 | 0.766957 |
username = usernameFromRequest(request)
password = request.args.get('password', [''])[0]
return credentials.UsernamePassword(username, password) | def getCredentials(self, request) | Derive credentials from an HTTP request.
Override SessionWrapper.getCredentials to add the Host: header to the
credentials. This will make web-based virtual hosting work.
@type request: L{nevow.inevow.IRequest}
@param request: The request being handled.
@rtype: L{twisted.cred... | 4.192395 | 4.515297 | 0.928487 |
for tab in tabs:
if not tab.linkURL:
tab.linkURL = webTranslator.linkTo(tab.storeID)
setTabURLs(tab.children, webTranslator) | def setTabURLs(tabs, webTranslator) | Sets the C{linkURL} attribute on each L{Tab} instance
in C{tabs} that does not already have it set
@param tabs: sequence of L{Tab} instances
@param webTranslator: L{xmantissa.ixmantissa.IWebTranslator}
implementor
@return: None | 4.512563 | 3.608898 | 1.250399 |
flatTabs = []
def flatten(tabs):
for t in tabs:
flatTabs.append(t)
flatten(t.children)
flatten(tabs)
forURL = '/' + forURL.path
for t in flatTabs:
if forURL == t.linkURL:
return t
flatTabs.sort(key=lambda t: len(t.linkURL), reverse=Tr... | def getSelectedTab(tabs, forURL) | Returns the tab that should be selected when the current
resource lives at C{forURL}. Call me after L{setTabURLs}
@param tabs: sequence of L{Tab} instances
@param forURL: L{nevow.url.URL}
@return: L{Tab} instance | 2.664828 | 2.922092 | 0.911959 |
setTabURLs(navigation, translator)
getp = IQ(tag).onePattern
def fillSlots(tabs):
for tab in tabs:
if tab.children:
kids = getp('subtabs').fillSlots('kids', fillSlots(tab.children))
else:
kids = ''
yield dictFillSlots(getp('t... | def startMenu(translator, navigation, tag) | Drop-down menu-style navigation view.
For each primary navigation element available, a copy of the I{tab}
pattern will be loaded from the tag. It will have its I{href} slot
filled with the URL for that navigation item. It will have its I{name}
slot filled with the user-visible name of the navigation ... | 9.798429 | 7.9076 | 1.239115 |
setTabURLs(navigation, translator)
selectedTab = getSelectedTab(navigation,
url.URL.fromContext(ctx))
getp = IQ(ctx.tag).onePattern
tabs = []
for tab in navigation:
if tab == selectedTab or selectedTab in tab.children:
p = 'selected-app-tab... | def applicationNavigation(ctx, translator, navigation) | Horizontal, primary-only navigation view.
For the navigation element currently being viewed, copies of the
I{selected-app-tab} and I{selected-tab-contents} patterns will be
loaded from the tag. For all other navigation elements, copies of the
I{app-tab} and I{tab-contents} patterns will be loaded.
... | 5.05267 | 4.176164 | 1.209883 |
for subnav in self.children:
subpath = subnav.pathFromItem(item, avatar)
if subpath:
subpath.insert(0, self)
return subpath
else:
myItem = self.loadForAvatar(avatar)
if myItem is item:
return [self]
... | def pathFromItem(self, item, avatar) | @param item: A thing that we linked to, and such.
@return: a list of [child, grandchild, great-grandchild, ...] that
indicates a path from me to the navigation for that item, or [] if
there is no path from here to there. | 3.864673 | 3.354212 | 1.152185 |
privateKey = rsa.generate_private_key(
public_exponent=65537,
key_size=4096,
backend=default_backend())
return Key(privateKey).toString('openssh') | def _generate() | Generate a new SSH key pair. | 3.919255 | 3.21448 | 1.21925 |
privateKey = Key.fromString(data=self.hostKey)
public = privateKey.public()
factory = SSHFactory()
factory.publicKeys = {'ssh-rsa': public}
factory.privateKeys = {'ssh-rsa': privateKey}
factory.portal = Portal(
IRealm(self.store), [ICredentialsChecker... | def getFactory(self) | Create an L{SSHFactory} which allows access to Mantissa accounts. | 5.251172 | 4.060797 | 1.293138 |
self._window.draw(self._width, self._height, self.terminal) | def _draw(self) | Call the drawing API for the main menu widget with the current known
terminal size and the terminal. | 12.30514 | 5.105531 | 2.410159 |
self._protocol.connectionLost(None)
self._protocol = None
self.terminal.reset()
self._window.filthy()
self._window.repaint() | def reactivate(self) | Called when a sub-protocol is finished. This disconnects the
sub-protocol and redraws the main menu UI. | 11.089338 | 7.812114 | 1.419505 |
viewer = _AuthenticatedShellViewer(list(getAccountNames(self._store)))
self._protocol = app.buildTerminalProtocol(viewer)
self._protocol.makeConnection(_ReturnToMenuWrapper(self, self.terminal)) | def switchTo(self, app) | Use the given L{ITerminalServerFactory} to create a new
L{ITerminalProtocol} and connect it to C{self.terminal} (such that it
cannot actually disconnect, but can do most anything else). Control of
the terminal is delegated to it until it gives up that control by
disconnecting itself fro... | 24.751312 | 17.542028 | 1.410972 |
if self._protocol is not None:
self._protocol.keystrokeReceived(keyID, modifier)
else:
self._window.keystrokeReceived(keyID, modifier) | def keystrokeReceived(self, keyID, modifier) | Forward input events to the application-supplied protocol if one is
currently active, otherwise forward them to the main menu UI. | 2.738042 | 2.12886 | 1.286154 |
if interface is IConchUser:
componentized = Componentized()
user = _BetterTerminalUser(componentized, None)
session = _BetterTerminalSession(componentized)
session.transportFactory = TerminalSessionTransport
session.chainedProtocolFactory = l... | def indirect(self, interface) | Create an L{IConchUser} avatar which will use L{ShellServer} to
interact with the connection. | 8.630676 | 7.695191 | 1.121568 |
api = self.doapi_manager
return api._floating_ip(api.request(self.url)["floating_ip"]) | def fetch(self) | Fetch & return a new `FloatingIP` object representing the floating IP's
current state
:rtype: FloatingIP
:raises DOAPIError: if the API endpoint replies with an error (e.g., if
the floating IP no longer exists) | 30.600605 | 17.684175 | 1.730395 |
if isinstance(droplet_id, Droplet):
droplet_id = droplet_id.id
return self.act(type='assign', droplet_id=droplet_id) | def assign(self, droplet_id) | Assign the floating IP to a droplet
:param droplet_id: the droplet to assign the floating IP to as either
an ID or a `Droplet` object
:type droplet_id: integer or `Droplet`
:return: an `Action` representing the in-progress operation on the
floating IP
:rtype: Act... | 2.99585 | 3.919528 | 0.764339 |
r
if self.get("id") is not None:
return self.id
elif self.get("fingerprint") is not None:
return self.fingerprint
else:
raise TypeError('SSHKey has neither .id nor .fingerprint') | def _id(self) | r"""
The `SSHKey`'s ``id`` field, or if that is not defined, its
``fingerprint`` field. If neither field is defined, accessing this
attribute raises a `TypeError`. | 7.388 | 3.435677 | 2.150377 |
api = self.doapi_manager
return api._ssh_key(api.request(self.url)["ssh_key"]) | def fetch(self) | Fetch & return a new `SSHKey` object representing the SSH key's current
state
:rtype: SSHKey
:raises DOAPIError: if the API endpoint replies with an error (e.g., if
the SSH key no longer exists) | 29.727058 | 20.016985 | 1.485092 |
# The `_ssh_key` is to avoid conflicts with MutableMapping.update.
api = self.doapi_manager
return api._ssh_key(api.request(self.url, method='PUT',
data={"name": name})["ssh_key"]) | def update_ssh_key(self, name) | Update (i.e., rename) the SSH key
:param str name: the new name for the SSH key
:return: an updated `SSHKey` object
:rtype: SSHKey
:raises DOAPIError: if the API endpoint replies with an error | 15.015981 | 19.110291 | 0.785754 |
sender, conn_id, path, rest = msg.split(' ', 3)
headers, rest = tnetstring.pop(rest)
body, _ = tnetstring.pop(rest)
if type(headers) is str:
headers = json.loads(headers)
return MongrelRequest(sender, conn_id, path, headers, body) | def parse(msg) | Helper method for parsing a Mongrel2 request string and returning a new
`MongrelRequest` instance. | 5.261908 | 3.946236 | 1.333399 |
if self.headers.get('connection') == 'close':
return True
elif 'content-length' in self.headers or \
self.headers.get('METHOD') in ['HEAD', 'GET']:
return self.headers.get('connection') != 'keep-alive'
elif self.headers.get('VERSION') == 'HTTP/1.0':
... | def should_close(self) | Check whether the HTTP connection of this request should be closed
after the request is finished.
We check for the `Connection` HTTP header and for the HTTP Version
(only `HTTP/1.1` supports keep-alive. | 3.335934 | 2.972423 | 1.122295 |
flag, timestamp, status = self._query(('GETDAT? 1', (Integer, Float, Integer)))
return {
# convert unix timestamp to datetime object
'timestamp': datetime.datetime.fromtimestamp(timestamp),
# bit 0-3 represent the temperature controller status
'te... | def system_status(self) | The system status codes. | 3.766781 | 3.653505 | 1.031005 |
cmd = 'BEEP', [Float(min=0.1, max=5.0), Integer(min=500, max=5000)]
self._write(cmd, duration, frequency) | def beep(self, duration, frequency) | Generates a beep.
:param duration: The duration in seconds, in the range 0.1 to 5.
:param frequency: The frequency in Hz, in the range 500 to 5000. | 6.384089 | 5.49895 | 1.160965 |
cmd = 'MOVE', [Float, Integer, Integer(min=0, max=14)]
self._write(cmd, position, 0, slowdown) | def move(self, position, slowdown=0) | Move to the specified sample position.
:param position: The target position.
:param slowdown: The slowdown code, an integer in the range 0 to 14,
used to scale the stepper motor speed. 0, the default, is the
fastest rate and 14 the slowest. | 14.072852 | 12.886088 | 1.092097 |
cmd = 'MOVE', [Float, Integer]
self._write(cmd, position, 1) | def move_to_limit(self, position) | Move to limit switch and define it as position.
:param position: The new position of the limit switch. | 24.263332 | 31.890402 | 0.760835 |
cmd = 'MOVE', [Float, Integer]
self._write(cmd, position, 2) | def redefine_position(self, position) | Redefines the current position to the new position.
:param position: The new position. | 30.830339 | 38.137341 | 0.808403 |
if not hasattr(measure, '__call__'):
raise TypeError('measure parameter not callable.')
self.set_temperature(temperature, rate, 'no overshoot', wait_for_stability=False)
start = datetime.datetime.now()
while True:
# The PPMS needs some time to update the... | def scan_temperature(self, measure, temperature, rate, delay=1) | Performs a temperature scan.
Measures until the target temperature is reached.
:param measure: A callable called repeatedly until stability at target
temperature is reached.
:param temperature: The target temperature in kelvin.
:param rate: The sweep rate in kelvin per minu... | 6.894099 | 6.874177 | 1.002898 |
if not hasattr(measure, '__call__'):
raise TypeError('measure parameter not callable.')
self.set_field(field, rate, approach='linear', mode=mode, wait_for_stability=False)
if self.system_status['magnet'].startswith('persist'):
# The persistent switch takes some t... | def scan_field(self, measure, field, rate, mode='persistent', delay=1) | Performs a field scan.
Measures until the target field is reached.
:param measure: A callable called repeatedly until stability at the
target field is reached.
:param field: The target field in Oersted.
.. note:: The conversion is 1 Oe = 0.1 mT.
:param rate: T... | 5.446447 | 5.156691 | 1.05619 |
self.target_field = field, rate, approach, mode
if wait_for_stability and self.system_status['magnet'].startswith('persist'):
# Wait until the persistent switch heats up.
time.sleep(self.magnet_config[5])
while wait_for_stability:
status = self.syste... | def set_field(self, field, rate, approach='linear', mode='persistent',
wait_for_stability=True, delay=1) | Sets the magnetic field.
:param field: The target field in Oersted.
.. note:: The conversion is 1 Oe = 0.1 mT.
:param rate: The field rate in Oersted per minute.
:param approach: The approach mode, either 'linear', 'no overshoot' or
'oscillate'.
:param mode: Th... | 6.337676 | 6.112148 | 1.036898 |
self.target_temperature = temperature, rate, mode
start = datetime.datetime.now()
while wait_for_stability:
# The PPMS needs some time to update the status code, we therefore ignore it for 10s.
if (self.system_status['temperature'] == 'normal stability at target ... | def set_temperature(self, temperature, rate, mode='fast', wait_for_stability=True, delay=1) | Sets the temperature.
:param temperature: The target temperature in kelvin.
:param rate: The sweep rate in kelvin per minute.
:param mode: The sweep mode, either 'fast' or 'no overshoot'.
:param wait_for_stability: If wait_for_stability is `True`, the function call blocks
un... | 6.632922 | 6.657305 | 0.996337 |
assert all_grants or setspec or source, \
"Either '--all', '--setspec' or '--source' is required parameter."
if all_grants:
harvest_all_openaire_projects.delay()
elif setspec:
click.echo("Remote grants loading sent to queue.")
harvest_openaire_projects.delay(setspec=sets... | def loadgrants(source=None, setspec=None, all_grants=False) | Harvest grants from OpenAIRE.
:param source: Load the grants from a local sqlite db (offline).
The value of the parameter should be a path to the local file.
:type source: str
:param setspec: Harvest specific set through OAI-PMH
Creates a remote connection to OpenAIRE.
:type setspec: st... | 5.205545 | 5.01967 | 1.037029 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.