code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def _submit_request(self, url, params=None, data=None, headers=None, method="GET"): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if method == 'POST': <NEW_LINE> <INDENT> result = requests.post( url, params=params, data=data, headers=headers) <NEW_LINE> <DEDENT> elif method == 'GET': <NEW_LINE> <INDENT> result = request...
Submits the given request, and handles the errors appropriately. Args: url (str): the request to send. params (dict): params to be passed along to get/post data (bytes): the data to include in the request. headers (dict): the headers to include in the request. method (str): the method to use for th...
625941c41b99ca400220aa85
def terminal_width(): <NEW_LINE> <INDENT> width = 0 <NEW_LINE> try: <NEW_LINE> <INDENT> import struct, fcntl, termios <NEW_LINE> s = struct.pack('HHHH', 0, 0, 0, 0) <NEW_LINE> x = fcntl.ioctl(1, termios.TIOCGWINSZ, s) <NEW_LINE> width = struct.unpack('HHHH', x)[1] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <N...
Function to compute the terminal width. WARNING: This is not my code, but I've been using it previous projects and I don't remember where it came from.
625941c4bde94217f3682dc7
def processXMLElement( xmlElement, xmlProcessor ): <NEW_LINE> <INDENT> group.processShape( Sphere, xmlElement, xmlProcessor )
Process the xml element.
625941c4d53ae8145f87a247
def _cartprod(d): <NEW_LINE> <INDENT> if not d: <NEW_LINE> <INDENT> return [dict()] <NEW_LINE> <DEDENT> r = [] <NEW_LINE> k, vs = d.popitem() <NEW_LINE> itervals = vs if type(vs) is tuple else [vs] <NEW_LINE> for v in itervals: <NEW_LINE> <INDENT> cps = _cartprod(d) <NEW_LINE> for cp in cps: <NEW_LINE> <INDENT> kv = {k...
makes a combinatorial explosion from a dictionary only combinations are made from values in tuples
625941c4e76e3b2f99f3a7e2
@app.route('/delete/<int:snippet_id>', methods=['GET']) <NEW_LINE> @login_required <NEW_LINE> def delete_snippet_get(snippet_id): <NEW_LINE> <INDENT> item = Snippet.all.filter(c.id == snippet_id).one(None).execute() <NEW_LINE> if item: <NEW_LINE> <INDENT> return render_template( 'delete.html.jinja2', snip_id=snippet_id...
The page for deleting snippets. Argument: snippet_id -- The id of the snippet to delete
625941c48a43f66fc4b5403b
def login_prompt(self): <NEW_LINE> <INDENT> email = typer.prompt("Enter email address") <NEW_LINE> password = typer.prompt("Enter password",hide_input=True) <NEW_LINE> url = f"{app_settings.get_endpoint()}/programmers/login" <NEW_LINE> data = { "username" : email, "password" : password } <NEW_LINE> try: <NEW_LINE> <IND...
login prompt to enter credentials.
625941c4379a373c97cfab18
def parse_validator(self, validator_data): <NEW_LINE> <INDENT> name = validator_data['name'] <NEW_LINE> validator = self.registry.get_validator(self.type, name)(self, validator_data) <NEW_LINE> return validator
Returns a function that checks the value of a field. Accepts a dict parameter with a type property to lookup against the list of validators. The returned function should have three parameters: * form - parsed field values. * path - path to the current field as a list. * value - parsed value of the current field.
625941c4460517430c39415e
def __init__(self, inp): <NEW_LINE> <INDENT> if isinstance(inp,dict): <NEW_LINE> <INDENT> assert len(inp) == 1 <NEW_LINE> self.night = list(inp.keys())[0] <NEW_LINE> assert len(inp[self.night]) == 1 <NEW_LINE> self.expid = list(inp[self.night].keys())[0] <NEW_LINE> assert len(inp[self.night][self.expid]) == 2 <NEW_LINE...
Class to organize and execute QA for a DESI frame x.flavor, x.qa_data, x.camera Args: inp : Frame object or dict * Frame -- Must contain meta data * dict -- Usually read from hard-drive Notes:
625941c46fece00bbac2d711
def _cache_get(self, metric_name): <NEW_LINE> <INDENT> metric = self.__cache.get(metric_name, False) <NEW_LINE> if metric is False: <NEW_LINE> <INDENT> return None, False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return metric, True
Get metric from cache.
625941c47d847024c06be28e
def YieldStart(builder): <NEW_LINE> <INDENT> return Start(builder)
This method is deprecated. Please switch to Start.
625941c4796e427e537b0599
def create_multitem_treeview(self): <NEW_LINE> <INDENT> self.headers = ['Python Module','Installed Version','Available Versions'] <NEW_LINE> from pip_tkinter.utils import MultiItemsList <NEW_LINE> self.multi_items_list = MultiItemsList(self, self.headers) <NEW_LINE> self.multi_items_list.scroll_tree.bind( '<<TreeviewSe...
Create multitem treeview to show search results with headers : 1. Python Module 2. Installed version 3. Available versions List of buttons : 1. navigate_back 2. navigate_next 3. search_button
625941c450485f2cf553cd6d
def Rz(t): <NEW_LINE> <INDENT> return np.matrix([[c(t), -s(t), 0], [s(t), c(t), 0], [0, 0, 1]])
Rotation matrix around z axis, theta in radians
625941c4a8ecb033257d30a2
def overlay_bounding_boxes(raw_img, refined_bboxes, lw, n = 0): <NEW_LINE> <INDENT> face_list = [] <NEW_LINE> OneD = [] <NEW_LINE> for r in refined_bboxes: <NEW_LINE> <INDENT> _score = expit(r[4]) <NEW_LINE> cm_idx = int(np.ceil(_score * 255)) <NEW_LINE> rect_color = [int(np.ceil(x * 255)) for x in util.cm_data[cm_idx]...
Overlay bounding boxes of face on images. Args: raw_img: A target image. refined_bboxes: Bounding boxes of detected faces. lw: Line width of bounding boxes. If zero specified, this is determined based on confidence of each detection. Returns: None.
625941c40a50d4780f666e65
def _del_remote_user(batch_client, pool_id, node_id, username): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> batch_client.compute_node.delete_user( pool_id, node_id, username) <NEW_LINE> logger.debug('deleted remote user {} from node {}'.format( username, node_id)) <NEW_LINE> <DEDENT> except batchmodels.BatchErrorExcep...
Delete a remote user on a node :param batch_client: The batch client to use. :type batch_client: `azure.batch.batch_service_client.BatchServiceClient` :param str pool_id: pool id :param str node_id: node id :param str username: user name
625941c45fdd1c0f98dc0207
def test_get_formatted_locations_basic_auth(self) -> None: <NEW_LINE> <INDENT> index_urls = [ "https://pypi.org/simple", "https://repo-user:[email protected]", ] <NEW_LINE> find_links = ["https://links-user:[email protected]"] <NEW_LINE> search_scope = SearchScope( find_links=find_links, index_urls=ind...
Test that basic authentication credentials defined in URL is not included in formatted output.
625941c49c8ee82313fbb749
def find_nearest_point_idx(ref_pts,que_pts): <NEW_LINE> <INDENT> assert(ref_pts.shape[1]==que_pts.shape[1] and 1<que_pts.shape[1]<=3) <NEW_LINE> pn1=ref_pts.shape[0] <NEW_LINE> pn2=que_pts.shape[0] <NEW_LINE> dim=ref_pts.shape[1] <NEW_LINE> ref_pts=np.ascontiguousarray(ref_pts[None,:,:],np.float32) <NEW_LINE> que_pts=n...
for every point in que_pts, find the nearest point in ref_pts :param ref_pts: pn1,3 or 2 :param que_pts: pn2,3 or 2 :return: idxs pn2
625941c4d8ef3951e3243512
def test_upload(self): <NEW_LINE> <INDENT> client = api.Client(self.cfg, api.json_handler) <NEW_LINE> repo = client.post(REPOSITORY_PATH, gen_repo()) <NEW_LINE> self.addCleanup(client.delete, repo['_href']) <NEW_LINE> rpm = utils.http_get(RPM_WITH_VENDOR_URL) <NEW_LINE> upload_import_unit(self.cfg, rpm, {'unit_type_id'...
Test whether Pulp recognizes an uploaded RPM's vendor information. Create a repository, upload an RPM with a non-null vendor, and perform several checks. See :meth:`do_test`.
625941c4097d151d1a222e30
def test_operator(self): <NEW_LINE> <INDENT> g = L('ABC') | L('ABD') <NEW_LINE> self.assertTrue(issubclass(g, modgrammar.OR_Operator)) <NEW_LINE> self.check_sanity(g, (Literal, Literal)) <NEW_LINE> g = L('ABC') | 'ABD' <NEW_LINE> self.assertTrue(issubclass(g, modgrammar.OR_Operator)) <NEW_LINE> self.check_sanity(g, (Li...
Test the OR operator ('|') Make sure the OR operator ('|') correctly wraps other grammars in an OR class. Also make sure that ORing together grammars with non-grammars results in a correctly regularized result.
625941c4cad5886f8bd26fae
def on_session_ended(session_ended_request, session): <NEW_LINE> <INDENT> logger.info("on_session_ended requestId=" + session_ended_request['requestId'] + ", sessionId=" + session['sessionId'])
Called when the user ends the session. Is not called when the skill returns should_end_session=true
625941c4bf627c535bc131a3
def Save(self, request, context): <NEW_LINE> <INDENT> print('Method Save in main server get called:') <NEW_LINE> self.update_db() <NEW_LINE> record = get_record(self.db, request) <NEW_LINE> if record is None: <NEW_LINE> <INDENT> return dist_bank_pb2.BalanceRecord(uid="0", balance=0, index=-1, res_info=_RECORD_NOT_EXIST...
Implementation of save money method. request: A SaveRequest (see dist_bank.proto) return: A BalanceRecord response (see dist_bank.proto)
625941c4099cdd3c635f0c30
def create_folderpath_if_not_exists(dirname): <NEW_LINE> <INDENT> if os.path.exists(dirname)==False: <NEW_LINE> <INDENT> os.makedirs(dirname)
Creates the given filepath path if not existing
625941c463b5f9789fde70ba
def store_json(paper, storage_path=STORAGE_PATH): <NEW_LINE> <INDENT> if not paper.file_path_json or paper.file_path_json in [None, ""]: <NEW_LINE> <INDENT> name = make_random_string() <NEW_LINE> filename = name + ".json" <NEW_LINE> jsonpath = make_full_path(filename, storage_path=storage_path) <NEW_LINE> <DEDENT> else...
Store paper metadata somewhere.
625941c43c8af77a43ae3773
@transaction.atomic <NEW_LINE> def update_tag(request, t): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> tid = int(t) <NEW_LINE> tag = ExTag.objects.get(id=tid) <NEW_LINE> if 'text' in request.POST and request.POST['text'].strip(): <NEW_LINE> <INDENT> tag.text = request.POST['text'].strip() <NEW_LINE> <DEDENT> if 'info'...
更新一个标签 :param request: 请求 :param t: 标签id :return: 是否成功
625941c4aad79263cf390a13
def get_transmat(): <NEW_LINE> <INDENT> c=0 <NEW_LINE> c_map={} <NEW_LINE> for v in data : <NEW_LINE> <INDENT> for key in v : <NEW_LINE> <INDENT> value=v[key] <NEW_LINE> <DEDENT> prints("value[0] is "+value[0]) <NEW_LINE> for v_i in range(len(value)-1): <NEW_LINE> <INDENT> couple=value[v_i:v_i+2] <NEW_LINE> c_couple_so...
get transmat of status
625941c4b545ff76a8913deb
def test_config_cfgpath_cwd(fakeClient, tmpconfigfile, monkeypatch, tmpfiles): <NEW_LINE> <INDENT> monkeypatch.setenv("HOME", str(tmpconfigfile.home)) <NEW_LINE> cfgdirs = [ Path("~/.config/icat").expanduser(), Path("~/.icat").expanduser(), Path("."), ] <NEW_LINE> monkeypatch.setattr(icat.config, "cfgdirs", cfgdirs) <N...
Test a cfgpath configuration variable. Same as test_config_cfgpath_default() but a file in the current working directory takes precedence of the one in the configuration directory.
625941c482261d6c526ab471
def _latex_(self): <NEW_LINE> <INDENT> return "\\textnormal{Berlekamp-Welch decoder for } %s" % self.code()._latex_()
Return a latex representation of ``self``. EXAMPLES: sage: q = 3^2 sage: m = 4 sage: Fqm = GF(q^m) sage: Fq = GF(q) sage: n, k = 4, 2 sage: C = codes.GabidulinCode(Fqm, n, k, Fq) sage: D = codes.decoders.GabidulinBerlekampWelchDecoder(C) sage: latex(D) \textnormal{Berlekamp-Welch d...
625941c46aa9bd52df036d78
def show(self): <NEW_LINE> <INDENT> write(self._option_names) <NEW_LINE> self._command_line.show()
Show menu
625941c47d847024c06be28f
def display_output(data, out=None, opts=None): <NEW_LINE> <INDENT> if opts is None: <NEW_LINE> <INDENT> opts = {} <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> display_data = get_printout(out, opts)(data).rstrip() <NEW_LINE> <DEDENT> except (KeyError, AttributeError): <NEW_LINE> <INDENT> log.debug(traceback.format_exc()...
Print the passed data using the desired output
625941c49b70327d1c4e0da9
@contextmanager <NEW_LINE> def working_dir(new_path): <NEW_LINE> <INDENT> old_dir = os.getcwd() <NEW_LINE> os.chdir(new_path) <NEW_LINE> try: <NEW_LINE> <INDENT> yield <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> os.chdir(old_dir)
A context manager that changes to the new_path directory and returns to the current working directory when it completes.
625941c432920d7e50b281a3
def generate_per_host_enqueue_ops_fn_for_host( ctx, input_fn, inputs_structure_recorder, batch_axis, device, host_id): <NEW_LINE> <INDENT> captured_infeed_queue = _CapturedObject() <NEW_LINE> hooks = [] <NEW_LINE> with ops.device(device): <NEW_LINE> <INDENT> inputs = _Inputs.from_input_fn(input_fn()) <NEW_LINE> is_data...
Generates infeed enqueue ops for per-host input_fn on a single host.
625941c4cc40096d61595926
def tweak(ebook_file): <NEW_LINE> <INDENT> fmt = ebook_file.rpartition('.')[-1].lower() <NEW_LINE> exploder, rebuilder = get_tools(fmt) <NEW_LINE> if exploder is None: <NEW_LINE> <INDENT> prints('Cannot tweak %s files. Supported formats are: EPUB, HTMLZ, AZW3, MOBI' % fmt.upper() , file=sys.stderr) <NEW_LINE> raise Sys...
Command line interface to the Tweak Book tool
625941c496565a6dacc8f6a0
def t_NEWLINE(self, t): <NEW_LINE> <INDENT> t.lexer.lineno += t.value.count("\n") <NEW_LINE> t.value = ('NEWLINE', t.value) <NEW_LINE> return t
((?:\n)|(?:\r\n))+
625941c467a9b606de4a7e90
def renamed(self, name_map): <NEW_LINE> <INDENT> return Snippets({name_map[name]: snippet for (name, snippet) in self.__snippets.items()})
Create a snippet collection by renaming the snippets of another one. name_map: dict of string to string mapping of original snippet names to new snippet names returns: a new Snippets instance with the keys being renamed
625941c496565a6dacc8f6a1
def finish_publishing(self): <NEW_LINE> <INDENT> if "verification_key_end" not in self._offsets: <NEW_LINE> <INDENT> raise LayoutInvalid("You must put the verification key before " "you can publish the offsets") <NEW_LINE> <DEDENT> offsets_offset = struct.calcsize(MDMFHEADERWITHOUTOFFSETS) <NEW_LINE> offsets = struct.p...
I add a write vector for the offsets table, and then cause all of the write vectors that I've dealt with so far to be published to the remote server, ending the write process.
625941c4009cb60464c63388
def test_key_set_reset_unset_permissions(self): <NEW_LINE> <INDENT> with RandomKeyTmpFile() as first_fname, RandomKeyTmpFile() as second_fname: <NEW_LINE> <INDENT> self._test_permissions( [_STRATIS_CLI, "key", "set", "testkey2", "--keyfile-path", first_fname], True, True, ) <NEW_LINE> self._test_permissions( [ _STRATIS...
Test setting, resetting, and unsetting a key fails with dropped permissions.
625941c432920d7e50b281a4
def print_titles(data): <NEW_LINE> <INDENT> for name, info in data.items(): <NEW_LINE> <INDENT> print(info[0], name) <NEW_LINE> <DEDENT> print()
print a list of titles and names :param data: dict of data :return: None
625941c476d4e153a657eb05
def drop_tables(cur, conn): <NEW_LINE> <INDENT> for query in drop_table_queries: <NEW_LINE> <INDENT> cur.execute(query) <NEW_LINE> conn.commit()
This function drop the tables from the database Parameters: cur (object): object cursor conn (object): object conn Returns None
625941c4f8510a7c17cf96d0
def post_order_search(self, node=None): <NEW_LINE> <INDENT> if node is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.post_order_search(node.left) <NEW_LINE> self.post_order_search(node.right) <NEW_LINE> print(node.data, end=' ')
Post order algorithm. :input: node : It must be Node type. :return: None. Just print elements. You can override to do other jobs.
625941c41f5feb6acb0c4b28
def test_name_set_compulsory(self): <NEW_LINE> <INDENT> name = "Field Name" <NEW_LINE> field = basic.numeric(5, name=name, compulsory=True) <NEW_LINE> self.assertEqual(name, field.name)
Tests that the given field name is set correctly for optional fields, for compulsory fields.
625941c4c4546d3d9de72a07
def getAttribute(self, key): <NEW_LINE> <INDENT> return self.blockProperties.getAttribute(key)
Return the attribute corresponding to the key argument in the dictionary.
625941c4f8510a7c17cf96d1
def constraint(self, canvas, item, handle, glue_item): <NEW_LINE> <INDENT> origin = canvas.project(glue_item, self.point) <NEW_LINE> point = canvas.project(item, handle.pos) <NEW_LINE> c = PositionConstraint(origin, point) <NEW_LINE> return c
Return connection position constraint between item's handle and the port.
625941c450812a4eaa59c2f8
def main(global_config, **settings): <NEW_LINE> <INDENT> config = Configurator(settings=settings) <NEW_LINE> config.include("pyramid_chameleon") <NEW_LINE> if asbool(settings.get("dingen.dev")): <NEW_LINE> <INDENT> dev_static = settings.get("dingen.dev_static", "static") <NEW_LINE> config.add_static_view(name=dev_stati...
This function returns a Pyramid WSGI application.
625941c48c3a87329515838e
def merge_dictionaries_with_list_values(dictionaries): <NEW_LINE> <INDENT> result = collections.defaultdict(list) <NEW_LINE> for d in dictionaries: <NEW_LINE> <INDENT> for k in d: <NEW_LINE> <INDENT> result[k].extend(d[k]) <NEW_LINE> <DEDENT> <DEDENT> return result
Merge dictionaries with list values, concatenating the lists. Returns a dictionary with keys in the union of the input keys. The value for a particular key is the concatenation of the values for that key across all input dictionaries.
625941c43346ee7daa2b2d40
def LL(self,h,X=None,stack=True,REML=False): <NEW_LINE> <INDENT> if X is None: <NEW_LINE> <INDENT> X = self.X0t <NEW_LINE> <DEDENT> elif stack: <NEW_LINE> <INDENT> self.X0t_stack[:,(self.q)] = matrixMult(self.Kve.T,X)[:,0] <NEW_LINE> X = self.X0t_stack <NEW_LINE> <DEDENT> n = float(self.N) <NEW_LINE> q = float(X.shape[...
Computes the log-likelihood for a given heritability (h). If X==None, then the default X0t will be used. If X is set and stack=True, then X0t will be matrix concatenated with the input X. If stack is false, then X is used in place of X0t in the LL calculation. REML is computed by adding additional terms to the stan...
625941c42ae34c7f2600d107
def __init__(self, screen, optionsa): <NEW_LINE> <INDENT> self.screen = screen <NEW_LINE> self.optionsa = optionsa <NEW_LINE> self.xcoord = 0 <NEW_LINE> self.ycoord = 0 <NEW_LINE> self.font = pygame.font.Font(None, 32) <NEW_LINE> self.option = 0 <NEW_LINE> self.width = 1 <NEW_LINE> self.color = [0, 0, 0] <NEW_LINE> sel...
initialising :param screen: main view screen :param optionsa: options(color) :return:
625941c4de87d2750b85fd66
def generateTransferManifest(clientManifest,serverManifest): <NEW_LINE> <INDENT> with sftp.open("/home/{}/ftpsync/.client01Control/transferManifest.json".format(SERVERUSER)) as infile: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> transfermanifest = json.load(infile) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> trans...
Function takes the most up-to-date client manifest and server manifest and compares them. Looks for files that aren't on the server or the server version is older, this files are added to a dict (under the top level key "Transfer") along with they critical properties (SHA256 hash, last modified times, file directories)...
625941c497e22403b379cf6e
def _authorize(ctx): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ctx.user = superviseur.authorize(ctx.simulation.compute_node_login) <NEW_LINE> <DEDENT> except UserWarning as err: <NEW_LINE> <INDENT> logger.log_mq_warning("Supervision authorization failure: {}".format(err)) <NEW_LINE> ctx.abort = True
Verifies that the user has authorized supervision.
625941c4925a0f43d2549e4b
def validate_fusions(self): <NEW_LINE> <INDENT> if self.args.valfile is None: <NEW_LINE> <INDENT> raise Exception('validate_fusions step requires --valfile argument') <NEW_LINE> <DEDENT> outdir = os.path.join("fusions", "cff") <NEW_LINE> cluster = os.path.join(outdir, "merged.cff.renamed.reann.cluster.blck_filter.RT_fi...
Compares the pipeline output in merged.cff.reann.dnasupp.bwafilter.30.cluster with the predetermined fusion gene test file.This step should be run only with a test .bam/.fastq file, in order to confirm detection of validated fusions which are known to bepresent in the sample. Requires --valfile flag, with correspondin...
625941c4a05bb46b383ec7f8
def elapseTime(self, gameState): <NEW_LINE> <INDENT> newParticles = [] <NEW_LINE> for oldParticle in self.particles: <NEW_LINE> <INDENT> newParticle = list(oldParticle) <NEW_LINE> "*** YOU DON'T NEED TO WRITE CODE HERE ***" <NEW_LINE> newParticles.append(tuple(newParticle)) <NEW_LINE> <DEDENT> self.particles = newParti...
Samples each particle's next state based on its current state and the gameState. To loop over the ghosts, use: for i in range(self.numGhosts): ... Then, assuming that `i` refers to the index of the ghost, to obtain the distributions over new positions for that single ghost, given the list (prevGhostPositions) ...
625941c4bf627c535bc131a4
def print_par(self): <NEW_LINE> <INDENT> print("#{}\nPOS ({},{})\nvalue: {}\n".format( self.index, round(self.position[0], 3), round(self.position[1], 3), round(self.fitness, 3) ))
Print info of a particle
625941c46fece00bbac2d712
def _convert_g_raw_to_gh(self, g_raw, l_max=None): <NEW_LINE> <INDENT> if not l_max: <NEW_LINE> <INDENT> l_max = self.l_max <NEW_LINE> <DEDENT> g = {} <NEW_LINE> h = {} <NEW_LINE> g[1] = {0:g_raw[0]} <NEW_LINE> g[1][1] = g_raw[1] <NEW_LINE> h[1] = {0:0, 1:g_raw[2]} <NEW_LINE> i = 3 <NEW_LINE> for l in range(2,l_max+1):...
Converts g_raw computed for a time to g, h dictionaries Inputs ------ g_raw: numpy array of g_raw, standard ordering as on single-time g_raw files from website. l_max: spherical harmonic degree included in model (automatically taken from data_file) Returns ------- g, h: dictionaries of Gauss coefficients o...
625941c430c21e258bdfa471
def __init__(self, celeba_loader, rafd_loader, config): <NEW_LINE> <INDENT> self.celeba_loader = celeba_loader <NEW_LINE> self.rafd_loader = rafd_loader <NEW_LINE> self.c_dim = config.c_dim <NEW_LINE> self.c2_dim = config.c2_dim <NEW_LINE> self.image_size = config.image_size <NEW_LINE> self.e_conv_dim = config.e_conv_d...
Initialize configurations.
625941c4bd1bec0571d90604
def __scan_option_tags_for_group(cls, opt): <NEW_LINE> <INDENT> def add_option_to_group(atag): <NEW_LINE> <INDENT> __group = '__%s' % atag <NEW_LINE> group = getattr(cls, __group, None) <NEW_LINE> if group is not None: <NEW_LINE> <INDENT> if isinstance(group, OptionGroup): <NEW_LINE> <INDENT> group.add(opt) <NEW_LINE> ...
Scan all tags in a given Option object and add the object to appropriate group of the tag. :param opt: Option object :return:
625941c499fddb7c1c9de367
def _FormatFile(filename, lines, style_config=None, no_local_style=False, in_place=False, print_diff=False, verify=False, quiet=False, verbose=False): <NEW_LINE> <INDENT> if verbose and not quiet: <NEW_LINE> <INDENT> print('Reformatting %s' % filename) <NEW_LINE> <DEDENT> if style_config is None and not no_local_style:...
Format an individual file.
625941c4167d2b6e31218b6b
@contextmanager <NEW_LINE> def fail_at(deadline): <NEW_LINE> <INDENT> with move_on_at(deadline) as scope: <NEW_LINE> <INDENT> yield scope <NEW_LINE> <DEDENT> if scope.cancelled_caught: <NEW_LINE> <INDENT> raise TooSlowError
Creates a cancel scope with the given deadline, and raises an error if it is actually cancelled. This function and :func:`move_on_at` are similar in that both create a cancel scope with a given absolute deadline, and if the deadline expires then both will cause :exc:`Cancelled` to be raised within the scope. The diffe...
625941c47b25080760e3942f
def test_create_party_name_empty(self): <NEW_LINE> <INDENT> response = self.Client.post('/api/v1/parties', data=json.dumps(self.no_name), content_type='application/json') <NEW_LINE> result = json.loads(response.data.decode()) <NEW_LINE> self.assertEqual(result['message'], {'name': 'Name of the party should be filled'})
Return name to be filled as require data
625941c45e10d32532c5eefd
def update_tox_envlist(envlist: str, new_versions: SortedVersionList) -> str: <NEW_LINE> <INDENT> m = re.search(r',\s*|\n', re.sub(r'[{][^}]*[}]', '', envlist.strip())) <NEW_LINE> if m: <NEW_LINE> <INDENT> sep = m.group() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sep = ',' <NEW_LINE> <DEDENT> trailing_comma = envli...
Update an environment list. Makes sure all Python versions from ``new_versions`` are in the list. Removes all Python versions not in ``new_versions``. Leaves other environments (e.g. flake8, docs) alone. Tries to preserve formatting and braced groups.
625941c466656f66f7cbc180
def test_list_storagepool_tiers(self): <NEW_LINE> <INDENT> pass
Test case for list_storagepool_tiers
625941c4ff9c53063f47c1ca
def test_anonymous_can_not_view_protected(self): <NEW_LINE> <INDENT> user = AnonymousUser() <NEW_LINE> project = ProjectFactory(pub_state='protected') <NEW_LINE> self.assertFalse(user.has_perm('projects.view_project', project))
Tests anonymous can not view protected
625941c4a8ecb033257d30a3
def numMatchingSubseq(self, S, words): <NEW_LINE> <INDENT> def isMatch(S, words): <NEW_LINE> <INDENT> nextStartIndex = 0 <NEW_LINE> for c in words: <NEW_LINE> <INDENT> nextStartIndex = S.find(c, nextStartIndex) + 1 <NEW_LINE> if nextStartIndex == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return T...
:type S: str :type words: List[str] :rtype: int
625941c4bde94217f3682dc8
def exception(self, msg, *args, **kwargs): <NEW_LINE> <INDENT> kwargs['exc_info'] = 1 <NEW_LINE> self.error(msg, *args, **kwargs)
Exception level
625941c4167d2b6e31218b6c
def get_random_chart(group): <NEW_LINE> <INDENT> return choice(list(group['charts']))
Get a random chart from a specific chart sub-group. Args: group (dict): A group from the global chart settings config.
625941c44f88993c3716c03e
def update_inventory(self, inventory, generation): <NEW_LINE> <INDENT> self._update_generation(generation) <NEW_LINE> if self.has_inventory_changed(inventory): <NEW_LINE> <INDENT> self.inventory = copy.deepcopy(inventory) <NEW_LINE> return True <NEW_LINE> <DEDENT> return False
Update the stored inventory for the provider along with a resource provider generation to set the provider to. The method returns whether the inventory has changed.
625941c4796e427e537b059a
def update(self): <NEW_LINE> <INDENT> self.readStates()
Runs to update the state of the GPIO inputs
625941c43617ad0b5ed67ecf
def get_plan_quality(plan_code): <NEW_LINE> <INDENT> if plan_code[-2:] == "_2": <NEW_LINE> <INDENT> quality = "Moyenne" <NEW_LINE> <DEDENT> elif plan_code[-2:] == "_3": <NEW_LINE> <INDENT> quality = "Haute" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> quality = "Normale" <NEW_LINE> <DEDENT> return quality
Define the quality of plan in function of its code. Args: plan_code (str): The plan's code like "bcmaea15_3". Return: quality (str): The plan's quality.
625941c4be7bc26dc91cd5d8
def decoupage_bbox_cadastre_size(bbox, max_size, pixels_ratio): <NEW_LINE> <INDENT> xmin,ymin,xmax,ymax = bbox <NEW_LINE> assert(xmin < xmax) <NEW_LINE> assert(ymin < ymax) <NEW_LINE> xmin = xmin - 10 <NEW_LINE> xmax = xmax + 10 <NEW_LINE> ymin = ymin - 10 <NEW_LINE> ymax = ymax + 10 <NEW_LINE> nb_x = int((xmax - xmin ...
Génère un découpage de la bbox en m*n sous bbox, de taille maximale (max_size, max_size) Retourne des tuples ( (i,j), sous_bbox, (largeur_px,hauteur_px) ) correspondant à la sous bbox d'indice i,j dans le découpage m*n. Cette sous bbox ayant une taille en pixels size*pixels_ratio
625941c457b8e32f5248346f
def neighbors(self, node) -> list: <NEW_LINE> <INDENT> return list(self.graph_data[node])
Return all nodes that are directly accessible from given node.
625941c4dc8b845886cb550a
def __init__(self, graph: DirectedGraphWeighted, starting_vertex: str) -> None: <NEW_LINE> <INDENT> self._edge_to = {} <NEW_LINE> self._distance_to = {} <NEW_LINE> self._visited = set() <NEW_LINE> self._pq = PriorityQueue() <NEW_LINE> self._starting_vertex = starting_vertex <NEW_LINE> for vertex in graph.vertices(): <N...
Initializes the algorithm.
625941c4ac7a0e7691ed40a5
def __init__(self): <NEW_LINE> <INDENT> self.stack = {}
initialize your data structure here.
625941c40a366e3fb873e7ee
def _batch_norm(name,inputs, is_training): <NEW_LINE> <INDENT> with tf.variable_scope(name): <NEW_LINE> <INDENT> return tf.contrib.layers.batch_norm(inputs, decay=0.9, scale=True, updates_collections=None, is_training=is_training)
Batch Normalization
625941c4283ffb24f3c558d9
def ucs(problem): <NEW_LINE> <INDENT> closed = set() <NEW_LINE> fringe = data_structures.PriorityQueue() <NEW_LINE> state = problem.start_state() <NEW_LINE> root = data_structures.Node(state, None, None) <NEW_LINE> fringe.push(root, 0) <NEW_LINE> while not fringe.is_empty(): <NEW_LINE> <INDENT> node = fringe.pop() <NEW...
Uniform cost first graph search algorithm :param problem (a Problem object) representing the quest see Problem class definition in spartanquest.py) :return: list of actions representing the solution to the quest
625941c438b623060ff0adc4
def embed_selected_hdas(kwargs): <NEW_LINE> <INDENT> defs = set() <NEW_LINE> for s in hou.selectedNodes(): <NEW_LINE> <INDENT> d = s.type().definition() <NEW_LINE> if d and d.libraryFilePath()!="Embedded": <NEW_LINE> <INDENT> defs.add(d) <NEW_LINE> <DEDENT> <DEDENT> defs = list(defs) <NEW_LINE> if len(defs)==0: <NEW_LI...
Embed HDA definitions of selected nodes (interactive only).
625941c40a366e3fb873e7ef
def rot_dist(q1,q2=None): <NEW_LINE> <INDENT> q1_w_neg = torch.stack((q1,-q1),dim=-2) <NEW_LINE> if q2 is not None: q2 = q2[...,None,:] <NEW_LINE> dists = 2*quat_dist(q1_w_neg,q2) <NEW_LINE> dist_min = dists.min(-1)[0] <NEW_LINE> return dist_min
Get dist between two rotations, with q <-> -q symmetry
625941c44f6381625f114a11
def process_toi(source_info, options, debug): <NEW_LINE> <INDENT> tags = source_info.get('tags') <NEW_LINE> name = source_info.get('name') <NEW_LINE> category = "" <NEW_LINE> html = "" <NEW_LINE> if options.rss_local: <NEW_LINE> <INDENT> html_source = options.rss_local + "/" + name + ".html" <NEW_LINE> <DEDENT> else: <...
we fetch the source and then use regex to extract the URLs and IDs we want :param source_info: Information about the furl source (RSS feed in this case) :param options: Any options passed in :param debug: If true, print additional debugging info :return: A list of items extracted from the html, that can be further pro...
625941c4d486a94d0b98e11b
def p_compount_stmt(p): <NEW_LINE> <INDENT> pass
compount_stmt : LLAVEIZQ local_declarations statement_list LLAVEDER | LLAVEIZQ local_declarations statement_list LLAVEDER WHILE PARENIZQUIERDA expression PARENDERECHA PUNTOYCOMA
625941c4b830903b967e98e3
def fromFile(filename, encoding='utf-8-sig'): <NEW_LINE> <INDENT> filename = pathToString(filename) <NEW_LINE> if filename.endswith('.psydat'): <NEW_LINE> <INDENT> with open(filename, 'rb') as f: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> contents = pickle.load(f) <NEW_LINE> <DEDENT> except UnicodeDecodeError: <NEW_L...
Load data from a pickle or JSON file. Parameters ---------- encoding : str The encoding to use when reading a JSON file. This parameter will be ignored for any other file type.
625941c42c8b7c6e89b35798
def get_energy(self, word1, word2): <NEW_LINE> <INDENT> energy = 0.0 <NEW_LINE> word1_id = None <NEW_LINE> try: <NEW_LINE> <INDENT> word1_id = self._get_voc().word2id(word1) <NEW_LINE> <DEDENT> except KeyError as e: <NEW_LINE> <INDENT> logging.debug("{} not in W2G vocab. Defaulting to 0.0 energy".format(word1)) <NEW_LI...
Get the cosine similarity between vectors corresponding to word1 and word2. Note that energy is only calcuable if both word1 and word2 are valid ngrams in the vocabulary. If not, an engergy of 0.0 is returned :param word1: the first word to compare :type word1: str :param word2: the second word to compare :type word2...
625941c473bcbd0ca4b2c04c
def set_provider_urls(self, index_url): <NEW_LINE> <INDENT> url_obj = urlparse(index_url) <NEW_LINE> index_file = url_obj.path.split("/")[-1] <NEW_LINE> schedule_path = "/".join(url_obj.path.split("/")[:-1]) + "/sched" <NEW_LINE> schedule_file = index_file.replace("-main", "") <NEW_LINE> self.schedule_file = schedule_f...
Set our URLs so we can reference them later.
625941c456b00c62f0f1462f
def _create_imageset(records, format_class, format_kwargs=None): <NEW_LINE> <INDENT> records = list(records) <NEW_LINE> assert all(x.template is None for x in records) <NEW_LINE> filenames = [os.path.abspath(x.filename) for x in records] <NEW_LINE> imageset = dxtbx.imageset.ImageSetFactory.make_imageset( filenames, for...
Create an ImageSet object from a set of single-image records. Args: records: Single-image metadata records to merge into a single imageset format_class: The format class object for these image records format_kwargs: Extra arguments to pass to the format class when creating an ImageSet Returns: ...
625941c4711fe17d82542345
def update(self): <NEW_LINE> <INDENT> oschdir(self.options.conf['base_directory']) <NEW_LINE> self.nextep.update(self.options.dict_bug, self.options.conf['login'], self.options.conf['password']) <NEW_LINE> self.centralWidget.playing.update(self.options.conf['player']) <NEW_LINE> if(self.nextep.connectSucc...
update tab
625941c43eb6a72ae02ec4af
def promote(self): <NEW_LINE> <INDENT> info=self.getNextInfo() <NEW_LINE> if not info: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> ww=info['prestige'] <NEW_LINE> nowww=self.owner.finance.getPrestige() <NEW_LINE> if nowww>=ww: <NEW_LINE> <INDENT> self.owner.finance.updatePrestige(nowww-ww) <NEW_LINE> self._leve...
升级爵位 return bool
625941c44f88993c3716c03f
def deq_picker(self, j="", p={}): <NEW_LINE> <INDENT> if self.json_invalid(j): <NEW_LINE> <INDENT> return p <NEW_LINE> <DEDENT> j = json.loads(j) <NEW_LINE> for i in self.kds_deq_pickl: <NEW_LINE> <INDENT> if i in j[self.kds_model]: <NEW_LINE> <INDENT> p[i] = j[self.kds_model][i] <NEW_LINE> <DEDENT> else: <NEW_LINE> <I...
deq(json)から各種情報のスクレイピング処理 アクセス数: 0回 j: json-string, p: return-dictionary,
625941c4091ae35668666f37
def __init__( self, obj: Union[Nodes, AbstractConnection], state_vars: Iterable[str], time: Optional[int] = None, batch_size: int = 1, ): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.obj = obj <NEW_LINE> self.state_vars = state_vars <NEW_LINE> self.time = time <NEW_LINE> self.batch_size = batch_size <NEW_LINE...
Constructs a ``Monitor`` object. :param obj: An object to record state variables from during network simulation. :param state_vars: Iterable of strings indicating names of state variables to record. :param time: If not ``None``, pre-allocate memory for state variable recording.
625941c45fcc89381b1e1694
def clean_name(self, name, clan=False): <NEW_LINE> <INDENT> clean = self.clean_text(name) <NEW_LINE> split = clean.split() <NEW_LINE> if not clan and len(split) > 1: <NEW_LINE> <INDENT> return split[1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return clean
Removes color tags from names. Removes clantags by default. Args: name (str): The name to clean. clan (bool): Whether to keep or remove clantags if present.
625941c456ac1b37e62641a9
def get_dbus( bus_type, obj, path, interface, method, arg): <NEW_LINE> <INDENT> if bus_type == "session": <NEW_LINE> <INDENT> bus = dbus.SessionBus() <NEW_LINE> <DEDENT> if bus_type == "system": <NEW_LINE> <INDENT> bus = dbus.SystemBus() <NEW_LINE> <DEDENT> proxy = bus.get_object(obj, path) <NEW_LINE> method = proxy.ge...
utility: executes dbus method on specific interface
625941c4b7558d58953c4eee
def ammortization_rate(K_0,r,n): <NEW_LINE> <INDENT> if r ==0.0: <NEW_LINE> <INDENT> R=K_0/n <NEW_LINE> return R <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> R_values = 0 <NEW_LINE> R = K_0 * (r/(1-(1+r) ** -n)) <NEW_LINE> i = 0 <NEW_LINE> while (K_0 > 0): <NEW_LINE> <INDENT> i = i + 1 <NEW_LINE> H = K_0 * r <NEW_LINE...
This functions determines an ammortization rate such that the loan is payed back after exactly n years. print("test")
625941c4ab23a570cc250157
def plot_latitude_guide(self, latitude): <NEW_LINE> <INDENT> assert -pi/2 <= latitude <= pi/2, latitude <NEW_LINE> small_circle = Rotation(Line(0, 0), Line(0, pi/2 - latitude)) <NEW_LINE> self.plot_rotation(small_circle, state=tk.DISABLED)
Show a small circle at the specified -pi/2 <= latitude <= pi/2.
625941c43539df3088e2e321
def rule_bill(): <NEW_LINE> <INDENT> return [[-2,5],[-5,2]]
Return the CNF form of BILL THE LIZARD's statement
625941c4f548e778e58cd553
def get_logger(self, loglevel=None, verbose=False, logfile=None): <NEW_LINE> <INDENT> loglevels = {'debug': 10, 'info': 20, 'warning': 30, 'error': 40, 'critical': 50} <NEW_LINE> if not loglevel: <NEW_LINE> <INDENT> loglevel = loglevels[self.config.LOGLEVEL] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> loglevel = logl...
Returns a logger object with the current settings in config.py. If the -q (quiet) flag is set, it doesn't log to console. If the -v (verbose) flag is set, it increases logging verbosity by one step.
625941c4d10714528d5ffcb7
def decode(self, s): <NEW_LINE> <INDENT> s = s.split('\\n') <NEW_LINE> return [s[i].replace('\\\\', '\\') for i in xrange(len(s)-1)]
Decodes a single string to a list of strings. :type s: str :rtype: List[str]
625941c4293b9510aa2c326e
def prefix(tokens, prefix, sep=False): <NEW_LINE> <INDENT> if not tokens: <NEW_LINE> <INDENT> raise ValueError('lista de tokens vazia') <NEW_LINE> <DEDENT> start = tokens[0].start <NEW_LINE> diff = delta(0, tkhdelta(prefix)) <NEW_LINE> prefix = tkcopy(prefix, start=start, end=start + diff) <NEW_LINE> prefix = tkcopy(pr...
Adiciona token prefix antes da lista de tokens e ajusta alinhamento horizontal
625941c429b78933be1e5685
@app.route('/<int:category_id>/items/<int:item_id>/edit/', methods=['GET', 'POST']) <NEW_LINE> def editItem(category_id, item_id): <NEW_LINE> <INDENT> session = DBSession() <NEW_LINE> category = session.query(Categories).filter_by(id=category_id).one() <NEW_LINE> categories = session.query(Categories).order_by(asc(Cate...
Connects to the DB, queries the categories, items and checks if a user is logged in and it is the same user who created the item. Function redirects the users if they aren't the creators of the item. It provides the html template on GET request and stores data into the DB on POST request. Authorization check is also ma...
625941c48a43f66fc4b5403d
def __del__(self): <NEW_LINE> <INDENT> print("Bye rectangle...") <NEW_LINE> Rectangle.number_of_instances -= 1
Message gets printed when a Rectangle instance is deleted
625941c4fbf16365ca6f6197
def is_localhost(self, host=None): <NEW_LINE> <INDENT> if host is None: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if host in self._h2l: <NEW_LINE> <INDENT> return self._h2l[host] <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> (hostname, aliaslist, iplist) = socket.gethostbyname_ex(host) <NEW_LINE> <DEDENT> exce...
:param host: Hostname of machine :type host: str or None :returns: true if specified host (by name) is the localhost all aliases matching the hostname are searched
625941c47d847024c06be290
def test_001c_carrier_offset_cp (self): <NEW_LINE> <INDENT> fft_len = 8 <NEW_LINE> cp_len = 2 <NEW_LINE> n_syms = 3 <NEW_LINE> occupied_carriers = ((-2, -1, 1, 2),) <NEW_LINE> carr_offset = -1 <NEW_LINE> tx_data = ( 0,-1j,-1j, 0,-1j,-1j, 0, 0, 0, -1, -1, 0, -1, -1, 0, 0, 0, 1j, 1j, 0, 1j, 1j, 0, 0, ) <NEW_LINE> rx_expe...
Same as before, but put a carrier offset in there and a CP
625941c4379a373c97cfab1b
def _get_report_link(self): <NEW_LINE> <INDENT> script_xpath = '//*[@id="divsinglecolumnminwidth"]/script' <NEW_LINE> scripts = self.pjs.find_elements(script_xpath) <NEW_LINE> for script in scripts: <NEW_LINE> <INDENT> src = script.get_attribute('outerHTML') <NEW_LINE> if 'function downloadReport(reportID)' not in src:...
we want to find the script that contains the above regex it'll be in a script that has the downloadReport fn
625941c4a219f33f34628942
def _key_index_split(self, indexed_key: str) -> list: <NEW_LINE> <INDENT> return re.split(r'\[([0-9]+)\]', indexed_key)
Split index from key
625941c4435de62698dfdc23
def test_module(): <NEW_LINE> <INDENT> @hug.get() <NEW_LINE> def module_tester(hug_module): <NEW_LINE> <INDENT> return hug_module.__name__ <NEW_LINE> <DEDENT> assert hug.test.get(api, 'module_tester').data == api.__name__
Test to ensure the module directive automatically includes the current API's module
625941c450485f2cf553cd70
def extract_variables(self, x, var_offsets, interface): <NEW_LINE> <INDENT> local_x = interface.zeros(*self.x_size) <NEW_LINE> offset = 0 <NEW_LINE> for var in self.variables(): <NEW_LINE> <INDENT> var_size = var.size[0]*var.size[1] <NEW_LINE> value = x[var_offsets[var.data]:var_offsets[var.data]+var_size] <NEW_LINE> i...
Extract the function variables from the vector x of all variables.
625941c45fdd1c0f98dc0209
def split_and_apply_template_on_each(field, old_field_value, template, mapper, separator=","): <NEW_LINE> <INDENT> bits = old_field_value.split(separator) <NEW_LINE> translated_bits = [mapper.get(x.strip(), x.strip()) for x in bits] <NEW_LINE> new_value = ', '.join(["{{%s|%s}}" % (template, x) for x in translated_bits]...
Split the old value against the given separator and apply the template on each part
625941c499cbb53fe6792bbd