code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if isinstance(cont, np.ndarray): # If cont is an array, it is not a list of contours, # because contours can have different lengths. cont = [cont] ret_list = False else: ret_list = True length = len(cont) inert_ratio_prnc = np.zeros(length, dtype=float) * n...
def get_inert_ratio_prnc(cont)
Compute principal inertia ratio of a contour The principal inertia ratio is rotation-invariant, which makes it applicable to reservoir measurements where e.g. cells are not aligned with the channel. Parameters ---------- cont: ndarray or list of ndarrays of shape (N,2) A 2D array that ...
2.857144
2.773128
1.030296
if isinstance(cont, np.ndarray): # If cont is an array, it is not a list of contours, # because contours can have different lengths. cont = [cont] ret_list = False else: ret_list = True length = len(cont) inert_ratio_raw = np.zeros(length, dtype=float) * np...
def get_inert_ratio_raw(cont)
Compute the inertia ratio of a contour The inertia ratio is computed from the central second order of moments along x (mu20) and y (mu02) via `sqrt(mu20/mu02)`. Parameters ---------- cont: ndarray or list of ndarrays of shape (N,2) A 2D array that holds the contour of an event (in pixels) ...
3.047769
2.879707
1.058361
if isinstance(cont, np.ndarray): # If cont is an array, it is not a list of contours, # because contours can have different lengths. cont = [cont] ret_list = False else: ret_list = True length = len(cont) tilt = np.zeros(length, dtype=float) * np.nan f...
def get_tilt(cont)
Compute tilt of raw contour relative to channel axis Parameters ---------- cont: ndarray or list of ndarrays of shape (N,2) A 2D array that holds the contour of an event (in pixels) e.g. obtained using `mm.contour` where `mm` is an instance of `RTDCBase`. The first and second colum...
3.583105
3.463116
1.034648
''' Constructs a decorator that tags a function with specified strings (@tags). The tags on the decorated function are available via fn.tags ''' def dfn(fn): _tags = getattr(fn, 'tags', set()) _tags.update(tags) fn.tags = _tags return fn return dfn
def tag(*tags)
Constructs a decorator that tags a function with specified strings (@tags). The tags on the decorated function are available via fn.tags
6.543462
2.482571
2.63576
''' Constructs a decorator that marks the fn as raw response format ''' def dfn(fn): tags = getattr(fn, 'tags', set()) tags.add('raw') fn.tags = tags fn.mime = getattr(fn, 'mime', mime) return fn return dfn
def raw(mime='application/octet-stream')
Constructs a decorator that marks the fn as raw response format
5.703156
3.281634
1.737902
''' Called when client opens connection. Initialization is done here. ''' self.id = id(self) self.funcserver = self.application.funcserver self.pysession_id = pysession_id # register this connection with node self.state = self.funcserver.websocks[...
def open(self, pysession_id)
Called when client opens connection. Initialization is done here.
8.339151
5.559124
1.500084
''' Called when client sends a message. Supports a python debugging console. This forms the "eval" part of a standard read-eval-print loop. Currently the only implementation of the python console is in the WebUI but the implementation of a terminal based console...
def on_message(self, msg)
Called when client sends a message. Supports a python debugging console. This forms the "eval" part of a standard read-eval-print loop. Currently the only implementation of the python console is in the WebUI but the implementation of a terminal based console is planned.
4.730626
2.587121
1.828529
''' Called when client closes this connection. Cleanup is done here. ''' if self.id in self.funcserver.websocks: self.funcserver.websocks[self.id] = None ioloop = tornado.ioloop.IOLoop.instance() ioloop.add_callback(lambda: self.funcserver.web...
def on_close(self)
Called when client closes this connection. Cleanup is done here.
3.575003
2.753463
1.298366
''' Remove unexpected keyword arguments from the set of received keyword arguments. ''' # Do not do the cleaning if server config # doesnt ask to ignore if not self.server.IGNORE_UNEXPECTED_KWARGS: return kwargs expected_kwargs = set(inspect.g...
def _clean_kwargs(self, kwargs, fn)
Remove unexpected keyword arguments from the set of received keyword arguments.
4.830881
3.788346
1.275195
''' Dumps the stack of all threads. This function is meant for debugging. Useful when a deadlock happens. borrowed from: http://blog.ziade.org/2012/05/25/zmq-and-gevent-debugging-nightmares/ ''' dump = [] # threads threads = dict([(th.ident, th.name) ...
def dump_stacks(self)
Dumps the stack of all threads. This function is meant for debugging. Useful when a deadlock happens. borrowed from: http://blog.ziade.org/2012/05/25/zmq-and-gevent-debugging-nightmares/
4.804689
2.212036
2.172067
hooks = super(Server, self).define_log_pre_format_hooks() # NOTE enabling logs only on debug mode if self.args.func == self.run and self.args.debug: hooks.append(self._send_log_to_ws) return hooks
def define_log_pre_format_hooks(self)
adds a hook to send to websocket if the run command was selected
7.167579
5.66958
1.264217
self.log_id = 0 # all active websockets and their state self.websocks = {} # all active python interpreter sessions self.pysessions = {} if self.DISABLE_REQUESTS_DEBUG_LOGS: disable_requests_debug_logs() self.threadpool = ThreadPool(self.T...
def run(self)
prepares the api and starts the tornado funcserver
3.62257
3.450547
1.049854
with open(os.path.join(SQL_DIR, filename), 'r') as f: return f.read()
def _get_sql(filename)
Returns the contents of the sql file from the given ``filename``.
2.53549
2.510371
1.010006
stmt = _get_sql('verify-id-and-version.sql') args = dict(id=id, version=version) with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute(stmt, args) try: valid = cursor.fetchone()[0] except TypeError: rai...
def verify_id_n_version(id, version)
Given an ``id`` and ``version``, verify the identified content exists.
4.079874
4.09424
0.996491
try: id, version = split_ident_hash(ident_hash) except IdentHashMissingVersion: # XXX Don't import from views... And don't use httpexceptions from pyramid.httpexceptions import HTTPNotFound from cnxarchive.views.helpers import get_latest_version try: vers...
def get_id_n_version(ident_hash)
From the given ``ident_hash`` return the id and version.
4.909818
4.828675
1.016804
id, version = get_id_n_version(ident_hash) stmt = _get_sql('get-type.sql') args = dict(id=id, version=version) with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute(stmt, args) type = cursor.fetchone()[0] return type
def get_type(ident_hash)
Return the database type for the given ``ident_hash`` As of now, this could either be a 'Module' or 'Collection'.
3.429532
3.367837
1.018319
id, version = get_id_n_version(ident_hash) stmt = _get_sql('get-metadata.sql') args = dict(id=id, version=version) # FIXME The license_url and license_text metadata attributes need to # change to a License structure similar to what is used in cnx-authoring. with db_connect() as db_conn: ...
def get_metadata(ident_hash)
Return the dictionary of metadata from the database. This data is keyed using the cnx-epub data structure.
5.856631
5.348689
1.094966
id, version = get_id_n_version(ident_hash) filename = 'index.cnxml.html' if context is not None: stmt = _get_sql('get-baked-content.sql') args = dict(id=id, version=version, context=context) else: stmt = _get_sql('get-content.sql') args = dict(id=id, version=version...
def get_content(ident_hash, context=None)
Returns the content for the given ``ident_hash``. ``context`` is optionally ident-hash used to find the content within the context of a Collection ident_hash.
3.584771
3.670732
0.976582
if context is None: stmt = _get_sql('get-file-info.sql') args = dict(hash=hash) else: stmt = _get_sql('get-file-info-in-context.sql') id, version = get_id_n_version(context) args = dict(hash=hash, id=id, version=version) with db_connect() as db_conn: wit...
def get_file_info(hash, context=None)
Returns information about the file, identified by ``hash``. If the `context` (an ident-hash) is supplied, the information returned will be specific to that context.
2.746192
2.850962
0.963251
stmt = _get_sql('get-file.sql') args = dict(hash=hash) with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute(stmt, args) try: file, _ = cursor.fetchone() except TypeError: raise FileNotFound(hash) r...
def get_file(hash)
Return the contents of the file as a ``memoryview``.
3.921137
3.5164
1.1151
id, version = get_id_n_version(ident_hash) stmt = _get_sql('get-registered-files-info.sql') args = dict(id=id, version=version) with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute(stmt, args) rows = cursor.fetchall() if rows is None: ...
def get_registered_files(ident_hash)
Returns a list SHA1 hashes for registered file entries identified by the given module ``ident_hash``. Note, it's possible for a module to reference a file without having a registered file entry for it. Note, all files are included, including the raw form of the content.
4.110325
4.203553
0.977822
id, version = get_id_n_version(ident_hash) stmt = _get_sql('get-tree.sql') args = dict(id=id, version=version, baked=baked) with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute(stmt, args) try: tree = cursor.fetchone()[0] ...
def get_tree(ident_hash, baked=False)
Return a tree structure of the Collection
2.88517
2.906744
0.992578
o = subprocess.check_output(['file', '--mime-type', '-Lb', filepath]) o = o.strip() return o
def guess_media_type(filepath)
Returns the media-type of the file at the given ``filepath``
6.0741
6.401397
0.948871
with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute( "SELECT module_ident FROM modules " "WHERE uuid = %s " "AND CONCAT_WS('.', major_version, minor_version) = %s", (id, version)) try: ...
def lookup_module_ident(id, version)
Return the ``module_ident`` for the given ``id`` & major and minor version as a tuple.
3.78195
3.856773
0.9806
resource_hash = get_file_sha1(file) with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute("SELECT fileid FROM files WHERE sha1 = %s", (resource_hash,)) try: fileid = cursor.fetchone()[0] except (I...
def insert_file(file, media_type)
Upsert the ``file`` and ``media_type`` into the files table. Returns the ``fileid`` and ``sha1`` of the upserted file.
2.305042
2.140742
1.076749
with db_connect() as db_conn: with db_conn.cursor() as cursor: cursor.execute("SELECT true FROM module_files " "WHERE module_ident = %s " "AND filename = %s", (module_ident, filename,)) try: ...
def upsert_module_file(module_ident, fileid, filename)
Upsert a file associated with ``fileid`` with ``filename`` as a module_files entry associated with content at ``module_ident``.
1.678392
1.760046
0.953607
resource_hash = get_file_sha1(file) with db_connect() as db_conn: with db_conn.cursor() as cursor: s_ident_hash = split_ident_hash(ident_hash) module_ident = lookup_module_ident(*s_ident_hash) fileid, resource_hash = insert_file(file, media_type) upse...
def inject_resource(ident_hash, file, filename, media_type)
Injects the contents of ``file`` (a file-like object) into the database as ``filename`` with ``media_type`` in association with the content at ``ident_hash``.
4.280247
4.470766
0.957386
if isinstance(mask, np.ndarray) and len(mask.shape) == 2: mask = [mask] ret_list = False else: ret_list = True contours = [] for mi in mask: c0 = find_contours(mi.transpose(), level=.9999, positive_orientation="l...
def get_contour(mask)
Compute the image contour from a mask The contour is computed in a very inefficient way using scikit-image and a conversion of float coordinates to pixel coordinates. Parameters ---------- mask: binary ndarray of shape (M,N) or (K,M,N) The mask outlining the pixel positions of the event. ...
3.3414
3.367119
0.992362
def scan(self, stop_on_first=True, base_ip=0): tvs = [] # Check if base_ip has been passed if base_ip == 0: # Find IP address of computer pymitv is running on sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.connect(("8.8.8.8", 80...
Scans the local network for TVs.
null
null
null
def check_ip(ip, log=False): if log: print('Checking ip: {}...'.format(ip)) request_timeout = 0.1 try: tv_url = 'http://{}:6095/request?action=isalive'.format(ip) request = requests.get(tv_url, timeout=request_timeout) except reque...
Attempts a connection to the TV and checks if there really is a TV.
null
null
null
types = (t[5:] for t in dir(f) if t[:4] == 'TYPE' and getattr(f, t) == f.type) return next(types)
def get_field_type(f)
Obtain the type name of a GRPC Message field.
5.690271
5.428833
1.048157
type_name = get_field_type(f) if type_name == 'MESSAGE' and \ {sf.name for sf in f.message_type.fields} == {'key', 'value'}: return 'map<string, string>' elif type_name == 'MESSAGE': return f.message_type.full_name elif type_name == 'ENUM': return f.enum_type.ful...
def get_field_description(f)
Get the type description of a GRPC Message field.
2.836334
2.721852
1.04206
if args and not use_signature: raise NotImplementedError("Only keyword arguments allowed in Python2") if use_signature: new_kwargs = {kw: unwrap(value) for kw, value in kwargs.items()} new_args = tuple(unwrap(value) for value in args) bound_args = method.signature.bind( ...
def make_static_request(method, *args, **kwargs)
Creates a request from a static method function call.
3.24918
3.199406
1.015557
if args and not use_signature: raise NotImplementedError("Only keyword arguments allowed in Python2") new_kwargs = {kw: unwrap(value) for kw, value in kwargs.items()} if use_signature: new_args = tuple(unwrap(value) for value in args) bound_args = method.signature.bind( ...
def make_request(self, method, *args, **kwargs)
Creates a request from a method function call.
3.428366
3.365195
1.018772
if m.is_simple: def simple_method(self): return apply_transform( self.__service__, m.output_transform, grpc_call(self.__service__, m, unwrap(self))) return simple_method elif m.input_transform is not None: def transform_met...
def method_wrapper(m)
Generates a method from a `GrpcMethod` definition.
2.39926
2.247616
1.067469
if self.static and not self.uses_request: return 'Empty' if not self.uses_request: return None if isinstance(self.uses_request, str): return self.uses_request return to_camel_case(self.name) + "Request"
def request_name(self)
Generate the name of the request.
5.139553
4.311216
1.192135
if self.static and not self.uses_request: return getattr(xenon_pb2, 'Empty') if not self.uses_request: return None return getattr(xenon_pb2, self.request_name)
def request_type(self)
Retrieve the type of the request, by fetching it from `xenon.proto.xenon_pb2`.
6.978578
4.647303
1.50164
if not use_signature: raise NotImplementedError("Python 3 only.") if self.static: parameters = \ (Parameter(name='cls', kind=Parameter.POSITIONAL_ONLY),) else: parameters = \ (Parameter(name...
def signature(self)
Create a signature for this method, only in Python > 3.4
3.659956
3.470956
1.054452
s = getattr(servicer, to_lower_camel_case(self.name)).__doc__ \ or "TODO: no docstring in .proto file" if self.uses_request: s += "\n" for field in get_fields(self.request_type): if field != self.field_name: type_info = ge...
def docstring(self, servicer)
Generate a doc-string.
4.080018
3.981297
1.024796
filtered_string = [] if isinstance(string, str): string = unicode(string, 'utf-8') for i in unicodedata.normalize('NFKC', string): cat = unicodedata.category(i)[0] # filter out all the non letter and non number characters from the # input (L is letter and N is number) ...
def slugify(string)
Return a slug for the unicode_string. (lowercase, only letters and numbers, hyphens replace spaces)
3.843371
3.655943
1.051267
if isinstance(item, list): return [utf8(i) for i in item] if isinstance(item, tuple): return tuple([utf8(i) for i in item]) if isinstance(item, dict): return {utf8(k): utf8(v) for k, v in item.items()} try: return item.decode('utf-8') except: # bare except since...
def utf8(item)
Change all python2 str/bytes instances to unicode/python3 str.
2.284741
2.173552
1.051155
try: uuid, (mj_ver, mn_ver) = split_ident_hash( ident_hash, split_version=True) except IdentHashMissingVersion as e: uuid, mj_ver, mn_ver = e.id, None, None args = [uuid] stmt = "SELECT module_ident FROM {} WHERE uuid = %s" table_name = 'modules' if mj_ver is Non...
def get_module_ident_from_ident_hash(ident_hash, cursor)
Return the moduleid for a given ``ident_hash``.
2.949872
3.002506
0.98247
uuid, version = split_ident_hash(ident_hash) cursor.execute(SQL['get-tree-by-uuid-n-version'], (uuid, version, as_collated,)) try: tree = cursor.fetchone()[0] except TypeError: # NoneType raise ContentNotFound() if type(tree) in (type(''), type(u'')): ...
def get_tree(ident_hash, cursor, as_collated=False)
Return a JSON representation of the binder tree for ``ident_hash``.
4.031101
3.882854
1.03818
cursor.execute(SQL['get-collated-content'], (ident_hash, context_ident_hash,)) try: return cursor.fetchone()[0] except TypeError: # NoneType return
def get_collated_content(ident_hash, context_ident_hash, cursor)
Return collated content for ``ident_hash``.
3.308775
3.12969
1.057221
plan = plpy.prepare("SELECT uuid FROM modules WHERE moduleid = $1;", ('text',)) result = plpy.execute(plan, (moduleid,), 1) if result: return result[0]['uuid']
def get_module_uuid(plpy, moduleid)
Retrieve page uuid from legacy moduleid.
4.138309
4.10439
1.008264
plan = plpy.prepare('''\ SELECT m.module_ident FROM modules m WHERE m.moduleid = $1 ORDER BY revised DESC''', ('text',)) results = plpy.execute(plan, (moduleid,), 1) if results: return results[0]['module_ident']
def get_current_module_ident(moduleid, plpy)
Retrieve module_ident for a given moduleid. Note that module_ident is used only for internal database relational associations, and is equivalent to a uuid@version for a given document.
5.525166
5.472147
1.009689
# Make sure to always return the max minor version that is already in the # database, in case the given module_ident is not the latest version plan = plpy.prepare('''\ WITH t AS ( SELECT uuid, major_version FROM modules WHERE module_ident = $1 ...
def get_minor_version(module_ident, plpy)
Retrieve minor version only given module_ident.
4.350901
4.135458
1.052096
# Make sure to only return one match per collection and only if it is the # latest collection (which may not be the same as what is in # latest_modules) plan = plpy.prepare(''' WITH RECURSIVE t(node, parent, path, document) AS ( SELECT tr.nodeid, tr.parent_id, ARRAY[tr.nodeid], tr.documenti...
def get_collections(module_ident, plpy)
Get all the collections that the module is part of.
5.206025
5.129691
1.014881
plan = plpy.prepare(''' WITH RECURSIVE t(node, parent, path, document) AS ( SELECT tr.nodeid, tr.parent_id, ARRAY[tr.nodeid], tr.documentid FROM trees tr WHERE tr.documentid = $1 and tr.is_collated = 'False' UNION ALL SELECT c.nodeid, c.parent_id, path || ARRAY[c.nodeid]...
def get_subcols(module_ident, plpy)
Get all the sub-collections that the module is part of.
4.108064
3.93214
1.04474
get_tree = plpy.prepare(''' WITH RECURSIVE t(node, parent, document, title, childorder, latest, path) AS (SELECT tr.nodeid, tr.parent_id, tr.documentid, tr.title, tr.childorder, tr.latest, ARRAY[tr.nodeid] FROM trees tr WHERE tr.documentid = $1 AND tr.is_c...
def rebuild_collection_tree(old_collection_ident, new_document_id_map, plpy)
Create a new tree for the collection based on the old tree. This uses new document ids, replacing old ones.
2.882151
2.90575
0.991879
sql = ''' INSERT INTO modules (portal_type, moduleid, uuid, version, name, created, revised, abstractid, licenseid, doctype, submitter, submitlog, stateid, parent, language, authors, maintainers, licensors, parentauthors, google_analytics, buylink, print_style, major_version...
def republish_collection(submitter, submitlog, next_minor_version, collection_ident, plpy, revised=None)
Insert a new row for collection_ident with a new version. Returns the module_ident of the row inserted.
2.968087
2.902444
1.022616
modified = 'OK' legacy_major, legacy_minor = legacy_version.split('.') if portal_type == 'Collection': # For collections, both major and minor needs to be set modified = 'MODIFY' td['new']['major_version'] = int(legacy_minor) if td['new']['minor_version'] is None: ...
def set_version(portal_type, legacy_version, td)
Set the major_version and minor_version if they are not set.
4.969017
4.706717
1.055729
portal_type = td['new']['portal_type'] modified = 'OK' moduleid = td['new']['moduleid'] legacy_version = td['new']['version'] submitter = td['new']['submitter'] submitlog = td['new']['submitlog'] modified = set_version(portal_type, legacy_version, td) current_module_ident = get_cu...
def republish_module(td, plpy)
When a module is republished, create new minor versions of collections. All collections (including subcollections) that this module is contained in part of will need to be updated (a minor update). e.g. there is a collection c1 v2.1, which contains a chapter sc1 v2.1, which contains a module m1 v3. Wh...
4.598282
4.631365
0.992857
# Is this an insert from legacy? Legacy always supplies the version. is_legacy_publication = td['new']['version'] is not None if not is_legacy_publication: # Bail out, because this trigger only applies to legacy publications. return "OK" plpy.log('Trigger fired on %s' % (td['new'][...
def republish_module_trigger(plpy, td)
Trigger called from postgres database when republishing a module. When a module is republished, the versions of the collections that it is part of will need to be updated (a minor update). e.g. there is a collection c1 v2.1, which contains module m1 v3 m1 is updated, we have a new row in the modules...
6.611382
7.224203
0.915171
modified_state = "OK" portal_type = td['new']['portal_type'] uuid = td['new']['uuid'] moduleid = td['new']['moduleid'] version = td['new']['version'] # Is this an insert from legacy? Legacy always supplies the version. is_legacy_publication = version is not None if moduleid is Non...
def assign_moduleid_default_trigger(plpy, td)
Trigger to fill in legacy ``moduleid`` when publishing. This correctly assigns ``moduleid`` value to cnx-publishing publications. This does NOT include matching the ``moduleid`` to previous revision by way of ``uuid``. This correctly updates the sequence values when a legacy publication specifies ...
4.426039
4.321385
1.024218
modified_state = "OK" portal_type = td['new']['portal_type'] version = td['new']['version'] minor_version = td['new']['minor_version'] # Set the minor version on collections, because by default it is # None/Null, which is the correct default for modules. if minor_version is None and po...
def assign_version_default_trigger(plpy, td)
Trigger to fill in legacy data fields. A compatibilty trigger to fill in legacy data fields that are not populated when inserting publications from cnx-publishing. If this is not a legacy publication the ``version`` will be set based on the ``major_version`` value.
4.85262
4.919453
0.986414
modified_state = "OK" uuid = td['new']['uuid'] # Only do the procedure if this is a legacy publication. if uuid is None: modified_state = "MODIFY" plan = plpy.prepare(, ('integer',)) uuid_ = plpy.execute(plan, (td['new']['licenseid'],))[0]['uuid'] td['new']['uuid'] ...
def assign_document_controls_default_trigger(plpy, td)
Trigger to fill in document_controls when legacy publishes. A compatibilty trigger to fill in ``uuid`` and ``licenseid`` columns of the ``document_controls`` table that are not populated when inserting publications from legacy. This uuid default is not on ``modules.uuid`` column itself, because th...
8.988266
8.762802
1.02573
modified_state = "OK" uuid_ = td['new']['uuid'] authors = td['new']['authors'] and td['new']['authors'] or [] maintainers = td['new']['maintainers'] and td['new']['maintainers'] or [] is_legacy_publication = td['new']['version'] is not None if not is_legacy_publication: return modi...
def upsert_document_acl_trigger(plpy, td)
Trigger for filling in acls when legacy publishes. A compatibility trigger to upsert authorization control entries (ACEs) for legacy publications.
4.10413
3.972446
1.033149
modified_state = "OK" authors = td['new']['authors'] and td['new']['authors'] or [] maintainers = td['new']['maintainers'] and td['new']['maintainers'] or [] licensors = td['new']['licensors'] and td['new']['licensors'] or [] is_legacy_publication = td['new']['version'] is not None if not ...
def upsert_users_from_legacy_publication_trigger(plpy, td)
A compatibility trigger to upsert users from legacy persons table.
3.406415
3.325228
1.024415
modified_state = "OK" users = td['new']['personids'] and td['new']['personids'] or [] plan = plpy.prepare(, ['text[]']) existing_users = set([r['username'] for r in plpy.execute(plan, (users,))]) new_users = set(users).difference(existing_users) for username in new...
def insert_users_for_optional_roles_trigger(plpy, td)
Trigger to update users from optional roles entries. A compatibility trigger to insert users from moduleoptionalroles records. This is primarily for legacy compatibility, but it is not possible to tell whether the entry came from legacy or cnx-publishing. Therefore, we only insert into users.
5.468854
5.824304
0.938971
module_ident = td['new']['module_ident'] filename = td['new']['filename'] msg = "produce {}->{} for module_ident = {}" def check_for(filenames, module_ident): stmt = plpy.prepare(, ['text', 'integer']) any_exist = False for filename in filenames: result...
def add_module_file(plpy, td)
Database trigger for adding a module file. When a legacy ``index.cnxml`` is added, this trigger transforms it into html and stores it as ``index.cnxml.html``. When a cnx-publishing ``index.cnxml.html`` is added, this trigger checks if ``index.html.cnxml`` exists before transforming it into cnxml an...
4.239377
3.815925
1.11097
plan = plpy.prepare(, ('integer',)) result = plpy.execute(plan, (module_ident,), 1)[0] abstractid, cnxml, html = ( result['abstractid'], result['abstract'], result['html']) if cnxml is not None and html is not None: return # skip # TODO Prevent blank abstracts (abstract = null ...
def _transform_abstract(plpy, module_ident)
Transform abstract, bi-directionally. Transforms an abstract using one of content columns ('abstract' or 'html') to determine which direction the transform will go (cnxml->html or html->cnxml). A transform is done on either one of them to make the other value. If no value is supplied, the trigger r...
4.664723
3.937679
1.184638
cursor.execute(''' WITH RECURSIVE t(node, parent, document, path) AS ( SELECT tr.nodeid, tr.parent_id, tr.documentid, ARRAY[tr.nodeid] FROM trees tr WHERE tr.documentid = %s and tr.is_collated = 'False' UNION ALL SELECT c.nodeid, c.parent_id, c.documentid, path || ARRAY[...
def get_collection_tree(collection_ident, cursor)
Build and retrieve json tree representation of a book.
3.954502
3.947386
1.001803
cursor.execute(, (id,)) return [i[0] for i in cursor.fetchall()]
def get_module_can_publish(cursor, id)
Return userids allowed to publish this book.
6.772374
4.861068
1.393187
nodes = [] for item in tree['contents']: if 'contents' in item: sub_nodes = tree_to_nodes(item, context=context, metadata=metadata) if metadata is None: metadata = {} else: metadata = metadata.copy() for key in ('ti...
def tree_to_nodes(tree, context=None, metadata=None)
Assembles ``tree`` nodes into object models. If ``context`` is supplied, it will be used to contextualize the contents of the nodes. Metadata will pass non-node identifying values down to child nodes, if not overridden (license, timestamps, etc)
2.71997
2.792903
0.973886
model = factory(ident_hash, baked=(format != 'raw')) if isinstance(model, cnxepub.Document): model = cnxepub.TranslucentBinder(nodes=[model]) cnxepub.make_epub(model, file)
def create_epub(ident_hash, file, format='raw')
Creates an epub from an ``ident_hash``, which is output to the given ``file`` (a file-like object). Returns None, writes to the given ``file``.
13.739429
15.499855
0.886423
settings = get_current_registry().settings exports_dirs = settings['exports-directories'].split() args = request.matchdict ident_hash, type = args['ident_hash'], args['type'] id, version = split_ident_hash(ident_hash) with db_connect() as db_connection: with db_connection.cursor() ...
def get_export(request)
Retrieve an export file.
4.771102
4.687749
1.017781
request = get_current_request() type_info = dict(request.registry.settings['_type_info']) metadata = get_content_metadata(id, version, cursor) legacy_id = metadata['legacy_id'] legacy_version = metadata['legacy_version'] reachable_dirs = [dir for dir in exports_dirs if safe_stat(dir)] ...
def get_export_files(cursor, id, version, types, exports_dirs, read_file=True)
Retrieve files associated with document.
2.845331
2.861943
0.994196
# Do the module lookup args = dict(id=id, version=version) # FIXME We are doing two queries here that can hopefully be # condensed into one. cursor.execute(SQL['get-module-metadata'], args) try: result = cursor.fetchone()[0] # version is what we want to return, but in ...
def get_content_metadata(id, version, cursor)
Return metadata related to the content from the database.
10.466786
10.612794
0.986242
if level >= 1 or level <= 0: raise ValueError("`level` must be in (0,1), got '{}'!".format(level)) # level relative to maximum level = level * density.max() # xy coordinates if len(x.shape) == 2: assert np.all(x[:, 0] == x[:, 1]) x = x[:, 0] if len(y.shape) == 2: ...
def find_contours_level(density, x, y, level, closed=False)
Find iso-valued density contours for a given level value Parameters ---------- density: 2d ndarray of shape (M, N) Kernel density estimate for which to compute the contours x: 2d ndarray of shape (M, N) or 1d ndarray of size M X-values corresponding to `kde` y: 2d ndarray of shape (...
2.754715
2.872723
0.958921
# xy coordinates if len(x.shape) == 2: assert np.all(x[:, 0] == x[:, 1]) x = x[:, 0] if len(y.shape) == 2: assert np.all(y[0, :] == y[1, :]) y = y[0, :] # remove bad events bad = get_bad_vals(xp, yp) xp = xp[~bad] yp = yp[~bad] # Normalize interpola...
def get_quantile_levels(density, x, y, xp, yp, q, normalize=True)
Compute density levels for given quantiles by interpolation For a given 2D density, compute the density levels at which the resulting contours contain the fraction `1-q` of all data points. E.g. for a measurement of 1000 events, all contours at the level corresponding to a quantile of `q=0.95` (95t...
2.927333
2.889114
1.013229
if quantile >= 1 or quantile <= 0: raise ValueError("Invalid value for `quantile`: {}".format(quantile)) # remove bad events bad = get_bad_vals(xp, yp) xp = xp[~bad] yp = yp[~bad] # initial guess level = quantile # error of current iteration err = 1 # iteration fac...
def _find_quantile_level(density, x, y, xp, yp, quantile, acc=.01, ret_err=False)
Find density level for a given data quantile by iteration Parameters ---------- density: 2d ndarray of shape (M, N) Kernel density estimate for which to compute the contours x: 2d ndarray of shape (M, N) or 1d ndarray of size M X-values corresponding to `kde` y: 2d ndarray of shape ...
4.291171
4.393209
0.976774
di = {} for a, b in tup: di.setdefault(a, []).append(b) for key, val in di.items(): dictlist.append((key, val)) return dictlist
def _convert(tup, dictlist)
:param tup: a list of tuples :param di: a dictionary converted from tup :return: dictionary
2.650205
2.937761
0.902118
res = [] for ele in val_list: res.append(ele.upper()) return res
def _upper(val_list)
:param val_list: a list of strings :return: a list of upper-cased strings
3.337845
3.211941
1.039199
# Build the SQL statement. statement, arguments = _build_search(query) # Execute the SQL. if statement is None and arguments is None: return QueryResults([], [], 'AND') with db_connect() as db_connection: with db_connection.cursor() as cursor: cursor.execute(statem...
def search(query, query_type=DEFAULT_QUERY_TYPE)
Search database using parsed query. Executes a database search query from the given ``query`` (a ``Query`` object) and optionally accepts a list of search weights. By default, the search results are ordered by weight. :param query: containing terms, filters, and sorts. :type query: Query :retu...
4.107944
4.073926
1.00835
if query_string.count('"') % 2 == 0: # no unbalanced quotes to fix return query_string fields = [] # contains what's matched by the regexp # e.g. fields = ['sort:pubDate', 'author:"first last"'] def f(match): fields.append(match.string[matc...
def fix_quotes(cls, query_string)
Heuristic attempt to fix unbalanced quotes in query_string.
5.83009
5.372651
1.085142
try: node_tree = grammar.parse(query_string) except IncompleteParseError: query_string = cls.fix_quotes(query_string) node_tree = grammar.parse(query_string) structured_query = DictFormater().visit(node_tree) return cls([t for t in structure...
def from_raw_query(cls, query_string)
Parse raw string to query. Given a raw string (typically typed by the user), parse to a structured format and initialize the class.
5.573222
5.571968
1.000225
abstract_terms = self.fields.get('abstract', []) if abstract_terms: sql = _read_sql_file('highlighted-abstract') else: sql = _read_sql_file('get-abstract') arguments = {'id': self['id'], 'query': ' & '.join(abstract_terms), ...
def highlighted_abstract(self)
Highlight the found terms in the abstract text.
3.578054
3.38186
1.058014
terms = self.fields.get('fulltext', []) if not terms: return None arguments = {'id': self['id'], 'query': ' & '.join(terms), } with db_connect() as db_connection: with db_connection.cursor() as cursor: ...
def highlighted_fulltext(self)
Highlight the found terms in the fulltext.
4.386812
4.179885
1.049505
r if data_predict is None: data_predict = self.data else: data_predict = _adjust_shape(data_predict, self.k_vars) pdf_est = [] for i in range(np.shape(data_predict)[0]): pdf_est.append(gpke(self.bw, data=self.data, ...
def pdf(self, data_predict=None)
r""" Evaluate the probability density function. Parameters ---------- data_predict: array_like, optional Points to evaluate at. If unspecified, the training data is used. Returns ------- pdf_est: array_like Probability density function e...
3.938848
4.259577
0.924704
prefix = Path(sys.prefix) locations = [ prefix / 'lib', prefix / 'local' / 'lib' ] for location in locations: jar_file = location / 'xenon-grpc-{}-all.jar'.format( xenon_grpc_version) if not jar_file.exists(): continue else: ...
def find_xenon_grpc_jar()
Find the Xenon-GRPC jar-file, windows version.
2.865325
2.814629
1.018011
logger = logging.getLogger('xenon') logger.info('Terminating Xenon-GRPC server.') os.kill(process.pid, signal.SIGINT) process.wait()
def kill_process(process)
Kill the process group associated with the given process. (posix)
5.636439
6.589113
0.855417
jar_file = find_xenon_grpc_jar() if not jar_file: raise RuntimeError("Could not find 'xenon-grpc' jar file.") cmd = ['java', '-jar', jar_file, '-p', str(port)] if not disable_tls: crt_file, key_file = create_self_signed_cert() cmd.extend([ '--server-cert-chain...
def start_xenon_server(port=50051, disable_tls=False)
Start the server.
2.320786
2.284315
1.015966
def send_keystrokes(ip, keystrokes, wait=False): tv_url = 'http://{}:6095/controller?action=keyevent&keycode='.format(ip) for keystroke in keystrokes: if keystroke == 'wait' or wait is True: time.sleep(0.7) else: request = reque...
Connects to TV and sends keystroke via HTTP.
null
null
null
def mute(ip): tv_url = 'http://{}:6095/controller?action=keyevent&keycode='.format(ip) count = 0 while count > 30: count = count + 1 request = requests.get(tv_url + 'volumedown') if request.status_code != 200: return False ...
Polyfill for muting the TV.
null
null
null
results = {} args = request.matchdict ident_hash = args['ident_hash'] args['search_term'] = request.params.get('q', '') query_type = request.params.get('query_type', '') combiner = '' if query_type: if query_type.lower() == 'or': combiner = '_or' id, version =...
def in_book_search(request)
Full text, in-book search.
2.9484
2.94373
1.001587
results = {} args = request.matchdict ident_hash = args['ident_hash'] page_ident_hash = args['page_ident_hash'] try: page_uuid, _ = split_ident_hash(page_ident_hash) except IdentHashShortId as e: page_uuid = get_uuid(e.id) except IdentHashMissingVersion as e: p...
def in_book_search_highlighted_results(request)
In-book search - returns a highlighted version of the HTML.
3.341659
3.34368
0.999396
dat = np.asarray(dat) if dat.ndim > 2: dat = np.squeeze(dat) if dat.ndim == 1 and k_vars > 1: # one obs many vars nobs = 1 elif dat.ndim == 1 and k_vars == 1: # one obs one var nobs = len(dat) else: if np.shape(dat)[0] == k_vars and np.shape(dat)[1] != k_vars: ...
def _adjust_shape(dat, k_vars)
Returns an array of shape (nobs, k_vars) for use with `gpke`.
2.741863
2.560628
1.070778
r kertypes = dict(c=ckertype, o=okertype, u=ukertype) Kval = np.empty(data.shape) for ii, vtype in enumerate(var_type): func = kernel_func[kertypes[vtype]] Kval[:, ii] = func(bw[ii], data[:, ii], data_predict[ii]) iscontinuous = np.array([c == 'c' for c in var_type]) dens = Kva...
def gpke(bw, data, data_predict, var_type, ckertype='gaussian', okertype='wangryzin', ukertype='aitchisonaitken', tosum=True)
r""" Returns the non-normalized Generalized Product Kernel Estimator Parameters ---------- bw: 1-D ndarray The user-specified bandwidth parameters. data: 1D or 2-D ndarray The training data. data_predict: 1-D ndarray The evaluation points at which the kernel estimation i...
3.648162
3.731574
0.977647
if bw is None: bw = 'normal_reference' if not isinstance(bw, string_types): self._bw_method = "user-specified" res = np.asarray(bw) else: # The user specified a bandwidth selection method self._bw_method = bw # Wor...
def _compute_bw(self, bw)
Computes the bandwidth of the data. Parameters ---------- bw: array_like or str If array_like: user-specified bandwidth. If a string, should be one of: - cv_ml: cross validation maximum likelihood - normal_reference: normal reference rule...
4.071315
3.216293
1.265841
self.n_res = defaults.n_res self.n_sub = defaults.n_sub self.randomize = defaults.randomize self.return_median = defaults.return_median self.efficient = defaults.efficient self.return_only_bw = defaults.return_only_bw self.n_jobs = defaults.n_jobs
def _set_defaults(self, defaults)
Sets the default values for the efficient estimation
3.691325
3.463553
1.065762
config = RawConfigParser() config.read(os.path.join('..', 'setup.cfg')) return config.get('metadata', 'version')
def get_version()
Return package version from setup.cfg
3.130256
2.518918
1.242699
root = etree.Element('sitemapindex', nsmap={None: SITEMAP_NS}) for sitemap in self.sitemaps: sm = etree.SubElement(root, 'sitemap') etree.SubElement(sm, 'loc').text = sitemap.url if hasattr(sitemap.lastmod, 'strftime'): etree.SubElement(sm, 'l...
def to_string(self)
Convert SitemapIndex into a string.
1.902049
1.747869
1.08821
if len(args) == 1 and not kwargs and isinstance(args[0], UrlEntry): self.urls.append(args[0]) else: self.urls.append(UrlEntry(*args, **kwargs))
def add_url(self, *args, **kwargs)
Add a new url to the sitemap. This function can either be called with a :class:`UrlEntry` or some keyword and positional arguments that are forwarded to the :class:`UrlEntry` constructor.
2.410636
2.049867
1.175996
root = etree.Element('urlset', nsmap={None: SITEMAP_NS}) for url in self.urls: url.generate(root) return etree.tostring(root, pretty_print=True, xml_declaration=True, encoding='utf-8')
def to_string(self)
Convert the sitemap into a string.
3.216525
2.519057
1.276877
if root_element is not None: url = etree.SubElement(root_element, 'url') else: url = etree.Element('url') etree.SubElement(url, 'loc').text = self.loc if self.lastmod: if hasattr(self.lastmod, 'strftime'): etree.SubElement(url,...
def generate(self, root_element=None)
Create <url> element under root_element.
1.697875
1.526143
1.112527
input_queue = Queue() def input_stream(): while True: cmd, msg = input_queue.get() if cmd == 'end': input_queue.task_done() return elif cmd == 'msg': yield msg.encode() input_queue.task_done() ...
def make_input_stream()
Creates a :py:class:`Queue` object and a co-routine yielding from that queue. The queue should be populated with 2-tuples of the form `(command, message)`, where `command` is one of [`msg`, `end`]. When the `end` command is recieved, the co-routine returns, ending the stream. When a `msg` command ...
2.977271
2.400654
1.240192
for blocked in PAGES_TO_BLOCK: if blocked[0] != '*': blocked = '*' + blocked rx = re.compile(blocked.replace('*', '[^$]*')) if rx.match(page): return False return True
def notblocked(page)
Determine if given url is a page that should be in sitemap.
4.572641
4.520256
1.011589
xml = Sitemap() author = request.matchdict.get('from_id') if author is not None: match = "AND '{}' = authors[1]".format(author) else: match = '' with db_connect() as db_connection: with db_connection.cursor() as cursor: cursor.execute(.format(match)) ...
def sitemap(request)
Return a sitemap xml file for search engines.
4.28802
4.192922
1.022681
sitemaps = [] with db_connect() as db_connection: with db_connection.cursor() as cursor: cursor.execute() for author, revised in cursor.fetchall(): sitemaps.append(Sitemap(url=request.route_url( 'sitemap', from_id=author), ...
def sitemap_index(request)
Return a sitemap index xml file for search engines.
3.932339
3.896585
1.009176