code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def swing(self, containers): <NEW_LINE> <INDENT> fail_msg = 'Failed to kill container: {0}' <NEW_LINE> complete_msg = 'Killed {0} of {1} containers.' <NEW_LINE> i = 0 <NEW_LINE> for container in containers: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.logger.debug('Killing container: {0}'.format(container)) <NEW_LINE> self.docker_client.kill(container) <NEW_LINE> self.logger.debug('Killed container: {0}'.format(container)) <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.logger.exception(fail_msg.format(container)) <NEW_LINE> <DEDENT> <DEDENT> if i == len(containers): <NEW_LINE> <INDENT> self.logger.info(complete_msg.format(i, len(containers))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.logger.error(complete_msg.format(i, len(containers)))
Kills a list of containers. Args: containers (mixed, iterable): An iterable object of container ids. Returns: None Examples: >>> swordsman = Damocles() >>> swordsman.swing(['xxxxxxxxxx', 'yyyyyyyyyyy'])
625941c1167d2b6e31218b1d
def __init__(self, base_arbitration_id, module_name=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> int(base_arbitration_id) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise ValueError( 'unable to represent given base_arbitration_id as an integer: ', base_arbitration_id) <NEW_LINE> <DEDENT> self.magic_word = [0x05, 0xCC] <NEW_LINE> self.enable_arbitration_id = base_arbitration_id <NEW_LINE> self.disable_arbitration_id = base_arbitration_id + 1 <NEW_LINE> self.command_arbitration_id = base_arbitration_id + 2 <NEW_LINE> self.report_arbitration_id = base_arbitration_id + 3 <NEW_LINE> self.module_name = module_name
Initialize CAN data specific to OSCC module.
625941c1498bea3a759b9a37
def parse_values_from_lines(self,lines): <NEW_LINE> <INDENT> assert len(lines) == len(CONTROL_VARIABLE_LINES), "ControlData error: len of lines not equal to " + str(len(CONTROL_VARIABLE_LINES)) <NEW_LINE> for iline,line in enumerate(lines): <NEW_LINE> <INDENT> vals = line.strip().split() <NEW_LINE> names = CONTROL_VARIABLE_LINES[iline].strip().split() <NEW_LINE> for name,val in zip(names,vals): <NEW_LINE> <INDENT> v,t,f = self._parse_value(val) <NEW_LINE> name = name.replace('[','').replace(']','') <NEW_LINE> if t != self._df.loc[name,"type"]: <NEW_LINE> <INDENT> if t == np.int32 and self._df.loc[name,"type"] == np.float64: <NEW_LINE> <INDENT> self._df.loc[name,"value"] = np.float64(v) <NEW_LINE> <DEDENT> elif self._df.loc[name,"required"]: <NEW_LINE> <INDENT> raise Exception("wrong type found for variable " + name + ":" + str(t)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> found = False <NEW_LINE> for nname,avalues in self.accept_values.items(): <NEW_LINE> <INDENT> if v in avalues: <NEW_LINE> <INDENT> if t == self._df.loc[nname,"type"]: <NEW_LINE> <INDENT> self._df.loc[nname,"value"] = v <NEW_LINE> found = True <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if not found: <NEW_LINE> <INDENT> print("warning: non-conforming value found for " + name + ":" + str(v)) <NEW_LINE> print("ignoring...") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self._df.loc[name,"value"] = v
cast the string lines for a pest control file into actual inputs Parameters: ---------- lines: strings from pest control file Returns: ------- None
625941c1435de62698dfdbd4
def convert_tg_mean(mu, scale, step=1e-7): <NEW_LINE> <INDENT> X = np.arange(0, 1, step) <NEW_LINE> return (X * sc.norm.pdf(X, loc=mu, scale=scale)).mean()+ 1 - sc.norm.cdf(1, loc=mu, scale=scale)
:param mu: mean of the underlying gaussian r.v :param scale: scale of the underlying gaussian r.v :param step: precision of the numerical integration :return: compute the mean of the Truncated Gaussian r.v knowing the parameters of its associated Gaussian r.v
625941c13617ad0b5ed67e80
def main(argv): <NEW_LINE> <INDENT> args, opts = oss.gopt(argv[1:], [], [('o', 'output')], main.__doc__ + __doc__) <NEW_LINE> outfile = 'cmd_help.html' if opts.output is None else opts.output <NEW_LINE> if len(args) == 0: <NEW_LINE> <INDENT> args = oss.ls('*.py') <NEW_LINE> <DEDENT> title = oss.pwd() <NEW_LINE> print("Writing to file: '%s'" % outfile) <NEW_LINE> with open(outfile, 'w') as otf: <NEW_LINE> <INDENT> otf.write(HTML_BEGIN % (title, title)) <NEW_LINE> links = ['<a href="#{0}">{0}</a>'.format(nm) for nm in args] <NEW_LINE> otf.write('<a name="top"><h2>Contents</h2></a>\n') <NEW_LINE> otf.write("<center>\n" + utils.makeTable(links, tattr='border="1" width="90%"') + "\n</center>\n\n") <NEW_LINE> otf.flush() <NEW_LINE> for prgm in args: <NEW_LINE> <INDENT> print(prgm) <NEW_LINE> otf.write('\n\n<hr/>\n') <NEW_LINE> otf.write('<a name="{0}">'.format(prgm)) <NEW_LINE> otf.write('<h2>' + prgm + '</h2></a>\n') <NEW_LINE> s = oss.r(prgm + ' --help', '$') <NEW_LINE> otf.write('<font size="5"><pre>' + cgi.escape(s) + '</pre></font>\n') <NEW_LINE> otf.write('<a href="#top">Top</a>\n') <NEW_LINE> otf.flush() <NEW_LINE> <DEDENT> otf.write(HTML_END) <NEW_LINE> <DEDENT> oss.exit(0)
usage: mk_cmd_help.py [options] [<file_name> ...] options: -o | --output : html file output <default: 'cmd_help.html' generate an html output file of the help strings from the specified commands
625941c196565a6dacc8f653
def trained_estimator_from_hyperparams(s3_train_data, hyperparams, output_path, s3_test_data=None): <NEW_LINE> <INDENT> knn = sagemaker.estimator.Estimator(get_image_uri(boto3.Session().region_name, "knn"), get_execution_role(), train_instance_count=1, train_instance_type='ml.c4.xlarge', output_path=output_path, sagemaker_session=sagemaker.Session()) <NEW_LINE> knn.set_hyperparameters(**hyperparams) <NEW_LINE> fit_input = {'train': s3_train_data} <NEW_LINE> knn.fit(fit_input) <NEW_LINE> return knn
Create an Estimator from the given hyperparams, fit to training data, and return a deployed predictor
625941c1e76e3b2f99f3a797
def svd(data): <NEW_LINE> <INDENT> N, D = data.shape <NEW_LINE> data = data - np.mean(data, axis=0) <NEW_LINE> Veig_val, Veig_vector = np.linalg.eigh(np.dot(data.T, data)) <NEW_LINE> VT = Veig_vector[:, np.argsort(-abs(Veig_val))].T <NEW_LINE> Ueig_val, Ueig_vector = np.linalg.eigh(np.dot(data, data.T)) <NEW_LINE> U = Ueig_vector[:, np.argsort(-abs(Ueig_val))] <NEW_LINE> Sigma = np.zeros((N, D)) <NEW_LINE> for i in range(D): <NEW_LINE> <INDENT> Sigma[i, i] = np.dot(data, VT[i])[i]/U[i,i] <NEW_LINE> <DEDENT> return U, Sigma, VT
:param data: :return: U, Sigma, VT
625941c18da39b475bd64ef9
def discriminator_loss(self, D, y, fake_y, label, use_lsgan=True): <NEW_LINE> <INDENT> if use_lsgan: <NEW_LINE> <INDENT> error_real = tf.reduce_mean(tf.squared_difference(D(y), label)) <NEW_LINE> error_fake = tf.reduce_mean(tf.square(D(fake_y))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> error_real = -tf.reduce_mean(ops.safe_log(D(y))) <NEW_LINE> error_fake = -tf.reduce_mean(ops.safe_log(1 - D(fake_y))) <NEW_LINE> <DEDENT> loss = (error_real + error_fake) / 2 <NEW_LINE> return loss
Note: default: D(y).shape == (batch_size,5,5,1), fake_buffer_size=50, batch_size=1 Args: G: generator object D: discriminator object y: 4D tensor (batch_size, image_size, image_size, 3) Returns: loss: scalar
625941c163b5f9789fde706d
def _on_change_pos(self, editable): <NEW_LINE> <INDENT> if self.__updating: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.__updating = True <NEW_LINE> el = False <NEW_LINE> if self._notebook.get_current_page() == 0: <NEW_LINE> <INDENT> el = self._get_active_bg() <NEW_LINE> <DEDENT> elif self._notebook.get_current_page() == 1: <NEW_LINE> <INDENT> el = self.theme.get_body() <NEW_LINE> <DEDENT> elif self._notebook.get_current_page() == 2: <NEW_LINE> <INDENT> el = self.theme.get_footer() <NEW_LINE> <DEDENT> if el is False: <NEW_LINE> <INDENT> self.__updating = False <NEW_LINE> return False <NEW_LINE> <DEDENT> lf = self._p['lf'].get_value() <NEW_LINE> rt = self._p['rt'].get_value() <NEW_LINE> tp = self._p['tp'].get_value() <NEW_LINE> bt = self._p['bt'].get_value() <NEW_LINE> if rt <= lf: <NEW_LINE> <INDENT> if editable == self._p['rt']: <NEW_LINE> <INDENT> lf = rt - 0.01 <NEW_LINE> self._p['lf'].set_value(lf) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> rt = lf + 0.01 <NEW_LINE> self._p['rt'].set_value(lf) <NEW_LINE> <DEDENT> <DEDENT> if bt <= tp: <NEW_LINE> <INDENT> if editable == self._p['bt']: <NEW_LINE> <INDENT> tp = bt - 0.01 <NEW_LINE> self._p['tp'].set_value(tp) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> bt = tp + 0.01 <NEW_LINE> self._p['bt'].set_value(bt) <NEW_LINE> <DEDENT> <DEDENT> el.pos[0] = lf <NEW_LINE> el.pos[1] = tp <NEW_LINE> el.pos[2] = rt <NEW_LINE> el.pos[3] = bt <NEW_LINE> self.__updating = False <NEW_LINE> self._set_changed() <NEW_LINE> self.draw()
Update the position on change. `pos.right` will be updated to be larger than `pos.left`. Same for top and bottom.
625941c18e71fb1e9831d732
def isTitleVisible(self): <NEW_LINE> <INDENT> return self.titleVisible
True if the title is configured to be visible, False otherwise.
625941c1293b9510aa2c321f
def subscribe(self, channel, *clients): <NEW_LINE> <INDENT> active_subscribers = self._get_active_subscribers_idx(channel) <NEW_LINE> for client in clients: <NEW_LINE> <INDENT> ch_logger.debug('Subscribe client {} on channel {}'.format( client.address, channel)) <NEW_LINE> active_subscribers.update({client.address: weakref.proxy(client)}) <NEW_LINE> <DEDENT> self.registry[channel] = active_subscribers.values() <NEW_LINE> return 'subscribed'
Subscribe client for a channel. Method supports multiple subscriptions. :param channel: string channel name :param clients: geventwebsocket.handler.Client list
625941c1009cb60464c6333b
def listening(port, shortened=False, pid_only=False, proc_only=False, kill=False): <NEW_LINE> <INDENT> if platform.system() != 'Linux': <NEW_LINE> <INDENT> sys.stderr.write('listeningPort available only under Linux!\n') <NEW_LINE> sys.exit(-1) <NEW_LINE> <DEDENT> proc = subprocess.Popen('/usr/sbin/fuser %s/tcp' % str(port), shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) <NEW_LINE> line = proc.stdout.readline() <NEW_LINE> subproc_items = line.split() <NEW_LINE> if len(subproc_items) == 0: <NEW_LINE> <INDENT> if shortened is False: <NEW_LINE> <INDENT> sys.stdout.write('Port %s : Nobody listening\n' % str(port)) <NEW_LINE> <DEDENT> return 0 <NEW_LINE> <DEDENT> pid = subproc_items[-1] <NEW_LINE> proc.wait() <NEW_LINE> out, err = subprocess.Popen('/usr/bin/ps x | /usr/bin/grep %s' % pid, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate() <NEW_LINE> if err and len(err): <NEW_LINE> <INDENT> sys.stderr.write(err + '\n') <NEW_LINE> <DEDENT> for line in out.splitlines(): <NEW_LINE> <INDENT> items = line.split() <NEW_LINE> if items[0] != pid: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if kill: <NEW_LINE> <INDENT> p = psutil.Process(int(pid)) <NEW_LINE> p.terminate() <NEW_LINE> return 1 <NEW_LINE> <DEDENT> if shortened: <NEW_LINE> <INDENT> sys.stdout.write('%s %s %s\n' % (str(port), pid, ' '.join(items[5:]))) <NEW_LINE> <DEDENT> elif pid_only: <NEW_LINE> <INDENT> sys.stdout.write('%s\n' % pid) <NEW_LINE> <DEDENT> elif proc_only: <NEW_LINE> <INDENT> sys.stdout.write('%s\n' % ' '.join(items[4:])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sys.stdout.write('Port %s : listening thru pid %s %s\n' % (str(port), pid, ' '.join(items[5:]))) <NEW_LINE> <DEDENT> return 1 <NEW_LINE> <DEDENT> return 0
The return code may seem to be reversed, but it exists for the common command line version: return N # Indicate found N listeners return 0 # Indicates nobody listening
625941c10a50d4780f666e18
def build_map_dict_by_name(gdpinfo, plot_countries, year): <NEW_LINE> <INDENT> return_dict = {} <NEW_LINE> return_set1,return_set2 = set(), set() <NEW_LINE> gdpdata = read_csv_as_nested_dict(gdpinfo['gdpfile'], gdpinfo['country_name'], gdpinfo['separator'], gdpinfo['quote']) <NEW_LINE> for country_code in plot_countries : <NEW_LINE> <INDENT> input_country_name = plot_countries[country_code] <NEW_LINE> for country_name in gdpdata : <NEW_LINE> <INDENT> if input_country_name == country_name : <NEW_LINE> <INDENT> if gdpdata[country_name][year] : <NEW_LINE> <INDENT> return_dict[country_code] = math.log10(float(gdpdata[country_name][year])) <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> return_set2.add(country_code) <NEW_LINE> <DEDENT> <DEDENT> else : <NEW_LINE> <INDENT> return_set1.add(country_code) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for removal in return_dict : <NEW_LINE> <INDENT> return_set1.discard(removal) <NEW_LINE> <DEDENT> for removal in return_set2 : <NEW_LINE> <INDENT> return_set1.discard(removal) <NEW_LINE> <DEDENT> return return_dict, return_set1, return_set2
Inputs: gdpinfo - A GDP information dictionary plot_countries - Dictionary whose keys are plot library country codes and values are the corresponding country name year - String year to create GDP mapping for Output: A tuple containing a dictionary and two sets. The dictionary maps country codes from plot_countries to the log (base 10) of the GDP value for that country in the specified year. The first set contains the country codes from plot_countries that were not found in the GDP data file. The second set contains the country codes from plot_countries that were found in the GDP data file, but have no GDP data for the specified year.
625941c199fddb7c1c9de31a
@api.route('/mapreduce', methods=['POST','GET']) <NEW_LINE> @auto.doc() <NEW_LINE> def mapreduce(): <NEW_LINE> <INDENT> collection = request.args.get('collection', 'revisions') <NEW_LINE> full_response = request.args.get('full_response', False) <NEW_LINE> db = RevisionDB(config={'host': config['default'].MONGO_HOST, 'port': config['default'].MONGO_PORT, 'username': config['default'].MONGO_USERNAME, 'password': config['default'].MONGO_PASSWORD, 'db_name':config['default'].MONGO_DB_NAME}) <NEW_LINE> query = request.get_json(silent=True) <NEW_LINE> map_code = Code(request.args.get('map')) <NEW_LINE> reduce_code = Code(request.args.get('reduce')) <NEW_LINE> out = json_util.dumps({'out':'map_reduce'}) <NEW_LINE> result = db.mapreduce(out, collection, map_code, reduce_code, full_response, query) <NEW_LINE> return Response( json_util.dumps(result.find()), mimetype='application/json' )
Use a json payload to query map reduce results Params: <ul class="params"> <li>collection.Required. Collection name</li> <li>map. Required. map function code</li> <li>reduce. Required. reduce function code</li> </ul> <i>Example: <a href="mapreduce?map=function(){emit(this.user,this.size);}&reduce=function(user_id,values_sizes){return Array.sum(values_sizes);}&collection=revisions" target="_blank">api/v1/mapreduce?map=function(){emit(this.user,this.size);}&reduce=function(user_id,values_sizes){ return Array.sum(values_sizes);}&collection=revisions</a></i>
625941c14e696a04525c93d4
def param_type(param): <NEW_LINE> <INDENT> if isinstance(param, Mixed) and len(param): <NEW_LINE> <INDENT> subtypes = [param_type(subparam) for subparam in param] <NEW_LINE> return " or ".join(subtypes) <NEW_LINE> <DEDENT> elif isinstance(param, (list, tuple, set)) and len(param): <NEW_LINE> <INDENT> return "array of " + " or ".join([param_type(subparam) for subparam in param]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return xmlrpc_type(python_type(param))
Return the XML-RPC type of a parameter.
625941c1ec188e330fd5a72b
def testOffset(self): <NEW_LINE> <INDENT> encoder = RandomDistributedScalarEncoder(name="encoder", resolution=1.0) <NEW_LINE> encoder.encode(23.0) <NEW_LINE> self.assertEqual(encoder._offset, 23.0, "Offset not specified and not initialized to first input") <NEW_LINE> encoder = RandomDistributedScalarEncoder(name="encoder", resolution=1.0, offset=25.0) <NEW_LINE> encoder.encode(23.0) <NEW_LINE> self.assertEqual(encoder._offset, 25.0, "Offset not initialized to specified constructor" " parameter")
Test that offset is working properly
625941c156ac1b37e626415b
def test_if_excel_generator_adds_content_correctly(self): <NEW_LINE> <INDENT> path_of_excel_workbook_exemplar = ( CURRENT_PATH + '/exemplar_data/expected_excel_sheet_outcome.xlsx') <NEW_LINE> xlsx_file = generate_test_data_excel_workbook() <NEW_LINE> df1 = pd.read_excel(xlsx_file) <NEW_LINE> df2 = pd.read_excel(open(path_of_excel_workbook_exemplar, "rb")) <NEW_LINE> diff_xlsx_files = pd.concat([df1, df2]).drop_duplicates(keep=False) <NEW_LINE> assert df1.equals(df2), "The examplar excel workbook converges from the one generated." "The diff occured in following lines \n\n{}".format( diff_xlsx_files)
Test if an excel workbook generated by the linkchecker does not differ an exemplar workbook containing the expected data.
625941c171ff763f4b549610
def testCookerCommandEvent(self, command, params): <NEW_LINE> <INDENT> pattern = params[0] <NEW_LINE> command.cooker.testCookerCommandEvent(pattern) <NEW_LINE> command.finishAsyncCommand()
Dummy command used by OEQA selftest to test tinfoil without IO
625941c167a9b606de4a7e43
def template_wrapping_substitute(line, dict): <NEW_LINE> <INDENT> for key, value in dict.items(): <NEW_LINE> <INDENT> splits = line.split(key) <NEW_LINE> l = len(splits) <NEW_LINE> if l > 1: <NEW_LINE> <INDENT> for i in range(1, l, 2): <NEW_LINE> <INDENT> word = value.replace(key, splits[i]) <NEW_LINE> splits[i] = word <NEW_LINE> <DEDENT> <DEDENT> line = "".join(splits) <NEW_LINE> <DEDENT> return line
substitutes in a line expressions from a dict expressions are of the sort : wrapperKEYwrapper -> blaKEYblo For instance : dict = { "_" : "A[:,_]" } line = "_1_ + _2_" will return "A[:,1] + A[:,2]"
625941c1e8904600ed9f1eb3
def toggle_left_pane(self): <NEW_LINE> <INDENT> enabled = config.get('enable_vertical_tab_list') <NEW_LINE> if not config.silent_set('enable_vertical_tab_list', str(not enabled)): <NEW_LINE> <INDENT> self.information('Unable to write in the config file', 'Error') <NEW_LINE> <DEDENT> self.call_for_resize()
Enable/disable the left panel.
625941c16fb2d068a760f023
def simplify_unit_impulse(self): <NEW_LINE> <INDENT> result = simplify_unit_impulse(self.expr, self.var) <NEW_LINE> return self.__class__(result, **self.assumptions)
Simplify UnitImpulse(4 * k + 8) to UnitImpulse(k + 2), etc.
625941c1956e5f7376d70df6
def findLongestChain(self, pairs): <NEW_LINE> <INDENT> n = len(pairs) <NEW_LINE> pairs.sort(key = lambda x:(x[0],x[1])) <NEW_LINE> chain_len, chain_end = 1, pairs[0][1] <NEW_LINE> for p in range(1,n) : <NEW_LINE> <INDENT> if pairs[p][0] <= chain_end: <NEW_LINE> <INDENT> chain_end = min(chain_end, pairs[p][1]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> chain_len += 1 <NEW_LINE> chain_end = pairs[p][1] <NEW_LINE> <DEDENT> <DEDENT> return chain_len
:type pairs: List[List[int]] :rtype: int
625941c1baa26c4b54cb10aa
def calculateHandlen(hand): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> for key, value in hand.items(): <NEW_LINE> <INDENT> count += hand.get(key, 0) <NEW_LINE> <DEDENT> return count
Returns the length (number of letters) in the current hand. hand: dictionary (string-> int) returns: integer
625941c1d99f1b3c44c6751c
def test_exact_fscore_agreement(): <NEW_LINE> <INDENT> for nprobs in range(1, 9): <NEW_LINE> <INDENT> probs = np.random.rand(nprobs) <NEW_LINE> thresh = np.random.rand() <NEW_LINE> naive = fsc.exact_expected_fscore_naive(probs, thresh) <NEW_LINE> clever = cfsc.efscore(probs, thresh) <NEW_LINE> assert naive == pytest.approx(clever), 'Disagreement on probs {} with thresh {}'.format(probs, thresh)
Test whether the naive and 'clever' implementations of exact expected fscore agree on a bunch of randomly generated examples of different sizes.
625941c13346ee7daa2b2cf2
def formatLine(self, line): <NEW_LINE> <INDENT> line = line.split("] ", 1)[1] <NEW_LINE> line = line.replace("[Server]", '', 1) <NEW_LINE> line = line.replace('[Server thread/INFO]:', '', 1) <NEW_LINE> line = line.strip() <NEW_LINE> return line
Cut unwanted parts from given line. - :param line: Line to be formatted - :type line: string - :returns string:
625941c1be383301e01b5411
def put_HelpContextID(self, contextID): <NEW_LINE> <INDENT> return super(ICommandItem, self).put_HelpContextID(contextID)
Method ICommandItem.put_HelpContextID INPUT contextID : long
625941c1c432627299f04bcc
def test_shell_show_selected_sorted(): <NEW_LINE> <INDENT> resp = run_cmd("show selected sortby sender asc limit 2") <NEW_LINE> assert "Preview of first 2" in resp <NEW_LINE> assert len(resp.split('\n')) == 3 <NEW_LINE> resp = run_cmd("show selected sortby sender desc limit 2") <NEW_LINE> assert "Preview of first 2" in resp <NEW_LINE> assert len(resp.split('\n')) == 3
Test 'show selected sortby sender limit 2' command
625941c15e10d32532c5eeaf
def configure_for_kubernetes(): <NEW_LINE> <INDENT> pass
Configures Baker Street for a Kubernetes deployment
625941c1287bf620b61d39ed
def check_scm(domain_str, gittree_str): <NEW_LINE> <INDENT> global _message <NEW_LINE> _message = [] <NEW_LINE> try: <NEW_LINE> <INDENT> domains_data = parse_blocks(domain_str, MAPPING) <NEW_LINE> trees_data = parse_blocks(gittree_str, MAPPING) <NEW_LINE> <DEDENT> except ValueError as err: <NEW_LINE> <INDENT> error(str(err)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> domains = check_domain(domains_data) <NEW_LINE> check_gittree(trees_data, domains) <NEW_LINE> <DEDENT> return _message
check domain and gittree file. The return value: zero means everything is ok, non-zero means something is wrong, and the number is the error num in total.
625941c1d8ef3951e32434c5
@wraps('lazy') <NEW_LINE> def relu_forward(x): <NEW_LINE> <INDENT> out = np.maximum(0, x) <NEW_LINE> return out
Computes the forward pass for a layer of rectified linear units (ReLUs). Input: - x: Inputs, of any shape Returns a tuple of: - out: Output, of the same shape as x - cache: x
625941c18a43f66fc4b53fef
def read_json(file, *_args, **_kwargs): <NEW_LINE> <INDENT> if sys.version_info >= (3, 6): <NEW_LINE> <INDENT> _json = json.load(file) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> file_content_str = file.read().decode() <NEW_LINE> _json = json.loads(file_content_str) <NEW_LINE> <DEDENT> flattened = json_normalize(_json) <NEW_LINE> return flattened
Read a semi-structured JSON file into a flattened dataframe. Args: file: file-like object _args: positional arguments receiver; not used _kwargs: keyword arguments receiver; not used Returns: Dataframe with single column level; original JSON hierarchy is expressed as dot notation in column names
625941c157b8e32f52483422
def check(com, user): <NEW_LINE> <INDENT> if com == user: <NEW_LINE> <INDENT> print("I chose same :", com) <NEW_LINE> print("A DRAW. AGAIN...") <NEW_LINE> return 2 <NEW_LINE> <DEDENT> elif com == "rock" and user == "paper": <NEW_LINE> <INDENT> print("YOU WIN!! I chose", com) <NEW_LINE> return 1 <NEW_LINE> <DEDENT> elif com == "rock" and user == "scissors": <NEW_LINE> <INDENT> print("YOU LOSE!! I chose", com) <NEW_LINE> return 0 <NEW_LINE> <DEDENT> elif com == "paper" and user == "rock": <NEW_LINE> <INDENT> print("YOU LOSE!! I chose", com) <NEW_LINE> return 0 <NEW_LINE> <DEDENT> elif com == "paper" and user == "scissors": <NEW_LINE> <INDENT> print("YOU WIN!! I chose", com) <NEW_LINE> return 1 <NEW_LINE> <DEDENT> elif com == "scissors" and user == "rock": <NEW_LINE> <INDENT> print("YOU WIN!! I chose", com) <NEW_LINE> return 1 <NEW_LINE> <DEDENT> elif com == "scissors" and user == "paper": <NEW_LINE> <INDENT> print("YOU LOSE!! I chose", com) <NEW_LINE> return 0
Logic of the entire game. returns 2 for a DRAW, 1 if USER WINS, 0 IF COM WINS
625941c155399d3f0558863b
def get_insn(self): <NEW_LINE> <INDENT> return self.insn
Get the insn buffer :rtype: bytes
625941c1b5575c28eb68df87
def parse_tile(text: str) -> Tuple[int, List[List[str]]]: <NEW_LINE> <INDENT> id_tile, image = text.split(":\n") <NEW_LINE> return int(id_tile.replace("Tile ", "")), [list(i) for i in image.split("\n")]
Given 'Tile 1567: .####.##.# .......#.. .###..###. .....#..#. ..#....#.. #......### #..#.....# #....##... ...###...# #.#.#..##.' return (1567, [['.', '#', '#', '#', '#', '.', '#', '#', '.', '#'], ['.', '.', '.', '.', '.', '.', '.', '#', '.', '.'], ...]
625941c17b25080760e393e2
def SetFixedImageIndexes(self, *args): <NEW_LINE> <INDENT> return _itkImageToImageMetricPython.itkImageToImageMetricIUL2IUL2_SetFixedImageIndexes(self, *args)
SetFixedImageIndexes(self, std::vector<(itkIndex2,std::allocator<(itkIndex2)>)> indexes)
625941c1be7bc26dc91cd58c
def summary(self): <NEW_LINE> <INDENT> print("\nSummary") <NEW_LINE> print("=" * 79) <NEW_LINE> cmd = "All repositories are updated." <NEW_LINE> if self.count_repo == 1: <NEW_LINE> <INDENT> cmd = "Repository is updated." <NEW_LINE> <DEDENT> if self.count_news > 0: <NEW_LINE> <INDENT> cmd = "Run the command 'slpkg update'." <NEW_LINE> <DEDENT> print("{0}From {1} repositories need {2} updating. {3}{4}\n".format( self.meta.color["GREY"], self.count_repo, self.count_news, cmd, self.meta.color["ENDC"]))
Print summary
625941c13317a56b86939be6
def nsmallest(n, iterable, key=None): <NEW_LINE> <INDENT> if n == 1: <NEW_LINE> <INDENT> it = iter(iterable) <NEW_LINE> sentinel = object() <NEW_LINE> if key is None: <NEW_LINE> <INDENT> result = min(it, default=sentinel) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = min(it, default=sentinel, key=key) <NEW_LINE> <DEDENT> return [] if result is sentinel else [result] <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> size = len(iterable) <NEW_LINE> <DEDENT> except (TypeError, AttributeError): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if n >= size: <NEW_LINE> <INDENT> return sorted(iterable, key=key)[:n] <NEW_LINE> <DEDENT> <DEDENT> if key is None: <NEW_LINE> <INDENT> it = iter(iterable) <NEW_LINE> result = [(elem, i) for i, elem in zip(range(n), it)] <NEW_LINE> if not result: <NEW_LINE> <INDENT> return result <NEW_LINE> <DEDENT> _heapify_max(result) <NEW_LINE> top = result[0][0] <NEW_LINE> order = n <NEW_LINE> _heapreplace = _heapreplace_max <NEW_LINE> for elem in it: <NEW_LINE> <INDENT> if elem < top: <NEW_LINE> <INDENT> _heapreplace(result, (elem, order)) <NEW_LINE> top, _order = result[0] <NEW_LINE> order += 1 <NEW_LINE> <DEDENT> <DEDENT> result.sort() <NEW_LINE> return [elem for (elem, order) in result] <NEW_LINE> <DEDENT> it = iter(iterable) <NEW_LINE> result = [(key(elem), i, elem) for i, elem in zip(range(n), it)] <NEW_LINE> if not result: <NEW_LINE> <INDENT> return result <NEW_LINE> <DEDENT> _heapify_max(result) <NEW_LINE> top = result[0][0] <NEW_LINE> order = n <NEW_LINE> _heapreplace = _heapreplace_max <NEW_LINE> for elem in it: <NEW_LINE> <INDENT> k = key(elem) <NEW_LINE> if k < top: <NEW_LINE> <INDENT> _heapreplace(result, (k, order, elem)) <NEW_LINE> top, _order, _elem = result[0] <NEW_LINE> order += 1 <NEW_LINE> <DEDENT> <DEDENT> result.sort() <NEW_LINE> return [elem for (k, order, elem) in result]
Find the n smallest elements in a dataset. Equivalent to: sorted(iterable, key=key)[:n]
625941c18c0ade5d55d3e941
def rightButton(autohotpy,event): <NEW_LINE> <INDENT> stroke = InterceptionMouseStroke() <NEW_LINE> stroke.state = InterceptionMouseState.INTERCEPTION_MOUSE_RIGHT_BUTTON_DOWN <NEW_LINE> autohotpy.sendToDefaultMouse(stroke) <NEW_LINE> stroke.state = InterceptionMouseState.INTERCEPTION_MOUSE_RIGHT_BUTTON_UP <NEW_LINE> autohotpy.sendToDefaultMouse(stroke)
This function simulates a right click
625941c19f2886367277a817
def print_first_and_last(sentence): <NEW_LINE> <INDENT> words = break_words(sentence) <NEW_LINE> print_first_world(words) <NEW_LINE> print_last_world(words)
prints the first and last words of the sentence
625941c1e1aae11d1e749c3e
def butConnHandler(self): <NEW_LINE> <INDENT> if not validIp(self.serverIp): <NEW_LINE> <INDENT> QMessageBox.critical(self, 'Invalid Ip', f"Invalid IP address: {self.serverIp}", QMessageBox.Ok) <NEW_LINE> self.tIp.setFocus() <NEW_LINE> return <NEW_LINE> <DEDENT> if not validPort(self.serverPorta): <NEW_LINE> <INDENT> QMessageBox.critical(self, 'Invalid Port', f"Invalid port number: {self.serverPorta}", QMessageBox.Ok) <NEW_LINE> self.tPort.setFocus() <NEW_LINE> return <NEW_LINE> <DEDENT> self.conn.initConn(self.serverIp, self.serverPorti) <NEW_LINE> if not self.conn.isAlive: <NEW_LINE> <INDENT> self.connectFailedHint() <NEW_LINE> return <NEW_LINE> <DEDENT> self.close()
button逻辑,判断输入是否合法
625941c1627d3e7fe0d68dd7
def _parse_line_with_compiled_regexes(self, line): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> for item, reg in self.mapping.compiled_regexes: <NEW_LINE> <INDENT> if reg.search(line): <NEW_LINE> <INDENT> line, _count = reg.subn(self.mapping.get(item.lower()), line) <NEW_LINE> count += _count <NEW_LINE> <DEDENT> <DEDENT> return line, count
Check the provided line against known items we have encountered before and have pre-generated regex Pattern() objects for. :param line: The line to parse for possible matches for obfuscation :type line: ``str`` :returns: The obfuscated line and the number of changes made :rtype: ``str``, ``int``
625941c115baa723493c3efc
def __init__(self, format_maps): <NEW_LINE> <INDENT> if format_maps is None: <NEW_LINE> <INDENT> format_maps = [{}] <NEW_LINE> <DEDENT> if not isinstance(format_maps, (list, tuple)): <NEW_LINE> <INDENT> raise GenestackException('Format map should be list or tuple') <NEW_LINE> <DEDENT> map(self.validate, format_maps) <NEW_LINE> self.__list = deepcopy(format_maps)
Format pattern is a list of format maps. You can specify all required formats in constructor or add them from other format pattern with ``add`` method :param format_maps: list of dicts :return:
625941c1a8370b7717052829
def close(self): <NEW_LINE> <INDENT> if self.logger is not None: <NEW_LINE> <INDENT> logger.close()
Stop crawling and close any additional running functionalities.
625941c1851cf427c661a49a
def expand_query(query_str): <NEW_LINE> <INDENT> index = 0 <NEW_LINE> word_index = -1 <NEW_LINE> index_reset = False <NEW_LINE> for ch in query_str: <NEW_LINE> <INDENT> global full_word_query <NEW_LINE> if ch == " ": <NEW_LINE> <INDENT> if index == len(query_str) - 1: <NEW_LINE> <INDENT> global last_word <NEW_LINE> last_word = True <NEW_LINE> <DEDENT> index += 1 <NEW_LINE> continue <NEW_LINE> <DEDENT> if not ch.isalpha() and ch != "*": <NEW_LINE> <INDENT> index += 1 <NEW_LINE> continue <NEW_LINE> <DEDENT> if not ch.isupper(): <NEW_LINE> <INDENT> if word_index >= 0: <NEW_LINE> <INDENT> if index_reset: <NEW_LINE> <INDENT> full_word_query = query_str[word_index:index + 1] <NEW_LINE> index_reset = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> full_word_query += query_str[index] <NEW_LINE> <DEDENT> <DEDENT> index += 1 <NEW_LINE> continue <NEW_LINE> <DEDENT> word_index = index <NEW_LINE> index_reset = True <NEW_LINE> global upper_case_query <NEW_LINE> upper_case_query = upper_case_query + ch <NEW_LINE> if full_word_query != "": <NEW_LINE> <INDENT> full_word_queries.append(full_word_query) <NEW_LINE> <DEDENT> full_word_query = "" <NEW_LINE> index += 1 <NEW_LINE> <DEDENT> if full_word_query != "": <NEW_LINE> <INDENT> full_word_queries.append(full_word_query) <NEW_LINE> <DEDENT> full_word_query = ""
Expand the raw query string to generate term queries that can be used to search the documents :param query_str: the raw input query that needs to be expanded. UpperCased query if raw query contains only lower case characters. :return: all possible term queries that include * upper_case_query - the sequence of upper case letters that needs to be present in the class name * full_word_queries - List of words or substrings that are to be present in the class name
625941c1a934411ee375161b
def get_a_action(base, action_id): <NEW_LINE> <INDENT> res = base.client.get_obj('actions', action_id) <NEW_LINE> return res['body']
Utility function that gets a Senlin action.
625941c107d97122c4178810
def __init__(self, nodes , activationFunction = "ReLU"): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.learning_rate = 0.02 <NEW_LINE> self.gene_off = 0 <NEW_LINE> self.nodes = nodes <NEW_LINE> self.layer = len(self.nodes) <NEW_LINE> self.five_fold_count = 1 <NEW_LINE> self.activationFunction = activationFunction
:param 1. nodes: nodes list of Deep neural network. 2. activationFunction : choice of activation function , default is ReLU
625941c12eb69b55b151c835
def mixer_s32_256(**kwargs): <NEW_LINE> <INDENT> model = MLP_Mixer(patch_size = 32, num_layers = 8 , dim = 512, token_dim = 256, channel_dim = 2048, **kwargs) <NEW_LINE> return model
Mixer-S/32 256x256
625941c15510c4643540f372
def __itruediv__(self, arg): <NEW_LINE> <INDENT> return self._binary_operator_inplace(arg, lambda l, r: l / r)
_CPP_: MO__VEC_OP_INPLACE(l /= r)
625941c14e696a04525c93d5
def file_util_is_exists(path): <NEW_LINE> <INDENT> return os.path.exists(path)
判断文件或目录是否存在
625941c14a966d76dd550f96
def send_file_service(service): <NEW_LINE> <INDENT> send_file(device_id, url=service.data.get('url'), api_key=api_key)
Service to send files to devices.
625941c192d797404e304112
def PkgConfigGetLibDirs(pkgname, tool = "pkg-config"): <NEW_LINE> <INDENT> if (sys.platform == "win32" or not LocateBinary(tool)): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> if (tool == "pkg-config"): <NEW_LINE> <INDENT> handle = os.popen(LocateBinary("pkg-config") + " --silence-errors --libs-only-L " + pkgname) <NEW_LINE> <DEDENT> elif (tool == "wx-config" or tool == "ode-config"): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> handle = os.popen(LocateBinary(tool) + " --ldflags") <NEW_LINE> <DEDENT> result = handle.read().strip() <NEW_LINE> handle.close() <NEW_LINE> if len(result) == 0: return [] <NEW_LINE> libs = [] <NEW_LINE> for l in result.split(" "): <NEW_LINE> <INDENT> if (l.startswith("-L")): <NEW_LINE> <INDENT> libs.append(l.replace("-L", "").replace("\"", "").strip()) <NEW_LINE> <DEDENT> <DEDENT> return libs
Returns a list of library paths for the package, NOT prefixed by -L.
625941c16fb2d068a760f024
def __exit__(self, exc_type, exc_val, exc_tb): <NEW_LINE> <INDENT> self.close()
Activated at the end of the with statement.
625941c1656771135c3eb7f5
def get_instrument_info(self,instrument,granularity,number_of_candles,start_time=None,end_time=None): <NEW_LINE> <INDENT> if start_time == None and end_time == None: <NEW_LINE> <INDENT> params = {'granularity':granularity,'count':number_of_candles,'price':'BA'} <NEW_LINE> <DEDENT> elif end_time == None: <NEW_LINE> <INDENT> params = {'granularity':granularity,'count':number_of_candles,'price':'BA','from':start_time} <NEW_LINE> <DEDENT> elif start_time == None: <NEW_LINE> <INDENT> params = {'granularity':granularity,'count':number_of_candles,'price':'BA','to':end_time} <NEW_LINE> <DEDENT> request = instruments.InstrumentsCandles(instrument=instrument,params=params) <NEW_LINE> self.API.request(request) <NEW_LINE> return_dict = {'time':[],'bid_open':[],'bid_high':[],'bid_low':[],'bid_close':[],'ask_open':[],'ask_high':[],'ask_low':[],'ask_close':[],'volume':[]} <NEW_LINE> for candle in request.response['candles']: <NEW_LINE> <INDENT> return_dict['time'].append(candle['time']) <NEW_LINE> return_dict['volume'].append(float(candle['volume'])) <NEW_LINE> return_dict['bid_open'].append(float(candle['bid']['o'])) <NEW_LINE> return_dict['bid_high'].append(float(candle['bid']['h'])) <NEW_LINE> return_dict['bid_close'].append(float(candle['bid']['c'])) <NEW_LINE> return_dict['bid_low'].append(float(candle['bid']['l'])) <NEW_LINE> return_dict['ask_open'].append(float(candle['ask']['o'])) <NEW_LINE> return_dict['ask_high'].append(float(candle['ask']['h'])) <NEW_LINE> return_dict['ask_close'].append(float(candle['ask']['c'])) <NEW_LINE> return_dict['ask_low'].append(float(candle['ask']['l'])) <NEW_LINE> <DEDENT> return return_dict
gets number_of_candles from start_time (if specified) for instrument at granularity returns dictionary of lists dictionary keys are 'time','bid_open','bid_high','bid_low','bid_close','ask_open','ask_high','ask_low','ask_close' volume list for each are of length number of candles, and represent the values for each of the keys, at that time
625941c176e4537e8c3515f9
def add_controller( self, controller_name, controller ): <NEW_LINE> <INDENT> self.controllers[ controller_name ] = controller
Add a controller class to this application. A controller class has methods which handle web requests. To connect a URL to a controller's method use `add_route`.
625941c1bf627c535bc13157
def evaluate_left(self, eval_scope={}): <NEW_LINE> <INDENT> return self.left_size.evaluate(**eval_scope)
Evaluate left side size.
625941c11d351010ab855aa5
def robust_rmtree(path: Union[str, bytes]) -> None: <NEW_LINE> <INDENT> if not isinstance(path, bytes): <NEW_LINE> <INDENT> path = path.encode('utf-8') <NEW_LINE> <DEDENT> if not os.path.exists(path): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not os.path.islink(path) and os.path.isdir(path): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> children = os.listdir(path) <NEW_LINE> <DEDENT> except FileNotFoundError: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for child in children: <NEW_LINE> <INDENT> child_path = os.path.join(path, child) <NEW_LINE> robust_rmtree(child_path) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> shutil.rmtree(path) <NEW_LINE> <DEDENT> except FileNotFoundError: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.unlink(path) <NEW_LINE> <DEDENT> except FileNotFoundError: <NEW_LINE> <INDENT> return
Robustly tries to delete paths. Continues silently if the path to be removed is already gone, or if it goes away while this function is executing. May raise an error if a path changes between file and directory while the function is executing, or if a permission error is encountered.
625941c12eb69b55b151c836
def powerset(iterable): <NEW_LINE> <INDENT> s = list(iterable) <NEW_LINE> return itertools.chain.from_iterable( itertools.combinations(s, r) for r in range(len(s)+1))
powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)
625941c14d74a7450ccd414c
def mk_cgroup_cgcreate(self, pwd=None, cgroup=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> parent_cgroup = self.get_cgroup_name(pwd) <NEW_LINE> if cgroup is None: <NEW_LINE> <INDENT> range = "abcdefghijklmnopqrstuvwxyz0123456789" <NEW_LINE> sub_cgroup = "cgroup-" + "".join(random.sample(range + range.upper(), 6)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sub_cgroup = cgroup <NEW_LINE> <DEDENT> if parent_cgroup is None: <NEW_LINE> <INDENT> cgroup = sub_cgroup <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cgroup = os.path.join(parent_cgroup, sub_cgroup) <NEW_LINE> <DEDENT> if self.__get_cgroup_pwd(cgroup) in self.cgroups: <NEW_LINE> <INDENT> raise exceptions.TestFail("%s exists!" % cgroup) <NEW_LINE> <DEDENT> cgcreate_cmd = "cgcreate -g %s:%s" % (self.module, cgroup) <NEW_LINE> process.run(cgcreate_cmd, ignore_status=False) <NEW_LINE> pwd = self.__get_cgroup_pwd(cgroup) <NEW_LINE> self.cgroups.append(pwd) <NEW_LINE> return len(self.cgroups) - 1 <NEW_LINE> <DEDENT> except process.CmdError: <NEW_LINE> <INDENT> raise exceptions.TestFail("Make cgroup by cgcreate failed!")
Make a cgroup by executing the cgcreate command :params: cgroup: name of the cgroup to be created :return: last cgroup index
625941c1377c676e91272132
def __init__(self, model, memory_size=1024, Batch_size=32, Gamma=0.99, Epsilon=rangefloat(1.0,0.1,1e6), K=1, name='Agent'): <NEW_LINE> <INDENT> self.Memory = PrioritizedReplay(memory_size) <NEW_LINE> self.Batch_size = Batch_size <NEW_LINE> self.Gamma = Gamma <NEW_LINE> if type(Epsilon) is float or type(Epsilon) is int: <NEW_LINE> <INDENT> self.Epsilon = Epsilon <NEW_LINE> self.Epsilon_gen = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.Epsilon_gen = Epsilon <NEW_LINE> self.Epsilon = next(self.Epsilon_gen) <NEW_LINE> <DEDENT> self.K = K <NEW_LINE> self.current_state = None <NEW_LINE> self.current_action = None <NEW_LINE> self.model = FFNetAsync(model) <NEW_LINE> self.target_model = FFNetAsync(model) <NEW_LINE> self.terminal = False
Create Agent from model description file.
625941c116aa5153ce362401
def verifyPreorder(self, preorder): <NEW_LINE> <INDENT> lower = -sys.maxint <NEW_LINE> i = 0 <NEW_LINE> for e in preorder: <NEW_LINE> <INDENT> if e < lower: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> while i > 0 and e > preorder[i-1]: <NEW_LINE> <INDENT> lower = preorder[i-1] <NEW_LINE> i -= 1 <NEW_LINE> <DEDENT> preorder[i] = e <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> return True
:type preorder: List[int] :rtype: bool
625941c1507cdc57c6306c5f
def format(self): <NEW_LINE> <INDENT> return Table([[v] for v in self._values]).format(alignment="r")
Format the vector for human consumption
625941c1fb3f5b602dac361a
@nox.session(python=False) <NEW_LINE> def sign(session): <NEW_LINE> <INDENT> def sign_darwin(cert_name): <NEW_LINE> <INDENT> session.run('security', 'find-identity', external=True) <NEW_LINE> session.run( 'codesign', '--deep', '--force', '--verbose', '--timestamp', '--identifier', OSX_BUNDLE_IDENTIFIER, '--entitlements', OSX_BUNDLE_ENTITLEMENTS, '--options', 'runtime', '--sign', cert_name, 'dist/b2', external=True ) <NEW_LINE> session.run('codesign', '--verify', '--verbose', 'dist/b2', external=True) <NEW_LINE> <DEDENT> def sign_windows(cert_file, cert_password): <NEW_LINE> <INDENT> session.run('certutil', '-f', '-p', cert_password, '-importpfx', cert_file) <NEW_LINE> session.run( WINDOWS_SIGNTOOL_PATH, 'sign', '/f', cert_file, '/p', cert_password, '/tr', WINDOWS_TIMESTAMP_SERVER, '/td', 'sha256', '/fd', 'sha256', 'dist/b2.exe', external=True ) <NEW_LINE> session.run(WINDOWS_SIGNTOOL_PATH, 'verify', '/pa', '/all', 'dist/b2.exe', external=True) <NEW_LINE> <DEDENT> if SYSTEM == 'darwin': <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> certificate_name, = session.posargs <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> session.error('pass the certificate name as a positional argument') <NEW_LINE> return <NEW_LINE> <DEDENT> sign_darwin(certificate_name) <NEW_LINE> <DEDENT> elif SYSTEM == 'windows': <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> certificate_file, certificate_password = session.posargs <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> session.error('pass the certificate file and the password as positional arguments') <NEW_LINE> return <NEW_LINE> <DEDENT> sign_windows(certificate_file, certificate_password) <NEW_LINE> <DEDENT> elif SYSTEM == 'linux': <NEW_LINE> <INDENT> session.log('signing is not supported for Linux') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> session.error('unrecognized platform: {}'.format(SYSTEM)) <NEW_LINE> <DEDENT> asset_old_path = glob('dist/*')[0] <NEW_LINE> name, ext = os.path.splitext(os.path.basename(asset_old_path)) <NEW_LINE> asset_path = 'dist/{}-{}{}'.format(name, SYSTEM, ext) <NEW_LINE> session.run('mv', '-f', asset_old_path, asset_path, external=True) <NEW_LINE> if CI: <NEW_LINE> <INDENT> asset_path = glob('dist/*')[0] <NEW_LINE> print('::set-output name=asset_path::', asset_path, sep='')
Sign the bundled distribution (macOS and Windows only).
625941c199cbb53fe6792b70
def dispose(self, v): <NEW_LINE> <INDENT> key = self._value_to_key.pop(v) <NEW_LINE> pool = self._pools[key] <NEW_LINE> return pool.dispose(v)
Dispose a previously acquired value.
625941c145492302aab5e24a
def render_simple_tray_divider(self, width, height, move): <NEW_LINE> <INDENT> if self.move(height, width, move, True): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> t = self.thickness <NEW_LINE> self.polyline( height - t, 90, t, -90, t, 90, width - 2 * t, 90, t, -90, t, 90, height - t, 90, width, 90, ) <NEW_LINE> self.move(height, width, move) <NEW_LINE> self.render_simple_tray_divider_feet(width, height, move)
Simple movable divider. A wall with small feet for a little more stability.
625941c1711fe17d825422f9
def _set_capacities_proportionally(topology, capacities, metric, capacity_unit='Mbps'): <NEW_LINE> <INDENT> if not capacity_unit in capacity_units: <NEW_LINE> <INDENT> raise ValueError("The capacity_unit argument is not valid") <NEW_LINE> <DEDENT> if any((capacity < 0 for capacity in capacities)): <NEW_LINE> <INDENT> raise ValueError('All capacities must be positive') <NEW_LINE> <DEDENT> topology.graph['capacity_unit'] = capacity_unit <NEW_LINE> min_metric = min(metric.values()) <NEW_LINE> max_metric = max(metric.values()) <NEW_LINE> capacities = sorted(capacities) <NEW_LINE> min_capacity = capacities[0] - 0.5 * (capacities[1] - capacities[0]) <NEW_LINE> max_capacity = capacities[-1] + 0.5 * (capacities[-1] - capacities[-2]) <NEW_LINE> capacity_boundaries = [0.5*(capacities[i] + capacities[i + 1]) for i in range(len(capacities) - 1)] <NEW_LINE> capacity_boundaries.append(max_capacity) <NEW_LINE> metric_boundaries = [(capacity_boundary - min_capacity) * ((max_metric - min_metric)/ (max_capacity - min_capacity)) + min_metric for capacity_boundary in capacity_boundaries] <NEW_LINE> metric_boundaries[-1] = max_metric + 0.1 <NEW_LINE> for (u, v), metric_value in metric.items(): <NEW_LINE> <INDENT> for i in range(len(metric_boundaries)): <NEW_LINE> <INDENT> if metric_value <= metric_boundaries[i]: <NEW_LINE> <INDENT> capacity = capacities[i] <NEW_LINE> topology.edge[u][v]['capacity'] = capacity <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> else: topology.edge[u][v]['capacity'] = capacities[-1]
Set link capacities proportionally to the value of a given edge metric. Parameters ---------- topology : Topology The topology to which link capacities will be set capacities : list A list of all possible capacity values metric : dict A dictionary with all values of the given edge metric, keyed by edge name capacity_unit : str, optional The unit in which capacity value is expressed (e.g. Mbps, Gbps etc..)
625941c1fff4ab517eb2f3c4
def serialize_numpy(self, buff, numpy): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> buff.write(self.angles.tostring()) <NEW_LINE> <DEDENT> except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self))))) <NEW_LINE> except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
serialize message with numpy array types into buffer :param buff: buffer, ``StringIO`` :param numpy: numpy python module
625941c116aa5153ce362402
def determine_db_dir(): <NEW_LINE> <INDENT> if platform.system() == "Darwin": <NEW_LINE> <INDENT> return os.path.expanduser("~/Library/Application Support/PeepCoin/") <NEW_LINE> <DEDENT> elif platform.system() == "Windows": <NEW_LINE> <INDENT> return os.path.join(os.environ['APPDATA'], "PeepCoin") <NEW_LINE> <DEDENT> return os.path.expanduser("~/.peepcoin")
Return the default location of the peepcoin data directory
625941c1460517430c394113
def peekFirst(self): <NEW_LINE> <INDENT> if self.isEmpty(): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.deque[len(self.deque) -1]
Returns but does not remove the first item of the deque.
625941c115fb5d323cde0a96
def get_parameters(self): <NEW_LINE> <INDENT> strategy_parameters = {} <NEW_LINE> for name in self.parameters: <NEW_LINE> <INDENT> strategy_parameters[name] = getattr(self, name) <NEW_LINE> <DEDENT> return strategy_parameters
Get strategy parameters dict.
625941c15166f23b2e1a50e2
def getProject(self, pid): <NEW_LINE> <INDENT> return self.request(Endpoints.PROJECTS + '/{0}'.format(pid))
return all projects that are visable to a user
625941c1b5575c28eb68df88
def __init__(self,n_input,n_hidden,transfer_function = tf.nn.softplus,optimizer = tf.train.AdamOptimizer(),scale = 0.1): <NEW_LINE> <INDENT> self.n_input = n_input <NEW_LINE> self.n_hidden = n_hidden <NEW_LINE> self.transfer = transfer_function <NEW_LINE> self.scale = tf.placeholder(tf.float32) <NEW_LINE> self.training_scale = scale <NEW_LINE> network_weights = self._initialize_weights() <NEW_LINE> self.weights = network_weights <NEW_LINE> self.x = tf.placeholder(tf.float32, [None,self.n_input]) <NEW_LINE> self.hidden = self.transfer(tf.add(tf.matmul(self.x + scale * tf.random_normal((n_input,)),self.weights['w1']),self.weights['b1'])) <NEW_LINE> self.reconstruction = tf.add(tf.matmul(self.hidden,self.weights['w2']),self.weights['b2']) <NEW_LINE> self.cost = 0.5 * tf.reduce_sum(tf.pow(tf.subtract(self.reconstruction, self.x),2.0)) <NEW_LINE> self.optimizer = optimizer.minimize(self.cost) <NEW_LINE> init = tf.global_variables_initializer(); <NEW_LINE> self.sess = tf.Session() <NEW_LINE> self.sess.run(init)
构造器 Args: n_input:输入变量数 n_hidden:隐含层节点数量 transfer_function:隐含层激活函数 optimizer:优化器 scale:高斯噪声系数
625941c160cbc95b062c64cc
def candidates(word, WORDS): <NEW_LINE> <INDENT> return (known([word], WORDS) or known(edits1(word), WORDS) or known(edits2(word), WORDS) or [word])
Generate possible spelling corrections for word.
625941c1cc40096d615958da
@pytest.mark.xfail <NEW_LINE> def test_convert_scalar(): <NEW_LINE> <INDENT> foo = Value(scalars=1.2) <NEW_LINE> assert foo.scalars[0].value == 1.2
Test that scalars are made rigid
625941c17d847024c06be243
def refresh(self): <NEW_LINE> <INDENT> self.__plugins = {} <NEW_LINE> return self
Clean-up plugin cache This will force to reinitialize each plugin when asked
625941c19f2886367277a818
def __init__(self): <NEW_LINE> <INDENT> self.OrderId = None <NEW_LINE> self.PkgId = None <NEW_LINE> self.Status = None <NEW_LINE> self.StartTime = None <NEW_LINE> self.EndTime = None
:param OrderId: 定单唯一性ID :type OrderId: str :param PkgId: 云存套餐ID :type PkgId: str :param Status: 定单服务状态 :type Status: int :param StartTime: 定单服务生效时间 :type StartTime: int :param EndTime: 定单服务失效时间 :type EndTime: int
625941c163f4b57ef00010a8
def reset( self, resource_group_name, workflow_name, trigger_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 = "2019-05-01" <NEW_LINE> accept = "application/json" <NEW_LINE> url = self.reset.metadata['url'] <NEW_LINE> path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'workflowName': self._serialize.url("workflow_name", workflow_name, 'str'), 'triggerName': self._serialize.url("trigger_name", trigger_name, 'str'), } <NEW_LINE> url = self._client.format_url(url, **path_format_arguments) <NEW_LINE> query_parameters = {} <NEW_LINE> query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') <NEW_LINE> header_parameters = {} <NEW_LINE> header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') <NEW_LINE> request = self._client.post(url, query_parameters, header_parameters) <NEW_LINE> pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) <NEW_LINE> response = pipeline_response.http_response <NEW_LINE> if response.status_code not in [200]: <NEW_LINE> <INDENT> map_error(status_code=response.status_code, response=response, error_map=error_map) <NEW_LINE> error = self._deserialize(_models.ErrorResponse, response) <NEW_LINE> raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) <NEW_LINE> <DEDENT> if cls: <NEW_LINE> <INDENT> return cls(pipeline_response, None, {})
Resets a workflow trigger. :param resource_group_name: The resource group name. :type resource_group_name: str :param workflow_name: The workflow name. :type workflow_name: str :param trigger_name: The workflow trigger name. :type trigger_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: None, or the result of cls(response) :rtype: None :raises: ~azure.core.exceptions.HttpResponseError
625941c16fece00bbac2d6c6
def add_package_menu_items(self, pkg_id, pkg_name, items): <NEW_LINE> <INDENT> if len(self._package_menu_items) == 0: <NEW_LINE> <INDENT> self.packagesMenu.menuAction().setEnabled(True) <NEW_LINE> <DEDENT> if not self._package_menu_items.has_key(pkg_id): <NEW_LINE> <INDENT> pkg_menu = self.packagesMenu.addMenu(str(pkg_name)) <NEW_LINE> self._package_menu_items[pkg_id] = pkg_menu <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pkg_menu = self._package_menu_items[pkg_id] <NEW_LINE> pkg_menu.clear() <NEW_LINE> <DEDENT> for item in items: <NEW_LINE> <INDENT> (name, callback) = item <NEW_LINE> action = QtGui.QAction(name,self) <NEW_LINE> self.connect(action, QtCore.SIGNAL('triggered()'), callback) <NEW_LINE> pkg_menu.addAction(action)
add_package_menu_items(pkg_id: str,pkg_name: str,items: list)->None Add a pacckage menu entry with submenus defined by 'items' to Packages menu.
625941c130bbd722463cbd4d
def maxTurbulenceSize(self, A): <NEW_LINE> <INDENT> pass
:type A: List[int] :rtype: int
625941c18e05c05ec3eea2fc
@app.route('/shutdown') <NEW_LINE> def shutdown(): <NEW_LINE> <INDENT> func = request.environ.get('werkzeug.server.shutdown') <NEW_LINE> if func is None: <NEW_LINE> <INDENT> return jsonify({'status': 'error - Not running with the Werkzeug Server'}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> func() <NEW_LINE> return jsonify({'status': 'shutting down'})
Shutdown server
625941c14f88993c3716bff2
def glInitPlatformX11KHR(): <NEW_LINE> <INDENT> from OpenGL import extensions <NEW_LINE> return extensions.hasGLExtension( _EXTENSION_NAME )
Return boolean indicating whether this extension is available
625941c1a17c0f6771cbdfdc
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> if issubclass(ManualHealthCheck, dict): <NEW_LINE> <INDENT> for key, value in self.items(): <NEW_LINE> <INDENT> result[key] = value <NEW_LINE> <DEDENT> <DEDENT> return result
Returns the model properties as a dict
625941c11f037a2d8b946188
def __getitem__(self, item): <NEW_LINE> <INDENT> return self._expense[item]
returns payment with index of item :param item: payment index :return: payment
625941c199fddb7c1c9de31b
def test_nrows_ncols_ndepths_sum(self): <NEW_LINE> <INDENT> self.assertModule('r3.mapcalc', expression='nrows_ncols_ndepths_sum = nrows() + ncols() + ndepths()') <NEW_LINE> self.to_remove.append('nrows_ncols_ndepths_sum') <NEW_LINE> self.assertRaster3dMinMax('nrows_ncols_ndepths_sum', refmin=2160, refmax=2160)
Test if sum of nrows, ncols and ndepths matches one expected from current region settigs
625941c1bde94217f3682d7c
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'markethink.settings') <NEW_LINE> try: <NEW_LINE> <INDENT> from django.core.management import execute_from_command_line <NEW_LINE> <DEDENT> except ImportError as exc: <NEW_LINE> <INDENT> raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc <NEW_LINE> <DEDENT> execute_from_command_line(sys.argv)
Run administrative tasks.
625941c123e79379d52ee4ef
def remove(self, widget): <NEW_LINE> <INDENT> path = self.removable_list[self.remove_item[0]][self.remove_item[1]] <NEW_LINE> self.current_collection.remove(path) <NEW_LINE> self.removable_list[self.remove_item[0]].pop(self.remove_item[1]) <NEW_LINE> self.show_update() <NEW_LINE> self.show_remove_button(False)
remove an extension
625941c15fcc89381b1e1646
def _data_dialog(self): <NEW_LINE> <INDENT> self.progress_processing.setHidden(True) <NEW_LINE> self.progress_processing.setMinimum(0) <NEW_LINE> self.progress_processing.setValue(0) <NEW_LINE> self.tasks = transport.get_result_files(self.work_dir, self.substances) <NEW_LINE> n_tas = len(self.tasks) <NEW_LINE> self.solutions = transport.parse_task_dirs(self.work_dir, FNAME_ELEMS) <NEW_LINE> n_sols = len(self.solutions) <NEW_LINE> if n_tas - n_sols == 0: <NEW_LINE> <INDENT> self.button_process_newonly.setHidden(True) <NEW_LINE> self.button_process_all.setText('Start') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.button_process_newonly.setVisible(True) <NEW_LINE> self.button_process_all.setText('All') <NEW_LINE> <DEDENT> msg = "Found {} tasks to analyze. It may take a while\n".format(n_tas) <NEW_LINE> msg += "{} tasks was already processed (compressed file found), {} still need processing\n".format( n_sols, n_tas - n_sols) <NEW_LINE> if self.substances and n_sols > 0: <NEW_LINE> <INDENT> msg += "\n\nYour task works with multiple substances. Now you close this primary task and open result for single substance in subfolder." <NEW_LINE> <DEDENT> self.label_processing_text.setText(msg) <NEW_LINE> self.progress_processing.setMaximum(n_tas * 4)
a dialog for data processing
625941c1ad47b63b2c509f09
def check_job_successful(job): <NEW_LINE> <INDENT> job_dir = job_file(job.uuid) <NEW_LINE> html = job_file(job.uuid, 'STEME.html') <NEW_LINE> meme = job_file(job.uuid, 'meme.txt') <NEW_LINE> successful = ( os.path.exists(job_dir) and os.path.exists(html) and os.stat(html).st_size and os.path.exists(meme) ) <NEW_LINE> return successful
Check that the job finished successfully.
625941c1cc0a2c11143dce19
def stop(self) -> None: <NEW_LINE> <INDENT> for upload in self.active_uploads.values(): <NEW_LINE> <INDENT> upload[1].cancel() <NEW_LINE> <DEDENT> if self.observer: <NEW_LINE> <INDENT> self.observer.stop() <NEW_LINE> <DEDENT> self.loop.stop()
Stop the client.
625941c15fdd1c0f98dc01bc
def where_parse(where_l): <NEW_LINE> <INDENT> res=[] <NEW_LINE> key=['and','or','not'] <NEW_LINE> char='' <NEW_LINE> for i in where_l: <NEW_LINE> <INDENT> if i in key: <NEW_LINE> <INDENT> if len(char) != 0: <NEW_LINE> <INDENT> char=three_parse(char) <NEW_LINE> res.append(char) <NEW_LINE> <DEDENT> res.append(i) <NEW_LINE> char='' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> char+=i <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> char=three_parse(char) <NEW_LINE> res.append(char) <NEW_LINE> <DEDENT> return res
对用户输入的where子句后的条件格式化,每个子条件都改成列表形式 where_l: ['id>', '4', 'and', 'id<', '10'] ---> ['id', >', '4', 'and', 'id', '<', '10'] :param where_l: 用户输入where后对应的过滤条件列表 :return:
625941c1ff9c53063f47c17e
def add_application_vertices(self, application_graph): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> import sqlite3 as sqlite <NEW_LINE> connection = sqlite.connect(self._database_path) <NEW_LINE> cur = connection.cursor() <NEW_LINE> cur.execute( "CREATE TABLE Application_vertices(" "vertex_id INTEGER PRIMARY KEY AUTOINCREMENT, " "vertex_label TEXT, no_atoms INT, max_atom_constrant INT," "recorded INT)") <NEW_LINE> cur.execute( "CREATE TABLE Application_edges(" "edge_id INTEGER PRIMARY KEY AUTOINCREMENT, " "pre_vertex INTEGER, post_vertex INTEGER, edge_label TEXT, " "FOREIGN KEY (pre_vertex)" " REFERENCES Application_vertices(vertex_id), " "FOREIGN KEY (post_vertex)" " REFERENCES Application_vertices(vertex_id))") <NEW_LINE> cur.execute( "CREATE TABLE Application_graph(" "vertex_id INTEGER, edge_id INTEGER, " "FOREIGN KEY (vertex_id) " "REFERENCES Application_vertices(vertex_id), " "FOREIGN KEY (edge_id) " "REFERENCES Application_edges(edge_id), " "PRIMARY KEY (vertex_id, edge_id))") <NEW_LINE> for vertex in application_graph.vertices: <NEW_LINE> <INDENT> if isinstance(vertex, AbstractRecordable): <NEW_LINE> <INDENT> cur.execute( "INSERT INTO Application_vertices(" "vertex_label, no_atoms, max_atom_constrant, recorded)" " VALUES('{}', {}, {}, {});" .format(vertex.label, vertex.n_atoms, vertex.get_max_atoms_per_core(), int(vertex.is_recording_spikes()))) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if isinstance(vertex, AbstractHasGlobalMaxAtoms): <NEW_LINE> <INDENT> cur.execute( "INSERT INTO Application_vertices(" "vertex_label, no_atoms, max_atom_constrant, " "recorded) VALUES('{}', {}, {}, 0);" .format(vertex.label, vertex.n_atoms, vertex.get_max_atoms_per_core())) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cur.execute( "INSERT INTO Application_vertices(" "vertex_label, no_atoms, max_atom_constrant, " "recorded) VALUES('{}', {}, {}, 0);" .format(vertex.label, vertex.n_atoms, sys.maxint)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> vertices = application_graph.vertices <NEW_LINE> for vertex in application_graph.vertices: <NEW_LINE> <INDENT> for edge in application_graph. get_edges_starting_at_vertex(vertex): <NEW_LINE> <INDENT> cur.execute( "INSERT INTO Application_edges (" "pre_vertex, post_vertex, edge_label) " "VALUES({}, {}, '{}');" .format(vertices.index(edge.pre_vertex) + 1, vertices.index(edge.post_vertex) + 1, edge.label)) <NEW_LINE> <DEDENT> <DEDENT> edge_id_offset = 0 <NEW_LINE> for vertex in application_graph.vertices: <NEW_LINE> <INDENT> edges = application_graph.get_edges_starting_at_vertex( vertex) <NEW_LINE> for edge in application_graph. get_edges_starting_at_vertex(vertex): <NEW_LINE> <INDENT> cur.execute( "INSERT INTO Application_graph (" "vertex_id, edge_id)" " VALUES({}, {})" .format(vertices.index(vertex) + 1, edges.index(edge) + edge_id_offset)) <NEW_LINE> <DEDENT> edge_id_offset += len(edges) <NEW_LINE> <DEDENT> connection.commit() <NEW_LINE> connection.close() <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> traceback.print_exc()
:param application_graph: :return:
625941c1167d2b6e31218b1f
def __init__(self, data): <NEW_LINE> <INDENT> self._data = pickle.load(data) <NEW_LINE> self._v_label = _('Time') <NEW_LINE> self._h_label = ''
Import chart data from file.
625941c13617ad0b5ed67e82
def _cleanup_remote_target( self, array, volume, remote_array, device_id, target_device, rdf_group, volume_name, rep_extra_specs): <NEW_LINE> <INDENT> self.masking.remove_and_reset_members( remote_array, volume, target_device, volume_name, rep_extra_specs, False) <NEW_LINE> are_vols_paired, local_vol_state, pair_state = ( self.rest.are_vols_rdf_paired( array, remote_array, device_id, target_device)) <NEW_LINE> if are_vols_paired: <NEW_LINE> <INDENT> is_metro = self.utils.is_metro_device( self.rep_config, rep_extra_specs) <NEW_LINE> if is_metro: <NEW_LINE> <INDENT> rep_extra_specs['allow_del_metro'] = self.allow_delete_metro <NEW_LINE> self._cleanup_metro_target( array, device_id, target_device, rdf_group, rep_extra_specs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.provision.break_rdf_relationship( array, device_id, target_device, rdf_group, rep_extra_specs, pair_state) <NEW_LINE> <DEDENT> <DEDENT> self._delete_from_srp( remote_array, target_device, volume_name, rep_extra_specs)
Clean-up remote replication target after exception or on deletion. :param array: the array serial number :param volume: the volume object :param remote_array: the remote array serial number :param device_id: the source device id :param target_device: the target device id :param rdf_group: the RDF group :param volume_name: the volume name :param rep_extra_specs: replication extra specifications
625941c1b7558d58953c4ea2
@login_required <NEW_LINE> def project_gene_list_settings(request, project_id): <NEW_LINE> <INDENT> project = get_object_or_404(Project, project_id=project_id) <NEW_LINE> if not project.can_view(request.user): <NEW_LINE> <INDENT> raise PermissionDenied <NEW_LINE> <DEDENT> return render(request, 'project/project_gene_list_settings.html', { 'project': project, 'is_manager': project.can_admin(request.user), })
Manager can edit project settings
625941c157b8e32f52483423
def get_submission_count(self, obj): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return obj.submission_count <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return obj.submissions
Add a custom method to get submission count
625941c1460517430c394114
def authenticate(self, name, password=None, source=None, mechanism='MONGODB-CR'): <NEW_LINE> <INDENT> if not isinstance(name, str): <NEW_LINE> <INDENT> raise TypeError("name must be an instance " "of %s" % (str.__name__,)) <NEW_LINE> <DEDENT> if password is not None and not isinstance(password, str): <NEW_LINE> <INDENT> raise TypeError("password must be an instance " "of %s" % (str.__name__,)) <NEW_LINE> <DEDENT> if source is not None and not isinstance(source, str): <NEW_LINE> <INDENT> raise TypeError("source must be an instance " "of %s" % (str.__name__,)) <NEW_LINE> <DEDENT> common.validate_auth_mechanism('mechanism', mechanism) <NEW_LINE> credentials = (source or self.name, str(name), password and str(password) or None, mechanism) <NEW_LINE> self.connection._cache_credentials(self.name, credentials) <NEW_LINE> return True
Authenticate to use this database. Raises :class:`TypeError` if either `name` or `password` is not an instance of :class:`basestring` (:class:`str` in python 3). Authentication lasts for the life of the underlying client instance, or until :meth:`logout` is called. The "admin" database is special. Authenticating on "admin" gives access to *all* databases. Effectively, "admin" access means root access to the database. .. note:: This method authenticates the current connection, and will also cause all new :class:`~socket.socket` connections in the underlying client instance to be authenticated automatically. - Authenticating more than once on the same database with different credentials is not supported. You must call :meth:`logout` before authenticating with new credentials. - When sharing a client instance between multiple threads, all threads will share the authentication. If you need different authentication profiles for different purposes you must use distinct client instances. - To get authentication to apply immediately to all existing sockets you may need to reset this client instance's sockets using :meth:`~pymongo.mongo_client.MongoClient.disconnect`. :Parameters: - `name`: the name of the user to authenticate. - `password` (optional): the password of the user to authenticate. Not used with GSSAPI authentication. - `source` (optional): the database to authenticate on. If not specified the current database is used. - `mechanism` (optional): See :data:`~pymongo.auth.MECHANISMS` for options. Defaults to MONGODB-CR (MongoDB Challenge Response protocol) .. versionchanged:: 2.5 Added the `source` and `mechanism` parameters. :meth:`authenticate` now raises a subclass of :class:`~pymongo.errors.PyMongoError` if authentication fails due to invalid credentials or configuration issues. .. mongodoc:: authenticate
625941c194891a1f4081ba32
def test_api_root_endpoint(app): <NEW_LINE> <INDENT> assert 'application/json' == app.get('/api/').content_type
Make sure the api root (/api/) works
625941c16fece00bbac2d6c7
def isPalindrome(self, s): <NEW_LINE> <INDENT> if len(s) == 0: return True <NEW_LINE> result = re.subn('[^0-9A-Za-z]', '', s)[0].lower() <NEW_LINE> reverse = result[-1:-len(result) - 1:-1] <NEW_LINE> return result == reverse
:type s: str :rtype: bool
625941c1167d2b6e31218b20
@app.route("/apperror") <NEW_LINE> def appError(): <NEW_LINE> <INDENT> flash('Something happened in the system !!! ','error') <NEW_LINE> return render_template('general_error.html'), 404
In order to manage the unexpected error
625941c17c178a314d6ef3e5
def HermeticZipInfo(*args, **kwargs): <NEW_LINE> <INDENT> date_time = None <NEW_LINE> if len(args) >= 2: <NEW_LINE> <INDENT> date_time = args[1] <NEW_LINE> <DEDENT> elif 'date_time' in kwargs: <NEW_LINE> <INDENT> date_time = kwargs['date_time'] <NEW_LINE> <DEDENT> if not date_time: <NEW_LINE> <INDENT> kwargs['date_time'] = HermeticDateTime() <NEW_LINE> <DEDENT> ret = zipfile.ZipInfo(*args, **kwargs) <NEW_LINE> ret.external_attr = (0o644 << 16) <NEW_LINE> return ret
Creates a zipfile.ZipInfo with a constant timestamp and external_attr. If a date_time value is not provided in the positional or keyword arguments, the default value from HermeticDateTime is used. Args: See zipfile.ZipInfo. Returns: A zipfile.ZipInfo.
625941c10a50d4780f666e1a
def toggle_anim(self, toggling): <NEW_LINE> <INDENT> if toggling: <NEW_LINE> <INDENT> self.anim.setDirection(QAbstractAnimation.Forward) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.anim.setDirection(QAbstractAnimation.Backward) <NEW_LINE> <DEDENT> self.anim.start()
Toggle the animation to be play forward or backward Parameters ---------- toggling: bool True for forward, False for backward
625941c16aa9bd52df036d2c