code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
r if (status is None) == (locked is None): ### TODO: Is TypeError the right type of error? raise TypeError('Exactly one of "status" and "locked" must be' ' specified') droplets = map(self._droplet, droplets) if status is not None: ...
def wait_droplets(self, droplets, status=None, locked=None, wait_interval=None, wait_time=None)
r""" Poll the server periodically until all droplets in ``droplets`` have reached some final state, yielding each `Droplet`'s final value when it's done. If ``status`` is non-`None`, ``wait_droplets`` will wait for each droplet's ``status`` field to equal the given value. If ``...
3.140031
4.371801
0.718247
r return self._wait(map(self._action, actions), "done", True, wait_interval, wait_time)
def wait_actions(self, actions, wait_interval=None, wait_time=None)
r""" Poll the server periodically until all actions in ``actions`` have either completed or errored out, yielding each `Action`'s final value as it ends. If ``wait_time`` is exceeded, a `WaitTimeoutError` (containing any remaining in-progress actions) is raised. If a `K...
12.646825
23.240028
0.544183
acts = [] for o in objects: a = o.fetch_last_action() if a is None: yield o else: acts.append(a) for a in self.wait_actions(acts, wait_interval, wait_time): yield a.fetch_resource()
def wait_actions_on_objects(self, objects, wait_interval=None, wait_time=None)
.. versionadded:: 0.2.0 Poll the server periodically until the most recent action on each resource in ``objects`` has finished, yielding each resource's final state when the corresponding action is done. If ``wait_time`` is exceeded, a `WaitTimeoutError` (containing any remaini...
3.404352
3.242467
1.049927
data = {"name": name, "public_key": public_key} data.update(kwargs) return self._ssh_key(self.request('/v2/account/keys', method='POST', data=data)["ssh_key"])
def create_ssh_key(self, name, public_key, **kwargs)
Add a new SSH public key resource to the account :param str name: the name to give the new SSH key resource :param str public_key: the text of the public key to register, in the form used by :file:`authorized_keys` files :param kwargs: additional fields to include in the API request...
4.362464
4.898386
0.890592
# pylint: disable=redefined-builtin r params = {} if type is not None: params["type"] = type if private is not None: params["private"] = 'true' if private else 'false' return map(self._image, self.paginate('/v2/images', 'images', ...
def fetch_all_images(self, type=None, private=None)
r""" Returns a generator that yields all of the images available to the account :param type: the type of images to fetch: ``"distribution"``, ``"application"``, or all (`None`); default: `None` :type type: string or None :param bool private: whether to only return th...
3.457084
4.675754
0.739364
if isinstance(ip_address, FloatingIP): ip_address = ip_address.ip data = {"name": name, "ip_address": ip_address} data.update(kwargs) return self._domain(self.request('/v2/domains', method='POST', data=data)["do...
def create_domain(self, name, ip_address, **kwargs)
Add a new domain name resource to the account. Note that this method does not actually register a new domain name; it merely configures DigitalOcean's nameservers to provide DNS resolution for the domain. See `How To Set Up a Host Name with DigitalOcean <https://www.digitalocean.com/co...
4.107467
4.088609
1.004612
if (droplet_id is None) == (region is None): ### TODO: Is TypeError the right type of error? raise TypeError('Exactly one of "droplet_id" and "region" must be' ' specified') if droplet_id is not None: if isinstance(droplet_id, Drop...
def create_floating_ip(self, droplet_id=None, region=None, **kwargs)
Create a new floating IP assigned to a droplet or reserved to a region. Either ``droplet_id`` or ``region`` must be specified, but not both. The returned `FloatingIP` object will represent the IP at the moment of creation; if the IP address is supposed to be assigned to a droplet, the a...
2.588071
2.653408
0.975376
return self._tag(self.request('/v2/tags', method='POST', data={ "name": name, })["tag"])
def create_tag(self, name)
.. versionadded:: 0.2.0 Add a new tag resource to the account :param str name: the name of the new tag :rtype: Tag :raises DOAPIError: if the API endpoint replies with an error
8.467164
10.121692
0.836536
r objects = list(objects) if not objects: return if wait_interval is None: wait_interval = self.wait_interval if wait_time < 0: end_time = None else: if wait_time is None: wait_time = self.wait_time ...
def _wait(self, objects, attr, value, wait_interval=None, wait_time=None)
r""" Calls the ``fetch`` method of each object in ``objects`` periodically until the ``attr`` attribute of each one equals ``value``, yielding the final state of each object as soon as it satisfies the condition. If ``wait_time`` is exceeded, a `WaitTimeoutError` (containing any ...
2.174532
2.032882
1.069679
parallel_env = queue_id.split(':')[0] queue_name = queue_id.split(':')[1] tasks = 1 pe_tasks = tasks with os.popen('qconf -sp ' + parallel_env) as f: try: for line in f: if line.split(' ')[0] == 'allocation_rule': # This may throw exceptio...
def min_tasks_per_node(queue_id)
This function is used when requesting non exclusive use as the parallel environment might enforce a minimum number of tasks
5.00481
4.649443
1.076432
@wraps(meth) def wrapped_meth(self, val): if isinstance(val, (larray, numpy.ndarray)): if val.shape != self._shape: raise ValueError("shape mismatch: objects cannot be broadcast to a single shape") return meth(self, val) return wrapped_meth
def check_shape(meth)
Decorator for larray magic methods, to ensure that the operand has the same shape as the array.
3.397593
2.891158
1.175167
def size(x, max): if isinstance(x, (int, long, numpy.integer)): return None elif isinstance(x, slice): y = min(max, x.stop or max) # slice limits can go past the bounds return 1 + (y - (x.start or 0) - 1) // (x.step or 1) elif isinstance(x, collectio...
def partial_shape(addr, full_shape)
Calculate the size of the sub-array represented by `addr`
2.896161
2.836388
1.021074
@wraps(func) def reversed_func(a, b): return func(b, a) reversed_func.__doc__ = "Reversed argument form of %s" % func.__doc__ reversed_func.__name__ = "reversed %s" % func.__name__ return reversed_func
def reverse(func)
Given a function f(a, b), returns f(b, a)
3.075683
2.895951
1.062063
def larray_compatible_ufunc(x): if isinstance(x, larray): y = deepcopy(x) y.apply(func) return y else: return func(x) return larray_compatible_ufunc
def _build_ufunc(func)
Return a ufunc that works with lazy arrays
4.098827
3.533489
1.159994
hom_base = isinstance(self.base_value, (int, long, numpy.integer, float, bool)) \ or type(self.base_value) == self.dtype \ or (isinstance(self.dtype, type) and isinstance(self.base_value, self.dtype)) hom_ops = all(obj.is_homogeneous for f, obj in self.oper...
def is_homogeneous(self)
True if all the elements of the array are the same.
5.417838
5.247676
1.032426
if self.is_homogeneous: if simplify: base_val = self.base_value else: base_val = self._homogeneous_array(addr) * self.base_value elif isinstance(self.base_value, (int, long, numpy.integer, float, bool)): base_val = self._homoge...
def _partially_evaluate(self, addr, simplify=False)
Return part of the lazy array.
2.888686
2.813469
1.026735
def is_boolean_array(arr): return hasattr(arr, 'dtype') and arr.dtype == bool def check_axis(x, size): if isinstance(x, (int, long, numpy.integer)): lower = upper = x elif isinstance(x, slice): lower = x.start or 0 ...
def check_bounds(self, addr)
Check whether the given address is within the array bounds.
2.777081
2.715774
1.022574
# need to catch the situation where a generator-based larray is evaluated a second time if self.is_homogeneous: if simplify: x = self.base_value else: x = self.base_value * numpy.ones(self._shape, dtype=self.dtype) elif isinstance(...
def evaluate(self, simplify=False, empty_val=0)
Return the lazy array as a real NumPy array. If the array is homogeneous and ``simplify`` is ``True``, return a single numerical value.
2.759377
2.712768
1.017182
for name, obj in task.get_params(): if name == param_name: return hasattr(obj, 'use_closest_date') return False
def is_closest_date_parameter(task, param_name)
Return the parameter class of param_name on task.
4.510492
4.138271
1.089946
if isinstance(x, list): x = [e.replace("'", "") for e in x] return '-'.join(sorted(x)) return x
def delistify(x)
A basic slug version of a given parameter list.
4.050633
3.768639
1.074826
params = self.param_kwargs if 'date' in params and is_closest_date_parameter(self, 'date'): params['date'] = self.closest() task_id_parts = sorted(['%s=%s' % (k, str(v)) for k, v in params.items()]) return '%s(%s)' % (self.task_family, ', '.join(task_id_parts...
def effective_task_id(self)
Replace date in task id with closest date.
4.81416
4.192783
1.148201
return os.path.join(self.BASE, self.TAG, self.task_family)
def taskdir(self)
Return the directory under which all artefacts are stored.
10.92514
9.256137
1.180313
if self.BASE is NotImplemented: raise RuntimeError('BASE directory must be set.') params = dict(self.get_params()) if filename is None: parts = [] for name, param in self.get_params(): if not param.significant: c...
def path(self, filename=None, ext='tsv', digest=False, shard=False, encoding='utf-8')
Return the path for this class with a certain set of parameters. `ext` sets the extension of the file. If `hash` is true, the filename (w/o extenstion) will be hashed. If `shard` is true, the files are placed in shards, based on the first two chars of the filename (hashed).
2.907117
2.850549
1.019844
luigi.LocalTarget(path=self.fixture).copy(self.output().path)
def run(self)
Just copy the fixture, so we have some output.
19.296652
9.091048
2.122599
return list(map(lambda listener: listener[0], self.listeners[name]))
def get_listeners(self, name)
Return the callables related to name
6.48011
5.127666
1.263754
if name not in self.listeners: self.listeners[name] = [] self.listeners[name].append((listener, priority)) # reorder event self.listeners[name].sort(key=lambda listener: listener[1], reverse=True)
def add_listener(self, name, listener, priority=0)
Add a new listener to the dispatch
2.698044
2.693263
1.001775
container = container or container_element nsmap = nsmap or ns attribs = attribs or container_attribs return dump_etree_helper(container, data, rules, nsmap, attribs)
def dump_etree(data, container=None, nsmap=None, attribs=None)
Convert dictionary to Simple Dublin Core XML as ElementTree. :param data: Dictionary. :param container: Name (include namespace) of container element. :param nsmap: Namespace mapping for lxml. :param attribs: Default attributes for container element. :returns: LXML ElementTree.
5.151915
8.011038
0.643102
@rules.rule(plural) def f(path, values): for v in values: if v: elem = etree.Element( '{{http://purl.org/dc/elements/1.1/}}{0}'.format(singular)) elem.text = v yield elem f.__name__ = plural return f
def rule_factory(plural, singular)
Element rule factory.
4.434421
4.458247
0.994656
AMP.startReceivingBoxes(self, sender) log.addObserver(self._emit)
def startReceivingBoxes(self, sender)
Start observing log events for stat events to send.
21.122921
12.472898
1.693505
AMP.stopReceivingBoxes(self, reason) log.removeObserver(self._emit)
def stopReceivingBoxes(self, reason)
Stop observing log events.
17.313896
12.138688
1.42634
if (event.get('interface') is not iaxiom.IStatEvent and 'athena_send_messages' not in event and 'athena_received_messages' not in event): return out = [] for k, v in event.iteritems(): if k in ('system', 'message', 'interface', 'isError')...
def _emit(self, event)
If the given event is a stat event, send a I{StatUpdate} command.
5.930921
5.056249
1.172988
# if the url pointed to a directory then just replace all the special chars filename = re.sub("/|\\|;|:|\?|=", "_", filename) if len(filename) > 150: prefix = hashlib.md5(filename).hexdigest() filename = prefix + filename[-140:] return filename
def normalize_filename(filename)
Remove special characters and shorten if name is too long
6.732931
6.42188
1.048436
assert download_url or filename, "Either filename or URL must be specified" # if no filename provided, use the original filename on the server if not filename: digest = hashlib.md5(download_url.encode('utf-8')).hexdigest() parts = split(download_url) filename = digest + "." + "...
def build_local_filename(download_url=None, filename=None, decompress=False)
Determine which local filename to use based on the file's source URL, an optional desired filename, and whether a compression suffix needs to be removed
3.573427
3.529561
1.012428
if isinstance(file1, six.string_types): # pragma: no branch file1 = open(file1, 'r', True) if isinstance(file2, six.string_types): # pragma: no branch file2 = open(file2, 'r', True) file1_contents = file1.read() file2_contents = file2.read() return file1_contents == file2_cont...
def compare(file1, file2)
compares the contents of two files, passed in either as open file handles or accessible file paths. Does a simple naive string comparison, so do not use on larger files
1.987463
1.960363
1.013824
h = hashlib.sha1() fp = open(f, 'rb') while True: block = fp.read(512 * 1024) if not block: break h.update(block) return h.hexdigest()
def sha1sum(f)
Return the SHA-1 hash of the contents of file `f`, in hex format
1.940112
2.008333
0.966031
fd, tmpname = tempfile.mkstemp(dir=os.path.dirname(dest)) shutil.copyfileobj(open(src, 'rb'), os.fdopen(fd, 'wb')) shutil.copystat(src, tmpname) os.rename(tmpname, dest)
def safe_copyfile(src, dest)
safely copy src to dest using a temporary intermediate and then renaming to dest
1.927127
1.922974
1.00216
if radians==False: ra0 = np.radians(ra0) dec0 = np.radians(dec0) ra1 = np.radians(ra1) dec1 = np.radians(dec1) deltaRa= ra1-ra0 deltaDec= dec1-dec0 val = haversine(deltaDec) val += np.cos(dec0) * np.cos(dec1) * haversine(deltaRa) val = min(1, np.sqrt(val...
def sphericalAngSep(ra0, dec0, ra1, dec1, radians=False)
Compute the spherical angular separation between two points on the sky. //Taken from http://www.movable-type.co.uk/scripts/gis-faq-5.1.html NB: For small distances you can probably use sqrt( dDec**2 + cos^2(dec)*dRa) where dDec = dec1 - dec0 and dRa = ra1 - ra0 ...
2.734428
2.89568
0.944313
if radians==False: ra0 = np.radians(ra0) dec0 = np.radians(dec0) ra1 = np.radians(ra1) dec1 = np.radians(dec1) deltaRa= ra1-ra0 deltaDec= dec1-dec0 avgDec = .5*(dec0+dec1) x = deltaRa*np.cos(avgDec) val = np.hypot(x, deltaDec) if radians == False: ...
def sphericalAngSepFast(ra0, dec0, ra1, dec1, radians=False)
A faster (but less accurate) implementation of sphericalAngleSep Taken from http://www.movable-type.co.uk/scripts/latlong.html For additional speed, set wantSquare=True, and the return value is the square of the separation
2.232927
2.199063
1.015399
y = .5*x y = np.sin(y) return y*y
def haversine(x)
Return the haversine of an angle haversine(x) = sin(x/2)**2, where x is an angle in radians
8.804227
16.235064
0.542297
_DefaultShareID(store=store, shareID=shareID, priority=priority)
def addDefaultShareID(store, shareID, priority)
Add a default share ID to C{store}, pointing to C{shareID} with a priority C{priority}. The highest-priority share ID identifies the share that will be retrieved when a user does not explicitly provide a share ID in their URL (e.g. /host/users/username/). @param shareID: A share ID. @type shareID:...
5.514728
8.158764
0.675927
defaultShareID = store.findFirst( _DefaultShareID, sort=_DefaultShareID.priority.desc) if defaultShareID is None: return u'' return defaultShareID.shareID
def getDefaultShareID(store)
Get the highest-priority default share ID for C{store}. @return: the default share ID, or u'' if one has not been set. @rtype: C{unicode}
5.769317
4.690623
1.229968
if isinstance(sharedProxyOrItem, sharing.SharedProxy): userStore = sharing.itemFromProxy(sharedProxyOrItem).store else: userStore = sharedProxyOrItem.store appStore = isAppStore(userStore) if appStore: # This code-path should be fixed by #2703; PublicWeb is deprecated. ...
def linkTo(sharedProxyOrItem)
Generate the path part of a URL to link to a share item or its proxy. @param sharedProxy: a L{sharing.SharedProxy} or L{sharing.Share} @return: a URL object, which when converted to a string will look something like '/users/user@host/shareID'. @rtype: L{nevow.url.URL} @raise: L{RuntimeError}...
6.783908
6.126206
1.107359
lm = store.findUnique( userbase.LoginMethod, attributes.AND( userbase.LoginMethod.localpart == username, userbase.LoginMethod.internal == True), default=None) if lm is not None: return lm.account.avatars.open()
def _storeFromUsername(store, username)
Find the user store of the user with username C{store} @param store: site-store @type store: L{axiom.store.Store} @param username: the name a user signed up with @type username: C{unicode} @rtype: L{axiom.store.Store} or C{None}
5.891695
6.050641
0.973731
if self._shareID is not None: self = url.URL.child(self, self._shareID) self._shareID = None return url.URL.child(self, path)
def child(self, path)
Override the base implementation to inject the share ID our constructor was passed.
6.290551
3.785106
1.661922
return self.__class__( self._shareID, scheme, netloc, pathsegs, querysegs, fragment)
def cloneURL(self, scheme, netloc, pathsegs, querysegs, fragment)
Override the base implementation to pass along the share ID our constructor was passed.
5.842688
3.434524
1.701164
store = _storeFromUsername( self.loginSystem.store, segments[0].decode('utf-8')) if store is None: return rend.NotFound return (SharingIndex(store, self.webViewer), segments[1:])
def locateChild(self, ctx, segments)
Retrieve a L{SharingIndex} for a particular user, or rend.NotFound.
14.529483
6.94589
2.09181
shareID = segments[0].decode('utf-8') role = self.webViewer.roleIn(self.userStore) # if there is an empty segment if shareID == u'': # then we want to return the default share. if we find one, then # let's use that defaultShareID = getDefau...
def locateChild(self, ctx, segments)
Look up a shared item for the role viewing this SharingIndex and return a L{PublicAthenaLivePage} containing that shared item's fragment to the user. These semantics are UNSTABLE. This method is adequate for simple uses, but it should be expanded in the future to be more consistent wit...
5.994784
5.67691
1.055994
if hasattr(connection.connection, "autocommit"): if callable(connection.connection.autocommit): connection.connection.autocommit(True) else: connection.connection.autocommit = True elif hasattr(connection.connection, "set_isolation_level")...
def _set_autocommit(connection)
Make sure a connection is in autocommit mode.
2.069893
1.894748
1.092437
if django.VERSION[:2] < (1, 3): return from django.contrib.staticfiles.handlers import StaticFilesHandler return StaticFilesHandler(handler)
def _patch_static_handler(handler)
Patch in support for static files serving if supported and enabled.
4.86471
3.554896
1.368454
from django.conf import settings test_case = get_test_case_class(test) test_case.selenium_plugin_started = True # Provide some reasonable default values sel = selenium( getattr(settings, "SELENIUM_HOST", "localhost"), int(getattr(settings, "SELE...
def _inject_selenium(self, test)
Injects a selenium instance into the method.
3.935381
3.924567
1.002756
try: HTTPServer.server_bind(self) except Exception as e: raise WSGIServerException(e) self.setup_environ() self.socket.settimeout(1)
def server_bind(self)
Bind server to socket. Overrided to store server name and set timeout.
4.979539
4.613887
1.07925
if wait: self._async_resp.wait() if not self.finished(): raise RuntimeError("Result is not ready yet") raw_response = self._async_resp.get() return Result(result=raw_response["result"], error=raw_response["error"], id=raw_response...
def result(self, wait=False)
Gets the result of the method call. If the call was successful, return the result, otherwise, reraise the exception. :param wait: Block until the result is available, or just get the result. :raises: RuntimeError when called and the result is not yet available.
4.971685
5.022631
0.989857
app = container.get('ioc.extra.flask.app') app.config.update(container_builder.parameters.get('ioc.extra.flask.app.config')) if container.has('ioc.extra.jinja2'): # This must be an instance of jinja.ChoiceLoader # This code replace the flask specific jinja conf...
def post_build(self, container_builder, container)
This method make sure the flask configuration is fine, and check the if ioc.extra.jinja2 service is available. If so, the flask instance will use this service, by keeping the flask template loader and the one registered at the jinja2
3.75447
2.987657
1.256661
assert not self._started self._listening_stream.on_recv(self._recv_callback) self._started = True
def start(self)
Start to listen for incoming requests.
7.959742
6.923938
1.149597
sock = self._zmq_context.socket(zmq.PULL) sock.connect(pull_addr) stream = ZMQStream(sock, io_loop=self.io_loop) return stream
def _create_listening_stream(self, pull_addr)
Create a stream listening for Requests. The `self._recv_callback` method is asociated with incoming requests.
3.453114
3.459428
0.998175
sock = self._zmq_context.socket(zmq.PUB) sock.setsockopt(zmq.IDENTITY, self.sender_id) sock.connect(pub_addr) stream = ZMQStream(sock, io_loop=self.io_loop) return stream
def _create_sending_stream(self, pub_addr)
Create a `ZMQStream` for sending responses back to Mongrel2.
3.052668
2.63053
1.160477
m2req = MongrelRequest.parse(msg[0]) MongrelConnection(m2req, self._sending_stream, self.request_callback, no_keep_alive=self.no_keep_alive, xheaders=self.xheaders)
def _recv_callback(self, msg)
Method is called when there is a message coming from a Mongrel2 server. This message should be a valid Request String.
11.309421
8.789473
1.286701
headers = self.m2req.headers self._request = HTTPRequest(connection=self, method=headers.get("METHOD"), uri=self.m2req.path, version=headers.get("VERSION"), headers=headers, remote_ip=headers.get("x-forwarded-for")) if len(se...
def _begin_request(self)
Actually start executing this request.
3.534398
3.503996
1.008676
assert self._request, "Request closed" self._request_finished = True if self.m2req.should_close() or self.no_keep_alive: self._send("") self._request = None
def finish(self)
Finish this connection.
11.812065
11.353356
1.040403
uuid = self.m2req.sender conn_id = self.m2req.conn_id header = "%s %d:%s," % (uuid, len(str(conn_id)), str(conn_id)) zmq_message = header + ' ' + msg self.stream.send(zmq_message)
def _send(self, msg)
Raw send to the given connection ID at the given uuid, mostly used internally.
7.678339
6.178285
1.242795
@wraps(func) def inner(self, o): try: return o._redpipe_struct_as_dict # noqa except AttributeError: pass return func(self, o) return inner
def _json_default_encoder(func)
Monkey-Patch the core json encoder library. This isn't as bad as it sounds. We override the default method so that if an object falls through and can't be encoded normally, we see if it is a Future object and return the result to be encoded. I set a special attribute on the Struct object so I can t...
6.559563
6.227441
1.053332
for item in async_result_wrappers: if not isinstance(item, AsyncMethodCall): raise TypeError("Got non-AsyncMethodCall object: {}".format(item)) wrappers_copy = list(async_result_wrappers) while len(wrappers_copy): completed = list(filter(lambda x: x.finished(), wrappers_co...
def as_completed(*async_result_wrappers)
Yields results as they become available from asynchronous method calls. Example usage :: async_calls = [service.call_method_async("do_stuff", (x,)) for x in range(25)] for async_call in gemstone.as_completed(*async_calls): print("just finished with result ", async_call.result()) ...
3.114967
3.317009
0.939089
for item in async_result_wrappers: if not isinstance(item, AsyncMethodCall): raise TypeError("Got non-AsyncMethodCall object: {}".format(item)) wrappers_copy = list(async_result_wrappers) while True: completed = list(filter(lambda x: x.finished(), wrappers_copy)) if ...
def first_completed(*async_result_wrappers)
Just like :py:func:`as_completed`, but returns only the first item and discards the rest. :param async_result_wrappers: :return: .. versionadded:: 0.5.0
3.921469
4.564479
0.859127
parts = module_or_member.split(".") if len(parts) > 1: name_to_import = parts[-1] module_to_import = ".".join(parts[:-1]) else: name_to_import = None module_to_import = module_or_member module = importlib.import_module(module_to_import) if name_to_import: ...
def dynamic_load(module_or_member)
Dynamically loads a class or member of a class. If ``module_or_member`` is something like ``"a.b.c"``, will perform ``from a.b import c``. If ``module_or_member`` is something like ``"a"`` will perform ``import a`` :param module_or_member: the name of a module or member of a module to import. :return...
1.832376
1.906066
0.961339
if value not in [True, False]: raise InvalidValue('not a boolean') return b'1' if value else b''
def encode(cls, value)
convert a boolean value into something we can persist to redis. An empty string is the representation for False. :param value: bool :return: bytes
7.280282
5.870673
1.24011
try: if float(value) + 0 == value: return repr(value) except (TypeError, ValueError): pass raise InvalidValue('not a float')
def encode(cls, value)
encode a floating point number to bytes in redis :param value: float :return: bytes
6.705586
6.768623
0.990687
try: coerced = int(value) if coerced + 0 == value: return repr(coerced) except (TypeError, ValueError): pass raise InvalidValue('not an int')
def encode(cls, value)
take an integer and turn it into a string representation to write into redis. :param value: int :return: str
5.996186
5.960324
1.006017
coerced = unicode(value) if coerced == value: return coerced.encode(cls._encoding) raise InvalidValue('not text')
def encode(cls, value)
take a valid unicode string and turn it into utf-8 bytes :param value: unicode, str :return: bytes
8.392218
8.158465
1.028651
coerced = unicode(value) if coerced == value and cls.PATTERN.match(coerced): return coerced.encode(cls._encoding) raise InvalidValue('not ascii')
def encode(cls, value)
take a list of strings and turn it into utf-8 byte-string :param value: :return:
6.644839
7.437316
0.893446
try: coerced = bytes(value) if coerced == value: return coerced except (TypeError, UnicodeError): pass raise InvalidValue('not binary')
def encode(cls, value)
write binary data into redis without encoding it. :param value: bytes :return: bytes
5.713759
6.153638
0.928517
try: coerced = list(value) if coerced == value: return json.dumps(coerced).encode(cls._encoding) except TypeError: pass raise InvalidValue('not a list')
def encode(cls, value)
take a list and turn it into a utf-8 encoded byte-string for redis. :param value: list :return: bytes
5.179598
5.097494
1.016107
try: return None if value is None else \ list(json.loads(value.decode(cls._encoding))) except (TypeError, AttributeError): return list(value)
def decode(cls, value)
take a utf-8 encoded byte-string from redis and turn it back into a list :param value: bytes :return: list
5.41772
5.578045
0.971258
try: coerced = dict(value) if coerced == value: return json.dumps(coerced).encode(cls._encoding) except (TypeError, ValueError): pass raise InvalidValue('not a dict')
def encode(cls, value)
encode the dict as a json string to be written into redis. :param value: dict :return: bytes
5.000699
5.017423
0.996667
try: data = [v for v in value.decode(cls._encoding).split(',') if v != ''] return data if data else None except AttributeError: return value
def decode(cls, value)
decode the data from redis. :param value: bytes :return: list
6.012757
5.382
1.117197
try: coerced = [str(v) for v in value] if coerced == value: return ",".join(coerced).encode(cls._encoding) if len( value) > 0 else None except TypeError: pass raise InvalidValue('not a list of strings')
def encode(cls, value)
the list it so it can be stored in redis. :param value: list :return: bytes
5.404408
5.136395
1.052179
self.init_config(app) app.cli.add_command(openaire) before_record_index.connect(indexer_receiver, sender=app) app.extensions['invenio-openaire'] = self
def init_app(self, app)
Flask application initialization.
8.695166
8.426245
1.031915
if subject.startswith('Tweet from'): lines = body.split('\n') for idx, line in enumerate(lines): if re.match(r'.*, ?\d{2}:\d{2}]]', line) is not None: try: subject = lines[idx + 1] except IndexError: pass ...
def swap_twitter_subject(subject, body)
If subject starts from 'Tweet from...' then we need to get first meaning line from the body.
4.205576
3.522655
1.193865
global _trial # pylint: disable=global-statement if _trial: # TODO: would be nice to stack crawl at creation time to report # where that initial trial was created, and that creation line # info is helpful to keep around anyway. raise ValueError("A trial already exists in th...
def trial(log_dir=None, upload_dir=None, sync_period=None, trial_prefix="", param_map=None, init_logging=True)
Generates a trial within a with context.
4.429159
4.339056
1.020765
if index < 0: index += length if 0 <= index < length: return index raise IndexError()
def index(index, length)
Generates an index. :param index: The index, can be positive or negative. :param length: The length of the sequence to index. :raises: IndexError Negative indices are typically used to index a sequence in reverse order. But to use them, the indexed object must convert them to the correct, pos...
3.093377
3.964831
0.780204
values, units = zip(*(r.split() for r in ranges)) # Detect common unit. unit = os.path.commonprefix([u[::-1] for u in units]) # Strip unit to get just the SI prefix. prefixes = (u[:-len(unit)] for u in units) # Convert string value and scale with prefix. values = [float(v) * SI_PREFIX...
def range_to_numeric(ranges)
Converts a sequence of string ranges to a sequence of floats. E.g.:: >>> range_to_numeric(['1 uV', '2 mV', '1 V']) [1E-6, 0.002, 1.0]
5.664125
6.49098
0.872615
def make_wrapper(fn): @functools.wraps(fn) def wrapper(*args, **kw): try: return fn(*args, **kw) except exc as e: future.utils.raise_with_traceback(new_exc(e)) return wrapper return make_wrapper
def wrap_exception(exc, new_exc)
Catches exceptions `exc` and raises `new_exc(exc)` instead. E.g.:: >>> class MyValueError(Exception): ... '''Custom ValueError.''' ... @wrap_exception(exc=ValueError, new_exc=MyValueError) ... def test(): ... raise ValueError()
2.624024
3.099131
0.846697
self._buffer.append(abs(value)) mean = sum(self._buffer) / len(self._buffer) estimate = next( (r for r in self.ranges if mean < self.scale * r), self.ranges[-1] ) if self._mapping: return self._mapping[estimate] else: ...
def range(self, value)
Estimates an appropriate sensitivity range.
5.013089
4.6799
1.071196
binding = self.get_binding(schema, data) uri, triples = triplify(binding) for triple in triples: self.graph.add(triple) return uri
def add(self, schema, data)
Stage ``data`` as a set of statements, based on the given ``schema`` definition.
5.359414
5.769228
0.928966
if self.parent.buffered: query = query = query % (self.identifier.n3(), self.graph.serialize(format='nt')) self.parent.graph.update(query) self.flush() else: self.meta.generate()
def save(self)
Transfer the statements in this context over to the main store.
10.32863
8.478236
1.218252
if self.parent.buffered: query = 'CLEAR SILENT GRAPH %s ;' % self.identifier.n3() self.parent.graph.update(query) self.flush() else: self.graph.remove((None, None, None))
def delete(self)
Delete all statements matching the current context identifier from the main store.
6.74104
5.591401
1.205608
buffer_size = len(self._buffer) if buffer_size > num_bytes: # The buffer is larger than the requested amount of bytes. data, self._buffer = self._buffer[:num_bytes], self._buffer[num_bytes:] elif 0 < buffer_size <= num_bytes: # This might return less ...
def read_bytes(self, num_bytes)
Reads at most `num_bytes`.
3.185626
3.001523
1.061336
if delimiter in self._buffer: data, delimiter, self._buffer = self._buffer.partition(delimiter) return data else: self._buffer += self.__read__(self._max_bytes) return self.read_until(delimiter)
def read_until(self, delimiter)
Reads until the delimiter is found.
3.586213
3.473637
1.032409
if self._device is not None: ibsta = self._lib.ibonl(self._device, 0) self._check_status(ibsta) self._device = None
def close(self)
Closes the gpib transport.
10.837138
9.185629
1.179793
ibsta = self._lib.ibtrg(self._device) self._check_status(ibsta)
def trigger(self)
Triggers the device. The trigger method sens a GET(group execute trigger) command byte to the device.
28.304199
25.94553
1.090909
if ibsta & 0x4000: raise LinuxGpib.Timeout() elif ibsta & 0x8000: raise LinuxGpib.Error(self.error_status)
def _check_status(self, ibsta)
Checks ibsta value.
6.488596
5.80725
1.117327
output = shellout('wget -q "{url}" -O {output}', url=self.url) luigi.LocalTarget(output).move(self.output().path)
def run(self)
Just run wget quietly.
7.681221
5.966746
1.287338
return luigi.LocalTarget(path=self.path(digest=True, ext='html'))
def output(self)
Use the digest version, since URL can be ugly.
18.377453
10.409415
1.765464
document = {} document['_id'] = hashlib.sha1('%s:%s' % ( self.date, self.url)).hexdigest() with self.input().open() as handle: document['content'] = handle.read().decode('utf-8', 'ignore') document['url'] = self.url docu...
def run(self)
Construct the document id from the date and the url.
3.406397
2.665521
1.277948
with self.input().open() as handle: body = json.loads(handle.read()) es = elasticsearch.Elasticsearch() id = body.get('_id') es.index(index='frontpage', doc_type='html', id=id, body=body)
def run(self)
Index the document. Since ids are predictable, we won't index anything twice.
4.601092
4.256428
1.080975
id = hashlib.sha1('%s:%s' % (self.date, self.url)).hexdigest() es = elasticsearch.Elasticsearch() try: es.get(index='frontpage', doc_type='html', id=id) except elasticsearch.NotFoundError: return False return True
def complete(self)
Check, if out hashed date:url id is already in the index.
4.538383
3.373487
1.345309
for url in NEWSPAPERS: yield IndexPage(url=url, date=self.date)
def requires(self)
Index all pages.
19.71356
10.8459
1.817605
if self.node.specific_attribute: return self.node.name name = data.get(self.predicate_var) if str(RDF.type) in [self.node.name, name]: return '$schema' if name.startswith(PRED): name = name[len(PRED):] return name
def get_name(self, data)
For non-specific queries, this will return the actual name in the result.
8.452098
8.054956
1.049304
if self.parent: print (self.parent.var, self.predicate, self.var) q = q.project(self.var, append=True) if parent and self.parent: q = q.project(self.parent.var, append=True) if not self.node.specific_attribute: q = q.project(self.predicate, ap...
def project(self, q, parent=False)
Figure out which attributes should be returned for the current level of the query.
3.84801
3.709081
1.037456
if self.node.leaf and self.node.filtered: # TODO: subject filters? q = q.where((self.parent.var, self.predicate, self.var)) # TODO: inverted nodes q = self.filter_value(q, self.var) elif self.paren...
def filter(self, q, parents=None)
Apply any filters to the query.
4.803621
4.655567
1.031802
# TODO: benchmark single-query strategy q = Select([]) q = self.project(q, parent=True) q = self.filter(q, parents=parents) if self.parent is None: subq = Select([self.var]) subq = self.filter(subq, parents=parents) subq = subq.offset...
def query(self, parents=None)
Compose the query and generate SPARQL.
4.794021
4.460234
1.074836