code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def dispatch(message): <NEW_LINE> <INDENT> if message == 'get_value': <NEW_LINE> <INDENT> return get_value <NEW_LINE> <DEDENT> elif message == 'set_value': <NEW_LINE> <INDENT> return set_value <NEW_LINE> <DEDENT> elif message == 'str': <NEW_LINE> <INDENT> print('{0}{1}'.format(symbol, amount)) <NEW_LINE> <DEDENT> elif ...
This function returns the requested function based on the received text.
625941c48e05c05ec3eea362
def assertURL(self, url, host, base, data={}): <NEW_LINE> <INDENT> parts = urlparse.urlparse(url) <NEW_LINE> self.assertEquals("{0}://{1}".format(parts.scheme, parts.netloc), host) <NEW_LINE> self.assertEquals(parts.path, base) <NEW_LINE> params = dict(urlparse.parse_qsl(parts.query)) <NEW_LINE> if data: <NEW_LINE> <IN...
assert a URL match on host/path/data
625941c47047854f462a13fa
def update(probabilities, one_gene, two_genes, have_trait, p): <NEW_LINE> <INDENT> for person in probabilities: <NEW_LINE> <INDENT> number_genes = __num_genes(person, one_gene, two_genes) <NEW_LINE> probabilities[person][TRAIT][person in have_trait] += p <NEW_LINE> probabilities[person][GENE][number_genes] += p
Add to `probabilities` a new joint probability `p`. Each person should have their "gene" and "trait" distributions updated. Which value for each distribution is updated depends on whether the person is in `have_gene` and `have_trait`, respectively.
625941c4aad79263cf390a2e
def list_dir_sorted(dir_name): <NEW_LINE> <INDENT> files = os.listdir(dir_name) <NEW_LINE> alphanumeric_sort(files) <NEW_LINE> return files
Helper for listing the directory contents with the preferred sorting.
625941c4460517430c394178
def length_of_pose(pose): <NEW_LINE> <INDENT> return math.sqrt(pose[0] * pose[0] + pose[1] * pose[1])
Calculate the length of a pose.
625941c432920d7e50b281be
def add_colored_points(point_cloud, cval, ax, cb = True, dim = 2): <NEW_LINE> <INDENT> if dim == 2: <NEW_LINE> <INDENT> sc = ax.scatter(point_cloud[0, :], point_cloud[1, :], c=cval, s = 50.0) <NEW_LINE> <DEDENT> elif dim == 3: <NEW_LINE> <INDENT> sc = ax.scatter(point_cloud[0, :], point_cloud[1, :], point_cloud[2, :], ...
Add points to 2D/3D plot with coloring indicating by the cval value.
625941c421bff66bcd684943
def checkin(test): <NEW_LINE> <INDENT> setattr(test, 'checkin', True) <NEW_LINE> setattr(test, 'all', True) <NEW_LINE> return test
super short tests that must pass before check-in occurs
625941c4fff4ab517eb2f42a
@app.route('/api/v01/item/<int:item_id>/JSON/') <NEW_LINE> def item_JSON(item_id): <NEW_LINE> <INDENT> item = session.query(Item).filter_by(id=item_id).one() <NEW_LINE> return jsonify(item=item.serialize)
Returns a specific item's information in JSON. Args: item_id: An integer representing the database id of the item who's data is to be returned Returns: JSON object representing a specific Item where Item.id==item_id.
625941c4f8510a7c17cf96ea
def __init__(self, name, title): <NEW_LINE> <INDENT> super(MainWindow, self).__init__() <NEW_LINE> self.w = 0 <NEW_LINE> self.h = 0 <NEW_LINE> self.init_ui(name, title)
初始化类的成员变量
625941c4009cb60464c633a2
def __init__(self, file_path, meta_keys={'subreddit': 'section'}): <NEW_LINE> <INDENT> self.meta = meta_keys <NEW_LINE> file_path = Path(file_path) <NEW_LINE> if not file_path.exists(): <NEW_LINE> <INDENT> raise IOError("Can't find file path: {}".format(file_path)) <NEW_LINE> <DEDENT> if not file_path.is_dir(): <NEW_LI...
file_path (unicode / Path): Path to archive or directory of archives. meta_keys (dict): Meta data key included in the Reddit corpus, mapped to display name in Prodigy meta. RETURNS (Reddit): The Reddit loader.
625941c430dc7b7665901957
def make_bag_of_words(clean_qa_bodies_l): <NEW_LINE> <INDENT> cf.logger.debug("Creating the bag of words for word counts ...") <NEW_LINE> from sklearn.feature_extraction.text import CountVectorizer <NEW_LINE> vectorizer = CountVectorizer(analyzer="word", tokenizer=None, preprocessor=None, stop_words=None, ngram_range=(...
Extract numerical features from input text data. Later steps can use those features with machine learning algorithms to analyze the data further. The input data is a list of strings of cleaned text, for one Q&A group. Each string contains the words of the Body field of the question or an answer. Consider the entire ...
625941c4cc40096d61595940
def _value__get(self): <NEW_LINE> <INDENT> for el in self: <NEW_LINE> <INDENT> if 'checked' in el.attrib: <NEW_LINE> <INDENT> return el.get('value') <NEW_LINE> <DEDENT> <DEDENT> return None
Get/set the value, which checks the radio with that value (and unchecks any other value).
625941c423e79379d52ee554
def serve(host, port, request_handler, error_handler, debug=False, request_timeout=60, sock=None, request_max_size=None, reuse_port=False, loop=None, protocol=HttpProtocol, backlog=100): <NEW_LINE> <INDENT> loop = loop or async_loop.new_event_loop() <NEW_LINE> asyncio.set_event_loop(loop) <NEW_LINE> if debug: <NEW_LINE...
在一个独立进程中启动异步 HTTP 服务器. :param host: 服务器地址 :param port: 服务器端口 :param request_handler: 请求处理器 :param error_handler: 异常处理器 :param debug: 开启 debug 输出 :param request_timeout: 以秒为单位,请求超时时间 :param sock: 接受连接的套接字 :param request_max_size: 大小以字节为单位,`None`代表无限制 :param reuse_port: `True` for multiple workers :param loop: 异步事件循环 :pa...
625941c43d592f4c4ed1d061
def setAnimationEndTime(*args, **kwargs): <NEW_LINE> <INDENT> pass
setAnimationEndTime(MTime) -> None Set the value of the last frame in the animation.
625941c499cbb53fe6792bd6
def _is_remote_before(self, version_tuple): <NEW_LINE> <INDENT> if self._remote_version_is_before is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return version_tuple >= self._remote_version_is_before
Is it possible the remote side supports RPCs for a given version? Typical use:: needed_version = (1, 2) if medium._is_remote_before(needed_version): fallback_to_pre_1_2_rpc() else: try: do_1_2_rpc() except UnknownSmartMethod: medium._remember_remote_is_befor...
625941c46e29344779a62602
def run_selected_algorithm(timeseries): <NEW_LINE> <INDENT> if len(timeseries) < MIN_TOLERABLE_LENGTH: <NEW_LINE> <INDENT> raise TooShort() <NEW_LINE> <DEDENT> if time() - timeseries[-1][0] > STALE_PERIOD: <NEW_LINE> <INDENT> raise Stale() <NEW_LINE> <DEDENT> if len(set(item[1] for item in timeseries[-MAX_TOLERABLE_BOR...
Filter timeseries and run selected algorithm. Return true in case of anomaly.
625941c4090684286d50ecd3
def get_url(): <NEW_LINE> <INDENT> host = os.getenv("HOST", "0.0.0.0") <NEW_LINE> port = os.getenv("PORT", 8000) <NEW_LINE> return host, port
Get server's host and port
625941c47d43ff24873a2c8f
def grid_equal (grid1, grid2): <NEW_LINE> <INDENT> for i in range(4): <NEW_LINE> <INDENT> for j in range(4): <NEW_LINE> <INDENT> if grid1[i][j] != grid2[i][j]: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return True
check if 2 grids are equal - return boolean value
625941c40fa83653e4656fab
def _operation_to_path_style(self, operation, **kwargs): <NEW_LINE> <INDENT> return GraphicPathStyle( stroke_style=operation.line_style, stroke_color=operation.line_color, **kwargs )
Generate a :class:`GraphicPathStyle` instance for a operation
625941c410dbd63aa1bd2b93
def _create_repo(repo): <NEW_LINE> <INDENT> return { "name": repo, "mention": [], "label": [], "enabled": { "label": True, "pr": True, "mention": True, "maintainer": False } }
Create a repo json structure for the given repository name. Defaults enabled to all except maintainer. :param repo: repository name to create json structure for :return: a new repo json object
625941c4ec188e330fd5a791
def add_local_rpath(env, *targets): <NEW_LINE> <INDENT> for target in targets: <NEW_LINE> <INDENT> target = env.Entry(target) <NEW_LINE> if not isinstance(target, SCons.Node.FS.Dir): <NEW_LINE> <INDENT> target = target.dir <NEW_LINE> <DEDENT> relpath = os.path.relpath(target.abspath, env['BUILDDIR']) <NEW_LINE> compone...
Set up an RPATH for a library which lives in the build directory. The construction environment variable BIN_RPATH_PREFIX should be set to the relative path of the build directory starting from the location of the binary.
625941c45fdd1c0f98dc0222
def create_emr_python_wordcount_step(): <NEW_LINE> <INDENT> step = { "Name": "python-wordcount-{}".format(env), "ActionOnFailure": "TERMINATE_JOB_FLOW", "HadoopJarStep": { "Jar": "command-runner.jar", "Args": [ "spark-submit", "--deploy-mode", "cluster", "--master", "yarn", "--conf", "spark.yarn.submit.waitAppCompletio...
Generate a python test step
625941c45166f23b2e1a5148
def daemonize(redirect_out=True): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> pid = os.fork() <NEW_LINE> if pid > 0: <NEW_LINE> <INDENT> os._exit(hubblestack.defaults.exitcodes.EX_OK) <NEW_LINE> <DEDENT> <DEDENT> except OSError as exc: <NEW_LINE> <INDENT> log.error('fork #1 failed: %s (%s)', exc.errno, exc) <NEW_LINE>...
Daemonize hubblestack process
625941c4004d5f362079a323
def parse_options( custom_entries: List[Custom], ) -> Tuple[FavaOptions, Iterable[BeancountError]]: <NEW_LINE> <INDENT> options: FavaOptions = copy.deepcopy(DEFAULTS) <NEW_LINE> errors = [] <NEW_LINE> for entry in (e for e in custom_entries if e.type == "fava-option"): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> key =...
Parse custom entries for Fava options. The format for option entries is the following: 2016-04-01 custom "fava-option" "[name]" "[value]" Args: custom_entries: A list of Custom entries. Returns: A tuple (options, errors) where options is a dictionary of all options to values, and errors contains pos...
625941c4a8370b771705288f
def test_acquisition_non_blocking(self): <NEW_LINE> <INDENT> self.sem.acquire() <NEW_LINE> self.sem.block = False <NEW_LINE> with self.assertRaises(sysv_ipc.BusyError): <NEW_LINE> <INDENT> self.sem.acquire()
tests that a non-blocking attempt at acquisition works
625941c4a219f33f3462895b
def sweepA(fitnesses, front): <NEW_LINE> <INDENT> stairs = [-fitnesses[0][1]] <NEW_LINE> fstairs = [fitnesses[0]] <NEW_LINE> for fit in fitnesses[1:]: <NEW_LINE> <INDENT> idx = bisect.bisect_right(stairs, -fit[1]) <NEW_LINE> if 0 < idx <= len(stairs): <NEW_LINE> <INDENT> fstair = max(fstairs[:idx], key=front.__getitem_...
Update rank number associated to the fitnesses according to the first two objectives using a geometric sweep procedure.
625941c430c21e258bdfa48b
def __str__(self): <NEW_LINE> <INDENT> st = "Season: "+str(self.year)+ " " + "\n" <NEW_LINE> for i in range(len(self.tournaments)): <NEW_LINE> <INDENT> st += " • "+str(self.tournaments[i])+"\n" <NEW_LINE> <DEDENT> return st
String representation of season
625941c43539df3088e2e33a
def main(): <NEW_LINE> <INDENT> depth, target_x, target_y = 10689, 11, 722 <NEW_LINE> cave = scan_cave(depth, target_x, target_y, 1000, 1000) <NEW_LINE> print(solve_a(cave, target_x, target_y)) <NEW_LINE> print(solve_b(cave, target_x, target_y))
Main program.
625941c42eb69b55b151c89c
def make_change(self, remote_id): <NEW_LINE> <INDENT> return Change( src_client_state=self.pos.get_axis_state(remote_id), src_rel_server_state=self.get_rel_server_state(remote_id), op=self.operation.op, pos=self.operation.pos, val=self.operation.val, precedence=self.operation.prec)
Make a Change object which is consumable by the given remote object Call on the source of the operation in question.
625941c41f037a2d8b9461ed
def test_simple_query_fullname(self): <NEW_LINE> <INDENT> qbl = QueryBlock("somehost") <NEW_LINE> assert qbl.target in [r'somehost\Z(?ms)', r'(?s:somehost)\Z'] <NEW_LINE> assert qbl.trait is None <NEW_LINE> assert qbl.flags == ()
Test simple query for fullname. <target> :[flags]:<target> :return:
625941c497e22403b379cf88
def editButtonAction(self): <NEW_LINE> <INDENT> self.dbPending = ac.DBPENDING_UPDATE <NEW_LINE> self.setFieldStatus(status=ac.ENABLE) <NEW_LINE> self.setButtonStatus(ac.APP_EDIT) <NEW_LINE> tabledata = self.extractTableData() <NEW_LINE> self.populateFields(tabledata) <NEW_LINE> self.frmFieldProgram.setFocus()
Set the database pending value, handle the database action, and set button status.
625941c4956e5f7376d70e5d
def partition(l, condition): <NEW_LINE> <INDENT> return filter(condition, l), filter(lambda x: not condition(x), l)
Returns a pair of lists, the left one containing all elements of `l` for which `condition` is ``True`` and the right one containing all elements of `l` for which `condition` is ``False``. `condition` is a function that takes a single argument (each individual element of the list `l`) and returns either ``True`` or ``F...
625941c4d7e4931a7ee9df0c
def queryset(self, request): <NEW_LINE> <INDENT> query_set = self.model.objects <NEW_LINE> ordering = self.get_ordering(request) <NEW_LINE> if ordering: <NEW_LINE> <INDENT> query_set = query_set.order_by(*ordering) <NEW_LINE> <DEDENT> return query_set
Ensure we use the correct manager. :param request: HttpRequest object
625941c4ad47b63b2c509f6f
def revise_pbr_rule_revise(self, body, section_id, rule_id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async_req'): <NEW_LINE> <INDENT> return self.revise_pbr_rule_revise_with_http_info(body, section_id, rule_id, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDEN...
Update an Existing Rule and Reorder the Rule # noqa: E501 Modifies existing PBR rule along with relative position among other PBR rules inside a PBR section. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.revise...
625941c4566aa707497f455b
def add_loss_acc(self): <NEW_LINE> <INDENT> self.loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=self.label_placeholder, logits=self.fc2)) <NEW_LINE> correct_prediction = tf.equal(tf.argmax(self.fc2, 1), tf.argmax(self.label_placeholder, 1)) <NEW_LINE> self.acc = tf.reduce_mean(tf.cast(correct_pred...
设置损失函数和精确度
625941c4dd821e528d63b199
def test_post(self): <NEW_LINE> <INDENT> expected_uuid = uuid.uuid4() <NEW_LINE> self.mock_program_detail_endpoint(expected_uuid, self.site_configuration.discovery_api_url) <NEW_LINE> expected_benefit_value = 10 <NEW_LINE> data = { 'program_uuid': expected_uuid, 'benefit_type': Benefit.PERCENTAGE, 'benefit_value': expe...
A new program offer should be created.
625941c4f9cc0f698b1405ec
def pc_nproduced_avg(self): <NEW_LINE> <INDENT> return _blocks_swig3.max_ii_sptr_pc_nproduced_avg(self)
pc_nproduced_avg(max_ii_sptr self) -> float
625941c46fece00bbac2d72c
@reentry.command('map') <NEW_LINE> @click.option('--dist', help='limit map to a distribution') <NEW_LINE> @click.option('--group', help='limit map to an entry point group') <NEW_LINE> @click.option('--name', help='limit map to entrypoints that match NAME') <NEW_LINE> def map_(dist, group, name): <NEW_LINE> <INDENT> imp...
Print out a map of cached entry points
625941c4cb5e8a47e48b7a9b
def is_local_source( filename: Union[str, Path], modname: str, experiment_path: Union[str, Path] ) -> bool: <NEW_LINE> <INDENT> filename = Path(os.path.abspath(os.path.realpath(filename))) <NEW_LINE> experiment_path = Path(os.path.abspath(os.path.realpath(experiment_path))) <NEW_LINE> if experiment_path not in filename...
Check if a module comes from the given experiment path. Check if a module, given by name and filename, is from (a subdirectory of ) the given experiment path. This is used to determine if the module is a local source file, or rather a package dependency. Parameters ---------- filename: str The absolute filename o...
625941c4498bea3a759b9a9f
def weight(self): <NEW_LINE> <INDENT> if len(self) == 0: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> m = max(max(row) for row in self) <NEW_LINE> res = [0] * m <NEW_LINE> for row in self: <NEW_LINE> <INDENT> for i in row: <NEW_LINE> <INDENT> if i > 0: <NEW_LINE> <INDENT> res[i - 1] += 1 <NEW_LINE> <DEDENT> <DEDEN...
Return the weight of the tableau ``self``. Trailing zeroes are omitted when returning the weight. The weight of a tableau `T` is the sequence `(a_1, a_2, a_3, \ldots )`, where `a_k` is the number of entries of `T` equal to `k`. This sequence contains only finitely many nonzero entries. The weight of a tableau `T` is ...
625941c43617ad0b5ed67ee8
def test_spill_format(spill): <NEW_LINE> <INDENT> if ',' not in spill and not spill[0].isdigit(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> spill_sep = spill.split(',') <NEW_LINE> n_par = int(spill_sep[0]) <NEW_LINE> if len(spill_sep) != (1 + n_par + n_par**2): <NEW_LINE> <INDENT> return False <NEW_LINE> <DE...
Confirms $SPILLOVER value has correct format. [# channels], [ch 1,...,ch n], [val 1, ..., val n**2]
625941c4dd821e528d63b19a
def shutdown(self, cancel_pending=True, timeout=5): <NEW_LINE> <INDENT> self.setThreadCount(0) <NEW_LINE> threads = self.threads <NEW_LINE> expiration = time() + timeout <NEW_LINE> while threads: <NEW_LINE> <INDENT> if time() >= expiration: <NEW_LINE> <INDENT> log.error("%d thread(s) still running" % len(threads)) <NEW...
See zope.server.interfaces.ITaskDispatcher
625941c4d53ae8145f87a262
def stop_job(self, job): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ext_id = job.get_job_runner_external_id() <NEW_LINE> assert ext_id not in (None, 'None'), 'External job id is None' <NEW_LINE> kill_script = job.get_destination_configuration(self.app.config, "drmaa_external_killjob_script", None) <NEW_LINE> if kill_...
Attempts to delete a job from the DRM queue
625941c4d4950a0f3b08c340
def test_mods_geographicCode(self): <NEW_LINE> <INDENT> expected = ['7013331', '7013938'] <NEW_LINE> self.assertEqual(expected, self.record.geographic_code)
checks subject/geographicCode
625941c4be383301e01b5478
def add_prefixes(self, code): <NEW_LINE> <INDENT> map_values = { "GREEN": "Added to Netbox:", "YELLOW": "Added to Netbox (IP overlap):", } <NEW_LINE> colour = getattr(Fore, code) <NEW_LINE> self.nb.ipam.prefixes.create( prefix=self.prefix["prefix"], site=self.prefix["location"], tenant=self.prefix["subscription"], cust...
Creates and updates prefixes in Netbox Data is pulled in from Azure
625941c476d4e153a657eb20
def sg(self): <NEW_LINE> <INDENT> return { 'Description': 'Security group for {}'.format(self.__class__.__name__), 'Allow': [self.PORT], }
Security group.
625941c45166f23b2e1a5149
def get_time_taken(self, obj): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> time_diff = obj.completed_at - obj.started_at <NEW_LINE> result = duration_string(time_diff) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> result = None <NEW_LINE> <DEDENT> return result
TODO: add me
625941c4bd1bec0571d9061f
def repPrune(self, validX, validY): <NEW_LINE> <INDENT> rootId = (0,) <NEW_LINE> self.tree.getVertex(rootId).setTestInds(numpy.arange(validX.shape[0])) <NEW_LINE> self.recursiveSetPrune(validX, validY, rootId) <NEW_LINE> self.computeAlphas() <NEW_LINE> self.prune()
Prune the decision tree using reduced error pruning.
625941c463d6d428bbe444df
def exit_with_msg(self, msg, err): <NEW_LINE> <INDENT> print ('\n\nProgram Exiting! ' + msg) <NEW_LINE> if err: <NEW_LINE> <INDENT> print ('Error recieved: {}'.format(err)) <NEW_LINE> <DEDENT> if self._sock: <NEW_LINE> <INDENT> self._sock.close() <NEW_LINE> <DEDENT> exit(0)
Print message then exit.
625941c460cbc95b062c6532
def test_sibling(self): <NEW_LINE> <INDENT> assertIsNotSubdomainOf(self, b'foo.example.com', b'bar.example.com')
L{dns._isSubdomainOf} returns C{False} if the first name is a sibling of the second name.
625941c4f9cc0f698b1405ed
def _export_variable(self, **kwargs_for_variable): <NEW_LINE> <INDENT> export_graph = ops.Graph() <NEW_LINE> with export_graph.as_default(): <NEW_LINE> <INDENT> v = resource_variable_ops.ResourceVariable(3., **kwargs_for_variable) <NEW_LINE> with session_lib.Session() as session: <NEW_LINE> <INDENT> session.run([v.init...
A 1.x SavedModel with a single variable.
625941c40c0af96317bb81d8
def _extract_result(self, response): <NEW_LINE> <INDENT> return ActionServerResult.translate_from_rpc(response.action_server_result)
Returns the response status and description
625941c4baa26c4b54cb1111
@cli.command("init") <NEW_LINE> def init(): <NEW_LINE> <INDENT> title("Init Mambo...") <NEW_LINE> mambo_conf = os.path.join(CWD, Mambo.config_yml) <NEW_LINE> if os.path.isfile(mambo_conf): <NEW_LINE> <INDENT> error_exit("Mambo is already initialized in '%s'. Or delete 'mambo.yml' if it's a mistake " % CWD) <NEW_LINE> <...
Initialize Mambo in the current directory
625941c43346ee7daa2b2d5b
def show_menu(self, arg=None, menuw=None): <NEW_LINE> <INDENT> mpd_menu = self.create_menu() <NEW_LINE> menuw.pushmenu(mpd_menu) <NEW_LINE> menuw.refresh()
this displays the menu
625941c44f6381625f114a2b
def pun_setcookie(response, user_id, password, expire): <NEW_LINE> <INDENT> password_hash = forum_hmac(password, FLUXBB_COOKIE_SEED + '_password_hash') <NEW_LINE> cookie_hash = forum_hmac('{0}|{1}'.format(user_id, expire), FLUXBB_COOKIE_SEED + '_cookie_hash') <NEW_LINE> forum_setcookie( response, FLUXBB_COOKIE_NAME, '{...
Wrapper around forum_setcookie.
625941c407d97122c4178878
def clean_docs(docs): <NEW_LINE> <INDENT> docs_clean = [] <NEW_LINE> for d in docs: <NEW_LINE> <INDENT> document_test = re.sub(r'[^\x00-\x7F]+', ' ', d) <NEW_LINE> document_test = re.sub(r'@\w+', '', document_test) <NEW_LINE> document_test = document_test.lower() <NEW_LINE> document_test = re.sub(r'[%s]' % re.escape(st...
Clean up all the documents in order to simplify search thru them
625941c4004d5f362079a324
def fitfunc_3d_with_offdiagonal_terms(params, q, data=None): <NEW_LINE> <INDENT> norm = params['norm'].value <NEW_LINE> lam = params['lam'].value <NEW_LINE> r_out = params['r_out'].value <NEW_LINE> r_long = params['r_long'].value <NEW_LINE> r_side = params['r_side'].value <NEW_LINE> rr = np.array([r_out, r_side, r_long...
Do 3D Gaussian fit of data, including R_{os}, R_{ol}, R_{sl} terms in fit. .. math:: CF(\vec{q}) = NORM(1 + λ exp( -((qo * [Ro])^2 + (qs * [Rs])^2 + (ql * [Rl])^2 + 2 * qo * qs * [Ros]^2 + 2 * qo * ql * [Rol]^2+ 2 * qs * ql * [Rsl]^2) )) params: norm - "global" normalization factor (unitless) lam...
625941c4be383301e01b5479
def test_visit_from_form_with_cookie_fallback(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> config.update({'visit.source': 'form,cookie'}) <NEW_LINE> testutil.create_request("/") <NEW_LINE> first_key = cherrypy.response.body[0].strip() <NEW_LINE> morsel = cherrypy.response.simple_cookie[self.cookie_name] <NEW_LIN...
Test if visit key is retrieved from cookie if not found in params.
625941c473bcbd0ca4b2c066
def serialize_numpy(self, buff, numpy): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> buff.write(_struct_b.pack(self.votation)) <NEW_LINE> <DEDENT> except struct.error as se: self._check_types(se) <NEW_LINE> except TypeError as te: self._check_types(te)
serialize message with numpy array types into buffer :param buff: buffer, ``StringIO`` :param numpy: numpy python module
625941c4be7bc26dc91cd5f2
def test_policy_data(self): <NEW_LINE> <INDENT> cage = congress.dse.d6cage.d6Cage() <NEW_LINE> cage.loadModule("TestDriver", helper.data_module_path( "../tests/datasources/test_driver.py")) <NEW_LINE> cage.loadModule("TestPolicy", helper.policy_module_path()) <NEW_LINE> cage.createservice(name="data", moduleName="TestD...
Test policy properly inserts data and processes it normally.
625941c4442bda511e8be40a
def get_services(self): <NEW_LINE> <INDENT> service_array = [] <NEW_LINE> for container in self.get_containers(): <NEW_LINE> <INDENT> if 'services' in container['ContainerRegistration']: <NEW_LINE> <INDENT> for service in container['ContainerRegistration']['services']: <NEW_LINE> <INDENT> service_array.append(service) ...
Returns the services registered in DPE Returns: service_array (Array): array with the services information
625941c4ab23a570cc250171
def create( self, publisher_id, offer_id, plan_id, parameters, custom_headers=None, raw=False, **operation_config): <NEW_LINE> <INDENT> url = '/subscriptions/{subscriptionId}/providers/Microsoft.MarketplaceOrdering/offerTypes/{offerType}/publishers/{publisherId}/offers/{offerId}/plans/{planId}/agreements/current' <NEW_...
Save marketplace terms. :param publisher_id: Publisher identifier string of image being deployed. :type publisher_id: str :param offer_id: Offer identifier string of image being deployed. :type offer_id: str :param plan_id: Plan identifier string of image being deployed. :type plan_id: str :param parameters: Paramete...
625941c4046cf37aa974cd39
def test_list_of_techniques(self): <NEW_LINE> <INDENT> request = self.get_request( django.urls.reverse('OasisMembers:techniques')) <NEW_LINE> response = views.techniques(request) <NEW_LINE> self.assertContains( response, '<a href="/technique/1/">Awakening</a>', html=True) <NEW_LINE> self.assertContains( response, '<tit...
Test the view with a list of techniques.
625941c415baa723493c3f64
def test_success(self): <NEW_LINE> <INDENT> command = "python convertor.py sample.py --reports=n" <NEW_LINE> expected_result = "%s/sample.py:6:0: [C] More than one statement on a single line\n" % PROJECT_FOLDER <NEW_LINE> pros = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE) <NEW_LINE> result = pros.stdo...
successful scenario
625941c407f4c71912b11471
def pre_process(region_in_lines, view): <NEW_LINE> <INDENT> processed_result = defaultdict(list) <NEW_LINE> for line in region_in_lines: <NEW_LINE> <INDENT> content = view.substr(line) <NEW_LINE> if spaceIgnored(): <NEW_LINE> <INDENT> content = content.strip() <NEW_LINE> <DEDENT> if caseIgnored(): <NEW_LINE> <INDENT> c...
Counts line occurrences of a view using a hash. The lines are stripped and tested before count.
625941c4d8ef3951e324352d
def run(): <NEW_LINE> <INDENT> import Zope2.Startup <NEW_LINE> starter = Zope2.Startup.get_starter() <NEW_LINE> opts = _setconfig() <NEW_LINE> starter.setConfiguration(opts.configroot) <NEW_LINE> try: <NEW_LINE> <INDENT> starter.prepare() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> starter.shutdown() <NEW_LINE> rai...
Start a Zope instance
625941c4fb3f5b602dac3682
def sizeof_fmt(num, suffix='b'): <NEW_LINE> <INDENT> for unit in ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z']: <NEW_LINE> <INDENT> if abs(num) < 1024.0: <NEW_LINE> <INDENT> return "%3.1f %s%s" % (num, unit, suffix) <NEW_LINE> <DEDENT> num /= 1024.0 <NEW_LINE> <DEDENT> return "%.1f%s%s" % (num, 'Yi', suffix)
Readable file size :param num: Bytes value :type num: int :param suffix: Unit suffix (optionnal) default = o :type suffix: str :rtype: str
625941c4b830903b967e98fd
def fuzzy_match(self, other): <NEW_LINE> <INDENT> magic, fuzzy = False, False <NEW_LINE> try: <NEW_LINE> <INDENT> magic = self.alias == other.magic <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> if '.' in self.alias: <NEW_LINE> <INDENT> major = self.alias.split('.')[0] <NEW_LINE...
Given another token, see if either the major alias identifier matches the other alias, or if magic matches the alias.
625941c4f548e778e58cd56d
def gtid_enabled(self): <NEW_LINE> <INDENT> if self.master and self.master.supports_gtid() != "ON": <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> for slave_dict in self.slaves: <NEW_LINE> <INDENT> slave = slave_dict['instance'] <NEW_LINE> if slave is None or not slave.is_alive(): <NEW_LINE> <INDENT> continue <NE...
Check if topology has GTID turned on. This method check if GTID mode is turned ON for all servers in the replication topology, skipping the check for not available servers. Returns bool - True = GTID_MODE=ON for all available servers (master and slaves) in the replication topology..
625941c46fece00bbac2d72d
def test_xml_string_roundtrip(self): <NEW_LINE> <INDENT> forcefield_1 = ForceField(xml_simple_ff) <NEW_LINE> string_1 = forcefield_1.to_string("XML") <NEW_LINE> assert " " in string_1 <NEW_LINE> assert "\t" not in string_1 <NEW_LINE> forcefield_2 = ForceField(string_1) <NEW_LINE> string_2 = forcefield_2.to_string("X...
Test writing a ForceField to an XML string
625941c4435de62698dfdc3c
def GetStaticCloseness(t, model='SECOND'): <NEW_LINE> <INDENT> if model =='FIRST': <NEW_LINE> <INDENT> D = Paths.GetFirstOrderDistanceMatrix(t) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> D = Paths.GetSecondOrderDistanceMatrix(t, model) <NEW_LINE> <DEDENT> name_map = Utilities.firstOrderNameMap( t ) <NEW_LINE> closen...
Computes closeness centralities of nodes based on the first- or second-order time-aggregated network. @param t: The temporal network instance for which closeness centralities will be computed @param model: either C{"FIRST"}, C{"SECOND"} or C{"SECONDNULL"}, where C{"SECOND"} is the the default value.
625941c4b7558d58953c4f07
def set_frame_period(self, frame_period): <NEW_LINE> <INDENT> self.set_attribute_value("FrameTime",frame_period*1E3,error_on_missing=False) <NEW_LINE> return self.get_frame_period()
Set frame period (time between two consecutive frames in the internal trigger mode)
625941c456b00c62f0f14649
def write_NBHs_to_csv(self, timestep, results_path): <NEW_LINE> <INDENT> NBH_csv_file = os.path.join(results_path, "NBHs_time_%s.csv"%timestep) <NEW_LINE> out_file = open(NBH_csv_file, "wb") <NEW_LINE> csv_writer = csv.writer(out_file) <NEW_LINE> csv_writer.writerow(["nid", "rid", "x", "y", "numpsns", "numhs", "agveg",...
Writes a list of neighborhoods, with a header row, to CSV.
625941c450485f2cf553cd89
def _mean_attentive_vectors(self, x2, cosine_matrix): <NEW_LINE> <INDENT> expanded_cosine_matrix = cosine_matrix.unsqueeze(-1) <NEW_LINE> x2 = x2.unsqueeze(1) <NEW_LINE> weighted_sum = (expanded_cosine_matrix * x2).sum(2) <NEW_LINE> sum_cosine = (cosine_matrix.sum(-1) + self.epsilon).unsqueeze(-1) <NEW_LINE> attentive_...
Mean attentive vectors. Calculate mean attentive vector for the entire sentence by weighted summing all the contextual embeddings of the entire sentence # Arguments x2: sequence vectors, (batch_size, x2_timesteps, embedding_size) cosine_matrix: cosine similarities matrix of x1 and x2, (batch_...
625941c456ac1b37e62641c2
def pyrange(start=0, stop=0, step=1): <NEW_LINE> <INDENT> return (list(range(start, stop, step)),)
range(start, stop, step)
625941c4a219f33f3462895c
def _common_build(self): <NEW_LINE> <INDENT> bitbake('mtools-native core-image-minimal')
Common build for test cases: 1445 , XXXX
625941c49f2886367277a87f
def test_incomplete_sentence(self): <NEW_LINE> <INDENT> testsentence = '$GPRMC,165629.00,V,,' <NEW_LINE> self.assertFalse(sentence.calculate_nmea_checksum(testsentence))
feed in an incomplete NMEA sentence with no checksum should return False as we are unable to calculate the checksum as there isn't one!
625941c4925a0f43d2549e66
def get_parameter(self, name, file_content): <NEW_LINE> <INDENT> return file_content.partition(name)[2].partition('\n')[0][1:]
Get the parameter name in a file (file_content)
625941c42c8b7c6e89b357b2
def get_data(key, default=None): <NEW_LINE> <INDENT> _session=Session(expire_on_commit=False) <NEW_LINE> _data=_session.query(Data).get(key.upper()) <NEW_LINE> if _data: <NEW_LINE> <INDENT> Session.remove() <NEW_LINE> f=pydoc.locate(_data.type_of) <NEW_LINE> return f(_data.value) <NEW_LINE> <DEDENT> Session.remove() <N...
Get data from database Returns the default value if key does not exists
625941c44e696a04525c943c
def initConnection(self, ipAddress): <NEW_LINE> <INDENT> sock = None <NEW_LINE> try: <NEW_LINE> <INDENT> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <NEW_LINE> <DEDENT> except socket.error: <NEW_LINE> <INDENT> self.connected = False <NEW_LINE> <DEDENT> sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR...
Initialisation du socket permettant de communiquer avec le serveur :return: Le socket :rtype: socket.socket
625941c4711fe17d8254235f
def get_one(self, sql_command, cmd_param=None): <NEW_LINE> <INDENT> if cmd_param: <NEW_LINE> <INDENT> count = self._mysql_cursor.execute(sql_command, cmd_param) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> count = self._mysql_cursor.execute(sql_command) <NEW_LINE> <DEDENT> if count: <NEW_LINE> <INDENT> sql_result = se...
"Get one sql command execute result. Args: sql_command: sql command cmd_param : sql command paramaters Returns: dict
625941c4cc40096d61595941
def test_Ancestors(self): <NEW_LINE> <INDENT> result = self.tx['7'].ancestors() <NEW_LINE> tax_ids = [taxon_obj.TaxonId for taxon_obj in result] <NEW_LINE> self.assertEqual(tax_ids, [6, 2, 1])
NcbiTaxonomy should support Ancestors correctly, not incl. self
625941c4a4f1c619b28b002d
def create_enrollment_track_partition(course): <NEW_LINE> <INDENT> enrollment_track_scheme = UserPartition.get_scheme("enrollment_track") <NEW_LINE> partition = enrollment_track_scheme.create_user_partition( id=1, name="Test Enrollment Track Partition", description="Test partition for segmenting users by enrollment tra...
Create an EnrollmentTrackUserPartition instance for the given course.
625941c471ff763f4b549679
def createImageLinks(self, srcImgPath, imgUUID): <NEW_LINE> <INDENT> sdRunDir = os.path.join(constants.P_VDSM_STORAGE, self.sdUUID) <NEW_LINE> fileUtils.createdir(sdRunDir) <NEW_LINE> imgRunDir = os.path.join(sdRunDir, imgUUID) <NEW_LINE> self.log.debug("Creating symlink from %s to %s", srcImgPath, imgRunDir) <NEW_LINE...
qcow chain is build by reading each qcow header and reading the path to the parent. When creating the qcow layer, we pass a relative path which allows us to build a directory with links to all volumes in the chain anywhere we want. This method creates a directory with the image uuid under /var/run/vdsm and creates sym ...
625941c463f4b57ef000110e
def animal(root): <NEW_LINE> <INDENT> start = time.time() <NEW_LINE> task_path = assert_dirs(root, 'chinese_lexicon_animal') <NEW_LINE> url = "https://raw.githubusercontent.com/Hourout/datasets/master/nlp/chinese_lexicon/chinese_lexicon_animal.txt" <NEW_LINE> rq.table(url, path_join(task_path, 'chinese_lexicon_animal.t...
Chinese lexicon animal datasets. datasets url:`https://github.com/fighting41love/funNLP` chinese_lexicon_animal dataset contains 17200+ samples. Data storage directory: root = `/user/.../mydata` chinese_lexicon_animal data: `root/chinese_lexicon_animal/chinese_lexicon_animal.txt` Args: root: str, Store the abso...
625941c429b78933be1e569f
def consecutives(seq, n=2): <NEW_LINE> <INDENT> prevs = [] <NEW_LINE> for item in seq: <NEW_LINE> <INDENT> prevs.append(item) <NEW_LINE> if len(prevs) == n: <NEW_LINE> <INDENT> yield tuple(prevs) <NEW_LINE> prevs.pop(0)
>>> [''.join(t) for t in consecutives('abcd')] ['ab', 'bc', 'cd'] >>> [''.join(t) for t in consecutives('abcd', 3)] ['abc', 'bcd'] >>> [''.join(t) for t in consecutives('abcd', 5)] # seq is too short []
625941c423849d37ff7b3080
def Display(self, args, result): <NEW_LINE> <INDENT> if not result: <NEW_LINE> <INDENT> resource_printer.Print(resources={'key': args.key, 'success': True}, print_format=args.format or 'yaml', out=log.out)
Display prints information about what just happened to stdout. Args: args: The same as the args in Run. result: an Operation object Raises: TypeError: if result is not of type Operation
625941c4379a373c97cfab35
def test_get_orgs_with_err(self): <NEW_LINE> <INDENT> orgs_url = 'https://{sat_host}:{port}/katello/api/v2/organizations' <NEW_LINE> with requests_mock.Mocker() as mocker: <NEW_LINE> <INDENT> url = construct_url(orgs_url, '1.2.3.4') <NEW_LINE> jsonresult = {'results': [{'id': 1}, {'id': 7}, {'id': 8}], 'per_page': 100}...
Test the method to get orgs with err.
625941c485dfad0860c3ae4b
def gc(self, lifetime): <NEW_LINE> <INDENT> file_lifetime = time.mktime(datetime.datetime.now().timetuple()) - lifetime <NEW_LINE> for filename in os.listdir(self.path): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> filepath = self._session_file(filename) <NEW_LINE> m = os.stat(filepath) <NEW_LINE> if m.st_mtime > file_...
ガーベジコレクション
625941c4e76e3b2f99f3a7fe
def report_extended_data_type_enum(status): <NEW_LINE> <INDENT> if status == 'note': <NEW_LINE> <INDENT> return ExtendedReportDataType.NOTE <NEW_LINE> <DEDENT> elif status == 'macro': <NEW_LINE> <INDENT> return ExtendedReportDataType.MACRO <NEW_LINE> <DEDENT> elif status == 'fixit': <NEW_LINE> <INDENT> return ExtendedR...
Returns the given extended report data Thrift enum value.
625941c4e76e3b2f99f3a7ff
def test_build_read_gmms(self): <NEW_LINE> <INDENT> mdl = IMP.Model() <NEW_LINE> topology_file=self.get_input_file_name("topology.txt") <NEW_LINE> t=IMP.pmi.topology.TopologyReader(topology_file) <NEW_LINE> self.assertEqual(t.defaults['gmm_dir'],'./') <NEW_LINE> bm = IMP.pmi.macros.BuildModel(mdl, component_topologies=...
Test building with macro BuildModel using a topology file
625941c4cad5886f8bd26fca
def p_var_assign(p): <NEW_LINE> <INDENT> obj = None <NEW_LINE> if(len(p) == 5): <NEW_LINE> <INDENT> if p[4] in var: <NEW_LINE> <INDENT> value = var[p[4]][1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> value = p[4] <NEW_LINE> <DEDENT> type = p[1] <NEW_LINE> if(type == 'vid'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDEN...
assign : TYPE ID EQUALS type_value | ID EQUALS id_value
625941c424f1403a92600b58
def get_staticfile_response(self, request, path): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return serve(request, path, document_root=settings.STATIC_ROOT) <NEW_LINE> <DEDENT> except Http404: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return None
This method takes a path and tries to serve the content for the given path. Will return None if serving fails.
625941c4507cdc57c6306cc8
def test_domains(runner, make_app, app_id): <NEW_LINE> <INDENT> domain = '{}.example.com'.format(app_id) <NEW_LINE> result = runner.invoke(entry, ['domains:add', domain]) <NEW_LINE> assert result.exit_code == 0 <NEW_LINE> result = runner.invoke(entry, ['domains']) <NEW_LINE> assert result.exit_code == 0 <NEW_LINE> asse...
@type runner: click.testing.CliRunner
625941c467a9b606de4a7eab
def rand_family(self, org): <NEW_LINE> <INDENT> all_families = list(Family.objects.filter(organizationfamilylink__organization=org)) <NEW_LINE> if len(all_families) == 0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return random.choice(all_families)
returns a random Family record linked to the given org. :param org: :return:
625941c4be8e80087fb20c35
def post(self, request, *args, **kwargs): <NEW_LINE> <INDENT> upc_code = request.POST.get('upc_code', 'NONE') <NEW_LINE> api_key = os.environ.get('api_key', '') <NEW_LINE> api_id = os.environ.get('api_id', '') <NEW_LINE> try: <NEW_LINE> <INDENT> obj = Product.objects.filter(gtin_code=upc_code) <NEW_LINE> context = {'st...
Custom method for listview
625941c45510c4643540f3d9
def generate_emotion_profile_from_response(response): <NEW_LINE> <INDENT> emotion_profile = generate_empty_emotion_profile() <NEW_LINE> emotion_scaler = 0 <NEW_LINE> response = response['hits']['hits'] <NEW_LINE> if len(response) == 0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> for hit in response: <NEW_LINE> ...
:param response: elasticsearch response :return: dict of emotion profile
625941c4627d3e7fe0d68e3f
def task91(self): <NEW_LINE> <INDENT> self.ex("SELECT account_id , cust_id, avail_balance, product_cd " "FROM account " "WHERE product_cd IN (SELECT product_cd " " FROM product " " WHERE product_type_cd='LOAN')")
Extracts account id, customer id and available balance where product type is a loan.
625941c48e05c05ec3eea364
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, ServicePackageMetadata): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941c41d351010ab855b0d
def __init__(self, frame=None, service=None, serviceLength=0): <NEW_LINE> <INDENT> if frame is not None and service is not None: <NEW_LINE> <INDENT> raise KNXnetIPHeaderValueError("can't give both frame and service type") <NEW_LINE> <DEDENT> if frame is not None: <NEW_LINE> <INDENT> frame = bytearray(frame) <NEW_LINE> ...
Creates a new KNXnet/IP header Header can be loaded either from frame or from sratch @param frame: byte array with contained KNXnet/IP frame @type frame: sequence @param service: service identifier @type service: int @param serviceLength: length of the service structure @type serviceLength: int @raise KnxNetIPHead...
625941c4d10714528d5ffcd2