code
stringlengths
81
3.79k
def current_docker_container_id(): try: with open('/proc/1/cgroup', 'r') as readable: raw = readable.read() ids = set(re.compile('[0-9a-f]{12,}').findall(raw)) assert len(ids) == 1 return ids.pop() except: logging.exception('Failed to obtain current container ID') raise NotInsideContainerError()
def get_student_messaging_for_sis_course_id_and_sis_user_id( self, sis_user_id, sis_course_id): url = ("/api/v1/courses/%s/analytics/" "users/sis_user_id:%s/communication.json") % ( self._sis_id(sis_course_id, sis_field="course"), sis_user_id) return self._get_resource(url)
def create_instance(self, instance_id, configuration_name, node_count, display_name, project_id=None): self._apply_to_instance(project_id, instance_id, configuration_name, node_count, display_name, lambda x: x.create())
def remove_action(self, action_name, action_id): action = self.get_action(action_name, action_id) if action is None: return False action.cancel() self.actions[action_name].remove(action) return True
def update_x(self, x, indices=None): x = _make_np_bool(x) if indices is None: if len(self._x) != len(x): raise QiskitError("During updating whole x, you can not change " "the number of qubits.") self._x = x else: if not isinstance(indices, list) and not isinstance(indices, np.ndarray): indices = [indices] for p, idx in enumerate(indices): self._x[idx] = x[p] return self
def _subgraph_parse( self, node, pathnode, extra_blocks ): loose_ends = [] self.tail = node self.dispatch_list(node.body) loose_ends.append(self.tail) for extra in extra_blocks: self.tail = node self.dispatch_list(extra.body) loose_ends.append(self.tail) if node.orelse: self.tail = node self.dispatch_list(node.orelse) loose_ends.append(self.tail) else: loose_ends.append(node) if node: bottom = "%s" % self._bottom_counter self._bottom_counter += 1 for le in loose_ends: self.graph.connect(le, bottom) self.tail = bottom
def set_constant(self, name, value): assert isinstance(name, str) or isinstance(name, sympy.Symbol), \ "constant name needs to be of type str, unicode or a sympy.Symbol" assert type(value) is int, "constant value needs to be of type int" if isinstance(name, sympy.Symbol): self.constants[name] = value else: self.constants[symbol_pos_int(name)] = value
def parse(cls, parser, token): bits, as_var = parse_as_var(parser, token) tag_name, args, kwargs = parse_token_kwargs(parser, bits, ('template',) + cls.allowed_kwargs, compile_args=cls.compile_args, compile_kwargs=cls.compile_kwargs) cls.validate_args(tag_name, *args) return cls(tag_name, as_var, *args, **kwargs)
def resolves_for(self, session): if self.url: self.actual_path = session.current_url else: result = urlparse(session.current_url) if self.only_path: self.actual_path = result.path else: request_uri = result.path if result.query: request_uri += "?{0}".format(result.query) self.actual_path = request_uri if isregex(self.expected_path): return self.expected_path.search(self.actual_path) else: return normalize_url(self.actual_path) == normalize_url(self.expected_path)
def retrieve_image(self, path_to_image): image = self.storage.open(path_to_image, 'rb') file_ext = path_to_image.rsplit('.')[-1] image_format, mime_type = get_image_metadata_from_file_ext(file_ext) return ( Image.open(image), file_ext, image_format, mime_type )
def create_build_package(package_files): for package_file in package_files: if not os.path.exists(package_file): bot.exit('Cannot find %s.' % package_file) bot.log('Generating build package for %s files...' % len(package_files)) build_dir = get_tmpdir(prefix="sregistry-build") build_tar = '%s/build.tar.gz' % build_dir tar = tarfile.open(build_tar, "w:gz") for package_file in package_files: tar.add(package_file) tar.close() sha256 = get_file_hash(build_tar) hash_tar = "%s/%s.tar.gz" %(build_dir, sha256) shutil.move(build_tar, hash_tar) return hash_tar
def step_next_char(self): self._index += 1 self._col_offset += 1 if self._index > self._maxindex: self._maxindex = self._index self._maxcol = self._col_offset self._maxline = self._lineno
def _get_cached_arg_spec(fn): arg_spec = _ARG_SPEC_CACHE.get(fn) if arg_spec is None: arg_spec_fn = inspect.getfullargspec if six.PY3 else inspect.getargspec try: arg_spec = arg_spec_fn(fn) except TypeError: arg_spec = arg_spec_fn(fn.__call__) _ARG_SPEC_CACHE[fn] = arg_spec return arg_spec
def export_xhtml(html, filename, image_tag=None): if image_tag is None: image_tag = default_image_tag else: image_tag = ensure_utf8(image_tag) with open(filename, 'w') as f: offset = html.find("<html>") assert offset > -1, 'Invalid HTML string: no <html> tag.' html = ('<html xmlns="http://www.w3.org/1999/xhtml">\n'+ html[offset+6:]) html = fix_html(html) f.write(IMG_RE.sub(lambda x: image_tag(x, path = None, format = "svg"), html))
def get_properties(self): return {prop.get_name(): prop.get_value() for prop in self.properties.values()}
def get_card(self, card_id, **query_params): card_json = self.fetch_json( uri_path=self.base_uri + '/cards/' + card_id ) return self.create_card(card_json)
def with_context(exc, context): if not hasattr(exc, 'context'): exc.context = {} exc.context.update(context) return exc
def delete(self, url, **kwargs): check_type(url, basestring, may_be_none=False) erc = kwargs.pop('erc', EXPECTED_RESPONSE_CODE['DELETE']) self.request('DELETE', url, erc, **kwargs)
def effective_sample_size(states, filter_threshold=0., filter_beyond_lag=None, name=None): states_was_list = _is_list_like(states) if not states_was_list: states = [states] filter_beyond_lag = _broadcast_maybelist_arg(states, filter_beyond_lag, 'filter_beyond_lag') filter_threshold = _broadcast_maybelist_arg(states, filter_threshold, 'filter_threshold') with tf.compat.v1.name_scope(name, 'effective_sample_size'): ess_list = [ _effective_sample_size_single_state(s, ml, mlt) for (s, ml, mlt) in zip(states, filter_beyond_lag, filter_threshold) ] if states_was_list: return ess_list return ess_list[0]
def add_requirements(self, metadata_path): additional = list(self.setupcfg_requirements()) if not additional: return pkg_info = read_pkg_info(metadata_path) if 'Provides-Extra' in pkg_info or 'Requires-Dist' in pkg_info: warnings.warn('setup.cfg requirements overwrite values from setup.py') del pkg_info['Provides-Extra'] del pkg_info['Requires-Dist'] for k, v in additional: pkg_info[k] = v write_pkg_info(metadata_path, pkg_info)
def get_module(self, name, node): for mod in self.modules(): mod_name = mod.node.name if mod_name == name: return mod package = node.root().name if mod_name == "%s.%s" % (package, name): return mod if mod_name == "%s.%s" % (package.rsplit(".", 1)[0], name): return mod raise KeyError(name)
def copy(self, copy_source, bucket, key, extra_args=None, subscribers=None, source_client=None): if extra_args is None: extra_args = {} if subscribers is None: subscribers = [] if source_client is None: source_client = self._client self._validate_all_known_args(extra_args, self.ALLOWED_COPY_ARGS) call_args = CallArgs( copy_source=copy_source, bucket=bucket, key=key, extra_args=extra_args, subscribers=subscribers, source_client=source_client ) return self._submit_transfer(call_args, CopySubmissionTask)
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0): local_stream = utils.BytearrayStream() if len(self._credentials) == 0: raise ValueError("Authentication struct missing credentials.") for credential in self._credentials: credential.write(local_stream, kmip_version=kmip_version) self.length = local_stream.length() super(Authentication, self).write( output_stream, kmip_version=kmip_version ) output_stream.write(local_stream.buffer)
def dims(x): if isinstance(x, tf.TensorShape): return x.dims r = tf.TensorShape(x).dims return None if r is None else list(map(tf.compat.dimension_value, r))
def ancestral_reconstruction(params): if assure_tree(params, tmp_dir='ancestral_tmp'): return 1 outdir = get_outdir(params, '_ancestral') basename = get_basename(params, outdir) gtr = create_gtr(params) aln, ref, fixed_pi = read_if_vcf(params) is_vcf = True if ref is not None else False treeanc = TreeAnc(params.tree, aln=aln, ref=ref, gtr=gtr, verbose=1, fill_overhangs=not params.keep_overhangs) ndiff =treeanc.infer_ancestral_sequences('ml', infer_gtr=params.gtr=='infer', marginal=params.marginal, fixed_pi=fixed_pi) if ndiff==ttconf.ERROR: return 1 if params.gtr=="infer": print('\nInferred GTR model:') print(treeanc.gtr) export_sequences_and_tree(treeanc, basename, is_vcf, params.zero_based, report_ambiguous=params.report_ambiguous) return 0
def chain_nac_proxy(chain, sender, contract_address, value=0): "create an object which acts as a proxy for the contract on the chain" klass = registry[contract_address].im_self assert issubclass(klass, NativeABIContract) def mk_method(method): def m(s, *args): data = abi_encode_args(method, args) block = chain.head_candidate output = test_call(block, sender, contract_address, data) if output is not None: return abi_decode_return_vals(method, output) return m class cproxy(object): pass for m in klass._abi_methods(): setattr(cproxy, m.__func__.func_name, mk_method(m)) return cproxy()
def _generate(self, source, name, filename, defer_init=False): return generate(source, self, name, filename, defer_init=defer_init)
def send_json(self, ids=None): items = ids or self._registration_id values = {"registration_ids": items} if self._data is not None: values["data"] = self._data for key, val in self._kwargs.items(): if val: values[key] = val data = json.dumps(values, separators=(",", ":"), sort_keys=True).encode( self.encoding) result = json.loads(self._send(data, "application/json")) if ("failure" in result) and (result["failure"]): unregistered = [] throw_error = False for index, error in enumerate(result.get("results", [])): error = error.get("error", "") if error in ("NotRegistered", "InvalidRegistration"): unregistered.append(items[index]) elif error != "": throw_error = True self.deactivate_unregistered_devices(unregistered) if throw_error: raise GCMPushError(result) return result
def compounds(context, case_id): adapter = context.obj['adapter'] LOG.info("Running scout update compounds") case_obj = adapter.case(case_id) if not case_obj: LOG.warning("Case %s could not be found", case_id) context.abort() try: adapter.update_case_compounds(case_obj) except Exception as err: LOG.warning(err) context.abort()
def try_passwordless_ssh(server, keyfile, paramiko=None): if paramiko is None: paramiko = sys.platform == 'win32' if not paramiko: f = _try_passwordless_openssh else: f = _try_passwordless_paramiko return f(server, keyfile)
def analyze_entities(self, document, encoding_type=None, retry=None, timeout=None, metadata=None): client = self.get_conn() return client.analyze_entities( document=document, encoding_type=encoding_type, retry=retry, timeout=timeout, metadata=metadata )
def __load_symbol_maps(self): repo = SymbolMapRepository(self.__get_session()) all_maps = repo.get_all() self.symbol_maps = {} for item in all_maps: self.symbol_maps[item.in_symbol] = item.out_symbol
def connection(self): ctx = _app_ctx_stack.top if ctx is not None: if not hasattr(ctx, 'mysql_db'): ctx.mysql_db = self.connect return ctx.mysql_db
def multiqc(store, institute_id, case_name): institute_obj, case_obj = institute_and_case(store, institute_id, case_name) return dict( institute=institute_obj, case=case_obj, )
def write_change(change): action, rrset = change change_vals = get_change_values(change) e_change = etree.Element("Change") e_action = etree.SubElement(e_change, "Action") e_action.text = action e_rrset = etree.SubElement(e_change, "ResourceRecordSet") e_name = etree.SubElement(e_rrset, "Name") e_name.text = change_vals['name'] e_type = etree.SubElement(e_rrset, "Type") e_type.text = rrset.rrset_type if change_vals.get('set_identifier'): e_set_id = etree.SubElement(e_rrset, "SetIdentifier") e_set_id.text = change_vals['set_identifier'] if change_vals.get('weight'): e_weight = etree.SubElement(e_rrset, "Weight") e_weight.text = change_vals['weight'] if change_vals.get('alias_hosted_zone_id') or change_vals.get('alias_dns_name'): e_alias_target = etree.SubElement(e_rrset, "AliasTarget") e_hosted_zone_id = etree.SubElement(e_alias_target, "HostedZoneId") e_hosted_zone_id.text = change_vals['alias_hosted_zone_id'] e_dns_name = etree.SubElement(e_alias_target, "DNSName") e_dns_name.text = change_vals['alias_dns_name'] if change_vals.get('region'): e_weight = etree.SubElement(e_rrset, "Region") e_weight.text = change_vals['region'] e_ttl = etree.SubElement(e_rrset, "TTL") e_ttl.text = str(change_vals['ttl']) if rrset.is_alias_record_set(): return e_change e_resource_records = etree.SubElement(e_rrset, "ResourceRecords") for value in change_vals['records']: e_resource_record = etree.SubElement(e_resource_records, "ResourceRecord") e_value = etree.SubElement(e_resource_record, "Value") e_value.text = value return e_change
def _init_transformer(cls, data): if isinstance(data, QuantumChannel): return data if hasattr(data, 'to_quantumchannel'): return data.to_channel() if hasattr(data, 'to_channel'): return data.to_channel() return Operator(data)
def _cmd(self, cmd, *args, **kw): ok = kw.setdefault('ok', False) self._wakeup() if args: cmd = "%s %s" % (cmd, ' '.join(str(a) for a in args)) for i in xrange(3): log.info("send: " + cmd) self.port.write(cmd + '\n') if ok: ack = self.port.read(len(self.OK)) log_raw('read', ack) if ack == self.OK: return else: ack = self.port.read(len(self.ACK)) log_raw('read', ack) if ack == self.ACK: return raise NoDeviceException('Can not access weather station')
def _index_put(self, idx_name, *ids_and_fcs): keys = self._index_keys_for(idx_name, *ids_and_fcs) with_vals = map(lambda k: (k, '0'), keys) self.kvl.put(self.INDEX_TABLE, *with_vals)
def valid(schema=None): def dec(fun): @wraps(fun) def d_func(self, ctx, data, *a, **kw): try: validate(data['params'], schema) except ValidationError as err: raise InvalidParams(err) except SchemaError as err: raise InternalError(err) return fun(self, ctx, data['params'], *a, **kw) return d_func return dec
def map_thread_names(): name2id = {} for thread_id in list(threading._active.keys()): thread = threading._active[thread_id] name = thread.getName() if name not in list(name2id.keys()): name2id[name] = thread_id pass pass return name2id
def _choi_to_kraus(data, input_dim, output_dim, atol=ATOL_DEFAULT): if is_hermitian_matrix(data, atol=atol): w, v = la.eigh(data) if len(w[w < -atol]) == 0: kraus = [] for val, vec in zip(w, v.T): if abs(val) > atol: k = np.sqrt(val) * vec.reshape( (output_dim, input_dim), order='F') kraus.append(k) if not kraus: kraus.append(np.zeros((output_dim, input_dim), dtype=complex)) return (kraus, None) mat_u, svals, mat_vh = la.svd(data) kraus_l = [] kraus_r = [] for val, vec_l, vec_r in zip(svals, mat_u.T, mat_vh.conj()): kraus_l.append( np.sqrt(val) * vec_l.reshape((output_dim, input_dim), order='F')) kraus_r.append( np.sqrt(val) * vec_r.reshape((output_dim, input_dim), order='F')) return (kraus_l, kraus_r)
def login(self, *login_args, **login_kwargs): def decorator(f): @wraps(f) def decorated(*args, **kwargs): self.response = make_response() adapter = WerkzeugAdapter(request, self.response) login_kwargs.setdefault('session', session) login_kwargs.setdefault('session_saver', self.session_saver) self.result = super(FlaskAuthomatic, self).login( adapter, *login_args, **login_kwargs) return f(*args, **kwargs) return decorated return decorator
def main(args=None): options, paths = _parse_options(args) format = getattr(options, 'output', 'simple') formatter = _FORMATTERS[format](options) for path in paths: meta = get_metadata(path, options.metadata_version) if meta is None: continue if options.download_url_prefix: if meta.download_url is None: filename = os.path.basename(path) meta.download_url = '%s/%s' % (options.download_url_prefix, filename) formatter(meta) formatter.finish()
def _get_format_from_document(self, token, document): code, html = self._formatter._format_lines([(token, u'dummy')]).next() self._document.setHtml(html) return QtGui.QTextCursor(self._document).charFormat()
def authenticate_credentials(self, key): user, token = super(TokenAuthentication, self).authenticate_credentials(key) if token.expires < timezone.now(): msg = _('Token has expired.') raise exceptions.AuthenticationFailed(msg) token.update_expiry() return (user, token)
def parse_issues(raw_page): raw_issues = json.loads(raw_page) issues = raw_issues['issues'] for issue in issues: yield issue
def nice_pair(pair): start, end = pair if start == end: return "%d" % start else: return "%d-%d" % (start, end)
def comments(self): record_numbers = range(2, self.fward) if not record_numbers: return '' data = b''.join(self.read_record(n)[0:1000] for n in record_numbers) try: return data[:data.find(b'\4')].decode('ascii').replace('\0', '\n') except IndexError: raise ValueError('DAF file comment area is missing its EOT byte') except UnicodeDecodeError: raise ValueError('DAF file comment area is not ASCII text')
def quadrature_scheme_lognormal_quantiles( loc, scale, quadrature_size, validate_args=False, name=None): with tf.name_scope(name or "quadrature_scheme_lognormal_quantiles"): dist = transformed_distribution.TransformedDistribution( distribution=normal.Normal(loc=loc, scale=scale), bijector=exp_bijector.Exp(), validate_args=validate_args) batch_ndims = tensorshape_util.rank(dist.batch_shape) if batch_ndims is None: batch_ndims = tf.shape(input=dist.batch_shape_tensor())[0] def _compute_quantiles(): zero = tf.zeros([], dtype=dist.dtype) edges = tf.linspace(zero, 1., quadrature_size + 3)[1:-1] edges = tf.reshape( edges, shape=tf.concat( [[-1], tf.ones([batch_ndims], dtype=tf.int32)], axis=0)) quantiles = dist.quantile(edges) perm = tf.concat([tf.range(1, 1 + batch_ndims), [0]], axis=0) quantiles = tf.transpose(a=quantiles, perm=perm) return quantiles quantiles = _compute_quantiles() grid = (quantiles[..., :-1] + quantiles[..., 1:]) / 2. new_shape = tensorshape_util.concatenate(dist.batch_shape, [quadrature_size]) tensorshape_util.set_shape(grid, new_shape) probs = tf.fill( dims=[quadrature_size], value=1. / tf.cast(quadrature_size, dist.dtype)) return grid, probs
def do_debug(self, args): if not args: self.help_fn("What information would you like: data, sys?") return ERR for info in args: if info == 'sys': print("-- sys ----------------------------------------") for line in info_formatter(self.coverage.sysinfo()): print(" %s" % line) elif info == 'data': print("-- data ---------------------------------------") self.coverage.load() print("path: %s" % self.coverage.data.filename) print("has_arcs: %r" % self.coverage.data.has_arcs()) summary = self.coverage.data.summary(fullpath=True) if summary: filenames = sorted(summary.keys()) print("\n%d files:" % len(filenames)) for f in filenames: print("%s: %d lines" % (f, summary[f])) else: print("No data collected") else: self.help_fn("Don't know what you mean by %r" % info) return ERR return OK
def read_channel(self): channel, message = self.protocol.channel_layer.receive_many([u'slack.send'], block=False) delay = 0.1 if channel: self.protocols[0].sendSlack(message) reactor.callLater(delay, self.read_channel)
def check_range(self, j): if isinstance(j, int): if j < 0 or j >= self.size: raise QiskitIndexError("register index out of range") elif isinstance(j, slice): if j.start < 0 or j.stop >= self.size or (j.step is not None and j.step <= 0): raise QiskitIndexError("register index slice out of range")
def split_vert_on_nonmanifold_face(script, vert_displacement_ratio=0.0): filter_xml = ''.join([ ' <filter name="Split Vertexes Incident on Non Manifold Faces">\n', ' <Param name="VertDispRatio" ', 'value="{}" '.format(vert_displacement_ratio), 'description="Vertex Displacement Ratio" ', 'type="RichFloat" ', '/>\n', ' </filter>\n']) util.write_filter(script, filter_xml) return None
def strsplit(self, pattern): fr = H2OFrame._expr(expr=ExprNode("strsplit", self, pattern)) fr._ex._cache.nrows = self.nrow return fr
def setup_cmd_parser(cls): parser = BackendCommandArgumentParser(cls.BACKEND.CATEGORIES, from_date=True, token_auth=True, archive=True) action = parser.parser._option_string_actions['--api-token'] action.required = True group = parser.parser.add_argument_group('Slack arguments') group.add_argument('--max-items', dest='max_items', type=int, default=MAX_ITEMS, help="Maximum number of items requested on the same query") parser.parser.add_argument('channel', help="Slack channel identifier") return parser
def _step_decorator_args(self, decorator): args = decorator.children[3:-2] step = None if len(args) == 1: try: step = ast.literal_eval(args[0].get_code()) except (ValueError, SyntaxError): pass if isinstance(step, six.string_types+(list,)): return step logging.error("Decorator step accepts either a string or a list of strings - %s:%d", self.file_path, decorator.start_pos[0]) else: logging.error("Decorator step accepts only one argument - %s:%d", self.file_path, decorator.start_pos[0])
def _create_prefix(self, dirname): if dirname in ('.', '/'): dirname = '' prefix = os.path.join(self._bucket_root, dirname) prefix = prefix.rstrip('/') return prefix
def build_fake_input_fns(batch_size): num_words = 1000 vocabulary = [str(i) for i in range(num_words)] random_sample = np.random.randint( 10, size=(batch_size, num_words)).astype(np.float32) def train_input_fn(): dataset = tf.data.Dataset.from_tensor_slices(random_sample) dataset = dataset.batch(batch_size).repeat() return tf.compat.v1.data.make_one_shot_iterator(dataset).get_next() def eval_input_fn(): dataset = tf.data.Dataset.from_tensor_slices(random_sample) dataset = dataset.batch(batch_size) return tf.compat.v1.data.make_one_shot_iterator(dataset).get_next() return train_input_fn, eval_input_fn, vocabulary
def voronoi(script, hole_num=50, target_layer=None, sample_layer=None, thickness=0.5, backward=True): if target_layer is None: target_layer = script.current_layer() if sample_layer is None: sampling.poisson_disk(script, sample_num=hole_num) sample_layer = script.last_layer() vert_color.voronoi(script, target_layer=target_layer, source_layer=sample_layer, backward=backward) select.vert_quality(script, min_quality=0.0, max_quality=thickness) if backward: select.invert(script) delete.selected(script) smooth.laplacian(script, iterations=3) return None
def get_ip(self): if len(self.client_nodes) > 0: node = self.client_nodes[0] else: node = self.nodes[0] return node.get_ip()
def project_dict(self, project_name, token_name, public): project_dict = {} project_dict['project_name'] = project_name if token_name is not None: if token_name == '': project_dict['token_name'] = project_name else: project_dict['token_name'] = token_name else: project_dict['token_name'] = project_name if public is not None: project_dict['public'] = public return project_dict
def extract_tar(archive, output_folder, handle_whiteout=False): from .terminal import run_command if handle_whiteout is True: return _extract_tar(archive, output_folder) args = '-xf' if archive.endswith(".tar.gz"): args = '-xzf' command = ["tar", args, archive, "-C", output_folder, "--exclude=dev/*"] if not bot.is_quiet(): print("Extracting %s" % archive) return run_command(command)
def walk_upgrade_domain(self, service_name, deployment_name, upgrade_domain): _validate_not_none('service_name', service_name) _validate_not_none('deployment_name', deployment_name) _validate_not_none('upgrade_domain', upgrade_domain) return self._perform_post( self._get_deployment_path_using_name( service_name, deployment_name) + '/?comp=walkupgradedomain', _XmlSerializer.walk_upgrade_domain_to_xml( upgrade_domain), as_async=True)
def get_clinvar_id(self, submission_id): submission_obj = self.clinvar_submission_collection.find_one({'_id': ObjectId(submission_id)}) clinvar_subm_id = submission_obj.get('clinvar_subm_id') return clinvar_subm_id
def generate_sentence(self, chain): def weighted_choice(choices): total_weight = sum(weight for val, weight in choices) rand = random.uniform(0, total_weight) upto = 0 for val, weight in choices: if upto + weight >= rand: return val upto += weight sentence = list(random.choice(chain.startwords)) while not sentence[-1][-1] in ['.', '?', '!']: sentence.append( weighted_choice( chain.content[tuple(sentence[-2:])].items() ) ) return ' '.join(sentence)
def _bisect(value_and_gradients_function, initial_args, f_lim): def _loop_cond(curr): return ~tf.reduce_all(input_tensor=curr.stopped) def _loop_body(curr): mid = value_and_gradients_function((curr.left.x + curr.right.x) / 2) failed = (curr.failed | ~is_finite(mid) | tf.equal(mid.x, curr.left.x) | tf.equal(mid.x, curr.right.x)) to_update = ~(curr.stopped | failed) update_left = (mid.df < 0) & (mid.f <= f_lim) left = val_where(to_update & update_left, mid, curr.left) right = val_where(to_update & ~update_left, mid, curr.right) stopped = curr.stopped | failed | (right.df >= 0) return [_IntermediateResult( iteration=curr.iteration, stopped=stopped, failed=failed, num_evals=curr.num_evals + 1, left=left, right=right)] return tf.while_loop( cond=_loop_cond, body=_loop_body, loop_vars=[initial_args])[0]
def from_pandas(df, name="pandas", copy_index=True, index_name="index"): import six vaex_df = vaex.dataframe.DataFrameArrays(name) def add(name, column): values = column.values try: vaex_df.add_column(name, values) except Exception as e: print("could not convert column %s, error: %r, will try to convert it to string" % (name, e)) try: values = values.astype("S") vaex_df.add_column(name, values) except Exception as e: print("Giving up column %s, error: %r" % (name, e)) for name in df.columns: add(name, df[name]) if copy_index: add(index_name, df.index) return vaex_df
def network_to_pandas_hdf5(network, filename, rm_nodes=None): if rm_nodes is not None: nodes, edges = remove_nodes(network, rm_nodes) else: nodes, edges = network.nodes_df, network.edges_df with pd.HDFStore(filename, mode='w') as store: store['nodes'] = nodes store['edges'] = edges store['two_way'] = pd.Series([network._twoway]) store['impedance_names'] = pd.Series(network.impedance_names)
def build_all_iop(self): lg.info('Building all b and c from IOPs') self.build_a() self.build_bb() self.build_b() self.build_c()
def _put_information(self): self.session._add_object() self.session._out('<<') self.session._out('/Producer ' + self._text_to_string( 'PDFLite, https://github.com/katerina7479')) if self.title: self.session._out('/Title ' + self._text_to_string(self.title)) if self.subject: self.session._out('/Subject ' + self._text_to_string(self.subject)) if self.author: self.session._out('/Author ' + self._text_to_string(self.author)) if self.keywords: self.session._out('/Keywords ' + self._text_to_string(self.keywords)) if self.creator: self.session._out('/Creator ' + self._text_to_string(self.creator)) self.session._out('/CreationDate ' + self._text_to_string( 'D:' + datetime.now().strftime('%Y%m%d%H%M%S'))) self.session._out('>>') self.session._out('endobj')
def get_rendition_key_set(key): try: rendition_key_set = IMAGE_SETS[key] except KeyError: raise ImproperlyConfigured( "No Rendition Key Set exists at " "settings.VERSATILEIMAGEFIELD_RENDITION_KEY_SETS['{}']".format(key) ) else: return validate_versatileimagefield_sizekey_list(rendition_key_set)
def _method_magic_marker(magic_kind): validate_type(magic_kind) def magic_deco(arg): call = lambda f, *a, **k: f(*a, **k) if callable(arg): func = arg name = func.func_name retval = decorator(call, func) record_magic(magics, magic_kind, name, name) elif isinstance(arg, basestring): name = arg def mark(func, *a, **kw): record_magic(magics, magic_kind, name, func.func_name) return decorator(call, func) retval = mark else: raise TypeError("Decorator can only be called with " "string or function") return retval magic_deco.__doc__ = _docstring_template.format('method', magic_kind) return magic_deco
def get_management_certificate(self, thumbprint): _validate_not_none('thumbprint', thumbprint) return self._perform_get( '/' + self.subscription_id + '/certificates/' + _str(thumbprint), SubscriptionCertificate)
def key_wrapping_data(self): key_wrapping_data = {} encryption_key_info = { 'unique_identifier': self._kdw_eki_unique_identifier, 'cryptographic_parameters': { 'block_cipher_mode': self._kdw_eki_cp_block_cipher_mode, 'padding_method': self._kdw_eki_cp_padding_method, 'hashing_algorithm': self._kdw_eki_cp_hashing_algorithm, 'key_role_type': self._kdw_eki_cp_key_role_type, 'digital_signature_algorithm': self._kdw_eki_cp_digital_signature_algorithm, 'cryptographic_algorithm': self._kdw_eki_cp_cryptographic_algorithm, 'random_iv': self._kdw_eki_cp_random_iv, 'iv_length': self._kdw_eki_cp_iv_length, 'tag_length': self._kdw_eki_cp_tag_length, 'fixed_field_length': self._kdw_eki_cp_fixed_field_length, 'invocation_field_length': self._kdw_eki_cp_invocation_field_length, 'counter_length': self._kdw_eki_cp_counter_length, 'initial_counter_value': self._kdw_eki_cp_initial_counter_value } } if not any(encryption_key_info['cryptographic_parameters'].values()): encryption_key_info['cryptographic_parameters'] = {} if not any(encryption_key_info.values()): encryption_key_info = {} mac_sign_key_info = { 'unique_identifier': self._kdw_mski_unique_identifier, 'cryptographic_parameters': { 'block_cipher_mode': self._kdw_mski_cp_block_cipher_mode, 'padding_method': self._kdw_mski_cp_padding_method, 'hashing_algorithm': self._kdw_mski_cp_hashing_algorithm, 'key_role_type': self._kdw_mski_cp_key_role_type, 'digital_signature_algorithm': self._kdw_mski_cp_digital_signature_algorithm, 'cryptographic_algorithm': self._kdw_mski_cp_cryptographic_algorithm, 'random_iv': self._kdw_mski_cp_random_iv, 'iv_length': self._kdw_mski_cp_iv_length, 'tag_length': self._kdw_mski_cp_tag_length, 'fixed_field_length': self._kdw_mski_cp_fixed_field_length, 'invocation_field_length': self._kdw_mski_cp_invocation_field_length, 'counter_length': self._kdw_mski_cp_counter_length, 'initial_counter_value': self._kdw_mski_cp_initial_counter_value } } if not any(mac_sign_key_info['cryptographic_parameters'].values()): mac_sign_key_info['cryptographic_parameters'] = {} if not any(mac_sign_key_info.values()): mac_sign_key_info = {} key_wrapping_data['wrapping_method'] = self._kdw_wrapping_method key_wrapping_data['encryption_key_information'] = encryption_key_info key_wrapping_data['mac_signature_key_information'] = mac_sign_key_info key_wrapping_data['mac_signature'] = self._kdw_mac_signature key_wrapping_data['iv_counter_nonce'] = self._kdw_iv_counter_nonce key_wrapping_data['encoding_option'] = self._kdw_encoding_option if not any(key_wrapping_data.values()): key_wrapping_data = {} return key_wrapping_data
def encode(self): header = bytearray(1) varHeader = bytearray() payload = bytearray() header[0] = 0x10 varHeader.extend(encodeString(self.version['tag'])) varHeader.append(self.version['level']) flags = (self.cleanStart << 1) if self.willTopic is not None and self.willMessage is not None: flags |= 0x04 | (self.willRetain << 5) | (self.willQoS << 3) if self.username is not None: flags |= 0x80 if self.password is not None: flags |= 0x40 varHeader.append(flags) varHeader.extend(encode16Int(self.keepalive)) payload.extend(encodeString(self.clientId)) if self.willTopic is not None and self.willMessage is not None: payload.extend(encodeString(self.willTopic)) payload.extend(encodeString(self.willMessage)) if self.username is not None: payload.extend(encodeString(self.username)) if self.password is not None: payload.extend(encode16Int(len(self.password))) payload.extend(bytearray(self.password, encoding='ascii', errors='ignore')) header.extend(encodeLength(len(varHeader) + len(payload))) header.extend(varHeader) header.extend(payload) self.encoded = header return str(header) if PY2 else bytes(header)
def stop_step(self, step_name): if self.finished is not None: raise AlreadyFinished() steps = copy.deepcopy(self.steps) step_data = self._get_step(step_name, steps=steps) if step_data is None: raise StepNotStarted() elif 'stop' in step_data: raise StepAlreadyFinished() step_data['stop'] = datetime.utcnow() step_data['duration'] = util.timedelta_total_seconds(step_data['stop'] - step_data['start']) self._save(steps=steps)
def _notebook_model_from_db(self, record, content): path = to_api_path(record['parent_name'] + record['name']) model = base_model(path) model['type'] = 'notebook' model['last_modified'] = model['created'] = record['created_at'] if content: content = reads_base64(record['content']) self.mark_trusted_cells(content, path) model['content'] = content model['format'] = 'json' self.validate_notebook_model(model) return model
def signal_kernel(self, signum): if self.has_kernel: self.kernel.send_signal(signum) else: raise RuntimeError("Cannot signal kernel. No kernel is running!")
def _header_constructor( cls, data_to_print, header_separator="-", column_separator=" " ): header_data = [] header_size = "" before_size = "%-" after_size = "s" if header_separator: header_separator_data = [] length_data_to_print = len(data_to_print) - 1 i = 0 for data in data_to_print: size = data_to_print[data] header_data.append(data) header_size += before_size + str(size) + after_size if i < length_data_to_print: header_size += column_separator if header_separator: header_separator_data.append(header_separator * size) i += 1 if header_separator: return [ header_size % tuple(header_data), header_size % tuple(header_separator_data), ] return [header_size % tuple(header_data)]
def equals_order_sensitive(self, other): if not isinstance(other, Mapping) or len(self) != len(other): return False return all(i == j for (i, j) in izip(iteritems(self), iteritems(other)))
def admin_footer(parser, token): tag_name = token.split_contents() if len(tag_name) > 1: raise base.TemplateSyntaxError( '{} tag does not accept any argument(s): {}'.format( token.contents.split()[0], ', '.join(token.contents.split()[1:]) )) return AdminFooterNode()
def next(self): val = self._current self._current = self.readfunc() return val
def create(self): if not os.path.exists(self.path): open(self.path, 'a').close() else: raise Exception("File exists: {}".format(self.path))
def write_json_report(sample_id, data1, data2): parser_map = { "base_sequence_quality": ">>Per base sequence quality", "sequence_quality": ">>Per sequence quality scores", "base_gc_content": ">>Per sequence GC content", "base_n_content": ">>Per base N content", "sequence_length_dist": ">>Sequence Length Distribution", "per_base_sequence_content": ">>Per base sequence content" } json_dic = { "plotData": [{ "sample": sample_id, "data": { "base_sequence_quality": {"status": None, "data": []}, "sequence_quality": {"status": None, "data": []}, "base_gc_content": {"status": None, "data": []}, "base_n_content": {"status": None, "data": []}, "sequence_length_dist": {"status": None, "data": []}, "per_base_sequence_content": {"status": None, "data": []} } }] } for cat, start_str in parser_map.items(): if cat == "per_base_sequence_content": fs = 1 fe = 5 else: fs = 1 fe = 2 report1, status1 = _get_quality_stats(data1, start_str, field_start=fs, field_end=fe) report2, status2 = _get_quality_stats(data2, start_str, field_start=fs, field_end=fe) status = None for i in ["fail", "warn", "pass"]: if i in [status1, status2]: status = i json_dic["plotData"][0]["data"][cat]["data"] = [report1, report2] json_dic["plotData"][0]["data"][cat]["status"] = status return json_dic
def case_insensitive(self, fields_dict): if hasattr(self.model, 'CASE_INSENSITIVE_FIELDS'): for field in self.model.CASE_INSENSITIVE_FIELDS: if field in fields_dict: fields_dict[field + '__iexact'] = fields_dict[field] del fields_dict[field]
def trim_data_back_to(monthToKeep): global g_failed_tests_info_dict current_time = time.time() oldest_time_allowed = current_time - monthToKeep*30*24*3600 clean_up_failed_test_dict(oldest_time_allowed) clean_up_summary_text(oldest_time_allowed)
def fill(self, doc_contents): for key, content in doc_contents.items(): doc_contents[key] = replace_chars_for_svg_code(content) return super(SVGDocument, self).fill(doc_contents=doc_contents)
def In(sigOrVal, iterable): res = None for i in iterable: i = toHVal(i) if res is None: res = sigOrVal._eq(i) else: res = res | sigOrVal._eq(i) assert res is not None, "Parameter iterable is empty" return res
def set_client_certificate(self, certificate): _certificate = BSTR(certificate) _WinHttpRequest._SetClientCertificate(self, _certificate)
def validate_chunks(self, chunks): starts = set([ch.byte for ch in chunks]) for ch in chunks: assert all([(ex in starts or ex < 0) for ex in ch.exits])
def get_external_tools_in_account(self, account_id, params={}): url = ACCOUNTS_API.format(account_id) + "/external_tools" external_tools = [] for data in self._get_paged_resource(url, params=params): external_tools.append(data) return external_tools
def execute(self, context): self.hook = DiscordWebhookHook( self.http_conn_id, self.webhook_endpoint, self.message, self.username, self.avatar_url, self.tts, self.proxy ) self.hook.execute()
def make_dict_observable(matrix_observable): dict_observable = {} observable = np.array(matrix_observable) observable_size = len(observable) observable_bits = int(np.ceil(np.log2(observable_size))) binary_formater = '0{}b'.format(observable_bits) if observable.ndim == 2: observable = observable.diagonal() for state_no in range(observable_size): state_str = format(state_no, binary_formater) dict_observable[state_str] = observable[state_no] return dict_observable
def _check_wiremap_validity(self, wire_map, keymap, valmap): for k, v in wire_map.items(): kname = "%s[%d]" % (k[0].name, k[1]) vname = "%s[%d]" % (v[0].name, v[1]) if k not in keymap: raise DAGCircuitError("invalid wire mapping key %s" % kname) if v not in valmap: raise DAGCircuitError("invalid wire mapping value %s" % vname) if type(k) is not type(v): raise DAGCircuitError("inconsistent wire_map at (%s,%s)" % (kname, vname))
def pformat_dict_summary_html(dict): if not dict: return ' {}' html = [] for key, value in sorted(six.iteritems(dict)): if not isinstance(value, DICT_EXPANDED_TYPES): value = '...' html.append(_format_dict_item(key, value)) return mark_safe(u'<br/>'.join(html))
def selected(self): if self._selected: return self._selected if self.asc else \ "-{0}".format(self._selected) return None
def _helpful_failure(method): @wraps(method) def wrapper(self, val): try: return method(self, val) except: exc_cls, inst, tb = sys.exc_info() if hasattr(inst, '_RERAISE'): _, expr, _, inner_val = Q.__debug_info__ Q.__debug_info__ = QDebug(self, expr, val, inner_val) raise if issubclass(exc_cls, KeyError): exc_cls = QKeyError prettyval = repr(val) if len(prettyval) > 150: prettyval = "<%s instance>" % (type(val).__name__) msg = "{0}\n\n\tEncountered when evaluating {1}{2}".format( inst, prettyval, self) new_exc = exc_cls(msg) new_exc._RERAISE = True Q.__debug_info__ = QDebug(self, self, val, val) six.reraise(exc_cls, new_exc, tb) return wrapper
def _add_to_tree(self, start_node, split_names, type_name, group_type_name, instance, constructor, args, kwargs): try: act_node = start_node last_idx = len(split_names) - 1 add_link = type_name == LINK link_added = False for idx, name in enumerate(split_names): if name not in act_node._children: if idx == last_idx: if add_link: new_node = self._create_link(act_node, name, instance) link_added = True elif group_type_name != type_name: new_node = self._create_any_param_or_result(act_node, name, type_name, instance, constructor, args, kwargs) self._flat_leaf_storage_dict[new_node.v_full_name] = new_node else: new_node = self._create_any_group(act_node, name, group_type_name, instance, constructor, args, kwargs) else: new_node = self._create_any_group(act_node, name, group_type_name) if name in self._root_instance._run_information: self._root_instance._run_parent_groups[act_node.v_full_name] = act_node if self._root_instance._is_run: if link_added: self._root_instance._new_links[(act_node.v_full_name, name)] = \ (act_node, new_node) else: self._root_instance._new_nodes[(act_node.v_full_name, name)] = \ (act_node, new_node) else: if name in act_node._links: raise AttributeError('You cannot hop over links when adding ' 'data to the tree. ' 'There is a link called `%s` under `%s`.' % (name, act_node.v_full_name)) if idx == last_idx: if self._root_instance._no_clobber: self._logger.warning('You already have a group/instance/link `%s` ' 'under `%s`. ' 'However, you set `v_no_clobber=True`, ' 'so I will ignore your addition of ' 'data.' % (name, act_node.v_full_name)) else: raise AttributeError('You already have a group/instance/link `%s` ' 'under `%s`' % (name, act_node.v_full_name)) act_node = act_node._children[name] return act_node except: self._logger.error('Failed adding `%s` under `%s`.' % (name, start_node.v_full_name)) raise
def tostring(self): root = self.as_element() indent(root) txt = ET.tostring(root, encoding="utf-8") txt = re.sub(r'_[A-Z]_','',txt) txt = '<?xml version="1.0" encoding="utf-8"?>\n' + txt return txt
def __head(self,h): return '%s%s%s' % (self.color_table.active_colors.header,h, self.color_table.active_colors.normal)