code
stringlengths
51
2.34k
docstring
stringlengths
11
171
def assert_valid(self, instance, value=None): valid = super(Tuple, self).assert_valid(instance, value) if not valid: return False if value is None: value = instance._get(self.name) if value is None: return True if ( (self.min_length is not None and len(value) < self.min_length) or (self.max_length is not None and len(value) > self.max_length) ): self.error( instance=instance, value=value, extra='(Length is {})'.format(len(value)), ) for val in value: if not self.prop.assert_valid(instance, val): return False return True
Check if tuple and contained properties are valid
def __update(self): self.reset() if not os.path.exists(self.IRQ_FILE): return self.stats try: with open(self.IRQ_FILE) as irq_proc: time_since_update = getTimeSinceLastUpdate('irq') self.__header(irq_proc.readline()) for line in irq_proc.readlines(): irq_line = self.__humanname(line) current_irqs = self.__sum(line) irq_rate = int( current_irqs - self.lasts.get(irq_line) if self.lasts.get(irq_line) else 0 // time_since_update) irq_current = { 'irq_line': irq_line, 'irq_rate': irq_rate, 'key': self.get_key(), 'time_since_update': time_since_update } self.stats.append(irq_current) self.lasts[irq_line] = current_irqs except (OSError, IOError): pass return self.stats
Load the IRQ file and update the internal dict.
def serialize(self): keys = self._all_keys() serdata = {} for fieldname, value in self._data.items(): serdata[fieldname] = getattr(type(self), fieldname).python_to_cache(value) return json.dumps(serdata)
Serialize all the fields into one string.
def _getFont(self, font): if os.path.isfile(font): font_files = [font] else: font_files = fc.query(family=font) if not font_files: raise ValueError('No such font') return font_files
Returns font paths from font name or path
def owner(self): if self._writer is not None: return self.WRITER if self._readers: return self.READER return None
Returns whether the lock is locked by a writer or reader.
def create_process(self, command, shell=True, stdout=None, stderr=None, env=None): env = env if env is not None else dict(os.environ) env['DISPLAY'] = self.display return subprocess.Popen(command, shell=shell, stdout=stdout, stderr=stderr, env=env)
Execute a process using subprocess.Popen, setting the backend's DISPLAY
def positive_float(string): error_msg = 'Positive float required, {string} given.'.format(string=string) try: value = float(string) except ValueError: raise ArgumentTypeError(error_msg) if value < 0: raise ArgumentTypeError(error_msg) return value
Convert string to positive float.
def contains(self, key): for store in self._stores: if store.contains(key): return True return False
Returns whether the object is in this datastore.
def collect_episodes(local_evaluator=None, remote_evaluators=[], timeout_seconds=180): pending = [ a.apply.remote(lambda ev: ev.get_metrics()) for a in remote_evaluators ] collected, _ = ray.wait( pending, num_returns=len(pending), timeout=timeout_seconds * 1.0) num_metric_batches_dropped = len(pending) - len(collected) if pending and len(collected) == 0: raise ValueError( "Timed out waiting for metrics from workers. You can configure " "this timeout with `collect_metrics_timeout`.") metric_lists = ray_get_and_free(collected) if local_evaluator: metric_lists.append(local_evaluator.get_metrics()) episodes = [] for metrics in metric_lists: episodes.extend(metrics) return episodes, num_metric_batches_dropped
Gathers new episodes metrics tuples from the given evaluators.
def main(): parser = argparse.ArgumentParser( description='Start an instance of the Cheroot WSGI/HTTP server.', ) for arg, spec in _arg_spec.items(): parser.add_argument(arg, **spec) raw_args = parser.parse_args() '' in sys.path or sys.path.insert(0, '') raw_args._wsgi_app.server(raw_args).safe_start()
Create a new Cheroot instance with arguments from the command line.
def cli(env): ticket_mgr = SoftLayer.TicketManager(env.client) table = formatting.Table(['id', 'subject']) for subject in ticket_mgr.list_subjects(): table.add_row([subject['id'], subject['name']]) env.fout(table)
List Subject IDs for ticket creation.
def _fetch_headers(self): self._header_text, self._n_ref = self._read_top_header() self._ref_lengths, self._ref_names = self._read_reference_information() self._header = SAMHeader(self._header_text)
Needs ._fh handle to stream to be set by child
def insult(rest): "Generate a random insult from datahamster" url = 'http://autoinsult.datahamster.com/' ins_type = random.randrange(4) ins_url = url + "?style={ins_type}".format(**locals()) insre = re.compile('<div class="insult" id="insult">(.*?)</div>') resp = requests.get(ins_url) resp.raise_for_status() insult = insre.search(resp.text).group(1) if not insult: return if rest: insultee = rest.strip() karma.Karma.store.change(insultee, -1) if ins_type in (0, 2): cinsre = re.compile(r'\b(your)\b', re.IGNORECASE) insult = cinsre.sub("%s's" % insultee, insult) elif ins_type in (1, 3): cinsre = re.compile(r'^([TY])') insult = cinsre.sub( lambda m: "%s, %s" % ( insultee, m.group(1).lower()), insult) return insult
Generate a random insult from datahamster
def _get_args(self, *args) -> (Exception, str): ex = None msg = None for arg in args: if isinstance(arg, str): msg = arg elif isinstance(arg, Exception): ex = arg return ex, msg
Returns exception and message from the provided arguments
def format_value(self, val): if isinstance(val, six.text_type): return self.format_string(val) else: return six.text_type(val)
Helper function to format a value.
def prepare_auth(self, auth, url=''): if auth is None: url_auth = get_auth_from_url(self.url) auth = url_auth if any(url_auth) else None if auth: if isinstance(auth, tuple) and len(auth) == 2: auth = HTTPBasicAuth(*auth) r = auth(self) self.__dict__.update(r.__dict__) self.prepare_content_length(self.body)
Prepares the given HTTP auth data.
def loop(self): for mail in Mail.objects.filter(done=False, send_fail_count__lt=3): mail.send_mail() for mail in Mail.objects.filter(done=True, timestamp__lt=time() - 60 * 60 * 24 * 7): mail.delete() return 1, None
check for mails and send them
def elliot_function( signal, derivative=False ): s = 1 abs_signal = (1 + np.abs(signal * s)) if derivative: return 0.5 * s / abs_signal**2 else: return 0.5*(signal * s) / abs_signal + 0.5
A fast approximation of sigmoid
def add_to_map(map_obj, lat, lon, date_time, key, cluster_obj): text = "Event {0} at {1}".format(key, date_time.split()[1]) folium.Marker([lat, lon], popup=text).add_to(cluster_obj)
Add individual elements to a foilum map in a cluster object
def finalize(self, result): if not self._running: return del os.environ["TEST_MONGODB"] del os.environ["TEST_MONGODB_DATABASE"] if sys.platform == 'darwin': self.process.kill() else: self.process.terminate() self.process.wait() shutil.rmtree(self.mongodb_param['db_path']) self._running = False
Stop the mongodb instance.
def _rm_gos_edges(rm_goids, edges_all): edges_reduced = [] for goid_child, goid_parent in sorted(edges_all, key=lambda t: t[1]): if goid_child not in rm_goids and goid_parent not in rm_goids: edges_reduced.append((goid_child, goid_parent)) return edges_reduced
Remove any is_a edges that contain user-specified edges.
def find_file(name, directory): path_bits = directory.split(os.sep) for i in range(0, len(path_bits) - 1): check_path = path_bits[0:len(path_bits) - i] check_file = "%s%s%s" % (os.sep.join(check_path), os.sep, name) if os.path.exists(check_file): return abspath(check_file) return None
Searches up from a directory looking for a file
def execute(self, cacheable=False): if self.network.is_caching_enabled() and cacheable: response = self._get_cached_response() else: response = self._download_response() return minidom.parseString(_string(response).replace("opensearch:", ""))
Returns the XML DOM response of the POST Request from the server
def privmsg(self, target, message, nowait=False): if message: messages = utils.split_message(message, self.config.max_length) if isinstance(target, DCCChat): for message in messages: target.send_line(message) elif target: f = None for message in messages: f = self.send_line('PRIVMSG %s :%s' % (target, message), nowait=nowait) return f
send a privmsg to target
def runPlugins(self, category, func, protocol, *args): for plugin in self.plugins: try: event_listener = getattr(plugin, func) except AttributeError: pass else: try: stop = event_listener(protocol, *args) if stop: break except Exception: traceback.print_exc()
Run the specified set of plugins against a given protocol.
def name(self) -> str: if self.is_platform: if self._data["publicCode"]: return self._data['name'] + " Platform " + \ self._data["publicCode"] else: return self._data['name'] + " Platform " + \ self.place_id.split(':')[-1] else: return self._data['name']
Friendly name for the stop place or platform
def sign(self, encoded): signature = self._hmac.copy() signature.update(encoded) return signature.hexdigest().encode('utf-8')
Return authentication signature of encoded bytes