code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def parse_file(filename): <NEW_LINE> <INDENT> with open(filename, "r") as f: <NEW_LINE> <INDENT> data = [[float(y) for y in x.strip().split(" ")] for x in f] <NEW_LINE> data[0] = [int(x) for x in data[0]] <NEW_LINE> return data
This function is provided to you as an example of the preprocessing we do prior to calling run_train_test
625941cd99fddb7c1c9de4ad
def dialog_info(self, title, message): <NEW_LINE> <INDENT> box = QMessageBox() <NEW_LINE> box.setWindowTitle(title) <NEW_LINE> box.setText(message) <NEW_LINE> box.exec_()
Generic Qt Message box Arg 1: the window title <string> Arg 2: the message <string>
625941cd10dbd63aa1bd2cc0
def drop_question(self, name): <NEW_LINE> <INDENT> if name in self.keys(): <NEW_LINE> <INDENT> del self[name] <NEW_LINE> self.columns = list(self.keys()) <NEW_LINE> self._update_log(command='remove question', column=name)
Removes a dictionary entry for the specified column. Parameters ---------- name: str The name of the dictionary column to be returned
625941cdd18da76e235325f3
def enhance_projs_aps_1id(imgstack, median_ks=5, ncore=None): <NEW_LINE> <INDENT> ncore = mproc.mp.cpu_count()-1 if ncore is None else ncore <NEW_LINE> tmp = [] <NEW_LINE> with cf.ProcessPoolExecutor(ncore) as e: <NEW_LINE> <INDENT> for n_img in range(imgstack.shape[0]): <NEW_LINE> <INDENT> tmp.append(e.submit(_enhance...
Enhance the projection images with weak contrast collected at APS 1ID This filter uses a median fileter (will be switched to enhanced recursive median fileter, ERMF, in the future) for denoising, and a histogram equalization for dynamic range adjustment to bring out the details. Parameters ---------- imgstack : np....
625941cda8ecb033257d31ea
def call(self, inputs, reset_mask, initial_state=None): <NEW_LINE> <INDENT> if initial_state is None and self.dtype is None: <NEW_LINE> <INDENT> raise ValueError("Must provide either dtype or initial_state") <NEW_LINE> <DEDENT> inputs = tf.nest.map_structure(common.transpose_batch_time, inputs) <NEW_LINE> inputs_flat =...
Perform the computation. Args: inputs: A tuple containing tensors in batch-major format, each shaped `[batch_size, n, ...]`. reset_mask: A `bool` matrix shaped `[batch_size, n]`, describing the locations for which the state will be reset to zeros. Typically this is the value `time_steps.is_first()` wh...
625941cd3617ad0b5ed68014
def columns(self) -> [str]: <NEW_LINE> <INDENT> return ()
Return list of columns required/defined by this statement.
625941cdb5575c28eb68e11d
def test_merge(): <NEW_LINE> <INDENT> list1 = [13, 11, 9, 7, 5, 3, 1] <NEW_LINE> list2 = [14, 12, 10, 8, 6, 4, 2] <NEW_LINE> result = list(util.merge([list1, list2])) <NEW_LINE> assert result[::-1] == sorted(result)
This should return a sorted (from greatest to least) merged list from list1 and list2.
625941cdbde94217f3682f0e
def get_build_source_upload_url( self, resource_group_name, registry_name, custom_headers=None, raw=False, **operation_config): <NEW_LINE> <INDENT> api_version = "2018-02-01-preview" <NEW_LINE> url = self.get_build_source_upload_url.metadata['url'] <NEW_LINE> path_format_arguments = { 'subscriptionId': self._serialize....
Get the upload location for the user to be able to upload the source. :param resource_group_name: The name of the resource group to which the container registry belongs. :type resource_group_name: str :param registry_name: The name of the container registry. :type registry_name: str :param dict custom_headers: header...
625941cd97e22403b379d0b6
@blueprint.route('/delete/<use_cace_id>', methods=['GET', 'POST']) <NEW_LINE> def delete(use_cace_id): <NEW_LINE> <INDENT> if not ObjectId.is_valid(use_cace_id): <NEW_LINE> <INDENT> return init_return({}, sucess=False, error="用例id参数错误", errorCode=1001) <NEW_LINE> <DEDENT> result = UseCase.objects(id=ObjectId(use_cace_i...
5 根据用例id :param: use_cace_id :return:
625941cdfb3f5b602dac37b0
def test_video_task_chain(mocker): <NEW_LINE> <INDENT> def ctx(): <NEW_LINE> <INDENT> return celery.app.task.Context( { "lang": "py", "task": "cloudsync.tasks.stream_to_s3", "id": "1853b857-84d8-4af4-8b19-1c307c1e07d5", "chain": [ { "task": "cloudsync.tasks.transcode_from_s3", "args": [351], "kwargs": {}, "options": {"...
Test that video task get_task_id method returns the correct id from the chain.
625941cd32920d7e50b282ed
def main(thread, email, pwd, links, names, file, save_path, count_total, counts): <NEW_LINE> <INDENT> print("\033[H\033[J") <NEW_LINE> one_thread = detect_one_thread(counts, links, 0) <NEW_LINE> start = FileJoker(email, pwd, links, names, file, save_path, thread, count_total, one_thread) <NEW_LINE> with futures.ThreadP...
for e, url in zip(counts, links): FileJoker(email, pwd, url, names, file, save_path, thread, count_total, e)
625941cd0a366e3fb873e937
def draw_node(draw, tree, x, y): <NEW_LINE> <INDENT> if tree.results is None: <NEW_LINE> <INDENT> w1 = get_width(tree.tb) * 100 <NEW_LINE> w2 = get_width(tree.fb) * 100 <NEW_LINE> left = x - (w1 + w2) / 2 <NEW_LINE> right = x + (w1 + w2) / 2 <NEW_LINE> draw.text((x - 20, y - 10), ('feature' + str(tree.col) + ':' + str(...
实际绘制决策树的节点,递归工作 :param draw: :param tree: :param x: :param y: :return:
625941cd5510c4643540f501
def do_zpj_distributions(root_dir, dir_append=""): <NEW_LINE> <INDENT> dir_names = ["ZPlusJets_Presel_q", "ZPlusJets_Presel_g", "ZPlusJets_Presel_unknown"][:2] <NEW_LINE> dir_names = [d+dir_append for d in dir_names] <NEW_LINE> root_file = cu.open_root_file(os.path.join(root_dir, qgc.DY_FILENAME)) <NEW_LINE> directorie...
Do plots comparing different jet flavs in z+jets region
625941cdadb09d7d5db6c8ac
def purchase_pr_with_haircut(self, haircut_perc=None): <NEW_LINE> <INDENT> if not haircut_perc: <NEW_LINE> <INDENT> return self.start_payment() <NEW_LINE> <DEDENT> return self.start_payment() * (1.0 - haircut_perc * 0.01)
Calculate repo start payment with haircut. Parameters ---------- haircut_perc: float, optional A float which specifies the haircut (in percent) of purchase price. Default is None. Returns ------- float The purchase price of repo. Examples -------- >>> repo_test = Repo(settlement=date(2020,7,15), maturit...
625941cd63d6d428bbe4460c
def write_data(uuid, data): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> CACHE.set( "{}{}".format(Keys.complete.value, uuid), codecs.decode( base64.b64encode(compress(codecs.encode( ujson.dumps(data), "utf-8", ))), "utf-8", ), timeout=EXPIRY, ) <NEW_LINE> <DEDENT> except Exception as error: <NEW_LINE> <INDENT> LOG.warn...
Try to store the data, log errors.
625941cd8a43f66fc4b54182
def _generate_level(self): <NEW_LINE> <INDENT> level = 0 <NEW_LINE> while True: <NEW_LINE> <INDENT> if random.random() <= 0.5: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> level += 1 <NEW_LINE> <DEDENT> return level
Private help method for insert. It generates the the level for an element to be inserted by randomness. The probability of level x is (1/2)^x.
625941cda79ad161976cc263
def generate_emeny(self, position=None): <NEW_LINE> <INDENT> if position is None: <NEW_LINE> <INDENT> position = self.field.get_random_empty_cell() <NEW_LINE> self.enemy = position <NEW_LINE> <DEDENT> self.field[position] = CellType.SNAKE_BODY <NEW_LINE> if np.random.random() > 0.2: <NEW_LINE> <INDENT> if (self.field[p...
Generate a new fruit at a random unoccupied cell.
625941cd44b2445a339321b3
def GetAttributes(self, pane): <NEW_LINE> <INDENT> attrs = [] <NEW_LINE> attrs.extend([pane.window, pane.frame, pane.state, pane.dock_direction, pane.dock_layer, pane.dock_pos, pane.dock_row, pane.dock_proportion, pane.floating_pos, pane.floating_size, pane.best_size, pane.min_size, pane.max_size, pane.caption, pane.na...
Returns all the attributes of a L{AuiPaneInfo}. :param `pane`: a L{AuiPaneInfo} instance.
625941cda4f1c619b28b0156
def strictly_increasing(L): <NEW_LINE> <INDENT> return all(x<y for x, y in zip(L, L[1:]))
Check for strictly increasing monotonously in L
625941cdd4950a0f3b08c46c
def class_prior(Y): <NEW_LINE> <INDENT> arr = [0] * 2 <NEW_LINE> for ele in Y: <NEW_LINE> <INDENT> if ele != 0: <NEW_LINE> <INDENT> arr[1] += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> arr[0] += 1 <NEW_LINE> <DEDENT> <DEDENT> nparr = np.array(arr) <NEW_LINE> PY = nparr/float(len(Y)) <NEW_LINE> return PY
Estimate the prior probability of Class labels: P(Class=y). Here we assume this is binary classification problem. Input: Y : the labels of training instances, an integer numpy vector of length n. Here n is the number of training instances. Each Y[i] = 0 or 1. Output: PY: the prior probability of each ...
625941cdec188e330fd5a8bc
def redo(self): <NEW_LINE> <INDENT> if not self.can_redo(): <NEW_LINE> <INDENT> LOGGER.info("Can't redo turn: stack is empty") <NEW_LINE> return <NEW_LINE> <DEDENT> assert self._start_time is not None <NEW_LINE> LOGGER.info('Redo turn') <NEW_LINE> with utils.at_exit(self._end_change): <NEW_LINE> <INDENT> prev = self._s...
Повтор хода
625941cde5267d203edcddba
def recommended_move(self, depth=2): <NEW_LINE> <INDENT> score, moves = ai.minimax.alphabeta(self, self.current_player, 0, depth, -float('inf'), float('inf')) <NEW_LINE> return random.choice(moves)
Use minimax ai to determine a move :param depth: Depth to search in minimax tree :return: Move
625941cd5166f23b2e1a5276
def checkout(self, identifier=None): <NEW_LINE> <INDENT> super().checkout() <NEW_LINE> if not identifier: <NEW_LINE> <INDENT> identifier = self.default_branch or self.fallback_branch <NEW_LINE> <DEDENT> identifier = self.find_ref(identifier) <NEW_LINE> code, out, err = self.checkout_revision(identifier) <NEW_LINE> self...
Checkout to identifier or latest.
625941cd796e427e537b06e3
def get_position(self): <NEW_LINE> <INDENT> return list(self.position)
Get the position of the object
625941cd91f36d47f21ac610
def test_globWin32(self): <NEW_LINE> <INDENT> self.assertGlob( ['a', 'a[b]c'], ['[ab]', 'a[b]c'], platform='win32')
On Windows globbing will only occur if the glob argument is not the name of an existing file, in which case the existing file name will be the only result of globbing that argument.
625941cd6fece00bbac2d85c
@with_setup_args(setup) <NEW_LINE> def three_particle_integral_light_test(params): <NEW_LINE> <INDENT> photon = Particle(**SMP.photon) <NEW_LINE> neutrino_e = Particle(**SMP.leptons.neutrino_e) <NEW_LINE> sterile = Particle(**NuP.dirac_sterile_neutrino(mass=100 * UNITS.MeV)) <NEW_LINE> neutral_pion = Particle(**SMP.had...
If M_N < M_pi, there should be integrals for the reactions: N + anti-nu_e <--> pion nu_e + anti-N <--> pion pi^0 <--> anti-nu_e + N pi^0 <--> nu_e + anti-N
625941cdadb09d7d5db6c8ad
@check_path <NEW_LINE> def config(path): <NEW_LINE> <INDENT> fname = os.path.join(path, BASE_GRM_DIR, CONFIG_FILE) <NEW_LINE> open_file(os.path.abspath(fname))
Edit the config.
625941cd1f037a2d8b94631b
def ev(self, x): <NEW_LINE> <INDENT> answer = 0 <NEW_LINE> for i in range(len(self.coefficients) - 1, -1, -1): <NEW_LINE> <INDENT> answer *= x <NEW_LINE> answer += self.coefficients[i] <NEW_LINE> <DEDENT> return answer
Returns a(x)
625941cdf548e778e58cd69b
@channels_endpoint.route('/resume/<int:channel_id>', methods = ['POST']) <NEW_LINE> @login_required <NEW_LINE> def resume(channel_id): <NEW_LINE> <INDENT> channel = get_channel(channel_id, must_owner = True) <NEW_LINE> if not (channel.is_published or channel.is_calculating): <NEW_LINE> <INDENT> raise BadRequest('cannot...
恢复频道状态, 避免因客户端网络原因造成的断流而错误的将频道终结. :param channel_id: 要恢复状态的频道id :return:
625941cd627d3e7fe0d68f6d
def analyze(self, text): <NEW_LINE> <INDENT> tokenizer = nltk.tokenize.TweetTokenizer() <NEW_LINE> tokens = tokenizer.tokenize(text) <NEW_LINE> score = 0 <NEW_LINE> for word in tokens: <NEW_LINE> <INDENT> word.lower() <NEW_LINE> word = word + '\n' <NEW_LINE> if word in self.positives: <NEW_LINE> <INDENT> score +=1 <NEW...
Analyze text for sentiment, returning its score.
625941cd4e4d5625662d44f5
def test_get(self): <NEW_LINE> <INDENT> self.assertEqual(200, self.response_get.status_code)
Check response of get scheduling is 200 ok
625941cd442bda511e8be536
def neighbors(graph,v): <NEW_LINE> <INDENT> return sorted(graph.neighbors(v))
Return the ordered list of neighbors ov a vertex Parameters ---------- graph : input graph v : vertex
625941cd596a897236089bde
def gradient_memory_mbs(): <NEW_LINE> <INDENT> start_time0 = time.perf_counter() <NEW_LINE> start_time = start_time0 <NEW_LINE> tf.reset_default_graph() <NEW_LINE> tf.set_random_seed(1) <NEW_LINE> train_op, loss = create_train_op_and_loss() <NEW_LINE> print("Graph construction: %.2f ms" %(1000*(time.perf_counter()-star...
Evaluates gradient, prints peak memory.
625941cd0a366e3fb873e938
def _new_spline_to_blender_curve(self, curve_object_data, is_cyclic): <NEW_LINE> <INDENT> style = self._calculate_style_in_context() <NEW_LINE> if style["fill"] != "none": <NEW_LINE> <INDENT> is_cyclic = True <NEW_LINE> <DEDENT> curve_object_data.splines.new("BEZIER") <NEW_LINE> spline = curve_object_data.splines[-1] <...
Adds a new spline to an existing Blender curve object and returns a reference to the spline.
625941cd60cbc95b062c6661
def readNCNRSensitivity(inputfile): <NEW_LINE> <INDENT> f = open(inputfile, 'rb') <NEW_LINE> data = f.read() <NEW_LINE> f.close() <NEW_LINE> dataformatstring = '<65600s' <NEW_LINE> (rawdatastring,) = struct.unpack_from(dataformatstring, data, offset=516) <NEW_LINE> detdata = np.empty(16384) <NEW_LINE> a = 0 <NEW_LINE> ...
Read VAX format SANS sensitivity file.
625941cd23849d37ff7b31ad
def connect(self): <NEW_LINE> <INDENT> self.client = Client( access_token=self.settings["access_token"], environment="production" ) <NEW_LINE> self.orders_api = self.client.orders <NEW_LINE> self.locations_api = self.client.locations
Create the client and necessary mini-apis if access_token is set.
625941cd26068e7796caedfd
def delete(self, table, dump): <NEW_LINE> <INDENT> dumpname = listkey(dump) <NEW_LINE> sql = 'delete from ' + table + ' where ' + dumpname + '=?' <NEW_LINE> return self.cs.execute(sql, [dump[dumpname]])
Delete table str, dump dict
625941cd4428ac0f6e5ba910
def pca(data, numcomp = .99): <NEW_LINE> <INDENT> from sklearn.decomposition import PCA <NEW_LINE> pca = PCA(n_components=numcomp, random_state = 52594) <NEW_LINE> pca.fit(data) <NEW_LINE> print("the explained variance ratio is ", pca.explained_variance_ratio_.sum()) <NEW_LINE> reduct = pca.transform(data) <NEW_LINE> p...
Performs PCA on the given data. :param data: DataFrame. The data to perform PCA on. :Param numcomp: Variable. As an int, the number of components to use when performing PCA. As a 2 decimal float < 1, the percentage of explained variance required when PCA is complete.
625941cd94891a1f4081bbc7
def valid_end_date(self, target_date): <NEW_LINE> <INDENT> return target_date
Returns a date that is valid for the end of the report. Arguments: target_date (datetime): The date you'd like examined Returns: datetime: A datetime made valid for the report based on the target_date argument.
625941cdd164cc6175782e6b
@rpc4django.rpcmethod( name='scheduling.sc.operational', signature=['String'], login_required=satnet_settings.JRPC_LOGIN_REQUIRED ) <NEW_LINE> def get_operational_slots(spacecraft_id): <NEW_LINE> <INDENT> return scheduling_serializers.serialize_sc_operational_slots( spacecraft_id )
JRPC method that permits obtaining all the OperationalSlots for all the channels that belong to the Spacecraft with the given identifier. :param spacecraft_id: Identifier of the spacecraft. :return: JSON-like structure with the data serialized.
625941cd30c21e258bdfa5bb
def analyze_parameters(args, parser): <NEW_LINE> <INDENT> payload = {} <NEW_LINE> payload['VmmControlType'] = args.Type <NEW_LINE> if args.Type == "Connect": <NEW_LINE> <INDENT> if args.Image is None: <NEW_LINE> <INDENT> parser.error('the following arguments are required: -i') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDE...
#==================================================================================== # @Method: Encapsulate the request body. # @Param:args,payload # @Return: # @date: 2017.8.1 11:09 #====================================================================================
625941cdeab8aa0e5d26dc76
def gethtml(self, url): <NEW_LINE> <INDENT> ob_openurl = OpenUrl(url) <NEW_LINE> code, html = ob_openurl.run() <NEW_LINE> if code == 200: <NEW_LINE> <INDENT> return html <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('open [{}] failed..'.format(url)) <NEW_LINE> return None
获取html文件 返回url的列表
625941cd6e29344779a62730
def next(self): <NEW_LINE> <INDENT> node = self._node <NEW_LINE> while node: <NEW_LINE> <INDENT> self._stack.append(node) <NEW_LINE> node = node.left <NEW_LINE> <DEDENT> node = self._stack.pop() <NEW_LINE> self._node = node.right <NEW_LINE> return node.val
:rtype: int
625941cd8c3a8732951584d9
def soft_reset(event): <NEW_LINE> <INDENT> NETWORK.controller.soft_reset()
Soft reset the controller.
625941cd5166f23b2e1a5277
def ffl_path(self, site, frametype): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.paths[(site, frametype)] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> self._find_paths() <NEW_LINE> return self.paths[(site, frametype)]
Returns the path of the FFL file for the given site and frametype Examples -------- >>> from gwpy.io.datafind import FflConnection >>> conn = FflConnection() >>> print(conn.ffl_path('V', 'V1Online')) /virgoData/ffl/V1Online.ffl
625941cd50812a4eaa59c440
def train_test(config, obj_classifier=None, teacher=None, model_params={}): <NEW_LINE> <INDENT> net = RelDN(config) <NEW_LINE> train_tester = TrainTester( net, config, {'images'}, obj_classifier, teacher ) <NEW_LINE> train_tester.train_test()
Train and test a net.
625941cdd486a94d0b98e264
def get_repeat_state(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.sp.current_playback()['repeat_state'] <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> raise ConnectionError('User is not connected to Spotify.')
Gets repeat state. :return: Repeat state, which can be 'track', 'context' or 'off'. :raises ConnectionError: User is not connected to Spotify.
625941cd498bea3a759b9bcd
def _handle_twilio_voice_end(self, request_context, chat, path, params): <NEW_LINE> <INDENT> context = {} <NEW_LINE> result = END_TEMPLATE.substitute(context) <NEW_LINE> return str(result)
Handle a request. Args: request_context: RequestContext object chat: Chat object path: http request path params: dict of http request params Returns: Twilio TwiML response Raises: TwilioHandlerException if the message is invalid and should be propagated.
625941cde8904600ed9f204b
def drpc(): <NEW_LINE> <INDENT> cppaths = [CLUSTER_CONF_DIR] <NEW_LINE> jvmopts = parse_args(confvalue("drpc.childopts", cppaths)) + [ "-Dlogfile.name=drpc.log", "-Dlog4j.configurationFile=" + os.path.join(get_log4j_conf_dir(), "cluster.xml") ] <NEW_LINE> exec_storm_class( "backtype.storm.daemon.drpc", jvmtype="-server...
Syntax: [storm drpc] Launches a DRPC daemon. This command should be run under supervision with a tool like daemontools or monit. See Distributed RPC for more information. (http://storm.incubator.apache.org/documentation/Distributed-RPC)
625941cd5fdd1c0f98dc0351
@pytest.fixture(scope='module') <NEW_LINE> def contained_evaluator() -> BooleanExpressionEvaluator: <NEW_LINE> <INDENT> token_evaluator = TokenContainedEvaluator(TOKENS_THAT_ARE_TRUE) <NEW_LINE> evaluator = BooleanExpressionEvaluator(token_evaluator, TOKEN_FORMAT) <NEW_LINE> return evaluator
Boolean expression evaluator using the TokenContainedEvaluator. All the tokens in TOKENS_THAT_ARE_TRUE will be evaluated to True and any other token to False.
625941ced18da76e235325f4
def is_empty(self): <NEW_LINE> <INDENT> return len(self.codelets()) == 0
Return True if the coderack is empty.
625941cd851cf427c661a62d
def parse_rec(filename, muscima, rescale_factor=1): <NEW_LINE> <INDENT> if not muscima: <NEW_LINE> <INDENT> tree = ET.parse(filename) <NEW_LINE> for size in tree.findall('size'): <NEW_LINE> <INDENT> width = int(round(float(size[0].text) * rescale_factor)) <NEW_LINE> height = int(round(float(size[1].text) * rescale_fact...
Parse a PASCAL VOC xml file
625941ce7cff6e4e81117aa4
@receiver(signals.post_save, sender=User) <NEW_LINE> def save_profile(sender, instance, **kwargs): <NEW_LINE> <INDENT> instance.userprofile.save()
the method responsible for saving each of the user profile
625941ce283ffb24f3c55a1f
def editListValues(self): <NEW_LINE> <INDENT> dialog = QListEditDialog(self._alias, self.controller, None) <NEW_LINE> if dialog.exec_() == QtGui.QDialog.Accepted: <NEW_LINE> <INDENT> values = dialog.getList() <NEW_LINE> self._alias.component.valueList = copy.copy(values) <NEW_LINE> self._str_values = [str(v) for v in v...
editListValues() -> None Show a dialog for editing the values
625941ce32920d7e50b282ee
def __init__(self, testcase, driver, logger): <NEW_LINE> <INDENT> super(FeiFanMembershipPage, self).__init__(testcase, driver, logger)
Constructor
625941ce5fcc89381b1e17dd
def __init__(self, name=None, parent=None): <NEW_LINE> <INDENT> super().__init__(name, parent)
Parameters ----------
625941ce627d3e7fe0d68f6e
def zero_normalize(image): <NEW_LINE> <INDENT> return (image - np.mean(image)) / np.std(image)
Zero-center and standardize image pixel values. :param image: (array) either one slice, met, or stack :return: (array) zero-centered and standardized image
625941ce7047854f462a1528
def deQueue(self): <NEW_LINE> <INDENT> if self.isEmpty(): <NEW_LINE> <INDENT> print("deQueue: ",self.queue, self.head, self.tail) <NEW_LINE> return False <NEW_LINE> <DEDENT> if self.tail==self.head: <NEW_LINE> <INDENT> self.tail=-1 <NEW_LINE> self.head=-1 <NEW_LINE> print("deQueue: ",self.queue, self.head, self.tail) <...
Delete an element from the circular queue. Return true if the operation is successful. :rtype: bool
625941ceb545ff76a8913f34
def get_groups(self): <NEW_LINE> <INDENT> from search.models import GroupMember <NEW_LINE> gm_objects = GroupMember.objects.filter(user=self.user) <NEW_LINE> groups = [] <NEW_LINE> for g in gm_objects: <NEW_LINE> <INDENT> groups.append(g.group) <NEW_LINE> <DEDENT> return groups
return list of groups that a user is in. Also can be used to see if a user is any group.
625941ceff9c53063f47c312
def main(): <NEW_LINE> <INDENT> args = create_parser().parse_args() <NEW_LINE> args = optionst.defaults(args) <NEW_LINE> try: <NEW_LINE> <INDENT> properties = propertyt.do_make_property(args.viewer_property, args.cbmc_property, args.srcdir) <NEW_LINE> print(properties) <NEW_LINE> <DEDENT> except UserWarning as error: <...
Properties checked by CBMC during property checking.
625941ced4950a0f3b08c46d
def parse(self, start_year=None, end_year=None, replace_missing_data=True): <NEW_LINE> <INDENT> if (end_year and start_year) and (end_year < start_year): <NEW_LINE> <INDENT> raise ValueError('end_year {} cannot be less than start_year {}'.format(end_year, start_year)) <NEW_LINE> <DEDENT> dly_delimiter = [11,4,2,4] + [5...
Parse the .dly file and store the resulting numpy array internally. Parameters ---------- start_year : int, optional Slice the initial data so only rows after start_year are stored end_year : int, optional Slice the initial data so only rows before end_year are stored replace_missing_data: bool, optional ...
625941ce711fe17d8254248a
def dcm_to_npy(dcm, norm=False): <NEW_LINE> <INDENT> def _dcm_to_npy(dcm, norm): <NEW_LINE> <INDENT> dcm_dtype = dcm.BitsAllocated <NEW_LINE> pixel = dcm.pixel_array.astype("float32") <NEW_LINE> if dcm.RescaleSlope != 1: <NEW_LINE> <INDENT> pixel *= dcm.RescaleSlope <NEW_LINE> <DEDENT> pixel += dcm.RescaleIntercept + 1...
Parameters ---------- dcm : Single Dicom object(2D), List Dicom object(3D) norm : If False :[0 4095]:, True :[0 1]:, default False Return ------ 2D or 3D CT Image(ndarray float32) Examples -------- >>> dcm = pydicom.dcmread("ex.dcm") >>> npy = dcm_to_npy(dcm, norm=True) >>> npy.min(), npy.max() >>> 0.0 1.0
625941ce656771135c3eb98d
def prop(attr): <NEW_LINE> <INDENT> class Inner: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.attr = attr <NEW_LINE> self.set_attr = None <NEW_LINE> self.delete_attr = None <NEW_LINE> <DEDENT> def __get__(self, instance, owner): <NEW_LINE> <INDENT> return self.attr(instance) <NEW_LINE> <DEDENT> def ...
This is the decorator version of the descriptor property. It decorates some attribute attr of the owner class.
625941ce460517430c3942a3
def helper(self, nums, start, paths, path, target): <NEW_LINE> <INDENT> if target < 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if target == 0: <NEW_LINE> <INDENT> paths.append(path[:]) <NEW_LINE> return <NEW_LINE> <DEDENT> for i in range(start, len(nums)): <NEW_LINE> <INDENT> path.append(nums[i]) <NEW_LINE> self...
以当前path为起点, 找到所有能够得到target的路径.
625941ce16aa5153ce362596
def hash_directory(directory): <NEW_LINE> <INDENT> assert os.path.isdir(directory), '"directory" must be a directory!' <NEW_LINE> md5_hash = hashlib.md5() <NEW_LINE> for root, dirs, files in os.walk(directory): <NEW_LINE> <INDENT> for name in sorted(files): <NEW_LINE> <INDENT> filename = os.path.join(root, name) <NEW_L...
Hashes recursively the content of a directory. Args: directory (path): path to a directory to be hashed Returns: hash of the directory content
625941ce8c0ade5d55d3ead9
def popular_sites(self, repeat=7): <NEW_LINE> <INDENT> random_repeat = random.randint(3, repeat) <NEW_LINE> for i in range(random_repeat): <NEW_LINE> <INDENT> self.browsing(random.choice(self.urls), i) <NEW_LINE> time.sleep(5) <NEW_LINE> self.limit_repeat = 0 <NEW_LINE> self.browse_populate_site() <NEW_LINE> <DEDENT> w...
Visit popular sites :return:
625941cea8ecb033257d31eb
def add(self, satp, boot=None, claimoption=None, description=None, device=None, driver=None, force=None, model=None, option=None, psp=None, pspoption=None, transport=None, type=None, vendor=None): <NEW_LINE> <INDENT> return execute_soap(self._client, self._host, self.moid, 'vim.EsxCLI.storage.nmp.satp.rule.Add', boot=b...
Add a rule to the list of claim rules for the given SATP. :param boot: boolean, This is a system default rule added at boot time. Do not modify esx.conf or add to host profile. :param claimoption: string, Set the claim option string when adding a SATP claim rule. :param description: string, Set the claim rule descripti...
625941ce2eb69b55b151c9ce
def pop_lowest_polygone(self): <NEW_LINE> <INDENT> if len(self.collection) == 0: <NEW_LINE> <INDENT> logging.info("There is no polygone in the collection") <NEW_LINE> return <NEW_LINE> <DEDENT> polygone_min = list(self.collection)[0] <NEW_LINE> min_y = self.collection[polygone_min][0][0][0][1] <NEW_LINE> for vertex in ...
Delete the polygone with the lowest y-axis in the collection and returns it. Returns ------- lowest_polygone : array of tuple of float
625941cead47b63b2c50a09e
def test__parse_binary_time(self): <NEW_LINE> <INDENT> cases = [ (datetime.timedelta(0, 44130), '\x08\x00\x00\x00\x00\x00\x0c\x0f\x1e'), (datetime.timedelta(14, 15330), '\x08\x00\x0e\x00\x00\x00\x04\x0f\x1e'), (datetime.timedelta(-14, 15330), '\x08\x01\x0e\x00\x00\x00\x04\x0f\x1e'), (datetime.timedelta(10, 58530, 23000...
Parse a time value from a binary packet
625941ced7e4931a7ee9e03c
def getInletXNew(linelons, linelats, lon, lat, lon0, lat0, anchorind=0): <NEW_LINE> <INDENT> xx = (linelons - lon0)*np.cos(lat0 * np.pi / 180.) * 60. * 1.85 <NEW_LINE> yy = (linelats - lat0)*60.*1.85 <NEW_LINE> distline = np.cumsum(np.sqrt(np.diff(xx)**2 + np.diff(yy)**2)) <NEW_LINE> distline = np.append([0.], distline...
get potison along an inlet line Anchor Ind should be S4
625941ce76e4537e8c351791
def statLinkedFiles(self): <NEW_LINE> <INDENT> files = [] <NEW_LINE> for lf in self.document.getLinkedFiles(): <NEW_LINE> <INDENT> filename = lf.filename <NEW_LINE> try: <NEW_LINE> <INDENT> s = os.stat(filename) <NEW_LINE> files.append( (filename, s.st_mtime, s.st_size) ) <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> ...
Stat linked files. Returns a list of (filename, mtime, size)
625941ce15fb5d323cde0c2e
def get_user_id_for_username(user_name, allow_none=False): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if c.userobj and c.userobj.name == user_name: <NEW_LINE> <INDENT> return c.userobj.id <NEW_LINE> <DEDENT> <DEDENT> except TypeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> user = model.User.get(user_name) <NEW_...
Helper function to get user id
625941ce94891a1f4081bbc8
def open_logfile_allconn(self, log_file_conn): <NEW_LINE> <INDENT> self.log_file_open = 1 <NEW_LINE> self.log_file_conn = log_file_conn
Run on all connections to signal log file is open
625941cebe383301e01b55a4
def test_touch_with_extra_parameter(self): <NEW_LINE> <INDENT> key = ('test', 'demo', 1) <NEW_LINE> policy = {'timeout': 1000} <NEW_LINE> with pytest.raises(TypeError) as typeError: <NEW_LINE> <INDENT> TestTouch.client.touch(key, 120, {}, policy, "") <NEW_LINE> <DEDENT> assert "touch() takes at most 4 arguments (5 give...
Invoke touch() with extra parameter.
625941cebd1bec0571d9074e
def read_file_header(self): <NEW_LINE> <INDENT> hdict = {} <NEW_LINE> hdr_dtype = MDTYPES[self.byte_order]['dtypes']['file_header'] <NEW_LINE> hdr = read_dtype(self.mat_stream, hdr_dtype) <NEW_LINE> hdict['__header__'] = hdr['description'].item().strip(b' \t\n\000') <NEW_LINE> v_major = hdr['version'] >> 8 <NEW_LINE> v...
Read in mat 5 file header
625941ced99f1b3c44c676ac
def get_xray_scan_schema(self, img: str) -> dict: <NEW_LINE> <INDENT> xray_scan = { "version": "1.0.0", "producerID": self.producer_id, "createdTS": self.scheduler.now_as_str(), "imageID": img, "imagePath": self.path_images } <NEW_LINE> return xray_scan
Returns an empty x_ray_scan schema. :param img: ID of the scanned image :return: filled xray_scan schema represented by a dictionary
625941cea79ad161976cc264
def __init__(self, condition_value_t=1000, eigenvals_t=1e-10): <NEW_LINE> <INDENT> self._condition_value_t = condition_value_t <NEW_LINE> self._eigenvals_t = eigenvals_t
Initializes a 'StatsLinear' instance. Args: condition_value_t (int): The condition value threshold (for multicollinearity). Usually, values higher than 1000 indicate strong multicollinearity or other numerical ...
625941ce507cdc57c6306dfa
def list( self, resource_group_name, virtual_network_name, **kwargs ): <NEW_LINE> <INDENT> cls = kwargs.pop('cls', None) <NEW_LINE> error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } <NEW_LINE> error_map.update(kwargs.pop('error_map', {})) <NEW_LINE> api_version = "2018...
Gets all subnets in a virtual network. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param virtual_network_name: The name of the virtual network. :type virtual_network_name: str :keyword callable cls: A custom type or function that will be passed the direct response :retur...
625941ce046cf37aa974ce66
def beale_func(x): <NEW_LINE> <INDENT> if not x.shape[1] == 2: <NEW_LINE> <INDENT> raise IndexError("Beale function only takes two-dimensional input.") <NEW_LINE> <DEDENT> if not np.logical_and(x >= -4.5, x <= 4.5).all(): <NEW_LINE> <INDENT> raise ValueError( "Input for Beale function must be within " "[-4.5, 4.5]." ) ...
Beale objective function. Only takes two dimensions and has a global minimum of `0` at :code:`f([3,0.5])` Its domain is bounded between :code:`[-4.5, 4.5]` Parameters ---------- x : numpy.ndarray set of inputs of shape :code:`(n_particles, dimensions)` Returns ------- numpy.ndarray computed cost of size :cod...
625941ce097d151d1a222f78
def test_profile_exists(self): <NEW_LINE> <INDENT> self.new_profile.save_profile() <NEW_LINE> test_profile = Passwords("Gmail", "ilovemygirlfriend", "17") <NEW_LINE> test_profile.save_profile() <NEW_LINE> test_exists = Passwords.profile_exists("Gmail") <NEW_LINE> self.assertTrue(test_exists)
Test to check if we can return a boolean if we cannot find a profile
625941ce99fddb7c1c9de4af
def buildSubtrees(self, child): <NEW_LINE> <INDENT> if child.isLeaf(): <NEW_LINE> <INDENT> return child.symbol() <NEW_LINE> <DEDENT> if (child.child1() is not None) and (child.child2() is not None): <NEW_LINE> <INDENT> subtree1 = self.buildSubtrees(child.child1()) <NEW_LINE> subtree2 = self.buildSubtrees(child.child2()...
child is a Label
625941ce66656f66f7cbc2c9
def nbgrader_format_db_url(course_id: str) -> str: <NEW_LINE> <INDENT> course_id = LTIUtils().normalize_string(course_id) <NEW_LINE> database_name = f"{org_name}_{course_id}" <NEW_LINE> return f"postgresql://{nbgrader_db_user}:{nbgrader_db_password}@{nbgrader_db_host}:{nbgrader_db_port}/{database_name}"
Returns the nbgrader database url with the format: <org_name>_<course-id> Args: course_id: the course id (usually associated with the course label) from which the launch was initiated.
625941ce99fddb7c1c9de4b0
def configuration_candidate_properties_values_all(self, id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('callback'): <NEW_LINE> <INDENT> return self.configuration_candidate_properties_values_all_with_http_info(id, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT...
Get Candidate Property values Lists all available values for given candidate property id. This endpoint is available only for SINGLE_SELECT candidate property type. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when recei...
625941ce07f4c71912b115a1
def is_opposition(body, date): <NEW_LINE> <INDENT> time1 = ephem.Date(date) <NEW_LINE> time2 = ephem.Date(time1 + 1) <NEW_LINE> body.compute(time1) <NEW_LINE> elong1 = body.elong.norm <NEW_LINE> body.compute(time2) <NEW_LINE> elong2 = body.elong.norm <NEW_LINE> return ((elong1 <= ephem.pi) and (elong2 >= ephem.pi)) or ...
Returns True if the body is at opposition (i.e. its elongation from the Sun passes 180 degrees, placing it behind the Earth). Keyword arguments: body -- a PyEphem Body object (typically a planet). date -- a YYYY-MM-DD string.
625941ce7b25080760e39578
def __init__(self, body): <NEW_LINE> <INDENT> super(Body, self).__init__() <NEW_LINE> self.value = body
Create a new <Body> element :param body: message body
625941ce4f6381625f114b59
def search_for_coords(dir): <NEW_LINE> <INDENT> def checked_before(r): <NEW_LINE> <INDENT> reruns = False <NEW_LINE> equils = False <NEW_LINE> if "rerun" in os.listdir(r.path): <NEW_LINE> <INDENT> reruns = any(f"{r.title}" in f for f in os.listdir(f"{r.path}/rerun")) <NEW_LINE> <DEDENT> if "spec" in os.listdir(r.path):...
Recursively searched log/out files of optimisations for a successful equilibration- then writes to `equil.xyz`. If unsuccesful, writes to `rerun/rerun.xyz`, whilst also creating the corresponding input and job file.
625941ced8ef3951e324365c
def is_gte_today(base): <NEW_LINE> <INDENT> return True if base >= datetime.date.today() else False
判断给定日期是否大于等于当前日期 :param base 基础日期
625941ce7c178a314d6ef57f
def site(request): <NEW_LINE> <INDENT> return {'site': get_current_site(request)}
Returns site settings which can be accessed with 'site' key.
625941cefb3f5b602dac37b2
def merge(self, path, corr = 1, bias = 0): <NEW_LINE> <INDENT> t2 = self.load(path) <NEW_LINE> t1_start_time = self.start_time <NEW_LINE> t1_end_time = self.end_time <NEW_LINE> t2_start_time = t2.start_time <NEW_LINE> t2_end_time = t2.end_time <NEW_LINE> self.start_time = min(t1_start_time, t2_start_time) <NEW_LINE> se...
Method to merge an existing tidal data set instance into the active one :param path: path to .tid file to merge :param corr: correction factor to multiply the water levels :param corr: bias to add to the water levels :return:
625941ce4c3428357757c446
def get_insult(date): <NEW_LINE> <INDENT> insults = models.Insult.objects <NEW_LINE> insult = insults.exclude( Q(days__date__range=[date - timezone.timedelta(days=365), date + timezone.timedelta(days=365)]) | Q(days__isnull=False)).order_by('?').first() <NEW_LINE> if not insult: <NEW_LINE> <INDENT> insult = insults.ord...
Get an insult from the database
625941cecdde0d52a9e53152
def control(self, num_ctrl_qubits=1, label=None, ctrl_state=None): <NEW_LINE> <INDENT> cmat = _compute_control_matrix(self.to_matrix(), num_ctrl_qubits, ctrl_state=None) <NEW_LINE> iso = isometry.Isometry(cmat, 0, 0) <NEW_LINE> cunitary = ControlledGate('c-unitary', num_qubits=self.num_qubits+num_ctrl_qubits, params=[c...
Return controlled version of gate Args: num_ctrl_qubits (int): number of controls to add to gate (default=1) label (str): optional gate label ctrl_state (int or str or None): The control state in decimal or as a bit string (e.g. '1011'). If None, use 2**num_ctrl_qubits-1. Returns: UnitaryGate:...
625941ce26238365f5f0ef8d
def read_serial_data(self): <NEW_LINE> <INDENT> qdata = list(get_all_from_queue(self.data_q)) <NEW_LINE> if len(qdata) > 0: <NEW_LINE> <INDENT> data = dict(timestamp=qdata[-1][1], temperature=float(qdata[-1][0])) <NEW_LINE> self.livefeed.add_data(data)
Called periodically by the update timer to read data from the serial port.
625941cede87d2750b85feb2
def simMove(self, pos, cmd): <NEW_LINE> <INDENT> x = pos[0] <NEW_LINE> y = pos[1] <NEW_LINE> a = pos[2] <NEW_LINE> forward = cmd[0] <NEW_LINE> turn = cmd[1] <NEW_LINE> forwardNoise = gauss(0, self.noise[0]) <NEW_LINE> turnNoise = gauss(0, self.noise[1]) <NEW_LINE> a = a + (turn + turnNoise) <NEW_LINE> a = wrapAngle(a) ...
Simulate the robot moving with noise
625941ce3d592f4c4ed1d18c
def calcSpeed(self): <NEW_LINE> <INDENT> pass
void KIO.SlaveInterface.calcSpeed()
625941ceac7a0e7691ed41eb
def plenty_api_create_attribute_value_name(self, value_id: int, lang: str, name: str) -> dict: <NEW_LINE> <INDENT> if not value_id or not lang or not name: <NEW_LINE> <INDENT> return [{'error': 'missing_parameter'}] <NEW_LINE> <DEDENT> path = str(f"/attribute_values/{value_id}/names") <NEW_LINE> if utils.get_language(l...
Create an attribute value name for a specific attribute. Parameter: value_id [str] - Attribute value ID from PlentyMarkets lang [str] - two letter abbreviation of a language name [str] - The visible name of the attribute in the given language Return...
625941cef8510a7c17cf981c
def set_database(self, db): <NEW_LINE> <INDENT> self.currentDB = db <NEW_LINE> self.set_list(u'', aozoraDB.keyYOMIWORKS)
データベースのアタッチ
625941cee1aae11d1e749dd6
def makeInputAndTarget(): <NEW_LINE> <INDENT> patterns = read_data("digits_train.txt") <NEW_LINE> inputs = np.empty((2500,196)) <NEW_LINE> targets = np.zeros((2500, 10)) <NEW_LINE> for row in range(2500): <NEW_LINE> <INDENT> inputs[row] = patterns[row].getInput() <NEW_LINE> col = row//250 <NEW_LINE> targets[row][col] =...
Makes training inputs and targets from digit_train.txt
625941ce435de62698dfdd6c
def _insert_default_stacors(session,network_code,station_code): <NEW_LINE> <INDENT> statement = text("select net, sta, seedchan, location, min(ondate), max(offdate) " "from channel_data where seedchan in ('SNN', 'SNE', 'BNN', 'BNE', " "'ENN', 'ENE', 'HNN', 'HNE', 'EHN', 'EHE', 'BHN', 'BHE', 'HHN', " "'HHE', 'EH1','EH2'...
inserts 0. (ml) and 1. (me) corrections for horizontal channels
625941ce187af65679ca523e
@app.route('/') <NEW_LINE> def hello_world(): <NEW_LINE> <INDENT> keyword_query = 'Covid' <NEW_LINE> article_data = get_article_data(keyword_query) <NEW_LINE> return render_template( "index.html", topic=keyword_query, headlines=article_data['headlines'], snippets=article_data['snippets'], dates=article_data['dates'], u...
Returns root endpoint HTML
625941ce44b2445a339321b5
def daemonize(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> pid = os.fork() <NEW_LINE> if pid > 0: <NEW_LINE> <INDENT> sys.exit(0) <NEW_LINE> <DEDENT> <DEDENT> except OSError as e: <NEW_LINE> <INDENT> sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror)) <NEW_LINE> sys.exit(1) <NEW_LINE> <DEDENT> ...
do the UNIX double-fork magic, see Stevens' "Advanced Programming in the UNIX Environment" for details (ISBN 0201563177) http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
625941cea17c0f6771cbe16f