code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def _init_dense_smoother(self): <NEW_LINE> <INDENT> mat = operators.op2mat( self._g_op_unobs, np.sum(self.mask_unobs), np.float64) <NEW_LINE> pinv_mat = np.linalg.pinv(mat) <NEW_LINE> def smoother(imap): <NEW_LINE> <INDENT> omap = np.zeros(imap.shape, imap.dtype) <NEW_LINE> omap[self.mask_unobs] = np.dot(pinv_mat, imap[self.mask_unobs]) <NEW_LINE> return omap <NEW_LINE> <DEDENT> return smoother, pinv_mat
Initialize the exact solver by computing the (pseudo) inverse of the G matrix. Should be used the most coarse level. Returns ------- smoother : callable Function that takes and returns (npol, npix) map.
625941c1462c4b4f79d1d653
def save_from_dict(self, configuration): <NEW_LINE> <INDENT> import json <NEW_LINE> with open(self.location, "w", encoding="utf-8") as data_file: <NEW_LINE> <INDENT> json.dump( dict(configuration), data_file, sort_keys=True, indent=4, separators=(",", ": "), )
Saving the configuration again.
625941c18c0ade5d55d3e93b
def __init__(self, qubit, circ=None): <NEW_LINE> <INDENT> super().__init__("y", [], [qubit], circ)
Create new Y gate.
625941c1d4950a0f3b08c2d3
def testWriteHeader(self): <NEW_LINE> <INDENT> expected_header = b'{' <NEW_LINE> self._output_module.WriteHeader() <NEW_LINE> header = self._output_writer.ReadOutput() <NEW_LINE> self.assertEqual(header, expected_header)
Tests the WriteHeader function.
625941c12eb69b55b151c82f
def find1d(a,b): <NEW_LINE> <INDENT> try : <NEW_LINE> <INDENT> da = np.array(a) <NEW_LINE> goal = b <NEW_LINE> ix = da == goal <NEW_LINE> iy = ix.tolist() <NEW_LINE> x = iy.index(True) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> print('can not find element!') <NEW_LINE> x = 'Error!' <NEW_LINE> <DEDENT> return x
This function is try to find an element in an array parameter: ---------- a : the array use to find an element b : the element need to find return: ------- the index of the element in the given array PS:if there are more than one element equal to b,the return value will be the first one
625941c1f548e778e58cd4ff
def showOccl(self, occl, img): <NEW_LINE> <INDENT> img = self.getImgs(img)[0] <NEW_LINE> fig,ax = plt.subplots(1) <NEW_LINE> if img is not None and not self.waiting: <NEW_LINE> <INDENT> self.showImg(img, wait=True, ax=ax) <NEW_LINE> <DEDENT> bounds = np.zeros(occl['imsize']) <NEW_LINE> for i in range(occl['ne']): <NEW_LINE> <INDENT> pixel_indices = occl['edges']['indices'][i] <NEW_LINE> num_pixels = len(pixel_indices) <NEW_LINE> pixel_coords = np.unravel_index(pixel_indices, occl['imsize'], order='F') <NEW_LINE> edgelabel = occl['edges']['edgelabel'][i] <NEW_LINE> bounds[pixel_coords] = 1 <NEW_LINE> for j in range(num_pixels - OCCLUSION_ARROW_DISTANCE): <NEW_LINE> <INDENT> if j % OCCLUSION_ARROW_DISTANCE == 0: <NEW_LINE> <INDENT> a = [pixel_coords[0][j] , pixel_coords[1][j]] <NEW_LINE> b = [pixel_coords[0][j+OCCLUSION_ARROW_DISTANCE], pixel_coords[1][j+OCCLUSION_ARROW_DISTANCE] ] <NEW_LINE> mid = (np.array(a) + np.array(b)) / 2 <NEW_LINE> d0 = b[0] - a[0] <NEW_LINE> d1 = b[1] - a[1] <NEW_LINE> if edgelabel != 1: <NEW_LINE> <INDENT> d0 *= -1 <NEW_LINE> d1 *= -1 <NEW_LINE> <DEDENT> norm = np.sqrt(d0 * d0 + d1 * d1) <NEW_LINE> d0 /= norm <NEW_LINE> d1 /= norm <NEW_LINE> ax.add_patch(FancyArrow(mid[1], mid[0], d0, -d1, width=0.0, head_width=2.5, head_length = 5.0, facecolor='white', edgecolor='none')) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.showMask(bounds, img)
Show occlusion data
625941c1091ae35668666ee5
def __getitem__(self, index): <NEW_LINE> <INDENT> row = self._target_df.iloc[index] <NEW_LINE> english_sentence, french_sentence = row[ENGLISH], row[FRENCH] <NEW_LINE> return self.vectorizer.vectorize(english_sentence, french_sentence)
Retrieve a single record from the target dataset.
625941c192d797404e30410c
def test_parsetyperegistry_should_assign_pattern_to_func_during_register(): <NEW_LINE> <INDENT> registry = ParseTypeRegistry() <NEW_LINE> custom_parse_type_func = lambda x: x <NEW_LINE> registry.register("name", custom_parse_type_func, "pattern") <NEW_LINE> assert custom_parse_type_func.pattern == "pattern"
The ParseTypeRegistry should assign the Custom Type Parse pattern to the function which is registered as type handler.
625941c1d8ef3951e32434c0
def setup(self, folder): <NEW_LINE> <INDENT> tempimages = glob.glob("resources/animations/" + folder + "/frame*.png") <NEW_LINE> tempimages.sort() <NEW_LINE> for i in range(len(tempimages)): <NEW_LINE> <INDENT> self.frames.append(pygame.image.load(tempimages[i])) <NEW_LINE> <DEDENT> self.maxframe = len(self.frames) - 1
Goes in the given folder and takes all the framse in order to visualise them later.
625941c121a7993f00bc7c6f
def plot_data(data_list, plot_id, plot_title=''): <NEW_LINE> <INDENT> fig = plt.figure(figsize=(8, 3)) <NEW_LINE> n, bins, patches = plt.hist(data_list, alpha=0.3) <NEW_LINE> x_axis = [] <NEW_LINE> for i in range(len(bins[:-1])): <NEW_LINE> <INDENT> x_axis.append((bins[i] + bins[i + 1]) / 2) <NEW_LINE> <DEDENT> error = np.std(data_list) <NEW_LINE> plt.errorbar(x_axis, n, yerr=error, fmt='o') <NEW_LINE> plt.plot(x_axis, n, linewidth=1, marker='4') <NEW_LINE> os.mkdir('Plots') if not os.path.exists('Plots') else None <NEW_LINE> if plot_title != '': <NEW_LINE> <INDENT> plt.title(plot_title) <NEW_LINE> plot_filename = (f"Plots/{plot_title.replace(' ', '_')}.png") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> plt.title(f"{plot_id} instrumentos - Distribuicao dos EC's ({len(data_list)} amostras)") <NEW_LINE> plot_filename = (f"Plots/{plot_id}_Insts_EC.png") <NEW_LINE> <DEDENT> plt.ylabel(f'# de ocorrencias (Desv. Pad.: {round(error, 2)})') <NEW_LINE> plt.xlabel("Valores Normalizados do Equilibrio de Coincidencias (EC)") <NEW_LINE> plt.grid() <NEW_LINE> plt.xlim(-1.0, 1.0) <NEW_LINE> plt.savefig(plot_filename, bbox_inches='tight', dpi=200)
Plots a histogram of the provided data. :param data_list: list of values to be plotted :param plot_id: in this case, the number of instruments that this plot corresponds to :param plot_title: a title, if the standard format one isnt suitable
625941c14e4d5625662d435d
def postcmd(self, stop, line): <NEW_LINE> <INDENT> return stop
Called after a command dispatch is finished. This command should return stop. onecmd() will return the return value here. Args: stop (bool): A flag indicating if execution will be terminated. Should be the return value of the method. If the method returns a false value, cmdloop will continue. line (str): The command that was interpreted.
625941c18e7ae83300e4af4f
def c(): <NEW_LINE> <INDENT> return 1
*** YOUR CODE HERE ***
625941c194891a1f4081ba2b
def _process_opcode_2(self, index: int) -> None: <NEW_LINE> <INDENT> params_number = 3 <NEW_LINE> params = self._get_params(index, params_number) <NEW_LINE> value_to_write = params[0] * params[1] <NEW_LINE> third_param_mode = str(self.opcodes[index])[:-4] <NEW_LINE> if third_param_mode == "2": <NEW_LINE> <INDENT> result_index = self.relative_base + self.opcodes[index + params_number] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result_index = self.opcodes[index + params_number] <NEW_LINE> <DEDENT> self.opcodes[result_index] = value_to_write <NEW_LINE> self.advance_pointer = params_number <NEW_LINE> return
Multiply two numbers and write the result to a specified position. The numbers to multiply are specified by the first two params. The third param specifies the position to write the result.
625941c1283ffb24f3c55886
def reshape_data(ary:list): <NEW_LINE> <INDENT> print(ary) <NEW_LINE> refined_data = [] <NEW_LINE> for i in range(len(ary[0])): <NEW_LINE> <INDENT> prices_at_given_time = [] <NEW_LINE> for j in range(len(ary)): <NEW_LINE> <INDENT> prices_at_given_time.append(ary[j][i]) <NEW_LINE> print("j = %s"%j) <NEW_LINE> <DEDENT> refined_data.append(prices_at_given_time) <NEW_LINE> <DEDENT> return refined_data
reshapes array and converts dataframe into 2 dimensional array :param ary: :return reshaped array:
625941c11d351010ab855a9f
def gen_uuid(self): <NEW_LINE> <INDENT> return str(uuid.uuid4())
Generates UUID value which can be useful where some unique value is required.
625941c18c0ade5d55d3e93c
def update(self, id_or_url, **kwargs): <NEW_LINE> <INDENT> url = self.url(id_or_url) <NEW_LINE> with wrap_exceptions: <NEW_LINE> <INDENT> response = self.client.put(url, data=kwargs) <NEW_LINE> response.raise_for_status()
Update an existing trigger. :param id_or_url: The ID of the :class:`.Trigger` to update or its URL :param kwargs: The fields to be updated
625941c1ab23a570cc250104
def extract_data(self, profile: Profile): <NEW_LINE> <INDENT> info = ( profile.username, profile.mediacount, profile.followers, profile.followees, int(profile.is_private), int("@" in str(profile.biography.encode("utf-8"))), int(profile.external_url is not None), int(profile.is_verified), ) <NEW_LINE> return info
Helper method to extract the data from the given profile Args: profile (Profile): The given profile to extract data from Returns: tuple: A tuple of the processed info from the profile
625941c156ac1b37e6264156
@ensure_csrf_cookie <NEW_LINE> @cache_control(no_cache=True, no_store=True, must_revalidate=True) <NEW_LINE> @require_level('staff') <NEW_LINE> def get_coupon_codes(request, course_id): <NEW_LINE> <INDENT> course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id) <NEW_LINE> coupons = Coupon.objects.filter(course_id=course_id) <NEW_LINE> query_features = [ 'code', 'course_id', 'percentage_discount', 'code_redeemed_count', 'description', 'expiration_date', 'is_active' ] <NEW_LINE> coupons_list = instructor_analytics.basic.coupon_codes_features(query_features, coupons) <NEW_LINE> header, data_rows = instructor_analytics.csvs.format_dictlist(coupons_list, query_features) <NEW_LINE> return instructor_analytics.csvs.create_csv_response('Coupons.csv', header, data_rows)
Respond with csv which contains a summary of all Active Coupons.
625941c132920d7e50b28151
@app.route('/api/record', endpoint="record_api") <NEW_LINE> def get_record() -> Response: <NEW_LINE> <INDENT> issue = arg_issues(request.args) <NEW_LINE> if issue: <NEW_LINE> <INDENT> issue_text, recommended_status_code = issue <NEW_LINE> app.logger.debug(issue_text) <NEW_LINE> return Response(issue_text, status=recommended_status_code) <NEW_LINE> <DEDENT> config.get_config(app) <NEW_LINE> domain = app.config.get('API_DOMAIN') <NEW_LINE> if domain is None: <NEW_LINE> <INDENT> return Response("Missing domain", status=500) <NEW_LINE> <DEDENT> api_key = app.config.get('API_KEY') <NEW_LINE> if api_key is None: <NEW_LINE> <INDENT> return Response("Missing api key", status=500) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> record_lookup_strategy = RecordGetter(request.args) <NEW_LINE> identifier = record_lookup_strategy.get_identifier(request.args) <NEW_LINE> metadata_record = record_lookup_strategy.get_record( server=getmarc2.records.RecordServer(domain, api_key), identifier=identifier ) <NEW_LINE> header = {"x-api-version": "v1"} <NEW_LINE> app.logger.info(f"Retrieved record for {identifier}") <NEW_LINE> if 'bib_id' in request.args: <NEW_LINE> <INDENT> field_adder = modifiers.Add955() <NEW_LINE> bibid = request.args["bib_id"] <NEW_LINE> field_adder.bib_id = bibid <NEW_LINE> if "v" in bibid: <NEW_LINE> <INDENT> field_adder.contains_v = True <NEW_LINE> <DEDENT> metadata_record = field_adder.enrich(metadata_record) <NEW_LINE> <DEDENT> return Response( metadata_record, headers=header, content_type="application/xml;charset=UTF-8" ) <NEW_LINE> <DEDENT> except AttributeError as error: <NEW_LINE> <INDENT> app.logger.info("Failed to retrieve record") <NEW_LINE> return Response(f"Failed. {error}", 400, content_type="text")
Get the record data for a given bibid. Returns: XML data
625941c199cbb53fe6792b6a
def __bytes__(self): <NEW_LINE> <INDENT> pass
Return bytes representation.
625941c110dbd63aa1bd2b27
def load_interior(self, level, obj_data, extras=None): <NEW_LINE> <INDENT> if extras is None: <NEW_LINE> <INDENT> extras = {} <NEW_LINE> <DEDENT> self.interior = Level3D() <NEW_LINE> self.interior.spaceship = self <NEW_LINE> self.interior.load_converted_char_map(level, obj_data, extras)
Load ship interior.
625941c1dc8b845886cb54b7
def velocity_to_restframe_frequency(self, velax=None, vlsr=0.0): <NEW_LINE> <INDENT> velax = self.velax if velax is None else np.squeeze(velax) <NEW_LINE> return self.nu * (1. - (velax - vlsr) / 2.998e8)
Return the rest-frame frequency [Hz] of the given velocity [m/s].
625941c1287bf620b61d39e8
def test_cannot_delete_an_unavilable_comment(self): <NEW_LINE> <INDENT> article = create_article() <NEW_LINE> url = reverse("articles:comment", kwargs={'article_slug':article.slug, "comment_pk":3}) <NEW_LINE> response = self.client.delete(url) <NEW_LINE> self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
Should not be able to post a comment on an comment that does not exist.
625941c1cc40096d615958d4
def symlink_create_win(creator_name: str, src_dir: str, mods_dir: str, mod_name: str = "Untitled") -> None: <NEW_LINE> <INDENT> scripts_path = get_scripts_path(creator_name, mods_dir, mod_name) <NEW_LINE> mod_folder_path = str(Path(scripts_path).parent) <NEW_LINE> symlink_remove_win(creator_name, mods_dir, mod_name) <NEW_LINE> ensure_path_created(mod_folder_path) <NEW_LINE> exec_cmd("mklink", '/J ' + '"' + scripts_path + '" ' '"' + src_dir + '"') <NEW_LINE> print("") <NEW_LINE> print("Dev Mode is activated, you no longer have to compile after each change, run devmode.reload [path.of.module]") <NEW_LINE> print("to reload individual files while the game is running. To exit dev mode, simply run 'compile.py' which will") <NEW_LINE> print("return things to normal.") <NEW_LINE> print("It's recomended to test a compiled version before final release after working in Dev Mode") <NEW_LINE> print("")
Creates a symlink, it first wipes out the mod that may be there. When entering devmode, you don't compile anymore, so any compiled code needs to be removed. :param creator_name: Creator Name :param src_dir: Path to the source folder in this project :param mods_dir: Path to the Mods Folder :param mod_name: Name of Mod :return: Nothing
625941c1c4546d3d9de729b5
def convertFile(self, input = None, output = None, encoding = None): <NEW_LINE> <INDENT> encoding = encoding or "utf-8" <NEW_LINE> input_file = codecs.open(input, mode="r", encoding=encoding) <NEW_LINE> text = input_file.read() <NEW_LINE> input_file.close() <NEW_LINE> text = text.lstrip(u'\ufeff') <NEW_LINE> html = self.convert(text) <NEW_LINE> if type(output) == type("string"): <NEW_LINE> <INDENT> output_file = codecs.open(output, "w", encoding=encoding) <NEW_LINE> output_file.write(html) <NEW_LINE> output_file.close() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> output.write(html.encode(encoding))
Converts a markdown file and returns the HTML as a unicode string. Decodes the file using the provided encoding (defaults to utf-8), passes the file content to markdown, and outputs the html to either the provided stream or the file with provided name, using the same encoding as the source file. **Note:** This is the only place that decoding and encoding of unicode takes place in Python-Markdown. (All other code is unicode-in / unicode-out.) Keyword arguments: * input: Name of source text file. * output: Name of output file. Writes to stdout if `None`. * extensions: A list of extension names (may contain config args). * encoding: Encoding of input and output files. Defaults to utf-8. * safe_mode: Disallow raw html. One of "remove", "replace" or "escape".
625941c150812a4eaa59c2a7
def upload(branch, user, tool, data): <NEW_LINE> <INDENT> with ProgressBar(_("Uploading")): <NEW_LINE> <INDENT> commit_message = _("automated commit by {}").format(tool) <NEW_LINE> data_str = " ".join(f"[{key}={val}]" for key, val in data.items()) <NEW_LINE> commit_message = f"{commit_message} {data_str}" <NEW_LINE> git = Git().set(Git.working_area) <NEW_LINE> run(git("commit -m {msg} --allow-empty", msg=commit_message)) <NEW_LINE> run_authenticated(user, git.set(Git.cache)("push origin {branch}", branch=branch)) <NEW_LINE> commit_hash = run(git("rev-parse HEAD")) <NEW_LINE> return user.name, commit_hash
Commit + push to a branch :param branch: git branch to commit and push to :type branch: str :param user: authenticated user who can push to the repo and branch :type user: lib50.User :param tool: name of the tool that started the push :type tool: str :param data: key value pairs that end up in the commit message. This can be used to communicate data with a backend. :type data: dict of strings :return: username and commit hash :type: tuple(str, str) Example usage:: from lib50 import authenticate, prepare, upload with authenticate("me50") as user: tool = "submit50" branch = "cs50/problems/2019/x/hello" with prepare(tool, branch, user, ["hello.c"]): upload(branch, user, tool, {tool:True})
625941c1ac7a0e7691ed4053
def missing_datetimes(self, task_cls, finite_datetimes): <NEW_LINE> <INDENT> return [d for d in finite_datetimes if not self._instantiate_task_cls(task_cls, self.datetime_to_parameter(d)).complete()]
Override in subclasses to do bulk checks. Returns a sorted list. This is a conservative base implementation that brutally checks completeness, instance by instance. Inadvisable as it may be slow.
625941c1d6c5a10208143fcc
def eval(self, k: int) -> np.ndarray: <NEW_LINE> <INDENT> if self._last_generated > k: <NEW_LINE> <INDENT> raise Exception("unable to generate value for time in the past") <NEW_LINE> <DEDENT> if self._last_generated == k: <NEW_LINE> <INDENT> return self._current_value <NEW_LINE> <DEDENT> self._last_generated = k <NEW_LINE> self._current_value += norm.rvs(size=self._current_value.shape, scale=self._delta * np.sqrt(self._dt)) <NEW_LINE> return self._current_value
Generate an instance of Brownian motion (i.e. the Wiener process): X(t) = X(0) + N(0, delta**2 * t; 0, t) where N(mu, sigma; t0, t1) is a normally distributed random variable with mean mu and variance sigma. The parameters t0 and t1 make explicit the statistical independence of N on different time intervals; that is, if [t0, t1) and [t2, t3) are disjoint intervals, then N(mu, sigma; t0, t1) and N(mu, sigma; t2, t3) are independent. Written as an iteration scheme, X(t + dt) = X(t) + N(0, delta**2 * dt; t, t+dt) If `x0`, i.e. shift, is an array (or array-like), each value in `x0` is treated as an initial condition, and the value returned is a numpy array with one more dimension than `x0`. :param k: float, the time step. :return: np array, array of generated process values.
625941c115fb5d323cde0a90
def test_inference_datum_string(self): <NEW_LINE> <INDENT> d1 = InferenceDatum(0.8, 0.05) <NEW_LINE> expected = dict(tpr=0.8, fpr=0.05) <NEW_LINE> result = json.loads(str(d1)) <NEW_LINE> self.assertEqual(expected, result, "string and back")
experiment datum can be stringified.
625941c17047854f462a138f
def GetCurrentCmd(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!')
获得当前正在执行的命令id,如果没有在执行的命令,则返回-1 命令id
625941c18da39b475bd64ef4
def getCorpusContentDirs(): <NEW_LINE> <INDENT> directoryName = getCorpusFilePath() <NEW_LINE> result = [] <NEW_LINE> excludedNames = ( 'license.txt', '_metadataCache', '__pycache__', ) <NEW_LINE> for filename in os.listdir(directoryName): <NEW_LINE> <INDENT> if filename.endswith(('.py', '.pyc')): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> elif filename.startswith('.'): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> elif filename in excludedNames: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> result.append(filename) <NEW_LINE> <DEDENT> return sorted(result)
Get all dirs that are found in the corpus that contain content; that is, exclude dirs that have code or other resources. >>> fp = common.getCorpusContentDirs() >>> fp # this test will be fragile, depending on composition of dirs ['airdsAirs', 'bach', 'beethoven', 'chopin', 'ciconia', 'corelli', 'cpebach', 'demos', 'essenFolksong', 'handel', 'haydn', 'josquin', 'leadSheet', 'luca', 'miscFolk', 'monteverdi', 'mozart', 'oneills1850', 'palestrina', 'ryansMammoth', 'schoenberg', 'schumann', 'schumann_clara', 'theoryExercises', 'trecento', 'verdi', 'weber'] Make sure that all corpus data has a directoryInformation tag in CoreCorpus. >>> cc = corpus.corpora.CoreCorpus() >>> failed = [] >>> di = [d.directoryName for d in cc.directoryInformation] >>> for f in fp: ... if f not in di: ... failed.append(f) >>> failed []
625941c17d847024c06be23d
@app.route('/1', methods=['GET', 'POST']) <NEW_LINE> @validate_json_type <NEW_LINE> def test1(): <NEW_LINE> <INDENT> a = validate_json_scheme("a", "b", "c", "d") <NEW_LINE> if a: <NEW_LINE> <INDENT> return jsonify("有参数缺失") <NEW_LINE> <DEDENT> return "ops"
:return:
625941c1925a0f43d2549df8
def set_filters(query, must_filter, base_filters=None): <NEW_LINE> <INDENT> filters = [f for f in base_filters if f is not None] <NEW_LINE> must_filters = [f for f in must_filter if f is not None] <NEW_LINE> query_filter = query['query'].get('filter', None) <NEW_LINE> if query_filter is not None: <NEW_LINE> <INDENT> filters = query_filter <NEW_LINE> <DEDENT> if 'bool' not in query['query'] and (must_filters or filters): <NEW_LINE> <INDENT> query['query']['bool'] = {} <NEW_LINE> <DEDENT> if must_filters: <NEW_LINE> <INDENT> query['query']['bool']['must'] = must_filters <NEW_LINE> <DEDENT> if filters: <NEW_LINE> <INDENT> query['query']['bool']['filter'] = filters
Put together must_filters and base_filters that are requested and set them as filter or accordingly. :param query: elastic query being constructed :param base_filters: all filters defined in the mapping already (elastic_filter_callback, elastic_filter) :param must_filters: all filters set inside the query (eg. resource config, sub_resource_lookup)
625941c1adb09d7d5db6c714
def _in_triangle(v, va, vb, vc): <NEW_LINE> <INDENT> return _on_same_side(v, va, vb, vc) and _on_same_side(v, vb, va, vc) and _on_same_side(v, vc, va, vb)
tell if v is inside a triangle define by va, vb and vc
625941c150485f2cf553cd1c
def run(plugins): <NEW_LINE> <INDENT> all_plugins = list_plugins() <NEW_LINE> if isinstance(plugins, str): <NEW_LINE> <INDENT> plugins = plugins.split(",") <NEW_LINE> <DEDENT> data = {} <NEW_LINE> for plugin in plugins: <NEW_LINE> <INDENT> if plugin not in all_plugins: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> data[plugin] = {} <NEW_LINE> muninout = __salt__["cmd.run"]( "munin-run {}".format(plugin), python_shell=False ) <NEW_LINE> for line in muninout.split("\n"): <NEW_LINE> <INDENT> if "value" in line: <NEW_LINE> <INDENT> key, val = line.split(" ") <NEW_LINE> key = key.split(".")[0] <NEW_LINE> try: <NEW_LINE> <INDENT> if "." in val: <NEW_LINE> <INDENT> val = float(val) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> val = int(val) <NEW_LINE> <DEDENT> data[plugin][key] = val <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return data
Run one or more named munin plugins CLI Example: .. code-block:: bash salt '*' munin.run uptime salt '*' munin.run uptime,cpu,load,memory
625941c16fece00bbac2d6c0
def __from_json__(self, jsondata, thunker): <NEW_LINE> <INDENT> self.run = jsondata["Run"] <NEW_LINE> self.eventsPerLumi = {} <NEW_LINE> for lumi, events in jsondata["Lumis"].iteritems(): <NEW_LINE> <INDENT> self.eventsPerLumi[int(lumi)] = events <NEW_LINE> <DEDENT> return self
__from_json__ Convert JSON data back into a Run object with integer lumi numbers
625941c160cbc95b062c64c6
def __str__(self): <NEW_LINE> <INDENT> string = "\n" <NEW_LINE> for t in self._typeNames: <NEW_LINE> <INDENT> string += "\t%s\n" % t <NEW_LINE> <DEDENT> return string
Print all available types.
625941c15fc7496912cc3901
@command.command(permission='view') <NEW_LINE> def cmd_view(bot, *args): <NEW_LINE> <INDENT> return 'Done'
Test command %%cmd_view
625941c10c0af96317bb816b
def __init__(self, rounds_to_cooperate=10): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._rounds_to_cooperate = rounds_to_cooperate
Parameters ---------- rounds_to_cooperate: int, 10 The number of rounds to cooperate initially
625941c1a8ecb033257d3051
def create_webapp(self, name, application_url, option_profile, excludes=None): <NEW_LINE> <INDENT> if excludes is None: <NEW_LINE> <INDENT> payload = { "ServiceRequest": { "data": { "WebApp": { "name": name, "url": application_url, "defaultProfile": {"id": int(option_profile)} } } } } <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> payload = { "ServiceRequest": { "data": { "WebApp": { "name": name, "url": application_url, "defaultProfile": {"id": int(option_profile)}, "urlBlacklist": {"set": {"UrlEntry": [ {"value": item, "regex": "true"} for item in excludes ]}}, "postDataBlacklist": {"set": {"UrlEntry": [ {"value": item, "regex": "true"} for item in excludes ]}} } } } } <NEW_LINE> <DEDENT> response = self._request( "/qps/rest/3.0/create/was/webapp", json=payload, validator=lambda r: r.ok and dot(r.json()).ServiceResponse.responseCode == "SUCCESS" ) <NEW_LINE> obj = dot(response.json()) <NEW_LINE> return obj.ServiceResponse.data[0].WebApp.id
Create WebApp record
625941c11f037a2d8b946182
def app_get(app_name_or_id, alias=None, input_params={}, always_retry=True, **kwargs): <NEW_LINE> <INDENT> fully_qualified_version = app_name_or_id + (('/' + alias) if alias else '') <NEW_LINE> return DXHTTPRequest('/%s/get' % fully_qualified_version, input_params, always_retry=always_retry, **kwargs)
Invokes the /app-xxxx/get API method. For more info, see: https://documentation.dnanexus.com/developer/api/running-analyses/apps#api-method-app-xxxx-yyyy-get
625941c130bbd722463cbd47
@login_required() <NEW_LINE> def notify_group(request): <NEW_LINE> <INDENT> group_notify = Notification.objects.filter(to_user=request.user, no_type='group', status='unread').order_by('-add_time') <NEW_LINE> ctx = { 'group_notify': group_notify, 'active': 'group' } <NEW_LINE> set_notity_clicked.send(sender=group_notify, request=request, no_type='group') <NEW_LINE> return render(request, 'notify/groups.html', ctx)
通知:群组 @fanlintao
625941c1097d151d1a222ddf
def get_results_json_report(): <NEW_LINE> <INDENT> report_dict = list(targetsList) <NEW_LINE> ret = {} <NEW_LINE> for item in report_dict: <NEW_LINE> <INDENT> _, _, _ = item.pop('logFile'), item.pop('hostIndex'), item.pop('commandList') <NEW_LINE> target = item.pop('target') <NEW_LINE> if not target in ret: <NEW_LINE> <INDENT> ret[target] = [item] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ret[target].append(item) <NEW_LINE> <DEDENT> <DEDENT> return ret
this function takes targetsList and produced report dictionary, where key is set to target and value of key is a list of checks done, so that it can be used for running deepdiff comaprison
625941c11d351010ab855aa0
def openimg(filepath): <NEW_LINE> <INDENT> def bgr_to_rgb(image): <NEW_LINE> <INDENT> b,g,r=np.split(image, 3, axis=2) <NEW_LINE> return np.concatenate((r,g,b), axis=2) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> filepath=Path(filepath) <NEW_LINE> if not(filepath.is_file()): <NEW_LINE> <INDENT> raise IOError("That file doesn't exist!") <NEW_LINE> <DEDENT> return bgr_to_rgb(cv2.imread(str(filepath), 1)) <NEW_LINE> <DEDENT> except IOError as e: <NEW_LINE> <INDENT> print(e)
Wrapper for cv2.imread to correct channel order.
625941c182261d6c526ab420
def cleanupdir(dirPath, ignoreErrors=True): <NEW_LINE> <INDENT> cleanupdir_errors = [] <NEW_LINE> def logit(func, path, exc_info): <NEW_LINE> <INDENT> cleanupdir_errors.append('%s: %s' % (func.__name__, exc_info[1])) <NEW_LINE> <DEDENT> shutil.rmtree(dirPath, onerror=logit) <NEW_LINE> if not ignoreErrors and cleanupdir_errors: <NEW_LINE> <INDENT> raise RuntimeError("%s %s" % (dirPath, cleanupdir_errors))
Recursively remove all the files and directories in the given directory
625941c13cc13d1c6d3c72fe
def ls (self, directory): <NEW_LINE> <INDENT> self._check_not_closed () <NEW_LINE> r = libguestfsmod.ls (self._o, directory) <NEW_LINE> return r
List the files in "directory" (relative to the root directory, there is no cwd). The '.' and '..' entries are not returned, but hidden files are shown. This function returns a list of strings.
625941c1e76e3b2f99f3a793
def testOperations(self): <NEW_LINE> <INDENT> pass
Test Operations
625941c1d486a94d0b98e0c9
def _iter_all_compatibility_tags(self, wheel): <NEW_LINE> <INDENT> implementation_tag, abi_tag, platform_tag = wheel.split("-")[-3:] <NEW_LINE> for implementation in implementation_tag.split("."): <NEW_LINE> <INDENT> for abi in abi_tag.split("."): <NEW_LINE> <INDENT> for platform in platform_tag.split("."): <NEW_LINE> <INDENT> yield (implementation, abi, platform)
Generates all possible combination of tag sets as described in PEP 425 https://www.python.org/dev/peps/pep-0425/#compressed-tag-sets
625941c163b5f9789fde7069
def __init__(self,idd,name,rank,info="",**kwargs): <NEW_LINE> <INDENT> self.idd = idd <NEW_LINE> self.name = name <NEW_LINE> self.rank = int(rank) <NEW_LINE> self.info = info <NEW_LINE> self.mail = None <NEW_LINE> self.subclass = "" <NEW_LINE> self.info = info <NEW_LINE> self.extra = list(kwargs.keys()) <NEW_LINE> self.__dict__.update(kwargs) <NEW_LINE> self._credits = 0 <NEW_LINE> self.alloted = {} <NEW_LINE> self.alloted_res = set() <NEW_LINE> self.alloted_base = set() <NEW_LINE> self.duties = 0
format: required positional params: idd - unique id (ususlly not by user) name - name of teacher rank - rank of teacher optional parameters: info - any extra info extra: kwargs - may include any property
625941c1435de62698dfdbd0
def create_user(name, phone_num): <NEW_LINE> <INDENT> user = User(name=name, phone_num=phone_num) <NEW_LINE> db.session.add(user) <NEW_LINE> db.session.commit() <NEW_LINE> return user
create and return a new user.
625941c1f548e778e58cd500
def has_header(sample, encoding=DEFAULT_ENCODING): <NEW_LINE> <INDENT> sniffer = csv.Sniffer().has_header <NEW_LINE> try: <NEW_LINE> <INDENT> return sniffer(sample) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> return sniffer(sample.decode(encoding)) <NEW_LINE> <DEDENT> except csv.Error: <NEW_LINE> <INDENT> return None
Check whether a piece of sample text from a file has a header Parameters ---------- sample : str Text to check for existence of a header encoding : str Encoding to use if ``isinstance(sample, bytes)`` Returns ------- h : bool or NoneType None if an error is thrown, otherwise ``True`` if a header exists and ``False`` otherwise.
625941c196565a6dacc8f64f
def test_pep8_conformance_test_place(self): <NEW_LINE> <INDENT> pep8s = pep8.StyleGuide(quiet=True) <NEW_LINE> result = pep8s.check_files(['tests/test_models/test_place.py']) <NEW_LINE> self.assertEqual(result.total_errors, 0, "Found code style errors in test_place.py")
Checking that test_place.py conforms to PEP8
625941c1293b9510aa2c321b
def training_data_cached(self): <NEW_LINE> <INDENT> return TFTDataCache.contains("train") and TFTDataCache.contains("valid")
Returns boolean indicating if training data has been cached.
625941c144b2445a3393201b
def finalize(self): <NEW_LINE> <INDENT> if self.redirect_context: <NEW_LINE> <INDENT> self.redirect_context.finalize()
Close & finalize each the metadata context
625941c14d74a7450ccd4147
def urltype(url): <NEW_LINE> <INDENT> path = urlparse(url).path <NEW_LINE> root, ext = splitext(path) <NEW_LINE> if ext == "": <NEW_LINE> <INDENT> return "direct" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "playlist"
determine the type of the given url this will currently be direct for the stream url playlist for the url of a playlist file extensions are normally m3u, pls or asx
625941c1cc40096d615958d5
def _get_source_address(self): <NEW_LINE> <INDENT> return self.__source_address
Getter method for source_address, mapped from YANG variable /acl/acl_sets/acl_set/acl_entries/acl_entry/ipv4/config/source_address (oc-inet:ipv4-prefix) YANG Description: Source IPv4 address prefix.
625941c16aa9bd52df036d26
def vertical_constraints(n): <NEW_LINE> <INDENT> clauses = list(list()) <NEW_LINE> for x in range(1, n+1): <NEW_LINE> <INDENT> for y in range(1, n+1): <NEW_LINE> <INDENT> for i in range(y+1, n+1): <NEW_LINE> <INDENT> aux = [-transform_coordinates_xy_to_val([x, y], n), -transform_coordinates_xy_to_val([x, i], n)] <NEW_LINE> clauses.append(aux.copy()) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for x in range(1, n+1): <NEW_LINE> <INDENT> aux = list() <NEW_LINE> for y in range(1, n+1): <NEW_LINE> <INDENT> aux.append(transform_coordinates_xy_to_val([x, y], n)) <NEW_LINE> <DEDENT> clauses.append(aux) <NEW_LINE> <DEDENT> return clauses
Create vertical constraints (one queen per column) :param n: board size (nxn) and number of queens. :return: clauses in CNF format for SAT solving.
625941c14f6381625f1149bf
def __init__(self): <NEW_LINE> <INDENT> self.Param = None <NEW_LINE> self.Value = None <NEW_LINE> self.SetValue = None <NEW_LINE> self.Default = None <NEW_LINE> self.Constraint = None <NEW_LINE> self.HaveSetValue = None
:param Param: Parameter name :type Param: str :param Value: Current parameter value :type Value: str :param SetValue: Previously set value, which is the same as `value` after the parameter takes effect. If no value has been set, this field will not be returned. Note: this field may return null, indicating that no valid values can be obtained. :type SetValue: str :param Default: Default value :type Default: str :param Constraint: Parameter constraint :type Constraint: :class:`tencentcloud.dcdb.v20180411.models.ParamConstraint` :param HaveSetValue: Whether a value has been set. false: no, true: yes :type HaveSetValue: bool
625941c17c178a314d6ef3df
def emergesend(self, event): <NEW_LINE> <INDENT> return self.queue.append(event, True)
Force send a new event to the main queue.
625941c1925a0f43d2549df9
def get_metadata_api(self, path): <NEW_LINE> <INDENT> self.api.set_var("path", path + "/metadata.json") <NEW_LINE> return self._get_json_contents(self.api.get_file())
Returns cotents of the metadata.json file from a path
625941c1283ffb24f3c55887
def test_imputer_numeric_data(test_dir): <NEW_LINE> <INDENT> N = 1000 <NEW_LINE> x = np.random.uniform(-np.pi, np.pi, (N,)) <NEW_LINE> df = pd.DataFrame({ 'x': x, 'cos': np.cos(x), '*2': x * 2, '**2': x ** 2}) <NEW_LINE> df_train, df_test = random_split(df, [.6, .4]) <NEW_LINE> output_path = os.path.join(test_dir, "tmp", "real_data_experiment_numeric") <NEW_LINE> data_encoder_cols = [NumericalEncoder(['x'])] <NEW_LINE> data_cols = [NumericalFeaturizer('x', numeric_latent_dim=100)] <NEW_LINE> for target in ['*2', '**2', 'cos']: <NEW_LINE> <INDENT> label_encoder_cols = [NumericalEncoder([target], normalize=False)] <NEW_LINE> imputer = Imputer( data_featurizers=data_cols, label_encoders=label_encoder_cols, data_encoders=data_encoder_cols, output_path=output_path ) <NEW_LINE> imputer.fit( train_df=df_train, learning_rate=1e-1, num_epochs=100, patience=5, test_split=.3, weight_decay=.0, batch_size=128 ) <NEW_LINE> pred, metrics = imputer.transform_and_compute_metrics(df_test) <NEW_LINE> df_test['predictions_' + target] = pred[target].flatten() <NEW_LINE> print("Numerical metrics: {}".format(metrics[target])) <NEW_LINE> assert metrics[target] < 10
Tests numeric encoder/featurizer only
625941c167a9b606de4a7e3f
def test_event_hierarchy(self): <NEW_LINE> <INDENT> class MyEvt(BaseEvent): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> class MyEvt2(MyEvt): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> class MyEvt3(MyEvt): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> class MyEvt4(MyEvt2, MyEvt3): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.assertEqual( self.evt_mgr.get_event_hierarchy(BaseEvent), (BaseEvent, )) <NEW_LINE> self.assertEqual( self.evt_mgr.get_event_hierarchy(MyEvt), (MyEvt, BaseEvent)) <NEW_LINE> self.assertEqual( self.evt_mgr.get_event_hierarchy(MyEvt2), (MyEvt2, MyEvt, BaseEvent)) <NEW_LINE> self.assertEqual( self.evt_mgr.get_event_hierarchy(MyEvt3), (MyEvt3, MyEvt, BaseEvent)) <NEW_LINE> self.assertEqual( self.evt_mgr.get_event_hierarchy(MyEvt4), (MyEvt4, MyEvt2, MyEvt3, MyEvt, BaseEvent))
Test whether the correct hierarchy of event classes is returned.
625941c191af0d3eaac9b99a
def get_page_text(self, ignore_page_numbers=False): <NEW_LINE> <INDENT> if ignore_page_numbers: <NEW_LINE> <INDENT> result = list(filter(lambda x: not x.text.isdigit(), self.lines)) <NEW_LINE> return '\n'.join(list(map(lambda x: x.text, result))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return '\n'.join(list(map(lambda x: x.text, self.lines)))
Return a string containing the content of the page. If the argument ignore_page_number is True, try to ignore page number when it is possible.
625941c15510c4643540f36d
def setResource(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!')
The caller must have permission to CREATE or UPDATE the resource accordingly
625941c126238365f5f0edef
def add_user_session(username): <NEW_LINE> <INDENT> token = b64encode(uuid4().bytes).decode() <NEW_LINE> con, cur = create_con() <NEW_LINE> cur.execute('INSERT INTO sessions(username, token) VALUES (?, ?);', (username, token)) <NEW_LINE> con.commit() <NEW_LINE> cur.close() <NEW_LINE> con.close() <NEW_LINE> return token
Generates a token for a user and adds that token and username to the sesssions.
625941c17b180e01f3dc4785
def remove_descriptor(self, fileno): <NEW_LINE> <INDENT> listeners = [] <NEW_LINE> listeners.append(self.listeners[READ].pop(fileno, noop)) <NEW_LINE> listeners.append(self.listeners[WRITE].pop(fileno, noop)) <NEW_LINE> listeners.extend(self.secondaries[READ].pop(fileno, ())) <NEW_LINE> listeners.extend(self.secondaries[WRITE].pop(fileno, ())) <NEW_LINE> for listener in listeners: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> listener.cb(fileno) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> self.squelch_generic_exception(sys.exc_info())
Completely remove all listeners for this fileno. For internal use only.
625941c124f1403a92600aec
def generate_room(x, y, z): <NEW_LINE> <INDENT> room = Room() <NEW_LINE> room.x, room.y, room.z = x, y, z <NEW_LINE> terrain, diverse = get_terrain_for_coord(x, y) <NEW_LINE> room.terrain = terrain <NEW_LINE> if diverse and terrain.diversity_symbol: <NEW_LINE> <INDENT> room.name = terrain.diversity_name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> room.name = terrain.room_name <NEW_LINE> <DEDENT> room.description = terrain.room_description <NEW_LINE> return room
Generate a single room at the given coordinates. :param int x: The room's x coordinate :param int y: The room's y coordinate :param int z: The room's z coordinate :returns world.Room: The generated room
625941c1fb3f5b602dac3615
def _identify_boundaries(self, depth_scores): <NEW_LINE> <INDENT> boundaries = [0 for x in depth_scores] <NEW_LINE> avg = sum(depth_scores)/len(depth_scores) <NEW_LINE> stdev = numpy.std(depth_scores) <NEW_LINE> if self.cutoff_policy == LC: <NEW_LINE> <INDENT> cutoff = avg-stdev/2.0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cutoff = avg-stdev/2.0 <NEW_LINE> <DEDENT> depth_tuples = sorted(zip(depth_scores, range(len(depth_scores)))) <NEW_LINE> depth_tuples.reverse() <NEW_LINE> hp = filter(lambda x:x[0]>cutoff, depth_tuples) <NEW_LINE> for dt in hp: <NEW_LINE> <INDENT> boundaries[dt[1]] = 1 <NEW_LINE> for dt2 in hp: <NEW_LINE> <INDENT> if dt[1] != dt2[1] and abs(dt2[1]-dt[1]) < 4 and boundaries[dt2[1]] == 1: <NEW_LINE> <INDENT> boundaries[dt[1]] = 0 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return boundaries
Identifies boundaries at the peaks of similarity score differences
625941c1be383301e01b540d
def _DoReadFileDtb(self, fname, use_real_dtb=False, map=False, update_dtb=False, entry_args=None, reset_dtbs=True, extra_indirs=None): <NEW_LINE> <INDENT> dtb_data = None <NEW_LINE> if use_real_dtb: <NEW_LINE> <INDENT> dtb_data = self._SetupDtb(fname) <NEW_LINE> for name in ['spl', 'tpl']: <NEW_LINE> <INDENT> dtb_fname = '%s/u-boot-%s.dtb' % (name, name) <NEW_LINE> outfile = os.path.join(self._indir, dtb_fname) <NEW_LINE> TestFunctional._MakeInputFile(dtb_fname, self._GetDtbContentsForSplTpl(dtb_data, name)) <NEW_LINE> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> retcode = self._DoTestFile(fname, map=map, update_dtb=update_dtb, entry_args=entry_args, use_real_dtb=use_real_dtb, extra_indirs=extra_indirs) <NEW_LINE> self.assertEqual(0, retcode) <NEW_LINE> out_dtb_fname = tools.GetOutputFilename('u-boot.dtb.out') <NEW_LINE> image = control.images['image'] <NEW_LINE> image_fname = tools.GetOutputFilename('image.bin') <NEW_LINE> self.assertTrue(os.path.exists(image_fname)) <NEW_LINE> if map: <NEW_LINE> <INDENT> map_fname = tools.GetOutputFilename('image.map') <NEW_LINE> with open(map_fname) as fd: <NEW_LINE> <INDENT> map_data = fd.read() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> map_data = None <NEW_LINE> <DEDENT> with open(image_fname, 'rb') as fd: <NEW_LINE> <INDENT> return fd.read(), dtb_data, map_data, out_dtb_fname <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> if reset_dtbs and use_real_dtb: <NEW_LINE> <INDENT> self._ResetDtbs()
Run binman and return the resulting image This runs binman with a given test file and then reads the resulting output file. It is a shortcut function since most tests need to do these steps. Raises an assertion failure if binman returns a non-zero exit code. Args: fname: Device-tree source filename to use (e.g. 005_simple.dts) use_real_dtb: True to use the test file as the contents of the u-boot-dtb entry. Normally this is not needed and the test contents (the U_BOOT_DTB_DATA string) can be used. But in some test we need the real contents. map: True to output map files for the images update_dtb: Update the offset and size of each entry in the device tree before packing it into the image entry_args: Dict of entry args to supply to binman key: arg name value: value of that arg reset_dtbs: With use_real_dtb the test dtb is overwritten by this function. If reset_dtbs is True, then the original test dtb is written back before this function finishes extra_indirs: Extra input directories to add using -I Returns: Tuple: Resulting image contents Device tree contents Map data showing contents of image (or None if none) Output device tree binary filename ('u-boot.dtb' path)
625941c14527f215b584c3de
def fill_3d(data, frame, weights): <NEW_LINE> <INDENT> return hist3d(_get_var(data, 'costh_' + frame), _get_var(data, 'phi_' + frame), _get_var(data, *binvar), hist_sett=hist_sett, weights=weights)
3D histograms
625941c1498bea3a759b9a34
def create_correct_data_window(self, TYPEOPERATIONS, DATA, NOTE=0): <NEW_LINE> <INDENT> if TYPEOPERATIONS == 'NEW': <NEW_LINE> <INDENT> self.fc.current_window = TypesWindows.dataCreateNewWindow <NEW_LINE> <DEDENT> elif TYPEOPERATIONS == 'COPY': <NEW_LINE> <INDENT> self.fc.current_window = TypesWindows.dataCreateNewWindowCopy <NEW_LINE> <DEDENT> elif TYPEOPERATIONS == 'CORRECTION': <NEW_LINE> <INDENT> self.fc.current_window = TypesWindows.dataCorrectWindow <NEW_LINE> <DEDENT> self.update_dict_active_images(DATA[8]) <NEW_LINE> self.toolbarMenu.pack_forget() <NEW_LINE> self.frameMain.place(x=0, y=0, height=720, width=1280) <NEW_LINE> self.clear_main_frame() <NEW_LINE> button_back = tk.Button(self.frameMain, image=self.active_images.get('back_img'), bg='black', name='button_Back') <NEW_LINE> button_back.place(x=0, y=0) <NEW_LINE> back_params = DATA[1] if TYPEOPERATIONS == 'NEW' else DATA <NEW_LINE> button_back.bind('<Button-1>', lambda eventbutton: self.fc.do_back_ward(back_params)) <NEW_LINE> Main_paint = tk.Label(self.frameMain, bg='black', image=self.active_images.get('item_image')) <NEW_LINE> Main_paint.place(x=820, y=45) <NEW_LINE> nameandcolor = self.define_text_and_color(DATA[1]) <NEW_LINE> l1 = tk.Label(self.frameMain, text=nameandcolor[0] + "/Ввод данных:", bg="black", foreground="#ccc", font="Arial 25") <NEW_LINE> l1.place(x=50, y=50) <NEW_LINE> self.show_operation_input_fields(TYPEOPERATIONS, DATA, NOTE) <NEW_LINE> if TYPEOPERATIONS in ('NEW', 'COPY'): <NEW_LINE> <INDENT> button_SaveNote = tk.Button(self.frameMain, text='Сохранить', name='button_Save', font="Arial 14", bg="#708090", foreground="#F5F5F5") <NEW_LINE> button_SaveNote.place(x=50, y=600, width=200, height=40) <NEW_LINE> button_SaveNote.bind('<Button-1>', lambda eventbutton: self.fc.save_new_operation(DATA)) <NEW_LINE> <DEDENT> elif TYPEOPERATIONS == 'CORRECTION': <NEW_LINE> <INDENT> button_SaveNote = tk.Button(self.frameMain, text='Сохранить изменения', name='button_Save', font="Arial 14", bg="#708090", foreground="#F5F5F5") <NEW_LINE> button_SaveNote.place(x=50, y=600, width=200, height=40) <NEW_LINE> button_SaveNote.bind('<Button-1>', lambda eventbutton: self.fc.save_changes_operation(DATA, NOTE))
Окно создания новой записи данных Если id записи (NOTE) == 0, открывается диалог записи с пустыми полями, если id записи (NOTE) != 0, то копируем поля из записи по id # TYPEOPERATIONS: 'NEW', 'COPY', 'CORRECTION'
625941c1cb5e8a47e48b7a31
def get_location_by_address(self, city, address): <NEW_LINE> <INDENT> params = { 'key': self.ak, 'city': city, 'address': address, 'sig': self.sign } <NEW_LINE> resp = json.loads(requests.get(url=self.url_geo, params=params).text) <NEW_LINE> if resp and len(resp.get('geocodes')) >= 1 and resp.get('geocodes')[0].get('location'): <NEW_LINE> <INDENT> location = resp.get('geocodes')[0].get('location') <NEW_LINE> gps_data = location.split(',') <NEW_LINE> gps_long = float(gps_data[0]) <NEW_LINE> gps_lati = float(gps_data[1]) <NEW_LINE> return gps_long, gps_lati <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('api解析地址出错,请检查ak!') <NEW_LINE> return None
通过地理位置到拿到经纬度 地理编码:https://lbs.amap.com/api/webservice/guide/api/georegeo/ :param address: :return:
625941c191f36d47f21ac474
def add_child(self, *node): <NEW_LINE> <INDENT> for child in node: <NEW_LINE> <INDENT> self.node_child.append(child)
Child node add.
625941c1c432627299f04bc8
def test_cannot_ride_too_short(self): <NEW_LINE> <INDENT> actual = unittype.raging_spirits(100) <NEW_LINE> self.assertEqual('乗れない', actual)
身長が100cmの場合、乗れないと判定される(FT) :return:
625941c10a366e3fb873e79c
def _parse_compile_options(parsed, options): <NEW_LINE> <INDENT> _parse_compile_order(parsed, options) <NEW_LINE> _parse_paragraph_options(parsed, options) <NEW_LINE> _parse_spacing(parsed, options)
Parse compile options from the config file data. @type parsed: object @param parsed: Data loaded from the config file. @type options: DotMap @param options: Data structure where options are stored.
625941c176d4e153a657eab4
def is_linux(): <NEW_LINE> <INDENT> return _PLATFORM == "linux"
Is Linux.
625941c126238365f5f0edf0
def getAvailableHrs(self, available): <NEW_LINE> <INDENT> hrsTotal = (available.total(), available.total(gc = True)) <NEW_LINE> hrs = [] <NEW_LINE> for w in self.lst.weatherTypes: <NEW_LINE> <INDENT> w = w.lower() <NEW_LINE> hrs.append((available.total(type = w) , available.total(type = w, gc = True))) <NEW_LINE> <DEDENT> return (hrsTotal, hrs[0], hrs[1], hrs[2])
Reorganize our data.
625941c130bbd722463cbd48
def get_team_ppa(self, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async_req'): <NEW_LINE> <INDENT> return self.get_team_ppa_with_http_info(**kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.get_team_ppa_with_http_info(**kwargs) <NEW_LINE> return data
Predicted Points Added (PPA/EPA) data by team # noqa: E501 Predicted Points Added (PPA) # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_team_ppa(async_req=True) >>> result = thread.get() :param async_req bool :param int year: Year filter (required if team not specified) :param str team: Team filter (required if year not specified) :param str conference: Conference filter :param bool exclude_garbage_time: Filter to remove garbage time plays from calculations :return: list[TeamPPA] If the method is called asynchronously, returns the request thread.
625941c13539df3088e2e2cf
def testNoConcreteModels(self): <NEW_LINE> <INDENT> with self.assertRaises(TypeError): <NEW_LINE> <INDENT> class Bad(VersionView, models.ConcreteModel): <NEW_LINE> <INDENT> test = dbmodels.CharField(max_length=20)
Version Views can't inherit from concrete models
625941c1e64d504609d747c4
def get_pathlabel(self): <NEW_LINE> <INDENT> if self.is_root() or not self._abstract: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> pathlabel = "" <NEW_LINE> parent_edge = self.parent_edge <NEW_LINE> while parent_edge is not None: <NEW_LINE> <INDENT> pathlabel = str(parent_edge) + pathlabel <NEW_LINE> parent_edge = parent_edge.src.parent_edge <NEW_LINE> <DEDENT> return pathlabel
Return substring represented by the root of this subtree.
625941c199cbb53fe6792b6b
def getBracket(self): <NEW_LINE> <INDENT> found = self._getObjectsContainedInDirectionType(Bracket) <NEW_LINE> if len(found) > 0: <NEW_LINE> <INDENT> return found[0] <NEW_LINE> <DEDENT> return None
Search this direction and determine if it contains a segno mark. >>> a = musicxml.Direction() >>> b = musicxml.DirectionType() >>> c = musicxml.Bracket() >>> b.append(c) >>> a.append(b) >>> a.getBracket() is not None True
625941c1442bda511e8be39f
def _logical_type(): <NEW_LINE> <INDENT> return "unsigned int"
Return the C type to match Fortran the logical type This may depend on the compiler used
625941c1be7bc26dc91cd588
def rhombus_at_intersection(gamma, r, s, kr, ks): <NEW_LINE> <INDENT> z0 = 1j*(zeta[r]*(ks-gamma[s]) - zeta[s]*(kr-gamma[r])) / zeta[s-r].imag <NEW_LINE> k = [0--((z0/t).real+p)//1 for t, p in zip(zeta, gamma)] <NEW_LINE> for k[r], k[s] in [(kr, ks), (kr+1, ks), (kr+1, ks+1), (kr, ks+1)]: <NEW_LINE> <INDENT> yield sum(x*t for t, x in zip(zeta, k))
Find the rhombus corresponding to a pentagrid intersection point. Generates four complex numbers, giving the vertices of the rhombus corresponding in the pentagrid described by parameters gamma to the intersection of the two lines with equations: (z/zeta[r]).real + gamma[r] == kr and (z/zeta[s]).real + gamma[s] == ks The vertices traverse the perimeter of the rhombus in order (though that order may be either clockwise or counterclockwise).
625941c1462c4b4f79d1d655
def __init__(self, consumer_key, consumer_secret, token, token_secret): <NEW_LINE> <INDENT> self.consumer_key = consumer_key <NEW_LINE> self.consumer_secret = consumer_secret <NEW_LINE> self.token = token <NEW_LINE> self.token_secret = token_secret <NEW_LINE> super().__init__()
Constructor :param consumer_key: consumer key :param consumer_secret: consumer secret :param token: API token :param token_secret: API token secret
625941c1d6c5a10208143fcd
def blocks(self): <NEW_LINE> <INDENT> return self._blocks
Get a list of all basic blocks.
625941c11f5feb6acb0c4ad8
def __init__(self, cohort_id, start_date, end_date, user_id=0): <NEW_LINE> <INDENT> self.cohort_id = cohort_id <NEW_LINE> self.start_date = start_date <NEW_LINE> self.end_date = end_date <NEW_LINE> self.user_id = user_id <NEW_LINE> self.recurrent_parent_id = None <NEW_LINE> self.persistent_id = None
Parameters: cohort_id : ID of the cohort start_date : Start date for the GlobalMetrics report end_date : End date for the GlobalMetrics report user_id : The user running this report
625941c1cad5886f8bd26f5e
def weight_variable(shape): <NEW_LINE> <INDENT> initial = tf.truncated_normal(shape, stddev=0.1) <NEW_LINE> return tf.Variable(initial, name='weight')
Generates a weight variable of a given shape.
625941c16e29344779a62599
@app.route("/") <NEW_LINE> def index(): <NEW_LINE> <INDENT> return redirect('./contacts')
Home page
625941c121a7993f00bc7c71
def is_true(self, object): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> value1 = getattr(object, self.name) <NEW_LINE> type1 = type(value1) <NEW_LINE> value2 = self.value <NEW_LINE> if not isinstance(value2, type1): <NEW_LINE> <INDENT> value2 = type1(value2) <NEW_LINE> <DEDENT> return getattr(self, self.operation_)(value1, value2) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return False
Returns whether the rule is true for a specified object.
625941c1a05bb46b383ec7a8
def poll_input(self, pollable): <NEW_LINE> <INDENT> self._inputs.append(pollable)
Registers an object to be polled with each loop. :param pollable: An object with a poll function.
625941c12ae34c7f2600d0b6
def main(request): <NEW_LINE> <INDENT> if request.user.is_anonymous(): <NEW_LINE> <INDENT> if request.method == 'POST': <NEW_LINE> <INDENT> form = register_form(large_input=False, data=request.POST) <NEW_LINE> if form.is_valid(): <NEW_LINE> <INDENT> form.save() <NEW_LINE> email = form.cleaned_data['email'] <NEW_LINE> user = MyUser.objects.get(email=email) <NEW_LINE> login(request, user) <NEW_LINE> return redirect(reverse('base_info_edit')) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> form = register_form(large_input=False) <NEW_LINE> ctx = { 'form': form } <NEW_LINE> return render(request, 'register.html', ctx) <NEW_LINE> <DEDENT> <DEDENT> elif request.user.is_authenticated(): <NEW_LINE> <INDENT> return redirect(reverse('index'))
进入网站的页面 未登录的显示,已经登录的跳转到首页
625941c176e4537e8c3515f6
@public <NEW_LINE> def index_from_edict(edict): <NEW_LINE> <INDENT> return edict.get_index()
Returns an index from the given edict
625941c123849d37ff7b3015
def timeRange( start: datetime.time, end: datetime.time, step: float) -> Iterator[datetime.datetime]: <NEW_LINE> <INDENT> assert step > 0 <NEW_LINE> start = _fillDate(start) <NEW_LINE> end = _fillDate(end) <NEW_LINE> delta = datetime.timedelta(seconds=step) <NEW_LINE> t = start <NEW_LINE> while t < datetime.datetime.now(): <NEW_LINE> <INDENT> t += delta <NEW_LINE> <DEDENT> while t <= end: <NEW_LINE> <INDENT> waitUntil(t) <NEW_LINE> yield t <NEW_LINE> t += delta
Iterator that waits periodically until certain time points are reached while yielding those time points. Args: start: Start time, can be specified as datetime.datetime, or as datetime.time in which case today is used as the date end: End time, can be specified as datetime.datetime, or as datetime.time in which case today is used as the date step (float): The number of seconds of each period
625941c1f8510a7c17cf9680
def test_wrong_shape(self): <NEW_LINE> <INDENT> with pytest.raises(InputParameterError): <NEW_LINE> <INDENT> self.gmodel.amplitude = [1, 2]
Tests raising an exception when attempting to update a model's parameter and the new value has the wrong shape.
625941c1377c676e9127212e
def count_snapshot_created_today(options, _fuse): <NEW_LINE> <INDENT> _fuse.setReadonly(True) <NEW_LINE> from dedupsqlfs.fuse.subvolume import Subvolume <NEW_LINE> sv = Subvolume(_fuse.operations) <NEW_LINE> sv.count_today_created_subvols(True) <NEW_LINE> _fuse.operations.destroy() <NEW_LINE> return
@param options: Commandline options @type options: object @param _fuse: FUSE wrapper @type _fuse: dedupsqlfs.fuse.dedupfs.DedupFS
625941c12eb69b55b151c832
@handle_boto_errors <NEW_LINE> def es_info(aws_config=None, domain_name=None): <NEW_LINE> <INDENT> es_client = get_client(client_type='es', config=aws_config) <NEW_LINE> try: <NEW_LINE> <INDENT> domain = es_client.describe_elasticsearch_domains(DomainNames=[domain_name]) <NEW_LINE> output_domain_info(domain=domain) <NEW_LINE> <DEDENT> except (ClientError, IndexError): <NEW_LINE> <INDENT> exit("Cannot find domain: {0}".format(domain_name))
@type aws_config: Config @type domain_name: unicode
625941c132920d7e50b28153
@tf_export('linalg.cholesky', 'cholesky') <NEW_LINE> @deprecated_endpoints('cholesky') <NEW_LINE> def cholesky(input, name=None): <NEW_LINE> <INDENT> _ctx = _context._context <NEW_LINE> if _ctx is None or not _ctx._eager_context.is_eager: <NEW_LINE> <INDENT> _, _, _op = _op_def_lib._apply_op_helper( "Cholesky", input=input, name=name) <NEW_LINE> _result = _op.outputs[:] <NEW_LINE> _inputs_flat = _op.inputs <NEW_LINE> _attrs = ("T", _op.get_attr("T")) <NEW_LINE> _execute.record_gradient( "Cholesky", _inputs_flat, _attrs, _result, name) <NEW_LINE> _result, = _result <NEW_LINE> return _result <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _result = _pywrap_tensorflow.TFE_Py_FastPathExecute( _ctx._context_handle, _ctx._eager_context.device_name, "Cholesky", name, _ctx._post_execution_callbacks, input) <NEW_LINE> return _result <NEW_LINE> <DEDENT> except _core._FallbackException: <NEW_LINE> <INDENT> return cholesky_eager_fallback( input, name=name, ctx=_ctx) <NEW_LINE> <DEDENT> except _core._NotOkStatusException as e: <NEW_LINE> <INDENT> if name is not None: <NEW_LINE> <INDENT> message = e.message + " name: " + name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> message = e.message <NEW_LINE> <DEDENT> _six.raise_from(_core._status_to_exception(e.code, message), None)
Computes the Cholesky decomposition of one or more square matrices. The input is a tensor of shape `[..., M, M]` whose inner-most 2 dimensions form square matrices. The input has to be symmetric and positive definite. Only the lower-triangular part of the input will be used for this operation. The upper-triangular part will not be read. The output is a tensor of the same shape as the input containing the Cholesky decompositions for all input submatrices `[..., :, :]`. **Note**: The gradient computation on GPU is faster for large matrices but not for large batch dimensions when the submatrices are small. In this case it might be faster to use the CPU. Args: input: A `Tensor`. Must be one of the following types: `float64`, `float32`, `complex64`, `complex128`. Shape is `[..., M, M]`. name: A name for the operation (optional). Returns: A `Tensor`. Has the same type as `input`.
625941c176d4e153a657eab5
def sample_documents(globstring): <NEW_LINE> <INDENT> for fn in glob.glob(globstring): <NEW_LINE> <INDENT> yield fn, document(fn)
Iterate over json-parsed test documents
625941c1dc8b845886cb54b9
def label_desc_to_label_id(self,label_desc): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> row = self.df[self.df[self.df.columns[-1]] == label_desc] <NEW_LINE> id = row.index[0] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return np.nan <NEW_LINE> <DEDENT> return id
根据排列组合转为id号 1,1,1,1=>40
625941c182261d6c526ab421
def sql(query): <NEW_LINE> <INDENT> conn = MySQLdb.connect(conf['dbhost'], conf['dbuser'], conf['dbpass']) <NEW_LINE> conn.select_db(conf['db']) <NEW_LINE> conn.autocommit(True) <NEW_LINE> cursor = conn.cursor() <NEW_LINE> cursor.execute(query) <NEW_LINE> ret = cursor.fetchall() <NEW_LINE> conn.close() <NEW_LINE> return ret
executes an sql query
625941c17d43ff24873a2c24